branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<file_sep>import os
import random
import numpy as np
import tensorflow as tf
def load_alphabet():
alpha_file = open('alphabet.txt', 'r')
symbols = alpha_file.read()
alpha_file.close()
return symbols
alphabet = load_alphabet()
card_files = []
for dir_name, _, files in os.walk('cards'):
for f in files:
card_files.append(os.path.join(dir_name, f))
def random_card():
f = open(random.choice(card_files), 'r')
text = f.read()
f.close()
return text
def encode(symbol):
return [1 if x == symbol else 0 for x in alphabet]
def encode_card(card):
return np.array([encode(symbol) for symbol in card], dtype=np.float32)
def encode_input(card):
encoded = encode_card(card)
return np.insert(encoded, 0, np.zeros(len(alphabet)), axis=0)
def encode_output(card):
encoded = encode_card(card)
return np.append(encoded, [np.zeros(len(alphabet))], axis=0)
class Config:
batch_size = 1
num_steps = 1
class Model:
def __init__(self, is_training, config):
self.batch_size = batch_size = config.batch_size
self.num_steps = num_steps = config.num_steps
self._input_data = tf.placeholder(tf.float32, [batch_size, num_steps])
self._targets = tf.placeholder(tf.float32, [batch_size, num_steps])
<file_sep>npm install unidecode mkdirp lodash
curl -O https://mtgjson.com/json/AllSets-x.json
node gen-card-files.js
cat cards/*/* | fold -w1 | sort -u | tr -d '\r\n' >alphabet.txt
echo >>alphabet.txt
<file_sep>const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const unidecode = require('unidecode');
const _ = require('lodash');
const sets = require('./AllSets-x.json');
class FileWriter {
constructor() {
this.isWriting = false;
this.queue = [];
this.all = fs.openSync(path.join('cards', 'all.txt'), 'w');
}
add(name, text) {
this.queue.push({ name, text });
if (!this.isWriting) {
this.isWriting = true;
this.writeNext();
}
}
writeNext() {
const next = this.queue.shift();
const name = toAscii(next.name.replace(/:|"| /g, '_'));
const fd = fs.openSync(name, 'w');
fs.write(fd, next.text, err => {
if (err) {
console.log(err);
} else {
fs.closeSync(fd);
if (this.queue.length > 0) {
this.writeNext();
} else {
this.isWriting = false;
}
}
});
fs.write(this.all, next.text, err => {
if (err) {
console.log(err);
}
});
}
closeAll() {
let iid = setInterval(() => {
if (!this.isWriting) {
fs.closeSync(this.all);
clearTimeout(iid);
}
}, 500);
}
}
const writer = new FileWriter();
processSets();
function processSets() {
const setNames = _.shuffle(Object.keys(sets));
for (let setName of setNames) {
const set = sets[setName];
mkdirp(path.join('cards', set.code), err => {
if (err) {
console.log(err);
} else {
processSet(set);
}
});
}
}
function processSet(set) {
const cardIndexes = _.shuffle(_.range(set.cards.length));
for (let i of cardIndexes) {
const card = set.cards[i];
if (!shouldProcess(card)) continue;
const fullText = genFullText(card);
const fileName = path.join('cards', set.code, card.name + '.txt');
writer.add(fileName, fullText);
}
}
function toAscii(s) {
const CAPITAL_AE = new RegExp('\u00c6', 'g');
return unidecode(s.replace(CAPITAL_AE, 'Ae'));
}
function shouldProcess(card) {
if (card.legalities &&
card.legalities.some(l => l.format === 'Un-Sets')) {
return false;
}
if (/Basic|Conspiracy|Vanguard|Plane(?!swalker)|Scheme|Phenomenon/.test(card.type)) {
return false;
}
return true;
}
function genFullText(card) {
card.fullText = toAscii(card.name);
if (card.manaCost) {
card.fullText += ' ' + card.manaCost;
}
card.fullText += '\n';
// type line
if (!card.manaCost && card.colors) {
card.fullText += '(' + card.colors.join('/') + ') ';
}
card.fullText += toAscii(card.type) + '\n';
// text body
if (card.text) {
card.fullText += toAscii(card.text) + '\n';
}
if (card.flavor) {
const flavorLines = toAscii(card.flavor).split('\n');
card.fullText += flavorLines.map(l => '>' + l).join('\n') + '\n';
}
// power/toughness or loyalty
if (card.types.indexOf('Creature') >= 0) {
card.fullText += card.power + '/' + card.toughness + '\n';
} else if (card.types.indexOf('Planeswalker') >= 0) {
card.fullText += 'Loyalty: ' + card.loyalty + '\n';
}
card.fullText += '\n';
return card.fullText;
}
|
cda9d4c5236ed0d8eaa54de062a445f1405306ad
|
[
"JavaScript",
"Python",
"Shell"
] | 3
|
Python
|
msmorgan/magic-gen
|
3a0918fbfd5cb77b7f9c5db1fde7275d2be969bb
|
3151aca2d1d4b63eeebf03d7eb3d43d285b6defa
|
refs/heads/master
|
<file_sep>export type NucleoObjectType = {
name: string,
fields: any
};
<file_sep>import lawyer from './lawyer';
interface saveInterface {
contracts: any;
store: any;
listeners: Array<Function>;
saveMethod: 'update'|'dispatch'
}
export default function save({
contracts,
store,
listeners,
saveMethod
}:saveInterface) {
return (contractName: string) => {
if (!contracts[contractName]) {
throw Error(
`Fatal error: The provided contract named as "${contractName}" could not be found in store contracts`
);
}
if (saveMethod === 'update' && !store[contractName]) {
throw Error(
`Fatal error: you can not update an item in store if it is not created yet.
First use dispatch to save it and then you can perform updates at ${contractName} contract.`
);
}
return (data: any) => {
return lawyer({
contract: { name: contractName, fields: contracts[contractName]},
data,
saveMethod,
__errors__: []
})(store, listeners);
};
}
};
<file_sep>import { createStore } from './store';
import {
NucleoString,
NucleoNumber,
NucleoBoolean
} from './nucleoTypes/primitive'
import NucleoObject from './nucleoTypes/NucleoObject';
import NucleoList from './nucleoTypes/NucleoList';
import { expect } from 'chai';
import 'mocha';
describe('Update forbidden attempts', () => {
const completeNameType = new NucleoObject({
name: 'completeName',
fields: {
firstName: NucleoString,
lastName: NucleoString
}
});
const userType = new NucleoObject({
name: 'user',
fields: {
name: completeNameType,
age: NucleoNumber
}
});
const contracts = { user: userType };
const store = createStore(contracts);
const { dispatch, update, getStore } = store;
it('should use update method and throw for this item in store be empty', () => {
const d = () => update('user')({ name: { firstName: 'John' }});
expect(d).to.throw();
});
it('should dispatch values and then return error tring to update fields violating the contract', () => {
const d = dispatch('user')({
name: { firstName: 'John', lastName: 'Doe' },
age: 27
});
const { errors, data } = update('user')({ name: { name: 'matheus' } });
expect(errors.length).to.equal(1);
expect(getStore().user.name.firstName).to.equal('John');
expect(getStore().user.name.lastName).to.equal('Doe');
expect(getStore().user.age).to.equal(27);
});
});
describe('Update method', () => {
const completeNameType = new NucleoObject({
name: 'completeName',
fields: {
firstName: NucleoString,
lastName: NucleoString
}
});
const userType = new NucleoObject({
name: 'user',
fields: {
name: completeNameType,
age: NucleoNumber
}
});
const contracts = { user: userType };
const store = createStore(contracts);
const { dispatch, update, getStore } = store;
it('should dispatch only one property in deeper levels and just this property should be updated in store', () => {
const d = dispatch('user')({
name: { firstName: 'John', lastName: 'Doe' },
age: 27
});
const { errors, data } = update('user')({ name: { firstName: 'matheus' } });
expect(getStore().user.name.firstName).to.equal('matheus');
expect(getStore().user.name.lastName).to.equal('Doe');
expect(getStore().user.age).to.equal(27);
});
it('should dispatch only one property in first level and just this property should be updated in store', () => {
const { errors, data } = update('user')({ age: 18 });
expect(getStore().user.name.firstName).to.equal('matheus');
expect(getStore().user.name.lastName).to.equal('Doe');
expect(getStore().user.age).to.equal(18);
});
});
<file_sep>interface SerializeFunction {
(value: string|boolean|number): boolean
}
export type NucleoPrimitiveType = {
Type: string,
serialize: SerializeFunction
}
<file_sep>import { NucleoObjectType } from './../_types/NucleoObjectType';
import { NucleoListType } from './../_types/NucleoListType';
import { NucleoPrimitiveType } from './../_types/NucleoPrimitiveType';
import NucleoObject from './../nucleoTypes/NucleoObject';
interface N {
name?:string;
fields?:any;
Type?:string;
serialize?:Function;
};
export default class NucleoList {
NucleoObject: NucleoObjectType;
NucleoPrimitive: N;
constructor(config: N) {
if (config instanceof NucleoObject) {
this.NucleoObject = config;
}
this.NucleoPrimitive = { Type: config.Type, serialize: config.serialize }
}
getListChildrenType = ():string => {
// TODO: oh please, improve this shit
if (this.NucleoObject) {
return 'NucleoObject';
}
return 'NucleoPrimitive';
}
}
<file_sep>import { createStore } from './store';
import {
NucleoString,
NucleoNumber,
NucleoBoolean
} from './nucleoTypes/primitive'
import NucleoObject from './nucleoTypes/NucleoObject';
import NucleoList from './nucleoTypes/NucleoList';
export {
createStore,
NucleoString,
NucleoNumber,
NucleoBoolean,
NucleoList,
NucleoObject
};
<file_sep># Nucleo
Nucleo creates and manages a strongly typed and predictable state container free of dependencies. It was built in TypeScript for be ran in any JavaScript ecosystem.
> Important note: This project is still under development. It's not recommended for production use yet, despite Nucleo basic functionalities are checked as done.
## Roadmap
It's in this project milestones https://github.com/mtmr0x/nucleo/milestones;
For requesting any feature, please open an issue with the prefix "[FEATURE REQUEST]".
## Why
JavaScript is a really dynamic language which we can't always rely in the language resilience from types perspective. Every project has types problems and developers can not make sure all the time the data is predictable. Inspired by how GraphQL does a great job with safety and trustful data and Redux by its simplicity on storing state, Nucleo was idealized to make sure the data model (contracts) and the data types are expected and reliable.
## Installation
Using NPM:
```
npm i nucleojs
```
Using Yarn:
```
yarn add nucleojs
```
## Basic usage
### Defining a data model (contract):
```javascript
import {
NucleoString,
NucleoNumber,
NucleoObject
} from 'nucleojs'
const completeNameContract = new NucleoObject({
name: 'completeNameContract',
fields: {
firstName: NucleoString,
lastName: NucleoString
}
});
const userContract = new NucleoObject({
name: 'user', // don't need to be the same name as the variable, but need to be unique
fields: {
name: completeNameType,
age: NucleoNumber
}
});
const productsContract = new NucleoObject({
name: 'products',
fields: {
title: NucleoString
}
});
const contracts = {
user: userContract,
products: productsContract
};
```
### Creating the store:
```javascript
import { createStore } from 'nucleojs';
const store = createStore(contracts); // send contracts to create the store
const { dispatch, update, getStore, subscribe } = store; // these 4 functions are returned from store creation
```
### Dispatching and updating the store:
Nucleo provides two methods of saving data, used for different approaches.
**dispatch:** works for saving data according to the full contract, used to save the very first contract state in the store or to update the whole contract in the store;
**update:** works for updating parts of data, it performs a index search in the object and save it. `update` will fail if you try to first save a contract to the store using it.
---
Dispatch function, considering user contract above:
```javascript
dispatch('user')({ name: { firstName: 'John', lastName: 'Nor' } });
// it'll fail because it's missing age field
dispatch('user')({ name: { firstName: 'John', lastName: 'Nor' }, age: 27 });
// it'll save the data to store properly
```
Update function, considering user contract above:
```javascript
update('user')({ name: { firstName: 'John' }});
// it'll update only the user first name and only if this item has been already created in the store before
```
### Subscribing to changes
You can simply subscribe to store changes by passing your listener functions to `subscribe` function. The listener must be a function and Nucleo will execute your listener sending an object argument with the updated contract for each update or dispatch to the store:
```javascript
subscribe(listener); // if it's not a function, Nucleo will throw an error
```
And inside Nucleo, your listener will be executed like this:
```javascript
listener({ contractName }); // This way you can understand better what was updated and consult Nucleo store as you wish
```
## Error management
Nucleo makes error management easy by type checking every level of contracts and returning an Object human and machine readable. The `update` and `dispatch` methods return an object with the following structure:
```javascript
{
status: 'NOK',
errors: [
{
error: '<some key> is not in <some contract> contract and can not be saved in store',
contract: 'contractName',
field: 'fieldName'
}
],
data: { ... } // the data you just tried to save in store
}
```
Code example:
```javascript
import {
NucleoString,
NucleoObject
} from 'nucleojs';
const userType = new NucleoObject({
name: 'user',
fields: {
name: NucleoString,
}
});
const contracts = {
user: userType
};
const { update } = createStore(contracts); // send contracts to create the store
const user = update('user')({ age: 140 });
console.log(user.errors); // here you'll find the error below:
/*
[
{
error: 'age field does not match its rules according to user contract',
contract: 'user',
field: 'age'
}
]
}
*/
```
In cases with no errors, `errors` list will be an empty list and `status` will be `OK`
```javascript
{
status: 'OK',
errors: []
data: { ... } // the data you just tried to save in store
}
```
## Contributing
Nucleo is open to any contribution made by community. And by contributing to Nucleo, you agree to our [code of conduct](https://github.com/mtmr0x/nucleo/blob/master/CODE_OF_CONDUCT.md)
### Bugs and improvements
Open a issue with the prefix [BUG] or [FEATURE REQUEST] for one of those cases with no restrictions, and try to clarify all your points bringing examples and well-founded arguments. If you need help in something, just make it clear at the beginning of your issue.
### Pull Requests
Once you want to fix something for Nucleo, you can just go ahead and do it, but for making people know the problem and that you're working on it (and maybe can get even more information) open an issue about it, and if necessary, just point that you desire to fix it, or if some help is needed.
For new features, it's highly recommended to open an issue first and discuss more to make sure this feature is really required to the project.
### Roadmap
Every approved issue as features and issues for fixes will be placed at Nucleo roadmap, in this repository milestones.
### Critical fixes
In case of critical fixes, which applies to everything that would directly interfere in Nucleo functionalities, we'll work hard to solve it and publish a new minor patch as soon as possible.
<file_sep>import { NucleoObjectType } from './NucleoObjectType';
import { NucleoPrimitiveType } from './NucleoPrimitiveType';
export type NucleoListType = {
itemsType: NucleoPrimitiveType
};
<file_sep>import { NucleoObjectType } from './../_types/NucleoObjectType';
// TODO: validate the name and fields, anything else can be here beyond the expected
export default class NucleoObject {
name: string;
fields: any;
constructor(config: NucleoObjectType) {
this.name = config.name;
this.fields = config.fields;
}
getFields = () => this.fields
}
|
64decaff31036e5420ae4e7cd673df5157935eac
|
[
"Markdown",
"TypeScript"
] | 9
|
TypeScript
|
rafaellincoln/nucleo
|
1a4f942aa29ca11ca36732137b32374da8591f8c
|
df9eac7b7fd7ea47eb8c5f96183be91d653f867e
|
refs/heads/main
|
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Provinces;
use Validator;
use Carbon\Carbon;
class ProvincesController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\Response
*/
public function index()
{
$provinces = Provinces::where('province_active_status', 1)->get();
return view('provinces.list', compact('provinces'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\Response
*/
public function create()
{
return view('provinces.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response
*/
public function store(Request $request, Provinces $province)
{
$province = new Provinces();
$province->province_id = $request->input('province_id');
$province->province_name = $request->input('province_name');
$province->province_active_status = $request->input('province_status');
$province->updated_at = null;
$province->save();
return redirect()->route('provinces.index')->with('success', 'Thêm dữ liệu thành công!');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\Response
*/
public function show(Provinces $provinces, $province_id)
{
}
public function showDeleted()
{
$provinces = Provinces::onlyTrashed()->get();
return view('provinces.deleted', compact('provinces'));
}
public function unlock($province_id)
{
$provinces = Provinces::onlyTrashed()->where('province_id', $province_id);
$provinces->restore();
$province = Provinces::find($province_id);
$province->province_active_status = 1;
$province->save();
return redirect()->route('provinces.index')->with('success', 'Phục hồi dữ liệu thành công!');
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\Response
*/
public function edit(Provinces $provinces, $province_id)
{
$provinces = Provinces::find($province_id);
//return $provinces;
return view('provinces.edit', compact('provinces'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response
*/
public function update(Request $request, Provinces $province)
{
$province->update($request->all());
return redirect()->route('provinces.index')->with('success', 'Sửa dữ liệu thành công!');
}
public function delete(Provinces $province)
{
$provinces = Provinces::findOrFail($province->province_id);
$provinces->province_active_status = 0;
$provinces->save();
$provinces->delete();
return redirect()->route('provinces.index')->with('success', 'Xoá dữ liệu thành công!');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response
*/
public function destroy($province_id)
{
$provinces = Provinces::onlyTrashed()->where('province_id', $province_id);
$provinces->forceDelete();
return redirect()->route('provinces.showDeleted')->with('success', 'Xoá dữ liệu thành công!');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\products;
class ProductsController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$data = products::all();
return view('welcome', compact('data'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$data = $request->all();
products::create($data);
return redirect()->route('index');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\Response
*/
public function show(products $product, $id)
{
//$product = products::findOrFail('$id');
//
$product = products::find($id);
//return $product;
return view('show', compact('product'));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, products $product)
{
products::where('id', $request->id)->update([
'name' => $request->name
]);
return redirect()->route('index');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Category;
use Illuminate\Support\Facades\Route;
class CategoryController extends Controller
{
public function index(Request $request)
{
$categoris = Category::where('parent_id',0)->get();
return view('category',["categoris" => $categoris]);
}
public function subCat(Request $request)
{
$parent_id = $request->cat_id;
$subcategories = Category::where('id',$parent_id)
->with('subcategories')
->get();
return response()->json([
'subcategories' => $subcategories
]);
}
}
<file_sep><?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PagesController;
use App\Http\Controllers\ProvincesController;
/*
|--------------------------------------------------------------------------
| 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('/cat', 'App\Http\Controllers\CategoryController@index');
// Route::post('/cat/{subcat}', 'App\Http\Controllers\CategoryController@subCat');
// Route::get('/', function () {
// return view('welcome');
// });
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
// Route::get('/', [PagesController::class, 'index'])->name('index');
Route::get('/provinces', [ProvincesController::class, 'index'])->name('provinces.index');
Route::get('/provinces/edit/{province}', [ProvincesController::class, 'edit'])->name('provinces.edit');
Route::post('/provinces/store', [ProvincesController::class, 'store'])->name('provinces.store');
Route::put('/provinces/update/{province}', [ProvincesController::class, 'update'])->name('provinces.update');
Route::get('/provinces/delete/{province}', [ProvincesController::class, 'delete'])->name('provinces.delete');
Route::get('/provinces/deleted', [ProvincesController::class, 'showDeleted'])->name('provinces.showDeleted');
Route::get('/provinces/unlock/{province}', [ProvincesController::class, 'unlock'])->name('provinces.unlock');
Route::get('/provinces/destroy/{province}', [ProvincesController::class, 'destroy'])->name('provinces.destroy');
/*
Route::get('/create',[ProductsController::class, 'create'])->name('create');
Route::post('/create',[ProductsController::class, 'store'])->name('store');
Route::get('/show/{id}',[ProductsController::class, 'show'])->name('show');
Route::put('/update', [ProductsController::class, 'update'])->name('update');
*/
|
723b22c5458470226f3be866c194389b4d3ff83d
|
[
"PHP"
] | 4
|
PHP
|
thoaidm/Laravel-Povinces-Login
|
8f2a2a366905c73b4733d0eb284d5519728004e9
|
6171e8d5bb63729618fee05a1cd9390b22867b6f
|
refs/heads/master
|
<file_sep>export const LOGIN_SUCCESS = 'LOGIN_SUCCESS';
export const LOGIN_FAIL = 'LOGIN_FAIL';
export const REGISTRATION_SUCCESS = 'REGISTRATION_SUCCESS';
export const REGISTRATION_FAIL = 'REGISTRATION_FAIL';
export const LOGOUT = 'LOGOUT';
export const SET_USER = 'SET_USER';
export const AUTH_ERROR = 'AUTH_ERROR';
export const KEEP_LOGGED_IN = 'KEEP_LOGGED_IN';
export const CLEAR_ERROR = 'CLEAR_ERROR';
export const SET_ERROR = 'SET_ERROR';
export const TODO_DELETE_SUCCESS = 'TODO_DELETE_SUCCESS';
export const TODO_DELETE_FAIL = 'TODO_DELETE_FAIL';
export const CREATE_TODO_SUCCESS = 'CREATE_TODO_SUCCESS';
export const CREATE_TODO_FAIL = 'CREATE_TODO_FAIL';
export const GET_TODOS_SUCCESS = 'GET_TODOS_SUCCESS';
export const GET_TODOS_FAIL = 'GET_TODOS_FAIL';
export const CLEAR_TODO = 'CLEAR_TODO';<file_sep>import React, { Fragment, useState, useContext } from 'react'
import ToDoContext from '../../contexts/todoContext/TodoContext';
export const FormToDo = () => {
const [name,setName] = useState('');
const {createToDo} = useContext(ToDoContext);
const handleChange = e => {
setName(e.target.value);
}
const handleSubmit = e => {
e.preventDefault();
createToDo(name);
setName('');
}
return (
<div className="mx-auto">
<form onSubmit={handleSubmit}>
<div className="input-group mb-3">
<input onChange={handleChange} value={name} type="text" className="form-control" placeholder="Add todo" />
<div className="input-group-append">
<button onClick={handleSubmit} className="btn btn-outline-secondary" type="button" id="button-addon2">Add</button>
</div>
</div>
</form>
</div>
)
}
export default FormToDo;
<file_sep>import Start from './Start';
import AuthState from './contexts/authContext/AuthState';
import React from 'react';
import setToken from './utils/setToken';
import TodoState from './contexts/todoContext/TodoState';
if (localStorage.token) {
setToken(localStorage.token);
}
function App() {
return (
<AuthState>
<TodoState>
<Start />
</TodoState>
</AuthState>
);
}
export default App;
<file_sep>import React, { Fragment, useState, useContext, useEffect } from 'react';
import AuthContext from '../../contexts/authContext/AuthContext';
import { Link } from 'react-router-dom';
const Register = (props) => {
const { registerUser, userAuth, errors, clearError ,setError} = useContext(AuthContext);
useEffect(() => {
clearError();
if (userAuth !== null) {
props.history.push('/');
}
}, [userAuth, props.history]);
const [user, setUser] = useState({
name: '',
email: '',
password: '',
passwordConfirm: ''
});
const handleChange = e => {
clearError();
setUser({
...user,
[e.target.name]: e.target.value
});
}
const handleSubmit = e => {
e.preventDefault();
const { name, email, password } = user;
if (user.passwordConfirm === user.password) {
registerUser({ name, email, password });
} else {
setError({
msg : "Passwords don't match"
});
}
}
return (
<div>
<h1 className="text-center">Register</h1>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="name">Name</label>
<input name="name" value={user.name} onChange={handleChange} type="text" className="form-control" id="name" />
</div>
<div className="form-group">
<label htmlFor="email">Email address</label>
<input name="email" value={user.email} onChange={handleChange} type="email" className="form-control" id="email" aria-describedby="emailHelp" />
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input name="password" value={user.password} onChange={handleChange} type="password" className="form-control" id="password" />
</div>
<div className="form-group">
<label htmlFor="passwordConfirm">Password</label>
<input name="passwordConfirm" value={user.passwordConfirm} onChange={handleChange} type="password" className="form-control" id="passwordConfirm" />
</div>
<button type="submit" className="btn btn-primary btn-block text-center">Submit</button>
<br />
{
errors !== null ?
(<div className="alert alert-danger alert-dismissible fade show" role="alert">
{errors.msg ? errors.msg : errors.error[0].msg}
<button type="button" className="close" onClick={() => clearError()}>
<span>×</span>
</button>
</div>) : null
}
</form>
<div>Already registered?
<Link to="/login">{" "}Log In</Link>
</div>
</div>
);
}
export default Register;<file_sep>import React, { useContext, useEffect, useLayoutEffect, useState, Fragment } from 'react';
import logo from './logo.svg';
import './App.css';
import Home from './components/pages/Home';
import Login from './components/pages/Login';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import PrivateRoute from './utils/PrivateRoute';
import AuthContext from './contexts/authContext/AuthContext';
import setToken from './utils/setToken';
import ReactLoading from 'react-loading';
import Register from './components/pages/Register';
function Start() {
const { keepUserLoggedIn } = useContext(AuthContext);
const [isLoading, setIsLoading] = useState(true);
useLayoutEffect(() => {
keepUserLoggedIn().then(() => setIsLoading(false))
}, []);
return (
<Fragment>
{
isLoading ? (
<ReactLoading type={"blank"} />
) : (
<Router>
<div className="container">
<Switch>
<PrivateRoute exact path="/" component={Home} />
<Route exact path="/login" component={Login} />
<Route exact path="/register" component={Register} />
</Switch>
</div>
</Router>
)
}
</Fragment>
);
}
export default Start;
<file_sep>const router = require('express').Router();
const auth = require('../middleware/AuthMiddleware');
const { check, validationResult } = require('express-validator');
const ToDo = require('../models/Todo');
router.get('/', auth, async (req, res) => {
try {
const todos = await ToDo.find({ user: req.user._id });
res.json(todos);
} catch (err) {
res.status(500).json({
msg : 'Server error'
});
}
});
router.post('/', auth,
[
check('name', 'Please provide todo').exists()
],
async (req, res) => {
const errors = validationResult(req);
if(!errors.isEmpty()) {
return res.status(400).json({error : errors.array()});
}
const {name} = req.body;
try {
let todo = new ToDo({
user : req.user._id,
name
});
todo = await todo.save();
res.status(200).json(todo);
} catch(err) {
res.status(500).json({
msg : 'Server error'
});
}
}
);
router.delete('/:_id',auth, async (req,res) => {
try {
let todo = await ToDo.findById(req.params._id);
if(!todo) {
return res.status(404).json({msg : 'Todo not found.'});
}
await ToDo.findByIdAndDelete(req.params._id);
res.send('todo deleted');
} catch(err) {
res.status(500).json({
msg : 'Server error'
});
}
})
module.exports = router;<file_sep>import React,{useReducer} from 'react';
import ToDoContext from './TodoContext';
import axios from 'axios';
import {CREATE_TODO_SUCCESS,CREATE_TODO_FAIL,TODO_DELETE_FAIL,TODO_DELETE_SUCCESS,GET_TODOS_FAIL,GET_TODOS_SUCCESS,CLEAR_TODO} from '../types';
import ToDoReducer from './TodoReducer';
import setToken from '../../utils/setToken';
const TodoState = (props) => {
const initialState = {
todos : [],
error : null
}
const [state,dispatch] = useReducer(ToDoReducer,initialState);
const config = {
header: {
'Content-Type': 'application/json'
}
};
const clearToDo = () => {
dispatch({
type : CLEAR_TODO
});
}
const getToDos = async () => {
if (localStorage.token) {
setToken(localStorage.token);
}
try {
const res = await axios.get('/todos')
dispatch({
type: GET_TODOS_SUCCESS,
payload: res.data
});
} catch (err) {
dispatch({
type: GET_TODOS_FAIL,
payload: err.response.msg
})
}
}
const createToDo = async (name) => {
try {
const res = await axios.post('/todos',{name},config);
dispatch({
type : CREATE_TODO_SUCCESS,
payload : res.data
});
} catch(err) {
dispatch({
type : CREATE_TODO_FAIL,
payload : err.response.data.msg
});
}
}
const deleteToDo = async (_id) => {
try {
await axios.delete(`/todos/${_id}`,config);
dispatch({
type : TODO_DELETE_SUCCESS,
payload : _id
});
} catch(err) {
dispatch({
type : TODO_DELETE_FAIL,
payload : err.response.data.msg
});
}
}
return (
<ToDoContext.Provider value={{
todos : state.todos,
error : state.error,
deleteToDo,
createToDo,
getToDos,
clearToDo
}}>
{props.children}
</ToDoContext.Provider>
);
}
export default TodoState;<file_sep>import {LOGIN_FAIL,LOGIN_SUCCESS,AUTH_ERROR,SET_USER,LOGOUT,KEEP_LOGGED_IN,SET_ERROR,REGISTRATION_FAIL,REGISTRATION_SUCCESS,CLEAR_ERROR} from '../types';
import setToken from '../../utils/setToken';
export default (state,{type,payload}) => {
switch(type) {
case KEEP_LOGGED_IN :
return {
...state,
userAuth : true,
user : payload,
errors : null
}
case REGISTRATION_SUCCESS :
case LOGIN_SUCCESS :
localStorage.setItem('token',payload.token);
return {
...state,
userAuth : true,
user : payload.user,
errors : null
}
case CLEAR_ERROR :
return {
...state,
errors : null
}
case SET_ERROR :
case AUTH_ERROR :
return {
...state,
errors : payload
}
case SET_USER :
return {
...state,
user : payload,
userAuth : true,
errors : null
}
case LOGOUT:
localStorage.removeItem('token');
return {
...state,
userAuth : null,
user : null,
}
case REGISTRATION_FAIL :
case LOGIN_FAIL :
localStorage.removeItem('token');
return {
...state,
userAuth : null,
user : null,
errors : payload
}
default :
return state;
}
}<file_sep>import React, { Fragment, useContext, useEffect } from 'react'
import ToDo from './ToDo'
import ToDoContext from '../../contexts/todoContext/TodoContext';
const ToDoList = () => {
const { todos, getToDos } = useContext(ToDoContext);
useEffect(() => {
getToDos();
}, []);
return (
<div className="mx-auto">
<ul className="list-group">
{todos.map(todo => <ToDo key={todo._id} todo={todo} />)}
</ul>
</div>
);
}
export default ToDoList;
<file_sep>import React, { useContext } from 'react';
import ToDoContext from '../../contexts/todoContext/TodoContext';
const ToDo = ({todo}) => {
const {deleteToDo} = useContext(ToDoContext);
return (
<li className="list-group-item">{todo.name} <span onClick={() => deleteToDo(todo._id)} style={{cursor : 'pointer'}} className="float-right"><i class="fas fa-trash"></i></span></li>
);
}
export default ToDo;<file_sep>import React,{useContext} from 'react';
import AuthContext from '../../contexts/authContext/AuthContext';
import ToDoList from '../todos/ToDoList';
import ToDoContext from '../../contexts/todoContext/TodoContext';
import FormToDo from '../todos/FormToDo';
const Home = (props) => {
const {logout,user} = useContext(AuthContext);
const {clearToDo} = useContext(ToDoContext);
const handleClick = () => {
logout();
clearToDo();
}
return (
<div className="text-center">
<h1>Welcome {user.name}</h1>
<br />
<FormToDo />
<br />
<ToDoList />
<br />
<button onClick={handleClick} className="btn btn-danger">Logout</button>
</div>
);
}
export default Home;
|
b9e118ca13bd4e632a0a8d50d365789795426a28
|
[
"JavaScript"
] | 11
|
JavaScript
|
vlad198/MERN-TODO
|
48be286ab1f7e08da59e55aa71353fff9a5cf54c
|
929ef594278fda538d1bfa508625565a5890daaa
|
refs/heads/master
|
<file_sep># SSHKit::Sudo
SSHKit extension, for sudo operation with password input.
## Installation
Add this line to your application's Gemfile:
```ruby
gem 'sshkit-sudo'
```
And then execute:
$ bundle
If you're using Capistrano, add the following to your Capfile:
```ruby
require 'sshkit/sudo'
```
## Usage
This gem adds `sudo` and `execute!` command to SSHKit backends.
To execute a command with sudo, call `sudo` instead of `execute`.
```ruby
sudo :cp, '~/something', '/something'
# Or as follows:
execute! :sudo, :cp, '~/something', '/something'
```
### Examples in Capistrano tasks
```ruby
# Executing a command with sudo in Capistrano task
namespace :nginx do
desc 'Reload nginx'
task :reload do
on roles(:web), in: :sequence do
sudo :service, :nginx, :reload
end
end
desc 'Restart nginx'
task :restart do
on roles(:web), in: :sequence do
execute! :sudo, :service, :nginx, :restart
end
end
end
namespace :prov do
desc 'Install nginx'
task :nginx do
on roles(:web), in: :sequence do
within '/etc/apt' do
unless test :grep, '-Fxq', '"deb http://nginx.org/packages/debian/ wheezy nginx"', 'sources.list'
execute! :echo, '"deb http://nginx.org/packages/debian/ wheezy nginx"', '|', 'sudo tee -a sources.list'
execute! :echo, '"deb-src http://nginx.org/packages/debian/ wheezy nginx"', '|', 'sudo tee -a sources.list'
execute! :wget, '-q0 - http://nginx.org/keys/nginx_signing.key', '|', 'sudo apt-key add -'
sudo :'apt-get', :update
end
end
sudo :'apt-get', '-y install nginx'
end
end
end
```
### Configuration
Available in sshkit-sudo 0.1.0 and later.
#### Same password across servers
If you are using a same password across all servers, you can skip inputting the password for the second server or after
by using `use_same_password!` method in your `deploy.rb` as follows:
```ruby
class SSHKit::Sudo::InteractionHandler
use_same_password!
end
```
#### Password prompt and wrong password matchers
You can set your own matchers in your `deploy.rb` as follows:
```ruby
class SSHKit::Sudo::InteractionHandler
password_prompt_regexp /[Pp]assword.*:/
wrong_password_regexp /Sorry.*\stry\sagain/
end
```
#### Making your own handler
You can write your own handler in your `deploy.rb` as follows:
```ruby
class SSHKit::Sudo::InteractionHandler
def on_data(command, stream_name, data, channel)
if data =~ wrong_password
SSHKit::Sudo.password_cache[password_cache_key(command.host)] = nil
end
if data =~ password_prompt
key = password_cache_key(command.host)
pass = SSHKit::Sudo.password_cache[key]
unless pass
print data
pass = $stdin.noecho(&:gets)
puts ''
SSHKit::Sudo.password_cache[key] = pass
end
channel.send_data(pass)
end
end
end
```
## Contributing
1. Fork it ( https://github.com/[my-github-username]/sshkit-sudo/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request
<file_sep>class OffDaySerializer < ActiveModel::Serializer
attributes :id , :user_id , :date , :is_all_day , :start , :end
end
<file_sep>class CreateSocialEventTypes < ActiveRecord::Migration[5.2]
def change
create_table :social_event_types, id: :uuid do |t|
t.references :social_event_category , type: :uuid , null: true , index: true ,foreign_key: { on_delete: :cascade , on_update: :cascade }
t.string :title , null: false
t.timestamps
end
end
end
<file_sep>require "sshkit/sudo/version"
require 'sshkit'
require 'sshkit/sudo/interaction_handler'
require 'sshkit/sudo/backends/abstract'
require 'sshkit/sudo/backends/netssh'
module SSHKit
module Sudo
def self.password_cache
@password_cache ||= {}
end
end
Backend::Abstract.send(:include, ::SSHKit::Sudo::Backend::Abstract)
Backend::Netssh.send(:include, ::SSHKit::Sudo::Backend::Netssh)
end
<file_sep>class Social < ApplicationRecord
# validations
validates_presence_of :name , :link
# enum
enum name: [ :twitter , :facebook , :telegram , :instagram , :snapchat , :soroush ]
# relations
# one to many
belongs_to :user
end
<file_sep>class AddAdminsToGroupsV2 < ActiveRecord::Migration[5.2]
def change
remove_column :users, :admins
add_column :groups, :admins, :string, array: true, default: []
end
end
<file_sep>module SSHKit
module Sudo
class DefaultInteractionHandler
def wrong_password; self.class.wrong_password; end
def password_prompt; self.class.password_prompt; end
def on_data(command, stream_name, data, channel)
if data =~ wrong_password
puts data if defined?(Airbrussh) and
Airbrussh.configuration.command_output != :stdout and
data !~ password_prompt
SSHKit::Sudo.password_cache[password_cache_key(command.host)] = nil
end
if data =~ password_prompt
key = password_cache_key(command.host)
pass = SSHKit::Sudo.password_cache[key]
unless pass
print data
pass = $stdin.noecho(&:gets)
puts ''
SSHKit::Sudo.password_cache[key] = pass
end
channel.send_data(pass)
end
end
def password_cache_key(host)
"#{host.user}@#{host.hostname}"
end
class << self
def wrong_password
@wrong_password ||= /<PASSWORD>/
end
def password_prompt
@password_prompt ||= /[Pp]assword.*:/
end
def wrong_password_regexp(regexp)
@wrong_password = regexp
end
def password_prompt_regexp(regexp)
@password_prompt = regexp
end
def use_same_password!
class_eval <<-METHOD, __FILE__, __LINE__ + 1
def password_cache_key(host)
'0'
end
METHOD
end
end
end
class InteractionHandler < DefaultInteractionHandler
end
end
end
<file_sep>class V1::Admin::UserController < ApplicationController
# ====================== validations
before_action :authenticate_request_admin
skip_before_action :authenticate_request_admin , :only => []
load_and_authorize_resource
# ======================= can can
rescue_from CanCan::AccessDenied do | exception |
render json: { alert: exception.message }
end
# ======================= show all user for admin
def index
page = params[:page] || 1
per = params[:per] || 10
render json: User.page(page).per(per) , status: 200
end
# ======================= delete user
def delete
User.where( id: params[:id] ).update(status: false ,role: :deleted ,phone_number: "deletedByAdmin")
render json: { success: "با موفقیت حذف شد" } , status: 200
end
# ======================= verify user manually with admin after calling to admins
def verify
if User.where( id: params[:id] ).update( verified: true)
render json: { success: "کاربر به روز رسانی شد" } , status: 200
end
end
# ======================= index deleted user
def indexDeletedUser
render json: User.where( "phone_number LIKE ?" , "%deletedByAdmin%" ).page(params[:page] || 1).per(param[:per] || 10)
end
# ======================= index active users
def indexActiveUser
render json: User.where( "phone_number NOT LIKE ?" , "%deletedByAdmin%" ).where( "verified" , true ).page(params[:page] || 1).per(params[:per] || 10)
end
end
<file_sep>class OffDay < ApplicationRecord
# ===================== validation
validates_presence_of :date
# ===================== relationship
# ============ one to many
# user and off day
belongs_to :user
end
<file_sep>class CreateOffDays < ActiveRecord::Migration[5.2]
def change
create_table :off_days, id: :uuid do |t|
t.references :user, type: :uuid, null: false, index: true ,foreign_key: { on_delete: :cascade , on_update: :cascade }
t.date :date , null:false
t.boolean :is_all_day , null: true
t.time :start , null: true
t.time :end , null: true
t.timestamps
end
end
end
<file_sep>class Group < ApplicationRecord
mount_base64_uploader :photo , GroupUploader
has_and_belongs_to_many :users
validates :name , presence: true
validates :description , presence: true
after_destroy :delete_members
def delete_members
self.group_members.destroy_all
end
end
<file_sep>class V1::MeetingController < ApplicationController
before_action :authenticate_request_user
load_and_authorize_resource
# ============================ can can
rescue_from CanCan::AccessDenied do | exception |
render json: { alert: exception.message }
end
# ================ create
def create
event = @current_user.event.build(eventParams)
event.event_type = "meeting"
event.is_private = true
event.is_verified = true
#1
if event.valid?
event.save
meeting = event.build_meeting(meetingParams)
#2
if meeting.valid?
meeting.save
#3
if meeting.is_invite == "true" or meeting.is_invite == 1
#4
if params[:user_id]
ivitedUserToMeeting = meeting.meeting_user.build(meetingUserParams)
#5
if ivitedUserToMeeting.save
render :json => {
:event => event.as_json(:except => [:created_at , :updated_at] , include: {meeting: {include: :meeting_user}} )
} , status: 200
return
#5
else
render json: ivitedUserToMeeting.errors , status:404
return
end
else
render json: { message: "sent user ids"} , status: 422
return
end
end
#3
if meeting.is_invite == "false" or meeting.is_invite == 0
render :json => {
:event => event.as_json(:except => [:created_at , :updated_at] , include: {meeting: {include: :meeting_user}}) ,
} , status: 200
return
#3
else
render json: { message: "مشکلی پیش آمده است به مدیر اطلاع دهید" } , status:422
return
#3
end
#2
else
render json: meeting.errors , status:422
return
#2
end
#1
else
render json: event.errors , status:422
return
#1
end
end
# ================ get all of meetings with pagination
def getAll
page = params[:page] || 1
per = params[:per] || 10
meeting = @current_user.event.where(event_type: "meeting").page(page).per(per)
render :json => {
:event => meeting.as_json(:except => [:created_at , :updated_at] , include: {meeting: {include: :meeting_user}})
} , status: 200
return
end
# ================ get between two time
def betweenTime
page = params[:page] || 1
per = params[:per] || 10
if params[:start_time] and params[:end_time]
meeting = @current_user.event.where(event_type: "meeting").where(date: params[:start_time]..params[:end_time]).page(page).per(per)
render :json => {
:event => meeting.as_json(:except => [:created_at , :updated_at] , include: {meeting: {include: :meeting_user}})
} , status: 200
return
else
render json: { message: "sent parameters completely" } , status: 422
end
end
# ================ today
def today
page = params[:page] || 1
per = params[:per] || 10
meeting = @current_user.event.where(event_type: "meeting").where(date: Time.now.strftime('%F')).page(page).per(per)
if meeting
render :json => {
:event => meeting.as_json(:except => [:created_at , :updated_at] , include: {meeting: {include: :meeting_user}})
} , status: 200
return
else
render json: { message: "not found" } , status:404
return
end
end
# =============== show
def show
#event = @current_user.event(id: params[:id]).first
meeting = Meeting.where(id: params[:id]).first
if meeting
render :json => {
:meeting => meeting.as_json(:except => [:created_at , :updated_at] , :include => [:event , :meeting_user] )
} , status: 200
return
else
render json: { message: "not found" } , status:404
end
end
# ================ delete
def delete
if params[:id]
meeting = Meeting.where(id: params[:id]).first.delete
render json: { message: "deleted successfully"} , status: 200
return
else
render json: { message: "meeting doesn't find" } , status: 404
return
end
end
# ================ private
private
def eventParams
params.permit(:date , :title , :description , :location_lat , :location_long , :address , :start_time , :end_time , :repeat_time , :notification_time , :end_of_repeat , :is_private , :is_verified , :photo)
end
def meetingParams
params.permit(:priority , :is_invite , :number_of_along)
end
def meetingUserParams
params.permit(:user_id)
end
end
<file_sep>class Lookup < ApplicationRecord
mount_base64_uploader :icon , LookupUploader
end
<file_sep>class V1::SocialsController < ApplicationController
before_action :authenticate_request_user
skip_before_action :authenticate_request_user, :only => []
load_and_authorize_resource
# ================== get socials
def getSocials
if @current_user
socials = @current_user.socials
render json: socials , status: 200
else
render json: { message: "کاربر پیدا نشد" } , status: 404
end
end
# ================== create socials
def create
# is user verified ?
unless @current_user.verified
render json: {error: " نام کاربری شما هنوز فعال نشده است "}, status: 400
return
end
# parameters are sent ?
if not params[:name] or not params[:link]
render json:{ message: " پارامتر ها به صورت کامل پر کنید " } , status: 404
return
end
# save social media
socials = @current_user.socials.build(socialParams)
if socials.save
render json: socials , status: :ok
else
render json: socials.errors , status: 400
end
end
# ===================== update social
def update
social = @current_user.socials.where( id: params[:id]).last
if social
if social.update(socialParams)
render json: social , status: 202
else
render json: social.errors, status: 400
end
else
render json: social.errors , status: 404
end
end
# =============== delete all socials
def delete_all
socials = @current_user.socials
if socials
if socials.destroy_all
render json: { success: " تمامی شبکه های اجتماهی حذف شدند " } , status: 202
else
render json: socials.errors , status: 400
end
else
render json: { error: " شبکه های اجتماعی کاربر مورد نظر یافت نشد " } , status: 404
end
end
# ================ delete a social
def delete
unless params[:id]
render json: {message: " اطلاعات را به صورت کامل بفرستید "}, status: 400
return
end
social = @current_user.socials.where( id: params[:id]).last
if social
if social.destroy
render json: { message: " شبکه اجتماعی حذف شد " } , status: 200
else
render json: social.errors , status: 400
end
else
render json: { message: " شبکه اجتماعی مورد نظر یافت نشد " } , status: 404
end
end
# =============== private methods
private
# =============== parameters to sent
def socialParams
params.permit( :name , :link)
end
end
<file_sep>Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
namespace :v1 , :defaults => {:format => :json} do
# ============== user's registration and login =================== #
post "user/register" , to: "user#register"
put "user/verify" , to: "user#verification"
post "user/token" , to: "authentication#authenticateUser"
post "user/resend_code" , to: "user#resendCode"
post "user/reset_password" , to: "user#resetPassword"
put "user/update_password" , to: "user#updatePassword"
delete "user/delete_account" , to: "user#deleteUser"
# ============== user's profile ================================= #
get "user/profile" , to: "user#profile"
put "user/update_profile" , to: "user#updateProfile"
put "user/upload_profile_picture" , to: "user#uploadProfilePicture"
# ============== social event routes ====================== #
# ============== personal evenet routes =================== #
post "personal_event/create" , to: "event#personalEventCreate"
get "personal_event/all" , to: "event#getAllPersonalEvent"
get "personal_event/month" , to: "event#getMonthPersonalEvent"
put "personal_event/update/:id" , to: "event#eventChange"
delete "personal_event/delete/:id" , to: "event#personalEventDelete"
get "personal_event" , to: "event#getTodayPersonalEvent"
get "personal_event/:id" , to: "event#getOnePersonalEvent"
# ============== party event routes ============================= #
post "party_event/create" , to: "party#createParty"
get "party_event/all" , to: "party#getAllPartyEvents"
get "party_event" , to: "party#getSpecifiedTimePartyEvent"
put "party_event/update/:id" , to: "party#updateParty"
match "party_event/delete/:id" , to: "party#deleteEvent", via: "delete"
get "party_event/today" , to: "party#todayParty"
get "party_event/:id" , to: "party#getOneParty"
# ============== surprise event ================================= #
post "surprise/create" , to: "surprise#create"
get "surprise/all" , to: "surprise#getAll"
get "surprise/between" , to: "surprise#betweenTime"
get "surprise/today" , to: "surprise#getToday"
get "surprise/show/:id" , to: "surprise#show"
delete "surprise/delete/:id" , to: "surprise#delete"
# ============== meeting event ================================== #
post "meeting_event" , to: "meeting#create"
get "meeting_event/all" , to: "meeting#getAll"
get "meeting_event/between" , to: "meeting#betweenTime"
get "meeting_event/today" , to: "meeting#today"
get "meeting_event/show/:id" , to: "meeting#show"
delete "meeting_event/delete/:id" , to: "meeting#delete"
# ============== social media =================================== #
get "user/social_media" , to: "socials#getSocials"
post "user/social_media/create" , to: "socials#create"
put "user/social_media/update/:id" , to: "socials#update"
delete "user/social_media/delete_all" , to: "socials#delete_all"
delete "user/social_media/delete/:id" , to: "socials#delete"
# =============== user types =================================== #
get "user/type" , to: "type_for_user#getUserTypes"
get "user/type/find" , to: "type_for_user#find"
post "user/type/create" , to: "type_for_user#create"
put "user/type/:id" , to: "type_for_user#update"
delete "user/type/delete/:id" , to: "type_for_user#delete"
# ============== user off days ================================ #
get "user/off_day" , to: "off_day#offDayUser"
get "user/off_day/from_to" , to: "off_day#offDayFromTo"
post "user/off_day/create" , to: "off_day#create"
put "user/off_day/update/:id" , to: "off_day#update"
delete "user/off_day/delete/:id" , to: "off_day#delete"
# ============== user event =================================== #
post "user/event/create" , to: "event#create"
# ============== our law ====================================== #
get "our_law" , to: "our_law#show"
# ============== national event routes ======================== #
get "today_national_event" , to: "national_event#todayEvent"
get "national_event/time_between" , to: "national_event#eventsInMonth"
# ============== national event routes ======================== #
get "today_event" , to: "event#todayEvent"
# ============== group routes =================================#
get "groups", to: "groups#getGroups"
post "group", to: "groups#createGroup"
put "group/:id", to: "groups#updateGroup"
get "group/:id", to: "groups#getGroup"
# ============== contact ===================== #
post "contacts", to: "user#insertContactNumbers"
get "contacts", to: "user#getContacts"
# ============= lookup ======================= #
get "lookup", to: "lookup#getLookup"
get "shake", to: "shake#make"
namespace :admin , :defaults => {:format => :json} do
# ============= user event ======================== #
get "users" , to: "user#index"
get "users/active" , to: "user#indexActiveUser"
get "users/deleted" , to: "user#indexDeletedUser"
delete "user/:id/delete" , to: "user#delete"
put "user/:id/verify" , to: "user#verify"
# ============== national event =================== #
get "national_event" , to: "national_event#index"
get "national_event/mySaved" , to: "national_event#userIndex"
get "national_event/time_between" , to: "national_event#eventsInMonth"
post "national_event/create" , to: "national_event#create"
put "national_event/update/:id" , to: "national_event#update"
delete "national_event/delete/:id" , to: "national_event#delete"
# ============== user social index ================= #
get "user/:user_id/social" , to: "social#indexUserSocial"
get "user/:user_id/social/:id" , to: "social#showSocial"
delete "user/:user_id/social/:id/delete" , to: "social#delete"
put "user/:user_id/social/:id/update" , to: "social#update"
# ============== user social index ================= #
get "user/:user_id/off_day" , to: "off_day#index"
get "user/:user_id/off_day/:id" , to: "off_day#show"
delete "user/:user_id/off_day/:id/delete" , to: "off_day#delete"
put "user/:user_id/off_day/:id/update" , to: "off_day#update"
# ============== our law ===================== #
get "our_law" , to: "our_law#show"
post "our_law" , to: "our_law#store"
put "our_law" , to: "our_law#update"
delete "our_law" , to: "our_law#delete"
# ============== social event category ================ #
post "social_event_category" , to: "social_event_category#create"
get "social_event_category/all" , to: "social_event_category#getAll"
put "social_event_category/:id" , to: "social_event_category#update"
delete "social_event_category/:id" , to: "social_event_category#delete"
# ============== social event category type ========================#
post "social_event_type" , to: "social_event_type#create"
get "social_event_type" , to: "social_event_type#categoryType"
delete "social_event_type/:social_event_type_id" , to: "social_event_type#delete"
put "social_event_type/:social_event_type_id" , to: "social_event_type#update"
end
end
end
<file_sep>class V1::Admin::NationalEventController < ApplicationController
before_action :authenticate_request_admin
skip_before_action :authenticate_request_admin , :only => []
# ============================ can can
load_and_authorize_resource
rescue_from CanCan::AccessDenied do | exception |
render json: { alert: exception.message }
end
# ============================= get national_events
def index
# if date sent
if params[ :date ]
searchWithDate
return
end
# if title passed
if params[:title]
searchWithTitle
return
end
# if is day off only passed
if params[ :is_day_off ]
searchWithDayOff
return
end
# only page and per sent
if params[ :page ] and params[ :per ]
searchWithPagination
return
end
events = NationalEvent.order( "updated_at DESC" ).all
render json: events , status: 302
end
# ============================= user saved national event
def userIndex
events = @current_user.national_event.order(" updated_at DESC ").page(params[:page] || 1).per(params[:per] || 10)
render json: events , status: 302
end
# ============================= create national event
def create
# parameters are sent ?
if not params[:date] or not params[:title] or not params[:is_day_off]
render json:{ error: "پارامتر ها را به صورت کامل ارسال کنید" } , status: 402
return
end
# save national event
event = @current_user.national_event.build(nationalEventParams)
if event.save
render json: event , status: :ok
else
render json: event.errors , status: 400
end
end
# ============================= update
def update
event = @current_user.national_event.where( id: params[:id]).last
if event
if event.update(nationalEventParams)
render json: event , status: 200
else
render json: event.errors , status: 400
end
else
render json: { error: " رویداد عمومی یافت نشد " } , status: 404
end
end
# ============================= delete
def delete
if NationalEvent.where( id: params[:id]).last.delete
render json: { successfull: "رویداد عمومی حذف شد" } , status: 200
end
end
# ============================= events between 2 date
def eventsInMonth
# if start and end time sent
if params[ :start ] and params[ :end ]
render json: NationalEvent.where( date: params[:start]..params[:end] ).order( "date" ).all , status: 302
else
render json: { error: "پارامتر ها را کامل پاس دهید" } , status: :not_found
end
end
# ================================ PRIVATE TO THIS CONTROLLER ========================================
private
# ================================ parameters to sent
def nationalEventParams
params.permit( :date , :title , :description , :is_day_off)
end
# ================================ define search with date
def searchWithDate
# if day is off and parameters of page and per passed
if params[ :page ] and params[:per] and params[ :is_day_off ] == true or params[ :is_day_off ] == "true"
events = NationalEvent.where( date: params[:date] ).where( is_day_off: true ).order( "updated_at DESC" ).page(params[:page]).per(params[:per])
render json: events , status: 302
return
# if day is off and parameters of page and per =>not<= passed
elsif params[ :is_day_off ] == true or params[ :is_day_off ] == "true"
events = NationalEvent.where( date: params[:date] ).where( is_day_off: true ).order( "updated_at DESC" ).all
render json: events , status: 302
return
# if day is on and parameters of page and per passed
elsif params[ :page ] and params[:per] and params[ :is_day_off ] == false or params[ :is_day_off ] == "false"
events = NationalEvent.where( date: params[:date] ).where( is_day_off: false ).order( "updated_at DESC" ).page(params[:page]).per(params[:per])
render json: events , status: 302
return
# if day is on and parameters of page and per =>not<= passed
elsif params[ :is_day_off ] == false or params[ :is_day_off ] == "false"
events = NationalEvent.where( date: params[:date] ).where( is_day_off: false ).order( "updated_at DESC" ).all
render json: events , status: 302
return
end
# date pass and params and per
if params[:page] and params[:per]
events = NationalEvent.where(date: params[:date]).order( "updated_at DESC" ).page(params[:page]).per(params[:per])
render json: events , status: 302
return
end
# date pass only
events = NationalEvent.where( date: params[:date]).order( "updated_at DESC" ).all
render json: events , status: 302
end
# ================================ define search with is day off
def searchWithDayOff
if params[:is_day_off] == true or params[:is_day_off] == "true"
# if page and per parameters were available
if params[:page] and params[:page]
events = NationalEvent.where( is_day_off: true ).order( "updated_at DESC" ).page(params[:page]).per(params[:per])
render json: events , status: 302
return
else
# if only day off matters
events = NationalEvent.where( is_day_off: true ).order( "updated_at DESC" ).all
render json: events , status: 302
return
end
# day is on
elsif params[:is_day_off] == false or params[:is_day_off] == "false"
# page and per sent
if params[:page] and params[:page]
events = NationalEvent.where( is_day_off: false ).order( "updated_at DESC" ).page(params[:page]).per(params[:per])
render json: events , status: 302
return
else
# if only day on matters
events = NationalEvent.where( is_day_off: false ).order( "updated_at DESC" ).all
render json: events , status: 302
return
end
end
end
# ================================ define search only with pagination
def searchWithPagination
events = NationalEvent.order( "updated_at DESC" ).page(params[:page]).per(params[:per])
render json: events , status: 302
end
# ================================ define search with title
def searchWithTitle
if params[:is_day_off] == true or params[:is_day_off] == "true"
# if page and per parameters were available
if params[:page] and params[:page]
events = NationalEvent.where( title: params[:title] ).order( "updated_at DESC" ).page(params[:page]).per(params[:per])
render json: events , status: 302
return
else
# if only day off matters
events = NationalEvent.where( title: params[:title] ).order( "updated_at DESC" ).all
render json: events , status: 302
return
end
# day is on
elsif params[:is_day_off] == false or params[:is_day_off] == "false"
# page and per sent
if params[:page] and params[:page]
events = NationalEvent.where( title: params[:title] ).order( "updated_at DESC" ).page(params[:page]).per(params[:per])
render json: events , status: 302
return
else
# if only day on matters
events = NationalEvent.where( title: params[:title] ).order( "updated_at DESC" ).all
render json: events , status: 302
return
end
end
if params[:page] and params[:per]
events = NationalEvent.where( title: params[:title] ).order( "updated_at DESC" ).page(params[:page]).per(params[:per])
render json: events , status: 302
end
events = NationalEvent.where( title: params[:title] ).order( "updated_at DESC" ).all
render json: events , status: 302
end
end
<file_sep>class V1::SurpriseController < ApplicationController
before_action :authenticate_request_user
load_and_authorize_resource
# ============================ can can
rescue_from CanCan::AccessDenied do | exception |
render json: { alert: exception.message }
end
# ============================ create
def create
event = @current_user.event.build(eventParams)
event.event_type = "surprise"
event.is_private = true
event.is_verified = true
if event.valid?
event.save
surprise = event.build_surprise(surpriseParams)
if surprise.valid?
surprise.save
if surprise.is_invite == "true" or surprise.is_invite == 1
if params[:user_id]
inviteUserToSurprise = surprise.surprise_user.build(surpriseUserParams)
if inviteUserToSurprise.save
render :json => {
:event => event.as_json(:except => [:created_at , :updated_at] , include: {surprise: {include: :surprise_user}} )
} , status: 200
else
render json: invitedUserToSurprise.errors , status: 422
end
else
render json: { message: "send user id parameter" } , status: 422
end
elsif surprise.is_invite == "false" or surprise.is_invite == 0
render :json => {
:event => event.as_json(:except => [:created_at , :updated_at] , include: {surprise: {include: :surprise_user}} )
} , status: 200
else
render json: { message: "something went wrong" } , status: 422
end
else
render json: surprise.errors , status: 422
end
else
render json: event.errors , status: 422
end
end
# ========================== get between two time
def betweenTime
page = params[:page] || 1
per = params[:per] || 10
if params[:start_time] and params[:end_time]
surprise = @current_user.event.where(event_type: "surprise").where(date: params[:start_time]..params[:end_time]).page(page).per(per)
render :json => {
:event => surprise.as_json(:except => [:created_at , :updated_at] , include: {surprise: {include: :surprise_user}})
} , status: 200
return
else
render json: { message: "sent parameters completely" } , status: 422
end
end
# =========================== get all
def getAll
page = params[:page] || 1
per = params[:per] || 10
surprise = @current_user.event.where(event_type: "surprise").page(page).per(per)
render :json => {
:event => surprise.as_json(:except => [:created_at , :updated_at] , include: {surprise: {include: :surprise_user}})
} , status: 200
return
end
# ========================== get today surprise
def getToday
page = params[:page] || 1
per = params[:per] || 10
surprise = @current_user.event.where(event_type: "surprise").where(date: Time.now.strftime('%F')).page(page).per(per)
if surprise
render :json => {
:event => surprise.as_json(:except => [:created_at , :updated_at] , include: {surprise: {include: :surprise_user}})
} , status: 200
return
else
render json: { message: "not found" } , status:404
return
end
end
# =========================== show
def show
surprise = Surprise.where(id: params[:id]).first
if surprise
render :json => {
:surprise => surprise.as_json(:except => [:created_at , :updated_at] , :include => [:event , :surprise_user] )
} , status: 200
return
else
render json: { message: "not found" } , status:404
end
end
# =========================== delete
def delete
if params[:id]
surprise = Surprise.where(id: params[:id]).first.delete
render json: { message: "deleted successfully"} , status: 200
return
else
render json: { message: "surprise doesn't find" } , status: 404
return
end
end
# =========================== private
def eventParams
params.permit(:date , :title , :description , :location_lat , :location_long , :address , :start_time , :end_time , :repeat_time , :notification_time , :end_of_repeat , :is_private , :is_verified , :photo)
end
def surpriseParams
params.permit(:fake_title , :fake_description , :theme , :is_invite , :number_of_along , :user_to_surprise_id)
end
def surpriseUserParams
params.permit(:user_id)
end
end
<file_sep>module SSHKit
module Sudo
module Backend
module Abstract
def sudo(*args)
execute!(:sudo, *args)
end
def execute!(*args)
options = args.extract_options!
options[:interaction_handler] ||= SSHKit::Sudo::InteractionHandler.new
create_command_and_execute!(args, options).success?
end
private
def execute_command!(*args)
execute_command(*args)
end
def create_command_and_execute!(args, options)
command(args, options).tap { |cmd| execute_command!(cmd) }
end
end
end
end
end
<file_sep>class UserToSurprise < ApplicationRecord
end
<file_sep>class UserSerializer < ActiveModel::Serializer
attributes :id, :first_name , :family_name , :phone_number , :sex , :birthday , :role , :photo , :bio , :username , :email , :location , :is_private , :verified
has_many :user_color_event
end
<file_sep>class CreateUsers < ActiveRecord::Migration[5.2]
require 'securerandom'
def change
create_table :users, id: :uuid do |t|
# fillables
t.string :first_name, null: false
t.string :family_name, null: false
t.string :phone_number , null:false , unique: true , index:true
t.string :password_digest
t.string :email , null: false , unique: true
t.date :birthday , null:false
t.integer :sex , null:false
t.integer :role , default: 1
# fill in update
t.string :photo , null: true
t.text :bio , null: true
t.string :username , null: true
t.string :location , null: true
t.boolean :is_private , default:true
# hidden
t.string :verification_code , null: false
t.boolean :verified , default: false
t.boolean :status , default: true
t.datetime :verification_code_sent_at
t.boolean :forget_password
t.timestamps
end
end
end
<file_sep>class V1::UserController < ApplicationController
# ====================== validations
before_action :authenticate_request_user
skip_before_action :authenticate_request_user, :except => [ :profile, :updatePassword , :updateProfile , :deleteUser , :uploadProfilePicture, :insertContactNumbers, :getContacts]
load_and_authorize_resource
skip_authorize_resource :only => [ :register , :verification , :deleteUser ]
# ======================= can can
rescue_from CanCan::AccessDenied do | exception |
render json: { alert: exception.message }
end
# ======================= register a user
def register
# check if the password and password confirmation is same
if params[:password] != params[:password_confirmation]
# 409 status code is for conflict
render json: { message: " رمز عبور ها همخوانی ندارند " } , status: 409
return
end
# check user is subscribed or not
if User.find_by(phone_number: params[:phone_number])
render json: { message: "اطلاعات شما در حال حاضر در سامانه سیت و میت حضور دارد " } , status: 422
return
end
# check the fields is filled or not
if not params[:first_name] or not params[:family_name] or not params[:phone_number] or not params[ :sex ] or not params[:password] or not params[:birthday]
render json: { message: " اطلاعات را به صورت کامل وارد کنید " } , status: 400
return
end
#register user
user = User.new(register_params)
user.verified = false
user.status = true
user.forget_password = false
code = rand(1000..9999)
user.verification_code = code
user.verification_code_sent_at = Time.now
if user.save
nc_authorization_key = register_to_nc
user.update(nc_authorization_key: nc_authorization_key)
for i in 0..4
userColorEvent = UserColorEvent.new
userColorEvent.user_id = user.id
userColorEvent.event_color = i
userColorEvent.event_type = i
userColorEvent.save
end
text = " سلام #{ user.first_name + ' ' + user.family_name } عزیز \n به سامانه ی سیت و میت خوش آمدید \n کد عبور شما #{ code } است \n سامانه ی سیت و می"
send_sms( user.phone_number , text)
render json: user , status: :created
else
render json: { message: user.errors }, status: :unprocessable_entity
end
end
# ======================= verify the user
def verification
# code is not sent
unless params[:code]
render json: { message: " اطلاعات را به صورت کامل بفرستید " } , status:400
return
end
# code is sent and user found
if params[:code]
user = User.where(verification_code: params[:code]).where(phone_number: params[:phone_number]).first
if user and not user.verified
if Time.now > user.verification_code_sent_at + 10.minute
render json: { message: " کد ارسالی شما باطل شده است " } , status: 403
else
user.verified = true
if user.save
render json: { message: " کاربر تایید شد " } , status: 200
else
render json: { message: user.errors.full_messages } , status: 400
end
end
elsif user&.verified
render json: { message: " شما در حال حاضر تایید شده هستید " } , status: 200
else
render json: { message: " کد را اشتباه وارد کردید " } , status: 400
end
end
end
# ======================= resend the code if time has been ended
def resendCode
user = User.where(phone_number: params[:phone_number]).first
code = rand(1000..9999)
unless user
render json: { message: " کاربر با شماره تلفن مورد نظر وجود ندارد " } , status: 404
return
end
user.verification_code = code
user.verification_code_sent_at = Time.now
if user.save
text = " #{ user.first_name } #{ user.family_name } عزیز \nکد ورود مجدد شما به سامانه سیت و میت #{ user.verification_code } است \nسامانه سیت و میت "
send_sms(user.phone_number , text)
render json: { message: " کد فرستاده شد " } , status: 200
else
render json: { message: user.errors.full_messages } , status: :unprocessable_entity
end
end
# ======================= reset password
def resetPassword
user = User.where(phone_number: params[:phone_number]).first
if user
if user.update(forget_password: true)
code = rand(1000..9999)
text = "#{ user.first_name + ' ' + user.family_name } عزیز\nکد عبور شما #{ code } است\nلطفا پس از ورود مجدد ، رمز خود را تغییر دهید\nسامانه سیت و میت"
user.password_digest = BCrypt::Password.create(code)
if user.save
send_sms(user.phone_number , text)
render json: { message: " پیام ارسال شد و کد عبور شما تغییر یافت " } , status: 200
else
render json: { message: " پیام ارسال نشد ، به واحد پشتیبانی خبر دهید. " } , status: 410
end
else
render json: { message: user.errors } , status: 403
end
else
render json: { message: "کاربر پیدا نشد" } , status: 404
end
end
# ======================= get user profile
def profile
if @current_user
render json: @current_user , status: 200
else
render json: { message: " توکن شما یافت نشد! " } , status: 200
end
end
# ======================= updating password
def updatePassword
if not params[:oldPassword] or not params[:newPassword] or not params[:newPasswordConfirmation]
render json: { message: " رمز عبور گذشته خود را وارد کنید " } , status: 422
return
end
user = @current_user
unless user.authenticate(params[:oldPassword])
render json: { message: " رمز عبور گذشته به درستی وارد نشده است " } , status: 400
return
end
unless params[:newPassword] == params[:newPasswordConfirmation]
render json: { message: " رمز عبور ها همخوانی ندارند " } , status: 400
end
user.password = params[:newPassword]
if user.forget_password
user.forget_password = false
end
if user.save
render json: { message: " رمز عبور با موفقیت تغییر یافت " } , status: 400
else
render json: { message: user.errors } , status: :unprocessable_entity
end
end
# ======================= upload profile picture
def uploadProfilePicture
if @current_user.update(profilePicture)
Rails.logger.info "****************#{@current_user.photo.url}****"
render json: @current_user , status: 200
else
render json: { message: @current_user.errors } , status: 404
end
end
# ======================= update profile
def updateProfile
lastPhoneNumber = @current_user.phone_number
if @current_user.update(updateParams)
unless lastPhoneNumber == @current_user.phone_number
current_user.update(verified: false)
code = rand(1000..9999)
current_user.verification_code = code
current_user.verification_code_sent_at = Time.now
text = " #{ user.first_name + ' ' + user.family_name } عزیز \nکد ورود مجدد شما به سامانه سیت و میت #{ user.verification_code } است \nسامانه سیت و میت "
send_sms(@current_user.phone_number,text)
render json: { message: " شماره تماس تغییر یافت و کد تایید مجدد فرستاده شد " } , status: :ok
return
end
render json: { message: " به روز راستی شد " } , status: :ok
end
end
# ======================= delete user
def deleteUser
@current_user.update(status: false ,role: :deleted ,phone_number: "#{@current_user.phone_number}*deleted*#{rand(11.99)}")
render json: { message: "با موفقیت حذف شد" }, status: 200
end
# ======================= insert contact numbers
def insertContactNumbers
@current_user.update(contacts: params[:contacts])
render json: {message: "ok"}
end
# ======= get contact
def getContacts
result = []
@current_user.contacts.each do |cn|
user = User.where("phone_number = ?", cn).last
if user
object = {id: user.id,phone_number: cn,photo: user.photo}
result.push(object)
end
end
render json: result
end
def getNotificationCenterInfo
""#render json: {authorization_key: @current_user.nc_authorization_key}
end
# ======================= private for this controller
private
# ======================= register parameters
def register_params
params.permit( :first_name , :family_name , :phone_number , :password , :sex , :birthday , :email)
end
# ======================= update parameters
def updateParams
params.permit( :first_name , :family_name , :phone_number , :sex , :birthday , :bio , :username , :email , :location , :is_private , :photo)
end
# ======================= upload profile
def profilePicture
params.permit( :photo)
end
# ======================= send sms
def send_sms(to,text)
url = "http://www.0098sms.com/sendsmslink.aspx?FROM=30005883333335&TO=#{to}&TEXT=#{text}&USERNAME=xsms6874&PASSWORD=<PASSWORD>&DOMAIN=0098"
url = URI.encode(url)
RestClient.get(url)
end
def register_to_nc
authorization_key = ""
response = RestClient.post 'http://31.184.135.239/api/v1/player', {api_key: "#{nd_android_api_key}"}
if response.code == 200
authorization_key = JSON.parse(response.body)["authorization_key"]
end
authorization_key
end
end
<file_sep>class UserColorEvent < ApplicationRecord
validates :event_type , presence: true
validates :event_color , presence: true
enum event_type: [ :personal , :surprise , :party , :meeting , :social ]
enum event_color: [ :red , :blue , :purple , :cyan , :orange ]
belongs_to :user
end
<file_sep>class SocialEventCategory < ApplicationRecord
validates :title , presence: true
# ============== one to many
has_many :social_event_type , :dependent => :destroy
end
<file_sep>class AddSomeFieldsToGroups < ActiveRecord::Migration[5.2]
def change
add_column :groups, :owner, :uuid, index: true
end
end
<file_sep>class SurpriseUser < ApplicationRecord
belongs_to :surprise
belongs_to :user
end
<file_sep>namespace :nginx do
desc <<-DESC
Setup nginx configuration
Configurable options are:
set :nginx_roles, :all
set :nginx_path, "/etc/nginx"
set :nginx_upstream, -> { fetch(:application) }
set :nginx_server_name, -> { fetch(:application) }
set :nginx_template, "config/deploy/nginx_conf.erb"
DESC
task :setup do
invoke :'nginx:create_config'
invoke :'nginx:enable_site'
end
task :create_config do
on roles fetch(:nginx_roles) do
config_file = fetch(:nginx_template)
unless File.exists?(config_file)
config_file = File.join(File.dirname(__FILE__), "../../generators/capistrano/nginx/templates/_nginx_conf.erb")
end
config = ERB.new(File.new(config_file).read, 0, '-').result(binding)
upload! StringIO.new(config), "#{fetch(:nginx_path)}/sites-available/#{fetch(:application)}.conf"
end
end
[:stop, :start, :restart, :reload, :'force-reload'].each do |action|
desc "#{action.to_s.capitalize} nginx"
task action do
on roles fetch(:nginx_roles) do
sudo :service, "nginx", action.to_s
end
end
end
desc 'Enable nginx site'
task :enable_site do
on roles fetch(:nginx_roles) do
execute :ln, "-sf",
"#{fetch(:nginx_path)}/sites-available/#{fetch(:application)}.conf",
"#{fetch(:nginx_path)}/sites-enabled/#{fetch(:application)}.conf"
end
invoke :'nginx:reload'
end
desc 'Disable nginx site'
task :disable_site do
on roles fetch(:nginx_roles) do
config_link = "#{fetch(:nginx_path)}/sites-enabled/#{fetch(:application)}.conf"
execute :unlink, config_link if test "[ -f #{config_link} ]"
end
invoke :'nginx:reload'
end
end
namespace :load do
task :defaults do
set :nginx_roles, :all
set :nginx_path, "/etc/nginx"
set :nginx_upstream, -> { fetch(:application) }
set :nginx_server_name, -> { fetch(:application) }
set :nginx_template, "config/deploy/nginx_conf.erb"
end
end
<file_sep>class V1::AuthenticationController < ApplicationController
# is user authenticate or not
def authenticateUser
user = User.where( :phone_number => params[:phone_number] ).first
# find user and if not present return 404 status code
unless user
render json: { message:" کاربر پیدا نشد " } , status: 404
return
end
# get to a user token
command = AuthenticateUser.call(params[:phone_number] , params[:password])
# find user by it's phone number
user = User.find_by(phone_number: params[:phone_number])
# if token is correctly accessed
if command.success?
unless user.verified
render :json => {
:data => user.as_json(:only => [:verified])
} , status: 401
return
end
if user.status
render json: { token: command.result}
end
elsif !user.status
render json: { message: " شما به این بخش دسترسی ندارید " } , status: 403
else
render json: { message: " اشتباه " } , status: 401
end
end
end
<file_sep>class SocialSerializer < ActiveModel::Serializer
attributes :id , :name , :link
# belongs_to :user
end
<file_sep>class NationalEvent < ApplicationRecord
# validations
validates_presence_of :date , :title
# relations
# one to many
belongs_to :user , :dependent => :destroy
end
<file_sep># Capistrano::nginx
Nginx support for Capistrano 3.x
## Installation
Add this line to your application's Gemfile:
```ruby
gem 'capistrano', '~> 3.0.0'
gem 'capistrano-nginx', github: 'koenpunt/capistrano-nginx'
```
And then execute:
$ bundle
Or install it yourself as:
$ gem install capistrano-nginx
## Usage
Require in `Capfile`:
```ruby
require 'capistrano/nginx'
```
Launch new tasks:
$ cap production nginx:setup
$ cap production nginx:reload
If you want to customize the nginx configuration, you can use the Rails generator to create a local copy of the config template:
$ rails generate capistrano:nginx:config
And then edit `config/deploy/nginx_conf.erb` as you like.
Configurable options, shown here with defaults:
```ruby
set :nginx_path, '/etc/nginx' # directory containing sites-available and sites-enabled
set :nginx_template, 'config/deploy/nginx_conf.erb' # configuration template
set :nginx_server_name, 'example.com' # optional, defaults to :application
set :nginx_upstream, 'example-app' # optional, defaults to :application
set :nginx_listen, 80 # optional, default is not set
set :nginx_roles, :all
```
### Tasks
This gem provides the following Capistrano tasks:
* `nginx:setup` creates `/etc/nginx/sites-available/APPLICATION.conf` and links it to `/etc/nginx/sites-enabled/APPLICATION.conf`
* `nginx:stop` invokes `service nginx stop` on server
* `nginx:start` invokes `service nginx start` on server
* `nginx:restart` invokes `service nginx restart` on server
* `nginx:reload` invokes `service nginx reload` on server
* `nginx:force-reload` invokes `service nginx force-reload` on server
* `nginx:enable_site` creates symlink in sites-enabled directory
* `nginx:disable_site` removes symlink from sites-enabled directory
## Contributing
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
<file_sep>class User < ApplicationRecord
# ======================== password
has_secure_password
# ======================== model has an image and uploader
mount_base64_uploader :photo , UserImageUploader
# ======================== User::Roles
# The available roles
enum role: [ :admin , :normal , :deleted]
def is?( requested_role )
self.role == requested_role.to_s
end
# ====================== validation
validates :first_name , presence: true
validates :family_name , presence: true
validates :phone_number , presence: true, uniqueness: true
# validates :password , presence: true
validates :sex , presence: true
validates :birthday , presence: true
validates :email , presence: true
validates :password_digest , confirmation: true
validates :photo , file_size: { less_than: 5.megabytes }
#validates_presence_of :event
#validates_presence_of :party
# ======================= enum
enum sex: [ :male , :female ]
# ======================= relations
# =========================== one to one
has_many :user_color_event , :dependent => :destroy
#has_many :event_color , :dependent => :destroy
# ============== one to many
has_many :national_event , :dependent => :destroy
has_many :our_laws , :dependent => :destroy
has_many :socials , :dependent => :destroy
has_many :off_days , :dependent => :destroy
has_many :social_event , :dependent => :destroy
has_and_belongs_to_many :groups
has_many :event , :dependent => :destroy
# ============== many to many
has_many :party , :through => "party_user" , :foreign_key => "party_id"
has_many :party_user
has_many :meeting , :through => "meeting_user" , :foreign_key => "meeting_id"
has_many :meeting_user
# surprise and user
has_many :surprise , :through => "surprise_user" , :foreign_key => "surprise_id"
has_many :surprise_user
end
<file_sep>source 'https://rubygems.org'
# Specify your gem's dependencies in capistrano-nginx.gemspec
gemspec
<file_sep>class V1::OurLawController < ApplicationController
# load_and_authorize_resource
# ============================ can can
rescue_from CanCan::AccessDenied do | exception |
render json: { alert: exception.message }
end
# ======================= show
def show
law = OurLaw.last
if law
render json: OurLaw.last , status: 200
else
render json: { error: "قوانین مورد نظر یافت نشد" } , status: 404
end
end
end
<file_sep>class UserColorEventSerializer < ActiveModel::Serializer
attributes :id , :event_type , :event_color
belongs_to :user
end
<file_sep>class CreateMeetingUsers < ActiveRecord::Migration[5.2]
def change
create_table :meeting_users, id: :uuid do |t|
t.references :meeting , type: :uuid, null: false, index: true ,foreign_key: { on_delete: :cascade , on_update: :cascade }
t.references :user , type: :uuid , null: false , index: true , foreign_key: { on_delete: :cascade , on_update: :cascade }
t.timestamps
end
end
end
<file_sep>class V1::Admin::SocialController < ApplicationController
before_action :authenticate_request_admin
skip_before_action :authenticate_request_admin , :only => []
# ============================ can can
load_and_authorize_resource
rescue_from CanCan::AccessDenied do | exception |
render json: { alert: exception.message }
end
# ============================ index user social
def indexUserSocial
render json: User.where( id: params[:user_id] ).last.socials.page(params[:page] || 1).per(params[:per] || 10) , status: 200
end
# ============================ show users Social individual
def showSocial
social = Social.where( user_id: params[:user_id] ).where( id: params[:id] ).last
if social
render json: social , status: 200
else
render json: { error: "شبکه اجتماعی یا کاربر پیدا نشد" } , status: 404
end
end
# ============================ delete social
def delete
if Social.where( user_id: params[:user_id] ).where( id: params[:id] ).last.destroy
render json: { success: "شبکه ی مورد نظر حذف شد" } , status: 200
else
render json: { error: " شبکه یا کاربر مورد نظر یافت نشد " } , status: 404
end
end
# ============================ update social
def update
social = Social.where( user_id: params[:user_id] ).where( id: params[:id] ).last
if social
if social.update(updateParams)
render json: social
else
render json: { error: social.errors } ,status: 404
end
else
render json: { error: " شبکه یا کاربر مورد نظر یافت نشد " } , status: 404
end
end
# ============================ private in this controller
private
def updateParams
params.permit( :name , :link )
end
end
<file_sep>class OurLaw < ApplicationRecord
# validations
validates_presence_of :title , :description
#relations
belongs_to :user , :dependent => :destroy
end
<file_sep>class V1::Admin::OurLawController < ApplicationController
before_action :authenticate_request_admin
skip_before_action :authenticate_request_admin , :only => []
# ============================ can can
load_and_authorize_resource
rescue_from CanCan::AccessDenied do | exception |
render json: { alert: exception.message }
end
# ============================ show
def show
render json: OurLaw.last , status: 200
end
# =========================== store
def store
if not params[:title] or not params[:description]
render json: { error: "پارامتر ها را به صورت کامل بفرستید" } , status: 400
return
end
law = @current_user.our_laws.build(ourLawParams)
if law.save
render json: law , status: :ok
else
render json: law.errors , status: 404
end
end
# ============================= update
def update
law = OurLaw.last
if law.update(ourLawParams)
render json: law , status: :ok
else
render json: law.errors , status: 404
end
end
# ============================= delete
def delete
law = OurLaw.last
if law
if law.delete
render json: { is_deleted: "true" } , status: 200
else
render json: { is_deleted: "false" , reason: law.errors } , status: 400
end
else
render json: { error: "قوانین مورد نظر یافت نشد" } , status: 404
end
end
# ============================= private methods
private
def ourLawParams
params.permit(:title , :description)
end
end
<file_sep>class SocialEvent < ApplicationRecord
mount_base64_uploader :photo , SocialEventPhotoUploader
validates_presence_of :title , :description , :price , :is_available , :capacity , :social_event_category_id , :social_event_type_id
has_one :social_event_category
has_one :social_event_type
belongs_to :user
end
<file_sep>class Event < ApplicationRecord
mount_base64_uploader :photo , PersonalEventUploaderUploader
# =========================== validations
validates_presence_of :event_type , :title , :date , :location_lat , :location_long , :address , :repeat_time , :notification_time , :end_of_repeat , :start_time , :end_time , :is_private , :is_private , :is_verified
# =========================== enums
enum event_type: [ :personal , :surprise , :party , :meeting , :social]
# enum color: [ :red , :blue , :purple , :cyan , :orange ]
enum repeat_time: [ :no_repeat , :every_day , :every_week , :every_month , :every_three_month , :every_six_month , :every_year ]
enum notification_time: [ :no_notification , :five_min_before , :fifteen_min_before , :thirty_min_before , :one_hour_before , :two_hour_before , :one_day_before , :three_day_before]
# =========================== relations
# ============== one to one
has_one :party, :dependent => :destroy
has_one :surprise, :dependent => :destroy
has_one :meeting , :dependent => :destroy
has_one :user_color_event
# ============== one to many
belongs_to :user , :dependent => :destroy
has_many :share_events , :dependent => :destroy
# ============== many to many
# event and groups
has_many :groups , :through => "event_groups" , :foreign_key => "group_id"
has_many :event_group
# event and types
has_many :types , :through => "event_types" , :foreign_key => "type_id"
has_many :event_types
# event and share event
has_many :share_events , :through => "event_share_events" , :foreign_key => "share_event_id"
has_many :event_share_events
end
<file_sep>class AddPhotoToSocialEvent < ActiveRecord::Migration[5.2]
def change
add_column :social_events , :photo , :string , null: true
end
end
<file_sep>class SocialEventType < ApplicationRecord
validates :title , presence: true
# ============== one to many
belongs_to :social_event_category
end
<file_sep>class V1::OffDayController < ApplicationController
before_action :authenticate_request_user
skip_before_action :authenticate_request_user , :only => []
load_and_authorize_resource
# ============================ can can
rescue_from CanCan::AccessDenied do | exception |
render json: { alert: exception.message }
end
# ============================ get all off day of a user
def offDayUser
page = params[:page] || 1
per = params[:per] || 5
render json: @current_user.off_days.page(page).per(per)
end
# ============================ userDayOfFromDateToDate
def offDayFromTo
# if start and end time sent
page = params[:page] || 1
per = params[:per] || 10
if params[ :from ] and params[ :to ]
day = @current_user.off_days.where( date: params[:from]..params[:to] ).order( "date" ).page(page).per(per)
render json: day , status: 302
else
render json: { message: "پارامتر ها را کامل پاس دهید" } , status: :not_found
end
end
# ============================ create off day
def create
# parameters are sent ?
unless params[:date]
render json: {message: " پارامتر ها به صورت کامل فرستاده نشده اند. "}, status: 402
return
end
# save off day
day = @current_user.off_days.build( offDayParams )
if day.save
render json: day , status: :ok
else
render json: { message: day.errors } , status: 400
end
end
# ============================ update off day
def update
day = @current_user.off_days.where( id: params[:id] ).last
if day
if day.update( offDayParams )
render json: { message: day } , status: 200
else
render json: { message: day.errors } , status: 400
end
else
render json: { message: " روز مورد نظر یافت نشد. " } , status: 404
end
end
# ============================ delete off day
def delete
day = OffDay.where( id: params[:id] ).last
if day.delete
render json: { message: " با موفقیت حذف شد " } , status: 200
else
render json: { message: day.errors }
end
end
# =========================== private methods
private
def offDayParams
params.permit( :date , :is_all_day , :start , :end )
end
end
<file_sep>class V1::Admin::OffDayController < ApplicationController
before_action :authenticate_request_admin
skip_before_action :authenticate_request_admin , :only => []
# ============================ can can
load_and_authorize_resource
rescue_from CanCan::AccessDenied do | exception |
render json: { alert: exception.message }
end
# ============================ index
def index
off_day = OffDay.where( user_id: params[:user_id] ).order( "updated_at DESC" ).page( params[:page] || 1 ).per( params[:per] || 10 )
if User.where( id: params[:user_id] ).last
if off_day
render json: off_day , status: 200
else
render json: { error: " روز مورد نظر پیدا نشد " } , status: 404
end
else
render json: { error: " متاسفانه کاربر مورد نظر پیدا نشد " } , status: 404
end
end
# ============================ show
def show
off_day = OffDay.where( user_id: params[:user_id] ).where( id: params[:id] ).last
if User.where( id: params[:user_id] ).last
if off_day
render json: off_day , status: 200
else
render json: { error: " روز مورد نظر پیدا نشد " }, status: 404
end
else
render json: { error: " کاربر مورد نظر پیدا نشد " }, status: 404
end
end
# ============================ delete
def delete
off_day = OffDay.where( user_id: params[:user_id] ).where( id: params[:id] ).last
if User.where( id: params[:user_id] ).last
if off_day.destroy
render json: { success: " روز مورد نظر پاک شد " } , status: 200
else
render json: { error: " روز مورد نظر پیدا نشد " } , status: 404
end
else
render json: { error: " کاربر مورد نظر پیدا نشد " } , status: 404
end
end
# ============================ update
def update
off_day = OffDay.where( user_id: params[:user_id] ).where( id: params[:id] ).last
if User.where( id: params[:user_id] ).last
if off_day.update(updateParams)
render json: off_day , status: 200
else
render json: { error: " روز مورد نظر پیدا نشد " } , status: 404
end
else
render json: { error: " کاربر مورد نظر پیدا نشد " } , status: 404
end
end
# =========================== private for controller
private
# =========================== parameters that admin can update
def updateParams
params.permit( :date, :description )
end
end
<file_sep>class V1::Admin::SocialEventCategoryController < ApplicationController
before_action :authenticate_request_admin
skip_before_action :authenticate_request_admin , :only => []
# ============================ can can
load_and_authorize_resource
rescue_from CanCan::AccessDenied do | exception |
render json: { alert: exception.message }
end
# ============================ create method
def create
socialEvent = SocialEventCategory.new(socialEventParams)
if socialEvent.save
render json: socialEvent , status: 200
else
render json: socialEvent.errors , status:422
end
end
# ============================ index
def getAll
render json: SocialEventCategory.all
end
# ============================ update
def update
if params[:id]
socialEventCategory = SocialEventCategory.where(id: params[:id]).first
if socialEventCategory.update(socialEventParams)
render json: socialEventCategory , status: 200
else
render json: socialEventCategory.errors , status: 404
end
else
render json: {message: "send id."} , status: 422
end
end
# ============================ delete
def delete
if params[:id]
socialEventCategory = SocialEventCategory.where(id: params[:id]).first
if socialEventCategory.delete
render json: { message: "successfully deleted"} , status: 200
else
render json: socialEventCategory.errors , status: 404
end
else
render json: {message: "send social event id."} , status: 422
end
end
# ============================ private
def socialEventParams
params.permit(:title)
end
end
<file_sep>class V1::EventController < ApplicationController
before_action :authenticate_request_user
load_and_authorize_resource
# ============================ can can
rescue_from CanCan::AccessDenied do | exception |
render json: { alert: exception.message }
end
# =========================== here we create personal events
def personalEventCreate
personalEvent = @current_user.event.build( personalEventParams )
personalEvent.event_type = "personal"
personalEvent.is_private = true
personalEvent.is_verified = true
if params[:start_time] > params[:end_time]
render json: {messsage: "تاریخ شروع بزرگتر از تاریخ پایان است"}
else
if personalEvent.save
render json: personalEvent , status: 200
else
render json: personalEvent.errors , status: 400
end
end
end
# ========================= get all of user personal event
def getAllPersonalEvent
page = params[:page] || 1
per = params[:per] || 10
render json: @current_user.event.where( event_type: "personal" ).page(page).per(per) , status: :ok
end
# ========================= get a month of user personal event
def getMonthPersonalEvent
if params[:start_time] and params[:end_time]
render json: @current_user.event.where( event_type: "personal" ).where( date: params[:start_time]..params[:end_time] ).order("date").all , status: 200
return
else
render json: { message: "اطلاعات را یه صورت کامل پاس دهید" }, status: 422
end
end
# ======================== personal event update
def eventChange
if params[:id]
@personalEvent = @current_user.event.where(id: params[:id]).first
if @personalEvent
if @personalEvent.update(personalEventParams)
render json: @personalEvent , status: 200
else
render json: @personalEvent.errors , status: 400
end
else
render json: @personalEvent.errors , status: 404
end
else
render json: { message: "پارامتر ها را به صورت کامل ارسال کنید" } , status: 422
end
end
# ========================== personal evenet delete
def personalEventDelete
if params[:id]
personalEvent = @current_user.event.where( id: params[:id]).first
if personalEvent
if personalEvent.delete
render json: { message: "حذف شد"} , status: :ok
return
else
render json: personalEvent.errors , status: 400
return
end
else
render json: { message: "برنامه شما پیدا نشد" } , status: 404
return
end
else
render json: { message: "پارامتر ها را به صورت کامل ارسال کنید" } , status: 422
return
end
end
# ========================== get only one event
def getOnePersonalEvent
if params[:id]
render json: @current_user.event.where( id: params[:id]).where(event_type: "personal" ).first , status: 200
else
render json: { message: "پارامتر ها را به صورت کامل ارسال کنید" } , status: 422
end
end
# ======================== get today event
def getTodayPersonalEvent
render json: @current_user.event.where( date: Time.now.strftime('%F') ).all , status: 200
end
# private parts for initial what we want
private
def personalEventParams
params.permit( :date , :title , :description , :location_lat , :location_long , :address , :start_time , :end_time , :repeat_time , :notification_time , :end_of_repeat , :is_private , :is_verified , :photo)
end
end
<file_sep>class NationalEventSerializer < ActiveModel::Serializer
attributes :id , :date , :is_day_off , :title , :description
end
<file_sep>class CreateSocialEvents < ActiveRecord::Migration[5.2]
def change
create_table :social_events, id: :uuid do |t|
t.references :users , type: :uuid , null: false , index: true ,foreign_key: { on_delete: :cascade , on_update: :cascade }
t.string :title , null: false
t.string :description
t.references :social_event_types , type: :uuid , null: true , index: true ,foreign_key: { on_delete: :cascade , on_update: :cascade }
t.references :social_event_categories , type: :uuid , null: true , index: true ,foreign_key: { on_delete: :cascade , on_update: :cascade }
t.integer :price , null: true
t.boolean :is_available , default:true
t.integer :capacity , null: true
t.boolean :is_accepted , default: false
t.timestamps
end
end
end
<file_sep>class CreateSocials < ActiveRecord::Migration[5.2]
def change
create_table :socials, id: :uuid do |t|
t.references :user , type: :uuid, null: false, index: true ,foreign_key: { on_delete: :cascade , on_update: :cascade }
t.integer :name , unique:true
t.string :link , unique:true
t.timestamps
end
end
end
<file_sep>module SSHKit
module Sudo
VERSION = "0.1.0"
end
end
<file_sep>module Capistrano
module Nginx
module Generators
class ConfigGenerator < Rails::Generators::Base
desc "Create local nginx configuration file for customization"
source_root File.expand_path('../templates', __FILE__)
def copy_template
copy_file "_nginx_conf.erb", "config/deploy/nginx_conf.erb"
end
end
end
end
end
<file_sep>class V1::LookupController < ApplicationController
def getLookup
lookups = Lookup.where(category: params[:category])
render json: lookups
end
end
<file_sep>class Party < ApplicationRecord
# =========================== validations
validates :theme , presence: true
validates :is_invite , presence: true
validates :number_of_along, presence: false
# validates_presence_of :theme , :is_invite
validates_associated :event
enum is_invite: [:false , :true]
# =========================== relations
# has_many :invites , :dependent => :destroy
belongs_to :event , :dependent => :destroy
has_many :user , :through => "party_user" , :foreign_key => "user_id"
has_many :party_user
end
<file_sep>class V1::SocialEventController < ApplicationController
before_action :authenticate_request_user
load_and_authorize_resource
# ============================ can can
rescue_from CanCan::AccessDenied do | exception |
render json: { alert: exception.message }
end
# ============================ social event create
def create
socialEvent = @current_user.social_event.build(socialEventParams)
socialEvent.is_accepted = false
if socialEvent.valid?
socialEvent.save
render json: socialEvent , status: 200
return
else
render json: socialEvent.errors , status: 422
return
end
end
# ============================== get all
def getAll
page = params[:page] || 1
per = params[:per] || 10
render json: @current_user.social_event.page(page).per(per) , status: 200
return
end
# ============================== get from time to time
def between
page = params[:page] || 1
per = params[:per] || 10
if params[:start_time] and params[:end_time]
socialEvent = @current_user.social_event.where(date: params[:start_time]..params[:end_time]).order("date").page(page).per(per)
if socialEvent
render json: socialEvent , status: 200
else
render json: { message: "social event not found"} , status: 404
end
else
render json: { message: "send start time and end time" } , status: 422
return
end
end
# ============================== update
def update
socialEvent = @current_user.social_event
if socialEvent
if socialEvent.update(socialEventParams)
socialEvent.is_accepted = false
render json: socialEvent , status: 200
else
render json: socialEvent.errors , status: 422
end
else
render json: socialEvent.errors , status: 422
return
end
end
# ============================= delete
def delete
socialEvent = @current_user.social_event.where(id: params[:id]).first
if socialEvent
if socialEvent.delete
render json: { message: "deleted "} , status: 200
return
else
render json: socialEvent.errors , status: 422
return
end
else
render json: { message: "social event not found"} , status: 404
return
end
end
# ============================== get one social event
def show
if params[:id]
socialEvent = @current_user.social_event.where(id: params[:id]).first
if socialEvent
render json: socialEvent , status: 200
return
else
render json: { message: "social event not found" } , status: 404
return
end
else
render json: { message: "send id of the social event" } , status: 422
return
end
# ============================== get today social event
def today
page = params[:page] || 1
per = params[:per] || 10
socialEvent = @current_user.social_event.where(date: Time.now.strftime('%F')).page(page).per(per)
render josn: socialEvent , status: 200
end
# ============================== privates
def socialEventParams
params.permit(:title , :description , :social_event_type_id , :social_event_category_id , :price , :is_available , :capacity , :photo)
end
end
<file_sep>class RenameColumnSocialEvent < ActiveRecord::Migration[5.2]
def change
rename_column :social_events , :social_event_types_id , :social_event_type_id
rename_column :social_events , :social_event_categories_id , :social_event_category_id
end
end
<file_sep>class Invite < ApplicationRecord
#======================= validation
validates_presence_of :number_of_along
# ======================= relations
# ======================= many to many
has_many :user , :dependent => :destroy
belongs_to :party
belongs_to :meeting
end
<file_sep># This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
users =
User.create(
[
first_name: "امیرحسین" ,
family_name: "جانی",
phone_number: "09334682529" ,
password_digest: <PASSWORD>" ,
sex: 0 ,
email: "<EMAIL>",
birthday: "2018-08-04",
role: 0,
is_private: true ,
verification_code: 1111 ,
verified: true ,
status: true ,
verification_code_sent_at: "2018-08-25 07:49:10.778897" ,
forget_password: false
]
) ,
User.create(
[
first_name: "احمد" ,
family_name: "آزاد" ,
phone_number: "09382782419" ,
email: "<EMAIL>" ,
password_digest: <PASSWORD>" ,
sex: 0 ,
birthday: "2018-08-04",
role: 1,
is_private: true ,
verification_code: 1111 ,
verified: true ,
status: true ,
verification_code_sent_at: "2018-08-25 07:49:10.778897" ,
forget_password: false
]
)
personalEvent =
Event.create(
[
user_id: User.first().id ,
event_type: "personal",
date: "2018-12-15T",
description: "<NAME> is here and coding",
title: "amir jani personal event",
location_lat: 35.689198,
location_long: 51.388973,
address: "sattarkhan",
start_time: "2018-12-15T08:59:37+00:00",
end_time: "2018-12-15T10:00:37+00:00",
repeat_time: "no_repeat",
notification_time: "no_notification",
end_of_repeat: "2018-12-15T11:00:37+00:00",
is_private: true,
is_verified: true,
photo: nil
]
)
colorEventUser =
UserColorEvent.create(
[
user_id: User.first().id,
event_type: 0,
event_color: 0
]),UserColorEvent.create(
[
user_id: User.first().id,
event_type: 1,
event_color: 1
]),UserColorEvent.create(
[
user_id: User.first().id,
event_type: 2,
event_color: 2
]),UserColorEvent.create(
[
user_id: User.first().id,
event_type: 3,
event_color: 3
]),UserColorEvent.create(
[
user_id: User.first().id,
event_type: 4,
event_color: 4
])
national_event = NationalEvent.create(
[
user_id: User.first().id,
date: "2018-12-29T" ,
title: "vafat e emam" ,
description: "emam rahmat dar in tarikh fot karde" ,
is_day_off: true
]),NationalEvent.create(
[
user_id: User.first().id,
date: "2018-12-30T" ,
title: "vafat e emam1" ,
description: "emam1 rahmat dar in tarikh fot karde" ,
is_day_off: false
]),NationalEvent.create(
[
user_id: User.first().id,
date: "2019-01-03T" ,
title: "vafat e emam3" ,
description: "emam3 rahmat dar in tarikh fot karde" ,
is_day_off: true
]),NationalEvent.create(
[
user_id: User.first().id,
date: "2019-01-07T" ,
title: "vafat e emam4" ,
description: "emam4 rahmat dar in tarikh fot karde" ,
is_day_off: true
])
socialEventCategory =
SocialEventCategory.create(
[
title: "cat 1"
]),SocialEventCategory.create(
[
title: "cat 2"
]),SocialEventCategory.create(
[
title: "cat 3"
]),SocialEventCategory.create(
[
title: "cat 4"
])
<file_sep>class V1::PersonalEventController < ApplicationController
#before_action :authenticate_request_user
#skip_before_action :authenticate_request_user, :except => []
#load_and_authorize_resource
# here we create personal events
def create
render json: "a" , status: 400
return
#personalEvent = @current_user.event.build( personalEventParams )
#if personalEvent.save
#render json: personalEvent , status: 200
#else
#render json: personalEvent.erros , status: 400
#end
end
# private parts for initial what we want
#private
#def personalEventParams
#params.permit( :type , :date , :title , :description , :location_lat , :location_long , :address , :start_time , :end_time , :repeat_time , :notification_time , :end_of_repeat , :is_private , :is_verified , :photo )
#end
end
<file_sep>class LookupSerializer < ActiveModel::Serializer
attributes :title, :code, :icon
end
<file_sep>class V1::NationalEventController < ApplicationController
before_action :authenticate_request_user
skip_before_action :authenticate_request_user, :only => []
load_and_authorize_resource
# ============================ can can
rescue_from CanCan::AccessDenied do | exception |
render json: { alert: exception.message }
end
# ============================ show today national event
def todayEvent
event = NationalEvent.where(date: Date.today ).all
if event
render json: event , status:200
else
render json: { error: "رویداد ملی ای پیدا نشد" } , status: 200
end
end
# ============================= events in month
def eventsInMonth
# if start and end time sent
if params[ :start ] and params[ :end ]
render json: NationalEvent.where( date: params[:start]..params[:end] ).order( "date" ).all , status: 302
else
render json: { error: "پارامتر ها را کامل پاس دهید" } , status: :not_found
end
end
end
<file_sep>class V1::PartyController < ApplicationController
before_action :authenticate_request_user
load_and_authorize_resource
# ============================ can can
rescue_from CanCan::AccessDenied do | exception |
render json: { alert: exception.message }
end
# =========================== create party event
def createParty
event = @current_user.event.build(eventParams)
event.event_type = "party"
event.is_private = true
event.is_verified = true
#1
if event.valid?
event.save
party = event.build_party(partyParams)
#2
if party.valid?
party.save
#3
if party.is_invite == "true" or party.is_invite == 1
#4
if params[:user_id]
ivitedUserToParty = party.party_user.build(partyUserParams)
#5
if ivitedUserToParty.save
render :json => {
:event => event.as_json(:except => [:created_at , :updated_at]) ,
:party => party.as_json(:except => [:created_at , :updated_at , :event_id]),
:ivitedUserToParty => ivitedUserToParty.as_json(:except => [:created_at , :updated_at , :party_id])
} , status: 200
return
#5
else
render json: ivitedUserToParty.errors , status:404
return
#5
end
#4
else
render json: { message: "send ids of users" }
return
#4
end
end
#3
if party.is_invite == "false" or party.is_invite == 0
render :json => {
:event => event.as_json(:except => [:created_at , :updated_at]) ,
:party => party.as_json(:except => [:created_at , :updated_at , :event_id])
} , status: 200
return
#3
else
render json: { message: "مشکلی پیش آمده است" } , status:422
return
#3
end
#2
else
render json: party.errors , status:422
return
#2
end
#1
else
render json: event.errors , status:422
return
#1
end
end
# =========================== get all of party event
def getAllPartyEvents
page = params[:page] || 1
per = params[:per] || 10
render :json => {
:event => @current_user.event.where( event_type: "party" ).page(page).per(per).as_json(:except => [:created_at , :updated_at] , include: {party: {include: :party_user}} )
} , status: 200
end
# ===================== get specified event
def getSpecifiedTimePartyEvent
#1
if params[:start_time] and params[:end_time]
event = @current_user.event.where( event_type: "party" ).where( date: params[:start_time]..params[:end_time] ).all
render :json => {
:event => event.as_json(:except => [:created_at , :updated_at] , include: {party: {include: :party_user}} )
} , status:200
#1
else
render json: { message: "پارامتر های شروع و پایان بازه را ارسال کنید" } , status: 422
#1
end
end
# ========================== update party events
def updateParty
# 1
if params[:id]
event = @current_user.event.where( id: params[:id] ).where( event_type: "party").first
# 2
if event
# 3
if event.update(eventParams)
party = event.party(partyParams)
invite = event.party.party_user(partyUserParams)
render :json => {
:event => event.as_json(:except => [:created_at , :updated_at]) ,
:party => party.as_json(:except => [:created_at , :updated_at]) ,
:invite => invite.as_json(:except => [:created_at , :updated_at])
} , status: 200
# 3
else
render json: event.errors , status: 422
# 3
end
# 2
else
render json: { message: " رویداد مورد نظر یافت نشد " } , status: 404
# 2
end
# 1
else
render json: { message: " پارامتر آیدی را ارسال کنید " } , status: 404
# 1
end
end
# ========================== delete
def deleteEvent
if params[:id]
party = Party.where(id: params[:id]).first.delete
render json: { message: "deleted successfully" } , status: 200
else
render json: { message: "pass id" } , status: 422
end
end
# =========================== get today event
def todayParty
event = @current_user.event.where(event_type: "party").where(date: Time.now.strftime('%F')).all
if event
render :json => {
:event => event.as_json(:except => [:created_at , :updated_at] , include: {party: {include: :party_user}} )
} , status: 200
else
render json: event.errors , status:400
end
end
# ======================= get one party
def getOneParty
#1
if params[:id]
party = Party.where(id: params[:id] ).first
render :json => {
:party => party.as_json(:except => [:created_at , :updated_at] , :include => [:event , :party_user] )
} , status:200
#1
else
render json: { message: "پارامتر های شروع و پایان بازه را ارسال کنید" } , status: 422
#1
end
end
#============================ private
private
def partyUserParams
params.permit(:user_id)
end
def eventParams
params.permit(:date , :title , :description , :location_lat , :location_long , :address , :start_time , :end_time , :repeat_time , :notification_time , :end_of_repeat , :is_private , :is_verified , :photo )
end
def partyParams
params.permit(:theme , :is_invite , :number_of_along)
end
end
<file_sep>class EventSerializer < ActiveModel::Serializer
attributes :id , :user_id , :event_type , :date , :title , :description , :location_lat , :location_long , :address , :start_time , :end_time , :repeat_time , :notification_time , :end_of_repeat , :is_private , :is_verified , :photo
# belongs_to :user_color_event
end
<file_sep># -*- encoding: utf-8 -*-
# stub: capistrano-nginx 1.0.0 ruby lib
Gem::Specification.new do |s|
s.name = "capistrano-nginx".freeze
s.version = "1.0.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["<NAME>".freeze, "<NAME>".freeze]
s.date = "2016-01-30"
s.description = "Simple nginx management for Capistrano 3.x".freeze
s.email = ["<EMAIL>".freeze, "<EMAIL>".freeze]
s.homepage = "https://github.com/ivalkeen/capistrano-nginx".freeze
s.licenses = ["MIT".freeze]
s.rubygems_version = "2.7.6".freeze
s.summary = "Simple nginx management for Capistrano 3.x".freeze
s.installed_by_version = "2.7.6" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<capistrano>.freeze, ["~> 3.1"])
s.add_development_dependency(%q<bundler>.freeze, ["~> 1.3"])
s.add_development_dependency(%q<rake>.freeze, [">= 0"])
else
s.add_dependency(%q<capistrano>.freeze, ["~> 3.1"])
s.add_dependency(%q<bundler>.freeze, ["~> 1.3"])
s.add_dependency(%q<rake>.freeze, [">= 0"])
end
else
s.add_dependency(%q<capistrano>.freeze, ["~> 3.1"])
s.add_dependency(%q<bundler>.freeze, ["~> 1.3"])
s.add_dependency(%q<rake>.freeze, [">= 0"])
end
end
<file_sep>class CreateSurpriseUsers < ActiveRecord::Migration[5.2]
def change
create_table :surprise_users, id: :uuid do |t|
t.references :user, type: :uuid, null: false, index: true ,foreign_key: { on_delete: :cascade , on_update: :cascade }
t.references :surprise, type: :uuid, null: false, index: true ,foreign_key: { on_delete: :cascade , on_update: :cascade }
t.timestamps
end
end
end
<file_sep>module SSHKit
module Sudo
module Backend
module Netssh
private
def execute_command!(cmd)
output.log_command_start(cmd)
cmd.started = true
exit_status = nil
with_ssh do |ssh|
ssh.open_channel do |chan|
chan.request_pty
chan.exec cmd.to_command do |_ch, _success|
chan.on_data do |ch, data|
cmd.on_stdout(ch, data)
output.log_command_data(cmd, :stdout, data)
end
chan.on_extended_data do |ch, _type, data|
cmd.on_stderr(ch, data)
output.log_command_data(cmd, :stderr, data)
end
chan.on_request("exit-status") do |_ch, data|
exit_status = data.read_long
end
#chan.on_request("exit-signal") do |ch, data|
# # TODO: This gets called if the program is killed by a signal
# # might also be a worthwhile thing to report
# exit_signal = data.read_string.to_i
# warn ">>> " + exit_signal.inspect
# output.log_command_killed(cmd, exit_signal)
#end
chan.on_open_failed do |_ch|
# TODO: What do do here?
# I think we should raise something
end
chan.on_process do |_ch|
# TODO: I don't know if this is useful
end
chan.on_eof do |_ch|
# TODO: chan sends EOF before the exit status has been
# writtend
end
end
chan.wait
end
ssh.loop
end
# Set exit_status and log the result upon completion
if exit_status
cmd.exit_status = exit_status
output.log_command_exit(cmd)
end
end
end
end
end
end
<file_sep>class ApplicationController < ActionController::API
# protect_from_forgery
# protect_from_forgery with: :null_session
before_action :set_headers
# before_action :authenticate_request_user
attr_reader :current_user
def set_headers
puts 'ApplicationController.set_headers'
if request.headers["HTTP_ORIGIN"]
headers['Access-Control-Allow-Origin'] = request.headers["HTTP_ORIGIN"]
headers['Access-Control-Expose-Headers'] = 'ETag'
headers['Access-Control-Allow-Methods'] = 'GET, POST, PATCH, PUT, DELETE, OPTIONS, HEAD'
headers['Access-Control-Allow-Headers'] = '*,x-requested-with,Content-Type,If-Modified-Since,If-None-Match,Auth-User-Token'
headers['Access-Control-Max-Age'] = '86400'
headers['Access-Control-Allow-Credentials'] = 'true'
end
end
def authenticate_request_user
@current_user = AuthorizeApiUser::call(request.headers).result
unless @current_user
render json: { error: "شما هنوز در سیستم ثبت نام نکرده اید !" }, status: 401
return
end
end
def authenticate_request_admin
@current_user = AuthorizeApiUser::call(request.headers).result
if @current_user.role != "admin"
render json: { error: "شما دسترسی به این آدرس ها را ندارید" }, status: 401
end
end
def nc_android_api_key
"<KEY>"
end
def nc_ios_api_key
""
end
def nc_web_api_key
""
end
helper_method :nc_android_api_key
helper_method :nc_ios_api_key
helper_method :nc_web_api_key
end
<file_sep>class CreateSurprises < ActiveRecord::Migration[5.2]
def change
create_table :surprises, id: :uuid do |t|
t.references :event, type: :uuid, null: false, index: true ,foreign_key: { on_delete: :cascade , on_update: :cascade }
t.string :fake_title
t.string :fake_description
t.string :theme
t.integer :is_invite , null: false , default: true
t.integer :number_of_along , null: true
t.integer :user_to_surprise_id , type: :uuid , null: false
t.timestamps
end
end
end
<file_sep>class PartyUser < ApplicationRecord
belongs_to :party
belongs_to :user
end
<file_sep>class V1::Admin::SocialEventTypeController < ApplicationController
before_action :authenticate_request_admin
skip_before_action :authenticate_request_admin , :only => []
# ============================ can can
load_and_authorize_resource
rescue_from CanCan::AccessDenied do | exception |
render json: { alert: exception.message }
end
# ============================ create
def create
if params[:social_event_category_id]
socialEventCategory = SocialEventCategory.where(id: params[:social_event_category_id]).first
if socialEventCategory
socialEventType = socialEventCategory.social_event_type.build(socialEventTypeParams)
if socialEventType.save
render json: socialEventType , status:200
else
render json: socialEventType.errors , status:422
end
else
render json: { message: "social event category not found."} , status: 404
end
else
render json: { message: "send social event category id." } , status: 422
end
end
# ============================ get all category's type
def categoryType
if params[:social_event_category_id]
socialEventCategory = SocialEventCategory.where(id: params[:social_event_category_id]).first
if socialEventCategory
render json: socialEventCategory.social_event_type , status: 200
else
render json: { message: "social event category not found."} , status: 404
end
else
render json: { message: "send social event category id." } , status: 422
end
end
# ============================ delete a type
def delete
if params[:social_event_type_id]
socialEventType = SocialEventType.where(id: params[:social_event_type_id]).first
if socialEventType.delete
render json: { message: "deleted successfully." } , status: 200
else
render json: socialEventType.errors , status: 422
end
else
render json: { message: "send social event type id." } , status: 422
end
end
# ============================ update
def update
if params[:social_event_type_id]
socialEventType = SocialEventType.where(id: params[:social_event_type_id]).first
if socialEventType.update(socialEventTypeParams)
render json: socialEventType , status: 200
else
render json: socialEventType.errors , status: 422
end
else
render json: { message: "send social event type id." } , status: 422
end
end
# ============================ private
private
def socialEventTypeParams
params.permit(:social_event_category_id , :title)
end
end
<file_sep>class Meeting < ApplicationRecord
validates_presence_of :priority , :is_invite
enum priority: [:instant , :important , :normal ]
enum is_invite: [:false , :true]
#has_many :invites , :dependent => :destroy
belongs_to :event
has_many :user , :through => "meeting_user" , :foreign_key => "user_id"
has_many :meeting_user
end
<file_sep>class V1::ShakeController < ApplicationController
before_action :authenticate_request_user
def make
near_event = Event.where('
is_private = false
AND earth_box(ll_to_earth(?, ?), 5/1.609*1000)
@> ll_to_earth(location_lat, location_long)',params[:lat],params[:lng]).order("RANDOM()").first
render json: near_event
end
end
<file_sep>class V1::TypeForUserController < ApplicationController
before_action :authenticate_request_user
skip_before_action :authenticate_request_user, :only => []
# load_and_authorize_resource
# ============================ can can
rescue_from CanCan::AccessDenied do | exception |
render json: { alert: exception.message }
end
# ============================= get user type
def getUserTypes
types = []
@current_user.user_types.each do |type|
if type.type.is_verified
types.push(type.type)
end
end
render json: { type: types }
end
# ============================= find user type
def find
if params[:id]
type = Type.where( id: params[:id] ).where( is_verified: true ).last
if type
render json: { type: type } , status: 200
else
render json: { error: " اطلاعات مورد نظر پیدا نشد یا هنوز تایید نشده است " } , status: 404
end
end
if params[:title]
type = Type.where( title: params[:title] ).where( is_verified: true ).last
if type
if type.user_types.last.user_id == @current_user.id
render json: { type: type } , status: 200
else
render json: { error: " شما مجاز به انجام این کار نیستید " } , status: 403
end
else
render json: { error: " اطلاعات مورد نظر شما پیدا نشد! " } , status: 404
end
end
end
# ============================ create user type
def create
# parameters are sent ?
if not params[:title] and not params[:color]
render json:{ error: "رنگ یا عنوان را وارد کنید !" } , status: 402
end
type = Type.new(createTypeParams)
if type.save
@current_user.user_types.new( type_id: type.id , user_id: @current_user.id ).save
render json: { success: type } , status: :ok
else
render json: { error: type.errors } , status: 400
end
end
# ============================ user type update
def update
type = @current_user.user_types.where( user_id: @current_user.id ).where( type_id: params[:id] ).last.type
if type
type.is_verified = false
if type.update(createTypeParams)
render json: { success: type } , status: 200
return
else
render json: { error: " مشکلی در به روز رسانی به وجود آمده است ! " } , status: 400
end
else
render json: { error: " اطلاعات مورد نظر یافت نشد ! " } , status: 404
end
end
# ============================ user type delete
def delete
type = Type.where( id: params[:id] ).last
if type
if type.delete
render json: { success: " با موفقیت حذف شد " } , status: 200
else
render json: { error: " مشکلی در حذف کردن به وجود آمده است ! " } , status: 400
end
else
render json: { error: " اطلاعات مورد نظر یافت نشد ! " } , status: 404
end
end
# ============================ privates for controller
private
# ============================ parameters for creating and updating
def createTypeParams
params.permit( :title , :description , :color , :is_verified)
end
end
<file_sep>class V1::GroupsController < ApplicationController
before_action :authenticate_request_user
def createGroup
validate_parameters
group = Group.new(group_params)
group.owner = @current_user.id
group.save
if params[:members]
params[:members].each do |m|
user = User.where(id: m).last
if user
group.users << user
end
end
end
render json: group, status: 201
end
def getGroups
groups = @current_user.groups
render json: groups
end
def updateGroup
members = []
group = Group.where(owner: @current_user.id).find(params[:id])
if group.update(group_params)
group.admins = params[:admins]
group.save
category = Lookup.where(category: "group_type",code: group.category).last
group.users.each do |u|
is_owner = group.owner == u.id ? true : false
is_admin = (group.admins.include? "#{u.id}") ? true : false
object = {
id: u.id,
name: "#{u.first_name} #{u.family_name}",
photo: u.photo,
is_owner: is_owner,
is_admin: is_admin
}
members.push(object)
end
render json: group.attributes.merge(members: members,category_name: category.title,category_icon: category.icon,phto: group.photo)
end
end
def getGroup
members = []
group = Group.find(params[:id])
category = Lookup.where(category: "group_type",code: group.category).last
group.users.each do |u|
is_owner = group.owner == u.id ? true : false
is_admin = (group.admins ? ((group.admins.include? "#{u.id}") ? true : false) : false)
object = {
id: u.id,
name: "#{u.first_name} #{u.family_name}",
photo: u.photo,
is_owner: is_owner,
is_admin: is_admin
}
members.push(object)
end
render json: group.attributes.merge(members: members,category_name: category.title,category_icon: category.icon,photo: group.photo)
end
private
def group_params
params.permit(:name,:description,:link,:is_private,:photo,:category,:admins=>[])
end
def validate_parameters
true
end
end
<file_sep>class AuthenticateUser
# A simple, standardized way to build and use Service Objects (aka Commands) in Ruby
prepend SimpleCommand
# initialize user with phone number and password
def initialize(phone_number , password)
@phone_number = phone_number
@password = <PASSWORD>
end
# encode user id
def call
encode( user_id: user.id ) if user
end
private
attr_accessor :phone_number, :password
# define user
def user
user = User.find_by(phone_number: phone_number)
return user if user && user.authenticate(password)
errors.add :user_authentication, 'invalid credentials'
nil
end
# define encode
def encode(payload, exp = 5.month.from_now)
payload[:exp] = exp.to_i
JWT.encode(payload, Rails.application.secrets.secret_key_base)
end
#define decode
def decode(token)
body = JWT.decode(token, Rails.application.secrets.secret_key_base)[0]
HashWithIndifferentAccess.new body
rescue
nil
end
end<file_sep>class Surprise < ApplicationRecord
# validation
validates_presence_of :fake_title , :fake_description , :theme , :user_to_surprise_id , :is_invite
# =================== relations
enum is_invite: [:true , :false]
# ============ one to many
# event and surprise
belongs_to :event
# ============ many to many
has_many :user , :through => "surprise_user" , :foreign_key => "user_id"
has_many :surprise_user
end
<file_sep>class CreateEvents < ActiveRecord::Migration[5.2]
def change
create_table :events, id: :uuid do |t|
t.references :user , type: :uuid , null: false , index: true ,foreign_key: { on_delete: :cascade , on_update: :cascade }
t.integer :event_type , null: false
t.date :date , null: false
t.string :title , null: false
t.string :description , null: true
# t.string :location_name , null: false
t.float :location_lat , null: false
t.float :location_long , null: false
t.string :address , null: false
t.datetime :start_time , null: false
t.datetime :end_time , null: false
t.integer :repeat_time , null: false
t.integer :notification_time , null: false
t.datetime :end_of_repeat , null: false
t.boolean :is_private , default: true
t.boolean :is_verified , null: true
t.string :photo , null: true
t.timestamps
end
end
end
<file_sep>class GroupSerializer < ActiveModel::Serializer
attributes :id, :name, :description, :is_private, :link, :photo, :admins
end
<file_sep>class AddNcAuthorizationKeysToUsers < ActiveRecord::Migration[5.2]
def change
remove_column :users, :nc_authorization_key
add_column :users, :nc_android_authorization_key, :string
add_column :users, :nc_ios_authorization_key, :string
add_column :users, :nc_web_authorization_key, :string
end
end
|
fafd394d557aca1a1f5f93daf5e794e80137da18
|
[
"Markdown",
"Ruby"
] | 79
|
Markdown
|
amirjani/sitomeet
|
4fb19580b737d76c28b9e7cd206c0909298f2bde
|
fcb406e3d897da7aa4a812e44b98cc10ec033dd7
|
refs/heads/master
|
<file_sep>#include <xc.h>
#include <pic18f4321.h>
#include <stddef.h>
unsigned char input();
void initialization();
void output(unsigned char);
void calculate(char);
unsigned char decoder[10] = {
0x7E, 0x30,
0x6D, 0x79,
0x33, 0x5B,
0x5F, 0x70,
0x7F, 0x73 };
unsigned char message;
void initialization()
{
TXSTA = 0x24;
SPBRG = 103;
ADCON1 = 0x0F;
TRISCbits.RC7 = 1;
TRISCbits.RC6 = 0;
TRISA = 0;
TRISD = 0;
RCSTA =0x90;
}
unsigned char input()
{
if(PIRbits.RC1IF)
{
return RCREG1;
}
else
{
return 0;
}
}
void output(unsigned char input)
{
while(!PIRbits.TX1IF);
TXREG1 = input;
}
void calculate(char data)
{
unsigned char ten, one;
ten = data / 10;
one = data % 10;
PORTA = decoder[ten];
PORTD = decoder[one];
}
void main(void)
{
initialization();
while(1)
{
message = input(); //receive data from serial
calculate(message);
output(72); // send data to serial comm
}
return;
}<file_sep># Microcontroller work with PIC18
<file_sep>#include <xc.h>
#include <p18f4321.h>
#pragma config OSC = INTIO2
#pragma config WDT = OFF
#pragma config LVP = OFF
#pragma config BOR = OFF
unsigned char ctrl[3], data[3];
unsigned char SPI(unsigned char);
void initialization()
{
for(unsigned char i = 0; i < 3; i++){
data[i] = 0;
ctrl[0] = 1;
ctrl[1] = 2;
ctrl[2] = 4;
OSCCONbits.IRCF1 = 1;
OSCCONbits.IRCF0 = 1; // Select the 8MHz freq
}
// Port Configurations
// all PORTC bits are output, except PC4, SDI, input
TRISC = 0x10;
// TRISCbits.TRISC4 = 1; // except SDI input
ADCON1 = 0X0F
// configure SPI
SSPSTAT = 0x40;
SSPADD = 0;
// enable SPI, idle low, and Fosc / 16
SSPCON1 = 0x21;
// configure TMR0
// Timer0, 16-bit mode, prescaler = 1/4
T0CON = 0x01;
TMR0H = 0x0B;
TMR0L = 0xDC;
T0CONBbits.TMR0ON = 1; // turn on the timer
INTCONbits.TMR0IF = 0; // clear the flag
}
unsigned char SPI(unsigned char message)
{
SSPBUF = message;
while(!SSPSTATbits.BF); // wait for transmission completion
return SSPBUF;
}
unsigned char dataSPI;
unsigned int select;
void output()
{
// select waveform
select = 2;
switch(select){
case 0:
PORTCbits.RC2 = 0;
dataSPI = 0x30 + (data[0]>>4);
SPI(dataSPI);
dataSPI = (data[0]<<4);
SPI(dataSPI);
PORTCbits.RC2 = 1;
break;
case 1:
PORTCbits.RC2 = 0;
dataSPI = 0x30 + (data[1]>>4);
SPI(dataSPI);
dataSPI = (data[1]<<4)
SPI(dataSPI);
PORTCbits.RC2 = 1;
break;
case 2:
PORTCbits.RC2 = 0;
dataSPI = 0x30 + (data[2]>>4);
SPI(dataSPI);
dataSPI = (data[2]<<4);
SPI(dataSPI)
PORTCbits.RC2 = 1;
break;
}
}
void calculate()
{
unsigned char sineTable[64] = {128 ,
140 , 152 , 165 , 176 , 188 , 199 , 209 , 218 ,
226 , 234 , 240 , 246 , 250 , 253 , 255 , 255 ,
255 , 253 , 250 , 246 , 240 , 234 , 226 , 218 ,
209 , 199 , 188 , 176 , 165 , 152 , 140 , 128 ,
115 , 103 , 90 , 79 , 67 , 56 , 46 , 37 ,
29 , 21 , 15 , 9 , 5 , 2 , 0 , 0 ,
0 , 2 , 5 , 9 , 15 , 21 , 29 , 37 ,
46 , 56 , 67 , 79 , 90 , 103 , 115};
//channel A sawtooth
data[0]=data[0]+1; //increment th
//channel B triangular
if(data[0] >=128)
data[1] = data[1] -2;
else
data[1] = data[1] +2;
//channel C
data[2] = sineTable[data[0]%64];
}
void input()
{}
void main()
{
initialization();
while(1)
{
input();
calculate();
output();
}
}
|
ed3542152336dab2f320ca6cabbfad8987d21b1e
|
[
"Markdown",
"C"
] | 3
|
C
|
Jestr117/mcu_work
|
7ba6c286840ac4bf77476cbb26e0b13158aa7ea6
|
ae1e7428a772492804d1ccf028e83a0bcf601dfd
|
refs/heads/master
|
<file_sep>/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
import React from 'react';
import PropTypes from 'prop-types';
import {
Col,
Collapse,
DropdownButton,
Label,
MenuItem,
OverlayTrigger,
Row,
Tooltip,
Well,
} from 'react-bootstrap';
import { t } from '@superset-ui/translation';
import ControlHeader from '../ControlHeader';
import ColumnOption from '../../../components/ColumnOption';
import MetricOption from '../../../components/MetricOption';
import DatasourceModal from '../../../datasource/DatasourceModal';
import ChangeDatasourceModal from '../../../datasource/ChangeDatasourceModal';
import TooltipWrapper from '../../../components/TooltipWrapper';
import Button from '../../../components/Button';
import './DatasourceControl.css';
const propTypes = {
onChange: PropTypes.func,
value: PropTypes.string,
datasource: PropTypes.object.isRequired,
};
const defaultProps = {
onChange: () => {},
onDatasourceSave: () => {},
value: null,
};
class DatasourceAggControl extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
showEditDatasourceModal: false,
showChangeDatasourceModal: false,
menuExpanded: false,
};
this.toggleChangeDatasourceModal = this.toggleChangeDatasourceModal.bind(this);
this.toggleEditDatasourceModal = this.toggleEditDatasourceModal.bind(this);
this.toggleShowDatasource = this.toggleShowDatasource.bind(this);
this.renderDatasource = this.renderDatasource.bind(this);
}
toggleShowDatasource() {
this.setState(({ showDatasource }) => ({ showDatasource: !showDatasource }));
}
toggleChangeDatasourceModal() {
this.setState(({ showChangeDatasourceModal }) => ({
showChangeDatasourceModal: !showChangeDatasourceModal,
}));
}
toggleEditDatasourceModal() {
this.setState(({ showEditDatasourceModal }) => ({
showEditDatasourceModal: !showEditDatasourceModal,
}));
}
renderDatasource() {
const datasource = this.props.datasource;
return (
<div className="m-t-10">
<Well className="m-t-0">
<div className="m-b-10">
<Label>
<i className="fa fa-database" /> {datasource.database.backend}
</Label>
{` ${datasource.database.name} `}
</div>
</Well>
</div>
);
}
render() {
const { showChangeDatasourceModal } = this.state;
const { datasource, onChange, onDatasourceSave, value } = this.props;
return (
<div>
<ControlHeader {...this.props} />
<div className="btn-group">
<Button
value={datasource.name}
className="label label-default label-btn m-r-5"
bsSize="lg"
id="datasource_menu"
>{datasource.name}</Button>
<TooltipWrapper
label="change-datasource"
tooltip={t('Click to change the datasource')}
>
<Button
onClick={this.toggleShowDatasource}
>
<i className="fa fa-table" /> select
</Button>
</TooltipWrapper>
</div>
<ChangeDatasourceModal
onDatasourceSave={onDatasourceSave}
onHide={this.toggleChangeDatasourceModal}
show={showChangeDatasourceModal}
onChange={onChange}
/>
</div>
);
}
}
DatasourceAggControl.propTypes = propTypes;
DatasourceAggControl.defaultProps = defaultProps;
export default DatasourceAggControl;
|
ace3a689d61caabbead8c2a1d387fa57cd9e8357
|
[
"JavaScript"
] | 1
|
JavaScript
|
zheng1040/hello-world
|
f035183350312d3d6ffe5ed4ca862a5e8f6c1a84
|
741225ae3a008afbea72a77acc1d7e43db999314
|
refs/heads/master
|
<repo_name>michalklim/schibsted-recru-task<file_sep>/client/src/sections/Home/index.ts
export { HomeSection } from './Home.section'
<file_sep>/client/src/sections/Search/index.ts
export { SearchSection } from './Search.section'
<file_sep>/server/src/items/items.router.ts
import { Router } from 'express'
import * as controllers from './items.controllers'
export const itemsRouter = Router()
// /api/items
itemsRouter.route('/').get(controllers.getMany)
<file_sep>/client/webpack.production.js
const path = require('path')
const webpackBaseConfig = require('../webpack.base')
const webpackBaseClientConfig = require('./webpack.client.base')
const merge = require('webpack-merge')
module.exports = () =>
merge(
{
mode: 'production',
output: {
path: path.resolve('dist', 'client'),
},
},
webpackBaseClientConfig,
webpackBaseConfig(__dirname, true),
)
<file_sep>/server/src/items/index.ts
export { itemsRouter } from './items.router'
<file_sep>/server/src/services/giphyService/index.ts
import { GifsResult, GiphyFetch, SearchOptions } from '@giphy/js-fetch-api'
import { ITEMS_PER_PAGE } from '../../common/constants'
import { Item } from '../../common/types'
const gf = new GiphyFetch(process.env.GIPHY_TOKEN || '')
const shapeResponse = (res: GifsResult): Item[] => {
return res.data.map((item) => ({
type: 'gif',
id: `${item.id}`,
image: {
src: item.images.original.url,
size: {
height: item.images.original.height,
width: item.images.original.width,
},
},
preview: {
src: item.images.preview_gif.url,
size: {
height: item.images.preview_gif.height,
width: item.images.preview_gif.width,
},
},
previewStatic: {
src: item.images.preview.url,
size: {
height: item.images.preview.height,
width: item.images.preview.width,
},
},
}))
}
export const fetchItems = async (term: string, page = 1, options?: SearchOptions): Promise<Item[]> => {
const DEFAULT_OPTIONS: SearchOptions = {
limit: ITEMS_PER_PAGE,
offset: ITEMS_PER_PAGE * (page - 1),
type: 'gifs',
}
const searchOptions = {
...DEFAULT_OPTIONS,
...options,
}
const searchRes = await gf.search(term, searchOptions)
return shapeResponse(searchRes)
}
<file_sep>/client/src/services/getItems/getItems.service.ts
import fetch from 'isomorphic-fetch'
import qs from 'querystring'
import { Item } from 'server/common/types'
export const getItems = async (term: string, page: number): Promise<Item[]> => {
const params = {
term,
page,
}
const baseUrl = `${process.env.CONTEXT ? '/.netlify/functions/index' : ''}`
const response = await fetch(`${baseUrl}/api/items?${qs.stringify(params)}`)
const json = await response.json()
return json
}
<file_sep>/server/src/server.ts
import express from 'express'
import es6promise from 'es6-promise'
import 'isomorphic-fetch'
import cors from 'cors'
import morgan from 'morgan'
import { itemsRouter } from './items'
import serverless from 'serverless-http'
es6promise.polyfill()
const app = express()
app.disable('x-powered-by')
const morganFormat = process.env.CONTEXT === 'production' ? 'tiny' : 'dev'
app.use(morgan(morganFormat))
app.use(
cors({
origin: process.env.URL,
}),
)
app.use('/api/items', itemsRouter)
export { app }
export const handler = serverless(app, {
basePath: '/.netlify/functions/index',
})
<file_sep>/server/webpack.production.js
const pkg = require('../package.json')
const path = require('path')
const webpackBaseConfig = require('../webpack.base')
const merge = require('webpack-merge')
module.exports = () =>
merge(
{
mode: 'production',
target: 'node',
devtool: 'source-map',
entry: path.resolve(__dirname, 'src', 'server.ts'),
output: {
path: path.resolve('dist', 'server'),
filename: 'index.js',
libraryTarget: 'umd',
library: pkg.name + '-backend',
},
},
webpackBaseConfig(__dirname, true),
)
<file_sep>/client/src/theme.ts
import { DefaultTheme } from 'styled-components'
import { modularScale } from 'polished'
export const appTheme: DefaultTheme = {
colors: {
primary: '#000000',
secondary: '#FFFFFF',
},
layers: {
top: 1000,
middle: 500,
bottom: 100,
},
typo: {
primaryFont: 'Montserrat, sans-serif',
secondaryFont: 'Open Sans, sans-serif',
},
ms: (step) => modularScale(step, '1rem', 'majorSecond'),
breakpoints: {
mobileM: '(min-width: 375px)',
tablet: '(min-width: 768px)',
desktop: '(min-width: 1024px)',
desktopL: '(min-width: 1440px)',
},
}
<file_sep>/client/src/styled.d.ts
import 'styled-components'
declare module 'styled-components' {
export interface DefaultTheme {
colors: {
primary: string
secondary: string
}
layers: {
top: number
middle: number
bottom: number
}
typo: {
primaryFont: string
secondaryFont: string
}
ms: (step: number) => string
breakpoints: {
mobileM: string
tablet: string
desktop: string
desktopL: string
}
}
}
<file_sep>/.env.example
URL=http://localhost:3000
GIPHY_TOKEN=<PASSWORD>
PIXABAY_TOKEN=<PASSWORD>
NODE_ENV=development<file_sep>/client/src/components/SearchForm/index.ts
export { SearchForm } from './SearchForm.component'
<file_sep>/webpack.base.js
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const Dotenv = require('dotenv-webpack')
const webpack = require('webpack')
const path = require('path')
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin')
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin')
module.exports = (context, isProduction) => ({
module: {
rules: [
{
test: /\.(ts|tsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
configFile: path.resolve(__dirname, 'babel.config.js'),
},
},
},
],
},
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx', '.json'],
plugins: [
new TsconfigPathsPlugin({
configFile: path.resolve(context, 'tsconfig.json'),
}),
],
},
plugins: [
new CleanWebpackPlugin(),
new webpack.ProgressPlugin(),
new Dotenv({
systemvars: true,
safe: path.resolve(__dirname, '.env.example'),
}),
new ForkTsCheckerWebpackPlugin({
eslint: true,
eslintOptions: {
emitError: isProduction,
},
tsconfig: path.resolve(context, 'tsconfig.json'),
async: !isProduction,
}),
],
})
<file_sep>/server/src/common/types.ts
export interface ImageResponse {
src: string
size: {
height: number
width: number
}
}
export interface Item {
type: 'photo' | 'gif'
id: string
image: ImageResponse
preview: ImageResponse
previewStatic: ImageResponse
}
<file_sep>/server/src/services/pixabayService/index.ts
import fetch from 'isomorphic-fetch'
import qs from 'querystring'
import { ITEMS_PER_PAGE } from '../../common/constants'
import { Item } from '../../common/types'
interface PixabayImage {
id: number
pageURL: string
type: string
tags: string
previewURL: string
previewWidth: number
previewHeight: number
webformatURL: string
webformatWidth: number
webformatHeight: number
largeImageURL: string
imageWidth: number
imageHeight: number
imageSize: number
views: number
downloads: number
favorites: number
likes: number
comments: number
user_id: number
user: string
userImageURL: string
}
interface PixabayResponse {
total: number
totalHits: number
hits: PixabayImage[]
}
const shapeResponse = (res: PixabayResponse): Item[] => {
return res.hits.map((item) => ({
type: 'photo',
id: `${item.id}`,
image: {
src: item.webformatURL,
size: {
width: item.webformatWidth,
height: item.webformatHeight,
},
},
previewStatic: {
src: item.previewURL,
size: {
width: item.previewWidth,
height: item.previewHeight,
},
},
preview: {
src: item.previewURL,
size: {
width: item.previewWidth,
height: item.previewHeight,
},
},
}))
}
export const fetchItems = async (term: string, page = 1, options?: {}): Promise<Item[]> => {
/* eslint-disable @typescript-eslint/camelcase */
const params = {
key: process.env.PIXABAY_TOKEN || '',
q: term,
image_type: 'photo',
per_page: ITEMS_PER_PAGE,
page,
...options,
}
/* eslint-enable @typescript-eslint/camelcase */
const response = await fetch(`https://pixabay.com/api?${qs.stringify(params)}`)
const json: PixabayResponse = await response.json()
return shapeResponse(json)
}
<file_sep>/client/src/services/getItems/index.ts
export { getItems } from './getItems.service'
<file_sep>/README.md
# Shibsted Recru App
Simple app that serves images from
[giphy](https://giphy.com/) and [pixabay](https://pixabay.com/) through
proxy node server that unifies their api response and serves it
to the client app. You can see current version o the app [here](https://suspicious-colden-0f383d.netlify.com/)
## Main stack
- [Typescript](https://www.typescriptlang.org/)
### Client
- [React](https://pl.reactjs.org/)
- [styled-components](https://styled-components.com/)
- [react-spring](https://www.react-spring.io/)
- [Reach router](https://reach.tech/router)
### Server
- [Express.js](https://expressjs.com/)
- [Morgan](https://www.npmjs.com/package/morgan)
- [Cors](https://www.npmjs.com/package/cors)
### Configuration
- [Babel](https://babeljs.io/)
- [Webpack](https://webpack.js.org/)
- [Eslint](https://eslint.org/)
- [Prettier](https://prettier.io/)
- [Commitlint](https://commitlint.js.org/#/)
## Usage
To run project in development mode you have to start both server and client app.
Note that you will need `.env` file in the root of the project. Please use `.env.example` for reference
Install all dependencies
```shell script
yarn
```
To start server app run:
```shell script
yarn dev:server
```
App should now be available on [http://localhost:3000](http://localhost:3000)
To start client run:
```shell script
yarn dev:client
```
App should now be available on [http://localhost:8080](http://localhost:8080)
To create server bundle run
```shell script
yarn build:server
```
To create client bundle:
```shell script
yarn build:client
```
Those commands will create `client` and `server` directory in `dist` directory.
Both of those are used by `prepare-deploy` which runs during CD after successful merge to `master` branch
Please note that both `build` commands run eslint and typescript check before actual bundling and
will fail if any of those checks produces and error
## Server
It is fairly standard express server with one exception. Express app is
additionally wrapped and exported with serverless hoc so it can be hosted
using lambda functions
## Client
Webpack dev is proxying every request to `/api` and reroutes it to `http://localhost:3000`
to omit cors policies in dev environment
## Additional configurations
- All packages will be installed with fixed version either using `npm` or `yarn`
- All commits are linted using [conventional commits spec](https://www.conventionalcommits.org/en/v1.0.0/). See `commitlint.config.js`
for the configuration
- A lot of webpack configurations are shared across project. See `webpack.base.js` for base configuration.
All others configuration are extending this one by using [webpack-merge](https://www.npmjs.com/package/webpack-merge)
- [Prettier](https://prettier.io/) will run on every commit to ensure that properly formatted code ends up in repo on every stage.
- If you don't have proper `.env` file you will get an error during webpack compilation. See `.env.example` for reference
## What could be done better (given bit more time 😉)
- Tests (my biggest pain here 🤕😭). I would use [Jest](https://jestjs.io/) for server and client app and
[@testing-library](https://testing-library.com/) for client
- Absolute imports in server app. Right now [ts-node-dev](https://www.npmjs.com/package/ts-node-dev) is used
to watch and recompile server app on change. I run into some issues when trying
to make it work together with [tsconfig-paths](https://www.npmjs.com/package/tsconfig-paths)
- Splitting app into smaller chunks. Right now it is one big bundle. I planned to use
`Suspense` together with `React.lazy` to optimize perf and user experience
- Optimizing images loading. Only one size of the images is used now. I would use smaller
versions of images on mobile breakpoints and use `webp` format with fallback. Also it would be nice to load static versions at the beginning
and then asynchronously load gifs
- Some tweaks to the animations, especially search introduction one
(second run gets you to search section but it doesn't animate)
- Unfortunately I left couple of `eslint-disable` comments. All of those are
due `plugin:react-hooks/recommended` configuration which I find useful in a lot of cases but on the other
hand I have bit trouble to achieve same logic in without much boilerplate other way around.
I have to give it more thought especially reading [this](https://github.com/facebook/react/issues/14920#issuecomment-471070149)
- A lot of smaller tweaks in the UI 😉
<file_sep>/server/src/items/items.controllers.ts
import shuffle from 'lodash/shuffle'
import { RequestHandler } from 'express'
import * as pixabayService from '../services/pixabayService'
import * as giphyService from '../services/giphyService'
export const getMany: RequestHandler = async (req, res) => {
const pixabayPromise = pixabayService.fetchItems(req.query.term, req.query.page)
const giphyPromise = giphyService.fetchItems(req.query.term, req.query.page)
const [pixabayRes, giphyRes] = await Promise.all([pixabayPromise, giphyPromise])
const results = shuffle([...pixabayRes, ...giphyRes])
return res.json(results)
}
|
7a69912fac722ee19a204386e44e95dee7e2df1b
|
[
"JavaScript",
"TypeScript",
"Markdown",
"Shell"
] | 19
|
TypeScript
|
michalklim/schibsted-recru-task
|
145a7e722277c9b0d41495723bd64382fef85012
|
e8642db1e133c24d558e75b17b43eb92eada8c14
|
refs/heads/master
|
<file_sep>import React, { Component } from 'react';
import './App.scss';
import TodoList from "./TodoList";
import ListsList from './ListsList'
import base from './base';
class App extends Component {
state = {
lists: {
deleted: {
listName: 'Deleted',
items: {}
},
default: {
listName: 'default',
items: {}
},
done: {
listName: 'DONE',
items: {}
}
},
currentList: 'default'
};
addList = (newListName) => {
console.log("New List: " + newListName);
let newLists = {...this.state.lists}
newLists[`list${Date.now()}`] = {
items: {
'item1': 'default item'
},
listName: newListName
};
this.setState({ lists: newLists });
};
setCurrentList = (key) => {
console.log("curent list:" + key);
this.setState({ currentList: key });
this.props.history.push(`/list/${key}`);
console.log(this.state);
};
updateListName = (key, value) => {
console.log("updating list");
var newState = {...this.state};
newState.lists[key].listName = value;
this.setState(newState);
}
deleteList = (listId, key) => {
let { lists } = this.state;
// Move items from the list to the deleted list
lists['deleted'].items = Object.assign(lists['deleted'].items || {}, {...lists[listId].items});
lists[listId] = null;
if (lists === undefined) {
lists = {}
}
this.setState({ lists });
};
addItem = (listId, newItemName, key = null) => {
console.log("add item");
console.log(listId, newItemName);
let lists = {...this.state.lists};
if (!lists[listId].items) {
lists[listId].items = {};
}
let newKey = key ? key : `item${Date.now()}`
lists[listId].items[newKey] = newItemName;
this.setState({ lists });
};
deleteItem = (listId, key) => {
var { lists } = this.state;
if (listId !== 'deleted') {
if (!lists['deleted'].items) {
lists['deleted'].items = {}
}
lists['deleted'].items[key] = {...lists[listId].items[key]};
}
lists[listId].items[key] = null;
if (lists[listId].items === undefined) {
lists[listId].items = {}
}
this.setState({ lists });
};
updateItem = (listId, key, value) => {
var { lists } = this.state;
lists[listId].items[key] = value;
this.setState({ lists });
}
moveItemToList = (fromListId, key, toListId) => {
var { lists } = this.state;
let value = lists[fromListId].items[key];
this.addItem(toListId, value, key);
this.deleteItem(fromListId, key);
}
componentDidMount = () => {
if (this.props.match.params.listId) {
let urlKey = this.props.match.params.listId;
if (this.state.lists[urlKey]) {
this.setState({currentList: this.props.match.params.listId});
}
else {
this.props.history.push(`/`);
}
}
this.ref = base.syncState('lists', {
context: this,
state: 'lists',
})
};
render() {
return (
<div className="App">
<ListsList lists={this.state.lists} addList={this.addList} setCurrentList={this.setCurrentList} activeList={this.state.currentList} updateListName={this.updateListName} deleteList={this.deleteList}/>
<TodoList list={this.state.lists[this.state.currentList]} addItem={this.addItem} deleteItem={this.deleteItem} listId={this.state.currentList} updateItem={this.updateItem} moveItemToList={this.moveItemToList}/>
</div>
);
}
}
export default App;
<file_sep>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import './ListHandler.scss';
class ListHandler extends Component {
state = {
editing: false
};
myValue = React.createRef();
setCurrentList = (e) => {
console.log("set current: " + this.props.listId);
this.props.setCurrentList(this.props.listId);
};
startEdit = (e) => {
if (this.props.listId !== 'default') {
this.setState({editing: true});
}
}
submitEditForm = (e) => {
e.preventDefault();
this.setState({editing: false});
if (this.myValue.current.value !== '') {
console.log("saving list");
this.props.updateListName(this.props.listId, this.myValue.current.value);
}
}
deleteItem = (e) => {
e.preventDefault();
e.stopPropagation();
this.props.setCurrentList('default');
this.props.deleteList(this.props.listId);
}
render () {
return (
<div className={"listHandler" + (this.props.activeList === this.props.listId ? ' activeList' : '')} onClick={this.setCurrentList}>
{this.state.editing ? (
<div className="listEditForm">
<form onSubmit={this.submitEditForm}>
<input autoFocus={true} ref={this.myValue} type="text" onBlur={this.submitEditForm} name="listEditName" defaultValue={this.props.list.listName}/>
</form>
</div>
) : (
<React.Fragment>
<div className="listName">
{this.props.list.listName}
</div>
<b onClick={this.startEdit} className="editList">(Edit)</b>
{this.props.listId !== 'default' && this.props.listId !== 'done' && this.props.listId !== 'deleted'? (
<span>
<b onClick={this.deleteItem} className="deleteIcon">X</b>
</span>
) : null}
</React.Fragment>
)}
</div>
)
}
}
ListHandler.propTypes = {
setCurrentList: PropTypes.func,
activeList: PropTypes.string,
list: PropTypes.object,
listId: PropTypes.string,
updateListName: PropTypes.func,
deleteList: PropTypes.func
}
export default ListHandler<file_sep>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import './NewItemForm.scss';
class NewItemForm extends Component {
newItemName = React.createRef();
addItem = (e) => {
e.preventDefault();
this.props.addItem(this.props.listId, this.newItemName.current.value);
this.newItemName.current.value = '';
};
render() {
return (
<div className="newItemForm">
<form onSubmit={this.addItem}>
<label>Add Item:</label>
<input type="text" ref={this.newItemName} className="newItemInput" name="newItemTitle"/>
</form>
</div>
);
}
}
NewItemForm.propTypes = {
addItem: PropTypes.func,
listId: PropTypes.string
};
export default NewItemForm;<file_sep>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import NewList from './NewList'
import './ListsList.scss';
import ListHandler from './ListHandler'
class ListsList extends Component {
render () {
return (
<div className="listsList">
<b>Lists</b>
{Object.keys(this.props.lists).map((key) => {
return <ListHandler
key={key}
listId={key}
list={this.props.lists[key]}
activeList={this.props.activeList}
setCurrentList={this.props.setCurrentList}
updateListName={this.props.updateListName}
deleteList={this.props.deleteList}
/>
})}
<NewList addList={this.props.addList}/>
</div>
)
}
}
ListsList.propTypes = {
lists: PropTypes.object,
addList: PropTypes.func,
setCurrentList: PropTypes.func,
activeList: PropTypes.string,
updateListName: PropTypes.func,
deleteList: PropTypes.func
}
export default ListsList<file_sep>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import './TodoItem.scss';
class TodoItem extends Component {
state = {
editing: false
};
myValue = React.createRef();
deleteItem = (e) => {
this.props.deleteItem(this.props.listId, this.props.id);
};
submitEditForm = (e) => {
e.preventDefault();
console.log("saving item");
this.setState({editing: false});
this.props.updateItem(this.props.listId, this.props.id, this.myValue.current.value);
}
startEdit = (e) => {
this.setState({editing: true});
}
moveToDone = (e) => {
this.props.moveItemToList(this.props.listId, this.props.id, 'done');
}
render() {
return (
<div className="todoItem">
{this.state.editing ? (
<div className="itemEditForm">
<form onSubmit={this.submitEditForm}>
<input autoFocus={true} ref={this.myValue} type="text" onBlur={this.submitEditForm} name="itemEditName" defaultValue={this.props.title}/>
</form>
</div>
) : (
<div>
{this.props.listId !== 'done' ? (<b onClick={this.moveToDone} className="doneIcon">DONE</b>) : null}
<b onClick={this.startEdit}>{this.props.title}</b>
<b onClick={this.deleteItem} className="deleteIcon">X</b>
</div>
)}
</div>
);
}
}
TodoItem.propTypes = {
title: PropTypes.string,
deleteItem: PropTypes.func,
listId: PropTypes.string,
updateItem: PropTypes.func,
moveItemToList: PropTypes.func
};
export default TodoItem;
|
2c0f1d53413daae4a64c111961d11f300f826d2c
|
[
"JavaScript"
] | 5
|
JavaScript
|
peterlozano/react-for-beginners
|
d2f13305b3c9646361c0dc5a1dd4474bc2da4a34
|
ea9cf4bab3bdd4a99d123522a559af7eef800ddb
|
refs/heads/master
|
<repo_name>weyewe/salorg<file_sep>/db/migrate/20120524032932_create_purchases.rb
class CreatePurchases < ActiveRecord::Migration
def change
create_table :purchases do |t|
t.integer :item_id
t.integer :supplier_id
t.integer :price
t.text :description
t.integer :discount, :default => 0 # (percentage)
t.datetime :discount_cut_off_date
t.boolean :has_early_delivery_discount, :default => false
t.integer :quantity_requested
t.integer :purchase_requester_id
t.integer :quantity_ordered
t.integer :purchase_order_creator_id
t.boolean :is_purchase_order_created, :default => false
t.integer :quantity_delivered , :default => 0
t.boolean :has_completed_delivery, :default => false
t.datetime :expected_delivery_date
t.datetime :actual_delivery_date
t.boolean :is_multiple_delivery , :default => false
t.string :purchase_order_identification_number
t.integer :total_quantity_delivered , :default => 0
# quantity delivered might be more than what is asked
# how will this impact the price? just take it as bonus
t.timestamps
end
end
end
<file_sep>/app/models/user_management/user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
# attr_accessible :title, :body
has_many :assignments
has_many :roles, :through => :assignments
validates_uniqueness_of :email
def self.create_user(role_list, email, password, password_confirmation)
new_user = User.new(:email => email, :password => <PASSWORD>, :password_confirmation => <PASSWORD>)
if not new_user.save
return nil
end
# job_attachment = JobAttachment.create(:user_id => new_user.id, :office_id => self.id)
role_list.each do |role|
Assignment.create_role_assignment_if_not_exists( role, new_user)
end
return new_user
end
def has_role?(role_sym)
roles.any? { |r| r.name.underscore.to_sym == role_sym }
end
=begin
As Sales Manager
=end
def proposed_purchases
PurchaseRequest.find(:all,:conditions => {
:purchase_requester_id => self.id
})
end
=begin
As Director or PO approval -> It can't be finance for now. they are all shit.
=end
def approved_purchase_requests
PurchaseRequest.find(:all,:conditions => {
:purchase_requester_id => self.id ,
:is_purchase_order_created => true
})
end
=begin
as the warehouse officer, receiving the goods
=end
end
<file_sep>/app/models/goods_creator/item_batch.rb
class ItemBatch < ActiveRecord::Base
# attr_accessible :title, :body
belongs_to :item_batch
has_one :purchase
# has_many :inbound_documents
end
<file_sep>/spec/models/category_spec.rb
require 'spec_helper'
describe Category do
context "root category post creation" do
before(:each) do
@root_category_1 = Category.create_root_category(:title => "Male")
end
it "should create category with root category as true" do
@root_category_1.is_root_category.should be_true
end
it "should create absolute depth == 0, for root category" do
@root_category_1.absolute_depth.should == ROOT_CATEGORY_ABSOLUTE_DEPTH
end
end
context "sub_category post creation" do
before(:each) do
# create the root
@root_category_1 = Category.create_root_category(:title => "Male")
@sub_category_depth_1 = @root_category_1.create_sub_category(:title => "Top")
@sub_category_depth_2 = @sub_category_depth_1.create_sub_category(:title => "T-Shirt")
end
it "should not return any other than itself, for root category direct parent" do
@root_category_1.direct_parent_category.id.should == @root_category_1.id
end
it "should produce depth level == x + 1 depth level, where x is the depth level of the direct parent" do
@sub_category_depth_2.absolute_depth.should == @sub_category_depth_1.absolute_depth + 1
end
it "should produce direct edge from the parent's parents to itself" do
CategoryEdge.find(:first, :conditions => {
:category_id => @root_category_1.id ,
:sub_category_id => @sub_category_depth_2.id
}).should be_valid
end
it "should produce N new edges, where N is the total depth of the tree from the root" do
CategoryEdge.find(:all, :conditions => {
:sub_category_id => @sub_category_depth_2.id
}).count.should == 2
end
it "should delete N edges post deletion" do
total_category_edges_before_destroy = CategoryEdge.count
@sub_category_depth_2.destroy
CategoryEdge.count.should == ( total_category_edges_before_destroy - 2 )
end
end
end
<file_sep>/spec/models/product_spec.rb
require 'spec_helper'
describe Product do
before(:each) do
@sales_manager_role = FactoryGirl.create(:sales_manager_role)
@product_creator_role = FactoryGirl.create(:product_creator_role)
@customer_service_role = FactoryGirl.create(:customer_service_role)
@warehouse_officer_role = FactoryGirl.create(:warehouse_officer_role)
@sales_manager = User.create_user( [@sales_manager_role],
'<EMAIL>',
'willy1234',
'willy1234'
)
@product_creator = User.create_user( [@product_creator_role],
'<EMAIL>',
'willy1234',
'willy1234'
)
@customer_service = User.create_user( [@customer_service_role],
'<EMAIL>',
'willy1234',
'willy1234'
)
@warehouse_officer = User.create_user( [@warehouse_officer_role],
'<EMAIL>',
'willy1234',
'willy1234'
)
@property_size = Property.create(:name => "Size" )
@small_size_value = @property_size.create_value(:name => "S", :description => "Small")
@medium_size_value = @property_size.create_value(:name => "M", :description => "Medium ")
@large_size_value = @property_size.create_value(:name => "L", :description => "Large")
@supplier = Supplier.create(:name => "Hamdani")
@property_size_hash = {
:property_id => @property_size.id,
:value_id => @small_size_value.id
}
@second_skin = Brand.create :name => "Second SKin"
end
context "Pre condition, create base product on behalf of supplier, auto promote from item" do
it "should not allow user with no product_creator role to create the item" do
product = Product.direct_promote_base_item_to_product_on_behalf_of_supplier(@product_creator, @supplier,
{:name => "Azalea"},
@second_skin, [@property_size_hash], BigDecimal("-5000") )
product.should be_nil
end
end
context "Post condition, create base product on behalf of supplier, auto promote from item" do
it "should create the related product memberships and items" do
product = Product.direct_promote_base_item_to_product_on_behalf_of_supplier(@product_creator, @supplier,
{:name => "Azalea"},
@second_skin, [@property_size_hash], BigDecimal("500000") )
product.should be_valid
product.should have(1).items
product.should have(1).product_memberships
product.should have(1).price_histories
end
end
context "Changing Price" do
before(:each) do
@product = Product.direct_promote_base_item_to_product_on_behalf_of_supplier(@product_creator, @supplier,
{:name => "Azalea"},
@second_skin, [@property_size_hash], BigDecimal("500000") )
end
it "should not allow negative price" do
result = @product.change_price(BigDecimal("-50") , @product_creator)
result.should be_nil
end
it "should only be changed by prodct creator" do
result = @product.change_price(BigDecimal("50") , @warehouse_officer)
result.should be_nil
end
it "should change the price, and add new price history" do
initial_price_history_count = @product.price_histories.count
new_price = BigDecimal("100000")
new_price_history = @product.change_price( new_price , @product_creator)
new_price_history.should be_valid
final_price_history_count = @product.price_histories.count
(final_price_history_count - initial_price_history_count).should == 1
@product.price.should == new_price
end
end
end
<file_sep>/spec/models/user_spec.rb
require 'spec_helper'
describe User do
before(:each) do
@sales_manager_role = FactoryGirl.create(:sales_manager_role)
@product_creator_role = FactoryGirl.create(:product_creator_role)
@customer_service_role = FactoryGirl.create(:customer_service_role)
@warehouse_officer_role = FactoryGirl.create(:warehouse_officer_role)
end
context "User creation" do
it "should not allow duplicate email" do
sales_manager = User.create_user([@sales_manager_role], '<EMAIL>', 'willy1234', 'willy1234')
sales_manager.should be_valid
sales_manager_2 = User.create_user([@sales_manager_role], '<EMAIL>', 'willy1234', 'willy1234')
sales_manager_2.should be_nil
end
it "should not allow double roles" do
sales_manager = User.create_user([@sales_manager_role,@sales_manager_role ], '<EMAIL>', 'willy1234', 'willy1234')
sales_manager.should have(1).roles
end
end
end
<file_sep>/db/migrate/20120522154232_create_price_histories.rb
class CreatePriceHistories < ActiveRecord::Migration
def change
create_table :price_histories do |t|
t.decimal :price , :precision => 9, :scale => 2 , :default => 0
t.integer :product_id
t.integer :price_changer_id
t.timestamps
end
end
end
<file_sep>/app/models/goods_creator/item.rb
class Item < ActiveRecord::Base
attr_accessible :name , :category_id
belongs_to :supplier
has_many :item_batches # item is bought batch by batch, with different price
# this is the method to calculate price
has_many :variants
has_many :variant_items, :through => :variants,
:source => :variant_item
# Variant Creator
has_many :property_values
has_many :properties, :through => :property_values
has_many :values, :through => :property_values
# Product creator
has_many :product_memberships
has_many :products, :through => :product_memberships
#Category Ownership
belongs_to :category
# Brand Ownership
# belongs_to :brand
validates_presence_of :name
=begin
For the self many-many referential
=end
def base_item
if self.is_base_item == true
return self
elsif self.is_base_item == false
return Item.find_by_id self.base_item_id
end
end
=begin
Create item on behalf of supplier
=end
def embed_property_value_list( property_value_list )
count = 1
property_value_list.each do |property_value_pair|
PropertyValue.create(:item_id => self.id,
:property_id => property_value_pair[:property_id],
:value_id => property_value_pair[:value_id],
:position => count)
count += 1
end
end
def self.valid_item_params_to_create_items_on_behalf_of_supplier( product_creator, property_value_list , supplier )
if not product_creator.has_role?(:product_creator)
return false
end
if not PropertyValue.valid_property_value_list?( property_value_list )
return false
end
if supplier.nil?
return false
end
return true
end
def self.create_base_item_on_behalf_of_supplier(product_creator, supplier,
item_params,
property_value_list )
if not self.valid_item_params_to_create_items_on_behalf_of_supplier( product_creator, property_value_list , supplier )
return nil
end
item = Item.create(:name => item_params[:name])
item.supplier_id = supplier.id
# item.brand_id = brand.id
item.embed_property_value_list( property_value_list )
return item
end
=begin
Create VariantItem on behalf of supplier
=end
def has_similar_property_value_list?( property_value_list )
property_value_list.each do |property_value_pair|
if self.property_values.where(:property_id => property_value_pair[:property_id],
:value_id => property_value_pair[:value_id]).count == 0
next
else
return true
end
end
return false
end
def create_variant_item( product_creator, property_value_list )
if self.has_similar_property_value_list?( property_value_list )
return nil
end
if not product_creator.has_role?(:product_creator)
return nil
end
variant_item = self.clone
variant_item.is_base_item = false
variant_item.base_item_id = self.id
variant_item.save
return variant_item
end
#
# def self.create_variant_item_on_behalf_of_supplier(product_creator, supplier,
# base_item,
# property_value_list )
#
# if not self.valid_item_params_to_create_items_on_behalf_of_supplier( product_creator, property_value_list , supplier )
# return nil
# end
#
# if self.has_similar_property_value_list_with_base_item( property_value_list )
# return nil
# end
#
#
#
# item = Item.create(:name => item_params[:name])
#
# item.supplier_id = supplier.id
# # item.brand_id = brand.id
#
# item.embed_property_value_list( property_value_list )
#
# return item
# end
#
end
<file_sep>/app/models/dynamic_constants/category.rb
class Category < ActiveRecord::Base
# attr_accessible :title, :body
# we use some of the graphy theory : node and edge
# the Category is the node. The link up between one category and its sub category is called
# the category edge
# category edge stores
# 1. the parent category
# 2. the child category
# 3. the distance (tree level). direct access. no traversal is needed
# the category node stores
# 1. the category title
# 2. the absolute level ( starts from 0)
has_many :category_edges
has_many :sub_categories, :through => :category_edges,
:source => :sub_category
after_create :propagate_edge_creation_to_the_root
before_destroy :propagate_edge_deletion_to_the_root
attr_accessible :title, :description
has_many :items
=begin
For the self many-many referential
=end
def direct_parent_category
if self.is_root_category == true
return self
elsif self.is_root_category == false
return Category.find_by_id self.direct_parent_category_id
end
end
def parent_category_id_list
CategoryEdge.find(:all, :conditions => {
:sub_category_id => self.id
}).collect {|x| x.category_id }
end
=begin
category creation
=end
def self.create_root_category( params )
# the absolute depth == 0
category = Category.new :title => params[:title], :description => params[:description]
category.absolute_depth = ROOT_CATEGORY_ABSOLUTE_DEPTH
category.is_root_category = true
category.save
return category
end
def create_sub_category(params)
category = Category.new :title => params[:title], :description => params[:description]
category.absolute_depth = self.absolute_depth + 1
category.direct_parent_category_id = self.id
category.save
# category.propagate_edge_creation_to_the_root
return category
end
protected
=begin
Example case
Have a look: Male, Female, Kids, Baby are all root categories
The category with depth 1 is Top, Bottom, and Underwear
category with depth 2 is Tshirt, shirt, singlet
Category with depth 3 is turtle neck, v-neck
Suppose that we are adding another category with depth 4
Variation of Turtle Neck : Maldive Turtle and China Turtle
For the Maldive Turtle
It will create
1 edge linking Turtle Neck and Maldive Turtle ( delta == 1 )
1 edge linking T-shirt and Maldive Turtle ( delta == 2 )
1 edge linking Top and Maldive Turtle
1 edge linking Male and Maldive Turtle
Number of edges created: total depth .. linear expansion. can we cater for this? ahaha
Male -> Top -> T-Shirt -> Turtle Neck -> [ Maldive Turtle ]
-> V Neck
-> Shirt -> Skinny
-> Loose
-> Singlet
-> Bottom
-> Underwear
Female
Kids
Baby
=end
def propagate_edge_creation_to_the_root
if self.is_root_category == true
return
end
direct_parent = self.direct_parent_category
# add the link ups with the direct parent's parents
direct_parent.parent_category_id_list.each do |parent_category_id|
parent_category = Category.find_by_id parent_category_id
CategoryEdge.create :category_id => parent_category_id ,
:sub_category_id => self.id ,
:delta => self.absolute_depth - parent_category.absolute_depth
end
# add the last link up with the direct parent
CategoryEdge.create :category_id => direct_parent.id ,
:sub_category_id => self.id ,
:delta => self.absolute_depth - direct_parent.absolute_depth
end
def propagate_edge_deletion_to_the_root
if self.is_root_category == true
return
end
CategoryEdge.find(:all, :conditions => {
:category_id => self.parent_category_id_list,
:sub_category_id => self.id
}).each {|x| x.destroy }
end
end
<file_sep>/spec/models/value_spec.rb
require 'spec_helper'
describe Value do
context "create value from property" do
before(:each) do
@size_property = Property.create :name => "Size"
end
it "should be created from property, linked to the creating property" do
small_value = @size_property.create_value(:name => "S")
medium_value = @size_property.create_value(:name => "M")
large_value = @size_property.create_value(:name => "L")
@size_property.should have(3).values
small_value.property.should == @size_property
end
end
end
<file_sep>/db/migrate/20120521151824_create_categories.rb
class CreateCategories < ActiveRecord::Migration
def change
create_table :categories do |t|
t.string :title
t.text :description
# root category is the first level category. the root.
# the absolute depth is 0.
# the first sub_category of this root_category is category with absolute depth == 1
t.boolean :is_root_category, :default => false
t.integer :direct_parent_category_id
t.integer :absolute_depth, :null => false
t.timestamps
end
end
end
<file_sep>/db/seeds.rb
base_item = Item.create :name => "Base Item"
variant_item_1 = Item.create :name => "Variant Item 1"
base_item.variant_items << variant_item_1
=begin
SETUP CODE
create category -> Item classification
create sub category -> Item classification
create property -> For the variations
create values corresponding to the property -> For the variations
create brands -> Storing the discount information.
=end
root_male_category = Category.create_root_category(:title => "Male")
root_female_category = Category.create_root_category(:title => "Female")
top_female_sub_cat_1 = root_female_category.create_sub_category(:title => "Bra")
top_female_sub_cat_2 = root_female_category.create_sub_category(:title => "Blouse")
top_female_sub_cat_3 = root_female_category.create_sub_category(:title => "Shirt")
top_male_sub_cat_1 = root_male_category.create_sub_category(:title => "Tie")
top_male_sub_cat_2 = root_male_category.create_sub_category(:title => "Jacket")
top_male_sub_cat_3 = root_male_category.create_sub_category(:title => "Sleeveless")
puts "Done with the category creation"
property_size = Property.create(:name => "Size" )
small_size_value = property_size.create_value(:name => "S", :description => "Small")
medium_size_value = property_size.create_value(:name => "M", :description => "Medium")
large_size_value = property_size.create_value(:name => "L", :description => "Large")
puts "Created the size property"
property_color = Property.create(:name => "Color")
red_color_value = property_color.create_value(:name => "Red")
green_color_value = property_color.create_value(:name => "Green" )
blue_color_value = property_color.create_value(:name => "Blue" )
black_color_value = property_color.create_value(:name => "Black" )
puts "Created the color property"
ajijah_brand = Brand.create(:name => "Ajijah", :member_discount => 15, :stockist_discount => 20 )
secondskin_brand = Brand.create(:name => "SecondSkin", :member_discount => 20, :stockist_discount => 30 )
puts "created the brand"
=begin
Add suppliers in the first place.
Supplier can offer items (upload the picture, basic information, and variations )
=end
hamdani_supplier = Supplier.create :name => "Hamdani"
atong_supplier = Supplier.create :name => "Atong"
=begin
But supplier game is the long run. In the short run, the employee, on behalf of supplier, uploads
the items.
Create Role
Create User
Assign Role to User
=end
sales_manager_role = Role.create :name => USER_ROLE[:sales_manager]
customer_service_role = Role.create :name => USER_ROLE[:customer_service]
warehouse_officer_role = Role.create :name => USER_ROLE[:warehouse_officer]
product_creator_role = Role.create :name => USER_ROLE[:product_creator]
# warehouse officer will do the data entry, on the item received and item going out. approval by the warehouse manager
sales_manager = User.create :email => "<EMAIL>", :password => "<PASSWORD>",
:password_confirmation => "<PASSWORD>"
product_creator = User.create :email => "<EMAIL>", :password => "<PASSWORD>",
:password_confirmation => "<PASSWORD>"
customer_service = User.create :email => "<EMAIL>", :password => "<PASSWORD>",
:password_confirmation => "<PASSWORD>"
warehouse_officer = User.create :email => "<EMAIL>", :password => "<PASSWORD>",
:password_confirmation => "<PASSWORD>"
sales_manager.roles << sales_manager_role
product_creator.roles << product_creator_role
customer_service.roles << customer_service_role
warehouse_officer.roles << warehouse_officer_role
puts "Done creating the users"
# product_creator.create_item_on_behalf_of_supplier(supplier, item_name, brand, property_value_list )
# they select the property, and values for that property appears. They select the value,
# a hidden input field will be filled in. name => properties[property_#{property_id}], value => the selected value
# there should be a helper, extracting the property-value -> Make it into an array [ [p1,v1], [p2,v2]]
# if the variant item property-value is exactly similar to base item, false
# at least, it has to have one property . Katalog -> property : edition, year
# product_creator.create_variant_item_on_behalf_of_supplier(base_item, supplier, item_name, brand, property_value_list)
# 2ndSkin condition => data migration in the short run
Product.direct_promote_base_item_to_product_on_behalf_of_supplier(product_creator, supplier,
item_params,
brand, property_value_list, price, base_price, current_quantity )
# create the variations
Product.direct_promote_variant_item_to_product_on_behalf_of_supplier(product_creator,supplier,
base_item, # name is taken from the base item
brand, property_value_list, price, base_price, current_quantity )
# keep creating several products and its variant
# in the migration, it alwayys come with the current quantity -> Initial Setup, no documents
# item without category? it is cool bro.. not that important. Category is just for data display
# not impacting the continuous data evolution . It is optional. Category should sticks to item, not product
# product creation is OK, with the final price attached. But we need the base price
# Inbound documents: output: ReceivalReceipt
# PO will produce many receival_receipts
# ReturnNotice will produce one receival_receipt
# DataMigration will produce one receival_receipt -> Increase the ItemBatch
# then, add the quantity. There has to be documents to add the quantity
# => (assumed to be good)
# flow: item quantity is expected to be added -> repeat more
# we need much leaner organization for second skin. it is shit now. can't be hierarchial.
# in this case, the PO creator is the owner/director | or even the sales manager himself
# sales manager clicked create purchase request
# finance | or in this case director will ask the
# => buyer will be forwarded of this PR
# the buyer has to come out with the item availability, price, and estimated delivery, or the director has to chase
# for it. Buyer needs to call actively, and report to the finance
# => if those 3 metric makes sense, enter those data, click create PO from PR
# -> click approve (negotiate with the seller about the price, key in the price)
# Purchase Order will be generated
# based on this PO, warehouse will receive the ordered item (might be partial receival)
# adding quantity based on the purchase order is easy.
# Incoming documents: from the PO -*> Receipt Delivery
# Incoming Documents: data migration DataMigration -> ReceiptDelivery
# => (assumed to be bad)
# incoming documents: from the customer SalesOrder -> ReturnNotice -> ReceiptDelivery
# Outbound documents: output: DeliveryReceipt
# sending things to supplier based on SupplierReturnDocument
# sending things to customer based on SalesOrderDocument
# sending things to customer based on CustomerReplacementDocument
# => Incoming Delivery Receipt -> recording the receival delivery of goods (from supplier, from member)
# => Outgoing Delivery Receipt -> recording the sending delivery of goods ( to supplier because of reject, to member to exchange
# their goods)
<file_sep>/app/models/dynamic_constants/value.rb
class Value < ActiveRecord::Base
attr_accessible :name, :property_id
belongs_to :property
has_many :items, :through => :property_values
has_many :property_values
end
<file_sep>/db/migrate/20120522014545_create_item_batches.rb
class CreateItemBatches < ActiveRecord::Migration
def change
create_table :item_batches do |t|
t.decimal :item_price , :precision => 9, :scale => 2 , :default => 0 # highest price is 7 digit
# 9,999,999
t.integer :quantity_purchased
t.integer :quantity_received
t.integer :quantity_sold
t.boolean :is_finished, :default => false
t.integer :item_id
# linked
t.integer :purchase_id
t.timestamps
end
end
end
<file_sep>/app/models/goods_creator/variant.rb
class Variant < ActiveRecord::Base
# attr_accessible :title, :body
belongs_to :item
belongs_to :variant_item, :class_name => "Item"
after_create :assign_item_variation_status
protected
def assign_item_variation_status
variant_item = self.variant_item
variant_item.is_base_item = false
variant_item.base_item_id = self.item_id
variant_item.save
end
end
<file_sep>/app/models/dynamic_constants/property.rb
class Property < ActiveRecord::Base
# attr_accessible :title, :body
has_many :values
has_many :items, :through => :property_values
has_many :property_values
attr_accessible :name
def create_value(params)
Value.create :property_id => self.id, :name => params[:name]
end
def has_value?(value)
self.values.where(:id => value.id ).count == 1
end
end
<file_sep>/app/models/goods_creator/property_value.rb
class PropertyValue < ActiveRecord::Base
attr_accessible :item_id, :property_id, :value_id, :position
belongs_to :item
belongs_to :property
belongs_to :value
def PropertyValue.valid_property_value_list?( property_value_list )
if property_value_list.length == 0
return false
end
property_value_list.each do |property_value_pair|
property = Property.find_by_id property_value_pair[:property_id]
value = Value.find_by_id property_value_pair[:value_id]
if property.has_value?(value)
next
else
return false
end
end
return true
end
end
<file_sep>/app/models/incoming_delivery.rb
class IncomingDelivery < ActiveRecord::Base
# attr_accessible :title, :body
# purchase_order has incoming delivery
# return notice has incoming delivery
# which price? price when it was bought. In sales order, list the batch id
# sales order entry
# reject supplier has incoming delivery
# good candidate for polymorphism
belongs_to :incoming_deliverable, :polymorphic => true
end
<file_sep>/config/initializers/app_constants.rb
ROOT_CATEGORY_ABSOLUTE_DEPTH = 0
USER_ROLE = {
:sales_manager => "SalesManager",
:product_creator => "ProductCreator",
:customer_service => "CustomerService",
:warehouse_officer => "WarehouseOfficer"
}
PRODUCT_TYPE = {
:single_item => 0,
:bundled_items => 1
}<file_sep>/db/migrate/20120521115529_create_items.rb
class CreateItems < ActiveRecord::Migration
def change
create_table :items do |t|
t.integer :supplier_id
t.string :name
# item has_many :variant_items
# variant_item belongs_to :base_item
t.integer :base_item_id
t.boolean :is_base_item , :default => true
t.integer :category_id
# t.decimal :base_price , :precision => 9, :scale => 2 , :default => 0 # highest price is 7 digit
# 9,999,999
# not like this. inventory pricing.
# the first batch (100 items) == 50,000
# the second batch( 200 items) == 30,000.
# FIFO: first in , first out.
# for the first 100 items, use the 50,000 rupiah.
# how can we model this?
t.timestamps
end
end
end
<file_sep>/app/models/user_management/assignment.rb
class Assignment < ActiveRecord::Base
attr_accessible :user_id, :role_id
belongs_to :user
belongs_to :role
def Assignment.create_role_assignment_if_not_exists( role, user )
assignments_count = Assignment.find(:all, :conditions => {
:role_id => role.id,
:user_id =>user.id
}).count
if assignments_count == 0
Assignment.create(:user_id => user.id , :role_id => role.id)
end
end
end
<file_sep>/db/migrate/20120521111702_create_suppliers.rb
class CreateSuppliers < ActiveRecord::Migration
def change
create_table :suppliers do |t|
t.string :name
t.text :address
t.text :other_information
t.string :phone_number
t.string :bbm_pin
t.string :contact_person_name
t.string :contact_person_phone_number
t.string :contact_person_bbm_pin
t.timestamps
end
end
end
<file_sep>/spec/models/category_edge_spec.rb
require 'spec_helper'
describe CategoryEdge do
context "POST condition of creation" do
before(:each) do
end
end
end
<file_sep>/spec/models/property_spec.rb
require 'spec_helper'
describe Property do
end
<file_sep>/spec/factories/roles.rb
# USER_ROLE = {
# :sales_manager => "SalesManager",
# :product_creator => "ProductCreator",
# :customer_service => "CustomerService",
# :warehouse_officer => "WarehouseOfficer"
# }
#
FactoryGirl.define do
factory :role do
name "The role"
end
factory :sales_manager_role, parent: :role do
name USER_ROLE[:sales_manager]
end
factory :product_creator_role, parent: :role do
name USER_ROLE[:product_creator]
end
factory :customer_service_role, parent: :role do
name USER_ROLE[:customer_service]
end
factory :warehouse_officer_role, parent: :role do
name USER_ROLE[:warehouse_officer]
end
end
<file_sep>/app/models/dynamic_constants/category_edge.rb
class CategoryEdge < ActiveRecord::Base
belongs_to :category
belongs_to :sub_category, :class_name => "Category"
# after_create :propagate_edge_creation_to_the_root
# before_destroy :propagate_edge_deletion_to_the_root
attr_accessible :category_id, :sub_category_id, :delta
end
<file_sep>/app/models/stock_migration.rb
class StockMigration < ActiveRecord::Base
# attr_accessible :title, :body
has_many :incoming_deliveries, :as => :incoming_deliverable
belongs_to :item
end
<file_sep>/db/migrate/20120522122411_create_products.rb
class CreateProducts < ActiveRecord::Migration
def change
create_table :products do |t|
t.decimal :price , :precision => 9, :scale => 2 , :default => 0
# max is 9,999,999 rupiah
t.integer :product_type , :default => PRODUCT_TYPE[:single_item]
t.integer :brand_id
t.integer :product_creator_id
t.timestamps
end
end
end
<file_sep>/spec/models/variant_spec.rb
require 'spec_helper'
describe Variant do
context "Post conditions on create" do
before(:each) do
@base_item = Item.create :name => "Base Item"
@variant_item_1 = Item.create :name => "Variant Item 2 "
@base_item.variant_items << @variant_item_1
end
it "should add the variant item " do
@base_item.should have(1).variant_items
end
it "should set the status of value item to be non-base item" do
@variant_item_1.is_base_item.should be_false
end
it "should respond to command base_item, returning the self if it is base item" do
@variant_item_1.base_item.id.should == @base_item.id
end
end
it
end
<file_sep>/app/models/goods_creator/supplier.rb
class Supplier < ActiveRecord::Base
attr_accessible :name
has_many :items
=begin
Self propose new item
=end
def create_item( name, description, base_price )
end
end
<file_sep>/spec/models/item_spec.rb
require 'spec_helper'
describe Item do
before(:each) do
@sales_manager_role = FactoryGirl.create(:sales_manager_role)
@product_creator_role = FactoryGirl.create(:product_creator_role)
@customer_service_role = FactoryGirl.create(:customer_service_role)
@warehouse_officer_role = FactoryGirl.create(:warehouse_officer_role)
@sales_manager = User.create_user( [@sales_manager_role],
'<EMAIL>',
'willy1234',
'willy1234'
)
@product_creator = User.create_user( [@product_creator_role],
'<EMAIL>',
'willy1234',
'willy1234'
)
@customer_service = User.create_user( [@customer_service_role],
'<EMAIL>',
'willy1234',
'willy1234'
)
@warehouse_officer = User.create_user( [@warehouse_officer_role],
'<EMAIL>',
'willy1234',
'willy1234'
)
@property_size = Property.create(:name => "Size" )
@small_size_value = @property_size.create_value(:name => "S", :description => "Small")
@medium_size_value = @property_size.create_value(:name => "M", :description => "Medium ")
@large_size_value = @property_size.create_value(:name => "L", :description => "Large")
@supplier = Supplier.create(:name => "Hamdani")
@property_size_hash = {
:property_id => @property_size.id,
:value_id => @small_size_value.id
}
end
context "Pre condition, create base item on behalf of supplier" do
before(:each) do
end
it "should not allow user with no product_creator role to create the item" do
item = Item.create_base_item_on_behalf_of_supplier(@warehouse_officer, @supplier,
{:name => "Azalea"},
[ @property_size_hash ] )
item.should be_nil
item = Item.create_base_item_on_behalf_of_supplier(@product_creator, @supplier,
{:name => "Azalea"},
[@property_size_hash] )
item.should be_valid
end
it "should have supplier linked to the item" do
item = Item.create_base_item_on_behalf_of_supplier(@product_creator, nil,
{:name => "Azalea"},
[@property_size_hash] )
item.should be_nil
item = Item.create_base_item_on_behalf_of_supplier(@product_creator, @supplier,
{:name => "Azalea"},
[@property_size_hash] )
item.should be_valid
end
it "should have at least one property" do
item = Item.create_base_item_on_behalf_of_supplier(@product_creator, @supplier,
{:name => "Azalea"},
[ ] )
item.should be_nil
item = Item.create_base_item_on_behalf_of_supplier(@product_creator, @supplier,
{:name => "Azalea"},
[ @property_size_hash] )
item.should be_valid
end
context "Post conditions for create item on behalf of supplier" do
before(:each) do
@item = Item.create_base_item_on_behalf_of_supplier(@product_creator, @supplier,
{:name => "Azalea"},
[ @property_size_hash] )
end
# it "sho"
end
end
context "Pre condition, create variant item on behalf of supplier" do
before(:each) do
@base_item = Item.create_base_item_on_behalf_of_supplier(@product_creator, @supplier,
{:name => "Azalea"},
[ @property_size_hash] )
end
it "should not allow duplicate property value in the item-variant_items group" do
new_property_size_hash = {
:property_id => @property_size.id,
:value_id => @medium_size_value.id
}
variant_item = @base_item.create_variant_item( @product_creator, [@property_size_hash] )
variant_item.should be_nil
variant_item = @base_item.create_variant_item( @product_creator, [new_property_size_hash] )
variant_item.should be_valid
variant_item.is_base_item.should be_false
variant_item.base_item_id.should == @base_item.id
variant_item.name.should == @base_item.name
variant_item.base_item.id.should == @base_item.id
end
end
end
<file_sep>/app/models/goods_creator/product.rb
class Product < ActiveRecord::Base
attr_accessible :price, :brand_id, :product_creator_id
has_many :items, :through => :product_memberships
has_many :product_memberships
# Brand Ownership
belongs_to :brand
has_many :price_histories
after_create :add_initial_price_history
=begin
Product Creation (direct promote from item, on behalf of supplier)
=end
def self.valid_direct_promote_item_to_product_parameters?(price, product_creator)
if price < BigDecimal("0")
return false
end
if not product_creator.has_role?(:product_creator)
return false
end
return true
end
def self.direct_promote_base_item_to_product_on_behalf_of_supplier(product_creator, supplier,
item_params,
brand, property_value_list, price )
if not Product.valid_direct_promote_item_to_product_parameters?(price, product_creator)
return nil
end
item = Item.create_base_item_on_behalf_of_supplier(product_creator, supplier,
item_params,
property_value_list )
if not item.nil?
# product = Product.create :price => price , :product_creator_id => product_creator.id
# product.items << item
# product.brand_id = brand.id
# return product
Product.create_from_item( price, product_creator, item, brand )
else
return nil
end
end
def Product.direct_promote_variant_item_to_product_on_behalf_of_supplier(product_creator,supplier,
base_item, # name is taken from the base item
brand, property_value_list, price )
if not Product.valid_direct_promote_item_to_product_parameters?(price, product_creator)
return nil
end
variant_item = base_item.create_variant_item(product_creator, property_value_list )
if not item.nil?
Product.create_from_item( price, product_creator, variant_item, brand )
# product = Product.create :price => price, :product_creator_id => product_creator.id
# product.items << item
# product.brand_id = brand.id
# return product
else
return nil
end
end
def Product.create_from_item( price, product_creator, item, brand )
product = Product.create :price => price, :product_creator_id => product_creator.id
product.items << item
product.brand_id = brand.id
product.save
return product
end
=begin
Utility methods for product
=end
def product_creator
User.find_by_id self.product_creator_id
end
=begin
Tracking price change
=end
def change_price(new_price, price_changer)
if new_price < BigDecimal("0") or not price_changer.has_role?(:product_creator)
return nil
else
self.price = new_price
price_history = PriceHistory.add_price_history( price_changer, self.price, self)
return price_history
end
end
def add_initial_price_history
# the first price created
PriceHistory.add_price_history( self.product_creator , self.price, self)
end
end
<file_sep>/app/models/goods_creator/price_history.rb
class PriceHistory < ActiveRecord::Base
attr_accessible :product_id
belongs_to :product
def self.add_price_history( user , price, product)
price_history = PriceHistory.create :product_id => product.id
price_history.price_changer_id = user.id
price_history.price = price
price_history.save
return price_history
end
end
<file_sep>/spec/factories/item_batches.rb
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :item_batch do
end
end
<file_sep>/app/models/goods_creator/brand.rb
class Brand < ActiveRecord::Base
attr_accessible :name, :member_discount, :stockist_discount
has_many :products
end
<file_sep>/app/models/purchase.rb
class Purchase < ActiveRecord::Base
# attr_accessible :title, :body
has_one :item_batch
has_many :incoming_deliveries, :as => :incoming_deliverable
def pending_approval_purchase_requests
# if it is the pasponsel.com, we take company params. :)
PurchaseRequest.find(:all, :conditions => {
:is_purchase_order_created => false
})
end
def ongoing_delivery_purchases
PurchaseRequest.find(:all, :conditions => {
:is_purchase_order_created => true,
:has_completed_delivery => false
})
end
def finished_delivery_purchases
PurchaseRequest.find(:all, :conditions => {
:is_purchase_order_created => true,
:has_completed_delivery => true
})
end
end
<file_sep>/app/models/goods_creator/product_membership.rb
class ProductMembership < ActiveRecord::Base
attr_accessible :item_id, :product_id
belongs_to :item
belongs_to :product
end
<file_sep>/db/migrate/20120521152349_create_category_edges.rb
class CreateCategoryEdges < ActiveRecord::Migration
def change
create_table :category_edges do |t|
t.integer :category_id
t.integer :sub_category_id
t.integer :delta
# delta: absolute depth of the sub_category
# minus absolute depth of the parent category
t.timestamps
end
end
end
<file_sep>/db/migrate/20120524041853_create_incoming_deliveries.rb
class CreateIncomingDeliveries < ActiveRecord::Migration
def change
create_table :incoming_deliveries do |t|
t.integer :quantity
t.integer :incoming_deliverable_id
t.string :incoming_deliverable_type
t.timestamps
end
end
end
|
697cdaddb693ffac2ec8cbd0a772179056706133
|
[
"Ruby"
] | 39
|
Ruby
|
weyewe/salorg
|
e2fcd2766ed8b48e57e6ecae9857206eee68b453
|
bffcb83e7b57a0cf50c90693e2542b43b70ca45e
|
refs/heads/master
|
<file_sep># django-batch-uploader
Django batch uploading
#Features
1. Users can batch upload files / bulk upload files / upload
multiple files at one -- however you prefer to phrase it!
2. Users can specify default values to apply in bulk. For example, if
you're a photographer uploading multiple images from a single shoot, you may
want to be able to tag all the images to a single shoot.
3. Users can individually edit specific fields. For example, if
you're a photographer uploading multiple images from a single shoot,
you may want to add titles when you first upload them so you don't
have to go back and update them individually.
#Compatibility / Requirements
1. Django (last tested with 1.8.2)
2. django-grappelli (last tested with 2.6.5)
3. Chrome, Firefox, Safari, IE10+ (Essentially this list: http://caniuse.com/#feat=input-file-multiple)
#Installation
pip install django-batch-uploader
##settings.py
INSTALLED_APPS = (
...
'django_batch_uploader',
...
)
##views.py
from django_batch_uploader.views import AdminBatchUploadView
class ImageBatchView(AdminBatchUploadView):
model = Image
#Media file name
media_file_name = 'image'
#Which fields can be applied in bulk?
default_fields = ['credit', 'admin_description', 'creator', 'tags']
#Which fields can be applied individually?
detail_fields = ['title', 'alt', 'caption']
default_values = {}
##urls.py
....
url( r'admin/media/images/batch/$', ImageBatchView.as_view(), name="admin_image_batch_view"),
....
##admin.py
from django_batch_uploader.admin import BaseBatchUploadAdmin
class BaseImageAdmin(BaseBatchUploadAdmin):
batch_url_name = "admin_image_batch_view"
fieldsets = (
("Image", {
'fields': ('image', 'title', 'alt', 'caption', 'credit','tags'),
}),
("Meta", {
'fields': ('creator','admin_description'),
})
)
#Screenshots
##Bulk upload button in changelist

##Select files and specify individual values

##Specify defaults to bulk-apply

##Upload in progress

##Upload successful

<file_sep>import json
import copy
from mimetypes import MimeTypes
import urllib
from django.contrib import admin
from django.contrib.admin.exceptions import DisallowedModelAdminToField
from django.contrib.admin.models import LogEntry, ADDITION
from django.contrib.admin.options import TO_FIELD_VAR
from django.contrib.admin.utils import unquote
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ImproperlyConfigured, PermissionDenied, ValidationError, NON_FIELD_ERRORS
from django.core.urlresolvers import reverse
from django.db.models.fields.related import ManyToManyRel
from django.http import HttpResponse, HttpResponseServerError
from django.template.defaultfilters import capfirst, linebreaksbr
from django.utils import six
from django.utils.encoding import force_text, smart_text
from django.utils.html import conditional_escape, format_html
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
def get_empty_value_display(cls):
if hasattr(cls.model_admin, 'get_empty_value_display'):
return cls.model_admin.get_empty_value_display()
else:
# Django < 1.9
from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE
return EMPTY_CHANGELIST_VALUE
from django.contrib.admin.utils import (
display_for_field, flatten_fieldsets, help_text_for_field, label_for_field,
lookup_field,
)
from .utils import get_media_file_name, get_media_file
class BaseBatchUploadAdmin(admin.ModelAdmin):
#Add batch_url to context
#batch_url_name = 'admin_image_batch_view'
change_list_template = "admin/batch_change_list.html"
def changelist_view(self, request, extra_context=None):
extra_context = extra_context or {}
if hasattr(self, 'batch_url_name'):
extra_context['batch_url_name'] = self.batch_url_name
extra_context['batch_url'] = reverse(self.batch_url_name)
return super(BaseBatchUploadAdmin, self).changelist_view(request, extra_context=extra_context)
def add_view(self, request, form_url='', extra_context=None):
is_batch_upload = request.method == 'POST' and "batch" in request.POST
response = None
if is_batch_upload:
errors = []
errors = self.validate_form(request, form_url, extra_context)
if errors is None:
default_response = super(BaseBatchUploadAdmin, self).add_view(request, form_url, extra_context)
response = self.batch_upload_response(request)
if response != None:
return response
else:
return default_response
data = {
"success":False,
"errors":errors
}
json_dumped = json.dumps(data)
return HttpResponse(json_dumped, content_type='application/json')
else:
return super(BaseBatchUploadAdmin, self).add_view(request, form_url, extra_context)
def validate_form(self, request, form_url, extra_context=None):
to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR))
if to_field and not self.to_field_allowed(request, to_field):
return {NON_FIELD_ERRORS:"The field %s cannot be referenced." % to_field}
model = self.model
opts = model._meta
add = True
if not self.has_add_permission(request):
return {NON_FIELD_ERRORS:"Permission Denied"}
obj = None
ModelForm = self.get_form(request, obj)
form = ModelForm(request.POST, request.FILES, instance=obj)
valid = form.is_valid()
if not form.is_valid():
error_dict = dict(form.errors.items())
media_file_name = get_media_file_name(self, self.model)
#BEGIN HACK -- Currently a second validation of the newly uploaded file results in a validation error.
if media_file_name in error_dict:
delete_indexes = []
i = 0
for error in copy.deepcopy(error_dict[media_file_name]):
from django.forms.fields import ImageField
ignore_validation_error = ImageField.default_error_messages['invalid_image']
ignore_validation_error_translated = _(ignore_validation_error)
if error == ignore_validation_error or error == ignore_validation_error_translated:
error_dict[media_file_name].pop(i)
i = i+1
if len(error_dict[media_file_name]) == 0:
del error_dict[media_file_name]
#Double check error dict after we've manipulated it
for key in error_dict:
if len(error_dict[key]) == 0:
del error_dict[key]
if len(error_dict.keys()) == 0:
error_dict = None
#END HACK
return error_dict
return None
#If we made it to here with no errors, we're valid.
def get_field_contents(self, field, obj):
from django.contrib.admin.templatetags.admin_list import _boolean_icon
model_admin = self
try:
f, attr, value = lookup_field(field, obj, self)
except (AttributeError, ValueError, ObjectDoesNotExist):
result_repr = get_empty_value_display(self)
else:
if f is None:
boolean = getattr(attr, "boolean", False)
if boolean:
result_repr = _boolean_icon(value)
else:
result_repr = smart_text(value)
if getattr(attr, "allow_tags", False):
result_repr = mark_safe(result_repr)
else:
result_repr = linebreaksbr(result_repr)
else:
if isinstance(f.rel, ManyToManyRel) and value is not None:
result_repr = ", ".join(map(six.text_type, value.all()))
else:
result_repr = display_for_field(value, f, "")
return conditional_escape(result_repr)
def batch_upload_response(self, request):
output_fields = flatten_fieldsets(self.fieldsets)
media_file_name = get_media_file_name(self, self.model)
#Disabling exception handling here @olivierdalang's feedback:
# try:
latest_log_entry = LogEntry.objects.filter(action_flag=ADDITION).order_by('-action_time')[0]
ct = ContentType.objects.get_for_id(latest_log_entry.content_type_id)
obj = ct.get_object_for_this_type(pk=latest_log_entry.object_id)
if obj:
object_data = {}
mime = MimeTypes()
media_file = get_media_file(self, self.model, obj)
media_file_url = media_file.url #urllib.pathname2url(media_file.url) #Not sure why i had this, but it's escaping the URL
mime_type = mime.guess_type(media_file_url)
edit_url = reverse('admin:%s_%s_change' %(obj._meta.app_label, obj._meta.model_name), args=[obj.id] )
object_data['media_file_url'] = media_file_url
object_data['media_file_size'] = media_file.size
object_data['media_file_type'] = mime_type[0]
object_data['edit_url'] = mark_safe(edit_url)
field_values = {}
for output_field in output_fields:
value = str(self.get_field_contents(output_field, obj))
label = str(label_for_field(output_field, self.model, self))
field_values[output_field] = {
'label':label,
'value':value
}
object_data['field_values'] = field_values
data = {
"success":True,
"files":[
object_data
]
}
json_dumped = json.dumps(data)
return HttpResponse(json_dumped, content_type='application/json')
# except Exception as e:
# return HttpResponseServerError(e)
<file_sep>from django.core.exceptions import ImproperlyConfigured
def get_media_file_name(cls, model):
#If explicitely labeled
if hasattr(model, 'media_file_name'):
return model.media_file_name
if hasattr(cls, 'media_file_name'):
return cls.media_file_name
file_types = []
for field in model._meta.fields:
if field.get_internal_type() == "FileField":
file_types.append(field)
if len(file_types) == 1:
return file_types[0].name
raise ImproperlyConfigured("We detected that there are either \
0 or or more than 1 media file on this model. Please specify 'media_file_name' \
for this model or view view that corresponds to the media file on the %s model. \
For example: media_file_name='image' "%(model._meta.model_name))
def get_media_file(cls, model, obj):
# try:
media_file_name = get_media_file_name(cls, model)
#If explicitely labeled
if hasattr(obj, media_file_name):
return getattr(obj, media_file_name)
# except:
# pass
if hasattr(obj, 'get_media_file'):
return obj.get_media_file()
if hasattr(model, 'get_media_file'):
return model.get_media_file()
if hasattr(cls, 'get_media_file'):
return cls.get_media_file()
raise ImproperlyConfigured("Either media_file_name or get_media_file not \
implemented on Instance (%s), Model (%s), or View (%s). "%(obj, model, cls)) <file_sep>from setuptools import setup, find_packages
setup(
name = 'django_batch_uploader',
version = '0.14',
author = '<NAME>',
author_email='<EMAIL>',
url = 'https://github.com/ninapavlich/django-batch-uploader',
license = "MIT",
description = 'Batch Uploading Mechanism for Django Admin',
keywords = ['libraries', 'web development'],
include_package_data = True,
packages = ['django_batch_uploader'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python'
]
)<file_sep>import json
from django import forms
from django.contrib.admin import helpers
from django.contrib.admin.views.decorators import staff_member_required
from django.core.urlresolvers import reverse
from django.forms.utils import ErrorDict, ErrorList, flatatt
from django.utils.decorators import method_decorator
from django.views.generic.edit import CreateView
from .utils import get_media_file_name
def model_to_modelform(model):
meta = type('Meta', (), { "model":model, "fields" : '__all__'})
modelform_class = type('modelform', (forms.ModelForm,), {"Meta": meta})
return modelform_class
class BaseBatchUploadView(CreateView):
template_name = 'batch/base.html'
def get_form(self, form_class=None):
if self.form_class:
form_class = self.get_form_class()
else:
form_class = model_to_modelform(self.model)
return form_class(**self.get_form_kwargs())
def get_context_data(self, **kwargs):
context = super(BaseBatchUploadView, self).get_context_data(**kwargs)
media_file_name = get_media_file_name(self, self.model)
if not hasattr(self, 'title'):
self.title = "Batch Upload %s"%(self.model._meta.verbose_name_plural.title())
if not hasattr(self, 'detail_fields'):
raise ImproperlyConfigured("Please specify detail_fields this view")
if not hasattr(self, 'default_fields'):
raise ImproperlyConfigured("Please specify default_fields this view")
if not hasattr(self, 'default_values'):
self.default_values = {}
if hasattr(self, 'instructions'):
context['instructions'] = self.instructions
context['app_name'] = self.model._meta.app_label.title()
context['model_name'] = self.model._meta.verbose_name.title()
context['model_name_plural'] = self.model._meta.verbose_name_plural.title()
context['title'] = self.title
context['media_file_name'] = media_file_name
context['default_fields'] = self.default_fields
context['detail_fields'] = self.detail_fields
context['default_values'] = json.dumps(self.default_values)
context['model_list_url'] = reverse('admin:app_list', kwargs={'app_label': self.model._meta.app_label})
context['model_app_url'] = reverse('admin:%s_%s_changelist'%(self.model._meta.app_label, self.model._meta.model_name))
context['model_add_url'] = reverse('admin:%s_%s_add'%(self.model._meta.app_label, self.model._meta.model_name))
context['adminform'] = adminForm = helpers.AdminForm(
self.get_form(),
list(self.get_fieldsets(self.request, None)),
self.get_prepopulated_fields(self.request, None),
self.get_readonly_fields(self.request, None),
model_admin=self
)
return context
def get_fieldsets(self, request, obj=None):
if not self.fields:
self.fields = list(set(self.default_fields + self.detail_fields))
return [(None, {'fields': self.fields})]
def get_prepopulated_fields(self, request, obj=None):
#Not implemented
return {}
def get_readonly_fields(self, request, obj=None):
#Not implemented
return []
class AdminBatchUploadView(BaseBatchUploadView):
@method_decorator(staff_member_required)
def dispatch(self, *args, **kwargs):
return super(AdminBatchUploadView, self).dispatch(*args, **kwargs)
|
d2c87894b1ed92ee8086e9c6a1f37291b266d78e
|
[
"Markdown",
"Python"
] | 5
|
Markdown
|
ninapavlich/django-batch-uploader
|
912503ab625a85b42721ef0b65d5ab5f0382aa3f
|
91b1f32ec5c15cf31da93213bb2cccdadd66bb7b
|
refs/heads/main
|
<repo_name>bomiteva/invoice-server<file_sep>/app/main.py
import os
from enum import Enum
from fastapi import FastAPI, UploadFile, File, HTTPException
from starlette.background import BackgroundTasks
from starlette.responses import FileResponse, JSONResponse
from app.process_invoice_file import ProcessInvoiceFile
from app.upload_invoice_file import UploadInvoiceFile
class TargetType(str, Enum):
xml = "xml"
csv = "csv"
BASE_DIR = "./processed_files"
TAGS_METADATA = [
{
"name": "Upload invoice",
"description": "Upload invoice file.",
},
{
"name": "Get invoice",
"description": "Get invoice file by buyer",
},
]
app = FastAPI(title="InvoiceApp", openapi_tags=TAGS_METADATA)
@app.post("/invoice", tags=["Upload invoice"], response_class=JSONResponse)
async def post_invoice(background_tasks: BackgroundTasks, file: UploadFile = File(...)):
"""This endpoint sends the csv file to the server.
Uploads the file and in the another process creates new files based on buyer.
Returns unique timestamp part of invoice directory"""
if file.content_type == "text/csv":
invoice_file = UploadInvoiceFile(file, BASE_DIR).save_upload_file()
# process the file in background task
process = ProcessInvoiceFile(invoice_file)
background_tasks.add_task(process.process_file)
else:
# throws an exception if the file is not csv
raise HTTPException(status_code=422, detail="Invalid file type")
return {"upload_id": invoice_file.timestamp}
@app.get("/invoice/{upload_id}/{buyer}", tags=["Get invoice"], response_class=FileResponse)
def get_invoice(upload_id: int, buyer: str, target_type: TargetType = TargetType.csv):
"""This endpoint returns xml or csv file by specific upload id, buyer and target type."""
if target_type != TargetType.csv and target_type != TargetType.xml:
raise HTTPException(status_code=422, detail="Target type not found")
file = f"{BASE_DIR}/invoices_{upload_id}/{buyer}.{target_type}"
if os.path.isfile(file):
return FileResponse(file)
else:
raise HTTPException(status_code=404, detail="File not found. Upload id or buyer invalid.")
<file_sep>/test/test_upload_invoice_file.py
import unittest
from unittest.mock import patch, mock_open
from fastapi import UploadFile
from app.upload_invoice_file import UploadInvoiceFile
class UploadInvoiceFileTest(unittest.TestCase):
"""Unit tests for UploadInvoiceFile class"""
def setUp(self) -> None:
self.invoice_file = UploadFile("test.csv")
self.upload_invoice = UploadInvoiceFile(upload_file=self.invoice_file, base_dir=".", timestamp=1123345555)
@patch('os.makedirs')
@patch('shutil.copyfileobj')
@patch('builtins.open', new_callable=mock_open, read_data="data")
def test_upload_file(self, mock_img_handler, mock_copy_object, mock_make_dir):
"""Tests """
self.upload_invoice.save_upload_file()
# assert if dir is created
mock_make_dir.assert_called_once_with('./invoices_1123345555', exist_ok=True)
# assert if opened file on write mode 'wb'
mock_img_handler.assert_called_once_with('./invoices_1123345555/test.csv', 'wb')
# assert if the specific content was written in file
mock_copy_object.assert_called_once()
<file_sep>/test/test_process_invoice_file.py
import base64
import unittest
from unittest.mock import patch, call, mock_open
import pandas
from pandas import Series
from app.errors import InvalidParamsError
from app.process_invoice_file import ProcessInvoiceFile
from app.upload_invoice_file import InvoiceFile
class ProcessInvoiceFileTest(unittest.TestCase):
"""Unit tests for ProcessInvoiceFile class"""
def setUp(self) -> None:
self.invoice_file = InvoiceFile(name="test.csv", dir=".", timestamp=1631351454)
self.process = ProcessInvoiceFile(self.invoice_file)
@patch('xml.etree.ElementTree.ElementTree.write')
@patch('pandas.DataFrame.to_csv')
@patch('pandas.read_csv')
def test_process_file_without_encode_img(self, mock_read_csv, mock_to_csv, mock_write_xml):
"""Tests creation of xml and csv files without image data."""
mock_read_csv.return_value = pandas.DataFrame({'buyer': Series(["South African Gold Mines Corp",
"South African Gold Mines Corp", "Traksas"]),
'image_name': Series(
["scanned_invoice_1.png", "", "scanned_invoice_3.png"])})
# invoke function
self.process.process_file()
# assert csv creation calls
mock_to_csv.assert_has_calls(
[call('./South African Gold Mines Corp.csv', index=False),
call('./Traksas.csv', index=False)])
# assert xml creation calls
mock_write_xml.assert_has_calls(
[call('./South African Gold Mines Corp.xml'),
call('./Traksas.xml')])
@patch('builtins.open', new_callable=mock_open)
@patch('xml.etree.ElementTree.ElementTree.write')
@patch('pandas.DataFrame.to_csv')
@patch('pandas.read_csv')
def test_process_file_with_encode_img(self, mock_read_csv, mock_to_csv, mock_write_xml, mock_img_handler):
"""Tests creation of xml and csv files with encoded image data."""
mock_read_csv.return_value = pandas.DataFrame({'buyer': Series(["South African Gold Mines Corp",
"South African Gold Mines Corp", "Traksas"]),
'image_name': Series(
["scanned_invoice_1.png", "", "scanned_invoice_3.png"]),
'invoice_image': Series([
"<KEY>
"",
"<KEY>])})
# invoke function
self.process.process_file()
# assert csv creation calls
mock_to_csv.assert_has_calls(
[call('./South African Gold Mines Corp.csv', index=False),
call('./Traksas.csv', index=False)])
# assert xml creation calls
mock_write_xml.assert_has_calls(
[call('./South African Gold Mines Corp.xml'),
call('./Traksas.xml')])
# assert img creation calls
mock_img_handler.assert_any_call('./scanned_invoice_1.png', 'wb')
mock_img_handler.assert_any_call('./scanned_invoice_3.png', 'wb')
self.assertEqual(mock_img_handler().write.call_count, 2)
@patch('pandas.read_csv')
def test_process_file_without_buyer(self, mock_read_csv):
"""Tests if InvalidParamsError throws when buyer missing"""
mock_read_csv.return_value = pandas.DataFrame({'image_name': Series(
["scanned_invoice_1.png", "", "scanned_invoice_3.png"])})
# assert if error is raises
with self.assertRaises(InvalidParamsError):
self.process.process_file()
@patch('builtins.open', new_callable=mock_open)
def test_save_img(self, mock_img_handler):
"""Tests save image encoded data."""
test_file_path = "test/file/path"
content = "<KEY>blwKrw<KEY>/"
self.process._save_image(test_file_path, content)
# assert if opened file on write mode 'wb'
mock_img_handler.assert_called_once_with(f"{self.process.invoice_file.dir}/{test_file_path}", 'wb')
# assert if the specific content was written in file
mock_img_handler().write.assert_called_once_with(base64.b64decode(content))
<file_sep>/requirements.txt
uvicorn==0.15.0
aiofiles==0.7.0
lxml==4.6.3
pandas==1.3.2
python-multipart==0.0.5
fastapi~=0.68.1
starlette~=0.14.2
pydantic~=1.8.2
numpy~=1.21.2<file_sep>/app/process_invoice_file.py
import base64
from xml.etree.ElementTree import Element, ElementTree, SubElement
import numpy as np
import pandas
from pandas import DataFrame
from app.errors import InvalidParamsError
from app.upload_invoice_file import InvoiceFile
class ProcessInvoiceFile:
"""Class that processes invoices, saves csv, xml and image in the InvoiceFile directory"""
def __init__(self, invoice_file: InvoiceFile):
self.invoice_file = invoice_file
def process_file(self):
"""Process InvoiceFile object - using pandas library for easier processing"""
# read DataFrame
data = pandas.read_csv(self.invoice_file.dir + "/" + self.invoice_file.name)
if "buyer" in data:
# group by buyer - like sql statement
for buyer, group in data.groupby(["buyer"]):
# create all cvs files
group.to_csv(f"{self.invoice_file.dir}/{buyer}.csv", index=False)
# create all xml files
self._process_xml(buyer, group)
else:
raise InvalidParamsError(message="Missing buyer in file")
def _process_xml(self, buyer: str, group: DataFrame) -> ElementTree:
"""Creates xml file with same csv format."""
# replace all nan with empty str
data_group = group.replace(np.nan, "", regex=True)
xml_root = Element("root")
xml_tree = ElementTree(xml_root)
# iterate over all rows
for _, row in data_group.iterrows():
xml_invoice = Element("invoice")
for k, v in row.items():
if k == "invoice_image":
if v != "": # save image only for existing data
self._save_image(row["image_name"], row["invoice_image"])
continue
xml_element = SubElement(xml_invoice, str(k))
xml_element.text = str(v)
xml_root.append(xml_invoice)
# save xml file in the same invoice directory
xml_tree.write(f"{self.invoice_file.dir}/{buyer}.xml")
return xml_tree
def _save_image(self, img_name: str, img_data: str):
"""Saves decoded image."""
with open(f"{self.invoice_file.dir}/{img_name}", "wb") as file_handler:
file_handler.write(base64.b64decode(img_data))
<file_sep>/test/test_main.py
from starlette.testclient import TestClient
from app.main import app
# Use the TestClient object the same way as you do with requests. Allows to send HTTP/1.1 requests easily.
client = TestClient(app)
def test_get_invoice():
"""Tests GET endpoint with buyer Axtronics and target type - xml"""
response = client.get("/invoice/1630952140/Axtronics?target_type=xml")
assert response.status_code == 200
assert response.text == "<root><invoice><buyer>Axtronics</buyer><image_name>f1.png</image_name><invoice_due_date>2020-10-23</invoice_due_date><invoice_number>AA-C56790</invoice_number><invoice_amount>305.45</invoice_amount><invoice_currency>USD</invoice_currency><invoice_status>NEW</invoice_status><supplier>Silver Logistics</supplier></invoice></root>"
def test_get_invalid_type_invoice():
"""Tests GET endpoint with buyer Axtronics and invalid target type - txt"""
response = client.get("/invoice/1630952140/Axtronics?target_type=txt")
assert response.status_code == 422
def test_post_invoice():
"""Tests POST endpoint with invoice file"""
response = client.post("/invoice", files={"file": ("invoice.csv", open("invoices.csv", "rb"), "text/csv")})
assert response.status_code == 200
assert "upload_id" in response.json()
def test_post_invalid_invoice():
"""Tests POST endpoint with invalid invoice file"""
response = client.post("/invoice", files={"file": ("invoice.html", open("invoices.csv", "rb"), "text/html")})
assert response.status_code == 422
def test_invalid_endpoint():
"""Tests server with invalid endpoint"""
response = client.get("/invoice/99")
assert response.status_code == 404
<file_sep>/README.md
# Invoice server
**Invoice-server** is a task that solves the following problem.
We need to write a system that parses and ingests the given (large) file and has the ability to
produce the two different output formats specified below.
As a user of that system I need to be able to configure or otherwise specify which of the two
output formats should be produced.
The new output formats will then later on be ingested by other systems - the integrity of data and
files has to stay. The later ingestion of the newly produced files is not part of this exercise.
The two destination formats should be:
1. CSV file of the original data but split up by 'buyer'. So if there are 10 different buyers overall
there should be 10 different output files. The rest of the data in the CSV should be arranged in
the same way as in the input file.
2. XML file of the original data split up by 'buyer'. The invoice image should not be part of the
XML data but the single invoice files should be extracted from the CSV and be placed into the file-system. The format of the XML should loosely follow the input CSV in regards to node-
names etc.You can decide any changes to folder-structure etc. of the output format.
## Implementation
The task is implemented with python using [FAST API](https://fastapi.tiangolo.com/).
The API is based on (and fully compatible with) the open standards for APIs: [OpenAPI](https://github.com/OAI/OpenAPI-Specification)
The pandas library is used for easy analysis of csv files. [pandas](https://pandas.pydata.org/docs/index.html) is an open source, BSD-licensed library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language.
## Deployment process
To build the docker container run:
```
docker build -t invoice-server .
```
After that you can run it by:
```
docker run -d --name invoice-server-container -p 80:80 invoice-server
```
## Using the API
The base path of the API is http://127.0.0.1/docs - if go to this page you will see the exposed API

- `POST /invoice` - uploads csv invoice and generates csv and xml based on buyer - returns unique upload id
- `GET /invoice/{upload_id}/{buyer}` - returns csv or xml file based on target type (csv or xml as query param) and upload id
## Troubleshooting
Get the id of the running container:
```
docker ps
```
Interactive mode, get access to a command prompt in a running container:
```
docker exec -it <container_id> sh
```
Go to `/app/processed_files/` - see generated files and images <br />

## API and Unit Testing
To run the tests:
1. install pytest with `pip install pytest`
2. Go to `test` dir and execute `pytest` (It will detect the files and tests automatically, execute them, and report the results back to you)
- test_main.py is an api test.
- test_process_invoice_file.py and test_upload_invoice_file.py are unit tests. <br />
## TODO
Here is a list of some items that could be further improved / added:
- I managed to upload a 3GB file. However, the library does have some limits and when dealing with big data files (more than 20GB) the recommended way to process them is in chunks.
- File processing could be triggered by a queue. This way we could have control over the number of files being processed and re-try processing if needed
- File format validation could be added
- Improve error handling
- Increase test coverage
- The test process should be an idempotent operation - delete the files after test process<file_sep>/app/errors.py
from http import HTTPStatus
from json import dumps
from typing import Optional
# Base HttpError class
class HttpError(Exception):
def __init__(
self,
status: int = HTTPStatus.INTERNAL_SERVER_ERROR,
code: str = "internal_failure",
message: str = "Internal Failure",
):
self.status = status
self.code = code
self.message = message
def __str__(self) -> str:
return dumps(self.to_dict())
def to_dict(self) -> dict:
return {"code": self.code, "message": self.message}
# Base Error classes
class IntentionalError(HttpError):
pass
class UnauthorizedError(HttpError): # Wrong or expired credentials
def __init__(self, error: str = "authorization_error", message: str = "Authorization error"):
super().__init__(HTTPStatus.UNAUTHORIZED, error, message)
class ForbiddenError(HttpError): # Authorization acknowledged, but insufficient rights
def __init__(self, error: str = "forbidden", message: str = "Not authorized to perform this action"):
super().__init__(HTTPStatus.FORBIDDEN, error, message)
class UnhandledEventError(HttpError):
def __init__(self, error: str = "unhandled_event", message: str = "Unhandled Event"):
super().__init__(HTTPStatus.NOT_IMPLEMENTED, error, message)
class NotFoundError(HttpError):
def __init__(self, error: str = "not_found", message: str = "Resource not found"):
super().__init__(HTTPStatus.NOT_FOUND, error, message)
class BadRequestError(HttpError):
def __init__(self, error: str = "bad_request", message: str = "Bad Request"):
super().__init__(HTTPStatus.BAD_REQUEST, error, message)
class ConflictError(HttpError):
def __init__(self, error: str = "conflict", message: str = "Conflict"):
super().__init__(HTTPStatus.CONFLICT, error, message)
class InvalidParamsError(HttpError):
def __init__(self, error: str = "invalid_params", message: str = "Invalid params"):
super().__init__(HTTPStatus.UNPROCESSABLE_ENTITY, error, message)
<file_sep>/app/upload_invoice_file.py
import os
import shutil
import time
from pydantic import BaseModel
from starlette.datastructures import UploadFile
# data object for invoice file
class InvoiceFile(BaseModel):
name: str
dir: str
timestamp: int
class UploadInvoiceFile:
"""Class creates base dir and uploads invoice file"""
def __init__(self, upload_file: UploadFile, base_dir: str, timestamp: int = int(time.time())):
self.upload_file = upload_file
self.filename = upload_file.filename
self.base_dir = base_dir
self.timestamp = timestamp
def save_upload_file(self) -> InvoiceFile:
"""Creates unique directory based on a timestamp and save the invoice in it."""
file_dir = f"{self.base_dir}/invoices_{str(self.timestamp)}"
file_path = file_dir + "/" + self.filename
try:
# creates file directory
self.create_file_dir(file_dir)
with open(file_path, "wb") as buffer:
shutil.copyfileobj(self.upload_file.file, buffer)
finally:
self.upload_file.file.close()
# return data object with invoice file information
return InvoiceFile(name=self.filename, dir=file_dir, timestamp=self.timestamp)
@staticmethod
def create_file_dir(file_dir: str) -> None:
os.makedirs(file_dir, exist_ok=True)
|
6fc5cdf5344d82e205482ecf049366837cd96fd5
|
[
"Markdown",
"Python",
"Text"
] | 9
|
Python
|
bomiteva/invoice-server
|
5b0fe949bfd413b2fbfc85ea2e333006d8edc556
|
ea38fb75e5ec9d1e8bd6f18b7f65e72667633954
|
refs/heads/master
|
<file_sep>import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class SampleClassOne {
// throws NullPointer Exception
public void invokeJackException() throws IOException{
Files.createFile(Paths.get("fileToDelete.txt"));
Path fileToDeletePath = Paths.get("fileToDelete_jdk7.txt");
Files.delete(fileToDeletePath);
}
//throws ArithmeticException
public void invokeJaneException(){
int n = 10.0/ 0;
}
}
<file_sep>package ru.sample;
/**
* Created by Alexander on 20.02.2016.
*/
public class SampleClassTwo {
public void packageExceptionMethod(){
throw new RuntimeException();
}
}
<file_sep>import ru.sample.SampleClassTwo;
import java.io.IOException;
/**
* Created by Alexander on 20.02.2016.
*/
public class Main {
public static void main(String[] args) throws IOException {
SampleClassOne sampleClassOne = new SampleClassOne();
SampleClassTwo sampleClassTwo = new SampleClassTwo();
// sampleClassTwo.packageExceptionMethod();
sampleClassOne.invokeJackException();
// sampleClassOne.invokeJaneException();
}
}
|
24d0ca7450f4ab9a976278e4330db473ee13eec0
|
[
"Java"
] | 3
|
Java
|
AlexanderDashkov/BlameWhoTest
|
1262674fb7b39597fc73adf6615f2ce9287bce50
|
2b6aeb8710c8c929d142a32b8e5f7a26d83529d7
|
refs/heads/master
|
<file_sep>/*
create database if not exists mcoffe default character set utf8 default collate utf8_general_ci;
create table if not exists estoque (cod smallint not null auto_increment,pro varchar (30) not null,pmp decimal(6,2),pre decimal(6,2) not null,qua smallint not null,qum tinyint,primary key (cod)) default charset = utf8;
create table if not exists cliente (id smallint not null primary key auto_increment,nome varchar(30)not null,cpf decimal(11,0)not null,cep decimal(8,0)not null,cpre decimal(6,2)) default charset = utf8;
create table if not exists comanda (id smallint not null primary key auto_increment,num varchar (3) not null,lpre decimal(6,2)) default charset = utf8;
create table if not exists venda (idCli smallint, idCom smallint, codPro smallint, pre decimal, dat date) default charset = utf8;
*/
create database mcoffe
default character set utf8 default
collate utf8_general_ci;
use mcoffe;
create table estoque (
cod smallint not null auto_increment,
pro varchar (30) not null,
pmp decimal(6,2),
pre decimal(6,2) not null,
qua smallint not null,
qum tinyint,
primary key (cod)
) default charset = utf8;
insert into estoque values (default,'Coca cola 2L','4.5','7','20','5'),
(default,'Dolly 2L','1.25','2.5','20','5'),
(default,'Torcida','.75','1.5','80','20'),
(default,'Ovo de pascoa','40','70','30','5');
select * from estoque;
create table cliente (
id smallint not null primary key auto_increment,
nome varchar(30)not null,
cpf decimal(11,0)not null,
cep decimal(8,0)not null,
cpro varchar(30),
cpre decimal(6,2),
cdat date
) default charset = utf8;
insert into cliente values ('1','a','12345678901','12345678','1','1','2016-1-1');
delete from mcoffe.cliente where id='1';
drop table cliente;
select * from estoque;
select * from estoque where pro like '%coc%';
create table comanda (
id smallint not null primary key auto_increment,
num varchar (3) not null,
lpro varchar(30),
lpre decimal(6,2),
ldat date
) default charset = utf8;
create table servico (
scod smallint not null primary key auto_increment,
ser varchar(30)not null,
spre decimal(6,2)
) default charset = utf8;
select * from servico;
insert into servico values (default,'Marmita','12'),
(default,'Prato Feito','12'),
(default,'Suco','2'),
(default,'Selfservice','25'),
(default,'Quilo','5');
use mcoffe;
select * from cliente;
select * from comanda;
insert into cliente (id,nome,cpf,cep,cpro,cpre,cdat)
values(default,'anderson','44942030846','06624170','','0','2016-03-24'),
(default,'costa','44942030800','06624171','','0','2016-03-24'),
(default,'silva','00042030846','08824170','','0','2016-03-24'),
(default,'adelmo','16425715553','06624170','','0','2016-03-24');
alter table comanda
drop ldat;
insert into comanda values(default,'001','0','2016-03-24',''),
(default,'002','0','2016-03-24',''),
(default,'003','0','2016-03-24',''),
(default,'004','0','2016-03-24','');
select * from cliente where nome like 'anderson';
select * from cliente ;
UPDATE `mcoffe`.`cliente` SET `nome`='Adelmo' WHERE `id`='5';
update mcoffe.cliente set cpre='1' where nome='anderson';<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 controle;
import java.sql.*;
/**
*
* @author acsgs
*/
public class Conexao {
public static String erro="";
public static ResultSet rs;
public static Statement st;
public static Connection con;
public static void conexao() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/software_1_1_1","root","1234");
st = con.createStatement();
} catch (Exception ex) {erro=""+ex;}}
public static void disconexao(){
try {
con.close();
} catch (SQLException e) {erro=""+e;}}}<file_sep># Mcoffe
Controle de estoque e vendas
Na pasta 'Version 2' coloquei a última versão da aplicação que usei para aprofundar meus conhecimentos em java, com Mcoffe.jar no diretório build pode-se ver o layout do projeto com o arquivo '.jar'.
Na pasta 'Version 1' eu mostro a primeira versão desse projeto bem no início das minhas aplicações.
<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 interfaces;
import static ferramentas.Conexao.*;
import java.sql.PreparedStatement;
import javax.swing.JOptionPane;
/**
*
* @author AndersonCS
*/
public class Estoque extends javax.swing.JFrame {
private int cod = 0;
/** Creates new form Estoque */
public Estoque() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
txtPro = new javax.swing.JTextField();
lbl = new javax.swing.JLabel();
lbl1 = new javax.swing.JLabel();
txtQua = new javax.swing.JTextField();
lbl2 = new javax.swing.JLabel();
txtPre = new javax.swing.JTextField();
lbl4 = new javax.swing.JLabel();
txtQum = new javax.swing.JTextField();
txtPmp = new javax.swing.JTextField();
lbl5 = new javax.swing.JLabel();
btnAtualizar = new javax.swing.JButton();
btnGravar = new javax.swing.JButton();
btnVoltar = new javax.swing.JButton();
btnPesquisar = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
txtCodigo = new javax.swing.JTextField();
btnApagar = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
txtPro.setHorizontalAlignment(javax.swing.JTextField.CENTER);
lbl.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl.setText("Descrição do Produto");
lbl1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl1.setText("Quantidade em Estoque");
txtQua.setHorizontalAlignment(javax.swing.JTextField.CENTER);
lbl2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl2.setText("Preço de Venda");
txtPre.setHorizontalAlignment(javax.swing.JTextField.CENTER);
lbl4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl4.setText("Preço da matéria Prima");
txtQum.setHorizontalAlignment(javax.swing.JTextField.CENTER);
txtPmp.setHorizontalAlignment(javax.swing.JTextField.CENTER);
lbl5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl5.setText("Quantidade Miníma");
btnAtualizar.setText("Atualizar");
btnAtualizar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAtualizarActionPerformed(evt);
}
});
btnGravar.setText("Gravar");
btnGravar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnGravarActionPerformed(evt);
}
});
btnVoltar.setText("Voltar");
btnVoltar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnVoltarActionPerformed(evt);
}
});
btnPesquisar.setText("Pesquisar");
btnPesquisar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnPesquisarActionPerformed(evt);
}
});
jLabel1.setText("Código do produto");
txtCodigo.setHorizontalAlignment(javax.swing.JTextField.CENTER);
btnApagar.setText("Apagar");
btnApagar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnApagarActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(btnPesquisar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnAtualizar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnGravar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnApagar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnVoltar))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl2)
.addComponent(txtPre, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl1)
.addComponent(txtQua, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl)
.addComponent(txtPro, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtQum, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl4)
.addComponent(txtPmp, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl5))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(lbl4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtPmp, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(lbl5)
.addGap(18, 18, 18)
.addComponent(txtQum, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(lbl)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtPro, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(lbl2)
.addGap(18, 18, 18)
.addComponent(txtPre, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(lbl1)
.addGap(18, 18, 18)
.addComponent(txtQua, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnPesquisar)
.addComponent(btnAtualizar)
.addComponent(btnGravar)
.addComponent(btnVoltar)
.addComponent(btnApagar))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void btnVoltarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVoltarActionPerformed
// TODO add your handling code here:
PaginaInicial.pagInc.setVisible(true);
Estoque.this.dispose();
}//GEN-LAST:event_btnVoltarActionPerformed
private void btnGravarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGravarActionPerformed
// TODO add your handling code here:
if(!(txtPmp.getText().matches("([0-9]*)([.]?)([0-9]{0,2})")&&txtPre.getText().matches("([0-9]*)([.]?)([0-9]{0,2})")
&&txtQua.getText().matches("[0-9]+")&&txtQum.getText().matches("[0-9]+"))||txtPro.getText().isEmpty()){
JOptionPane.showMessageDialog(rootPane, "Preencha todos os campos corretamente!");
}else{
if(JOptionPane.showConfirmDialog(rootPane, "Gravar produto?") == 0){
try{
cr = cs.executeQuery("select * from estoque where pro like '"+txtPro.getText()+"';");
if(cr.first()){
JOptionPane.showMessageDialog(rootPane, "Já existe!");
}else{
String sql = "insert into estoque (pro,pmp,pre,qua,qum) values ('%s','%s','%s','%s','%s');";
cs.executeUpdate(String.format(sql, txtPro.getText(), txtPmp.getText(), txtPre.getText(), txtQua.getText(), txtQum.getText()));
JOptionPane.showMessageDialog(rootPane, "Salvo com sucesso!");
}
}catch(Exception e){JOptionPane.showMessageDialog(rootPane, "Erro ao gravar!");}
}
}//*/
}//GEN-LAST:event_btnGravarActionPerformed
private void btnPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPesquisarActionPerformed
// TODO add your handling code here:
txtPmp.setText("");
txtPre.setText("");
txtQua.setText("");
txtQum.setText("");
cod = 0;
if(txtCodigo.getText().isEmpty() && txtPro.getText().isEmpty()){
JOptionPane.showMessageDialog(rootPane, "Preencha os campos: Codigo ou Descrição!");
}else{
try{
if(!txtCodigo.getText().isEmpty()){
cr = cs.executeQuery("select * from estoque where cod like '%"+txtCodigo.getText()+"%';");
if(!cr.first()){
txtCodigo.setText("");
txtPro.setText("");
cod = 0;
JOptionPane.showMessageDialog(rootPane, "Código do produto\nnão encontrado!");
}
}else{
cr = cs.executeQuery("select * from estoque where pro like '%"+txtPro.getText()+"%';");
if(!cr.first()){
txtPro.setText("");
txtCodigo.setText("");
cod = 0;
JOptionPane.showMessageDialog(rootPane, "Nome do produto\nnão encontrado!");
}
}
if(cr.first()){
txtCodigo.setText(cr.getString("cod"));
txtPro.setText(cr.getString("pro"));
txtPmp.setText(cr.getString("pmp"));
txtPre.setText(cr.getString("pre"));
txtQua.setText(cr.getString("qua"));
txtQum.setText(cr.getString("qum"));
cod = cr.getInt("cod");
}
}catch(Exception e){}
}
}//GEN-LAST:event_btnPesquisarActionPerformed
private void btnAtualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAtualizarActionPerformed
// TODO add your handling code here:
if(!(txtPmp.getText().matches("([0-9]*)([.]?)([0-9]{0,2})")&&txtPre.getText().matches("([0-9]*)([.]?)([0-9]{0,2})")
&&txtQua.getText().matches("[0-9]+")&&txtQum.getText().matches("[0-9]+"))
||txtPro.getText().isEmpty()||txtCodigo.getText().isEmpty()){
JOptionPane.showMessageDialog(rootPane, "Preencha todos os campos corretamente!");
}else{
if(JOptionPane.showConfirmDialog(rootPane, "Atualizar produto?") == 0){
try{
if(cod != 0){
cs.executeUpdate("update estoque set pmp = '"+txtPmp.getText()+"', pre = '"+txtPre.getText()+"', qua = '"+txtQua.getText()+"', qum = '"+txtQum.getText()+"' where cod = '"+cod+"';");
JOptionPane.showMessageDialog(rootPane, "Atualizado com sucesso!");
}else{
JOptionPane.showMessageDialog(rootPane, "Erro ao atualizar!");
}
}catch(Exception e){JOptionPane.showMessageDialog(rootPane, "Erro ao atualizar!");}
}
}
}//GEN-LAST:event_btnAtualizarActionPerformed
private void btnApagarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnApagarActionPerformed
// TODO add your handling code here:
if(JOptionPane.showConfirmDialog(rootPane, "Apagar produto?") == 0){
try{
if(cod != 0){
cs.executeUpdate("delete from mcoffe.estoque where cod = "+cod+";");
txtCodigo.setText("");
txtPmp.setText("");
txtPre.setText("");
txtPro.setText("");
txtQua.setText("");
txtQum.setText("");
cod = 0;
JOptionPane.showMessageDialog(rootPane, "Deletado com sucesso!");
}else{
JOptionPane.showMessageDialog(rootPane, "Erro ao deletar!");
}
}catch(Exception e){JOptionPane.showMessageDialog(rootPane, "Erro ao deletar!");}
}
}//GEN-LAST:event_btnApagarActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Estoque.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Estoque.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Estoque.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Estoque.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Estoque().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnApagar;
private javax.swing.JButton btnAtualizar;
private javax.swing.JButton btnGravar;
private javax.swing.JButton btnPesquisar;
private javax.swing.JButton btnVoltar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel lbl;
private javax.swing.JLabel lbl1;
private javax.swing.JLabel lbl2;
private javax.swing.JLabel lbl4;
private javax.swing.JLabel lbl5;
private javax.swing.JTextField txtCodigo;
private javax.swing.JTextField txtPmp;
private javax.swing.JTextField txtPre;
private javax.swing.JTextField txtPro;
private javax.swing.JTextField txtQua;
private javax.swing.JTextField txtQum;
// End of variables declaration//GEN-END:variables
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modelo;
/**
*
* @author acsgs
*/
public class Fucionario {
private short idfuc;
private String nofuc;
private String cpfuc;
private String cefuc;
private String rufuc;
private String cifuc;
private String sifuc;
private String bafuc;
private String tefuc;
private float safuc;
/**
* @return the idfuc
*/
public short getIdfuc() {
return idfuc;
}
/**
* @param idfuc the idfuc to set
*/
public void setIdfuc(short idfuc) {
this.idfuc = idfuc;
}
/**
* @return the nofuc
*/
public String getNofuc() {
return nofuc;
}
/**
* @param nofuc the nofuc to set
*/
public void setNofuc(String nofuc) {
this.nofuc = nofuc;
}
/**
* @return the cpfuc
*/
public String getCpfuc() {
return cpfuc;
}
/**
* @param cpfuc the cpfuc to set
*/
public void setCpfuc(String cpfuc) {
this.cpfuc = cpfuc;
}
/**
* @return the cefuc
*/
public String getCefuc() {
return cefuc;
}
/**
* @param cefuc the cefuc to set
*/
public void setCefuc(String cefuc) {
this.cefuc = cefuc;
}
/**
* @return the rufuc
*/
public String getRufuc() {
return rufuc;
}
/**
* @param rufuc the rufuc to set
*/
public void setRufuc(String rufuc) {
this.rufuc = rufuc;
}
/**
* @return the cifuc
*/
public String getCifuc() {
return cifuc;
}
/**
* @param cifuc the cifuc to set
*/
public void setCifuc(String cifuc) {
this.cifuc = cifuc;
}
/**
* @return the sifuc
*/
public String getSifuc() {
return sifuc;
}
/**
* @param sifuc the sifuc to set
*/
public void setSifuc(String sifuc) {
this.sifuc = sifuc;
}
/**
* @return the bafuc
*/
public String getBafuc() {
return bafuc;
}
/**
* @param bafuc the bafuc to set
*/
public void setBafuc(String bafuc) {
this.bafuc = bafuc;
}
/**
* @return the tefuc
*/
public String getTefuc() {
return tefuc;
}
/**
* @param tefuc the tefuc to set
*/
public void setTefuc(String tefuc) {
this.tefuc = tefuc;
}
/**
* @return the safuc
*/
public float getSafuc() {
return safuc;
}
/**
* @param safuc the safuc to set
*/
public void setSafuc(float safuc) {
this.safuc = safuc;
}
}
<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 modelo;
/**
*
* @author acsgs
*/
public class Olerite {
private short idole;
private short idfuc;
private String daole;
private String siole;
private float vaole;
/**
* @return the idole
*/
public short getIdole() {
return idole;
}
/**
* @param idole the idole to set
*/
public void setIdole(short idole) {
this.idole = idole;
}
/**
* @return the idfuc
*/
public short getIdfuc() {
return idfuc;
}
/**
* @param idfuc the idfuc to set
*/
public void setIdfuc(short idfuc) {
this.idfuc = idfuc;
}
/**
* @return the daole
*/
public String getDaole() {
return daole;
}
/**
* @param daole the daole to set
*/
public void setDaole(String daole) {
this.daole = daole;
}
/**
* @return the siole
*/
public String getSiole() {
return siole;
}
/**
* @param siole the siole to set
*/
public void setSiole(String siole) {
this.siole = siole;
}
/**
* @return the vaole
*/
public float getVaole() {
return vaole;
}
/**
* @param vaole the vaole to set
*/
public void setVaole(float vaole) {
this.vaole = vaole;
}
}
<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 visao;
import controle.ControleCaixa;
import controle.Data;
import javax.swing.ListSelectionModel;
import modelo.Cliente;
import modelo.Comanda;
import modelo.Estoque;
import modelo.Vendas;
/**
*
* @author acsgs
*/
public class Caixa extends javax.swing.JFrame {
int clicom=1,outro,com=1,cli=1,out=1,SQL;
String outro1="Outro";
Comanda comanda = new Comanda();
Cliente cliente = new Cliente();
Estoque estoque = new Estoque();
Vendas vendas = new Vendas();
ControleCaixa concai = new ControleCaixa();
/**
* Creates new form Caixa
*/
public Caixa() {
initComponents();
Data.data();
lblData.setText(Data.data);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
lblData = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
txtCliente = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
tabelaCaixa = new javax.swing.JTable();
jLabel4 = new javax.swing.JLabel();
lblTotal = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
btnPesquisarPro = new javax.swing.JButton();
jLabel8 = new javax.swing.JLabel();
btnConfirmarcom = new javax.swing.JButton();
btnImprimir = new javax.swing.JButton();
jLabel10 = new javax.swing.JLabel();
txtValorpag = new javax.swing.JTextField();
btnConfirmarpag = new javax.swing.JButton();
lblTroco = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
btnCliente = new javax.swing.JToggleButton();
btnComanda = new javax.swing.JToggleButton();
btnPesquisarcli = new javax.swing.JButton();
txtProduto = new javax.swing.JTextField();
lblCP = new javax.swing.JLabel();
txtValorPro = new javax.swing.JTextField();
btnOutro = new javax.swing.JToggleButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Caixa");
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jLabel1.setFont(new java.awt.Font("Tahoma", 3, 36)); // NOI18N
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("Caixa");
jLabel1.setToolTipText("");
lblData.setFont(new java.awt.Font("Tahoma", 3, 14)); // NOI18N
lblData.setName(""); // NOI18N
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel3.setText("CPF/CNJP");
txtCliente.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
txtCliente.setEnabled(false);
txtCliente.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
txtClienteMouseClicked(evt);
}
});
tabelaCaixa.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{},
{},
{},
{}
},
new String [] {
}
));
tabelaCaixa.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
tabelaCaixa.setOpaque(false);
tabelaCaixa.setShowHorizontalLines(false);
tabelaCaixa.setShowVerticalLines(false);
jScrollPane1.setViewportView(tabelaCaixa);
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel4.setText("Total");
lblTotal.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
lblTotal.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
jLabel6.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel6.setText("Produto");
btnPesquisarPro.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
btnPesquisarPro.setText("Pesquisar");
btnPesquisarPro.setEnabled(false);
btnPesquisarPro.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnPesquisarProActionPerformed(evt);
}
});
jLabel8.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel8.setText("Valor do produto");
btnConfirmarcom.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
btnConfirmarcom.setText("Confirmar compra");
btnConfirmarcom.setEnabled(false);
btnConfirmarcom.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnConfirmarcomActionPerformed(evt);
}
});
btnImprimir.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
btnImprimir.setText("Imprimir");
btnImprimir.setEnabled(false);
jLabel10.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel10.setText("Valor pago");
txtValorpag.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
txtValorpag.setEnabled(false);
txtValorpag.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
txtValorpagMouseClicked(evt);
}
});
btnConfirmarpag.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
btnConfirmarpag.setText("Confirmar pagamento");
btnConfirmarpag.setEnabled(false);
btnConfirmarpag.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnConfirmarpagActionPerformed(evt);
}
});
lblTroco.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
lblTroco.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
jLabel12.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel12.setText("Troco");
btnCliente.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
btnCliente.setText("Cliente");
btnCliente.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnClienteActionPerformed(evt);
}
});
btnComanda.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
btnComanda.setText("Comanda");
btnComanda.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnComandaActionPerformed(evt);
}
});
btnPesquisarcli.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
btnPesquisarcli.setText("Pesquisar");
btnPesquisarcli.setEnabled(false);
btnPesquisarcli.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnPesquisarcliActionPerformed(evt);
}
});
txtProduto.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
txtProduto.setEnabled(false);
txtProduto.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
txtProdutoMouseClicked(evt);
}
});
lblCP.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
lblCP.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblCP.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
txtValorPro.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
txtValorPro.setEnabled(false);
btnOutro.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
btnOutro.setText("Outro");
btnOutro.setEnabled(false);
btnOutro.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnOutroActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(25, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnConfirmarcom, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, 187, Short.MAX_VALUE)
.addComponent(txtValorpag))
.addGap(18, 18, 18)
.addComponent(btnConfirmarpag))
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 503, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(btnImprimir, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtProduto, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(btnPesquisarPro)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnOutro)
.addGap(12, 12, 12)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE)
.addComponent(jLabel12, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE)
.addComponent(jLabel8, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE)
.addComponent(lblTotal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtValorPro)
.addComponent(lblTroco, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 807, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 807, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(btnCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnComanda, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(lblCP, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnPesquisarcli))))
.addComponent(lblData, javax.swing.GroupLayout.PREFERRED_SIZE, 832, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)
.addComponent(lblData, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnComanda, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(7, 7, 7)
.addComponent(txtCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(14, 14, 14)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblCP, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnPesquisarcli, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(113, 113, 113)
.addComponent(jLabel6)
.addGap(10, 10, 10)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtProduto, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnPesquisarPro, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnConfirmarcom)
.addComponent(btnImprimir, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jLabel10)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtValorpag, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnConfirmarpag, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(30, 30, 30)
.addComponent(jLabel8)
.addGap(9, 9, 9)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(2, 2, 2)
.addComponent(txtValorPro, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(btnOutro, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(78, 78, 78)
.addComponent(jLabel12)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblTroco, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(25, Short.MAX_VALUE))
);
setSize(new java.awt.Dimension(873, 670));
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void btnPesquisarcliActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPesquisarcliActionPerformed
// TODO add your handling code here:
short txt=1;
String cp="";
if(clicom==1){
cliente.setNocli(txtCliente.getText());
concai.pesquisarcli(cliente);
txtCliente.setText(cliente.getNocli());
lblCP.setText(cliente.getCpcli());
btnPesquisarPro.setEnabled(false);
SQL = cliente.getIdcli();
}else{
try{
comanda.setNucom(txtCliente.getText());
concai.pesquisarcom(comanda);
txtCliente.setText(String.valueOf(comanda.getNucom()));
lblCP.setText("-");
btnPesquisarPro.setEnabled(false);
}catch(Exception e){
clicom=2;
txtCliente.setText("Preencha corretamente");
txtProduto.setEnabled(false);
lblCP.setText(null);
btnOutro.setEnabled(false);
btnPesquisarPro.setEnabled(false);
}
}
if(lblCP.getText()!=null){
btnImprimir.setEnabled(true);
txtProduto.setEnabled(true);
btnOutro.setEnabled(true);
txtValorpag.setEnabled(true);
tabelaCaixaPrencher();
}
}//GEN-LAST:event_btnPesquisarcliActionPerformed
private void txtClienteMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtClienteMouseClicked
// TODO add your handling code here:
txtCliente.selectAll();
}//GEN-LAST:event_txtClienteMouseClicked
private void txtProdutoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtProdutoMouseClicked
// TODO add your handling code here:
txtProduto.selectAll();
btnPesquisarPro.setEnabled(true);
}//GEN-LAST:event_txtProdutoMouseClicked
private void btnClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClienteActionPerformed
// TODO add your handling code here:
if(cli==1){
btnComanda.setSelected(false);
clicom=1;
btnPesquisarcli.setEnabled(true);
txtCliente.setEnabled(true);
lblCP.setText(null);
txtProduto.setEnabled(false);
btnOutro.setEnabled(false);
btnPesquisarPro.setEnabled(false);
btnImprimir.setEnabled(false);
txtValorpag.setEnabled(false);
btnConfirmarpag.setEnabled(false);
cli=2;
com=1;
}else{
btnPesquisarcli.setEnabled(false);
txtCliente.setEnabled(false);
lblCP.setText(null);
txtProduto.setEnabled(false);
btnOutro.setEnabled(false);
btnPesquisarPro.setEnabled(false);
btnImprimir.setEnabled(false);
txtValorpag.setEnabled(false);
btnConfirmarpag.setEnabled(false);
cli=1;
com=1;
}
}//GEN-LAST:event_btnClienteActionPerformed
private void btnComandaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnComandaActionPerformed
// TODO add your handling code here:
if(com==1){
btnCliente.setSelected(false);
clicom=2;
btnPesquisarcli.setEnabled(true);
txtCliente.setEnabled(true);
lblCP.setText(null);
txtProduto.setEnabled(false);
btnOutro.setEnabled(false);
btnPesquisarPro.setEnabled(false);
btnImprimir.setEnabled(false);
txtValorpag.setEnabled(false);
btnConfirmarpag.setEnabled(false);
com=2;
cli=1;
}else{
btnPesquisarcli.setEnabled(false);
txtCliente.setEnabled(false);
lblCP.setText(null);
txtProduto.setEnabled(false);
btnOutro.setEnabled(false);
btnPesquisarPro.setEnabled(false);
btnImprimir.setEnabled(false);
txtValorpag.setEnabled(false);
btnConfirmarpag.setEnabled(false);
com=1;
cli=1;
}
}//GEN-LAST:event_btnComandaActionPerformed
private void btnOutroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOutroActionPerformed
// TODO add your handling code here:
if(out==1){
txtValorPro.setEnabled(true);
btnConfirmarcom.setEnabled(true);
txtProduto.setEnabled(false);
btnPesquisarPro.setEnabled(false);
outro=1;
out=2;
}else{
txtValorPro.setEnabled(false);
btnConfirmarcom.setEnabled(false);
txtProduto.setEnabled(true);
btnPesquisarPro.setEnabled(false);
outro=0;
out=1;
}
}//GEN-LAST:event_btnOutroActionPerformed
private void txtValorpagMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtValorpagMouseClicked
// TODO add your handling code here:
btnConfirmarpag.setEnabled(true);
}//GEN-LAST:event_txtValorpagMouseClicked
private void btnPesquisarProActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPesquisarProActionPerformed
// TODO add your handling code here:
if("".equals(txtProduto.getText())){
txtProduto.setText("Vazio");
}else{
estoque.setNopro(txtProduto.getText());
concai.pesquisarPro(estoque);
txtProduto.setText(estoque.getNopro());
txtValorPro.setText(String.valueOf(estoque.getPrpro()));
txtValorPro.setEnabled(false);
btnConfirmarcom.setEnabled(true);
}
}//GEN-LAST:event_btnPesquisarProActionPerformed
private void btnConfirmarcomActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConfirmarcomActionPerformed
// TODO add your handling code here:
int conf;
if(clicom==1){
if(outro==1){
conf = 1;
vendas.setPrven(Float.parseFloat(txtValorPro.getText()));
concai.confirmarCompraCli(vendas,estoque,cliente,conf);
btnPesquisarcliActionPerformed(evt);
btnPesquisarPro.setEnabled(false);
txtProduto.setEnabled(false);
}else{
conf = 2;
concai.confirmarCompraCli(vendas,estoque,cliente,conf);
btnPesquisarcliActionPerformed(evt);
}
}else{
if(outro==1){
conf = 1;
vendas.setPrven(Float.parseFloat(txtValorPro.getText()));
concai.confirmarCompraCom(vendas,estoque,comanda,conf);
btnPesquisarcliActionPerformed(evt);
btnPesquisarPro.setEnabled(false);
txtProduto.setEnabled(false);
}else{
conf = 2;
concai.confirmarCompraCom(vendas,estoque,comanda,conf);
btnPesquisarcliActionPerformed(evt);
}
}
}//GEN-LAST:event_btnConfirmarcomActionPerformed
private void btnConfirmarpagActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConfirmarpagActionPerformed
// TODO add your handling code here:
if("".equals(txtValorpag.getText())){
txtValorpag.setText("Vazio");
}else{
float valorpag = Float.parseFloat(txtValorpag.getText());
concai.confirmarPagamento(valorpag);
}
}//GEN-LAST:event_btnConfirmarpagActionPerformed
private void tabelaCaixaPrencher(){
if(clicom==1){
concai.preencherTabelaCaixaCli(SQL);
tabelaCaixa.setModel(concai.tabela);
tabelaCaixa.getColumnModel().getColumn(0).setPreferredWidth(501);
tabelaCaixa.getColumnModel().getColumn(0).setResizable(true);
tabelaCaixa.getColumnModel().getColumn(1).setPreferredWidth(200);
tabelaCaixa.getColumnModel().getColumn(1).setResizable(true);
tabelaCaixa.getColumnModel().getColumn(2).setPreferredWidth(100);
tabelaCaixa.getColumnModel().getColumn(2).setResizable(true);
tabelaCaixa.getTableHeader().setReorderingAllowed(false);
tabelaCaixa.setAutoResizeMode(tabelaCaixa.AUTO_RESIZE_OFF);
tabelaCaixa.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
String tot=String.format("%.2f", concai.total);
lblTotal.setText(" R$ "+tot);
}else if(clicom==2){
concai.preencherTabelaCaixaCom(comanda);
tabelaCaixa.setModel(concai.tabela);
tabelaCaixa.getColumnModel().getColumn(0).setPreferredWidth(501);
tabelaCaixa.getColumnModel().getColumn(0).setResizable(true);
tabelaCaixa.getColumnModel().getColumn(1).setPreferredWidth(200);
tabelaCaixa.getColumnModel().getColumn(1).setResizable(true);
tabelaCaixa.getColumnModel().getColumn(2).setPreferredWidth(100);
tabelaCaixa.getColumnModel().getColumn(2).setResizable(true);
tabelaCaixa.getTableHeader().setReorderingAllowed(false);
tabelaCaixa.setAutoResizeMode(tabelaCaixa.AUTO_RESIZE_OFF);
tabelaCaixa.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
String tot=String.format("%.2f", concai.total);
lblTotal.setText(" R$ "+tot);
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Caixa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Caixa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Caixa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Caixa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Caixa().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JToggleButton btnCliente;
private javax.swing.JToggleButton btnComanda;
private javax.swing.JButton btnConfirmarcom;
private javax.swing.JButton btnConfirmarpag;
private javax.swing.JButton btnImprimir;
private javax.swing.JToggleButton btnOutro;
private javax.swing.JButton btnPesquisarPro;
private javax.swing.JButton btnPesquisarcli;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel8;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel lblCP;
private javax.swing.JLabel lblData;
private javax.swing.JLabel lblTotal;
private javax.swing.JLabel lblTroco;
private javax.swing.JTable tabelaCaixa;
private javax.swing.JTextField txtCliente;
private javax.swing.JTextField txtProduto;
private javax.swing.JTextField txtValorPro;
private javax.swing.JTextField txtValorpag;
// End of variables declaration//GEN-END:variables
}
|
ef7d25bd37fffd732d8c79f5358ed91b8b8799bb
|
[
"Java",
"SQL",
"Markdown"
] | 7
|
SQL
|
AsonCS/Mcoffe
|
b24614d335b90ee15c3034dfdd1196c01755c53f
|
2bbad81b6a40a1d11de1476aec816ee1a837cba4
|
refs/heads/master
|
<repo_name>lukesmyth9/Ass1PartA<file_sep>/src/test/java/Tester.java
import com.mycompany.softwareengassignment1.*;
import org.junit.*;
public class Tester {
/**
* @param args the command line arguments
*/
@Test
public void Test(){
Student student = new Student("Luke", 21, "2002-01-01", 173);
//System.out.println("Username= " + student.getUsername());
Assert.assertEquals("Luke21", student.getUsername()); //checks if getUsername works as it should
}
}<file_sep>/src/main/java/com/mycompany/softwareengassignment1/Module.java
/*
* 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 com.mycompany.softwareengassignment1;
import java.util.ArrayList;
/**
*
* @author lukej
*/
public class Module {
String moduleName;
String ID;
ArrayList<Course> courses = new ArrayList<Course>();
ArrayList<Student> students = new ArrayList<Student>();
public Module(String moduleName, String ID)//allows to add modulename and id
{
this.moduleName = moduleName;
this.ID = ID;
//this.students = students;
//this.courses = courses;
}
//Mutators
public void setModuleName(String moduleName)
{
this.moduleName = moduleName;
}
public void setID(String ID)
{
this.ID = ID;
}
//Accessors
public String getModuleName()
{
return this.moduleName;
}
public String getID()
{
return this.ID;
}
public void addStudentToModule(Student student)
{
students.add(student);//add student to module student to arraylist
}
public void addCourseToModule(Course course)
{
courses.add(course);//adds course to module
}
public void printStudents()//prints student iinfo
{
System.out.println("Students enrolled in this module: ");
for (Student student : students)
{
System.out.println("Name: " + student.getName() + " Username: " + student.getUsername());
}
}
public void printCourses()//prints courses
{
System.out.println("Courses that are in this module: ");
for (Course course : courses)
{
System.out.println("Name: " + course.getCourseName());
}
}
public void moduleInformation(Module module)//prints module info
{
System.out.println("Module Name: " + module.getModuleName() + "\nModule ID: " + module.getID() + "\n");
module.printCourses();
System.out.println("\n");
module.printStudents();
}
}
|
ac951c2b0b95089a7b6cb9c23fba9fcba3db2650
|
[
"Java"
] | 2
|
Java
|
lukesmyth9/Ass1PartA
|
3bd1f8c9b3354434e6397dece92b57887cdb11fe
|
3dc63ec4d31e85a06310d73868c4c1bd123978af
|
refs/heads/master
|
<repo_name>lizvdk/LA-good-eats<file_sep>/spec/features/homepage_displays_all_restaurants_spec.rb
require 'rails_helper'
feature "Homepage displays all resturants", %q{
As a user
I want see a list of all the resturants
So that I can choose a resturant that looks interesting
Acceptance Criteria:
- [x] /resturants displays all the resturants
} do
scenario "user visits '/resturants'" do
r1 = FactoryGirl.create(:restaurant)
r2 = FactoryGirl.create(:restaurant)
r3 = FactoryGirl.create(:restaurant)
visit restaurants_path
expect(page). to have_content "All the Restaurants!"
expect(page). to have_content r1.name
expect(page). to have_content r2.name
expect(page). to have_content r3.name
end
end
<file_sep>/app/models/review.rb
class Review < ActiveRecord::Base
belongs_to :restaurant
validates :body,
presence: true,
uniqueness: true
validates :rating,
presence: true,
inclusion: { in: 1..5}
end
<file_sep>/spec/features/user_adds_new_restaurant_spec.rb
require 'rails_helper'
feature "User adds a restaurant", %q{
As a user
I want to add a new restaurant
So that I can share info with others
Acceptance Criteria:
- [x] /restaurants/new displays a form for creating a new restaurant
} do
scenario "with valid attributes" do
restaurant = FactoryGirl.build(:restaurant)
visit root_path
click_on "Add a Restaurant"
fill_in "Name", with: restaurant.name
fill_in "Address", with: restaurant.address
fill_in "City", with: restaurant.city
fill_in "State", with: restaurant.state
fill_in "Zip", with: restaurant.zip
fill_in "Description", with: restaurant.description
fill_in "Category", with: restaurant.category
click_on "Submit"
expect(page).to have_content "Success! Your restaurant info has been added."
expect(page).to have_content restaurant.name
expect(page).to have_content restaurant.address
expect(page).to have_content restaurant.city
expect(page).to have_content restaurant.state
expect(page).to have_content restaurant.zip
expect(page).to have_content restaurant.description
expect(page).to have_content restaurant.category
end
scenario "with invalid attributes" do
visit root_path
click_on "Add a Restaurant"
click_on "Submit"
expect(page).to have_content "ERRAH"
expect(page).to have_content "Name can't be blank"
expect(page).to have_content "Address can't be blank"
expect(page).to have_content "City can't be blank"
expect(page).to have_content "State can't be blank"
expect(page).to have_content "Zip can't be blank"
end
end
<file_sep>/spec/support/factories.rb
FactoryGirl.define do
factory :restaurant do
sequence(:name) { |n| "The Greasy Spoon #{n}" }
address "33 Harrison Ave"
city "Boston"
state "MA"
zip "02111"
description "Best burnt coffee and highest fructose pancake syrup"
category "Diner"
end
factory :review do
rating "1"
sequence(:body) { |n| "The spoons are literally greasy. YUCK! #{n}" }
restaurant
end
end
<file_sep>/spec/features/rest_names_link_to_show_spec.rb
require 'rails_helper'
feature "Show pages link from index", %q{
As a user
I want to click on a restaurant's name and be taken to its info
So that I can learn more about it
Acceptance Criteria:
- [x] /restaurants/:id path shows the restaurant details for a restaurant/id
} do
scenario "links work" do
restaurant = FactoryGirl.create(:restaurant)
visit root_path
click_on restaurant.name
expect(page).to have_content restaurant.name
expect(page).to have_content restaurant.address
expect(page).to have_content restaurant.city
expect(page).to have_content restaurant.state
expect(page).to have_content restaurant.zip
expect(page).to have_content restaurant.description
expect(page).to have_content restaurant.category
end
end
<file_sep>/Gemfile
source 'https://rubygems.org'
gem 'rails', '4.1.6'
gem 'pg'
gem 'uglifier', '>= 1.3.0'
gem 'jquery-rails'
gem 'foundation-rails'
gem 'sass-rails'
group :development, :test do
gem 'spring'
gem 'rspec-rails'
gem 'capybara'
gem 'pry-rails'
gem 'launchy'
gem 'factory_girl_rails'
end
<file_sep>/app/models/restaurant.rb
class Restaurant < ActiveRecord::Base
validates :name,
presence: true,
uniqueness: true
validates :address, presence: true
validates :city, presence: true
validates :state, presence: true
validates :zip, presence: true
has_many :reviews
end
<file_sep>/spec/features/user_adds_review_spec.rb
require 'rails_helper'
feature "User adds a review", %q{
As a user
I want to add a review
So that I can share my opinion with others
Acceptance Criteria:
- [x] /restaurants/10/reviews/new displays a form for adding a review
} do
scenario "with valid attributes" do
restaurant = FactoryGirl.create(:restaurant)
review = FactoryGirl.build(:review)
visit restaurant_path(restaurant)
click_on "Rate this Restaurant"
fill_in "Rating", with: review.rating
fill_in "Body", with: review.body
click_on "Submit"
expect(page).to have_content "Success! Your review has been posted!"
expect(page).to have_content restaurant.name
expect(page).to have_content review.rating
expect(page).to have_content review.body
end
scenario "with invalid attributes" do
restaurant = FactoryGirl.create(:restaurant)
visit restaurant_path(restaurant)
click_on "Rate this Restaurant"
click_on "Submit"
expect(page).to have_content "ERRAH"
expect(page).to have_content "Rating can't be blank"
expect(page).to have_content "Body can't be blank"
end
end
|
d6f7771a268bffdf128ee092f6cee0f00eac3868
|
[
"Ruby"
] | 8
|
Ruby
|
lizvdk/LA-good-eats
|
0645a6116f79bc06178c2c1fe2edc9ade369462a
|
e4b2b08c1a54a716a915290bb1c00fb153ee3471
|
refs/heads/master
|
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.9.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Mar 10, 2020 at 11:23 AM
-- Server version: 10.4.8-MariaDB
-- PHP Version: 7.3.11
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: `vietgram`
--
-- --------------------------------------------------------
--
-- Table structure for table `photo`
--
CREATE TABLE `photo` (
`id` int(11) NOT NULL,
`username` varchar(255) NOT NULL,
`url` varchar(255) NOT NULL,
`caption` varchar(255) NOT NULL,
`likes` int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `photo`
--
INSERT INTO `photo` (`id`, `username`, `url`, `caption`, `likes`) VALUES
(1, 'herisn', 'https://cdn.shopify.com/s/files/1/0255/9429/8467/products/Yeezy-350-V2-EF2367-Reflective_3_1000x.jpg?v=1562708227', 'adidas Yeezy Boost 350 v2 Static Reflective', 250),
(2, 'herisn', 'https://image-cdn.hypb.st/https%3A%2F%2Fhypebeast.com%2Fimage%2F2020%2F02%2Fadidas-yeezy-boost-380-mist-release-date-info-002.jpg?q=75&w=800&cbr=1&fit=max', 'adidas YEEZY BOOST 380 \"Mist\"', 500),
(3, 'herisn', 'https://stockx-360.imgix.net/Adidas-Yeezy-Boost-750-Glow-In-The-Dark/Images/Adidas-Yeezy-Boost-750-Glow-In-The-Dark/Lv2/img01.jpg?auto=format,compress&w=559&q=90&dpr=2&updated_at=1538080256', 'adidas Yeezy Boost 750 Light Grey Glow In the Dark', 100);
-- --------------------------------------------------------
--
-- Table structure for table `profile`
--
CREATE TABLE `profile` (
`id` int(11) NOT NULL,
`username` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`website` varchar(255) NOT NULL,
`bio` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`phonenumber` varchar(255) NOT NULL,
`gender` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `profile`
--
INSERT INTO `profile` (`id`, `username`, `name`, `website`, `bio`, `email`, `phonenumber`, `gender`) VALUES
(1, 'admin', 'admin', 'http://instagram.com', ' ', '<EMAIL>', '082328930989', 'L'),
(2, 'herisn', '<NAME>', 'https://www.youtube.com/channel/UC4nBdevG7E14iYyOx_yhhSQ', 'youtuber ', '<EMAIL>', '082328930989', 'L');
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE `user` (
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `user`
--
INSERT INTO `user` (`username`, `password`, `email`) VALUES
('admin', 'admin', '<EMAIL>'),
('herisn', 'herisn', '<EMAIL>');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `photo`
--
ALTER TABLE `photo`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `profile`
--
ALTER TABLE `profile`
ADD PRIMARY KEY (`id`),
ADD KEY `username` (`username`);
--
-- Indexes for table `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`username`),
ADD KEY `username` (`username`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `photo`
--
ALTER TABLE `photo`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `profile`
--
ALTER TABLE `profile`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep># vietgram
On this repository I'll clone Instagram front end and back end
1301184382
<NAME>
IF-42-06
|
bdf8f733bdc1c3e94e259e9d935321a41a1351eb
|
[
"Markdown",
"SQL"
] | 2
|
SQL
|
herisn/vietgram-herisn
|
e17c92fd506f0b2dff9453d88255b25bccd2d2fe
|
53e3a2d2022af043f0dfd9d78aa8f522fd94f43a
|
refs/heads/master
|
<repo_name>Asror-bek/mostbyte_seria<file_sep>/app/Http/Controllers/CashController.php
<?php
namespace App\Http\Controllers;
use App\Http\Requests\CashRequest;
use App\Http\Resources\CashMovementResource;
use App\Http\Resources\CashResource;
use App\Service\CashService;
use App\Models\Cash;
class CashController extends Controller
{
private $cashService;
public function __construct(CashService $cashService)
{
$this-> cashService = $cashService;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function getList()
{
$cash = $this->cashService->list();
return CashResource::collection($cash);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(CashRequest $request)
{
$cash = $this->cashService->createOrUpdateCash($request->validated());
$this->cashService->cashMovements($request->validated(), $cash->id);
return new CashResource($cash->load('client'));
}
public function showClient($clientId)
{
$cash = $this->cashService->cashPoint($clientId);
return CashResource::collection($cash);
}
public function showHistory($cashId)
{
$cash = $this->cashService->cashHistory($cashId);
return CashMovementResource::collection($cash);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(CashRequest $request, Cash $cash)
{
$cash = $this->cashService->updateCash($request->validated(), $cash);
return new CashResource($cash->load("client"));
}
}
<file_sep>/app/Http/Controllers/ClientController.php
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Requests\ClientRequest;
use App\Http\Resources\ClientResource;
use App\Models\Client;
use App\Service\ClientService;
class ClientController extends Controller
{
private $clientService;
public function __construct(ClientService $clientService)
{
$this->clientService = $clientService;
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function listClients()
{
$clients = $this->clientService->list();
return ClientResource::collection($clients);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(ClientRequest $request)
{
$client = $this->clientService->createClient($request->validated());
return new ClientResource($client);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(ClientRequest $request, Client $client)
{
$client = $this->clientService->updateClient($request->validated(), $client);
return new ClientResource($client);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Client $client)
{
$this->clientService->deleteClient($client);
return response(['message' => 'Deleted successfully!']);
}
}
<file_sep>/app/Service/CashService.php
<?php
namespace App\Service;
use App\Constants\CashConstants;
use App\Models\Cash;
use App\Models\Cash_movement;
class CashService
{
public function list()
{
return Cash::query()->get();
}
public function createOrUpdateCash(array $validated)
{
$cash = Cash::query()->where("clientId", $validated["clientId"])->first();
if ($cash)
{
switch ($validated["type"])
{
case CashConstants::INPUT:
$cash->cash = $cash->cash + $validated["cash"];
break;
case CashConstants::OUTPUT:
$cash->cash = $cash->cash - $validated["cash"];
break;
}
}
else
{
$cash = Cash::query()->create($validated);
}
$cash->save();
return $cash;
}
public function cashMovements(array $validated, int $cashId)
{
$cashMovement = new Cash_movement();
$cashMovement->cash = $validated["cash"];
$cashMovement->type = $validated["type"];
$cashMovement->cashId = $cashId;
$cashMovement->save();
}
public function cashPoint($clientId)
{
return Cash::query()->where("clientId", "=", $clientId)->get();
}
public function cashHistory($cashId)
{
return Cash_movement::query()->where("cashId", "=", $cashId)->get();
}
public function updateCash(array $validated, Cash $cash)
{
$cash->cash = $validated['cash'];
$cash->clientId = $validated['clientId'];
$cash->save();
return $cash;
}
}
?>
<file_sep>/app/Service/ClientService.php
<?php
namespace App\Service;
use App\Models\Client;
class ClientService
{
public function list()
{
return Client::query()->get();
}
public function createClient(array $validated)
{
return Client::query()->create($validated);
}
public function updateClient(array $validated, Client $client)
{
return tap($client)->update($validated);
}
public function deleteClient(Client $client)
{
$client->delete();
}
}
?>
<file_sep>/app/Constants/CashConstants.php
<?php
namespace App\Constants;
class CashConstants
{
public const INPUT = "input";
public const OUTPUT = "output";
}
?>
|
fc059a3c4ab1bc5a42c1808a8b6976e6ac420c06
|
[
"PHP"
] | 5
|
PHP
|
Asror-bek/mostbyte_seria
|
b9a5f18e3c11c72ee8ef196a570cb03770939ebc
|
86d3450acb81685bb02f9537b35b88f2d4f5b594
|
refs/heads/master
|
<file_sep>Pushover Server
===============
A webserver to expose pushover notifications
Usage
-----
Create a config file
``` json
{
"buffer": 50,
"cache": "/var/tmp/pushover-server.json",
"host": "0.0.0.0",
"port": 8080,
"pushover": {
"secret": "secret here",
"device_id": "device id here"
}
}
```
and start the server
```
$ pushover-server config.json
loaded 2 items from cache
pulling unread messages
fetched 0 messages
listening on http://0.0.0.0:8080
127.0.0.1 - - [19/May/2016:14:38:14 -0400] "GET /messages.json HTTP/1.1" 200 275 "-" "curl/7.43.0"
```
`GET /messages.json` to see the notifications
```
$ curl -s localhost:8080/messages.json | json
[
{
"id": 16,
"message": "ok",
"app": "Pushover",
"aid": 1,
"icon": "pushover",
"date": 1463682341,
"priority": 0,
"acked": 0,
"umid": 4476,
"title": "hi"
},
{
"id": 18,
"message": "sticks",
"app": "Pushover",
"aid": 1,
"icon": "pushover",
"date": 1463682384,
"priority": 0,
"acked": 0,
"umid": 4478,
"title": "mozz"
}
]
```
Config
------
- `buffer` - number of messages to store locally
- `cache` - optional filename to store messages to be loaded up when the server starts
- `host` - HTTP host to listen on
- `port` - HTTP port to listen on
- `pushover.secret` - pushover secret
- `pushover.device_id` - pushover device_id
See https://github.com/bahamas10/node-pushover-open-client for pushover config options
Installation
------------
npm install -g pushover-server
License
-------
MIT License
<file_sep>#!/usr/bin/env node
/**
* Pushover Server
*
* View pushover notifications over an http server
*
* Author: <NAME> <<EMAIL>>
* Date: May 17, 2016
* License: MIT
*/
var fs = require('fs');
var http = require('http');
var accesslog = require('access-log');
var easyreq = require('easyreq');
var CircularBuffer = require('circular-buffer');
var PushoverOpenClient = require('pushover-open-client');
var vasync = require('vasync');
var config = {
buffer: +process.env.PUSHOVERSERVER_BUFFER || 50,
cache: process.env.PUSHOVERSERVER_CACHE,
host: process.env.PUSHOVERSERVER_HOST || '0.0.0.0',
port: +process.env.PUSHOVERSERVER_PORT || 8080,
pushover: {
secret: process.env.PUSHOVERSERVER_SECRET,
device_id: process.env.PUSHOVERSERVER_DEVICE_ID
}
};
var file = process.argv[2] || process.env.PUSHOVERSERVER_CONFIG_FILE;
if (file) {
var _config = JSON.parse(fs.readFileSync(file, 'utf8'));
Object.keys(_config).forEach(function (key) {
config[key] = _config[key];
});
}
if (!config.pushover.secret || !config.pushover.device_id) {
console.error('pushover config not found');
process.exit(1);
}
// buffer to store messages
var messagebuf = new CircularBuffer(config.buffer);
// load up the cache if specified
var q;
if (config.cache) {
var cache;
try {
cache = JSON.parse(fs.readFileSync(config.cache, 'utf8'));
} catch (e) {
cache = [];
}
cache.sort(function (a, b) {
return a.date < b.date ? -1 : 1;
}).forEach(function (message) {
messagebuf.enq(message);
});
console.log('loaded %d items from cache', cache.length);
q = vasync.queue(function (_, cb) {
var temp = config.cache + '.temp';
var data = JSON.stringify(messagebuf.toarray());
fs.writeFile(temp, data, 'utf8', function (err) {
if (err) {
console.error('failed to write cache to temp file %s: %s',
temp, err.message);
cb();
return;
}
fs.rename(temp, config.cache, function (err) {
if (err) {
console.error('failed to write cache to temp file %s: %s',
temp, err.message);
cb();
return;
}
cb();
});
});
}, 1);
}
var poc = new PushoverOpenClient(config.pushover);
console.log('pulling unread messages');
poc.fetchAndDeleteMessages(function (err, messages) {
if (err)
throw err;
console.log('fetched %d messages', messages.length);
messages.forEach(function (message) {
messagebuf.enq(message);
});
if (messages.length > 0 && q)
q.push(null);
poc.on('message', function (message) {
messagebuf.enq(message);
if (q)
q.push(null);
});
poc.startWatcher();
http.createServer(onrequest).listen(config.port, config.host, started);
});
function started() {
console.log('listening on http://%s:%d', config.host, config.port);
}
function onrequest(req, res) {
accesslog(req, res);
easyreq(req, res);
switch (req.urlparsed.normalizedpathname) {
case '/':
res.redirect('/ping');
break;
case '/ping':
res.end('pong\n');
break;
case '/messages.json':
res.setHeader('Access-Control-Allow-Origin', '*');
res.json(messagebuf.toarray());
break;
default:
res.notfound();
break;
}
}
|
0f32c3d727f5305681a45e49d169de01c4e6505f
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
bahamas10/node-pushover-server
|
bf69b78959e66d4007d6401df0955b31f38e4889
|
41c2602400ddf927531df5422073212ba71b212b
|
refs/heads/master
|
<file_sep>var app = angular.module('warhead');
app.controller('BrowserController', function($scope)
{
(function constructor() {
})();
});
<file_sep>var app = angular.module('warhead');
app.controller('AnyRequestController', function($scope, $http, $sce, $location, $stateParams, dialogs) {
var highlightJson = function(json) {
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
};
var highlight = function(obj) {
return highlightJson(angular.toJson(obj, true))
};
$scope.baseUriChanged = function() {
$location.search('base_uri', $scope.input.baseUri);
};
$scope.pathChanged = function() {
$location.search('path', $scope.input.path);
};
$scope.methodChanged = function() {
$location.search('method', $scope.input.method);
};
$scope.bodyChanged = function() {
$location.search('body', $scope.input.body);
};
$scope.btnRequestClicked = function() {
var url = $scope.input.baseUri + $scope.input.path;
var payload = $scope.input.body;
$http[$scope.input.method](url, payload).then(function(res) {
$scope.result = $sce.trustAsHtml(highlight(res.data));
}).catch(function(err) {
console.log(err);
});
};
$scope.btnResetFormClicked = function() {
dialogs.confirm().result.then(function() {
$scope.input.baseUri = 'http://127.0.0.1:9200/';
$scope.input.path = '_search';
$scope.input.method = 'post';
$scope.input.body = '{"query":{"match_all":{}}}';
var keys = _.keys($location.search());
_.each(keys, function(key) {
$location.search(key, null);
});
});
};
(function constructor() {
$scope.methods = ['post', 'get', 'put', 'head', 'delete'];
$scope.input = {};
$scope.input.baseUri = $stateParams.base_uri || 'http://127.0.0.1:9200/';
$scope.input.path = $stateParams.path || '_search';
$scope.input.method = $stateParams.method || 'post';
$scope.input.body = $stateParams.body || '{"query":{"match_all":{}}}';
})();
});
<file_sep>var gulp = require('gulp');
var connect = require('gulp-connect');
var modRewrite = require('connect-modrewrite');
var rename = require("gulp-rename");
var runSequence = require('run-sequence');
var usemin = require('gulp-usemin');
var templateCache = require('gulp-angular-templatecache');
var concat = require('gulp-concat');
var del = require('del');
gulp.task('connect', function() {
connect.server({
port: 9101,
middleware: function (connect, options) {
return [
modRewrite(['^[^\\.]*(\\?.*)?$ /dev.html [L]']),
];
}
});
});
gulp.task('usemin', function() {
return gulp.src('dev.html')
.pipe(usemin())
.pipe(gulp.dest('./build'))
});
gulp.task('partials', function () {
return gulp.src('./partials/**/*.html')
.pipe(gulp.dest('./build/partials'));
});
gulp.task('icons', function() {
return gulp.src('./bower_components/font-awesome/fonts/**.*')
.pipe(gulp.dest('./fonts'));
});
gulp.task('templatecache', function () {
return gulp.src('./partials/**/*.html')
.pipe(templateCache({module:'templatescache', standalone:true}))
.pipe(gulp.dest('./build'));
});
gulp.task('scripts', function() {
return gulp.src('./build/*.js')
.pipe(concat('app.min.js'))
.pipe(gulp.dest('./build'));
});
gulp.task('clean2', function() {
return gulp.src('./build/dev.html')
.pipe(rename('./index.html'))
.pipe(gulp.dest('./'));
});
gulp.task('clean1', function() {
return gulp.src('./build/build/*')
.pipe(gulp.dest('./build'));
});
gulp.task('clean', function() {
return del(['./build/public/templates.js', './build/build']);
});
gulp.task('server', ['connect']);
gulp.task('default', ['connect']);
gulp.task('build:prod', function() {
runSequence('usemin', 'partials', 'icons', 'templatecache', 'scripts', 'clean2', 'clean1', 'clean');
});
<file_sep>var app = angular.module('warhead',
['ui.router',
'ngSanitize',
'ui.bootstrap',
'ui-notification',
'ui.select',
'dialogs.main']);
app.constant('ENDPOINT', 'http://127.0.0.1:9200');
app.config(function($stateProvider, $urlRouterProvider, $locationProvider, dialogsProvider) {
dialogsProvider.useBackdrop(true);
dialogsProvider.useAnimation(true);
dialogsProvider.useFontAwesome();
dialogsProvider.setSize('sm');
$urlRouterProvider.otherwise("/");
$stateProvider
.state('home', {
url: '/',
templateUrl: 'partials/home.html',
controller: 'HomeController',
resolve: {
statePromise: function($http, ENDPOINT) {
return $http.get(ENDPOINT + '/_cluster/state');
},
statusPromise: function($http, ENDPOINT) {
return $http.get(ENDPOINT + '/_status');
},
},
})
.state('structuredQuery', {
url: '/structured-query',
templateUrl: 'partials/structured-query.html',
controller: 'StructuredQueryController',
reloadOnSearch: false,
resolve: {
statusPromise: function($http, ENDPOINT) {
return $http.get(ENDPOINT + '/_status');
},
},
})
.state('anyRequest', {
url: '/any-request?base_uri&path&method&body',
templateUrl: 'partials/any-request.html',
controller: 'AnyRequestController',
reloadOnSearch: false,
resolve: {
},
})
.state('indices', {
url: '/indices',
templateUrl: 'partials/indices.html',
controller: 'IndicesController',
reloadOnSearch: false,
resolve: {
statusPromise: function($http, ENDPOINT) {
return $http.get(ENDPOINT + '/_status');
},
},
})
.state('browser', {
url: '/browser',
templateUrl: 'partials/browser.html',
controller: 'BrowserController',
reloadOnSearch: false,
resolve: {
},
});
});
<file_sep>```
npm install
bower install
```
```
gulp server
```
<file_sep>var app = angular.module('warhead');
app.controller('NewIndexModalController', function($scope, $uibModalInstance)
{
$scope.btnCreateIndexClicked = function() {
$uibModalInstance.close($scope.input);
};
(function constructor() {
$scope.input = {};
$scope.input.nbShards = 5;
$scope.input.nbReplicas = 1;
})();
$scope.cancel = function() {
$uibModalInstance.dismiss('cancel');
};
});
<file_sep>var app = angular.module('warhead');
app.controller('DeleteModalController', function($scope, $uibModalInstance, indexName) {
$scope.btnDeleteClicked = function() {
$uibModalInstance.close($scope.input.text);
};
(function constructor() {
$scope.indexName = indexName;
$scope.input = {};
})();
$scope.cancel = function() {
$uibModalInstance.dismiss('cancel');
};
});
<file_sep>var app = angular.module('warhead');
app.controller('HomeController', function($scope, statePromise, $uibModal,
$http, $state, Notification, dialogs, ENDPOINT, statusPromise)
{
$scope.btnNewAliasClicked = function(index) {
var modalInstance = $uibModal.open({
templateUrl: 'partials/new-alias-modal.html',
controller: 'NewAliasModalController',
});
modalInstance.result.then(function(alias) {
var payload = {"actions":[{"add":{"index":index,"alias":alias}}]};
var url = ENDPOINT + '/_aliases';
$http.post(url, payload).then(function(res) {
console.log(res);
Notification.success('Alias created');
$state.reload();
}).catch(function(err) {
console.log(err);
});
});
};
$scope.btnRemoveAliasClicked = function(index, alias) {
dialogs.confirm().result.then(function() {
var payload = {"actions":[{"remove":{"index":index,"alias":alias}}]};
var url = ENDPOINT + '/_aliases';
$http.post(url, payload).then(function(res) {
console.log(res);
Notification.success('Alias deleted');
$state.reload();
}).catch(function(err) {
console.log(err);
});
});
};
$scope.btnDeleteClicked = function(index) {
var modalInstance = $uibModal.open({
templateUrl: 'partials/delete-modal.html',
controller: 'DeleteModalController',
resolve: {
indexName: function() { return index; },
}
});
modalInstance.result.then(function(text) {
if (text == 'DELETE') {
var url = ENDPOINT + '/' + index;
$http.delete(url).then(function(res) {
Notification.success('Index ' + index + ' deleted');
$state.reload();
}).catch(function(err) {
dialogs.error(err.status + ' - ' + err.statusText, '<code><pre>' + angular.toJson(err.data, true) + '</pre></code>', {size: 'lg'});
console.log(err);
});
}
});
};
$scope.btnRefreshClicked = function(indexName) {
var url = ENDPOINT + '/' + indexName + '/_refresh';
$http.post(url).then(function(res) {
Notification.success('Index refreshed');
$state.reload();
}).catch(function(err) {
dialogs.error(err.status + ' - ' + err.statusText, '<code><pre>' + angular.toJson(err.data, true) + '</pre></code>', {size: 'lg'});
console.log(err);
});
};
$scope.btnFlushClicked = function(indexName) {
var url = ENDPOINT + '/' + indexName + '/_flush';
$http.post(url).then(function(res) {
Notification.success('Index flushed');
$state.reload();
}).catch(function(err) {
dialogs.error(err.status + ' - ' + err.statusText, '<code><pre>' + angular.toJson(err.data, true) + '</pre></code>', {size: 'lg'});
console.log(err);
});
};
$scope.btnCloseIndexClicked = function(indexName) {
var url = ENDPOINT + '/' + indexName + '/_close';
$http.post(url).then(function(res) {
Notification.success('Index closed');
$state.reload();
}).catch(function(err) {
dialogs.error(err.status + ' - ' + err.statusText, '<code><pre>' + angular.toJson(err.data, true) + '</pre></code>', {size: 'lg'});
console.log(err);
});
};
$scope.btnOpenIndexClicked = function(indexName) {
var url = ENDPOINT + '/' + indexName + '/_open';
$http.post(url).then(function(res) {
Notification.success('Index opened');
$state.reload();
}).catch(function(err) {
dialogs.error(err.status + ' - ' + err.statusText, '<code><pre>' + angular.toJson(err.data, true) + '</pre></code>', {size: 'lg'});
console.log(err);
});
};
var highlightJson = function(json) {
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
};
var highlight = function(obj) {
return highlightJson(angular.toJson(obj, true))
};
$scope.btnIndexStatusClicked = function(indexName) {
var data = $scope.statusData.indices[indexName];
dialogs.notify('Index Status', '<code><pre>' + highlight(data) + '</pre></code>', {size: 'lg'});
};
$scope.btnIndexMetadataClicked = function(indexName) {
var data = $scope.stateData.metadata.indices[indexName];
dialogs.notify('Index Metadata', '<code><pre>' + highlight(data) + '</pre></code>', {size: 'lg'});
};
(function constructor() {
$scope.sorts = [
{label: 'By Name', value: 'name'},
{label: 'By Address', value: 'address'},
{label: 'By Type', value: 'type'},
];
$scope.stateData = statePromise.data;
$scope.statusData = statusPromise.data;
$scope.indexes = _.reduce($scope.stateData.metadata.indices, function(memo, item, key) {
item.name = key;
memo.push(item);
return memo;
}, []);
})();
});
<file_sep>var app = angular.module('warhead');
app.controller('NewAliasModalController', function($scope, $uibModalInstance) {
$scope.btnCreateAliasClicked = function() {
$uibModalInstance.close($scope.input.alias);
};
(function constructor() {
$scope.input = {};
})();
$scope.cancel = function() {
$uibModalInstance.dismiss('cancel');
};
});
<file_sep>var app = angular.module('warhead');
app.controller('IndicesController', function($scope, statusPromise, $uibModal,
$state, Notification, ENDPOINT, dialogs, $http)
{
$scope.btnNewIndexClicked = function() {
var modalInstance = $uibModal.open({
templateUrl: 'partials/new-index-modal.html',
controller: 'NewIndexModalController',
});
modalInstance.result.then(function(newIndex) {
var payload = {"settings":{"index":{"number_of_shards":newIndex.nbShards,"number_of_replicas":newIndex.nbReplicas}}};
var url = ENDPOINT + '/' + newIndex.indexName;
$http.put(url, payload).then(function(res) {
console.log(res);
Notification.success('Index created');
$state.reload();
}).catch(function(err) {
dialogs.error(err.status + ' - ' + err.statusText, '<code><pre>' + angular.toJson(err.data, true) + '</pre></code>', {size: 'lg'});
console.log(err);
});
});
};
(function constructor() {
$scope.statusData = statusPromise.data;
$scope.indices = _.reduce($scope.statusData.indices, function(memo, item, key) {
memo.push(key);
return memo;
}, []);
})();
});
|
4662393dda3d3ad74a10170bb1a6d4482df00bde
|
[
"JavaScript",
"Markdown"
] | 10
|
JavaScript
|
alaingilbert/warhead
|
0b3259648870754a62999d0ac487f1e1d7f7e1a4
|
dd0a4443300d227b604420c7b7bf658be5b16743
|
refs/heads/master
|
<repo_name>williballenthin/govt<file_sep>/README.md
govt - VirusTotal API for Go
============================
`govt` is a go module to use the [API](https://www.virustotal.com/documentation/public-api/) of [VirusTotal.com](https://www.virustotal.com/).
Implemented Features
====================
| *Resource* | *Description* | *VT API* | *govt support* |
|------------------------------------|----------------------------------------------------------------------------------------|-------|-----|
| POST /vtapi/v2/file/scan | Upload a file for scanning with VirusTotal. | public |true |
| GET /vtapi/v2/file/scan/upload_url | Get a special URL to upload files bigger than 32MB in size. | private|false|
| POST /vtapi/v2/file/rescan | Rescan a previously submitted file or schedule a scan to be performed in the future. | public |true |
| POST /vtapi/v2/file/rescan/delete | Delete a previously scheduled scan. | private|false|
| GET /vtapi/v2/file/report | Get the scan results for a file. | public |true |
| GET /vtapi/v2/file/behaviour | Get a report about the behaviour of the file when executed in a sandboxed environment. | private|true |
| GET /vtapi/v2/file/network-traffic | Get a dump of the network traffic generated by the file when executed. | private|true |
| GET /vtapi/v2/file/search | Search for samples that match certain binary/metadata/detection criteria. | private|true |
| GET /vtapi/v2/file/clusters | List file similarity clusters for a given time frame. | private|false|
| GET /vtapi/v2/file/distribution | Get a live feed with the lastest files submitted to VirusTotal. | private|true |
| GET /vtapi/v2/file/download | Download a file by its hash. | private|true |
| GET /vtapi/v2/file/false-positives | Consume file false positives from your notifications pipe. | private|false|
| POST /vtapi/v2/url/scan | Submmit a URL for scanning with VirusTotal. | public |true |
| GET /vtapi/v2/url/report | Get the scan results for a given URL. | public |true |
| GET /vtapi/v2/url/distribution | Get a live feed with the lastest URLs submitted to VirusTotal. | private|false|
| GET /vtapi/v2/ip-address/report | Get information about a given IP address. | public |true |
| GET /vtapi/v2/domain/report | Get information about a given domain. | public |true |
| POST /vtapi/v2/comments/put | Post a comment on a file or URL. | public |true |
| GET /vtapi/v2/comments/get | Get comments for a file or URL. | private|true |
Missing Features
================
- all of the above with a `false` in the `govt support` column.
- at least for testing the VT apikey has currently be put into the source (get the apikey from a file or an environment variable would be better)
- more and better testing
Install
=======
If you have a go workplace setup and working you can simply do:
```go get github.com/williballenthin/govt```
```go install github.com/williballenthin/govt```
Usage
=====
In order how to use the `govt` module please have a look at the `SampleClients` directory and it's content.
You need to have an VirusTotal API Key. You can register for an account at VirusTotal in order to get an public API key.
There are also private API keys available, for those you have to be accepted by VirusTotal and you need to pay for.
Depending on your API Key and the access level granted you can use all of the above functions, all but the ones reserved for AV companies, or just the public ones (if you have a free publich API key).
Check out the [README.md](https://github.com/williballenthin/govt/blob/master/SampleClients/README.md) file in the `SampleClients` directory to find out how to set-up your API key in order to use the provided Example programs.
Authors
=======
`govt` was initially written by `<NAME>`. Later improved and new features added by `Christopher 'tankbusta' Schmitt` and `Florian 'scusi' Walther`
<file_sep>/SampleClients/README.md
# Sample Clients for govt
Provides some example program that use the govt module.
In general all client programs get their VirusTotal API Key via an environment variable (VT_API_KEY).
Therefore you have to export VT_API_KEY before using any of the provided examples.
```export VT_API_KEY=<YOUR_API_KEY_GOES_HERE>```
## Overview
* vtDomainReport.go - fetches a domain report for a given domain
* vtFileCheck.go - checks if a given resource is known by VT (without uploading a given sample)
* vtFileDownload.go - downloads a sample from VT (needs private API Key)
* vtFileNetworkTraffic.go - downloads pcap from VT for a given resource
* vtFileKnownBySymantec.go - checks if a given resource is detected by a certain AV , Symantec is used in this example
* vtFileReport.go - fetches a report for a given sample
* vtFileRescan.go - initiates a rescan for a given sample
* vtFileScan.go - uploads a file for scanning
* vtIpReport.go - fetches a report for a given IP address
* vtUrlReport.go - fetches a report for a given url
* vtUrlScan.go - initiates a url scan for a given url.
* vtGetComments.go - fetches comments from the community for a given resource
* vtFileBehaviour.go - fetches a Cuckoo report of the file's execution
<file_sep>/SampleClients/urlscan/vtUrlScan.go
// vtUrlScan - Requests VirusTotal to scan a given URL
// vtUrlScan -url=http://www.virustotal.com/
package main
import (
"encoding/json"
"flag"
"fmt"
"os"
"github.com/williballenthin/govt"
)
var apikey string
var apiurl string
var url string
// init - initializes flag variables.
func init() {
flag.StringVar(&apikey, "apikey", os.Getenv("VT_API_KEY"), "Set environment variable VT_API_KEY to your VT API Key or specify on prompt")
flag.StringVar(&apiurl, "apiurl", "https://www.virustotal.com/vtapi/v2/", "URL of the VirusTotal API to be used.")
flag.StringVar(&url, "url", "", "url of a file to as VT about.")
}
// check - an error checking function
func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
flag.Parse()
if url == "" {
fmt.Println("-url=<url> missing!")
os.Exit(1)
}
c, err := govt.New(govt.SetApikey(apikey), govt.SetUrl(apiurl))
check(err)
// get an URL report
r, err := c.ScanUrl(url)
check(err)
fmt.Printf("r: %s\n", r)
j, err := json.MarshalIndent(r, "", " ")
check(err)
fmt.Printf("UrlReport: ")
os.Stdout.Write(j)
}
<file_sep>/SampleClients/filesearch/main.go
// vtFileSearch - shows how to use VT Intelligence to search for files that match certain criteria.
//
// <EMAIL>
//
package main
import (
"flag"
"fmt"
"github.com/williballenthin/govt"
"log"
"os"
)
var apikey string
var query string
var hashlist []string
var offset string
var Client *govt.Client
var err error
func init() {
flag.StringVar(&apikey, "apikey", os.Getenv("VT_API_KEY"), "Set environment variable VT_API_KEY to your VT API Key or specify on prompt")
flag.StringVar(&query, "query", "", "your search request")
}
func main() {
flag.Parse()
Client, err = govt.New(
govt.SetErrorLog(log.New(os.Stderr, "VT: ", log.Lshortfile)),
govt.SetApikey(apikey),
)
offset = ""
fetchAllHashes(query, offset)
fmt.Printf("found %d matches:\n", len(hashlist))
for i, h := range hashlist {
fmt.Printf("[%04d]\t\t%s\n", i, h)
}
}
func fetchAllHashes(query, offset string) {
result, err := Client.SearchFile(query, offset)
if err != nil {
log.Fatal(err)
}
//fmt.Printf("%+v\n", result)
offset = result.Offset
for _, h := range result.Hashes {
hashlist = append(hashlist, h)
}
if offset != "" {
fetchAllHashes(query, offset)
}
return
}
<file_sep>/SampleClients/filerescan/vtFileRescan.go
// vtFileRescan - asks VirusTotal to rescan a given resource.
// Resource can be a MD5, SHA-1 or SHA-2of a file.
// vtFileRescan -rsrc=8ac31b7350a95b0b492434f9ae2f1cde
//
package main
import (
"encoding/json"
"flag"
"fmt"
"os"
"github.com/williballenthin/govt"
)
var apikey string
var apiurl string
var rsrc string
// init - initializes flag variables.
func init() {
flag.StringVar(&apikey, "apikey", os.Getenv("VT_API_KEY"), "Set environment variable VT_API_KEY to your VT API Key or specify on prompt")
flag.StringVar(&apiurl, "apiurl", "https://www.virustotal.com/vtapi/v2/", "URL of the VirusTotal API to be used.")
flag.StringVar(&rsrc, "rsrc", "", "md5 sum of a file to as VT about.")
}
// check - an error checking function
func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
flag.Parse()
if rsrc == "" {
fmt.Println("-rsrc=<md5|sha1|sha2> missing!")
os.Exit(1)
}
c, err := govt.New(govt.SetApikey(apikey), govt.SetUrl(apiurl))
check(err)
r, err := c.RescanFile(rsrc)
check(err)
j, err := json.MarshalIndent(r, "", " ")
check(err)
fmt.Printf("FileReport: ")
os.Stdout.Write(j)
}
<file_sep>/SampleClients/fileknownbysymantec/vtFileKnownBySymantec.go
// vtFileKnownBySymantec.go - checks via VirusTotal if a given file is detected by Symantec AV.
package main
import (
"crypto/md5"
"encoding/json"
"flag"
"fmt"
"io"
"os"
"github.com/williballenthin/govt"
)
var apikey string
var apiurl string
var rsrc string
var file string
var vtUpload bool
func init() {
flag.StringVar(&apikey, "apikey", os.Getenv("VT_API_KEY"), "Set environment variable VT_API_KEY to your VT API Key or specify on prompt")
flag.StringVar(&apiurl, "apiurl", "https://www.virustotal.com/vtapi/v2/", "URL of the VirusTotal API to be used.")
flag.StringVar(&rsrc, "rsrc", "8ac31b7350a95b0b492434f9ae2f1cde", "resource of file to check VT for. Resource can be md5, sha-1 or sha-2 sum of a file.")
flag.StringVar(&file, "file", "", "submit a file instead of a resource")
flag.BoolVar(&vtUpload, "upload-vt", false, "if 'true' files unknown to VT will be uploaded to VT")
}
// calculate md5 of a given file
func calcMd5(filename string) (md5sum string) {
f, err := os.Open(filename)
check(err)
defer f.Close()
md5 := md5.New()
_, err = io.Copy(md5, f)
return fmt.Sprintf("%x", md5.Sum(nil))
}
func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
flag.Parse()
fileForError := ""
if file != "" {
rsrc = calcMd5(file)
fileForError = file
} else {
fileForError = "</path/to/file>"
}
c, err := govt.New(govt.SetApikey(apikey), govt.SetUrl(apiurl))
check(err)
r, err := c.GetFileReport(rsrc)
check(err)
if r.ResponseCode == 0 {
fmt.Println(rsrc + " NOT KNOWN by VirusTotal")
if vtUpload == true && file != "" {
r, err := c.ScanFile(file)
check(err)
j, err := json.MarshalIndent(r, "", " ")
fmt.Printf("FileReport: ")
os.Stdout.Write(j)
} else {
fmt.Printf("For uploading to VT use vtFileScan -file=%s\n", fileForError)
}
} else {
sr := r.Scans["Symantec"]
if sr.Detected == true {
fmt.Printf("%s detected by Symantec Version %s as %s since update %s\n", rsrc, sr.Version, sr.Result, sr.Update)
} else {
fmt.Printf("%s NOT detected by Symantec; Detection Rate: [%d/%d]\n", rsrc, r.Positives, r.Total)
fmt.Printf("If you want to upload this file to VT use: 'vtFileScan -file=%s'\n", fileForError)
fmt.Printf("If you want to submit it to Symantec use: 'symantecUpload -file=%s'\n", fileForError)
}
}
}
<file_sep>/govt_test.go
/*
A few test cases for the `govt` package.
We cannot have many test cases, because the public API is limited to four requests per minute.
So here, we demonstrate that the scheme works, and leave it at that
Written by <NAME> while at Mandiant.
June, 2013.
*/
package govt
import (
"flag"
"fmt"
"net/http"
"os"
"strings"
"testing"
"time"
)
var runExpensive bool
var runPrivate bool
var apikey string
func init() {
flag.StringVar(&apikey, "apikey", "", "VT api key used for testing")
flag.BoolVar(&runExpensive, "run-expensive", false, "Flag to run expensive tests")
flag.BoolVar(&runPrivate, "run-private", false, "Flag to run private API tests")
flag.Parse()
if apikey == "" {
fmt.Println("API key is required to run the tests agains VT")
os.Exit(1)
}
}
// TestGetFileReport tests the structure and execution of a request.
func TestGetFileReport(t *testing.T) {
govt, err := New(SetApikey(apikey))
if err != nil {
t.Fatal(err)
}
var testMd5 = "eeb024f2c81f0d55936fb825d21a91d6"
report, err := govt.GetFileReport(testMd5)
if err != nil {
t.Error("Error requesting report: ", err.Error())
return
}
if report.ResponseCode != 1 {
t.Errorf("Response code indicates failure: %d", report.ResponseCode)
return
}
if report.Md5 != testMd5 {
t.Error("Requested MD5 does not match result: ", testMd5, " vs. ", report.Md5)
return
}
}
// TestGetDetailedFileReport tests the structure and execution of a request.
func TestGetDetailedFileReport(t *testing.T) {
govt, err := New(SetApikey(apikey))
if err != nil {
t.Fatal(err)
}
var testMd5 = "e320908e9cac93876be08549bf0be67f"
var testFpr = []string{
"9617094A1CFB59AE7C1F7DFDB6739E4E7C40508F", // Microsoft Corporation
"3036E3B25B88A55B86FC90E6E9EAAD5081445166", // Microsoft Code Signing PCA
"A43489159A520F0D93D032CCAF37E7FE20A8B419", // Microsoft Root Authority
}
report, err := govt.GetDetailedFileReport(testMd5)
if err != nil {
t.Error("Error requesting report: ", err.Error())
return
}
if report.ResponseCode != 1 {
t.Errorf("Response code indicates failure: %d", report.ResponseCode)
return
}
if report.Md5 != testMd5 {
t.Error("Requested MD5 does not match result: ", testMd5, " vs. ", report.Md5)
return
}
i := 0
for _, sig := range report.AdditionnalInfo.Signature.SignersDetails {
fpr := sig.Thumbprint
if fpr != testFpr[i] {
t.Error("Requested signature fingerprint does not match result: ", testFpr[i], " vs. ", fpr)
return
}
i++
}
}
// TestGetFileReports tests the structure and execution of a request.
func TestGetFileReports(t *testing.T) {
govt, err := New(SetApikey(apikey))
if err != nil {
t.Fatal(err)
}
md5s := []string{"eeb024f2c81f0d55936fb825d21a91d6", "1F4C43ADFD45381CFDAD1FAFEA16B808"}
reports, err := govt.GetFileReports(md5s)
if err != nil {
t.Error("Error requesting reports: ", err.Error())
return
}
for _, r := range *reports {
if r.ResponseCode != 1 {
t.Errorf("Response code indicates failure: %d", r.ResponseCode)
return
}
}
}
// TestRescanFile tests the structure and execution of a request.
func TestRescanFile(t *testing.T) {
govt, err := New(SetApikey(apikey))
if err != nil {
t.Fatal(err)
}
var testMd5 = "eeb024f2c81f0d55936fb825d21a91d6"
report, err := govt.RescanFile(testMd5)
if err != nil {
t.Error("Error requesting rescan: ", err.Error())
return
}
if report.ResponseCode != 1 {
t.Errorf("Response code indicates failure: %d", report.ResponseCode)
return
}
}
// Test POST requests using custom http client
func TestPostTimeout(t *testing.T) {
httpClient := &http.Client{
Timeout: time.Nanosecond * 1,
}
govt, err := New(SetApikey(apikey), SetHttpClient(httpClient))
if err != nil {
t.Fatal(err)
}
var testMd5 = "0123456789abcdef0123456789abcdef"
_, err = govt.RescanFile(testMd5)
if err != nil {
if strings.Contains(err.Error(), "request canceled (Client.Timeout exceeded while awaiting headers)") {
return
}
t.Error(err.Error())
}
t.Error("Error requesting RescanFile with timeout not used timeout")
}
// Test GET requests using custom http client
func TestGetTimeout(t *testing.T) {
httpClient := &http.Client{
Timeout: time.Nanosecond * 1,
}
govt, err := New(SetApikey(apikey), SetHttpClient(httpClient))
if err != nil {
t.Fatal(err)
}
md5s := []string{"0123456789abcdef0123456789abcdef"}
_, err = govt.GetFileReports(md5s)
if err != nil {
if strings.Contains(err.Error(), "request canceled (Client.Timeout exceeded while awaiting headers)") {
return
}
t.Error(err.Error())
}
t.Error("Error requesting GetFileReports with timeout not used timeout")
}
// Private API calls
// TestFileFeed tests the new files feed private API
func TestFileFeed(t *testing.T) {
if !runPrivate {
t.Skip("To run this test, use: go test -run-private")
}
govt, err := New(SetApikey(apikey))
if err != nil {
t.Fatal(err)
}
// Current time in UTC minus one hour
var packageRange = time.Now().UTC().Add(time.Duration(-1 * time.Hour)).Format("20060102T1504")
_, err = govt.GetFileFeed(packageRange)
if err != nil {
t.Error("Error requesting feed: ", err.Error())
}
}
// TestGetFileBehaviour tests the structure and execution of a request.
func TestGetFileBehaviour(t *testing.T) {
if !runPrivate {
t.Skip("To run this test, use: go test -run-private")
}
govt, err := New(SetApikey(apikey))
if err != nil {
t.Fatal(err)
}
testMD5 := "1F4C43ADFD45381CFDAD1FAFEA16B808"
fileBehaviour, err := govt.GetFileBehaviour(testMD5)
if err != nil {
t.Error("Error requesting behaviour report: ", err.Error())
return
}
if fileBehaviour.ResponseCode == 0 && fileBehaviour.VerboseMsg != "" {
t.Errorf("Response code indicates failure: %d", fileBehaviour.ResponseCode)
return
}
}
// Expensive from here
// TestRescanFiles tests the structure and execution of a request.
func TestRescanFiles(t *testing.T) {
if !runExpensive {
t.Skip("To run this test, use: go test -run-expensive")
}
govt, err := New(SetApikey(apikey))
if err != nil {
t.Fatal(err)
}
testMd5s := []string{"eeb024f2c81f0d55936fb825d21a91d6", "eeb024f2c81f0d55936fb825d21a91d6"}
reports, err := govt.RescanFiles(testMd5s)
if err != nil {
t.Error("Error requesting rescan: ", err.Error())
return
}
for _, report := range *reports {
if report.ResponseCode != 1 {
t.Errorf("Response code indicates failure: %d", report.ResponseCode)
return
}
}
}
// TestScanUrl tests the structure and execution of a request.
func TestScanUrl(t *testing.T) {
if !runExpensive {
t.Skip("To run this test, use: go test -run-expensive")
}
govt, err := New(SetApikey(apikey))
if err != nil {
t.Fatal(err)
}
var testURL = "http://www.virustotal.com/"
report, err := govt.ScanUrl(testURL)
if err != nil {
t.Error("Error requesting Scan: ", err.Error())
return
}
if report.ResponseCode != 1 {
t.Errorf("Response code indicates failure: %d", report.ResponseCode)
return
}
}
// TestScanUrls tests the structure and execution of a request.
func TestScanUrls(t *testing.T) {
if !runExpensive {
t.Skip("To run this test, use: go test -run-expensive")
}
govt, err := New(SetApikey(apikey))
if err != nil {
t.Fatal(err)
}
testURLs := []string{"http://www.virustotal.com", "http://www.google.com"}
reports, err := govt.ScanUrls(testURLs)
if err != nil {
t.Error("Error requesting scan: ", err.Error())
return
}
if len(*reports) != len(testURLs) {
t.Errorf("Error count scan results. Excpected %d, but found %d", len(testURLs), len(*reports))
}
for _, report := range *reports {
if report.ResponseCode != 1 {
t.Errorf("Response code indicates failure: %d", report.ResponseCode)
return
}
}
}
// TestGetUrlReport tests the structure and execution of a request.
func TestGetUrlReport(t *testing.T) {
if !runExpensive {
t.Skip("To run this test, use: go test -run-expensive")
}
govt, err := New(SetApikey(apikey))
if err != nil {
t.Fatal(err)
}
var testURL = "http://www.virustotal.com/"
report, err := govt.GetUrlReport(testURL)
if err != nil {
t.Error("Error requesting report: ", err.Error())
return
}
if report.ResponseCode != 1 {
t.Errorf("Response code indicates failure: %d", report.ResponseCode)
return
}
if report.Url != testURL {
t.Error("Requested URL does not match result: ", testURL, " vs. ", report.Url)
return
}
}
// TestGetUrlReports tests the structure and execution of a request.
func TestGetUrlReports(t *testing.T) {
if !runExpensive {
t.Skip("To run this test, use: go test -run-expensive")
}
govt, err := New(SetApikey(apikey))
if err != nil {
t.Fatal(err)
}
var testURLs = []string{"http://www.virustotal.com", "http://www.google.com"}
reports, err := govt.GetUrlReports(testURLs)
if err != nil {
t.Error("Error requesting report: ", err.Error())
return
}
for _, report := range *reports {
if report.ResponseCode != 1 {
t.Errorf("Response code indicates failure: %d", report.ResponseCode)
return
}
}
}
// TestGetIpReport tests the structure and execution of a request.
// It does not perform logical tests on the returned data.
func TestGetIpReport(t *testing.T) {
if !runExpensive {
t.Skip("To run this test, use: go test -run-expensive")
}
govt, err := New(SetApikey(apikey))
if err != nil {
t.Fatal(err)
}
var testIP = "8.8.8.8"
report, err := govt.GetIpReport(testIP)
if err != nil {
t.Error("Error requesting report: ", err.Error())
return
}
if report.ResponseCode != 1 {
t.Errorf("Response code indicates failure: %d", report.ResponseCode)
return
}
}
// TestGetDomainReport tests the structure and execution of a request.
// It does not perform logical tests on the returned data.
func TestGetDomainReport(t *testing.T) {
if !runExpensive {
t.Skip("To run this test, use: go test -run-expensive")
}
govt, err := New(SetApikey(apikey))
if err != nil {
t.Fatal(err)
}
var testDomain = "www.virustotal.com"
report, err := govt.GetDomainReport(testDomain)
if err != nil {
t.Error("Error requesting report: ", err.Error())
return
}
if report.ResponseCode != 1 {
t.Errorf("Response code indicates failure: %d", report.ResponseCode)
return
}
}
// TestGetComments tests the structure and execution of a request.
func TestGetComments(t *testing.T) {
if !runExpensive {
t.Skip("To run this test, use: go test -run-expensive")
}
govt, err := New(SetApikey(apikey))
if err != nil {
t.Fatal(err)
}
testSHA256 := "2fcc9209ddeb18b2dbd4db5f42dd477feaf4a1c3028eb6393dbaa21bd26b800c"
report, err := govt.GetComments(testSHA256)
if err != nil {
t.Error("Error requesting comments: ", err.Error())
return
}
if report.ResponseCode != 1 {
t.Errorf("Response code indicates failure: %d", report.ResponseCode)
return
}
}
<file_sep>/SampleClients/filedownload/vtFileDownload.go
// vtFileDownload - fetches a sample from VirusTotal for the given resource. A resource can be MD5, SHA-1 or SHA-2 of a file.
// vtFileDownload -rsrc=8ac31b7350a95b0b492434f9ae2f1cde
//
// This feature of the VirusTotal API is just available if you have a private API key.
// With a public API key you can not download samples.
//
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"os"
"github.com/williballenthin/govt"
)
var apikey string
var apiurl string
var rsrc string
// init - initializes flag variables.
func init() {
flag.StringVar(&apikey, "apikey", os.Getenv("VT_API_KEY"), "Set environment variable VT_API_KEY to your VT API Key or specify on prompt")
flag.StringVar(&apiurl, "apiurl", "https://www.virustotal.com/vtapi/v2/", "URL of the VirusTotal API to be used.")
flag.StringVar(&rsrc, "rsrc", "", "resource of file to retrieve report for. A resource can be md5, sha-1 or sha-2 sum of a file.")
}
// check - an error checking function
func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
flag.Parse()
if rsrc == "" {
fmt.Println("-rsrc=<md5|sha-1|sha-2> not given!")
os.Exit(1)
}
c, err := govt.New(govt.SetApikey(apikey), govt.SetUrl(apiurl))
check(err)
// get a file report
r, err := c.GetFile(rsrc)
check(err)
//fmt.Printf("r: %s\n", r)
j, err := json.MarshalIndent(r, "", " ")
check(err)
fmt.Printf("FileReport: ")
os.Stdout.Write(j)
//fmt.Printf("%d %s \t%s \t%s \t%d/%d\n", r.Status.ResponseCode, r.Status.VerboseMsg, r.Resource, r.ScanDate, r.Positives, r.Total)
err = ioutil.WriteFile(rsrc, r.Content, 0600)
check(err)
fmt.Printf("file %s has been written.\n", rsrc)
}
<file_sep>/API-CHANGES.md
# Breaking API changes from version 1.0
1. Initialization
-----------------
Previously, initializing the client required creating the client with the relevant API key and other parameters:
```
// Create the client
c := govt.Client{Apikey: "api key"}
```
Now, the initialization is done via the New function with which checks that the client is initialized correctly:
```
// Create the client
c := govt.New(govt.SetErrorLog(log.New(os.Stderr, "VT: ", log.Lshortfile), govt.SetApikey(apikey), govt.SetUrl(apiurl))
```
You can provide multiple initialization functions of type govt.OptionFunc to help with the initialization.
| *Function* | *Description* | *Mandatory* |
|---------------|------------------------------------------------|-------------|
| SetApikey | Provide the API key to use | true |
| SetHttpClient | Provide a custom HTTP client | false |
| SetUrl | Provide a different URL from the default one | false |
| SetBasicAuth | Provide proxy credentials | false |
| SetErrorLog | Set error logger to write errors to | false |
| SetTraceLog | Set trace logger to dump requests / replies to | false |
2. Client implementation details
--------------------------------
Client implementation details such as internal fields are now private. This move was made so it will be easier to evolve and change the API without breaking compatibility with existing code.
3. File uploads
---------------
To improve memory footprint requirements, file uploads are now streaming using a goroutine.
<file_sep>/SampleClients/domainreport/vtDomainReport.go
// vtDomainReport.go - fetches and shows a VirusTotal Domain Report.
// usage:
// vtDomainReport.go -domain=scusiblog.org
//
package main
import (
"encoding/json"
"flag"
"fmt"
"os"
"github.com/williballenthin/govt"
)
var apikey string
var apiurl string
var domain string
// init - initializes flag variables.
func init() {
flag.StringVar(&apikey, "apikey", os.Getenv("VT_API_KEY"), "Set environment variable VT_API_KEY to your VT API Key or specify on prompt")
flag.StringVar(&apiurl, "apiurl", "https://www.virustotal.com/vtapi/v2/", "URL of the VirusTotal API to be used.")
flag.StringVar(&domain, "domain", "", "a domain to ask information about from VT.")
}
// check - an error checking function
func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
flag.Parse()
if domain == "" {
fmt.Println("-domain=<domainname> missing!")
os.Exit(1)
}
c, err := govt.New(govt.SetApikey(apikey), govt.SetUrl(apiurl))
check(err)
// get a domain report (passive dns info)
d, err := c.GetDomainReport(domain)
check(err)
j, err := json.MarshalIndent(d, "", " ")
fmt.Printf("DomainReport: ")
os.Stdout.Write(j)
}
<file_sep>/SampleClients/filescan/vtFileScan.go
// vtFileScan - request VirusTotal to scan a given file.
// vtFileScan -file=/path/to/fileToScan.ext
//
package main
import (
"encoding/json"
"flag"
"fmt"
"os"
"github.com/williballenthin/govt"
)
var apikey string
var apiurl string
var file string
// init - initializes flag variables.
func init() {
flag.StringVar(&apikey, "apikey", os.Getenv("VT_API_KEY"), "Set environment variable VT_API_KEY to your VT API Key or specify on prompt")
flag.StringVar(&apiurl, "apiurl", "https://www.virustotal.com/vtapi/v2/", "URL of the VirusTotal API to be used.")
flag.StringVar(&file, "file", "", "file to send to VT for scanning.")
}
// check - an error checking function
func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
flag.Parse()
if file == "" {
fmt.Println("-file=<fileToScan.ext> missing!")
os.Exit(1)
}
c, err := govt.New(govt.SetApikey(apikey), govt.SetUrl(apiurl))
check(err)
// get a file report
r, err := c.ScanFile(file)
check(err)
//fmt.Printf("r: %s\n", r)
j, err := json.MarshalIndent(r, "", " ")
check(err)
fmt.Printf("FileReport: ")
os.Stdout.Write(j)
}
<file_sep>/SampleClients/filecheck/vtFileCheck.go
// vtFileCheck.go - checks if VirusTotal knows a given file.
package main
import (
"flag"
"fmt"
"os"
"github.com/williballenthin/govt"
)
var apikey string
var apiurl string
var rsrc string
func init() {
flag.StringVar(&apikey, "apikey", os.Getenv("VT_API_KEY"), "Set environment variable VT_API_KEY to your VT API Key or specify on prompt")
flag.StringVar(&apiurl, "apiurl", "https://www.virustotal.com/vtapi/v2/", "URL of the VirusTotal API to be used.")
flag.StringVar(&rsrc, "rsrc", "8ac31b7350a95b0b492434f9ae2f1cde", "resource of file to check VT for. Resource can be md5, sha-1 or sha-2 sum of a file.")
}
func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
flag.Parse()
c, err := govt.New(govt.SetApikey(apikey), govt.SetUrl(apiurl))
check(err)
r, err := c.GetFileReport(rsrc)
check(err)
if r.ResponseCode == 0 {
//fmt.Println( r.VerboseMsg )
fmt.Println(rsrc + " NOT KNOWN by VirusTotal")
} else {
//fmt.Println(rsrc + "["+r.Positives+"/"+r.Total+"] IS KNOWN by VirusTotal")
fmt.Printf("%s [%d/%d] IS KNOWN by VirusTotal\n", rsrc, r.Positives, r.Total)
//j, err := json.MarshalIndent(r, "", " ")
//fmt.Printf("FileReport: ")
//os.Stdout.Write(j)
}
}
|
c29cc06fdaa5de5d1c97ae43aa6bb8061835d55e
|
[
"Markdown",
"Go"
] | 12
|
Markdown
|
williballenthin/govt
|
3ca547fdfb8744273f8dfcdcaf0d2062bcc664b2
|
0e7dc362c3d7ada595661e4694365c04c49c2adc
|
refs/heads/master
|
<repo_name>weiyuanGarage/algorithmPratice<file_sep>/src/main/java/solutions/medium/mergeIntervals.java
package solutions.medium;
import solutions.template;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class mergeIntervals implements template {
public class Interval {
int start;
int end;
Interval() { start = 0; end = 0; }
Interval(int s, int e) { start = s; end = e; }
}
@Override
public void run() {
}
public List<Interval> merge(List<Interval> intervals) {
List<Interval> result = new ArrayList<>();
int length = intervals.size();
if(length < 1) {
return result;
}
Collections.sort(intervals, (a, b) -> {
int r = a.start - b.start;
if(r == 0) {
r = a.end - b.end;
}
return r;
});
result.add(intervals.get(0));
for(int a = 1; a < length; ++a) {
int back = result.size() - 1;
Interval pre = result.get(back);
Interval cur = intervals.get(a);
if(pre.end >= cur.start) {
pre.end = pre.end > cur.end ? pre.end : cur.end;
result.set(back, pre);
}
else {
result.add(cur);
}
}
return result;
}
}
<file_sep>/src/main/java/solutions/easy/isSymmetric.java
package solutions.easy;
import solutions.template;
import java.util.LinkedList;
import java.util.Queue;
public class isSymmetric implements template {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
@Override
public void run() {
}
public boolean isSymmetricRe(TreeNode root) {
if(root == null) {
return true;
}
return checkLeftRight(root.left, root.right);
}
public boolean checkLeftRight(TreeNode left, TreeNode right) {
if(left == null && right == null) {
return true;
}
if(left == null || right == null || left.val != right.val) {
return false;
}
return checkLeftRight(left.left, right.right) && checkLeftRight(left.right, right.left);
}
public boolean isSymmetricIt(TreeNode root) {
if(root == null || (root.left == null && root.right == null)) {
return true;
}
if(root.left == null || root.right == null) {
return false;
}
Queue<TreeNode> levels = new LinkedList<>();
levels.add(root.left);
levels.add(root.right);
while(!levels.isEmpty()) {
int size = levels.size();
if(size % 2 != 0) {
return false;
}
for(int a = 0; a < size; a+=2) {
TreeNode left = levels.poll();
TreeNode right = levels.poll();
if (left.val != right.val) {
return false;
}
if (left.left != null && right.right != null) {
levels.add(left.left);
levels.add(right.right);
}
else if(left.left == null && right.right != null) {
return false;
}
else if(left.left != null && right.right == null) {
return false;
}
if (left.right != null && right.left != null) {
levels.add(left.right);
levels.add(right.left);
}
else if(left.right == null && right.left != null) {
return false;
}
else if(left.right != null && right.left == null) {
return false;
}
}
}
return true;
}
}
<file_sep>/src/main/java/extendHungry.java
/**
* Created by weiyuan on 2018/03/27.
*/
public class extendHungry{
public extendHungry() {
System.out.println("extend");
}
}
<file_sep>/src/main/java/solutions/easy/maxSubArray.java
package solutions.easy;
import solutions.template;
/**
* Created by weiyuan on 2018/04/20.
*/
public class maxSubArray implements template {
@Override
public void run() {
int nums[] = new int[]{-2,1,-3,4,-1,2,1,-5,4};
System.out.println(solution(nums));
}
private int solution(int[] nums) {
int length = nums.length;
if(length < 1) {
return 0;
}
int result[] = new int[nums.length];
result[0] = nums[0];
int max = result[0];
for(int a = 1; a < length; ++a) {
result[a] = Math.max(nums[a], result[a - 1] + nums[a]);
max = Math.max(max, result[a]);
}
return max;
}
}
<file_sep>/src/main/java/solutions/medium/largestValues.java
package solutions.medium;
import solutions.template;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/**
* Created by weiyuan on 2018/04/04.
*/
public class largestValues implements template {
@Override
public void run() {
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public List<Integer> solution(TreeNode root) {
Queue<TreeNode> cur = new LinkedList<>();
List<Integer> result = new ArrayList<>();
cur.add(root);
int queueSize = root == null ? 0 : 1;
while(queueSize > 0) {
int max = Integer.MIN_VALUE;
for(int a = 0; a < queueSize; ++a) {
TreeNode temp = cur.poll();
max = Integer.max(temp.val, max);
if(temp.left != null) {
cur.add(temp.left);
}
if(temp.right != null) {
cur.add(temp.right);
}
}
result.add(max);
queueSize = cur.size();
}
return result;
}
}
<file_sep>/src/main/java/solutions/medium/copyRandomList.java
package solutions.medium;
import solutions.template;
import java.util.HashMap;
import java.util.Map;
public class copyRandomList implements template {
class RandomListNode {
int label;
RandomListNode next, random;
RandomListNode(int x) { this.label = x; }
}
@Override
public void run() {
}
public RandomListNode copyRandomList(RandomListNode head) {
RandomListNode fakeHead = new RandomListNode(-1);
RandomListNode fh = fakeHead;
Map<Integer, RandomListNode> nodes = new HashMap<>();
RandomListNode h = head;
while(h != null) {
int l = h.label;
RandomListNode cur;
if(nodes.containsKey(l)) {
cur = nodes.get(l);
}
else {
cur = new RandomListNode(l);
nodes.put(l, cur);
}
if(h.random != null) {
int rl = h.random.label;
if (nodes.containsKey(rl)) {
cur.random = nodes.get(rl);
} else {
RandomListNode ram = new RandomListNode(rl);
cur.random = ram;
nodes.put(rl, ram);
}
}
else {
cur.random = null;
}
fh.next = cur;
fh = cur;
h = h.next;
}
return fakeHead.next;
}
}
<file_sep>/src/main/java/solutions/easy/reverseWords.java
package solutions.easy;
import solutions.template;
/**
* Created by weiyuan on 2018/03/30.
*/
public class reverseWords implements template {
@Override
public void run() {
System.out.println(solution("hello from mac"));
}
private String solution(String s) {
if(s.length() == 0) {
return s;
}
int start = 0;
int end = s.length();
char[] result = s.toCharArray();
while(start < end) {
int wordEnd = start;
while((wordEnd + 1) != end && s.charAt(wordEnd + 1) != ' ') {
++wordEnd;
}
int tempEnd = wordEnd;
while(start < wordEnd) {
char temp = s.charAt(start);
result[start++] = result[wordEnd];
result[wordEnd--] = temp;
}
start = tempEnd + 2;
}
return new String(result);
}
}
<file_sep>/src/main/java/solutions/medium/partitionLabels.java
package solutions.medium;
import solutions.template;
import java.util.ArrayList;
import java.util.List;
public class partitionLabels implements template {
@Override
public void run() {
}
public List<Integer> partitionLabels(String S) {
int positions[] = new int[26];
for(int a = 0; a < S.length(); ++a) {
positions[S.charAt(a) - 'a'] = a;
}
List<Integer> result = new ArrayList<>();
int start = 0;
int end = 0;
for(int a = 0; a < S.length(); ++a) {
char c = S.charAt(a);
if(end < positions[c - 'a']) {
end = positions[c - 'a'];
}
if(end == a) {
result.add(end - start + 1);
++end;
start = end;
}
}
return result;
}
}
<file_sep>/src/main/java/solutions/medium/topKFrequent.java
package solutions.medium;
import solutions.template;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
/**
* Created by weiyuan on 2018/04/02.
*/
public class topKFrequent implements template {
@Override
public void run() {
int[] nums = new int[]{1,1,1,2,2,3};
int k = 2;
solution(nums, k);
}
private List<Integer> solution (int[] nums, int k) {
Map<Integer, Integer> counts = new HashMap<>();
for(int a = 0; a < nums.length; ++a) {
counts.put(nums[a], counts.getOrDefault(nums[a], 0) + 1);
}
PriorityQueue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<>((a, b)->(b.getValue() - a.getValue()));
for(Map.Entry<Integer, Integer> entry : counts.entrySet()) {
queue.add(entry);
}
List<Integer> result = new ArrayList<>();
for(int a = 0; a < k; ++a) {
result.add(queue.poll().getKey());
}
return result;
}
}
<file_sep>/src/main/java/solutions/medium/ambiguousCoordinates.java
package solutions.medium;
import solutions.template;
import java.util.ArrayList;
import java.util.List;
/**
* Created by weiyuan on 2018/04/17.
*/
public class ambiguousCoordinates implements template {
@Override
public void run() {
String S = "(00011)";
solution(S);
}
private List<String> solution(String S) {
List<String> result = new ArrayList<>();
for(int a = 1; a < S.length() - 2; ++a) {
List<String> first = split(S.substring(1, a + 1));
List<String> second = split(S.substring(a + 1, S.length() - 1));
for(String f : first) {
for(String s : second) {
result.add("(" + f + ", " + s + ")");
}
}
}
for(String r : result) {
System.out.println(r);
}
return result;
}
private List<String> split(String sub) {
List<String> subResult = new ArrayList<>();
if(sub.length() == 1) {
subResult.add(sub);
return subResult;
}
if(sub.charAt(0) == '0' && sub.charAt(sub.length() - 1) == '0') {
return subResult;
}
if(sub.charAt(0) == '0') {
subResult.add(sub.substring(0, 1) + "." + sub.substring(1, sub.length()));
return subResult;
}
if(sub.charAt(sub.length() - 1) == '0') {
subResult.add(sub);
return subResult;
}
for(int a = 0; a < sub.length() - 1; ++a) {
subResult.add(sub.substring(0, a + 1) + "." + sub.substring(a + 1, sub.length()));
}
subResult.add(sub);
return subResult;
}
}
<file_sep>/src/main/java/solutions/quickSort.java
package solutions;
/**
* Created by weiyuan on 2018/04/20.
*/
public class quickSort {
public void sort(int arr[], int left, int right) {
int index = part(arr, left, right);
if(left < index - 1) {
sort(arr, left, index - 1);
}
if(index < right) {
sort(arr, index, right);
}
}
public int part(int arr[], int left, int right) {
int pivot = arr[(left + right) / 2];
while(left <= right) {
while(arr[left] < pivot) {
++left;
}
while(arr[right] > pivot) {
--right;
}
if(left <= right) {
int temp = arr[left];
arr[left++] = arr[right];
arr[right--] = temp;
}
}
return left;
}
}
<file_sep>/src/main/java/solutions/template.java
package solutions;
/**
* Created by weiyuan on 2018/03/19.
*/
public interface template {
void run();
}
<file_sep>/src/main/java/solutions/easy/rob.java
package solutions.easy;
import solutions.template;
/**
* Created by weiyuan on 2018/04/20.
*/
public class rob implements template {
@Override
public void run() {
}
private int solution(int[] nums) {
if(nums.length < 1) {
return 0;
}
int rob[] = new int[nums.length];
int nrob[] = new int[nums.length];
rob[0] = nums[0];
nrob[0] = 0;
for(int a = 1; a < nums.length; ++a) {
rob[a] = nums[a] + nrob[a - 1];
nrob[a] = Math.max(nrob[a - 1], rob[a - 1]);
}
return Math.max(rob[nums.length - 1], nrob[nums.length - 1]);
}
}
<file_sep>/src/main/java/solutions/easy/unsafePassword.java
package solutions.easy;
import solutions.template;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Created by weiyuan on 2018/04/19.
*/
public class unsafePassword implements template {
@Override
public void run() {
solution("abc");
}
private void solution(String s) {
List<String> result = createPer(s);
Set<String> all = new HashSet<>();
char q[] = new char[]{'a', 'b', 'c', 'd'};
for(int a = 0; a < s.length(); ++a) {
char ll[] = s.toCharArray();
char t = s.charAt(a);
for(int b = 1; b < 4; b++) {
char re = q[(t - 'a' + b) % 4];
ll[a] = re;
List<String> tempR = createPer(new String(ll));
for(String tr : tempR) {
if(!all.contains(tr)) {
all.add(tr);
result.add(tr);
}
}
}
}
Collections.sort(result);
for(String l : result) {
System.out.println(l);
}
}
private List<String> createPer(String s) {
List<String> result = new ArrayList<>();
result.add("");
for(Character c : s.toCharArray()) {
List<String> temp = new ArrayList<>();
for(String pre : result) {
for(int a = 0; a <= pre.length(); ++a) {
temp.add(pre.substring(0, a) + c + pre.substring(a));
}
}
result = temp;
}
return result;
}
}
<file_sep>/src/main/java/solutions/ctci/chapter9/allSubset.java
package solutions.ctci.chapter9;
import solutions.template;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Created by weiyuan on 2018/04/10.
*/
public class allSubset implements template {
@Override
public void run() {
int array[] = new int[]{1,2,3,4,5,6};
// for(int a = 1; a <= array.length; ++a) {
// solution(array, a, new ArrayList<>(), 0);
// }
solution2(array);
}
private void solution(int[] array, int rest, ArrayList<Integer> current, int start) {
if(rest == 0) {
for(int a = 0; a < current.size(); ++a) {
System.out.print(current.get(a) + " ");
}
System.out.println();
return;
}
for(; start < array.length; ++start) {
current.add(array[start]);
solution(array, rest - 1, current, start + 1);
current.remove(current.size() - 1);
}
}
private void solution2(int[] array) {
List<List<Integer>> result = new ArrayList<>();
result.add(new ArrayList<>());
for(int a = 0; a < array.length; ++a) {
int length = result.size();
for(int b = 0; b < length; ++b) {
List<Integer> pre = result.get(b);
List<Integer> cur = new ArrayList<>(pre);
cur.add(array[a]);
result.add(cur);
}
}
result.remove(0);
Collections.sort(result, new Comparator<List<Integer>>() {
@Override
public int compare(List<Integer> o1, List<Integer> o2) {
return o1.size() - o2.size();
}
});
}
}
<file_sep>/src/main/java/solutions/ctci/chapter9/allParenthses.java
package solutions.ctci.chapter9;
import solutions.template;
import java.util.ArrayList;
/**
* Created by weiyuan on 2018/04/11.
*/
public class allParenthses implements template {
@Override
public void run() {
solution(2, 0, 0, new ArrayList<>());
}
private void solution(int goal, int curLeft, int needRight, ArrayList<Character> cur) {
if(curLeft == goal && needRight == 0) {
for(Character c : cur) {
System.out.print(c);
}
System.out.println();
}
if(curLeft != goal) {
cur.add('(');
solution(goal, curLeft + 1, needRight + 1, cur);
cur.remove(cur.size() - 1);
}
if(needRight != 0) {
cur.add(')');
solution(goal, curLeft, needRight - 1, cur);
cur.remove(cur.size() - 1);
}
}
}
<file_sep>/src/main/java/solutions/medium/boundaryOfBinaryTree.java
package solutions.medium;
import solutions.template;
import java.util.ArrayList;
import java.util.List;
public class boundaryOfBinaryTree implements template {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
@Override
public void run() {
}
public List<Integer> boundaryOfBinaryTree(TreeNode root) {
List<Integer> result = new ArrayList<>();
if(root != null) {
result.add(root.val);
getBound(root.left, result, true, false);
getBound(root.right, result, false, true);
}
return result;
}
public void getBound(TreeNode root, List<Integer> result, boolean isLeftBound, boolean isRightBound) {
if(root == null) {
return;
}
if(isLeftBound) {
result.add(root.val);
}
if(!isLeftBound && !isRightBound && root.left == null && root.right == null) {
result.add(root.val);
}
getBound(root.left, result, isLeftBound, isRightBound && (root.right == null));
getBound(root.right, result, isLeftBound && (root.left == null), isRightBound);
if(isRightBound) {
result.add(root.val);
}
}
public List<Integer> boundaryOfBinaryTree1(TreeNode root) {
List<Integer> result = new ArrayList<>();
if(root != null) {
result.add(root.val);
leftBoundary(root.left, result);
botBoundary(root.left, result);
botBoundary(root.right, result);
rightBoundary(root.right, result);
}
return result;
}
public void leftBoundary(TreeNode root, List<Integer> result) {
if(root == null || (root.left == null && root.right == null)) {
return;
}
result.add(root.val);
if(root.left != null) {
leftBoundary(root.left, result);
}
else {
leftBoundary(root.right, result);
}
}
public void botBoundary(TreeNode root, List<Integer> result) {
if(root == null) {
return;
}
if(root.left == null && root.right == null) {
result.add(root.val);
}
else {
botBoundary(root.left, result);
botBoundary(root.right, result);
}
}
public void rightBoundary(TreeNode root, List<Integer> result) {
if(root == null || (root.left == null && root.right == null)) {
return;
}
if(root.right != null) {
rightBoundary(root.right, result);
}
else {
rightBoundary(root.left, result);
}
result.add(root.val);
}
}
<file_sep>/src/main/java/solutions/medium/divide.java
package solutions.medium;
import solutions.template;
public class divide implements template {
@Override
public void run() {
int dividend = -2147483648;
int divisor = -1;
divide(dividend, divisor);
}
public int divide(int dividend, int divisor) {
if (divisor == 0 || (dividend == Integer.MIN_VALUE && divisor == -1)) {
return Integer.MAX_VALUE;
}
boolean negative = false;
if((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0)) {
negative = true;
}
int dvd = Math.abs(dividend);
int dvs = Math.abs(divisor);
int result = 0;
while(dvd >= dvs) {
int temp = dvs;
int multi = 1;
while(dvd >= (temp << 1)) {
temp <<= temp;
multi <<= 1;
}
dvd -= temp;
result += multi;
}
return negative ? -result : result;
}
}
<file_sep>/src/main/java/solutions/ctci/chapter2/addTwoNumbers.java
package solutions.ctci.chapter2;
import solutions.template;
/**
* Created by weiyuan on 2018/04/03.
*/
public class addTwoNumbers implements template {
@Override
public void run() {
}
private ListNode solution(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode temp = head;
int sub = 0;
int sum = 0;
while(l1 != null || l2 != null || sub != 0) {
if(l1 != null) {
sum += l1.val;
l1 = l1.next;
}
if(l2 != null) {
sum += l2.val;
l2 = l2.next;
}
sum += sub;
ListNode result = new ListNode(sum % 10);
temp.next = result;
temp = result;
sub = sum / 10;
sum = 0;
}
return head.next;
}
public class ListNode {
int val;
ListNode next;
public ListNode(int x) {
val = x;
}
}
}
<file_sep>/src/main/java/solutions/hard/splitArraySameAverage.java
package solutions.hard;
import solutions.template;
import java.util.Arrays;
import java.util.Collections;
/**
* Created by weiyuan on 2018/04/17.
*/
public class splitArraySameAverage implements template {
@Override
public void run() {
}
private boolean solution(int[] A) {
int sum = 0;
for(int a : A) {
sum += a;
}
int length = A.length;
Arrays.sort(A);
for(int a = 1 ; a <= length/2; ++a) {
if((sum*a) % length == 0) {
if(check(A, sum*a/length, a, 0)) return true;
}
}
return false;
}
private boolean check(int[] A, int leftSum, int leftNum, int start) {
if(leftNum == 0) {
return leftSum == 0;
}
for(int a = start; a < A.length - leftNum + 1; ++a) {
if(a > start && A[a] == A[a - 1]) {
continue;
}
if(check(A, leftSum - A[a], leftNum - 1, a + 1)) {
return true;
}
}
return false;
}
}
<file_sep>/src/main/java/solutions/easy/islandPerimeter.java
package solutions.easy;
import solutions.template;
/**
* Created by weiyuan on 2018/03/30.
*/
public class islandPerimeter implements template {
@Override
public void run() {
int[][] grid = new int[][]{new int[]{0,1,0,0}, new int[]{1,1,1,0}, new int[]{0,1,0,0}, new int[]{1,1,0,0}};
System.out.println(solution2(grid));
}
private int solution(int[][] grid) {
int result = 0;
int length = grid.length;
if(length == 0) {
return result;
}
int width = grid[0].length;
if(width == 0) {
return result;
}
for(int a = 0; a < length; ++a) {
for(int b = 0; b < width; ++b) {
if(grid[a][b] == 1) {
int temp = 4;
if(b - 1 >= 0 && grid[a][b - 1] == 1) {
--temp;
}
if(b + 1 <= width - 1 && grid[a][b + 1] == 1) {
--temp;
}
if(a - 1 >=0 && grid[a - 1][b] == 1) {
--temp;
}
if(a + 1 <= length - 1 && grid[a + 1][b] == 1) {
--temp;
}
result += temp;
}
}
}
return result;
}
private int solution2(int[][] grid) {
int length = grid.length;
if(length == 0) {
return 0;
}
int width = grid[0].length;
if(width == 0) {
return 0;
}
int island = 0;
int ne = 0;
for(int a = 0; a < length; ++a) {
for(int b = 0; b < width; ++b) {
if(grid[a][b] == 1) {
++island;
if(b + 1 < width && grid[a][b + 1] == 1) {
++ne;
}
if(a + 1 < length && grid[a + 1][b] == 1) {
++ne;
}
}
}
}
return island * 4 - ne * 2;
}
}
<file_sep>/src/main/java/solutions/ctci/chapter1/setRLTo0.java
package solutions.ctci.chapter1;
import solutions.template;
/**
* Created by weiyuan on 2018/04/03.
*/
public class setRLTo0 implements template {
@Override
public void run() {
int matrix[][] = new int[][]{new int[]{1,1,0,1}, new int[]{1,1,1,1}};
print(matrix);
solution(matrix);
print(matrix);
}
private int[][] solution(int[][] matrix) {
int length = matrix.length;
int width = matrix[0].length;
int row[] = new int[length];
int col[] = new int[width];
for(int a = 0; a < length; ++a) {
for(int b = 0; b < width; ++b) {
if(matrix[a][b] == 0) {
row[a] = 1;
col[b] = 1;
}
}
}
for(int a = 0; a < length; ++a) {
for(int b = 0; b < width; ++b) {
if(row[a] == 1 || col[b] == 1) {
matrix[a][b] = 0;
}
}
}
return matrix;
}
private void print(int[][] matrix) {
int length = matrix.length;
int width = matrix[0].length;
for(int a = 0; a < length; ++a) {
for(int b = 0; b < width; ++b) {
System.out.print(matrix[a][b] + " ");
}
System.out.println();
}
}
}
<file_sep>/src/main/java/solutions/ctci/chapter1/checkIfPermutation.java
package solutions.ctci.chapter1;
import solutions.template;
/**
* Created by weiyuan on 2018/04/03.
*/
public class checkIfPermutation implements template {
@Override
public void run() {
String s1 = "abcdefg";
String s2 = "dcggfeb";
System.out.println(solution(s1, s2));
}
private boolean solution(String s1, String s2) {
if(s1.length() != s2.length()) {
return false;
}
int count[] = new int[26];
for(int a = 0; a < s1.length(); ++a) {
int index = s1.charAt(a) - 'a';
++count[index];
}
for(int a = 0; a < s2.length(); ++a) {
int index = s2.charAt(a) - 'a';
--count[index];
if(count[index] < 0) {
return false;
}
}
return true;
}
}
<file_sep>/src/main/java/solutions/easy/climbStairs.java
package solutions.easy;
import solutions.template;
/**
* Created by weiyuan on 2018/04/20.
*/
public class climbStairs implements template {
@Override
public void run() {
System.out.println(solution(1));
}
private int solution(int n) {
int result[] = new int[n + 1];
return climbStairs(n);
}
// private int climb(int n, int result[]) {
// if(n == 0) {
// return 1;
// }
// if(n < 0) {
// return 0;
// }
// if(result[n] != 0) {
// return result[n];
// }
// result[n] = climb(n - 1, result) + climb(n - 2, result);
// return result[n];
// }
//
// private int solution2(int n) {
// int result[] = new int[n];
// result[0] = 1;
// result[1] = 2;
// for(int a = 2; a < n; ++a) {
// result[a] = result[a - 1] + result[a - 2];
// }
// return result[n - 1];
// }
public int climbStairs(int n) {
int result[] = new int[n + 1];
result[0] = 1;
for(int a = 1; a <= n; ++a) {
if(a - 1 >= 0) {
result[a] += result[a - 1];
}
if(a - 2 >= 0) {
result[a] += result[a - 2];
}
}
return result[n];
}
}
<file_sep>/src/main/java/solutions/medium/wordLadder.java
package solutions.medium;
import solutions.template;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
public class wordLadder implements template {
@Override
public void run() {
}
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
int level = 1;
Queue<String> adj = new LinkedList<>();
Set<String> visited = new HashSet<>();
adj.add(beginWord);
while(!adj.isEmpty()) {
int size = adj.size();
for(int a = 0; a < size; ++a) {
String cur = adj.poll();
if(!visited.contains(cur)) {
if (cur.equals(endWord)) {
return level;
}
visited.add(cur);
for(int b = 0; b < wordList.size(); ++b) {
if(isOneDiff(cur, wordList.get(b)) && !visited.contains(wordList.get(b))) {
adj.add(wordList.get(b));
}
}
}
}
++level;
}
return 0;
}
public boolean isOneDiff(String left, String right) {
boolean result = true;
int count = 0;
for(int a = 0; a < left.length(); ++a) {
if(left.charAt(a) != right.charAt(a)) {
++count;
}
if(count >= 2) {
result = false;
break;
}
}
return result;
}
}
<file_sep>/src/main/java/solutions/easy/NumArray.java
package solutions.easy;
import solutions.template;
public class NumArray implements template {
int sum[];
@Override
public void run() {
}
public NumArray(int[] nums) {
sum = new int[nums.length];
int result = 0;
for(int a = 0; a < nums.length; ++a) {
result += nums[a];
sum[a] = result;
}
}
public int sumRange(int i, int j) {
int result = 0;
if(i == 0) {
result = sum[j];
}
else {
result = sum[j] - sum[i - 1];
}
return result;
}
}
<file_sep>/src/main/java/solutions/easy/isToeplitzMatrix.java
package solutions.easy;
import solutions.template;
/**
* Created by weiyuan on 2018/04/02.
*/
public class isToeplitzMatrix implements template {
@Override
public void run() {
int[][] m = {{1,2,3}, {3,1,2}, {1,3,2}};
solution(m);
}
private boolean solution(int[][] matrix) {
int length = matrix.length;
int width = matrix[0].length;
for(int a = 0; a < length - 1; ++a) {
for(int b = 0; b < width - 1; ++b) {
if(matrix[a][b] != matrix[a + 1][b + 1]) return false;
}
}
return true;
}
}
<file_sep>/src/main/java/LazyInit.java
/**
* Created by weiyuan on 2018/03/16.
*/
public final class LazyInit {
private static volatile LazyInit lazyInit;
private Integer l;
private LazyInit() {
l = 3;
System.out.println("kk");
}
public static LazyInit getInstance() {
if(lazyInit == null) {
synchronized (LazyInit.class) {
if(lazyInit == null) {
lazyInit = new LazyInit();
}
}
}
return lazyInit;
}
private void print() {
System.out.println("you got it");
}
public void setL(Integer temp) {
l = temp;
}
public Integer getL() {
return l;
}
}
<file_sep>/src/main/java/solutions/medium/numIslands.java
package solutions.medium;
import solutions.template;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
public class numIslands implements template {
@Override
public void run() {
}
class coord {
int x;
int y;
public coord(int a, int b) {
x = a;
y = b;
}
}
public int numIslandsBFS(char[][] grid) {
int result = 0;
int length = grid.length;
if(length <= 0) {
return result;
}
int width = grid[0].length;
if(width <= 0) {
return result;
}
Queue<coord> neigbor = new LinkedList<>();
Set<String> onStack = new HashSet<>();
for(int a = 0; a < length; ++a) {
for(int b = 0; b < width; ++b) {
if(grid[a][b] == '1') {
coord m = new coord(a, b);
neigbor.add(m);
onStack.add(a + "-" + b);
while(neigbor.isEmpty() == false) {
coord cur = neigbor.poll();
int x = cur.x;
int y = cur.y;
onStack.remove(x + "-" + y);
if (x - 1 >= 0 && grid[x - 1][y] == '1' && onStack.contains((x-1) + "-" + y) == false) {
neigbor.add(new coord(x - 1, y));
}
if (x + 1 < length && grid[x + 1][y] == '1' && onStack.contains((x+1) + "-" + y) == false) {
neigbor.add(new coord(x + 1, y));
}
if (y - 1 >= 0 && grid[x][y - 1] == '1' && onStack.contains(x + "-" + (y - 1)) == false) {
neigbor.add(new coord(x, y - 1));
}
if (y + 1 < width && grid[x][y + 1] == '1' && onStack.contains(x + "-" + (y + 1)) == false) {
neigbor.add(new coord(x, y + 1));
}
grid[x][y] = '0';
}
++result;
}
}
}
return result;
}
public int numIslands(char[][] grid) {
int result = 0;
int length = grid.length;
if(length <= 0) {
return result;
}
int width = grid[0].length;
if(width <= 0) {
return result;
}
for(int a = 0; a < length; ++a) {
for (int b = 0; b < width; ++b) {
if (grid[a][b] == '1') {
++result;
dfs(grid, a, b);
}
}
}
return result;
}
public void dfs(char[][] grid, int x, int y) {
if(x < 0 || y < 0 || x >= grid.length || y >= grid[0].length || grid[x][y] == '0') {
return;
}
grid[x][y] = '0';
dfs(grid, x - 1, y);
dfs(grid, x + 1, y);
dfs(grid, x, y - 1);
dfs(grid, x, y + 1);
}
}
<file_sep>/src/main/java/solutions/ctci/chapter1/rotateMatrix.java
package solutions.ctci.chapter1;
import solutions.template;
/**
* Created by weiyuan on 2018/04/03.
*/
public class rotateMatrix implements template {
@Override
public void run() {
int matrix[][] = new int[][]{
new int[]{1,2,3,4,5},
new int[]{6,7,8,9,10},
new int[]{11,12,13,14,15},
new int[]{16,17,18,19,20},
new int[]{21,22,23,24,25}
};
print(matrix);
System.out.println();
solution(matrix);
print(matrix);
}
private int[][] solution(int[][] matrix) {
int length = matrix.length;
for(int a = 0; a < length / 2; ++a) {
int end = length - 1 - a;
for(int b = a; b < end; ++b) {
int top = matrix[a][b];
matrix[a][b] = matrix[end - b + a][a];
matrix[end - b + a][a] = matrix[end][end - b + a];
matrix[end][end - b + a] = matrix[b][end];
matrix[b][end] = top;
}
}
return matrix;
}
private void print(int[][] matrix) {
int length = matrix.length;
int width = matrix[0].length;
for(int a = 0; a < length; ++a) {
for(int b = 0; b < width; ++b) {
System.out.print(matrix[a][b] + " ");
}
System.out.println();
}
}
}
<file_sep>/src/main/java/solutions/easy/reverseString.java
package solutions.easy;
import solutions.template;
/**
* Created by weiyuan on 2018/03/27.
*/
public class reverseString implements template {
@Override
public void run() {
System.out.println(solution("helloo"));
}
private String solution(String s) {
if(s.length() == 0) {
return s;
}
char[] result = s.toCharArray();
int start = 0;
int end = s.length() - 1;
while(start < end) {
Character c = s.charAt(start);
result[start++] = result[end];
result[end--] = c;
}
return new String(result);
}
}
<file_sep>/src/main/java/solutions/ctci/chapter2/partitionLinkedList.java
package solutions.ctci.chapter2;
import solutions.template;
/**
* Created by weiyuan on 2018/04/03.
*/
public class partitionLinkedList implements template {
@Override
public void run() {
}
private Node solution(Node head, int x) {
Node beforeStart = null;
Node beforeTail = null;
Node afterStart = null;
Node afterTail = null;
while(head != null) {
if(head.val < x) {
if(beforeStart == null) {
beforeStart = head;
beforeTail = head;
}
else {
beforeTail.next = head;
beforeTail = head;
}
}
else {
if(afterStart == null) {
afterStart = head;
afterTail = head;
}
else {
afterTail.next = head;
afterTail = head;
}
}
}
if(beforeStart == null) {
return afterStart;
}
beforeTail.next = afterStart;
return beforeStart;
}
public class Node {
int val;
Node next;
public Node(int v) {
val = v;
next = null;
}
public Node() {
next = null;
}
}
}
<file_sep>/src/main/java/solutions/ctci/chapter1/uniqueCharacter.java
package solutions.ctci.chapter1;
import solutions.template;
/**
* Created by weiyuan on 2018/04/03.
*/
public class uniqueCharacter implements template {
@Override
public void run() {
System.out.println(solution("aba"));
}
private Boolean solution(String s) {
if(s.length() > 26) {
return false;
}
int check = 0;
for(int a = 0; a < s.length(); ++a) {
int val = s.charAt(a) - 'a';
if((check & (1 << val)) > 0) {
return false;
}
check |= (1 << val);
}
return true;
}
}
<file_sep>/src/main/java/solutions/medium/zigzagLevelOrder.java
package solutions.medium;
import solutions.template;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.stream.Collectors;
public class zigzagLevelOrder implements template {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
@Override
public void run() {
TreeNode root = new TreeNode(1);
zigzagLevelOrder(root);
}
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
if(root == null) {
return result;
}
boolean left = true;
queue.add(root);
while(!queue.isEmpty()) {
int size = queue.size();
int[] curLevel = new int[size];
for(int a = 0; a < size; ++a) {
TreeNode cur = queue.poll();
curLevel[left ? a : (size - 1) - a] = cur.val;
if(cur.left != null) queue.add(cur.left);
if(cur.right != null) queue.add(cur.right);
}
result.add(Arrays.stream(curLevel).boxed().collect(Collectors.toList()));
left = !left;
}
return result;
}
}
|
9a6694d8fa301b97ed1008a4ab604aea1c85af51
|
[
"Java"
] | 34
|
Java
|
weiyuanGarage/algorithmPratice
|
67bbe84b440e29c61b1827de4a8d58b7c0eb6c19
|
f8372db1dd82968ab4aa53de7a6361e1389922af
|
refs/heads/master
|
<repo_name>Beauxie/spring-cloud-study<file_sep>/microservice-eureka-authenticating-client/readme.md
# mircoservice-eureka-authenticating-client
> 简单的微服务示例,将服务注册到需要登录认证的Eureka Server中。
* 集成了Eureka服务,可以自动注册到服务中心,需要登录验证服务,此时`defalutZone`的配置为:
```yml
http://user:password@EUREKA_HOST:EUREKA_PORT/eureka/
```
比如对于该例的配置为:
```yml
eureka:
client:
service-url:
#default-zone: http://localhost:8761/eureka/
defaultZone: http://user:password123@localhost:8761/eureka/ #需要用户名密码认证才能注册
```
用户名为`user`,密码为`<PASSWORD>`<file_sep>/microservice-consumer-movie/readme.md
# microservice-consumer-movie
> 简单的微服务示例,作为服务消费者
* 只有一个自定义的接口:根据id获取用户信息,调用微服务api获取用户信息
* 集成了Eureka服务,可以自动注册到服务中心
* 访问[http://localhost:8010/1](http://localhost:8010/1)<file_sep>/microservice-provider-user-with-auth/readme.md
# microservice-provider-user-with-auth
> 简单的服务提供者示例
* 集成了`spring security`,api需要登录验证
* 一共有两个用户:`user/password1`、`<PASSWORD>/<PASSWORD>`
* 只有一个自定义的接口:根据id获取用户信息,首次访问时需要登录;
* 使用H2作为内存数据库
* 集成了actuator
* 集成了Eureka服务,可以自动注册到服务中心<file_sep>/microservice-discovery-eureka/readme.md
# microservice-discovery-eureka
> 简单的Eureka服务注册中心使用示例,作为Eureka Server
* 访问[http://localhost:8761](http://localhost:8761)<file_sep>/microservice-consumer-movie-feign-hystrix-fallback-stream/readme.md
# microservice-consumer-movie-feign-hystrix-fallback-stream
> 简单的微服务示例,作为服务消费者,使用feign与服务提供者通信,测试Hystrix的监控。
> 除实现容错外,Hystrix还提供了近乎实时的监控,HystrixCommand和HystrixObservableCommand在执行时,会生成执行结果和运行指标,比如每秒执行的请求数、成功数等。
* Feign的fallback,使用`@FeignClient`的fallback属性指定回退类
* 需要引入`spring-cloud-starter-hystrix`、`spring-boot-starter-actuator`
* 在启动类上加上`EnableCircuitBreaker`注解
* 只有一个自定义的接口:根据id获取用户信息,调用微服务api获取用户信息
* 集成了Eureka服务,可以自动注册到服务中心
* 启动microservice-discovery-eureka。
* 启动microservice-provider-user。
启动microservice-consumer-movie-feign-hystrix-fallback-stream。
* 访问[http://localhost:8010/user/1](http://localhost:8010/user/1),可正常获得结果
* 然后访问[http://localhost:8010/hystrix.stream1](http://localhost:8010/hystrix.stream),可获得如下结果:
``` json
data: {"type":"HystrixCommand","name":"UserFeignClient#findById(Long)","group":"microservice-provider-user","currentTime":1530621828754,"isCircuitBreakerOpen":false,"errorPercentage":0,"errorCount":0,"requestCount":0,"rollingCountBadRequests":0,"rollingCountCollapsedRequests":0,"rollingCountEmit":0,"rollingCountExceptionsThrown":0,"rollingCountFailure":0,"rollingCountFallbackEmit":0,"rollingCountFallbackFailure":0,"rollingCountFallbackMissing":0,"rollingCountFallbackRejection":0,"rollingCountFallbackSuccess":0,"rollingCountResponsesFromCache":0,"rollingCountSemaphoreRejected":0,"rollingCountShortCircuited":0,"rollingCountSuccess":0,"rollingCountThreadPoolRejected":0,"rollingCountTimeout":0,"currentConcurrentExecutionCount":1,"rollingMaxConcurrentExecutionCount":0,"latencyExecute_mean":0,"latencyExecute":{"0":0,"25":0,"50":0,"75":0,"90":0,"95":0,"99":0,"99.5":0,"100":0},"latencyTotal_mean":0,"latencyTotal":{"0":0,"25":0,"50":0,"75":0,"90":0,"95":0,"99":0,"99.5":0,"100":0},"propertyValue_circuitBreakerRequestVolumeThreshold":20,"propertyValue_circuitBreakerSleepWindowInMilliseconds":5000,"propertyValue_circuitBreakerErrorThresholdPercentage":50,"propertyValue_circuitBreakerForceOpen":false,"propertyValue_circuitBreakerForceClosed":false,"propertyValue_circuitBreakerEnabled":true,"propertyValue_executionIsolationStrategy":"THREAD","propertyValue_executionIsolationThreadTimeoutInMilliseconds":1000,"propertyValue_executionTimeoutInMilliseconds":1000,"propertyValue_executionIsolationThreadInterruptOnTimeout":true,"propertyValue_executionIsolationThreadPoolKeyOverride":null,"propertyValue_executionIsolationSemaphoreMaxConcurrentRequests":10,"propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests":10,"propertyValue_metricsRollingStatisticalWindowInMilliseconds":10000,"propertyValue_requestCacheEnabled":true,"propertyValue_requestLogEnabled":true,"reportingHosts":1,"threadPool":"microservice-provider-user"}
data: {"type":"HystrixCommand","name":"UserFeignClient#findById(Long)","group":"microservice-provider-user","currentTime":1530621829227,"isCircuitBreakerOpen":false,"errorPercentage":0,"errorCount":0,"requestCount":0,"rollingCountBadRequests":0,"rollingCountCollapsedRequests":0,"rollingCountEmit":0,"rollingCountExceptionsThrown":0,"rollingCountFailure":0,"rollingCountFallbackEmit":0,"rollingCountFallbackFailure":0,"rollingCountFallbackMissing":0,"rollingCountFallbackRejection":0,"rollingCountFallbackSuccess":0,"rollingCountResponsesFromCache":0,"rollingCountSemaphoreRejected":0,"rollingCountShortCircuited":0,"rollingCountSuccess":0,"rollingCountThreadPoolRejected":0,"rollingCountTimeout":0,"currentConcurrentExecutionCount":1,"rollingMaxConcurrentExecutionCount":0,"latencyExecute_mean":0,"latencyExecute":{"0":0,"25":0,"50":0,"75":0,"90":0,"95":0,"99":0,"99.5":0,"100":0},"latencyTotal_mean":0,"latencyTotal":{"0":0,"25":0,"50":0,"75":0,"90":0,"95":0,"99":0,"99.5":0,"100":0},"propertyValue_circuitBreakerRequestVolumeThreshold":20,"propertyValue_circuitBreakerSleepWindowInMilliseconds":5000,"propertyValue_circuitBreakerErrorThresholdPercentage":50,"propertyValue_circuitBreakerForceOpen":false,"propertyValue_circuitBreakerForceClosed":false,"propertyValue_circuitBreakerEnabled":true,"propertyValue_executionIsolationStrategy":"THREAD","propertyValue_executionIsolationThreadTimeoutInMilliseconds":1000,"propertyValue_executionTimeoutInMilliseconds":1000,"propertyValue_executionIsolationThreadInterruptOnTimeout":true,"propertyValue_executionIsolationThreadPoolKeyOverride":null,"propertyValue_executionIsolationSemaphoreMaxConcurrentRequests":10,"propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests":10,"propertyValue_metricsRollingStatisticalWindowInMilliseconds":10000,"propertyValue_requestCacheEnabled":true,"propertyValue_requestLogEnabled":true,"reportingHosts":1,"threadPool":"microservice-provider-user"}
```
<file_sep>/microservice-consumer-movie-ribbon-hystrix/src/main/java/com/beauxie/cloud/study/controller/MovieController.java
package com.beauxie.cloud.study.controller;
import com.beauxie.cloud.study.entity.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* Created by 11323 on 2018/6/17.
*/
@RestController
public class MovieController {
private static final Logger LOGGER = LoggerFactory.getLogger(MovieController.class);
@Autowired
private RestTemplate restTemplate;
@Value("${user.userServiceUrl}")
private String userServiceUrl;
@Autowired
private LoadBalancerClient loadBalancerClient;
@HystrixCommand(fallbackMethod = "findByIdFallback",commandProperties = {
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "5000"),
@HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds" , value = "10000")
})
@GetMapping("/user/{id}")
public User findById(@PathVariable Long id) {
User findOne = this.restTemplate.getForObject(userServiceUrl + id, User.class);
return findOne;
}
@GetMapping("log-user-instance")
public void logUserInstance() {
ServiceInstance serviceInstance = this.loadBalancerClient.choose("microservice-provider-user");
LOGGER.info("{}:{}:{}", serviceInstance.getServiceId(), serviceInstance.getHost(), serviceInstance.getPort());
}
/**
* 回退方法
*
* @param id
* @return
*/
public User findByIdFallback(Long id) {
User user = new User();
user.setId(-1L);
user.setName("默认用户");
return user;
}
}
<file_sep>/microservice-discovery-eureka-ha/readme.md
# microservice-discovery-eureka-ha
> 简单的Eureka服务注册中心集群使用示例,作为Eureka Server集群配置
* 1.需要在hosts中配置
```
127.0.0.1 peer1
127.0.0.1 peer2
```
* 2.打包项目(``),并使用以下命令启动两个Eureka Server节点。
```
java -jar microservice-discovery-eureka-ha-0.0.1-SNAPSHOT.jar --spring.profiles.active=peer1
java -jar microservice-discovery-eureka-ha-0.0.1-SNAPSHOT.jar --spring.profiles.active=peer2
```
通过spring.profiles.active指定使用哪个profile启动,启动过程中如果报`unknow server`是正常的,等两个jar包都正常启动以后就不会报错了。
* 3.访问[http://peer1:8761](http://peer1:8761)会发现"registered-replicas"中已有peer2节点,同理访问[http://peer2:8762](http://peer2:8762),也能发现其中的"registered-replicas"中有peer1节点。<file_sep>/microservice-consumer-movie-feign-manul/readme.md
# microservice-consumer-movie-feign-manual
> 简单的微服务示例,作为服务消费者,使用feign与服务提供者通信
* 调用需要登录认证的`microservice-provider-user-with-auth`服务接口;
* 集成了Eureka服务,可以自动注册到服务中心
* 访问[http://localhost:8010/user-user/1](http://localhost:8010/user-user/1)或[http://localhost:8010/user-admin/1](http://localhost:8010/user-admin/1)<file_sep>/microservice-consumer-movie-feign-hystrix-fallback-factory/src/main/java/com/beauxie/cloud/study/service/UserFeignClient.java
package com.beauxie.cloud.study.service;
import com.beauxie.cloud.study.entity.User;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* 用户接口服务
* Feign的fallback测试
*
* @author Beauxie
* @date 2018/6/19.
*/
@FeignClient(name = "microservice-provider-user", fallbackFactory = FeignClientFallbackFactory.class)
public interface UserFeignClient {
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
User findById(@PathVariable("id") Long id);
}
<file_sep>/microservice-simple-provider-user/readme.md
# microservice-simple-provider-user
> 简单的微服务示例,作为服务提供者
* 只有一个自定义的接口:根据id获取用户信息
* 使用H2作为内存数据库
* 集成了actuator
* 集成了Eureka服务,可以自动注册到服务中心<file_sep>/README.md
# spring-cloud-study
spring cloud相关知识学习代码
代码参考:[https://github.com/huangjava/spring-cloud-docker-microservice-book-code](https://github.com/huangjava/spring-cloud-docker-microservice-book-code)
<file_sep>/microservice-consumer-movie-ribbon/readme.md
# microservice-consumer-movie-ribbon
> 简单的微服务示例,作为服务消费者,整合Ribbon,实现请求负载均衡
## 说明
* Ribbon是Netflix发布的负载均衡器,有助于控制HTTP和TCP客户端的行为。有多种负载均衡算法,例如轮询、随机等,支持自定义。
* 由于spring-cloud-starter-eureka已经包含spring-cloud-starter-ribbon依赖,因此不需要再引入Ribbon
* 需要将`user.serviceUrl`改为`http://microservice-provider-user/`,其中microservice-provider-user是用户微服务的虚拟主机名,默认情况下,虚拟机主机名和服务名称是一致的,可以使用配置属性eureka.instance.virtual-host-name指定虚拟机主机名
* 为RestTemplate添加@LoadBalanced注解,开启负载均衡:
```java
/**
* 加上@LoadBalanced,就可为RestTemplate整合Ribbon,使其具备负载均衡的能力
*
* @return
*/
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
//解决中文乱码
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
return restTemplate;
}
```
* 集成了Eureka服务,可以自动注册到服务中心
* 访问[http://localhost:8010/user/1](http://localhost:8010/user/1)
## 测试
1.启动microservice-discovery-eureka。
2.启动2个或多个microservice-provider-user示例。
3.启动microservice-consumer-movie-ribbon。
4.访问[http://localhost:8761](http://localhost:8761),可以看到:
> MICROSERVICE-CONSUMER-MOVIE 对应一个服务
> MICROSERVICE-PROVIDER_USER 对应多个服务
5.多次访问[http://localhost:8010/user/1](http://localhost:8010/user/1),返回以下结果;
```json
{
"id": 1,
"username": "account1",
"name": "张三",
"age": 20,
"balance": 100.00
}
```
同时,两个用户微服务示例都会打印查询如下日志:
```
Hibernate: select user0_.id as id1_0_0_, user0_.age as age2_0_0_, user0_.balance as balance3_0_0_, user0_.name as name4_0_0_, user0_.username as username5_0_0_ from user user0_ where user0_.id=?
```
6.多次访问[http://localhost:8010/log-user-instance](http://localhost:8010/log-user-instance),控制台会打印如下语句:
```
2018-06-18 12:57:11.513 INFO 16764 --- [nio-8010-exec-1] c.b.c.study.controller.UserController : microservice-provider-user:192.168.229.1:8001
2018-06-18 12:57:12.339 INFO 16764 --- [erListUpdater-0] c.netflix.config.ChainedDynamicProperty : Flipping property: microservice-provider-user.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2018-06-18 12:57:13.800 INFO 16764 --- [nio-8010-exec-3] c.b.c.study.controller.UserController : microservice-provider-user:192.168.229.1:8000
2018-06-18 12:57:15.987 INFO 16764 --- [nio-8010-exec-5] c.b.c.study.controller.UserController : microservice-provider-user:192.168.229.1:8001
2018-06-18 12:57:16.752 INFO 16764 --- [nio-8010-exec-7] c.b.c.study.controller.UserController : microservice-provider-user:192.168.229.1:8000
2018-06-18 12:57:17.439 INFO 16764 --- [nio-8010-exec-9] c.b.c.study.controller.UserController : microservice-provider-user:192.168.229.1:8001
2018-06-18 12:57:18.104 INFO 16764 --- [nio-8010-exec-1] c.b.c.study.controller.UserController : microservice-provider-user:192.168.229.1:8000
```<file_sep>/microservice-consumer-movie-ribbon-hystrix/readme.md
# microservice-consumer-movie-ribbon-hystrix
> 简单的微服务示例,作为服务消费者,整合Ribbon、hystrix,实现请求负载均衡
## 说明
*使用Hystrix可以对应用进行容错,该项目主要测试Hystrix的回退机制,并集成了Actuator
* Ribbon是Netflix发布的负载均衡器,有助于控制HTTP和TCP客户端的行为。有多种负载均衡算法,例如轮询、随机等,支持自定义。
* 由于spring-cloud-starter-eureka已经包含spring-cloud-starter-ribbon依赖,因此不需要再引入Ribbon
* 需要将`user.serviceUrl`改为`http://microservice-provider-user/`,其中microservice-provider-user是用户微服务的虚拟主机名,默认情况下,虚拟机主机名和服务名称是一致的,可以使用配置属性eureka.instance.virtual-host-name指定虚拟机主机名
* 为RestTemplate添加@LoadBalanced注解,开启负载均衡:
```java
/**
* 加上@LoadBalanced,就可为RestTemplate整合Ribbon,使其具备负载均衡的能力
*
* @return
*/
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
//解决中文乱码
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
return restTemplate;
}
```
* 集成了Eureka服务,可以自动注册到服务中心
* 访问[http://localhost:8010/user/1](http://localhost:8010/user/1)
## 测试
1.启动microservice-discovery-eureka。
2.启动2个或多个microservice-provider-user示例。
3.启动microservice-consumer-movie-ribbon-hystrix。
4.访问[http://localhost:8761](http://localhost:8761),可以看到:
> MICROSERVICE-CONSUMER-MOVIE 对应一个服务
> MICROSERVICE-PROVIDER_USER 对应一个服务
5.访问[http://localhost:8010/user/1](http://localhost:8010/user/1),返回以下结果;
```json
{
"id": 1,
"username": "account1",
"name": "张三",
"age": 20,
"balance": 100.00
}
```
此时,访问[http://localhost:8010/health](http://localhost:8010/health):
``` json
{
"description": "Spring Cloud Eureka Discovery Client",
"status": "UP",
"discoveryComposite": {
"description": "Spring Cloud Eureka Discovery Client",
"status": "UP",
"discoveryClient": {
"description": "Spring Cloud Eureka Discovery Client",
"status": "UP",
"services": [
"microservice-consumer-movie",
"microservice-provider-user"
]
},
"eureka": {
"description": "Remote status from Eureka server",
"status": "UP",
"applications": {
"MICROSERVICE-CONSUMER-MOVIE": 1,
"MICROSERVICE-PROVIDER-USER": 1
}
}
},
"diskSpace": {
"status": "UP",
"total": 212689256448,
"free": 199898849280,
"threshold": 10485760
},
"refreshScope": {
"status": "UP"
},
"hystrix": {
"status": "UP"
}
}
```
此时,hystrix的状态为`UP`
6.停掉microservice-provider-user,再次访问,[http://localhost:8010/user/1](http://localhost:8010/user/1),获得如下结果:
``` json
{
"id": -1,
"username": null,
"name": "默认用户",
"age": null,
"balance": null
}
```
说明当用户微服务不可用时,进入了回退方法。
然后,多次访问访问[http://localhost:8010/user/1](http://localhost:8010/user/1)以后(默认5秒内失败20次才会打开断路器),再访问[http://localhost:8010/health](http://localhost:8010/health):
```json
{
"description": "Spring Cloud Eureka Discovery Client",
"status": "UP",
"discoveryComposite": {
"description": "Spring Cloud Eureka Discovery Client",
"status": "UP",
"discoveryClient": {
"description": "Spring Cloud Eureka Discovery Client",
"status": "UP",
"services": [
"microservice-consumer-movie",
"microservice-provider-user"
]
},
"eureka": {
"description": "Remote status from Eureka server",
"status": "UP",
"applications": {
"MICROSERVICE-CONSUMER-MOVIE": 1,
"MICROSERVICE-PROVIDER-USER": 1
}
}
},
"diskSpace": {
"status": "UP",
"total": 212689256448,
"free": 199898849280,
"threshold": 10485760
},
"refreshScope": {
"status": "UP"
},
"hystrix": {
"status": "CIRCUIT_OPEN",
"openCircuitBreakers": [
"MovieController::findById"
]
}
}
```
此时,hystrix的状态为`CIRCUIT_OPEN`,表示已打开
## Hsytrix线程隔离策略与传播上下文
### 隔离策略
* THREAD(线程隔离):使用该方式,HystrixCommand将会在单独的线程上执行,并发请求受线程池中的线程数量限制
* SEMAPHORE(信号量隔离):使用该方式,HystrixCommand将会调用线程上执行,开销相对较小,并发请求受到信号量个数的限制
* 如果发生找不到上下文的运行时异常时,可考虑将隔离策略设置为SEMAPHORE
Hystrix默认并推荐使用**线程隔离**,因为这种方式有一个除网络超时以外有一个额外保护层。
<file_sep>/microservice-provider-user-my-metadata/readme.md
# microservice-provider-user-my-metadata
> 简单的Eureka自定义元数据示例。Eureka的元数据分为两种,分别是标准元数据和自定义元数据。
> 标准元数据指的是主机名、IP地址、端口号、状态页和健康检查等信息,这些信息都会被发布在服务注册表中,用于服务之间的调用。自定义元数据可以使用eureka.instance.metadata-map配置。
* 只有一个自定义的接口:根据id获取用户信息
* 使用H2作为内存数据库
* 集成了actuator
* 集成了Eureka服务,可以自动注册到服务中心
* 在配置文件中定义了一个名为`my-metadata`的Eureka元数据<file_sep>/microservice-consumer-movie-feign/readme.md
# microservice-consumer-movie-feign
> 简单的微服务示例,作为服务消费者,使用feign与服务提供者通信
* 只有一个自定义的接口:根据id获取用户信息,调用微服务api获取用户信息
* 集成了Eureka服务,可以自动注册到服务中心
* 访问[http://localhost:8010/1](http://localhost:8010/1)<file_sep>/microservice-consumer-movie-feign-hystrix-fallback-factory/readme.md
# microservice-consumer-movie-feign-hystrix-fallback
> 简单的微服务示例,作为服务消费者,使用feign与服务提供者通信,测试Hystrix
* Feign的fallback,使用`@FeignClient`的fallback属性指定回退类
* 只有一个自定义的接口:根据id获取用户信息,调用微服务api获取用户信息
* 集成了Eureka服务,可以自动注册到服务中心
* 启动microservice-discovery-eureka。
* 启动microservice-provider-user。
启动microservice-consumer-movie-feign-hystrix-fallback。
* 访问[http://localhost:8010/user/1](http://localhost:8010/user/1),可正常获得结果
* 停止microservice-provider-user
* 再次访问[http://localhost:8010/user/1](http://localhost:8010/user/1),可获得如下结果。说明当用户微服务不可用时,进入了回退的逻辑.
``` json
{
"id": -1,
"username": null,
"name": "默认用户",
"age": null,
"balance": null
}
```<file_sep>/microservice-discovery-eureka-authenticating/readme.md
# microservice-discovery-eureka-security
> 简单的Eureka服务注册中心使用示例,作为Eureka Server,并且添加用户认证,需要登录才能访问Eureka Server
* 访问[http://localhost:8761](http://localhost:8761),输入用户名:user,密码:<PASSWORD><file_sep>/microservice-simple-consumer-movie/readme.md
# microservice-simple-consumer-movie
> 简单的微服务示例,作为服务消费者
* 只有一个自定义的接口:根据id获取用户信息,调用微服务api获取用户信息
* 访问[http://localhost:8010/1](http://localhost:8010/1)
|
aeb127feff93905e738010a70e2a6f7f19e8ad29
|
[
"Markdown",
"Java"
] | 18
|
Markdown
|
Beauxie/spring-cloud-study
|
f80aafefc4eb9f6067f4065549cb0d8e5dde69f9
|
c98955cb3a8d5cf4c047f694e0008fcb723e775e
|
refs/heads/master
|
<file_sep>## Apriori Algorithm
<NAME>, 114117098
### Task
To implement the Apriori algorithm and use it to mine category sets that are frequent in the input data. The minimum support to be used on 0.01
### Input
A dataset(“categories.txt”) that consists of the category lists of 77,185 places in the US. Each line corresponds to the category list of one place, where the list consists of a number of category instances (e.g., hotels, restaurants, etc.) that are separated by semicolons.
### Output
Two files named Pattern.txt in the folder /results, one having length 1 frequent categories and the other having all frequent category sets.
### Running the Program
This Python program is written for the version 3.8 . Make sure you have atleast python 3.7 installed.
No external libraries are necessary, this is a native implementation.
__To run the program:__
Clone the repo
```bash
git clone <EMAIL>:yagneshlp/bdaAssignment2.git
```
Navigate to the folder and run the program
```bash
cd bdaAssignment2
python3 code.py
```
Wait for the program to finish executing.Then
```bash
cd results
ls
```
You can find two folders with solutions to 2 sub parts of the task.
_To view results for first part_
```bash
cd "part_A - L1 Frequent Categories"
nano patterns.txt
```
_To view results for second part_
```bash
cd "part_B - All Frequent Categories"
nano patterns.txt
```
<file_sep>#!/usr/bin/python3
import os
import operator
from collections import defaultdict
from itertools import combinations, chain
class Apriori:
def __init__(self, minSupport):
#Constructor
self.support_count = defaultdict(int)
self.minSupport = minSupport
def read_transactions_from_file(self, transaction_file):
#Read transactions from the input file.
with open(transaction_file, "r") as infile:
transactions = [set(line.rstrip("\n").split(";"))
for line in infile]
return transactions
def get_one_itemset(self, transactions):
#Gets unique items from the list of transactions.
one_itemset = set()
for transaction in transactions:
for item in transaction:
one_itemset.add(frozenset([item]))
return one_itemset
def self_cross(self, Ck, itemset_size):
#Takes union of a set with itself to form bigger sets.
Ck_plus_1 = {itemset1.union(itemset2)
for itemset1 in Ck for itemset2 in Ck
if len(itemset1.union(itemset2)) == itemset_size}
return Ck_plus_1
def prune_Ck(self, Ck, Lk_minus_1, itemset_size):
# a set of k-itemsets with Ck's whose Ck_minus_1's are in Lk_minus_1
Ck_ = set()
for itemset in Ck:
Ck_minus_1 = list(combinations(itemset, itemset_size-1))
flag = 0
for subset in Ck_minus_1:
if not frozenset(subset) in Lk_minus_1:
flag = 1
break
if flag == 0:
Ck_.add(itemset)
return Ck_
def get_min_supp_itemsets(self, Ck, transactions):
#Returns those itemsets whose support is > minSupport
temp_freq = defaultdict(int)
# update support count of each itemset
for transaction in transactions:
for itemset in Ck:
if itemset.issubset(transaction):
temp_freq[itemset] += 1
self.support_count[itemset] += 1
N = len(transactions)
Lk = [itemset for itemset, freq in temp_freq.items()
if freq/N > self.minSupport]
return set(Lk)
def frequent_item_set(self, transactions):
#returns each itemset in K_itemset has support > minSupport
K_itemsets = dict()
Ck = self.get_one_itemset(transactions)
Lk = self.get_min_supp_itemsets(Ck, transactions)
k = 2
while len(Lk) != 0:
K_itemsets[k-1] = Lk
Ck = self.self_cross(Lk, k)
Ck = self.prune_Ck(Ck, Lk, k)
Lk = self.get_min_supp_itemsets(Ck, transactions)
k += 1
return K_itemsets
def subsets(self, iterable):
#Returns subsets of a set.
list_ = list(iterable)
subsets_ = chain.from_iterable(combinations(list_, len)
for len in range(len(list_)+1))
subsets_ = list(map(frozenset, subsets_))
return subsets_
def write_part_1(self, K_itemsets):
#Writes Length 1 frequent itemsets with their support to a file.
main_dir = "./results/part_A - L1 Frequent Categories"
if not os.path.exists(main_dir):
os.makedirs(main_dir)
outfile_path = "./results/part_A - L1 Frequent Categories/patterns.txt"
with open(outfile_path, "w") as outfile:
for key, values in K_itemsets.items():
if key > 1:
break
for value in values:
support_ct = self.support_count[value]
outfile.write("{support}:{label}\n".format(
support=support_ct,
label=";".join(list(value))
))
def write_part_2(self, K_itemsets):
#Writes the frequent itemsets with their support to a file.
main_dir = './results/part_B - All Frequent Categories'
if not os.path.exists(main_dir):
os.makedirs(main_dir)
outfile_path = "./results/part_B - All Frequent Categories/patterns.txt"
with open(outfile_path, "w") as outfile:
for key, values in K_itemsets.items():
for value in values:
support_ct = self.support_count[value]
outfile.write("{support}:{label}\n".format(
support=support_ct,
label=";".join(list(value))
))
if __name__ == "__main__":
print("Assignment 2 | CSOE17 Big Data Analytics | 114117098")
print("Processing...")
in_transaction_file = "./categories.txt"
ap = Apriori(minSupport=0.01) #given in problem statement
transactions = ap.read_transactions_from_file(in_transaction_file)
K_itemsets = ap.frequent_item_set(transactions)
ap.write_part_1(K_itemsets)
ap.write_part_2(K_itemsets)
print("•○| Results generated, they can be found at /results |○•")
|
49caa82475482d2044d19ac0a28f4cdc98f178e4
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
yagneshlp/bdaAssignment2
|
36d77c79ab98e159cfccc73a65af120ff83b60d8
|
53d9daa8c21e8482872216bf26bb3849d14563ba
|
refs/heads/master
|
<file_sep># JS-Online-Test
https://arman-melikyan.github.io/JS-Online-Test/.
<file_sep>import { questions } from './questions.js'
import { innerText, answerResult } from './helpers.js'
const buttons = document.getElementsByTagName('button')
const answerButtons = document.getElementById('question-content')
const start = document.getElementById('start')
const div = document.querySelector('#test')
const click = document.getElementById('cl')
let plus = 0;
let curAnswer = 0;
let countAnswer = questions.length;
const counter = {}
const timer = (min) => {
if(min > 0) {
counter.timer = setInterval(() => {
min--;
let sec = min;
const mins = Math.floor(sec / 60);
sec -= mins * 60;
document.getElementById('timer').style.display = 'block';
document.getElementById('minute').innerHTML = mins;
document.getElementById('secund').innerHTML = sec;
if(min === 0) {
clearInterval(counter.timer);
document.getElementById('timer').style.display = 'none';
document.getElementById('timer').id = 'stop';
answerButtons.style.display = 'none';
document.getElementById('question').style.display='none';
let percent = Math.round(plus/countAnswer*100);
let resp = 'Bad'
if(percent>50) {
resp = 'GOOOD'
};
innerText('result', `
<span>Correct Answer ${plus} / ${countAnswer}</span>
<hr>
<b>${percent} %</b>
`);
document.querySelector('#test').style.display = 'block'
}
},1000);
}
}
const check = num => {
if (num == 0) {
answerButtons.style.display = 'block';
start.style.display = 'none';
innerText('question', questions[curAnswer][0])
innerText('option1', questions[curAnswer][1])
innerText('option2', questions[curAnswer][2])
innerText('option3', questions[curAnswer][3])
innerText('option4', questions[curAnswer][4])
timer(300)
} else {
answerResult(questions[curAnswer], num)
if (num == questions[curAnswer][5]) {
plus++
}
curAnswer++
if (curAnswer < countAnswer) {
innerText('question', questions[curAnswer][0])
innerText('option1', questions[curAnswer][1])
innerText('option2', questions[curAnswer][2])
innerText('option3', questions[curAnswer][3])
innerText('option4', questions[curAnswer][4])
} else {
answerButtons.style.display = 'none'
innerText('question', '')
div.style.display = 'block'
const percent = Math.round(plus / countAnswer * 100)
let resp = 'Bad'
if (percent > 50) {
resp = 'GOOOD'
}
innerText('result', `
<span>Correct Answer ${plus} / ${countAnswer}</span>
<hr>
<b>${percent} %</b>
`);
document.getElementById('timer').style.display = 'none';
clearInterval(counter.timer);
document.getElementById('timer').id = 'stop';
}
}
}
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', e => {
const value = e.target.value
check(value)
})
}
<file_sep>
export const innerText = (id, value) => {
document.getElementById(id).innerHTML = value
}
export const answerResult = (question, num) => {
const section = document.createElement('section')
section.innerHTML = `
<h3>${question[0]}</h3>
<p>Ճիշտ պատասխանն է ՝ <b>${question[question[5]]}</b></p>
<p>Դուք ընտրել եք ՝ <b>${question[num]}</b></p>
<hr>
`
document.querySelector('#test').appendChild(section)
}
|
1e195316d0932f7018a0e603a34a6f3b37cbe18e
|
[
"Markdown",
"JavaScript"
] | 3
|
Markdown
|
arman-melikyan/JS-Online-Test
|
fcc341fed298ee9f9b7adabf738a1322842bf0ac
|
3644dcf34bc8fdfd0f5a8ed1b798c32d37f7321a
|
refs/heads/master
|
<file_sep># This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
seed_books = [
{:title => 'Of Mice and Men', :genre => 'Drama', :description => 'Compelling story of two outsiders striving to find their place in an unforgiving world.', :isbn_number => '0142000671',
:publish_date => '08-Jan-2002'},
{:title => 'Lord of the Flies', :genre => 'Action and Adventure', :description => 'Group of British boys stranded on an uninhabited island have to survive.', :isbn_number => '0140283331',
:publish_date => '01-Oct-1999 '},
{:title => 'Pride and Prejudice', :genre => 'Romance', :description => 'Courtship and romance in the eighteenth-century setting.', :isbn_number => '0679783261',
:publish_date => '10-Oct-2000 '},
{:title => 'The Count of Monte Cristo', :genre => 'Action and Adventure', :description => 'Thrown in prison for a crime he has not committed, <NAME> is confined to the grim fortress of If.', :isbn_number => '0140449264',
:publish_date => '27-May-2003 '},
{:title => 'All Quiet on the Western Front ', :genre => 'Drama', :description => 'The horros of WWI through the eyes of a German soldier.', :isbn_number => '0449213943',
:publish_date => '12-Mar-1987 '}
]
seed_books.each do |book|
Book.create!(book)
end<file_sep>
FactoryBot.define do
factory :book do
title 'A Fake Title' # default values
author '<NAME>'
end
end<file_sep>Given(/^the following books exist:$/) do |table|
# table is a Cucumber::MultilineArgument::DataTable
table.hashes.each do |book|
Book.create!(book)
end
end
Then(/^the author of "([^"]*)" should be "([^"]*)"$/) do |arg1, arg2|
Book.find_by_title(arg1).author == arg2
end
<file_sep>
class Book < ActiveRecord::Base
def self.all_genres ; ['Science fiction', 'Drama', 'Action and Adventure', 'Romance', 'Mystery', 'Horror'] end
def self.similar_books(book)
Book.where author: book.author
end
end
|
71cb440409564e0a0c5cfc4fc76bfc6a83222ef6
|
[
"Ruby"
] | 4
|
Ruby
|
fbobg05/myfavoritebooks
|
1e7d2d1917720cec32545062a972f8e8560c2542
|
17d272c7b68d7347a82044c66a7d0befca9ebc66
|
refs/heads/main
|
<file_sep>#!/usr/bin/env python3
"""
Check that a merge request's POM artifact version is greater than
the target branch's.
"""
import pomversion
import os
import subprocess
import click
from sys import argv, stdout, stderr
from subprocess import PIPE
def eprint(*args):
"""Prints to stderr"""
print(*args, file=stderr)
def load_pom(commit_ish, pom_file="pom.xml"):
"""Loads the contents of a POM file.
Parameters
----------
commit_ish
The git commit-ish to load the POM file from. If None is given
it will load the POM file from the working directory.
pom_file
Path to POM file. Defaults to "pom.xml".
Returns
-------
str
The contents of the POM file from the given commit-ish.
"""
if commit_ish is None:
with open(pom_file, "r") as file:
return file.read()
command = ("git", "show", f"{commit_ish}:{pom_file}")
process = subprocess.run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
if process.returncode != 0:
raise(FileNotFoundError(process.stderr.strip()))
return process.stdout
def load_version(commit_ish, description, pom_file="pom.xml"):
"""Loads the artifact version from a POM file.
If an error occured while loading the POM, or while extracting the
version string, None will be returned and an appropriate error
message will be sent to stderr.
Parameters
----------
commit_ish
The git commit-ish to load the POM file from. If None is given
it will load the POM file from the working directory.
description
Nature of the commit-ish to use in error messages. For example:
"Source", or "Target".
pom_file
Path to POM file. Defaults to "pom.xml".
Returns
-------
semantic_version.Version, or None
The artifact version from the POM file as a semantic version.
"""
try:
pom_xml = load_pom(commit_ish, pom_file=pom_file)
return pomversion.from_xml(pom_xml)
except FileNotFoundError as err:
eprint(f'Error retrieving POM file: "{err}"')
except pomversion.InvalidVersionError as err:
eprint(f'{description} version is invalid: "{err.version_string}"')
except pomversion.MissingVersionError:
eprint(f"{description} version is missing")
return None
@click.command()
@click.argument("target_commit_ish")
@click.argument("source_commit_ish", required=False)
@click.option("--pom-file", default="pom.xml", help="Path to pom file. Defaults to pom.xml.")
@click.option("--quiet", "-q", is_flag=True, default=False, help="Only report errors.")
def mr_version_check(target_commit_ish, source_commit_ish, pom_file, quiet):
output = open(os.devnull, "w") if quiet else stdout
source_version = load_version(source_commit_ish, "Source", pom_file=pom_file)
if source_version is None:
exit(1)
print(f"Source version: {source_version}", file=output)
target_version = load_version(target_commit_ish, "Target", pom_file=pom_file)
if target_version is None:
exit(0)
print(f"Target version: {target_version}", file=output)
if source_version <= target_version:
eprint("Current version must be greater than target version")
exit(1)
if __name__ == "__main__":
mr_version_check()
<file_sep># python-play
A place for random snippets of python while I learn the language.
<file_sep>"""Load an artifact version from a POM file or XML."""
from semantic_version import Version
import xml.etree.ElementTree as ElementTree
import io
POM_NAMESPACE = {"pom": "http://maven.apache.org/POM/4.0.0"}
class InvalidVersionError(Exception):
def __init__(self, version_string, message=None):
message = message or f"Invalid version string '{version_string}'"
super().__init__(version_string, message)
self.version_string = version_string
self.message = message
def __str__(self):
return self.message
class MissingVersionError(Exception):
def __init__(self):
self.message = "Missing version"
def __str__(self):
return self.message
def load(file_or_filename="pom.xml"):
"""Loads the version from a POM file
Parameters
----------
file_or_filename : str
A file object or a file name to load the POM from.
Returns
-------
semantic_version.Version
The version from the POM file as a semantic version.
"""
root = ElementTree.parse(file_or_filename)
elements = root.findall("./pom:version", POM_NAMESPACE)
# doc = etree.parse(file_or_filename)
# elements = doc.xpath("/pom:project/pom:version", namespaces=POM_NAMESPACE)
if len(elements) < 1:
raise MissingVersionError()
version_string = elements[0].text.strip()
try:
return Version(version_string.strip())
except ValueError as err:
raise InvalidVersionError(version_string, str(err)) from None
def from_xml(xml_string):
"""Loads the version from POM XML
Parameters
----------
file_or_xml_string : str
An XML string
Returns
-------
semantic_version.Version
The version from the XML as a semantic version.
"""
return load(io.StringIO(xml_string))
<file_sep>import pytest
import pomversion
import semantic_version
import lxml
# Helpers
def load_pom_xml(filename):
with open(filename, "r") as file:
return file.read()
def load_artifact_version(filename):
doc = lxml.etree.parse(filename)
version_elements = doc.xpath("/pom:project/pom:version", namespaces=pomversion.POM_NAMESPACE)
if len(version_elements) == 0:
return None
return version_elements[0].text.strip()
# pomversion.load tests
def test_load_without_parameters():
expected_artifact_version = semantic_version.Version(load_artifact_version("pom.xml"))
assert pomversion.load() == expected_artifact_version
def test_load_with_filename():
expected_artifact_version = semantic_version.Version(load_artifact_version("pom.xml"))
assert pomversion.load("pom.xml") == expected_artifact_version
def test_load_with_file():
expected_artifact_version = semantic_version.Version(load_artifact_version("pom.xml"))
with open("pom.xml", "r") as file:
assert pomversion.load(file) == expected_artifact_version
def test_load_with_invalid_artifact_version():
with pytest.raises(pomversion.InvalidVersionError):
pomversion.load("invalid-version-pom.xml")
def test_load_with_missing_artifact_version():
with pytest.raises(pomversion.MissingVersionError):
pomversion.load("missing-version-pom.xml")
def test_load_with_missing_file():
with pytest.raises(OSError):
pomversion.load("no-such-pom.xml")
# pomversion.from_xml tests
def test_from_xml():
expected_artifact_version = semantic_version.Version(load_artifact_version("pom.xml"))
pom_xml = load_pom_xml("pom.xml")
assert pomversion.from_xml(pom_xml) == expected_artifact_version
def test_from_xml_with_invalid_artifact_version():
pom_xml = load_pom_xml("invalid-version-pom.xml")
with pytest.raises(pomversion.InvalidVersionError):
pomversion.from_xml(pom_xml)
def test_from_xml_with_missing_artifact_version():
pom_xml = load_pom_xml("missing-version-pom.xml")
with pytest.raises(pomversion.MissingVersionError):
pomversion.from_xml(pom_xml)
<file_sep>#!/usr/bin/env python3
"""
Check that a merge request's POM artifact version is greater than
the target branch's.
"""
import pomversion
import os
import subprocess
from sys import argv, stdout, stderr
from subprocess import PIPE
def eprint(*args):
"""Prints to stderr"""
print(*args, file=stderr)
class MergeRequestVersionCheck:
def __init_(self, target_commit_ish, source_commit_ish, pom_file, quiet):
self.target_commit_ish = target_commit_ish
self.source_commit_ish = source_commit_ish
self.pom_file = pom_file
self.quiet = quiet
self.output = os.devnull if quiet else stdout
def pom_from_file(self):
with open(self.pom_file, "r") as file:
return file.read()
def pom_from_commit_ish(self, commit_ish):
command = ("git", "show", f"{commit_ish}:{self.pom_file}")
process = subprocess.run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
if process.returncode != 0:
raise(FileNotFoundError(process.stderr.strip()))
return process.stdout
def load_pom(self, commit_ish):
if commit_ish is None:
return self.pom_from_file()
return self.pom_from_commit_ish(commit_ish)
def load_version(self, commit_ish, description):
try:
pom_xml = self.load_pom(commit_ish)
return pomversion.from_xml(pom_xml)
except FileNotFoundError as err:
eprint(f'Error retrieving POM file: "{err}"')
except pomversion.InvalidVersionError as err:
eprint(f'{description} version is invalid: "{err.version_string}"')
except pomversion.MissingVersionError:
eprint(f"{description} version is missing")
return None
def check(self):
source_version = self.load_version(self.source_commit_ish, "Source")
if source_version is None:
return(1)
print(f"Source version: {source_version}", file=self.output)
target_version = self.load_version(self.target_commit_ish, "Target")
if target_version is None:
return(0)
print(f"Target version: {target_version}", file=self.output)
if source_version <= target_version:
eprint( "Current version must be greater than target version")
return(0)
<file_sep>import functools
def memoize(func):
try:
return functools.cache(func)
except AttributeError:
return functools.lru_cache(maxsize=2)(func)
<file_sep>from memoize import memoize
@memoize
def some_function():
print("Getting the thing")
return "The thing"
x = some_function()
y = some_function()
print(x)
print(y)
@memoize
def power_up(value, by=2):
print(f"Powering up {value} by {by}")
return value ** by
def square_this(value):
return power_up(value, by=2)
print(square_this(4))
print(square_this(5))
print(square_this(4))
print(square_this(5))
print(power_up(4, by=3))
print(power_up(5, by=4))
print(power_up(4, by=3))
print(power_up(5, by=4))
print(power_up(4, by=4))
print(power_up(5, by=2))
print(power_up(4, by=4))
print(power_up(5, by=2))
|
4ba4b31c5aa48d0eec7041fbb1b462a05babaadc
|
[
"Markdown",
"Python"
] | 7
|
Python
|
johncarney/python-play
|
7b9172b55be0c0d34baba583d1c5a8f1a794f6f2
|
221cb13488214c0cce953c6a4095df53a17af68c
|
refs/heads/master
|
<file_sep>/******************************************************************************
** Much of the structure of this JavaScript is related to the ajaxcode file
** demo.js posted from the CS 290 lecture.
*****************************************************************************/
var favorites = null;
function Gist(gName, gURL) {
this.gName = gName;
this.gURL = gURL;
}
function addGist(favorites, gist) {
if(gist instanceof Gist) {
favorites.gists.push(gist);
localStorage.setItem('userFavorites', JSON.stringify(favorites));
return true;
}
console.error('Not a gist!');
return false;
}
function ddGist(Gist) {
var dl = document.createElement('dl');
var entry = dlEntry('', Gist.gName);
dl.appendChild(entry.dt);
dl.appendChild(entry.dd);
entry = dlEntry('', Gist.gURL);
entry.a.href = Gist.gURL;
entry.dd.appendChild(entry.a);
dl.appendChild(entry.a);
dl.appendChild(entry.favSubmit);
return dl;
}
function dlEntry(term, definition) {
var dt = document.createElement('dt');
var dd = document.createElement('dd');
var a = document.createElement('a');
dt.innerText = term;
dd.innerText = definition;
a.innerHTML = definition;
var favSubmit = document.createElement('input');
if(definition.includes('http')) {
favSubmit.type = "button";
favSubmit.name = "FavSubmitButton";
favSubmit.value = "Save";
favSubmit.id = "FavFormSubmit";
}
return {'dt':dt, 'dd':dd, 'a':a, 'favSubmit':favSubmit};
}
function createGistList(ul, name, url) {
var li = document.createElement('li');
var newGist = new Gist(name, url);
li.appendChild(ddGist(newGist));
ul.appendChild(li);
}
function getGists() {
var req = new XMLHttpRequest();
if(!req) {
throw 'Unable to create Http Request!';
}
var url = 'https://api.github.com/gists/public';
req.onreadystatechange = function(){
if(this.readyState == 4) {
for(var i = 0; i < 30; i++) {
var gistIn = JSON.parse(this.responseText);
var name = gistIn[i].description;
if(name == null || name == "") {
name = "No Description Provided";
}
var gistURL = gistIn[i].url;
createGistList(document.getElementById('gists'), name, gistURL);
}
var gistFavButtons = document.getElementsByName('FavSubmitButton');
for(var j = 0; j < 30; j++) {
gistFavButtons[j].onclick = function() {
var tmpName = this.parentNode.childNodes[1].innerText;
var tmpURL = this.parentNode.childNodes[2].innerText;
window.alert(tmpName + " added to favorites!");
var tmpGist = new Gist(tmpName, tmpURL);
addGist(favorites, tmpGist);
};
}
}
};
req.open('GET', url);
req.send();
}
function submitToGetGists() {
getGists();
}
function gistSearch() {
var searchName = document.getElementById("searchField").value;
var req = new XMLHttpRequest();
if(!req) {
throw 'Unable to create Http Request!';
}
var url = 'https://api.github.com/gists/public';
req.onreadystatechange = function() {
if(this.readyState == 4) {
var count = 0;
for(var i = 0; i < 30; i++) {
var gistIn = JSON.parse(this.responseText);
var name = gistIn[i].description;
if(name == null || name == "") {
name = "No Description Provided";
}
var gistURL = gistIn[i].url;
if(name.includes(searchName)) {
createGistList(document.getElementById('gists'), name, gistURL);
count += 1;
}
}
if(count == 0) {
window.alert("No recent gists found by that name!");
}
}
};
req.open('GET', url);
req.send();
}
window.onload = function() {
var favoritesStr = localStorage.getItem('userFavorites');
if(favoritesStr == null) {
favorites = {'gists': []};
localStorage.setItem('userFavorites', JSON.stringify(favorites));
} else {
favorites = JSON.parse(localStorage.getItem('userFavorites'));
var gistFavoriteList = favorites.gists;
for(var i = 0; i < gistFavoriteList.length; i++) {
createGistList(document.getElementById('favoritesList'), gistFavoriteList[i].gName, gistFavoriteList[i].gURL);
}
}
}
|
2a6b22f948b9afd7cc488713687be88cd8069eb2
|
[
"JavaScript"
] | 1
|
JavaScript
|
friendoflore/github_api_interaction
|
44057762e1fa7e8ed9a16719bd2c3ccf4dbb92e6
|
46a1cae9bc34e557b526e55cea1466d1d6e73d79
|
refs/heads/master
|
<repo_name>DoughtCom/z-rocks<file_sep>/src/main/copier.js
import { app } from 'electron';
import path from 'path';
import actions from '../renderer/store/actions'
import getSize from 'get-folder-size';
import fs from 'fs';
const dateformat = require('dateformat');
//Todo: Have the system search under /media/pi for the DCIM folder, for now every disk has to be named "DISK"
let cameraCard = '/media/pi/DISK/DCIM';
let cameraFolders = [];
let destination = '/media/pi/Image\ Dump';
let now = new Date();
const copyFolder = '!SD_Backup_' + dateformat(now, 'mm-dd-yy_HH-MM');
let destinationFolder = path.join(destination, copyFolder);
class Copier {
constructor(app) {
this.app = app;
//if the system is in development mode make sure you have c:\DCIM_Test and c:\DCIM_Dest with some test files in DCIM_Test
if (process.env.NODE_ENV === 'development')
{
cameraCard = 'C:\\DCIM_Test';
destination = 'C:\\DCIM_Dest';
destinationFolder = path.join(destination, copyFolder);
app.store.dispatch(actions.RESET_FILES);
}
}
//This fires on application start to do the work of finding all of the folders the system needs.
loadStore() {
app.store.dispatch(actions.RESET_STATE);
//Todo: Rewrite this messy code with regex and the ability to find any folder inside the DCIM folder
if (fs.existsSync(path.join(cameraCard, '101ND750')))
{
app.store.dispatch(actions.SET_CAMERA_CARD_LOCATION, '101ND750');
cameraFolders.push(path.join(cameraCard, '101ND750'));
}
if (fs.existsSync(path.join(cameraCard, '101ND800')))
{
app.store.dispatch(actions.SET_CAMERA_CARD_LOCATION, '101ND800');
cameraFolders.push(path.join(cameraCard, '101ND800'));
}
if (fs.existsSync(path.join(cameraCard, '101ND850')))
{
app.store.dispatch(actions.SET_CAMERA_CARD_LOCATION, '101ND850');
cameraFolders.push(path.join(cameraCard, '101ND850'));
}
if (fs.existsSync(path.join(cameraCard, '101GOPRO')))
{
app.store.dispatch(actions.SET_CAMERA_CARD_LOCATION, '101GOPRO');
cameraFolders.push(path.join(cameraCard, '101GOPRO'));
}
else {
app.store.dispatch(actions.SET_CAMERA_CARD_LOCATION, 'NOT FOUND');
}
app.store.dispatch(actions.SET_CAMERA_FOLDERS, cameraFolders);
if (fs.existsSync(destination))
{
app.store.dispatch(actions.SET_DESTINATION_FOLDER, destination);
}
else
{
app.store.dispatch(actions.SET_DESTINATION_FOLDER, 'NOT FOUND');
}
if (cameraFolders.length == 0)
{
this.loadFiles(cameraFolders[0]);
}
}
//This loads the files in each folder that the person selects they want to copy.
loadFiles(cameraFolder) {
if (fs.existsSync(cameraFolder)) {
let files = fs.readdirSync(cameraFolder);
let fileNames = files
.filter(fileName => fs.lstatSync(path.join(cameraFolder, fileName)).isFile());
app.store.dispatch(actions.SET_FILE_COUNT, fileNames.length);
getSize(cameraFolder, (err, size) => {
app.store.dispatch(actions.SET_FILE_SIZE, (size / 1024 / 1024).toFixed(2));
});
}
}
//This copies the files from the folders in the array of folders the person selected to copy.
copyFiles() {
try {
if (fs.existsSync(destination) && app.store.state.SelectedCameraFolders.length > 0) {
//Make the directory we set above.
fs.mkdirSync(destinationFolder);
//Set the state to copying so they can't double press the button and so that vue knows to set the button class.
app.store.dispatch(actions.SET_COPYING_STATE, true);
//Go through each folder that the person has selected and start copying files.
app.store.state.SelectedCameraFolders.forEach(cameraFolder => {
let files = fs.readdirSync(cameraFolder);
//Only grab files, ignore folders.
//Todo: Perhaps in the future we may want to only grab NEFs or JPGs ... oorrrr let the user decide.
let fileNames = files
.filter(fileName => fs.lstatSync(path.join(cameraFolder, fileName)).isFile());
fileNames.forEach(file => {
fs.copyFile(path.join(cameraFolder, file), path.join(destinationFolder, file), (err) => {
//If for whatever reason we get an error, dispatch it so that the vue component can show the user.
if (err) {
app.store.dispatch(actions.SET_ERROR_MESSAGE, err);
}
//Update the store with the current file and then increment the file index.
app.store.dispatch(actions.SET_FILE_BEING_MOVED, path.join(cameraFolder, file));
app.store.dispatch(actions.INCREMENT_CURRENT_FILE_INDEX);
});
});
});
}
} catch (error) {
//If for whatever reason we get an error, dispatch it so that the vue component can show the user.
app.store.dispatch(actions.SET_ERROR_MESSAGE, error);
//Reset the state to not copying.
app.store.dispatch(actions.SET_COPYING_STATE, false);
}
}
}
export default Copier;<file_sep>/docs/Installation.md
# Dev Installation and Deployment
- npm install
- npm run dev (to test code)
- Install WSL if you do not have this installed, you need a linux runtime to build for raspbian
- - Install Ubuntu and open up bash
- npm run build:rpi (to build the deb file for raspbian) from the bash in your ubuntu WSL
- Make sure you're in the root directory of the code, where the package.json is.
- scp ./build/z-rocks_0.1.0_armv7l.deb pi@192.168.1.124:~/z-rocks_0.1.0_armv7l.deb
- ssh to the raspberry pi
- run this inside the bash on the pi: sudo dpkg -i ~/z-rocks_0.1.0_armv7l.deb
---
#### Setup Raspberry Pi
- Install Raspbian to SD Card using etcher
- sudo nano /etc/xdg/lxsession/LXDE-pi/autostart
- - Add line: z-rocks
- - close and save
- sudo reboot (at this point if you've done all of the above it should autostart on boot)<file_sep>/README.md
# z-rocks
> A photo copier electronjs app made specifically for the RPi (4) to copy files off of an SD Card onto a backup drive.
The logo was inspired by my favorite childhood radio station [99.1 Z-Rock](https://youtu.be/XFLIf1OFHXM?t=120) and the name works as a pun to the company that invented the mouse that made photo copiers.
<img width="490" src="/docs/Screenshot-V.01.png" alt="electron-vue">
# z-rocks Notes
#### Dev Installation and Deployment
- npm install (if you're using windows do this from the windows powershell NOT WSL's bash)
- npm run dev (to test code/runtime)
- Install WSL if you do not have this installed, you need a linux runtime to build for raspbian
- Install Ubuntu and open up bash
- npm run build:rpi (to build the deb file for raspbian) from the bash in your ubuntu WSL
- Make sure you're in the root directory of the code, where the package.json is.
- scp ./build/z-rocks_0.1.0_armv7l.deb pi@192.168.1.124:~/z-rocks_0.1.0_armv7l.deb
#### Setup Raspberry Pi
- Install Raspbian to SD Card using etcher
- Follow instructions online for headless setup to get ssh working and to get it on wifi (if you do not have ethernet to utilize)
- Install z-rocks
- First time installing z-rocks you need to run the deb file from the GUI in raspbian for some reason cli does not work, *after this time however you can utilize the following command from bash*
- sudo dpkg -i ~/z-rocks_0.1.0_armv7l.deb
- sudo nano /etc/xdg/lxsession/LXDE-pi/autostart
- Add line: z-rocks
- close and save
- sudo reboot (at this point if you've done all of the above it should autostart on boot)
#### 3D Model
- [z-rocks case viewable model](https://myhub.autodesk360.com/ue29781b4/g/shares/SH919a0QTf3c32634dcff0055839dc1213d1?viewState=NoIgbgDAdAjCA0IDeAdEAXAngBwKZoC40ARXAZwEsBzAOzXjQEMyzd1C0YATCADgE4ATABYIAWgBmMQRLHCJAVkZiARv14LJAdggA2RluExGjYcLQBfEAF0gA)
- [z-rocks case download](https://www.thingiverse.com/thing:4167374)
---
# Notes from electron-vue
``` bash
# install dependencies
npm install
# serve with hot reload at localhost:9080
npm run dev
# build electron application for production
npm run build
# lint all JS/Vue component files in `src/`
npm run lint
```
#### Credits
- This project was generated with [electron-vue](https://github.com/SimulatedGREG/electron-vue) using [vue-cli](https://github.com/vuejs/vue-cli).
- Documentation about the original structure can be found [here](https://simulatedgreg.gitbooks.io/electron-vue/content/index.html).
- 3D Case was started by [CSD Salzburg](https://www.thingiverse.com/thing:1895374) and modified by me for the RPi 4 with some adjustments for this project.
|
4ec2d821e78fbed857d3a3a1f036b54965a33244
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
DoughtCom/z-rocks
|
d5107e24720062d2a740762bdb3217e6e45b90cf
|
5ee688f18e65722aa131d668dee2fe7601d50f67
|
refs/heads/master
|
<repo_name>cognitom/riot-action<file_sep>/demo/src/action-menu.js
import Action from 'riot-action'
/**
* Actions
* - actions are triggered via events
* - actions are automatically registered to its view as an events
*/
export default class $ extends Action {
/** provides the setting when mounting */
mount () {
const theme = localStorage.getItem('theme') || 'red'
this.update({ theme })
}
/**
* changes the color theme of the menubar
* @param { string } theme - selected theme
*/
change (theme) {
localStorage.setItem('theme', theme)
}
}
<file_sep>/demo/README.md
# Riot Action Demo
```bash
$ npm install
$ npm run build
$ superstatic
```
<file_sep>/lib/view.js
import riot from 'riot'
import route from 'riot-route'
/**
* Thin wrapper of `mount` and `route`
*/
class RiotActionView {
constructor (selector) {
this.r = route.create()
this.selector = selector
}
route (route, tag, options = {}) {
this.r(route, (...args) => {
const t = riot.mount(this.selector, tag, options)[0]
t.trigger('route', ...args)
})
return this
}
}
/**
* A factory method for RiotActionView
* @param { string } selector - point to mount the tag
* @returns { object } RiotActionView
*/
function mount (selector) {
return new RiotActionView(selector)
}
export default { mount }
<file_sep>/lib/action.js
/**
* Action
* Extend this class and define your actions (events)
*/
export default class Action {
constructor (view) {
this._view = view
this._tag_loading = true
const proto = Object.getPrototypeOf(this)
Object.getOwnPropertyNames(proto)
.filter(key => key != 'constructor' && typeof this[key] == 'function')
.forEach(key => {
this._view.on(key, this[key].bind(this))
})
}
update (obj, shouldRedraw = true) {
if (shouldRedraw)
this._view.update(obj)
else
Object.keys(obj).forEach(key => {
this._view[key] = obj[key]
})
}
route () {
// override this for custom route action
}
}
<file_sep>/demo/rollup.config.js
import riot from 'rollup-plugin-riot'
import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
import babel from 'rollup-plugin-babel'
export default {
entry: 'src/main.js',
dest: 'dist/bundle.js',
plugins: [
riot(),
resolve({ jsnext: true, main: true, browser: true }),
commonjs(),
babel()
]
}
<file_sep>/rollup.config.js
import babel from 'rollup-plugin-babel'
export default {
entry: 'index.js',
dest: 'dist/commonjs.js',
format: 'cjs',
external: ['riot', 'riot-route'],
plugins: [
babel()
]
}
<file_sep>/lib/mixin.js
export default {
/**
* Bind the tag to the instance of action class
*/
init: function() {
const Action = this.opts.action
if (Action)
// This is private. DO NOT ACCESS FROM TAG INSTANCE.
this._action = new Action(this)
}
}
<file_sep>/demo/src/action-notepad.js
import Action from 'riot-action'
import someBackendAPI from './someBackendAPI'
/**
* Actions
* - actions are triggered via events
* - actions are automatically registered to its view as an events
*/
export default class $ extends Action {
/**
* processes routing
* @param { string } id - id string passed from the router
*/
route (id) {
someBackendAPI.get(id)
.then(result => {
this.id = result.id
this.update({ message: result.message })
})
}
/**
* saves the current sheet
* @param { string } message - message to save
*/
save (message) {
someBackendAPI.save(message, this.id)
.catch(error => {
this.update({ error })
})
}
/** adds a new sheet */
add () {
someBackendAPI.add()
.then(result => {
this.id = result.id
this.update({ message: result.message })
})
}
}
<file_sep>/README.md
# Riot Action
This library provides an easy way to separate the view (`tag`) and the logic (`action`).
**NOTE: Riot Action is still in development**
## Basic usage
Write the view and apply the mixin `riot-action`:
```html
<memo>
<input type="text" value={ message || '' } onchange={ change }>
<button onclick={ click }>Clear</button>
<script>
this.change = (e) => {
this.trigger('save', this.message = e.target.value)
}
this.click = (e) => {
this.trigger('clear')
}
</script>
</memo>
```
Write the logic as a separated class:
```js
import Action from 'riot-action'
export default class $ extends Action {
// Actions
// - actions are triggered via events
// - actions are automatically registered to its view as an events
save (message) {
someAPI.save(message)
.catch(error => {
this.update({ error })
})
}
clear () {
someAPI.clearAll()
.then(() => {
this.update({ message: '' })
})
}
}
```
Combine the view and the logic:
```js
import riot from 'riot'
import { mixin } from 'riot-action'
import Memo from './action-memo'
import './memo.tag'
riot.mixin(mixin) // registers riot-action as a middleware
riot.mount('memo', { action: Memo })
```
Or:
```html
import Memo from './action-memo'
<app>
<memo action={ action.Memo } />
<script>
this.action = { Memo }
</script>
</app>
```
In both cases, the Action is passed by its attributes.
## Flow
- Events: the view use `this.trigger()` to tell something to the action
- Actions: do something in the action
- Updates: the action use `this.update()` to tell something to the view
`Action` class has `update()` method and it's the only way to control the view.
## Routings
Riot Action works perfectly with `riot-route`. And it has an utility class. You can create a new instance by `view.mount()`. The class has `route` method to register its route, and the method is chainable.
```javascript
import riot from 'riot'
import route from 'riot-route'
import { view, mixin } from 'riot-action'
// actions
import Notepad from './action-home'
import History from './action-detail'
// tags
import './app-home.tag'
import './app-detail.tag'
// registers riot-action as a middleware
riot.mixin(mixin)
// routings
view.mount('#container')
.route('home', 'app-home', { action: Home })
.route('detail/*', 'app-detail', { action: Detail })
route.start(true)
```
## HTML router (planned)
This feature has not been implemented yet.
```html
import Home from './action-home'
import Detail from './action-detail'
<app>
<route-group>
<route path="home"><app-home action={ action.Home } /></route>
<route path="detail/*"><app-detail action={ action.Detail } /></route>
</route-group>
<script>
this.action = { Home, Detail }
</script>
</app>
```
<file_sep>/demo/src/action-history.js
import Action from 'riot-action'
import someBackendAPI from './someBackendAPI'
/**
* Actions
* - actions are triggered via events
* - actions are automatically registered to its view as an events
*/
export default class $ extends Action {
/** processes routing */
route () {
someBackendAPI.all()
.then(result => {
this.update({ data: result, loaded: true })
})
}
/** clears the all sheets on the notepad */
clear () {
someBackendAPI.clearAll()
.then(result => {
this.update({ data: result })
})
}
}
<file_sep>/demo/src/main.js
import riot from 'riot'
import route from 'riot-route'
import { view, mixin } from 'riot-action'
// actions
import Menu from './action-menu'
import Notepad from './action-notepad'
import History from './action-history'
// tags
import './app-menu.tag'
import './app-notepad.tag'
import './app-history.tag'
// registers riot-action as a middleware
riot.mixin(mixin)
// routings
riot.mount('#menu', 'app-menu', { action: Menu })
view.mount('#container')
.route('notepad/*', 'app-notepad', { action: Notepad })
.route('history', 'app-history', { action: History })
route.start(true)
<file_sep>/test/specs/core.specs.js
describe('Core specs', function() {
var counter = 0, $, $$
before(function() {
$ = document.querySelector.bind(document)
$$ = document.querySelectorAll.bind(document)
// start router
route.start()
})
after(function() {
})
afterEach(function() {
counter = 0
})
it('action triggered', function() {
// TODO: create test
})
})
|
b57873df8881386ad10634f18048659424957bf6
|
[
"JavaScript",
"Markdown"
] | 12
|
JavaScript
|
cognitom/riot-action
|
6b3540187b14a0a160a8e53a2d877e591f40a9c3
|
67212da0bc10a76cd6115e80a37a8156c9584354
|
refs/heads/master
|
<repo_name>paulchenpmc/YT-Downloader<file_sep>/README.md
# YT-Downloader
### Wow, what the heck does this tool even do?
Great question. This tool is a user-friendly wrapper for the [youtube-dl command line program](https://github.com/ytdl-org/youtube-dl) with a couple extra bells and whistles. The intent of this tool is to provide a one-click solution to batch download playlists, and try to intelligently fill song metadata.
### Installation:
1. Ensure prerequisites are installed
1. [ffmpeg tool](https://ffmpeg.zeranoe.com/builds/)
1. Add /path/to/ffmpeg_folder/bin to your PATH environment variable
2. [Youtube-dl tool](https://yt-dl.org/latest/youtube-dl.exe)
1. Move youtube-dl.exe to /path/to/ffmpeg_folder/bin
3. Python 3
1. Install [python 3](https://www.python.org/downloads/), make sure to tick the box adding it to your PATH variable!
2. Install the python module mutagen. Open command prompt and enter the following:
`pip install mutagen`
2. Clone/download the YT-Downloader repository to your computer
### Usage:
1. Double click the download.bat file
2. Copy + paste a youtube playlist link into the command prompt window
3. Press enter
4. Wait for the download to finish<file_sep>/YT-DL.py
import os
import re
import argparse
import subprocess
from mutagen.easyid3 import EasyID3
download_command = 'youtube-dl -x --audio-format mp3 --audio-quality 0 --embed-thumbnail {}'
brackets_remove_list = ['audio', 'video', 'lyric', 'lyrics']
# Download the youtube videos to mp3 file format using ffmpeg
def youtube_download(youtube_playlist_link):
command = download_command.format(youtube_playlist_link)
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
while True:
try:
output = process.stdout.readline().decode()
if output == '' and process.poll() is not None:
break
if output:
print(output.strip())
except:
continue
process.wait()
if process.returncode != 0:
print('Error occurred during download, exiting...')
exit()
# Simple string processing on mp3 filenames to try and extract song metadata
def fill_metadata():
mp3_filepath_list,mp3_file_list = [],[]
# Find all mp3 files in subdirectories
for root, dirs, files in os.walk(os.getcwd()):
for file in files:
if file.endswith(".mp3"):
mp3_filepath_list.append(os.path.join(root, file))
mp3_file_list.append(file)
# Find and fill metadata for all mp3 files
for filepath,filename in zip(mp3_filepath_list,mp3_file_list):
# Clean filename
remove_list = []
match = re.search("(.*)(-.{11}.mp3)", filename) # Remove ffmpeg filenaming convention and .mp3 from filename
remove_list.append(match[2])
for keyword in brackets_remove_list:
match = re.search(".*([\(\[].*{}.*[\)\]]).*".format(keyword), filename, re.IGNORECASE) # Remove anything in brackets like (official audio), etc
if match is not None:
remove_list.append(match[1])
filename_cleaned = filename
for word in remove_list:
filename_cleaned = filename_cleaned.replace(word, '')
# Extract artist and song title from filename
dash_structure = re.search("(.*?) - (.*)", filename_cleaned)
# Typical dash structure used in many youtube song videos (e.g. Artist - Song Title)
if dash_structure is not None:
artist = dash_structure[1]
title = dash_structure[2]
# Assume Youtube video title is just the song name
else:
artist = None
title = filename_cleaned
# Edit metadata
audio = EasyID3(filepath)
audio['title'] = title
if artist:
audio['artist'] = artist
audio.save()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("playlist_link", help="The youtube playlist link to download and convert to audio.")
args = parser.parse_args()
youtube_playlist_link = args.playlist_link
youtube_download(youtube_playlist_link)
fill_metadata()
|
a6fb58125cc0cb7df3f199685dc29e5419dc0cc3
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
paulchenpmc/YT-Downloader
|
9e96818a0a4d0d2ee4db8efc7b0007eec1f79b7c
|
05e2c1f26b025329ed430b455ca315cf6cfe370c
|
refs/heads/develop
|
<file_sep>import {Component, Input, OnInit} from '@angular/core';
import {BehaviorSubject, interval, Observable, Subject, timer} from 'rxjs';
import {delay, map, takeUntil, tap} from 'rxjs/operators';
@Component({
selector: 'app-crossfade-buttons',
templateUrl: './crossfade-buttons.component.html',
styleUrls: ['./crossfade-buttons.component.scss']
})
export class CrossfadeButtonsComponent implements OnInit {
@Input()
readonly crossfade: (over: number) => void;
@Input()
readonly durations = [5, 10, 30, 60];
durationSubject = new BehaviorSubject<number>(this.durations[0]);
get duration$(): Observable<number> {
return this.durationSubject.asObservable();
}
directionSubject = new BehaviorSubject<'left' | 'right'>('left');
get direction$(): Observable<'left' | 'right'> {
return this.directionSubject.asObservable();
}
fading$: Observable<boolean>;
constructor() {
this.directionSubject.next('left');
}
ngOnInit(): void {
}
// TODO: Some kind of protection to let the animation play out when the duration is changed
click(duration: number): void {
this.durationSubject.next(duration);
}
fade(): void {
const duration = this.durationSubject.value; // The only time you should do this is in an instant function like this
this.crossfade(duration);
const timer$ = timer(duration * 1000);
this.fading$ = interval(10).pipe(
map(t => t < duration * 100),
takeUntil(timer$.pipe(
delay(1000) // Delay to allow t to become greater than the limit for a second
))
);
timer$.subscribe(() => this.changeDirection());
}
private changeDirection(): void {
this.directionSubject.next(this.directionSubject.value === 'left' ? 'right' : 'left');
}
}
<file_sep>import {Keys} from './keys';
export const environment = {
production: true,
firebase: {
apiKey: Keys.FIREBASE_API_KEY,
authDomain: 'mixer-37fd9.firebaseapp.com',
databaseURL: 'https://mixer-37fd9.firebaseio.com',
projectId: 'mixer-37fd9',
storageBucket: 'mixer-37fd9.appspot.com',
messagingSenderId: '460464382876',
appId: '1:460464382876:web:4bbcc4ec6f56e645b61e59',
measurementId: 'G-63JY572NYD'
}
};
<file_sep>import {Subject, timer} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
function duration(seconds: number): number {
return (seconds * 1000) / 100;
}
/**
* Lower the volume from max to min of a video over the period of time
* @param over: the period of time
* @param lower: the function to supply the falling number to
*/
export function lowerVolume(over: number, lower: (t: number) => void): void {
const stop = new Subject();
timer(0, duration(over)).pipe(
takeUntil(stop)
).subscribe(t => {
if (t >= 100) {
stop.next();
}
lower(100 - t);
});
}
/**
* Raise the volume from min to max of a video over the period of time
* @param over: the period of time
* @param raise: the function to supply the rising number to
*/
export function raiseVolume(over: number, raise: (t: number) => void): void {
const stop = new Subject();
timer(0, duration(over)).pipe(
takeUntil(stop)
).subscribe(t => {
if (t >= 100) {
stop.next();
}
raise(t);
});
}
<file_sep>import {YouTubeURLParser} from '@iktakahiro/youtube-url-parser';
export function parseURL(url: string): string | null {
return new YouTubeURLParser(url).getId();
}
<file_sep>import {Component, Input, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {AbstractControl, FormBuilder, FormGroup} from '@angular/forms';
import {YoutubeApiService} from '../../service/youtube.service';
import {BehaviorSubject, Observable, Subject} from 'rxjs';
import {VolumeService} from '../../service/volume.service';
import {YouTubePlayer} from '@angular/youtube-player';
import {isDefined} from '../../util/util';
import {map, switchMap, takeUntil} from 'rxjs/operators';
import {parseURL} from '../../util/parse-url';
@Component({
selector: 'app-youtube-video',
templateUrl: './youtube-video.component.html',
styleUrls: ['./youtube-video.component.scss']
})
export class YoutubeVideoComponent implements OnInit, OnDestroy {
@Input()
private readonly playerId: string;
@Input()
private readonly initialVolume: number;
@Input()
private readonly startSilent = false;
@ViewChild('player')
set player(player: YouTubePlayer) {
if (isDefined(player)) {
this._player = player;
this.initialisedSubject.next();
}
}
private _player: YouTubePlayer;
private readonly initialisedSubject = new Subject();
private readonly destroyed = new Subject();
readonly form: FormGroup;
private readonly id: AbstractControl;
private videoIdSubject = new Subject<string>();
videoId$ = new Observable<string>();
videoTitle$ = new Observable<string>();
constructor(private readonly volumeService: VolumeService,
private readonly youtubeService: YoutubeApiService,
formBuilder: FormBuilder) {
this.form = formBuilder.group({
id: ''
});
this.id = this.form.get('id');
this.initialisedSubject.subscribe(() => this.init());
this.videoId$ = this.videoIdSubject.asObservable().pipe(
takeUntil(this.destroyed)
);
this.videoTitle$ = this.videoId$.pipe(
switchMap(id => this.youtubeService.getDataForVideo(id)),
map(data => data.items[0].snippet.title),
takeUntil(this.destroyed)
);
this.videoId$.subscribe(console.log);
this.videoTitle$.subscribe(console.log);
}
private init(): void {
const initVolume = new Subject();
this._player.stateChange.pipe(
takeUntil(initVolume)
).subscribe(state => {
if (state.data === YT.PlayerState.PLAYING) {
this._player.setVolume(this.initialVolume);
initVolume.next();
}
});
this.volumeService.register(this._player, this.playerId);
this.volumeService.getVolume(this.playerId).pipe(
takeUntil(this.destroyed)
).subscribe(v => {
if (this._player.isMuted()) {
this._player.unMute();
}
this._player.setVolume(v);
});
this.videoIdSubject.next('oHg5SJYRHA0'); // Initialize to Rick Roll
}
ngOnInit(): void {
// TODO: Can we move this out? Directly manipulating the DOM is yucky
const tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
document.body.appendChild(tag);
}
ngOnDestroy(): void {
this.destroyed.next();
}
onSubmit(): void {
this.videoIdSubject.next(parseURL(this.id.value as string));
}
}
<file_sep>import {Component} from '@angular/core';
import {VolumeService} from '../../service/volume.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'YouTube Mixer';
readonly player1 = 'PLAYER_1';
readonly player2 = 'PLAYER_2';
private playing: 'PLAYER_1' | 'PLAYER_2' = 'PLAYER_1';
constructor(private readonly volumeService: VolumeService) {
}
crossfade(over: number): void {
if (this.playing === 'PLAYER_1') {
this.volumeService.crossfade(over, this.player1, this.player2);
this.playing = 'PLAYER_2';
} else {
this.volumeService.crossfade(over, this.player2, this.player1);
this.playing = 'PLAYER_1';
}
}
readonly fadeFunc = (over: number) => this.crossfade(over);
}
<file_sep>import {Injectable} from '@angular/core';
import {YouTubePlayer} from '@angular/youtube-player';
import {lowerVolume, raiseVolume} from '../util/youtube-player';
import {BehaviorSubject, Observable, Subject} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class VolumeService {
private readonly volumes: Map<string, Subject<number>> = new Map();
public register(player: YouTubePlayer, id: string): void {
this.volumes.set(id, new BehaviorSubject<number>(player.getVolume()));
}
public deregister(id: string): void {
this.volumes.delete(id);
}
public getVolume(id: string): Observable<number> {
return this.volumes.get(id).asObservable();
}
public crossfade(over: number, from: string, to: string): void {
lowerVolume(over, t => {
this.volumes.get(from).next(t);
});
raiseVolume(over, t => {
this.volumes.get(to).next(t);
});
}
}
<file_sep>import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {Keys} from '../../environments/keys';
@Injectable({
providedIn: 'root'
})
export class YoutubeApiService {
private readonly apiKey = Keys.YOUTUBE_API_KEY;
constructor(public http: HttpClient) { }
getDataForVideo(video: string): Observable<any> {
const url = 'https://www.googleapis.com/youtube/v3/videos?id=' + video + '&key=' + this.apiKey + '&part=snippet,statistics';
return this.http.get(url);
}
}
<file_sep>export function isDefined<T>(value: T | null | undefined): value is T {
return value != null;
}
export function isNotDefined<T>(value: T | null | undefined): value is null | undefined {
return !isDefined(value);
}
|
bfedf8826c180faa7a7bebc8c3f3f480e7da75c9
|
[
"TypeScript"
] | 9
|
TypeScript
|
Froopity/youtube-mixer
|
b0108f561ecb15aad036adefc62c9c69d78e9b70
|
68da4d6b56e827d2b5b892b8fc6b382f9ed30493
|
refs/heads/master
|
<repo_name>GerryHolt/upby<file_sep>/wp-content/themes/uppababy/template-locator.php
<?php
/*
Template Name: Retail Locator
*/
get_header(); the_post(); ?>
<div id="lcly-button-0"><a id="lcly-link-0" href="http://www.locally.com" target="_blank">Powered By Locally.com</a></div>
<script id="lcly-script-0" src="https://uppababy.locally.com/stores/map.js?company_id=24146&inline=1&no_link=1&company_name=UPPAbaby" async=""></script>
<style>
#lcly-button-0 {<br />
width: 100%!important;<br />
height: 100%!important;<br />
display: inline!important;<br />
}<br />
.mainImg {margin-bottom:0px!important;}<br />
.upSeo {display:none!important}<br />
#locator_links {padding:30px 0px!important;}<br />
</style>
<?php get_footer(); ?>
<file_sep>/wp-content/themes/uppababy/template-support.php
<?php
/*
Template Name: Support
*/
get_header(); the_post(); ?>
<?php
$pageBannerImage = get_field('banner_image');
$global_rows = get_field('default_accessories_banner', 'options'); // get all the rows
$rand_global_row = $global_rows[ array_rand( $global_rows ) ]; // get a random row
$rand_global_row_image = $rand_global_row['accessories_banner' ]; // get the sub field value
if(get_field('select_gradient_direction')) {
$gradient = get_field('select_gradient_direction');
}
if($pageBannerImage) { ?>
<section id="hero-banner" class="<?php echo $gradient; ?>" style="background-image:url('<?php echo $pageBannerImage['sizes']['hero-banner'] ?>'); background-size:cover; background-repeat:no-repeat;">
<div class="hero-content" <?php if(get_field('banner_content_padding')) {?>style="padding:<?php the_field('banner_content_padding');?>;" <?php } ?> <?php if( get_field('do_you_need_dark_text')){ ?>style="color:#666;"<?php } ?>>
<?php the_field('banner_content'); ?>
</div>
<?php } elseif($rand_global_row_image) { ?>
<section id="hero-banner" class="<?php echo $gradient; ?>" style="background-image:url('<?php echo $rand_global_row_image['sizes']['hero-banner'] ?>'); background-size:cover; background-repeat:no-repeat;">
<div class="hero-content" <?php if(get_field('banner_content_padding')) {?>style="padding:<?php the_field('banner_content_padding');?>;" <?php } ?> <?php if( get_field('do_you_need_dark_text')){ ?>style="color:#666;"<?php } ?>>
<?php the_field('banner_content'); ?>
</div>
<?php } ?>
</section>
<section id="support">
<div class="content-wrap">
<div class="contact-box">
<?php if(have_rows('address_box', 'option')) {
while(have_rows('address_box', 'option')) { the_row(); ?>
<h3><?php the_sub_field('address_header', 'option'); ?></h3>
<?php the_sub_field('address_text', 'option'); ?>
<?php } ?>
<?php } ?>
</div>
<div class="support-column">
<?php if(get_field('support_grid')) { ?>
<div class="support-list">
<ul class="support-item">
<?php while(have_rows('support_grid')) { the_row(); ?>
<li>
<a href="<?php the_sub_field('support_url'); ?>">
<?php $supportIMG = get_sub_field('support_image'); ?>
<img src="<?php echo $supportIMG['sizes']['support-image']; ?>" alt="<?php echo $supportIMG['alt']; ?>" class="title-img" />
<h4><?php the_sub_field('support_title'); ?></h4>
<p>
<?php the_sub_field('support_info'); ?>
</p>
</a>
</li>
<?php } ?>
</ul>
</div>
<?php } ?>
<?php if(get_field('distributor_information')) { ?>
<div class="support-content">
<div class="distributor-row">
<?php while(have_rows('distributor_information')) { the_row(); ?>
<h2><?php the_sub_field('distributor_country'); ?></h2>
<?php if(get_sub_field('country_details')): ?>
<p><i><?php the_sub_field('country_details'); ?></i></p>
<?php endif; ?>
<p class="name"><b><?php the_sub_field('distributor_name'); ?></b></p>
<p class="address"><?php the_sub_field('distributor_address'); ?></p>
<?php if(get_sub_field('distributor_phone_number')): ?>
<p class="phone"><b>Phone: </b><?php the_sub_field('distributor_phone_number'); ?></p>
<?php endif; ?>
<?php if(get_sub_field('distributor_fax')): ?>
<p class="fax"><b>Fax: </b><?php the_sub_field('distributor_fax'); ?></p>
<?php endif; ?>
<?php if(get_sub_field('distributor_email')): ?>
<p class="email"><b>Email: </b><?php the_sub_field('distributor_email'); ?></p>
<?php endif; ?>
<div class="inquiries">
<?php the_sub_field('customer_inquiries'); ?>
</div>
<?php if(get_sub_field('extra_information')): ?>
<?php while(have_rows('extra_information')) { the_row(); ?>
<p class="sub-header"><b><?php the_sub_field('content_header'); ?></b></p>
<p class="sub-details"><?php the_sub_field('content_details'); ?></p>
<?php } ?>
<?php endif; ?>
<?php if(get_sub_field('distributor_url')): ?>
<p class="url"><b>URL: </b><a href="<?php the_sub_field('distributor_url'); ?>" target="_blank"><?php the_sub_field('distributor_url'); ?></a></p>
<?php endif; ?>
<hr />
<?php } ?>
</div>
</div>
<?php } ?>
<?php if(get_field('content')) { ?>
<div class="support-content">
<?php the_field('content'); ?>
</div>
<?php } ?>
</div>
</div>
</section>
<?php get_footer(); ?>
<file_sep>/wp-content/themes/uppababy/template-spare-parts.php
<?php
/*
Template Name: Spare Parts
*/
get_header();
the_post();
//--- temporary CSS
if ( isset( $_SERVER['REQUEST_URI'] ) ) {
$ny_strpos = strpos( $_SERVER['REQUEST_URI'], 'spare-parts' );
}
$pageBannerImage = get_field('top_banner');
$global_rows = get_field('default_accessories_banner', 'options'); // get all the rows
$rand_global_row = $global_rows[ array_rand( $global_rows ) ]; // get a random row
$rand_global_row_image = $rand_global_row['accessories_banner' ]; // get the sub field value
if($pageBannerImage) {
?>
<section id="hero-banner" style="background-image:url('<?php echo $pageBannerImage['sizes']['hero-banner']; ?>'); background-size:cover; background-repeat:no-repeat;">
<?php } elseif($rand_global_row_image) { ?>
<section id="hero-banner" style="background-image:url('<?php echo $rand_global_row_image['sizes']['hero-banner']; ?>'); background-size:cover; background-repeat:no-repeat;">
<?php } ?>
</section>
<section id="sub-nav">
<?php
$subNav = get_field('select_sub_nav');
wp_nav_menu(
array(
'menu' => $subNav,
'container' => ''
)
);
?>
</section>
<section id="accessories-list">
<div class="acc-logo">
<?php $prodLogo = get_field('product_family_logo'); ?>
<img src="<?php echo $prodLogo['url']; ?>" alt=""/>
</div>
<?php
the_field('product_category_heading');
if(get_field('category_list')) {
while( have_rows('category_list') ) {
the_row();
$prodCat = get_sub_field('category_slug');
$prodSlug = $prodCat->slug;
$prodLabel = $prodCat->name;
$args = array(
'posts_per_page' => '-1',
'product_cat' => $prodSlug,
'post_type' => 'product',
'orderby' => 'menu_order',
);
?>
<div class="acc-section">
<h2><?php echo $prodLabel; ?></h2>
<?php
$query = new WP_Query( $args );
if( $query->have_posts() ) {
while( $query->have_posts() ) {
$query->the_post();
?>
<div class="item spare-part">
<?php $accIMG = get_field('hero_thumbnail');?>
<img src="<?php echo $accIMG['sizes']['acc-list-img'];?>" alt="" />
<h4 class="title"><?php the_title(); ?></h4>
<?php
$ny_product_id = $product->get_id();
if ( get_post_meta($ny_product_id, 'additional_information_simple', true) ) {
$ny_additional_info = get_post_meta( $ny_product_id, 'additional_information_simple', true );
if ( isset($ny_additional_info) && $ny_additional_info != 'Array' ) {
echo '<p class="rzt-cart-additional-info">';
echo $ny_additional_info;
echo '</p>';
}
}
echo '<p class="price">';
echo $product->get_price_html();
echo '</p>';
$ny_product_type = $product->get_type();
if ( $ny_product_type == 'variable' ) {
//wp_enqueue_script( 'wc-add-to-cart-variation' );
$ny_color_attributes_js_object = "";
$ny_dropdown_html_options = "";
$available_variations = $product->get_available_variations();
foreach ( $available_variations as $available_variation ) {
$ny_variation_object = new WC_Product_variation( $available_variation['variation_id'] );
if( $ny_variation_object->is_purchasable() && $ny_variation_object->is_in_stock() ) {
$ny_add_to_cart_text_conditional = ""; //__( 'Add to cart', 'woocommerce' )
} else {
$ny_add_to_cart_text_conditional = "_"; //__( 'Backorder', 'woocommerce' );
}
if ( isset($available_variation['attributes']['attribute_uppababy-color']) ) {
$ny_variation_color_code = $available_variation['attributes']['attribute_uppababy-color'];
}
//$ny_variation_color_name = $ny_variation_object->get_formatted_variation_attributes( true );
$ny_variation_color_name = wc_get_formatted_variation( $ny_variation_object );
$ny_variation_color_name = str_replace( 'Color: ', '', $ny_variation_color_name );
$ny_variation_color_name = str_replace( 'uppababy-color:', '', $ny_variation_color_name );
/*$ny_dropdown_html_options .= '<option value="'.$available_variation['variation_id']
.'_'.$ny_variation_color_code.'">'
.$ny_variation_color_name
.'</option>';*/
$ny_dropdown_html_options .= '
<option value="'.$available_variation['variation_id'].$ny_add_to_cart_text_conditional.'">'
.$ny_variation_color_name
.'</option>';
$ny_variation_price = $available_variation['price_html'];
$ny_dropdown_data_per_product = $available_variation['variation_id'].'|' .$ny_variation_color_code.'|'.$ny_variation_color_name.'|'.$ny_variation_price;
$ny_color_attributes_js_object .= 'ny_dropdown_data_for_all["'.$ny_product_id.'"] = "'
.$ny_dropdown_data_per_product.'";';
}
/*$a_href_to_return .= '<button style="display:none;" id="'
.esc_attr( $ny_product_id ).'" class="add_to_cart_button button" onclick=\"rzt_change_select_to_add_to_cart("'.$ny_product_id.'"); return false;\">ADD TO CART</button>'; */
$a_href_to_return = '
<form class="variations_form cart" method="post" enctype="multipart/form-data" id="form-'.$ny_product_id.'" name="form-'.$ny_product_id.'">
<input type="hidden" name="quantity" value="1">
<button type="button" class="single_add_to_cart_button button alt add_to_cart_button disabled" id="button-'.$ny_product_id.'" name="button-'.$ny_product_id.'" onclick="return false;">Choose a color</button>
<input type="hidden" name="add-to-cart" value="'.$ny_product_id.'">
<input type="hidden" name="product_id" value="'.$ny_product_id.'">
<input type="hidden" name="attribute_uppababy-color" id="selected_color_for_'.$ny_product_id.'" value="">
<input type="hidden" name="variation_id" class="variation_id" id="selected_variation_for_'.$ny_product_id.'" value="">
</form>';
$a_href_to_return .= '
<div class="select-box">
<select name="color" id="dropdown-'.$ny_product_id.'">
<option selected="" disabled="">Select Color</option>'
.$ny_dropdown_html_options
.'</select>
</div>';
//$a_href_to_return .='<script>'.$ny_color_attributes_js_object.'</script>';
}
if ( $ny_product_type == 'simple' ) {
if( $product->is_in_stock() ) {
$ny_class = ' class="'.esc_attr( isset( $class ) ? $class : 'button product_type_simple add_to_cart_button ajax_add_to_cart' ).'"';
$ny_onclick = ' onclick="rzt_run_the_add_to_cart_ajax( this, 0, '.esc_attr( $ny_product_id ).', '.esc_attr( isset( $quantity ) ? $quantity : 1 ).' )"';
} else {
$ny_class = ' class="'.esc_attr( isset( $class ) ? $class : 'button product_type_simple add_to_cart_button ajax_add_to_cart' ).' disabled out-of-stock"';
$ny_onclick = '';
}
$a_href_to_return =
'<p class="addtocart">
<a rel="nofollow" data-quantity="'.esc_attr( isset( $quantity ) ? $quantity : 1 )
.'" data-product_id="'.esc_attr( $ny_product_id )
.'" data-product_sku="'.esc_attr( $product->get_sku() )
.'"'.$ny_class.$ny_onclick.'>'
.esc_html( $product->add_to_cart_text() )
.'</a>
</p>';
}
echo $a_href_to_return;
?>
</div>
<?php
}
}
wp_reset_query();
echo '</div>';
}
}
?>
</section>
<?php get_footer(); ?><file_sep>/wp-content/themes/uppababy/template-overview.php
<?php
/*
Template Name: Overview
*/
get_header(); the_post(); ?>
<?php $bannerImg = get_field('banner_image'); ?>
<?php if(get_field('select_gradient_direction')) {
$gradient = get_field('select_gradient_direction');
} ?>
<section id="overview-banner" class="<?php echo $gradient; ?>" style="background-image:url('<?php echo $bannerImg['sizes']['hero-banner'] ?>'); background-size:cover; height:520px; width:1024px; background-repeat:no-repeat;">
<div class="hero-content" <?php if(get_field('banner_content_padding')) {?>style="padding:<?php the_field('banner_content_padding');?>;" <?php } ?> <?php if( get_field('do_you_need_dark_text')){ ?>style="color:#666;"<?php } ?>>
<?php if(get_field('banner_youtube')) {
$bannerYoutube = get_field('banner_youtube');?>
<a href="https://www.youtube.com/watch?v=<?php the_field('banner_youtube_id'); ?>" class="popup-youtube"><img src="<?php echo $bannerYoutube['url'] ?>" /></a>
<?php } ?>
<?php the_field('banner_content'); ?>
</div>
</section>
<?php $mobileBanner = get_field('mobile_banner');
$bannerOverlay = get_field('mobile_banner_overlay'); ?>
<section id="mobile-banner" style="background-image:url('<?php echo $mobileBanner['sizes']['mobile-image']; ?>'); background-size:cover; width:100%; background-repeat:no-repeat; position:relative; z-index:1; height:190px;">
<div class="mobile-overlay">
<img src="<?php echo $bannerOverlay['sizes']['mobile-image']; ?>" style="position:absolute; bottom:20px; left:30px; z-index:2; max-width:200px;"/>
</div>
</section>
<?php
$needSubNav = get_field('select_sub_nav');
if($needSubNav != 'none') { ?>
<section id="sub-nav">
<?php
$subNav = get_field('select_sub_nav');
wp_nav_menu(
array(
'menu' => $subNav,
'container' => ''
)
);
?>
</section>
<?php }?>
<section id="panels">
<?php if( have_rows('panel')) {
while(have_rows('panel')) { the_row();
if( get_row_layout() == 'image_only' ) { ?>
<div class="image-only panel">
<?php $panelImg = get_sub_field('panel_image'); ?>
<div class="wrap clearfix">
<a href="<?php the_sub_field('image_url'); ?>"><img src="<?php echo $panelImg['sizes']['full-column'] ?>" alt="naturally fire retardant" /></a>
</div>
</div>
<? } /* close image_only */
if( get_row_layout() == 'two_column_panel' ) { ?>
<div class="two-column panel">
<div class="wrap clearfix">
<?php if(get_sub_field('optional_background')) {
$panelBG = get_sub_field('optional_background')?>
<div class="two-col-bg" style="background-image:url('<?php echo $panelBG['url']; ?>'); min-height:<?php echo $panelBG['height']; ?>px; padding-top:<?php the_sub_field('top_padding');?>px; background-position:<?php the_sub_field('background_alignment'); ?>;">
<?php } else { ?>
<div class="two-col-bg">
<?php } ?>
<div class="left-col" <?php if(get_sub_field('left_side_padding')) { ?>style="padding:<?php the_sub_field('left_side_padding'); ?>;" <?php }?>>
<?php if( have_rows('left_side')) {
while(have_rows('left_side')) { the_row(); ?>
<?php if( get_row_layout() == 'select_image_left' ) { ?>
<div class="left-item" <?php if(get_sub_field('image_padding')) { ?>style="padding:<?php the_sub_field('image_padding'); ?>;" <?php }?>>
<?php if(get_sub_field('image_url')) { ?>
<?php $loneImg = get_sub_field('image_left'); ?>
<a href="<?php the_sub_field('image_url'); ?>"><img src="<?php echo $loneImg['url'] ?>" /></a>
<?php } else {?>
<?php $loneImg = get_sub_field('image_left'); ?>
<img src="<?php echo $loneImg['url'] ?>" />
<?php } ?>
</div>
<?php } ?>
<?php if( get_row_layout() == 'select_youtube_left' ) { ?>
<div class="left-item" <?php if(get_sub_field('youtube_padding')) { ?>style="padding:<?php the_sub_field('youtube_padding'); ?>;" <?php }?>>
<?php $Img = get_sub_field('youtube_image_left'); ?>
<a href="https://www.youtube.com/watch?v=<?php the_sub_field('youtube_id_left'); ?>" class="popup-youtube"><img src="<?php echo $Img['url'] ?>" /></a>
</div>
<?php } ?>
<?php if( get_row_layout() == 'select_content_left' ) { ?>
<div class="left-item" <?php if(get_sub_field('content_padding')) { ?>style="padding:<?php the_sub_field('content_padding'); ?>;" <?php }?>>
<div class="left-content">
<?php the_sub_field('content_left'); ?>
</div>
</div>
<?php } ?>
<?php }
} ?>
</div>
<div class="right-col" <?php if(get_sub_field('right_side_padding')) { ?>style="padding:<?php the_sub_field('right_side_padding'); ?>;" <?php }?>>
<?php if( have_rows('right_side')) {
while(have_rows('right_side')) { the_row(); ?>
<?php if( get_row_layout() == 'select_image_right' ) { ?>
<div class="right-item" <?php if(get_sub_field('image_padding')) { ?>style="padding:<?php the_sub_field('image_padding'); ?>;" <?php }?>>
<?php if(get_sub_field('image_url')) { ?>
<?php $loneImg = get_sub_field('image_right'); ?>
<a href="<?php the_sub_field('image_url'); ?>"><img src="<?php echo $loneImg['url'] ?>" /></a>
<?php } else {?>
<?php $loneImg = get_sub_field('image_right'); ?>
<img src="<?php echo $loneImg['url'] ?>" />
<?php } ?>
</div>
<?php } ?>
<?php if( get_row_layout() == 'select_youtube_left' ) { ?>
<div class="right-item" <?php if(get_sub_field('youtube_padding')) { ?>style="padding:<?php the_sub_field('youtube_padding'); ?>;" <?php }?>>
<?php $Img = get_sub_field('youtube_image_right'); ?>
<a href="https://www.youtube.com/watch?v=<?php the_sub_field('youtube_id_right'); ?>" class="popup-youtube"><img src="<?php echo $Img['url'] ?>" /></a>
</div>
<?php } ?>
<?php if( get_row_layout() == 'select_content_right' ) { ?>
<div class="right-item" <?php if(get_sub_field('content_padding')) { ?>style="padding:<?php the_sub_field('content_padding'); ?>;" <?php }?>>
<div class="right-content">
<?php the_sub_field('content_right'); ?>
</div>
</div>
<?php } ?>
<?php }
} ?>
</div>
</div>
</div>
</div>
<?php } /* close two_column_panel */
if( get_row_layout() == 'three_column_background' ) { ?>
<div class="three-column-bg panel">
<div class="wrap clearfix">
<div class="left-col">
<?php if( have_rows('left_side')) {
while(have_rows('left_side')) { the_row(); ?>
<?php if( get_row_layout() == 'select_image_left' ) { ?>
<div class="left-item">
<?php if(get_sub_field('image_url')) { ?>
<?php $loneImg = get_sub_field('image_left'); ?>
<a href="<?php the_sub_field('image_url'); ?>"><img src="<?php echo $loneImg['url'] ?>" /></a>
<?php } else {?>
<?php $loneImg = get_sub_field('image_left'); ?>
<img src="<?php echo $loneImg['url'] ?>" />
<?php } ?>
</div>
<?php } ?>
<?php if( get_row_layout() == 'select_youtube_left' ) { ?>
<div class="left-item">
<div class="left-content">
<?php $Img = get_sub_field('youtube_image_left'); ?>
<a href="https://www.youtube.com/watch?v=<?php the_sub_field('youtube_id_left'); ?>" class="popup-youtube"><img src="<?php echo $Img['url'] ?>" /></a>
</div>
</div>
<?php } ?>
<?php if( get_row_layout() == 'select_content_left' ) { ?>
<div class="left-item">
<div class="left-content">
<?php the_sub_field('content_left'); ?>
</div>
</div>
<?php } ?>
<?php }
} ?>
</div>
<div class="right-col">
<?php $threebgImg = get_sub_field('right_background'); ?>
<div class="right-bg" style="background-image:url('<?php echo $threebgImg['sizes']['three-col-bg'] ?>'); background-repeat:no-repeat; background-position: right; min-height:<?php echo $threebgImg['height']; ?>px;" >
<?php if( have_rows('center')) {
while(have_rows('center')) { the_row(); ?>
<?php if( get_row_layout() == 'select_image_center' ) { ?>
<div class="right-item">
<?php if(get_sub_field('image_url')) { ?>
<?php $loneImg = get_sub_field('image_center'); ?>
<a href="<?php the_sub_field('image_url'); ?>"><img src="<?php echo $loneImg['url'] ?>" /></a>
<?php } else {?>
<?php $loneImg = get_sub_field('image_center'); ?>
<img src="<?php echo $loneImg['url'] ?>" />
<?php } ?>
</div>
<?php } ?>
<?php if( get_row_layout() == 'select_youtube_center' ) { ?>
<div class="right-item">
<?php $Img = get_sub_field('youtube_image_center'); ?>
<a href="https://www.youtube.com/watch?v=<?php the_sub_field('youtube_id_center'); ?>" class="popup-youtube"><img src="<?php echo $Img['url'] ?>" /></a>
</div>
<?php } ?>
<?php if( get_row_layout() == 'select_content_center' ) { ?>
<div class="right-item">
<div class="right-content">
<?php the_sub_field('content_center'); ?>
</div>
</div>
<?php } ?>
<?php }
} ?>
</div>
</div>
</div>
</div>
<?php } /* close three column bg */
if( get_row_layout() == 'half-column-with-bg' ) { ?>
<?php $panelBgImg = get_sub_field('background_image'); ?>
<div class="half-column-with-bg panel" style="background-image:url('<?php echo $panelBgImg['sizes']['full-column'] ?>'); background-size:cover; width:1024px; background-repeat:no-repeat;">
<div class="wrap clearfix">
<?php the_sub_field('content'); ?>
<?php $youtubeImg = get_sub_field('youtube_video_image');?>
<a href="https://www.youtube.com/watch?v=<?php the_sub_field('youtube_video_id'); ?>" class="popup-youtube" style="padding-left:15px;"><img src="<?php echo $youtubeImg['url'] ?>" /></a>
</div>
</div>
<?php } /* close half-column-with-bg */
if( get_row_layout() == 'performance_panel' ) { ?>
<?php $performanceImg = get_sub_field('performance_background_image'); ?>
<div class="performance-system panel" style="background-image:url('<?php echo $performanceImg['sizes']['full-column'] ?>'); background-size:cover; width:1024px; background-repeat:no-repeat;">
<div class="wrap clearfix">
<?php the_sub_field('performance_top_content');?>
<div class="performance-last">
<?php the_sub_field('performance_bottom_content');?>
</div>
</div>
</div>
<?php } /* close performance_panel */
} /* close panel while */
} /* close panel if */ ?>
</section>
<section id="panels-mobile">
<?php $counter = 1;
if(have_rows('mobile_content')) {
while(have_rows('mobile_content')) { the_row();
if( get_row_layout() == 'images' ) { ?>
<div class="image-only-m panel-m" style="padding:<?php the_sub_field('padding');?>; margin-top:<?php the_sub_field('negative_margin');?>;">
<?php $imgMobile = get_sub_field('image-mobile');
if(get_sub_field('image_url')) { ?>
<a href="<?php the_sub_field('image_url'); ?>"><img src="<?php echo $imgMobile['sizes']['mobile-image']; ?>" alt="<?php echo $imgMobile['alt']; ?>" /></a>
<?php } else { ?>
<img src="<?php echo $imgMobile['sizes']['mobile-image']; ?>" alt="<?php echo $imgMobile['alt']; ?>" />
<?php } ?>
</div>
<?php } // close mobile image only
if( get_row_layout() == 'text_content' ) { ?>
<div class="text-content-m panel-m" style="margin-top:<?php the_sub_field('negative_margin');?>;">
<?php the_sub_field('content'); ?>
</div>
<?php } // close text_content
if( get_row_layout() == 'youtube' ) { ?>
<div class="youtube-m panel-m" style="padding:<?php the_sub_field('padding');?>; margin-top:<?php the_sub_field('negative_margin');?>;">
<?php $youtubeMobile = get_sub_field('youtube_thumbnails');?>
<a href="https://www.youtube.com/watch?v=<?php the_sub_field('youtube_id'); ?>" class="popup-youtube"><img src="<?php echo $youtubeMobile['url'] ?>" /></a>
</div>
<?php } // close youtube
if( get_row_layout() == 'background_with_text' ) { ?>
<?php $bgImg = get_sub_field('background_image'); ?>
<div class="background-text-m panel-m" style="background-image:url('<?php echo $bgImg['sizes']['mobile-image'];?>'); background-position:<?php the_sub_field('background_alignment'); ?>; background-size: 50%">
<div style="padding:<?php the_sub_field('text_padding');?>">
<?php the_sub_field('text'); ?>
</div>
</div>
<?php } // close background with text
if( get_row_layout() == 'video_slider' ) { ?>
<?php if (get_sub_field('slide')) { ?>
<div class="video-slider-m mobile-info owl-carousel owl-theme panel-m">
<?php while(have_rows('slide')) { the_row();
$vidImg = get_sub_field('youtube_thumbnail'); ?>
<div class="item">
<?php if(get_sub_field('video_id')) { ?>
<a href="https://www.youtube.com/watch?v=<?php the_sub_field('video_id'); ?>" class="popup-youtube"><img src="<?php echo $vidImg['sizes']['mobile-image']; ?>" alt="<?php echo $vidImg['alt']; ?>" /></a>
<?php } else { ?>
<img src="<?php echo $vidImg['sizes']['mobile-image']; ?>" alt="<?php echo $vidImg['alt']; ?>" />
<?php } ?>
<div class="slide-text">
<?php the_sub_field('content'); ?>
</div>
<?php if(get_sub_field('button_text')) { ?>
<div class="event-btn">
<a href="<?php the_sub_field('button_url'); ?>"><?php the_sub_field('button_text'); ?></a>
</div>
<?php } ?>
</div>
<?php } ?>
</div>
<?php }?>
<?php } // close video slider
if( get_row_layout() == 'accordion_content' ) { ?>
<div class="accordion-m">
<div class="acc-product-extra-info">
<input id="tab-<?php echo $counter;?>" type="checkbox" name="tabs">
<label for="tab-<?php echo $counter;?>"><?php the_sub_field('accordion_label'); ?></label>
<div class="tab-content">
<?php the_sub_field('content'); ?>
</div>
</div>
</div>
<?php $counter++;?>
<?php } // close accordion
if( get_row_layout() == 'slider_content' ) { ?>
<?php if (get_sub_field('slider')) { ?>
<div class="slider-m mobile-info owl-carousel owl-theme panel-m">
<?php while(have_rows('slider')) { the_row(); ?>
<?php if(get_row_layout() == 'images_slides' ) { ?>
<div class="item">
<?php $mobileSlide = get_sub_field('slider_image_real'); ?>?>
<img src="<?php echo $mobileSlide['sizes']['mobile-image']; ?>" alt="<?php echo $mobileSlide['alt']; ?>" /></a>
</div>
<?php }
if(get_row_layout() == 'text_slides' ) {?>
<div class="item">
<?php the_sub_field('slider_image'); ?>
</div>
<?php }?>
<?php } ?>
</div>
<?php }?>
<?php } // close Slider
if( get_row_layout() == 'spacers' ) { ?>
<div class="spacers-m" style="padding-top:<?php the_sub_field('spacer'); ?>"></div>
<?php } // close spacers ?>
<?php } //close mobile_content while ?>
<?php } //close mobile_content if ?>
</section>
<?php if(get_field('ny_related_product_to_display')) { ?>
<?php include 'include-mini-cart.php' ?>
<?php }?>
<?php if(have_rows('bottom_links')) { ?>
<section id="mobile-links">
<?php while(have_rows('bottom_links')) { the_row();?>
<div class="link">
<a href="<?php the_sub_field('link_url'); ?>"><?php the_sub_field('link_text'); ?></a>
</div>
<?php } ?>
</section>
<?php } ?>
<?php get_footer(); ?>
<file_sep>/wp-content/themes/uppababy/template-retailer-locator.php
<?php
/** Template Name: Simplemap Retailer Locator */
get_header();
?>
<div id="panels" class="rzt-retailer-locator">
<div id="content" role="main">
<?php while ( have_posts() ) {
the_post();
if ( has_post_thumbnail() ) {
//the_post_thumbnail('full');
$ny_banner_image_id = get_post_thumbnail_id( $post->ID, 'full');
$ny_banner_image = wp_get_attachment_image_src( $ny_banner_image_id )[0];
} else {
if ( function_exists('rzt_get_page_hero_banner_image') ) {
$ny_banner_image = rzt_get_page_hero_banner_image( );
}
}
if ( isset ($ny_banner_image) && $ny_banner_image != false ) {
if ( get_field('banner_content_padding')) {
$ny_padding = 'style="padding:'.get_field('banner_content_padding').'"';
}
if ( get_field('do_you_need_dark_text')) {
$ny_dark_text = 'style="color:#666;"';
}
echo '<section id="hero-banner" style="background-image:url(\''.$ny_banner_image.'\'); background-size:cover; background-repeat:no-repeat;">';
echo '<div class="hero-content"';
echo ' '.(isset( $ny_padding ) ? $ny_padding : '');
echo ' '.(isset( $ny_dark_text ) ? $ny_dark_text : '');
echo '>';
echo get_field('banner_content');
echo '</div>';
echo '</section>';
}
?>
<section id="support">
<div class="content-wrap">
<div class="contact-box">
<?php if( have_rows('address_box', 'option') ) {
while( have_rows('address_box', 'option')) { the_row(); ?>
<h3>
<?php the_sub_field('address_header', 'option'); ?>
</h3>
<?php the_sub_field('address_text', 'option'); ?>
<?php } ?>
<?php } ?>
</div>
<div class="support-column">
<div class="support-item rzt-simplemap">
<?php the_title( '<h4 class="entry-title">', '</h4>' ); ?>
<div class="support-content entry-content">
<?php the_content();
$ny_show_the_google_map = rzt_check_if_simplemap_option_true_false ( 'show_the_google_map', $post->ID );
$ny_show_the_search_form = rzt_check_if_simplemap_option_true_false ( 'show_the_search_form', $post->ID );
$ny_shortcode = '[simplemap';
//if ( isset($ny_show_the_google_map) && $ny_show_the_google_map != false ) {
if ( $ny_show_the_google_map ) {
//$ny_shortcode .= ' hide_map=false';
} else {
$ny_shortcode .= ' hide_map=true';
}
//if ( isset($ny_show_the_search_form) && $ny_show_the_search_form != false ) {
if ( $ny_show_the_search_form ) {
//$ny_shortcode .= ' hide_search=false';
} else {
$ny_shortcode .= ' hide_search=true';
}
$ny_zip_field_is_available = rzt_check_if_simplemap_option_is_set ( 'zip_field_is_available', false, $post->ID );
$ny_city_field_is_available = rzt_check_if_simplemap_option_is_set ( 'city_field_is_available', 0, $post->ID );
$ny_state_field_is_available = rzt_check_if_simplemap_option_is_set ( 'state_field_is_available', 0, $post->ID );
$ny_search_fields = ' search_fields="empty';
if ( isset($ny_city_field_is_available) && $ny_city_field_is_available != false ) {
$ny_search_fields .= '||labelsp_city';
} else {
$ny_search_fields .= '||empty';
}
if ( isset($ny_state_field_is_available) && $ny_state_field_is_available != false ) {
$ny_search_fields .= '||labelsp_state';
} else {
$ny_search_fields .= '||empty';
}
if ( isset($ny_zip_field_is_available) && $ny_zip_field_is_available != false ) {
$ny_search_fields .= '||labelsp_zip';
} else {
$ny_search_fields .= '||empty';
}
$ny_search_fields .= '||empty||empty||empty||submit||empty||empty||empty"';
$ny_shortcode .= $ny_search_fields;
$ny_shortcode .= ' search_form_cols=4';
$ny_shortcode .= ']';
echo do_shortcode( $ny_shortcode );
?>
</div>
</div>
</div>
</div>
</section>
<?php } ?> <!-- // end of the loop -->
</div> <!-- #content -->
</div> <!-- #panels -->
<?php get_footer(); ?><file_sep>/wp-content/themes/uppababy/woocommerce/checkout/thankyou.php
<?php
/**
* Thankyou page
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( $order ) :
$ny_order_id = $order->get_id();
if ( $order->has_status( 'failed' ) ) :
?>
<p class="woocommerce-thankyou-order-failed">
<?php
_e( 'Unfortunately your order cannot be processed as the originating bank/merchant has declined your transaction. Please attempt your purchase again.', 'woocommerce' );
?>
</p>
<p class="woocommerce-thankyou-order-failed-actions">
<a href="<?php echo esc_url( $order->get_checkout_payment_url() ); ?>" class="button pay">
<?php _e( 'Pay', 'woocommerce' ) ?>
</a>
<?php if ( is_user_logged_in() ) : ?>
<a href="<?php echo esc_url( wc_get_page_permalink( 'myaccount' ) ); ?>" class="button pay">
<?php _e( 'My Account', 'woocommerce' ); ?>
</a>
<?php endif; ?>
</p>
<?php else :
if ( get_post_meta($ny_order_id, 'shopatron_order_ID', true) ) {
$ny_shopatron_order_ID = get_post_meta($ny_order_id, 'shopatron_order_ID', true);
$ny_strpos = strpos($ny_shopatron_order_ID, "_");
}
if ( $ny_shopatron_order_ID && $ny_strpos !== false ) {
$ny_post_and_order_ids = explode( "_", $ny_shopatron_order_ID );
$ny_shopatron_order_ID = $ny_post_and_order_ids[1];
} else {
$ny_shopatron_order_ID = $order->get_order_number();
}
?>
<p class="woocommerce-thankyou-order-received">
<?php echo apply_filters( 'woocommerce_thankyou_order_received_text', __( 'Thank you! Your order has been received.', 'woocommerce' ), $order ); ?>
</p>
<ul class="woocommerce-thankyou-order-details order_details">
<li class="order">
<?php _e( 'Order Number:', 'woocommerce' ); ?>
<strong><?php echo $ny_shopatron_order_ID; ?></strong>
</li>
<li class="date">
<?php _e( 'Date:', 'woocommerce' ); ?>
<strong><?php echo date_i18n( get_option( 'date_format' ), strtotime( $order->get_date_paid() ) ); ?></strong>
</li>
<li class="total">
<?php _e( 'Total:', 'woocommerce' ); ?>
<strong><?php echo $order->get_formatted_order_total(); ?></strong>
</li>
<?php if ( $order->get_payment_method_title() ) : ?>
<li class="method">
<?php _e( 'Payment Method:', 'woocommerce' ); ?>
<strong><?php echo $order->get_payment_method_title(); ?></strong>
</li>
<?php endif; ?>
</ul>
<div class="clear"></div>
<?php endif; ?>
<?php do_action( 'woocommerce_thankyou_' . $order->get_payment_method(), $ny_order_id ); ?>
<?php do_action( 'woocommerce_thankyou', $ny_order_id ); ?>
<?php else : ?>
<p class="woocommerce-thankyou-order-received">
<?php echo apply_filters( 'woocommerce_thankyou_order_received_text', __( 'Thank you. Your order has been received.', 'woocommerce' ), null ); ?>
</p>
<?php endif; ?><file_sep>/wp-content/themes/uppababy/functions.php
<?php
/* ========================================================================= */
/* !WORDPRESS EXTERNAL FILES */
/* ========================================================================= */
include_once 'functions/functions-post-types.php';
//include_once 'functions/functions-widgets.php';
//include_once 'functions/functions-comments.php';
/* ========================================================================= */
/* !WORDPRESS SECURITY */
/* ========================================================================= */
remove_action('wp_head','feed_links_extra', 3); // Display the links to the extra feeds such as category feeds
remove_action('wp_head','feed_links', 2); // Display the links to the general feeds: Post and Comment Feed
remove_action('wp_head','rsd_link'); // Display the link to the Really Simple Discovery service endpoint, EditURI link
remove_action('wp_head','wlwmanifest_link'); // Display the link to the Windows Live Writer manifest file.
remove_action('wp_head','index_rel_link'); // index link
remove_action('wp_head','parent_post_rel_link', 10, 0); // prev link
remove_action('wp_head','start_post_rel_link', 10, 0); // start link
remove_action('wp_head','adjacent_posts_rel_link', 10, 0); // Display relational links for the posts adjacent to the current post.
remove_action('wp_head','wp_generator'); // Display the XHTML generator that is generated on the wp_head hook, WP version
/* Prevent Login Errors for Security */
add_filter('login_errors','__return_null');
/* ========================================================================= */
/* !WORDPRESS CUSTOMIZATION & SETUP */
/* ========================================================================= */
/* Post Thumbnail Sizes */
add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 64, 64, true );
add_image_size( 'hero-banner', 1024, 520);
add_image_size( 'full-column', 1024);
add_image_size( 'two-column-left', 550);
add_image_size( 'two-column-right', 424);
add_image_size( 'three-col-bg', 481);
add_image_size( 'accessories_main', 470);
add_image_size( 'accessories_thumb', 110, 85, true);
add_image_size( 'acc-list-img', 187, 172);
add_image_size( 'site-logo', 371, 60);
add_image_size( 'home-half-promo',245, 154 );
add_image_size( 'home-right-top-promo',506, 230 );
add_image_size( 'home-right-bot-promo',506, 77 );
add_image_size( 'news-image',800 );
add_image_size( 'news-featured',800, 200, true );
add_image_size( 'news-result',380 );
add_image_size( 'support-image',237, 110 );
add_image_size( 'mobile-image',750 );
/* Declare Nav Menu Areas */
if ( function_exists( 'register_nav_menus' ) ) {
register_nav_menus(
array(
'main-menu' => 'Main Menu',
'footer-menu' => 'Footer Menu'
)
);
}
/* ========================================================================= */
/* !DISABLE EMOJIS */
/* ========================================================================= */
remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'wp_print_styles', 'print_emoji_styles' );
/* Globally Hide Admin Meta Boxes */
function hide_meta_boxes() {
remove_meta_box('postcustom','post','normal'); // custom fields post
remove_meta_box('postcustom','page','normal'); // custom fields page
//remove_meta_box('commentstatusdiv','post','normal'); // discussion post
remove_meta_box('commentstatusdiv','page','normal'); // discussion page
//remove_meta_box('commentsdiv','post','normal'); // comments post
//remove_meta_box('commentsdiv','page','normal'); // comments page
//remove_meta_box('authordiv','post','normal'); // author post
remove_meta_box('authordiv','page','normal'); // author page
//remove_meta_box('revisionsdiv','post','normal'); // revisions post
//remove_meta_box('revisionsdiv','page','normal'); // revisions page
//remove_meta_box('postimagediv','post','normal'); // featured image post
remove_meta_box('postimagediv','page','normal'); // featured image page
//remove_meta_box('pageparentdiv','page','normal'); // page attributes
//remove_meta_box('tagsdiv-post-tag','post','normal'); // post tags
//remove_meta_box('categorydiv','post','normal'); // post categories
//remove_meta_box('postexcerpt','post','normal'); // post excerpt
remove_meta_box('trackbacksdiv','post','normal'); // track backs
}
add_action('admin_init', 'hide_meta_boxes');
/* Hide Wordpress Default Dashboard Widgets */
function remove_dashboard_widgets() {
global $wp_meta_boxes;
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press']);
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links']);
//unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now']);
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins']);
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_recent_drafts']);
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_comments']);
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']);
}
add_action('wp_dashboard_setup', 'remove_dashboard_widgets' );
/* ========================================================================= */
/* !CUSTOM LOGIN STYLES */
/* ========================================================================= */
function my_login_stylesheet() {
wp_enqueue_style( 'custom-login', '/ui/css/login.css' );
}
add_action( 'login_enqueue_scripts', 'my_login_stylesheet' );
function uppa_login() {
echo '<a href="http://uppababy.com/" target="_blank">';
echo '<div id="uppa-login"></div>';
echo '</a>';
}
add_action( 'login_footer', 'uppa_login' );
function uppa_login_url(){
return get_bloginfo('url');
}
add_action( 'login_headerurl', 'uppa_login_url' );
function uppa_login_title(){
return get_bloginfo('name');
}
add_action( 'login_headertitle', 'uppa_login_title' );
/* ========================================================================= */
/* !ENQUEUE STYLES */
/* ========================================================================= */
function enqueue_styles() {
wp_enqueue_style('style', 'https://uppababy.com/ui/css/style.css', array(), null);
}
// With Print Style Sheet
// function enqueue_styles() {
// wp_enqueue_style('style', 'http://uppababy.com/ui/css/style.css', array(), null, 'screen');
// wp_enqueue_style('print', 'http://uppababy.com/ui/css/print.css', array(), null, 'print');
// }
add_action('wp_enqueue_scripts', 'enqueue_styles');
/* ========================================================================= */
/* !ENQUEUE SCRIPTS */
/* ========================================================================= */
function enqueue_scripts() {
wp_deregister_script( 'jquery' );
wp_enqueue_script('modernizr', 'https://uppababy.com/ui/js/modernizr.js', array(), null);
wp_enqueue_script('svgxuse', 'https://uppababy.com/ui/js/svgxuse.js', array(), null, true);
wp_enqueue_script('jquery', 'https://uppababy.com/ui/js/jquery.js', array(), null);
wp_enqueue_script('plugins', 'https://uppababy.com/ui/js/jquery.plugins.js', array('jquery'), null, true);
wp_enqueue_script('init', 'https://uppababy.com/ui/js/jquery.init.js', array('jquery', 'plugins'), null, true);
}
add_action('wp_enqueue_scripts', 'enqueue_scripts');
/* ========================================================================= */
/* !GRAVITY FORM CUSTOMIZATIONS */
/* ========================================================================= */
add_filter("gform_submit_button", "form_submit_button", 10, 2);
function form_submit_button($button, $form){
$button_array = $form["button"];
$button_text = $button_array["text"];
return "<button type='submit' class='submit' id='gform_submit_button_{" . $form["id"] . "}'><span>$button_text</span></button>";
}
/* ========================================================================= */
/* !ADD ACF5 OPTIONS PAGE - more args available at http://www.advancedcustomfields.com/resources/acf_add_options_page/ */
/* ========================================================================= */
if( function_exists('acf_add_options_page') ) {
acf_add_options_page(array(
'page_title' => 'Options',
'menu_slug' => 'options'
));
}
/* ========================================================================= */
/* !WORDPRESS SUBPAGE SIDEBAR MENU */
/* ========================================================================= */
function uppa_tertiary_menu( $args ){
include_once 'functions/class-walker-tertiary-menu.php';
$uri_parts = explode('/', $_SERVER['REQUEST_URI']);
$args['ancestor'] = get_page_by_path($uri_parts[1]);
$args['echo'] = false;
$args['walker'] = new Walker_Tertiary_Menu();
return wp_nav_menu($args);
}
function check_is_subpage() {
global $post; // load details about this page
if ( is_page() && $post->post_parent ) { // test to see if the page has a parent
return $post->post_parent; // return the ID of the parent post
} else { // there is no parent so...
return false; // ...the answer to the question is false
}
}
/* HOW TO USE
Plug this code below into your submenu sidebar and set the theme location to use the menu you want to reference. This code checks whether the page is a subpage.
If page is a subpage it echos the children menu items of it. If page is not it then echos the top level pages of the menu.
<?php if(check_is_subpage() == false){ ?>
<h3><?php bloginfo('name'); ?></h3>
<div class="submenu-widget">
<?php wp_nav_menu(array('theme_location' => 'main-menu', 'container' => '', 'menu_class' => 'menu', 'menu_id' => '', 'depth' => 2)); ?>
</div>
<?php } else { ?>
<h3><?php $anc = get_ancestors(get_the_ID(),'page'); $count = count($anc); if($count > 0){ $anc_pg = get_post($anc[($count - 1)]); echo $anc_pg->post_title; } else the_title(); ?></h3>
<div class="submenu-widget">
<?php echo uppa_tertiary_menu(array('theme_location' => 'main-menu', 'container' => '', 'menu_class' => 'menu', 'menu_id' => '', 'depth' => 3)); ?>
</div>
<?php } ?>
*/
/* ========================================================================= */
/* Get Post Slug */
/* ========================================================================= */
function the_slug($echo=true){
$slug = basename(get_permalink());
do_action('before_slug', $slug);
$slug = apply_filters('slug_filter', $slug);
if( $echo ) echo $slug;
do_action('after_slug', $slug);
return $slug;
}
/* Use the tag below when querying the slug of a post.
<?php the_slug(); ?> */
/* ========================================================================= */
/* REMOVE [] FROM [...] */
/* ========================================================================= */
function new_excerpt_more( $more ) {
return '';
}
add_filter('excerpt_more', 'new_excerpt_more');
/* ========================================================================= */
/* Browser detection body_class() output */
/* ========================================================================= */
function alx_browser_body_class( $classes ) {
global $is_lynx, $is_gecko, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone;
if($is_lynx) $classes[] = 'lynx';
elseif($is_gecko) $classes[] = 'gecko';
elseif($is_opera) $classes[] = 'opera';
elseif($is_NS4) $classes[] = 'ns4';
elseif($is_safari) $classes[] = 'safari';
elseif($is_chrome) $classes[] = 'chrome';
elseif($is_IE) {
$browser = $_SERVER['HTTP_USER_AGENT'];
$browser = substr( "$browser", 25, 8);
if ($browser == "MSIE 7.0" ) {
$classes[] = 'ie7';
$classes[] = 'ie';
} elseif ($browser == "MSIE 6.0" ) {
$classes[] = 'ie6';
$classes[] = 'ie';
} elseif ($browser == "MSIE 8.0" ) {
$classes[] = 'ie8';
$classes[] = 'ie';
} elseif ($browser == "MSIE 9.0" ) {
$classes[] = 'ie9';
$classes[] = 'ie';
} else {
$classes[] = 'ie';
}
}
else $classes[] = 'unknown';
if( $is_iphone ) $classes[] = 'iphone';
return $classes;
}
add_filter( 'body_class', 'alx_browser_body_class' );
/* ========================================================================= */
/* !REMOVE <P> WRAPPER WHEN ONLY <IMG /> IS CONTAINED WITHIN */
/* ========================================================================= */
function filter_ptags_on_images($content){
return preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
}
add_filter('the_content', 'filter_ptags_on_images');
/* ========================================================================= */
/* !ADD OPTION TO FILTER PDF IN MEDIA LIBRARY */
/* ========================================================================= */
function modify_post_mime_types($post_mime_types) {
$post_mime_types['application/pdf'] = array(__( 'PDFs' ), __('Manage PDF'), _n_noop( 'PDF <span class="count">(%s)</span>', 'PDFs <span class="count">(%s)</span>'));
return $post_mime_types;
}
add_filter('post_mime_types', 'modify_post_mime_types');
/* ========================================================================= */
/* !EASY PRINTR() */
/* ========================================================================= */
function printr($var){ echo '<pre>'; print_r($var); echo '</pre>'; };
/* ========================================================================= */
/* EXCERPT LIMITER */
/* ========================================================================= */
function limit_excerpt($string, $word_limit) {
$words = explode(' ', $string);
return implode(' ', array_slice($words, 0, $word_limit));
}
/* Example Usage:
Solution 1:
<?php $excerpt = limit_excerpt(get_the_excerpt(), '50'); ?>
<?php echo $excerpt . '...' ?>
Solution 2:
<?php echo limit_excerpt(get_the_excerpt(), '50'); ?>
*/
/*
/* ========================================================================= */
/* !REMOVE ADMIN TOOLBAR */
/* ========================================================================= */
// add_filter('show_admin_bar', '__return_false');
/* ========================================================================= */
/* !WORDPRESS PAGINATION SCRIPT */
/* ========================================================================= */
/*
function uppa_paginate() {
global $wp_query, $wp_rewrite;
$wp_query->query_vars['paged'] > 1 ? $current = $wp_query->query_vars['paged'] : $current = 1;
$pagination = array(
'base' => @add_query_arg('page','%#%'),
'format' => '',
'total' => $wp_query->max_num_pages,
'current' => $current,
'show_all' => false,
'mid_size' => 1,
'end_size' => 3,
'type' => 'plain',
'next_text' => '',
'prev_text' => ''
);
if( $wp_rewrite->using_permalinks() )
$pagination['base'] = user_trailingslashit( trailingslashit( remove_query_arg( 's', get_pagenum_link( 1 ) ) ) . 'page/%#%/', 'paged' );
if( !empty($wp_query->query_vars['s']) )
$pagination['add_args'] = array( 's' => urlencode(get_query_var( 's' )) );
if($wp_query->query_vars['posts_per_page'] < $wp_query->found_posts){
echo '<div id="search-nav">';
echo paginate_links( $pagination );
echo '</div>';
}
}
*/
/* ========================================================================= */
/* !SHORTCUT CODES */
/* ========================================================================= */
/*
function morelink($atts, $content = null) {
extract(shortcode_atts(array(
"link" => '',
"target" => ''
), $atts));
return '<a href="'.$link.'" class="button btn-read-more" target="'.$target.'">'.$content.'</a>';
}
add_shortcode('button', 'morelink');
*/
/* ========================================================================= */
/* !TINYMCE SELECT DROPDOWN CLASS SETUP CODES */
/* ========================================================================= */
/*
add_filter( 'mce_buttons_2', 'my_mce_buttons_2' );
function my_mce_buttons_2( $buttons ) {
array_unshift( $buttons, 'styleselect' );
return $buttons;
}
add_filter( 'tiny_mce_before_init', 'my_mce_before_init' );
function my_mce_before_init( $settings ) {
$style_formats = array(
array(
'title' => 'Gray Box Button',
'selector' => 'a',
'classes' => 'box-link'
)
);
$settings['style_formats'] = json_encode( $style_formats );
return $settings;
}
*/
/* ========================================================================= */
/* !WORDPERSS CUSTOM THEME FUNCTIONS - Please use ACF and Meta Queries */
/* ========================================================================= */
/* ----- SHOW FUTURE POSTS FOR EVENT CUSTOM POST TYPES ----- */
/*
function show_future_posts($posts) {
global $wp_query, $wpdb;
if(is_single() && $wp_query->post_count == 0)
{
$posts = $wpdb->get_results($wp_query->request);
}
return $posts;
}
add_filter('the_posts', 'show_future_posts');
*/
/* ----- Get File Extension (ex: PDF, DOC) ----- */
/*
function uppa_get_file_ext($file_url){
return pathinfo($file_url, PATHINFO_EXTENSION);
}
*/
/* ========================================================================= */
/* !CLEAN FUNCTION - Helpful making better hash links out of repeating fields. */
/* ========================================================================= */
function clean($string) {
$string = strip_tags($string);
$string = strtolower($string);
$string = str_replace(' ', '-', $string);
return preg_replace('/[^A-Za-z0-9\-]/', '', $string);
}
/* ========================================================================= */
/* !TAG WRAP - No more empty tags*/
/* Usage:
/* echo tag_wrap(get_field('whatever'), 'h3 class="something"');
/* output: <h3 class="something">[contents of whatever field]</h3>
/* ========================================================================= */
function tag_wrap($f,$t){
if($f){
$r = "<{$t}>{$f}";
$e = explode(' ',$t);
$e = $e[0];
$r .= "</{$e}>";
return $r;
}
}
/* ========================================================================= */
/* SVG Support */
/* ========================================================================= */
function cc_mime_types($mimes) {
$mimes['svg'] = 'image/svg+xml';
return $mimes;
}
add_filter('upload_mimes', 'cc_mime_types');
/* ========================================================================= */
/* Add Classes to next_posts_link and prev_posts_link. */
/* ========================================================================= */
/*
add_filter('next_posts_link_attributes', 'posts_link_attributes');
add_filter('previous_posts_link_attributes', 'posts_link_attributes');
function posts_link_attributes() {
return 'class="btn pink-purple"';
}
*/
/* ========================================================================= */
/* !CUSTOM CHILD SITE COLOR
Add a custom color strip to the header for child sites on a multisite
install. Helps differentiate them when jumping back and forth.
/* ========================================================================= */
/*add_action('admin_enqueue_scripts', 'my_admin_background');
function my_admin_background() {
wp_enqueue_style('custom-style', get_template_directory_uri() . '/css/custom_script.css');
global $blog_id;
$color = '';
if ($blog_id == 1) {
$color = '#E1B13A';
} elseif ($blog_id == 2) {
$color = '#BA273A';
} elseif ($blog_id == 3) {
$color = '#BFD945';
}
$custom_css = "#wpadminbar { border-top: 5px solid $color }";
wp_add_inline_style( 'custom-style', $custom_css );
}*/
// Render fields at the bottom of variations - does not account for field group order or placement.
add_action( 'woocommerce_product_after_variable_attributes', function( $loop, $variation_data, $variation ) {
global $abcdefgh_i; // Custom global variable to monitor index
$abcdefgh_i = $loop;
// Add filter to update field name
add_filter( 'acf/prepare_field', 'acf_prepare_field_update_field_name' );
// Loop through all field groups
$acf_field_groups = acf_get_field_groups();
foreach( $acf_field_groups as $acf_field_group ) {
foreach( $acf_field_group['location'] as $group_locations ) {
foreach( $group_locations as $rule ) {
// See if field Group has at least one post_type = Variations rule - does not validate other rules
if( $rule['param'] == 'post_type' && $rule['operator'] == '==' && $rule['value'] == 'product_variation' ) {
// Render field Group
acf_render_fields( $variation->ID, acf_get_fields( $acf_field_group ) );
break 2;
}
}
}
}
// Remove filter
remove_filter( 'acf/prepare_field', 'acf_prepare_field_update_field_name' );
}, 10, 3 );
// Filter function to update field names
function acf_prepare_field_update_field_name( $field ) {
global $abcdefgh_i;
$field['name'] = preg_replace( '/^acf\[/', "acf[$abcdefgh_i][", $field['name'] );
return $field;
}
// Save variation data
add_action( 'woocommerce_save_product_variation', function( $variation_id, $i = -1 ) {
// Update all fields for the current variation
if ( ! empty( $_POST['acf'] ) && is_array( $_POST['acf'] ) && array_key_exists( $i, $_POST['acf'] ) && is_array( ( $fields = $_POST['acf'][ $i ] ) ) ) {
foreach ( $fields as $key => $val ) {
update_field( $key, $val, $variation_id );
}
}
}, 10, 2 );
/* ========================================================================= */
/* !ADDING RZT SUPPORT FOR WOOCOMMERCE
/* ========================================================================= */
function rzt_woocommerce_support() {
add_theme_support( 'woocommerce' );
}
add_action( 'after_setup_theme', 'rzt_woocommerce_support' );
/* ========================================================================= */
/* !HIDE UPDATE ALERT FROM THE DASHBOARD
Removes the alert from the top of the dashboard.
WP Engine manages updates, so this alert is not needed.
/* ========================================================================= */
function hide_update_notice() {
remove_action( 'admin_notices', 'update_nag', 3 );
}
add_action( 'admin_notices', 'hide_update_notice', 1 );<file_sep>/README.md
# UPB
### 1.0.
- Initial Commit
---
### Versioning
We will be utilizing a three-point numbering system.
- Point 1 (1.#.#) is used for site launches, phases, and site redesigns.
- Point 2 (#.1.#) is used for major edits, such as the finalizing of new templates, adding new sections or modules, etc.
- Point 3 (#.#.1) is used for minor structure/style/script edits, such as SDS edits, bug fixes, etc.
Each point can go past a single digit of iterations (for instance, the 11th major edit without a site launch would be 0.11.0, and not 1.1.0).
### Emojis
Here's a list of useful emojis for tracking changes (stripped from [Atom's commit messages](https://github.com/atom/atom/blob/master/CONTRIBUTING.md#git-commit-messages)):
- :bug: `:bug:` when fixing a bug
- :art: `:art:` when improving the format/structure of the code
- :fire: `:fire:` when removing code or files
- :lock: `:lock:` when dealing with security
<file_sep>/wp-content/themes/uppababy-uk-child/functions.php
<?php
function my_theme_enqueue_styles() {
$parent_style = 'style'; // This is 'uppababy' for the Twenty Fifteen theme.
wp_enqueue_style( $parent_style, 'https://uppababy.com/ui/css/style.css' );
wp_enqueue_style( 'child-style',
'https://uppababy.com/ui/css/uk-style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
);
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
// Hiding prices
add_filter( 'woocommerce_get_price_html', function( $price ) {
if ( is_admin() ) return $price;
return '';
} );
add_filter( 'woocommerce_cart_item_price', '__return_false' );
add_filter( 'woocommerce_cart_item_subtotal', '__return_false' );
?>
<file_sep>/wp-content/themes/uppababy/header-contact.php
<!DOCTYPE html>
<html lang="en-US" prefix="og: http://ogp.me/ns#">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<?php if (is_front_page()) { ?>
<title><?php bloginfo('name'); ?> | <?php bloginfo('description'); ?></title>
<?php } else { ?>
<title><?php wp_title(''); ?> | <?php bloginfo('name'); ?></title>
<?php }; ?>
<link type="text/plain" rel="author" href="<?php bloginfo('url'); ?>/authors.txt" />
<?php wp_head(); ?>
<link type="image/x-icon" rel="shortcut icon" href="<?php bloginfo('url'); ?>/favicon.ico" />
<!-- Start of uppababy Zendesk Widget script -->
<script>/*<![CDATA[*/window.zEmbed||function(e,t){var n,o,d,i,s,a=[],r=document.createElement("iframe");window.zEmbed=function(){a.push(arguments)},window.zE=window.zE||window.zEmbed,r.src="javascript:false",r.title="",r.role="presentation",(r.frameElement||r).style.cssText="display: none",d=document.getElementsByTagName("script"),d=d[d.length-1],d.parentNode.insertBefore(r,d),i=r.contentWindow,s=i.document;try{o=s}catch(e){n=document.domain,r.src='javascript:var d=document.open();d.domain="'+n+'";void(0);',o=s}o.open()._l=function(){var e=this.createElement("script");n&&(this.domain=n),e.id="js-iframe-async",e.src="https://assets.zendesk.com/embeddable_framework/main.js",this.t=+new Date,this.zendeskHost="uppababy.zendesk.com",this.zEQueue=a,this.body.appendChild(e)},o.write('<body onload="document._l();">'),o.close()}();
/*]]>*/</script>
<!-- End of uppababy Zendesk Widget script -->
<script>
window['_fs_debug'] = false;
window['_fs_host'] = 'fullstory.com';
window['_fs_org'] = 'A70HY';
window['_fs_namespace'] = 'FS';
(function(m,n,e,t,l,o,g,y){
if (e in m) {if(m.console && m.console.log) { m.console.log('FullStory namespace conflict. Please set window["_fs_namespace"].');} return;}
g=m[e]=function(a,b){g.q?g.q.push([a,b]):g._api(a,b);};g.q=[];
o=n.createElement(t);o.async=1;o.src='https://'+_fs_host+'/s/fs.js';
y=n.getElementsByTagName(t)[0];y.parentNode.insertBefore(o,y);
g.identify=function(i,v){g(l,{uid:i});if(v)g(l,v)};g.setUserVars=function(v){g(l,v)};
y="rec";g.shutdown=function(i,v){g(y,!1)};g.restart=function(i,v){g(y,!0)};
g.identifyAccount=function(i,v){o='account';v=v||{};v.acctId=i;g(o,v)};
g.clearUserCookie=function(){};
})(window,document,window['_fs_namespace'],'script','user');
</script>
</head>
<body id="body" <?php body_class(); ?>>
<div id="rzt-cart-overlay" onclick="rzt_cart_overlay_close();"></div>
<div id="site-center" class="menu-normal">
<section id="header">
<div class="wrap">
<div class="util-nav">
<div class="country-selector">
<ul>
<li class="icon-globe"><a href="/country-select/" style="display: block; height: 20px; width: 20px; position: absolute; top: 10px;"></a></li>
<li>
<form action="<?php echo home_url('/'); ?>" method="get" id="searchform">
<input type="checkbox" />
<input type="text" placeholder="Search" name="s" class="hm-search" />
</form>
<form action="<?php echo home_url('/'); ?>" method="get" id="searchform2">
<span class="icon-search"></span>
</form>
</li>
</ul>
</div>
<div class="top-nav">
<?php wp_nav_menu('menu=top-nav&container='); ?>
<?php
global $woocommerce;
$ny_cart_contents_count = $woocommerce->cart->cart_contents_count;
if( $ny_cart_contents_count > 0 ) {
$ny_show_hide_cart_icon_style = ' style="position: absolute; right: 0px; top: 1px; display:block;"';
$ny_show_hide_cart_popup_style = ' style=""';
} else {
$ny_show_hide_cart_icon_style = ' style="position: absolute; right: 0px; top: 1px; display:none"';
$ny_show_hide_cart_popup_style = ' style="display:none"';
}
echo '<div class="upShopping"'.$ny_show_hide_cart_icon_style.'>';
?>
<ul class="udClear">
<li style="padding-left:17px;">
<?php
echo '<span class="small-cart-icon">
<img src="'.content_url().'/themes/uppababy/images/icon-shopping-cart.png" border="0" alt="">
</span> ';
echo '
<span class="small-cart-count">
<a class="cart-contents" href="" title="" onclick="rzt_show_the_mini_cart_widget(); return false;">'
.$ny_cart_contents_count
.'</a>
</span>';
?>
</li>
</ul>
</div>
</div>
</div>
<?php
echo '<div id="rzt-cart"'.$ny_show_hide_cart_popup_style.'>';
the_widget( 'WC_Widget_Cart', 'title=' );
echo '</div>';
?>
<div class="logo">
<?php $siteLogo = get_field('site_logo', 'option');?>
<a href="<?php bloginfo('url'); ?>"><img src="<?php echo $siteLogo['sizes']['site-logo']; ?>" alt="<?php echo $siteLogo['alt']; ?>" /></a>
</div>
<div id="m-toggle" class="icon-bars">
<span></span>
</div>
<div class="mobile-nav">
<?php wp_nav_menu('menu=mobile-nav&container='); ?>
</div>
<div class="main-nav">
<?php wp_nav_menu('menu=new-main-nav&container='); ?>
</div>
</div>
</section>
<file_sep>/wp-content/themes/uppababy/woocommerce/emails/customer-processing-order.php
<?php // Customer processing order email
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
?>
<?php // @hooked WC_Emails::email_header() Output the email header
//do_action( 'woocommerce_email_header', $email_heading, $email );
$ny_customer_full_name = $order->billing_first_name .' '.$order->billing_last_name;
if ( get_post_meta($order->id, 'shopatron_order_ID', true) ) {
$ny_shopatron_order_ID = get_post_meta($order->id, 'shopatron_order_ID', true);
$ny_strpos = strpos($ny_shopatron_order_ID, "_");
}
if ( $ny_shopatron_order_ID && $ny_strpos !== false ) {
$ny_post_and_order_ids = explode( "_", $ny_shopatron_order_ID );
$ny_order_id = $ny_post_and_order_ids[1];
} else {
if ( $order->get_order_number() ) {
$ny_order_id = $order->get_order_number();
} else {
$ny_order_id = $order->id;
}
}
$ny_totals = $order->get_order_item_totals();
$ny_shipping = $ny_totals["shipping"]["value"];
$ny_shipping = str_replace( 'via Flat Rate','', $ny_shipping );
$ny_shipping = str_replace( 'Flat Rate','0', $ny_shipping );
$ny_card_number = sanitize_text_field( str_replace(' ','', $_POST['rzt_shopatron-card-number']) );
$ny_card_number_last_digits = substr( $ny_card_number, -4 );
$ny_card_type = rzt_get_card_type_from_number ( $ny_card_number );
?>
<!DOCTYPE html>
<html dir="<?php echo is_rtl() ? 'rtl' : 'ltr'?>">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?php bloginfo( 'charset' ); ?>" />
<title><?php echo get_bloginfo( 'name', 'display' ); ?></title>
</head>
<body <?php echo is_rtl() ? 'rightmargin' : 'leftmargin'; ?>="0" marginwidth="0" topmargin="0" marginheight="0" offset="0">
<div id="wrapper" dir="<?php echo is_rtl() ? 'rtl' : 'ltr'?>">
<div align="center">
<table width="600" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="border:1px solid #ccc;">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td align="center" width="130" style="border-bottom:1px solid #ccc; line-height:0px;">
<a href="http://app.bronto.com/t/l?ssid=17">
<img src="http://hosting.fyleio.com/17205/internal/templates/108972/uppababy-logo.jpg" border="0" alt="<?php echo $ny_customer_full_name; ?>">
</a>
</td>
<td align="left" valign="top" bgcolor="#F5F5F5" style="border-bottom:1px solid #ccc; border-left:1px solid #ccc;" height="95">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="font-family:Arial, Helvetica, sans-serif; font-size:14px; color:#5b656d; padding:35px 0 6px 17px; line-height:14px; text-align:left;">
<?php echo $ny_customer_full_name; ?>
</td>
</tr>
<tr>
<td style="font-family:'Arial Black', Arial, Helvetica, sans-serif; font-size:22px; color:#5b656d; padding:0px 0 14px 17px; text-align:left; line-height:24px;">
<div>
<div>Order Confirmation</div>
</div>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="padding:0 16px 46px 17px;">
<div align="right">
<table border="0" cellspacing="0" cellpadding="0" bgcolor="#5B656D">
<tbody>
<tr>
<td style="line-height:0;">
<img src="http://uppababy.com/wp-content/themes/UPPAbaby_2017/img/email/info-gray.gif" width="38" height="31" border="0" style="line-height:0;" alt="Order Status Icon">
</td>
<td style="font-family:Arial, Helvetica, sans-serif; font-size:12px; font-weight:bold; color:#FFFFFF;">
<div>
<div>Get Order Status</div>
</div>
</td>
<td style="line-height:0;">
<img src="http://uppababy.com/wp-content/themes/UPPAbaby_2017/img/email/question-gray.gif" width="49" height="31" border="0" style="line-height:0;" alt="Order Help Icon">
</td>
<td style="font-family:Arial, Helvetica, sans-serif; font-size:12px; font-weight:bold; color:#FFFFFF;">
<div>
<div>Get Order Help</div>
</div>
</td>
<td style="line-height:0;">
<img src="http://uppababy.com/wp-content/themes/UPPAbaby_2017/img/email/end-cap.gif" width="12" height="31" border="0" style="line-height:0;">
</td>
</tr>
</tbody>
</table>
</div>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="font-family:Arial, Helvetica, sans-serif; color:#000; font-size:12px; line-height:17px; padding:11px 0 23px 0; text-align:left;">
<div>
<div>Dear <?php echo $ny_customer_full_name; ?>,</div>
<div> </div>
<div>Thank you for placing UPPAbaby order # <?php echo $ny_order_id; ?>.</div>
</div>
</td>
</tr>
</tbody>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td valign="top" width="185" bgcolor="#F5F5F5" style="border:1px solid #dfdfdf; padding:14px 14px 16px;">
<table width="155" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="font-family:Arial, Helvetica, sans-serif; font-size:14px; font-weight:bold; color:#5b656d; line-height:18px; text-align:left;">
<div>
<div>Ship to:</div>
</div>
</td>
</tr>
<tr>
<td style="font-family:Arial, Helvetica, sans-serif; font-size:11px; color:#5b656d; line-height:18px; padding-top:3px; text-align:left;">
<?php if ( ! wc_ship_to_billing_address_only() && $order->needs_shipping_address() && ( $shipping = $order->get_formatted_shipping_address() ) ) : ?>
<p class="text"><?php echo $shipping; ?></p>
<?php endif; ?>
</td>
</tr>
</tbody>
</table>
</td>
<td style="line-height:0;">
<!-- img src="http://hosting.fyleio.com/17205/internal/templates/108972/spacer.gif" width="5" height="5" -->
</td>
<td valign="top" width="185" bgcolor="#F5F5F5" style="border:1px solid #dfdfdf; padding:14px 14px 16px;">
<table width="155" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="font-family:Arial, Helvetica, sans-serif; font-size:14px; font-weight:bold; color:#5b656d; line-height:18px; text-align:left;">
<div>
<div>Bill to:</div>
</div>
</td>
</tr>
<tr>
<td style="font-family:Arial, Helvetica, sans-serif; font-size:11px; color:#5b656d; line-height:18px; padding-top:3px; text-align:left;">
<p class="text"><?php echo $order->get_formatted_billing_address(); ?>
</p>
</td>
</tr>
</tbody>
</table>
</td>
<td style="line-height:0;">
<!-- img src="http://hosting.fyleio.com/17205/internal/templates/108972/spacer.gif" width="5" height="5" -->
</td>
<td valign="top" width="185" bgcolor="#F5F5F5" style="border:1px solid #dfdfdf; padding:14px 14px 16px;">
<table width="155" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="font-family:Arial, Helvetica, sans-serif; font-size:14px; font-weight:bold; color:#5b656d; line-height:18px; text-align:left;">
<div>
<div>Payment Method</div>
</div>
</td>
</tr>
<tr>
<td style="font-family:Arial, Helvetica, sans-serif; font-size:11px; color:#5b656d; line-height:18px; padding-top:3px; text-align:left;">
<div><?php echo $ny_card_type.'xxxxx'.$ny_card_number_last_digits; ?></div>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="border-bottom:1px dotted #999; padding-top:10px;"> </td>
</tr>
<tr>
<td style="font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000; font-weight:bold; padding:25px 0 15px 0; text-align:left;">
<div>
<div>Your order includes the following item(s):</div>
</div>
</td>
</tr>
</tbody>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0" style="border:1px solid #dfdfdf;">
<tbody>
<tr>
<td>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td bgcolor="#F5F5F5" style="font-family:Arial, Helvetica, sans-serif; font-size:12px; font-weight:bold; color:#5b656d; padding:11px 15px 11px; border-bottom:1px solid #dfdfdf; text-align:left;">
<div>
<div>Item</div>
</div>
</td>
<td align="right" bgcolor="#F5F5F5" style="font-family:Arial, Helvetica, sans-serif; font-size:12px; font-weight:bold; color:#5b656d; padding:11px 15px 11px; border-bottom:1px solid #dfdfdf;">
<div>
<div>Subtotal</div>
</div>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td><!----><!---->
<?php // @hooked WC_Emails::order_details() Shows the order details table.
// @hooked WC_Emails::order_schema_markup() Adds Schema.org markup.
// do_action( 'woocommerce_email_order_details', $order, $sent_to_admin, $plain_text, $email );
?>
<?php
echo $order->email_order_items_table( array(
'show_sku' => $sent_to_admin,
'show_image' => true,
'image_size' => array( 64, 64 ),
'plain_text' => $plain_text,
'sent_to_admin' => $sent_to_admin
) );
?>
<?php // @hooked WC_Emails::order_meta() Shows order meta data.
//do_action( 'woocommerce_email_order_meta', $order, $sent_to_admin, $plain_text, $email );
?>
<?php // @hooked WC_Emails::customer_details() Shows customer details
// @hooked WC_Emails::email_address() Shows email address
// do_action( 'woocommerce_email_customer_details', $order, $sent_to_admin, $plain_text, $email );
?>
<div style="border-bottom:1px solid #dfdfdf; line-height:0;">
<!-- img src="http://hosting.fyleio.com/17205/internal/templates/108972/spacer.gif" width="1" height="1" -->
</div>
<!----><!---->
</td>
</tr>
<tr>
<td align="right" bgcolor="#F5F5F5" style="font-family:Arial, Helvetica, sans-serif; font-size:12px; font-weight:normal; color:#5b656d; padding:11px 15px 11px; border-bottom:1px solid #dfdfdf;">
<div>
<div>Estimated Shipping & Handling: <?php echo $ny_shipping; ?> </div>
</div>
</td>
</tr>
</tbody>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td> </td>
</tr>
<tr>
<td align="left" valign="top" width="185" bgcolor="#F5F5F5" style="border:1px solid #dfdfdf;">
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="line-height:0; text-align:left;">
<img src="http://uppababy.com/wp-content/themes/UPPAbaby_2017/img/email/question-white.gif" width="49" height="43" alt="Help Icon">
</td>
<td style="font-family:Arial, Helvetica, sans-serif; font-weight:bold; font-size:12px; color:#000; text-align:left;">
<div>
<div>Important notes about your order:</div>
</div>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td style="border:1px solid #dfdfdf; border-top:none; font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#000; line-height:16px; padding:14px 14px 16px; text-align:left;">
<div>
<div>
<p>
<span xml="lang">• Your order may be shipped to you by UPPAbaby or by an authorized UPPAbaby retailer.</span>
</p>
<p>
<span xml="lang">• If sales tax is required, it will be added to the order.</span>
</p>
<p>
<span xml="lang">• If your order includes a pre-ordered item, visit the <a href="https://uppababy.com">
<span xml="lang">UPPAbaby</span></a> website to view its expected release date. We will send email when the item is available.</span>
</p>
<span xml="lang">• The charge will appear on your billing statement as: SPN*UPPAbaby.</span>
</div>
</div>
</td>
</tr>
</tbody>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="font-family:Arial, Helvetica, sans-serif; color:#000; font-size:12px; padding:20px 0 0 0; text-align:left; line-height:17px;">
<div>
<div>Thank you for shopping with UPPAbaby!</div>
</div>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
<img src="http://app.bronto.com/t/o?ssid=17205" width="0" height="0" border="0" style="visibility: hidden !important; display:none !important; max-height: 0; width: 0; line-height: 0; mso-hide: all;" alt="">
</div>
<?php
?>
</body>
</html>
<?php // @hooked WC_Emails::email_footer() Output the email footer
// do_action( 'woocommerce_email_footer', $email );
?><file_sep>/wp-content/themes/uppababy-ca-child/functions.php
<?php
function my_theme_enqueue_styles() {
$parent_style = 'style'; // This is 'uppababy' for the Twenty Fifteen theme.
wp_enqueue_style( $parent_style, 'https://uppababy.com/ui/css/style.css' );
wp_enqueue_style( 'child-style',
'https://uppababy.com/ui/css/ca-style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
);
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>
<file_sep>/wp-content/themes/uppababy/woocommerce/notices/error.php
<?php // Show error messages // theme/woocommerce/notices/error.php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! $messages ){
return;
}
//if ( is_page('checkout') ) {
if ( 1==1 ) {
?>
<style type="text/css">
.TB_modal {
max-width: 95% !important;
}
#TB_window {
top: 30% !important;
}
</style>
<script>
var ny_image_popup = '<div id="TB_overlay" class="TB_overlayBG" onclick="close_this_popup()"></div>';
ny_image_popup += '<div id="TB_window" class="TB_Transition TB_imageContent TB_captionBottom TB_singleLine" style="margin-left: -256px; width: 512px; margin-top: 7px; display: block;">';
ny_image_popup += '<a onclick="close_this_popup()" id="TB_ImageOff" title="Close">';
ny_image_popup += '<div class="rzt_checkout_message" id="rzt_checkout_error_message">';
ny_image_popup += '<ul class="woocommerce-error" style="border-top-color: #fff !important;">';
ny_image_popup += '<p id="rzt-close-popup" onclick="self.parent.tb_remove();" style="float:right; cursor:pointer;">';
ny_image_popup += '<img src="/wp-content/themes/uppababy/images/removefromcart.svg" width="17" height="17" border="0" alt="Close" title="Close">';
ny_image_popup += '</p>';
<?php
foreach ( $messages as $message ) {
echo 'ny_image_popup += "<li>* '.wp_kses_post( $message ).'</li>";';
}
?>
ny_image_popup += '<p> </p><p>Please correct and resubmit order.</p>';
ny_image_popup += '</ul>';
ny_image_popup += '</div>';
ny_image_popup += '</a>';
ny_image_popup += '<div id="TB_caption">';
ny_image_popup += '<div id="TB_secondLine"></div>';
ny_image_popup += '</div>';
ny_image_popup += '<div id="TB_closeWindow">';
ny_image_popup += '<a onclick="close_this_popup()" id="TB_closeWindowButton" title="Close">';
ny_image_popup += '<img src="/wp-content/themes/uppababy/images/tb-close.png">';
ny_image_popup += '</a>';
ny_image_popup += '</div>';
ny_image_popup += '</div>';
ny_image_popup += '';
jQuery("body").append(ny_image_popup);
function close_this_popup() {
jQuery("#TB_overlay").hide();
jQuery("#TB_window").hide();
jQuery("#TB_overlay").remove();
jQuery("#TB_window").remove();
}
jQuery('#TB_overlay, #TB_window, #TB_closeWindow').on( 'click', function(){
close_this_popup();
});
</script>
<?php } else { ?>
<ul class="woocommerce-error">
<?php foreach ( $messages as $message ) : ?>
<li>*
<?php echo wp_kses_post( $message ); ?>
</li>
<?php endforeach; ?>
</ul>
<?php } ?><file_sep>/wp-content/themes/uppababy/template-safety.php
<?php
/*
Template Name: Safety
*/
get_header(); the_post(); ?>
<?php $bannerImg = get_field('banner_image'); ?>
<section id="hero-banner" style="background-image:url('<?php echo $bannerImg['sizes']['hero-banner'] ?>'); background-size:cover; height:520px; width:1024px; background-repeat:no-repeat;">
<div class="hero-content" <?php if(get_field('banner_content_top_padding')) {?>style="padding-top:<?php the_field('banner_content_top_padding');?>px;" <?php } ?>>
<?php the_field('banner_content'); ?>
</div>
</section>
<section id="sub-nav">
<ul>
<li class="current"><a href="#">Overview</a></li>
<li><a href="#">Safety</a></li>
<li><a href="#">Convenience</a></li>
<li><a href="#">Accessories</a></li>
<li><a href="#">Tech Specs</a></li>
</ul>
</section>
<section id="panels">
<?php if( have_rows('panel')) {
while(have_rows('panel')) { the_row();
if( get_row_layout() == 'image_only' ) { ?>
<div class="image-only panel">
<?php $panelImg = get_sub_field('panel_image'); ?>
<div class="wrap clearfix">
<a href="<?php the_sub_field('image_url'); ?>"><img src="<?php echo $panelImg['sizes']['full-column'] ?>" alt="naturally fire retardant" /></a>
</div>
</div>
<? } /* close image_only */
if( get_row_layout() == 'two_column_panel' ) { ?>
<div class="two-column panel">
<div class="wrap clearfix">
<?php if(get_sub_field('optional_background')) {
$panelBG = get_sub_field('optional_background')?>
<div class="two-col-bg" style="background-image:url('<?php echo $panelBG['url']; ?>'); min-height:<?php echo $panelBG['height']; ?>px; padding-top:<?php the_sub_field('top_padding');?>px; background-position:<?php the_sub_field('background_alignment'); ?>;">
<?php } else { ?>
<div class="two-col-bg">
<?php } ?>
<div class="left-col" <?php if(get_sub_field('left_side_padding')) { ?>style="padding:<?php the_sub_field('left_side_padding'); ?>;" <?php }?>>
<?php if( have_rows('left_side')) {
while(have_rows('left_side')) { the_row(); ?>
<?php if( get_row_layout() == 'select_image_left' ) { ?>
<div class="left-item" <?php if(get_sub_field('image_padding')) { ?>style="padding:<?php the_sub_field('image_padding'); ?>;" <?php }?>>
<?php if(get_sub_field('image_url')) { ?>
<?php $loneImg = get_sub_field('image_left'); ?>
<a href="<?php the_sub_field('image_url'); ?>"><img src="<?php echo $loneImg['url'] ?>" /></a>
<?php } else {?>
<?php $loneImg = get_sub_field('image_left'); ?>
<img src="<?php echo $loneImg['url'] ?>" />
<?php } ?>
</div>
<?php } ?>
<?php if( get_row_layout() == 'select_youtube_left' ) { ?>
<div class="left-item" <?php if(get_sub_field('youtube_padding')) { ?>style="padding:<?php the_sub_field('youtube_padding'); ?>;" <?php }?>>
<div class="left-content">
<?php $Img = get_sub_field('youtube_image_left'); ?>
<a href="https://www.youtube.com/watch?v=<?php the_sub_field('youtube_id_left'); ?>" class="popup-youtube"><img src="<?php echo $Img['url'] ?>" /></a>
</div>
</div>
<?php } ?>
<?php if( get_row_layout() == 'select_content_left' ) { ?>
<div class="left-item" <?php if(get_sub_field('content_padding')) { ?>style="padding:<?php the_sub_field('content_padding'); ?>;" <?php }?>>
<div class="left-content">
<?php the_sub_field('content_left'); ?>
</div>
</div>
<?php } ?>
<?php }
} ?>
</div>
<div class="right-col" <?php if(get_sub_field('right_side_padding')) { ?>style="padding:<?php the_sub_field('right_side_padding'); ?>;" <?php }?>>
<?php if( have_rows('right_side')) {
while(have_rows('right_side')) { the_row(); ?>
<?php if( get_row_layout() == 'select_image_right' ) { ?>
<div class="right-item" <?php if(get_sub_field('image_padding')) { ?>style="padding:<?php the_sub_field('image_padding'); ?>;" <?php }?>>
<?php if(get_sub_field('image_url')) { ?>
<?php $loneImg = get_sub_field('image_right'); ?>
<a href="<?php the_sub_field('image_url'); ?>"><img src="<?php echo $loneImg['url'] ?>" /></a>
<?php } else {?>
<?php $loneImg = get_sub_field('image_right'); ?>
<img src="<?php echo $loneImg['url'] ?>" />
<?php } ?>
</div>
<?php } ?>
<?php if( get_row_layout() == 'select_youtube_left' ) { ?>
<div class="right-item" <?php if(get_sub_field('youtube_padding')) { ?>style="padding:<?php the_sub_field('youtube_padding'); ?>;" <?php }?>>
<?php $Img = get_sub_field('youtube_image_right'); ?>
<a href="https://www.youtube.com/watch?v=<?php the_sub_field('youtube_id_right'); ?>" class="popup-youtube"><img src="<?php echo $Img['url'] ?>" /></a>
</div>
<?php } ?>
<?php if( get_row_layout() == 'select_content_right' ) { ?>
<div class="right-item" <?php if(get_sub_field('content_padding')) { ?>style="padding:<?php the_sub_field('content_padding'); ?>;" <?php }?>>
<div class="right-content">
<?php the_sub_field('content_right'); ?>
</div>
</div>
<?php } ?>
<?php }
} ?>
</div>
</div>
</div>
</div>
<?php } /* close two_column_panel */
if( get_row_layout() == 'three_column_background' ) { ?>
<div class="three-column-bg panel">
<div class="wrap clearfix">
<div class="left-col">
<?php if( have_rows('left_side')) {
while(have_rows('left_side')) { the_row(); ?>
<?php if( get_row_layout() == 'select_image_left' ) { ?>
<div class="left-item">
<?php if(get_sub_field('image_url')) { ?>
<?php $loneImg = get_sub_field('image_left'); ?>
<a href="<?php the_sub_field('image_url'); ?>"><img src="<?php echo $loneImg['url'] ?>" /></a>
<?php } else {?>
<?php $loneImg = get_sub_field('image_left'); ?>
<img src="<?php echo $loneImg['url'] ?>" />
<?php } ?>
</div>
<?php } ?>
<?php if( get_row_layout() == 'select_youtube_left' ) { ?>
<div class="left-item">
<div class="left-content">
<?php $Img = get_sub_field('youtube_image_left'); ?>
<a href="https://www.youtube.com/watch?v=<?php the_sub_field('youtube_id_left'); ?>" class="popup-youtube"><img src="<?php echo $Img['url'] ?>" /></a>
</div>
</div>
<?php } ?>
<?php if( get_row_layout() == 'select_content_left' ) { ?>
<div class="left-item">
<div class="left-content">
<?php the_sub_field('content_left'); ?>
</div>
</div>
<?php } ?>
<?php }
} ?>
</div>
<div class="right-col">
<?php $threebgImg = get_sub_field('right_background'); ?>
<div class="right-bg" style="background-image:url('<?php echo $threebgImg['sizes']['three-col-bg'] ?>'); background-repeat:no-repeat; background-position: right; min-height:<?php echo $threebgImg['height']; ?>px;" >
<?php if( have_rows('center')) {
while(have_rows('center')) { the_row(); ?>
<?php if( get_row_layout() == 'select_image_center' ) { ?>
<div class="right-item">
<?php if(get_sub_field('image_url')) { ?>
<?php $loneImg = get_sub_field('image_center'); ?>
<a href="<?php the_sub_field('image_url'); ?>"><img src="<?php echo $loneImg['url'] ?>" /></a>
<?php } else {?>
<?php $loneImg = get_sub_field('image_center'); ?>
<img src="<?php echo $loneImg['url'] ?>" />
<?php } ?>
</div>
<?php } ?>
<?php if( get_row_layout() == 'select_youtube_center' ) { ?>
<div class="right-item">
<?php $Img = get_sub_field('youtube_image_center'); ?>
<a href="https://www.youtube.com/watch?v=<?php the_sub_field('youtube_id_center'); ?>" class="popup-youtube"><img src="<?php echo $Img['url'] ?>" /></a>
</div>
<?php } ?>
<?php if( get_row_layout() == 'select_content_center' ) { ?>
<div class="right-item">
<div class="right-content">
<?php the_sub_field('content_center'); ?>
</div>
</div>
<?php } ?>
<?php }
} ?>
</div>
</div>
</div>
</div>
<?php } /* close three column bg */
if( get_row_layout() == 'half-column-with-bg' ) { ?>
<?php $panelBgImg = get_sub_field('background_image'); ?>
<div class="half-column-with-bg panel" style="background-image:url('<?php echo $panelBgImg['sizes']['full-column'] ?>'); background-size:cover; width:1024px; background-repeat:no-repeat;">
<div class="wrap clearfix">
<?php the_sub_field('content'); ?>
<?php $youtubeImg = get_sub_field('youtube_video_image');?>
<a href="https://www.youtube.com/watch?v=<?php the_sub_field('youtube_video_id'); ?>" class="popup-youtube" style="padding-left:15px;"><img src="<?php echo $youtubeImg['url'] ?>" /></a>
</div>
</div>
<?php } /* close half-column-with-bg */
if( get_row_layout() == 'performance_panel' ) { ?>
<?php $performanceImg = get_sub_field('performance_background_image'); ?>
<div class="performance-system panel" style="background-image:url('<?php echo $performanceImg['sizes']['full-column'] ?>'); background-size:cover; width:1024px; background-repeat:no-repeat;">
<div class="wrap clearfix">
<?php the_sub_field('performance_top_content');?>
<div class="performance-last">
<?php the_sub_field('performance_bottom_content');?>
</div>
</div>
</div>
<?php } /* close performance_panel */
} /* close panel while */
} /* close panel if */ ?>
</section>
<?php include 'include-mini-cart.php' ?>
<?php get_footer(); ?>
<file_sep>/wp-content/themes/uppababy/footer.php
<section id="footer">
<div class="wrap">
<ul class="social-foot">
<li class="icon-facebook"><a href="<?php the_field('facebook', 'options'); ?>" target="_blank"></a></li>
<li class="icon-instagram"><a href="<?php the_field('instagram', 'options'); ?>" target="_blank"></a></li>
<li class="icon-twitter"><a href="<?php the_field('twitter', 'options'); ?>" target="_blank"></a></li>
<li class="icon-youtube"><a href="<?php the_field('youtube', 'options'); ?>" target="_blank"></a></li>
<li class="icon-pinterest"><a href="<?php the_field('pinterest', 'options'); ?>" target="_blank"></a></li>
</ul>
<ul class="links-foot">
<li>©<?php echo date("Y"); ?> UPPAbaby</li>
<li>Rockland, MA</li>
<li><a href="<?php echo site_url(); ?>/legal-docs/terms-service">Terms</a></li>
<li><a href="<?php echo site_url(); ?>/retailer-resources/"><img src="/ui/images/RetailerResources.png"/>Retailers</a></li>
</ul>
<div id="newsletterSignup" class="newsLetterBox" style="margin-top:0px;">
<div class="newsletter-box">
<div class="newsletter-left">
<a href="https://experiences.wyng.com/campaign/?experience=5924a64823847f1cae7f3d67" target="_blank" class="newsletter-link">Sign up for UPPAbaby News & Updates</a>
</div>
<div class="newsletter-right">
<a href="https://experiences.wyng.com/campaign/?experience=5924a64823847f1cae7f3d67" target="_blank"><img src="https://uppababy.com/ui/images/subscribe-arrow.jpg"></a>
</div>
</div>
</div>
</div>
</section>
</div>
<?php wp_footer(); ?>
</body>
</html>
<file_sep>/wp-content/themes/uppababy/woocommerce/checkout/form-checkout.php
<?php
/**
* Checkout Form
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
// wc_print_notices();
do_action( 'woocommerce_before_checkout_form', $checkout );
// If checkout registration is disabled and not logged in, the user cannot checkout
if ( ! $checkout->is_registration_enabled() && $checkout->is_registration_required() && ! is_user_logged_in() ) {
echo apply_filters( 'woocommerce_checkout_must_be_logged_in_message', __( 'You must be logged in to checkout.', 'woocommerce' ) );
return;
}
?>
<form name="checkout" method="post" class="checkout woocommerce-checkout" action="<?php echo esc_url( wc_get_checkout_url() ); ?>" enctype="multipart/form-data">
<div id="rzt-checkout-left-colum" style="width:333px; float:left;">
<?php if ( $checkout->get_checkout_fields() ) : ?>
<?php do_action( 'woocommerce_checkout_before_customer_details' ); ?>
<div class="col2-set" id="customer_details">
<div class="col-1" style="float: none; width: 100%;">
<?php do_action( 'woocommerce_checkout_billing' ); ?>
</div>
<div class="col-2" style="float: none; width: 100%;">
<?php do_action( 'woocommerce_checkout_shipping' ); ?>
</div>
</div>
<?php do_action( 'woocommerce_checkout_after_customer_details' ); ?>
<?php endif; ?>
</div>
<?php do_action( 'woocommerce_after_checkout_form', $checkout ); // moved here by rzt ?>
<div id="rzt-checkout-right-colum" style="float:right;">
<p id="order_review_heading" class="rzt-checkout-blue-subtitle"><?php _e( '3. Review your order', 'uppababy' ); ?></p>
<?php do_action( 'woocommerce_checkout_before_order_review' ); ?>
<div id="order_review" class="woocommerce-checkout-review-order">
<?php do_action( 'woocommerce_checkout_order_review' ); ?>
</div>
<?php do_action( 'woocommerce_checkout_after_order_review' ); ?>
</div>
</form>
<?php //do_action( 'rzt_after_checkout_form' ); // for the rzt-footer ?>
<?php echo rzt_new_footer_menu(); ?><file_sep>/wp-content/themes/uppababy/woocommerce/mobile-single-accessory.php
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if( is_page(array(17500,17506,17510)) ){
?>
<!-- <style>
#lcly-button-0 {
display:none!important;
}
.comingMAY {
display: block!important;
}
</style> -->
<?php }
global $post, $product;
$ny_product_id = get_the_ID();
/**
* hook : woocommerce_before_single_product
* @hooked wc_print_notices #10
*/
// do_action( 'woocommerce_before_single_product' );
if ( post_password_required() ) {
echo get_the_password_form();
return;
}
$ny_classes = get_post_class( array('product-box', 'align-center', 'rzt-accessory-for-mobile', 'no-padding') );
echo '<div itemscope itemtype="'.woocommerce_get_product_schema().'" id="product-'.get_the_ID().'" class = "'.implode(" ", $ny_classes).'">';
/**
* hook : woocommerce_before_single_product_summary
*/
// do_action( 'woocommerce_before_single_product_summary' );
//---
// Single Product Sale Flash function woocommerce_show_product_sale_flash #10
// sale-flash.php
if ( $product->is_on_sale() ) {
echo apply_filters(
'woocommerce_sale_flash',
'<span class="onsale rzt_sale_promo_image">' . __( 'ON SALE TODAY', 'uppababy' ) . '</span>',
$post,
$product
);
}
//---
// Single Product Image function woocommerce_show_product_images #20
// product-image.php
//echo '<div class="images product-img-box top-image accessory-image slick-initialized slick-slider">';
echo '<div class="images product-img-box top-image accessory-image ">';
echo '<div aria-live="polite" class="slick-list draggable">';
echo '<div class="slick-track" role="listbox" style="opacity: 1; width: 414px;">';
if ( has_post_thumbnail() ) {
$attachment_count = count( $product->get_gallery_attachment_ids() );
//$gallery = $attachment_count > 0 ? '[product-gallery]' : '';
$gallery = '';
$props = wc_get_product_attachment_props( get_post_thumbnail_id(), $post );
$image = get_the_post_thumbnail(
$post->ID,
apply_filters( 'single_product_large_thumbnail_size', 'shop_single' ),
array(
'title' => $props['title'],
'alt' => $props['alt'],
)
);
echo apply_filters(
'woocommerce_single_product_image_html',
sprintf(
'<a href="%s" itemprop="image" class="woocommerce-main-image thickbox zoom" title="%s" data-rel="prettyPhoto%s">%s</a>',
esc_url( $props['url'] ),
esc_attr( $props['caption'] ),
$gallery,
$image
),
$post->ID
);
} else {
echo apply_filters(
'woocommerce_single_product_image_html',
sprintf( '<img src="%s" alt="%s" />', wc_placeholder_img_src(), __( 'Placeholder', 'woocommerce' ) ),
$post->ID
);
}
do_action( 'woocommerce_product_thumbnails' );
echo '</div>';
echo '</div>';
echo '</div>';
//---
echo '<div class="summary entry-summary" style="/*margin-right: 22px; padding-left: 55px; width: 400px!important;*/">';
/**
* hook : woocommerce_single_product_summary
*/
//do_action( 'woocommerce_single_product_summary' );
echo '<div class="cms-pad">';
$ny_old_id = rzt_get_page_id_from_product_id( $ny_product_id );
$ny_mobile_old_id = $ny_old_id; // id outside of the loop (find in the globals)
//global $wp_query;
//$ny_mobile_old_id = $wp_query->$queried_object_id;
//echo '<script>console.log("old id : '.$ny_old_id.' mobile_old_id : '.$ny_mobile_old_id.'")</script>';
//---
// Single Product title function woocommerce_template_single_title 5
// title.php
$ny_accessory_title = get_the_title( $ny_old_id );
//the_title( '<h2 itemprop="name" class="product_title entry-title no-margin-bottom">', '</h2>' );
echo '<h2 itemprop="name" class="product_title entry-title no-margin-bottom">'.$ny_accessory_title.'</h2>';
//---
//--- original product page
$ny_page = get_post( $ny_old_id );
$ny_mobile_page = get_post( $ny_mobile_old_id );
$ny_accessory_content = apply_filters( 'the_content', $ny_page->post_content );
$ny_mobile_accessory_content = apply_filters( 'the_content', $ny_mobile_page->post_content );
$myStrollers = get_field('acc_for', $ny_old_id);
$xy = '';
if ( $myStrollers ) {
foreach ($myStrollers as $s) {
$s=strtolower($s);
if($s != 'g-series') {
$xy.= $s;
$xy.= ', ';
}
}
}
$xy = strtoupper($xy);
$xy = substr($xy, 0, -2);
$accessory_for_what = str_lreplace2(", ", ' '.__("and", "uppababy").' ', $xy);
$product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );
echo '<p class="accessory-sub-head">';
if(get_field('accessory_for_text', $product_id)) {
echo '<span class="agendalight" style="font-weight:normal; font-family:Agenda Light; font-size:15px;"><br />',the_field('accessory_for_text', $product_id),'</span>';
} else {
echo '<span class="agendamedium" style="font-size:24px;"><br />This Item is Missing Compatibility Text</span>';
}
// // echo '<span class="agendalight" style="font-weight:normal; font-family:Agenda Light; font-size:15px;"><br /> '.__("for", "uppababy").' '.$accessory_for_what;
//
// if( is_page( array( 2569, 2907, 2948 ) )) {
//
// echo get_field('productYear', $ny_old_id);
// }
// echo '</span>';
if( get_field('text_under_model', $ny_old_id) == 1){
echo ' <span class="agendalight" style="font-weight:normal; font-family:Agenda Light; font-size:15px;">';
echo get_field('text_under_model_txt', $ny_old_id);
echo '</span>';
}
echo '</p>';
if( get_field('old_acc', $ny_old_id) == 1){
echo '<div>
<a class="accessory-sub-link" href="'.get_field('old_acc_link', $ny_old_id).'">';
echo get_field('old_acc_text', $ny_old_id);
echo '</a>
</div>';
}
echo '</div>';
//---
//---PRODUCT DETAILS and bottom_image_1 - 3
echo '<div class="block bg--white block-accordion accessory-accordion">
<div id="accordion">
<h4 class="accordion-toggle">'.__( 'PRODUCT DETAILS', 'uppababy').'</h4>
<div class="accordion-content">'.$ny_mobile_accessory_content;
for( $i = 1; $i <= 3; $i++ ) {
if( get_field( 'bottom_image_' .$i, $ny_mobile_old_id ) ) {
$ny_bottom_image = get_field( 'bottom_image_'.$i, $ny_mobile_old_id );
if( get_field( 'image_description' . $i, $ny_mobile_old_id ) ) {
$ny_image_description = get_field( 'image_description' . $i, $ny_mobile_old_id );
}
echo '<div class="image-wrapper">
<img src="'.$ny_bottom_image.'" />'
.'<small>'.$ny_image_description.'</small>
</div>';
}
}
echo '</div>
</div>
</div>';
//---
//---
echo '<div class="block bg--white top">';
//---
// Single Product Price, including microdata for SEO function woocommerce_template_single_price 10
// price.php
echo '<div itemprop="offers" itemscope itemtype="http://schema.org/Offer">';
echo '<p class="price product-price">'.$product->get_price_html().'</p>';
echo '<meta itemprop="price" content="'.esc_attr( $product->get_display_price() ).'" />';
echo '<meta itemprop="priceCurrency" content="'.esc_attr( get_woocommerce_currency() ).'" />';
echo '<link itemprop="availability" href="http://schema.org/'.$product->is_in_stock() ? " " : "OutOfStock".'" />';
echo '</div>';
//---
// Add to cart function woocommerce_template_single_add_to_cart 30
// do_action( 'woocommerce_' . $product->product_type . '_add_to_cart' );
if ( $product->is_purchasable() ) {
if ( $product->product_type == 'simple') {
// Simple product add to cart
// add-to-cart/simple.php
// Availability
$availability = $product->get_availability();
$availability_html = empty( $availability['availability'] ) ? '' : '<p class="stock ' . esc_attr( $availability['class'] ) . '">' . esc_html( $availability['availability'] ) . '</p>';
echo apply_filters( 'woocommerce_stock_html', $availability_html, $availability['availability'], $product );
if ( $product->is_in_stock() ) {
do_action( 'woocommerce_before_add_to_cart_form' );
echo '<div class="product-buttons-box">';
echo '<form class="cart" method="post" enctype="multipart/form-data">';
do_action( 'woocommerce_before_add_to_cart_button' );
if ( ! $product->is_sold_individually() ) {
woocommerce_quantity_input( array(
'min_value' => apply_filters( 'woocommerce_quantity_input_min', 1, $product ),
'max_value' => apply_filters( 'woocommerce_quantity_input_max', $product->backorders_allowed() ? '' : $product->get_stock_quantity(), $product ),
'input_value' => ( isset( $_POST['quantity'] ) ? wc_stock_amount( $_POST['quantity'] ) : 1 )
) );
}
echo '<input type="hidden" name="add-to-cart" value="'.esc_attr( $product->id ).'" />';
echo '<button type="button" class="single_add_to_cart_button button alt">'.esc_html( $product->single_add_to_cart_text() ).'</button>';
echo '<div id="lcly-button-0">
<a id="lcly-link-0" href="http://www.locally.com" target="_blank"></a>
</div>';
echo '<script id="lcly-script-0" src="https://uppababy.locally.com/stores/map.js?company_id=24146&style='.ltrim( $product->get_sku()).'&show_location_switcher=0&show_dealers=0&show_unauthed_dealers=1&no_link=1&button_id=HTML&company_name=UPPAbaby&button_text=FIND+IT+LOCALLY&css=2" async>
</script>';
do_action( 'woocommerce_after_add_to_cart_button' );
echo '</form>';
echo '</div>';
/*echo '<div style="position:absolute; right:150px;top:265px;"><a href="/warranty/"><img style="width:135px;height:135px;" src="http://uppababy.com/wp-content/uploads/2016/01/ubExtend.png"></a></div>';
*/
echo '<script>
jQuery(document).ready(function(){
jQuery(".retailer-btn,#lcly-button-0").removeClass("full");
jQuery(".single_add_to_cart_button").show();
});
</script>';
do_action( 'woocommerce_after_add_to_cart_form' );
} else {
echo '<form class="cart">';
echo '<button type="submit" class="single_add_to_cart_button button alt disabled out-of-stock">Out of Stock</button>';
echo '</form>';
}
} else {
// Variable product add to cart
// function woocommerce_variable_add_to_cart() + add-to-cart/variable.php
// Enqueue variation scripts
wp_enqueue_script( 'wc-add-to-cart-variation' );
// Get Available variations?
$get_variations = sizeof( $product->get_children() ) <= apply_filters( 'woocommerce_ajax_variation_threshold', 30, $product );
// Load the template
//wc_get_template( 'rzt-single-variable.php', array(
$available_variations = $get_variations ? $product->get_available_variations() : false;
$attributes = $product->get_variation_attributes();
$selected_attributes = $product->get_variation_default_attributes();
$attribute_keys = array_keys( $attributes );
do_action( 'woocommerce_before_add_to_cart_form' );
echo '<form class="variations_form cart" method="post" enctype="multipart/form-data" data-product_id="'.absint( $product->id ).'" data-product_variations="'.htmlspecialchars( json_encode( $available_variations )) .'">';
do_action( 'woocommerce_before_variations_form' );
if ( empty( $available_variations ) && false !== $available_variations ) {
echo '<p class="stock out-of-stock">'.__( "This product is currently out of stock and unavailable.", "woocommerce" ).'</p>';
} else {
echo '<div class="woocommerce-variation single_variation"></div>';
echo rzt_color_box_for_mobile( $product );
echo '<table class="variations" cellspacing="0" style="display:none; height:0px; width:0px;">
<tbody>';
foreach ( $attributes as $attribute_name => $options ) {
echo '<tr>
<!--
<td class="label product-color"><label for="'.sanitize_title( $attribute_name ).'">'.wc_attribute_label( $attribute_name ).'</label></td>
-->
<td class="value">';
$selected = isset( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) ?
wc_clean( urldecode( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] )) :
$product->get_variation_default_attribute( $attribute_name );
wc_dropdown_variation_attribute_options( array(
'options' => $options,
'attribute' => $attribute_name,
'product' => $product,
'selected' => $selected,
'show_option_none' => __('Color Options', 'uppababy'),
)
);
/*echo end( $attribute_keys ) === $attribute_name ?
apply_filters( 'woocommerce_reset_variations_link', '<a class="reset_variations" href="#" title="reset"> X </a>' ) :
'';*/
echo '</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
do_action( 'woocommerce_before_add_to_cart_button' );
if ( $selected ) {
//echo '<script>console.log("ity ny selected : '.$selected.'")</script>';
echo '<script>
jQuery(document).ready(function(){
jQuery(".summary p.price.product-price").hide();
});
ny_product_color_code = "'.rzt_get_product_colors( $selected ).'";
ny_id = "#color-'.$selected.'";
jQuery("#rzt-color-boxes input+label").css("box-shadow", "");
jQuery(ny_id+"+label").css("box-shadow", "0 0 0 1px "+ny_product_color_code);
if( ny_hide_or_show_per_variation["'.$selected.'"] == 1 ) {
jQuery(".retailer-btn,#lcly-button-0").addClass("full");
jQuery(".single_add_to_cart_button").hide();
} else {
jQuery(".retailer-btn,#lcly-button-0").removeClass("full");
jQuery(".single_add_to_cart_button").show();
}
</script>';
}
if ( ! $product->is_in_stock() ) {
echo '<button type="submit" class="single_add_to_cart_button button alt disabled out-of-stock">Out of Stock</button>';
} else {
echo '<div class="single_variation_wrap product-buttons-box">';
//echo '<div class="single_variation_wrap">';
/*
Hook : woocommerce_before_single_variation
*/
do_action( 'woocommerce_before_single_variation' );
/*
Hook : woocommerce_single_variation .
to output the cart button and placeholder for variation data.
@hooked function : woocommerce_single_variation #10 (Empty div for variation data).
@hooked function : woocommerce_single_variation_add_to_cart_button #20 (Qty and cart button).
*/
//do_action( 'woocommerce_single_variation' );
if ( strpos( $product->post_name, 'cruz' ) != false ) {
$ny_css_for_color_name = 'position: absolute; top: 83px; left: 395px; text-align: center;';
} else {
$ny_css_for_color_name = 'position: absolute; top: 83px; left: 395px; text-align: center;';
}
echo '<div class="woocommerce-variation single_variation" style="/*'.$ny_css_for_color_name.'*/"></div>';
echo '<div class="woocommerce-variation-add-to-cart variations_button">';
if ( ! $product->is_sold_individually() ) {
woocommerce_quantity_input( array( 'input_value' => isset( $_POST['quantity'] ) ? wc_stock_amount( $_POST['quantity'] ) : 1 ) );
}
echo '<button type="button" class="single_add_to_cart_button button alt">'.esc_html( $product->single_add_to_cart_text() ).'</button>';
echo '<input type="hidden" name="add-to-cart" value="'.absint( $product->id ).'" />';
echo '<input type="hidden" name="product_id" value="'.absint( $product->id ).'" />';
echo '<input type="hidden" name="variation_id" class="variation_id" value="0" />';
echo '<div id="lcly-button-0">
<a id="lcly-link-0" href="http://www.locally.com" target="_blank"></a>
</div>';
echo '<script id="lcly-script-0" src="https://uppababy.locally.com/stores/map.js?company_id=24146&style='.ltrim( $product->get_sku()).'&show_location_switcher=0&show_dealers=0&show_unauthed_dealers=1&no_link=1&button_id=HTML&company_name=UPPAbaby&button_text=FIND+IT+LOCALLY&css=2" async>
</script>';
echo '</div>';
/*
Hook : woocommerce_after_single_variation
*/
do_action( 'woocommerce_after_single_variation' );
echo '</div>';
}
do_action( 'woocommerce_after_add_to_cart_button' );
}
do_action( 'woocommerce_after_variations_form' );
echo '</form>';
do_action( 'woocommerce_after_add_to_cart_form' );
} // End of variable product add to cart
} else {
echo '<div class="product-buttons-box">';
if ( ! $product->is_purchasable() ) { // or no colors to select
if( get_field('dis', $ny_mobile_old_id) == 1) {
echo '<span class="discontinued">*Discontinued</span>';
} else {
echo '<span class="comingMAY" style="display:none">Available in May</span>';
}
}
echo '
<div id="lcly-button-0">
<a id="lcly-link-0" href="http://www.locally.com" target="_blank"></a>
</div>
<script id="lcly-script-0" src="https://uppababy.locally.com/stores/map.js?company_id=24146&style='.$product->get_sku().'&show_location_switcher=0&show_dealers=0&show_unauthed_dealers=1&no_link=1&button_id=HTML&company_name=UPPAbaby&button_text=FIND+IT+LOCALLY&css=2" async>
</script>
';
echo '</div>';
} // End of is_purchasable
//--- uploads and assets
echo '<div class="product-buttons-box"> <!-- assets -->';
$manual = rzt_get_field_with_conditional( 'download_manuel_link', $ny_product_id );
$specs = rzt_get_field_with_conditional( 'config_chart', $ny_product_id );
if( $manual ) {
echo '<a href="'.$manual.'" class="manual-btn" target="_blank"><img src="'.get_stylesheet_directory_uri().'/library/images/manual-icon.png" alt="image description">'.__( 'Manual', 'uppababy' ).'</a>';
}
if( $specs ) {
echo '<a href="'.$specs.'" class="spec-btn" target="_blank"><img src="'.get_stylesheet_directory_uri().'/library/images/spec-icon.png" alt="image description">'.__( 'Config', 'uppababy' ).'</a>';
}
echo '</div> <!-- //assets -->';
echo '</div> <!-- //.block.bg--white -->';
//---
echo '</div> <!-- .summary -->';
//---
echo '<meta itemprop="url" content="'.get_the_permalink().'" />';
echo '</div><!-- #product-'.get_the_ID().' -->';
do_action( 'woocommerce_after_single_product' );
<file_sep>/wp-content/themes/uppababy/template-news.php
<?php
/*
Template Name: News
*/
get_header(); the_post(); ?>
</section>
<section id="news">
<div class="featured">
<h2>PRESS</h2>
<?php if(get_field('featured_posts', 'option')) {
while(have_rows('featured_posts', 'option')) { the_row(); ?>
<div class="featured-news">
<?php $featureObj = get_sub_field('featured', 'option');
$featureID = $featureObj->ID;
$featuredPOST = get_post($featureID);?>
<?php
echo get_the_post_thumbnail( $featuredPOST->ID, 'news-featured' ); ?>
<h2><a href="<?php echo get_permalink($featureID); ?>"><?php echo $featuredPOST->post_title; ?></a></h2>
<p>
<?php echo wp_trim_words( $featuredPOST->post_content, 50, '...' ); ?>
</p>
</div>
<?php } ?>
<?php } ?>
</div>
<div class="wrap clearfix">
<?php
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array(
'posts_per_page' => '30',
'paged' => $paged,
'post_type' => 'post',
'orderby' => 'date',
'order' => 'DESC'
);
$query = new WP_Query( $args );
if( $query->have_posts()) { ?>
<?php while( $query->have_posts() ) {
$query->the_post(); ?>
<div class="news-result">
<?php the_post_thumbnail('news-result'); ?>
<h4 class="title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
<?php the_excerpt(); ?>
</div>
<?php } ?>
<?php } ?>
<section id="loadmore">
<?php next_posts_link('Load More',$query->max_num_pages); ?>
</section>
</div>
</section>
<?php get_footer(); ?>
<file_sep>/wp-content/themes/uppababy/template-checkout.php
<?php
/**
Template Name: Checkout Page
*/
get_header();
?>
<div id="panels">
<div id="content" role="main">
<?php while ( have_posts() ) : the_post(); ?>
<div class="checkout-content entry-content">
<?php the_content(); ?>
</div><!-- .checkout-content -->
<?php endwhile; // end of the loop. ?>
</div><!-- #content -->
</div><!-- #panels -->
<?php get_footer(); ?><file_sep>/wp-content/themes/uppababy/functions/functions-post-types.php
<?php
// Manuals
$postName = 'Manuals'; // Name of post type
$postNameSlug = 'manuals'; // Name of post type
$postNameSingular = 'Manual'; // Singular Name
$postNamePlural = 'Manuals'; // Plural Name
$postDashIcon = 'dashicons-admin-post'; // Define Dashicon | Commonly Used: News = dashicons-welcome-widgets-menus, Clients - dashicons-businessman, Team - dashicons-groups, Event - dashicons-calendar, Full List - https://developer.wordpress.org/resource/dashicons/
register_post_type(
$postNameSlug, array(
'labels' => array(
'name' => $postName,
'singular_name' => $postNameSingular,
'add_new' => 'Add ' . $postNameSingular,
'add_new_item' => 'Add ' . $postNameSingular,
'edit_item' => 'Edit ' . $postNameSingular,
'search_items' => 'Search ' . $postNamePlural,
'not_found' => 'No ' . $postNamePlural. ' found',
'not_found_in_trash' => 'No ' . $postNamePlural. ' found in trash'
),
'public' => true,
'show_ui' => true,
'capability_type' => 'post',
'menu_icon' => $postDashIcon,
'hierarchical' => true,
'rewrite' => array('slug' => $postNameSlug),
'query_var' => true,
'show_in_nav_menus' => true,
'exclude_from_search' => false,
'has_archive' => false,
'supports' => array(
'title',
'editor',
'author',
'thumbnail', //featured image, theme must also support thumbnails
'excerpt',
'trackbacks',
'custom-fields',
'comments',
'revisions',
'page-attributes' //template and menu order, hierarchical must be true
)
)
);
// Sample Register Taxonomy
$taxonomyName = 'Manual Category';
$taxonomyNameSlug = 'manual-category';
$taxonomyNameSingular = 'Manual Category';
$taxonomyNamePlural = 'Manual Categories';
register_taxonomy(
$taxonomyNameSlug, array($postNameSlug), array(
'hierarchical' => true, // Category or Tag functionality
'query_var' => true,
'rewrite' => array('slug' => $taxonomyNameSlug),
'labels' => array(
'name' => $taxonomyName,
'singular_name' => $taxonomyNameSingular,
'search_items' => 'Search ' . $taxonomyNamePlural,
'popular_items' => 'Popular ' . $taxonomyNamePlural,
'all_items' => 'All ' . $taxonomyNamePlural,
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => 'Edit ' . $taxonomyNameSingular,
'update_item' => 'Update ' . $taxonomyNameSingular,
'add_new_item' => 'Add New ' . $taxonomyNameSingular,
'new_item_name' => 'New ' . $taxonomyNameSingular,
'separate_items_with_commas' => 'Separate ' . $taxonomyNamePlural . ' with commas',
'add_or_remove_items' => 'Add or remove ' . $taxonomyNamePlural,
'choose_from_most_used' => 'Choose from most used ' . $taxonomyNamePlural
)
)
);
// Configuration Charts
$postName = 'Config Charts'; // Name of post type
$postNameSlug = 'config-charts'; // Name of post type
$postNameSingular = 'Config Chart'; // Singular Name
$postNamePlural = 'Config Charts'; // Plural Name
$postDashIcon = 'dashicons-admin-post'; // Define Dashicon | Commonly Used: News = dashicons-welcome-widgets-menus, Clients - dashicons-businessman, Team - dashicons-groups, Event - dashicons-calendar, Full List - https://developer.wordpress.org/resource/dashicons/
register_post_type(
$postNameSlug, array(
'labels' => array(
'name' => $postName,
'singular_name' => $postNameSingular,
'add_new' => 'Add ' . $postNameSingular,
'add_new_item' => 'Add ' . $postNameSingular,
'edit_item' => 'Edit ' . $postNameSingular,
'search_items' => 'Search ' . $postNamePlural,
'not_found' => 'No ' . $postNamePlural. ' found',
'not_found_in_trash' => 'No ' . $postNamePlural. ' found in trash'
),
'public' => true,
'show_ui' => true,
'capability_type' => 'post',
'menu_icon' => $postDashIcon,
'hierarchical' => true,
'rewrite' => array('slug' => $postNameSlug),
'query_var' => true,
'show_in_nav_menus' => true,
'exclude_from_search' => false,
'has_archive' => false,
'supports' => array(
'title',
'editor',
'author',
'thumbnail', //featured image, theme must also support thumbnails
'excerpt',
'trackbacks',
'custom-fields',
'comments',
'revisions',
'page-attributes' //template and menu order, hierarchical must be true
)
)
);
/*
// Sample Register Post
$postName = 'Newsroom'; // Name of post type
$postNameSlug = 'news-post'; // Name of post type
$postNameSingular = 'News Posts'; // Singular Name
$postNamePlural = 'News Posts'; // Plural Name
$postDashIcon = 'dashicons-admin-post'; // Define Dashicon | Commonly Used: News = dashicons-welcome-widgets-menus, Clients - dashicons-businessman, Team - dashicons-groups, Event - dashicons-calendar, Full List - https://developer.wordpress.org/resource/dashicons/
register_post_type(
$postNameSlug, array(
'labels' => array(
'name' => $postName,
'singular_name' => $postNameSingular,
'add_new' => 'Add ' . $postNameSingular,
'add_new_item' => 'Add ' . $postNameSingular,
'edit_item' => 'Edit ' . $postNameSingular,
'search_items' => 'Search ' . $postNamePlural,
'not_found' => 'No ' . $postNamePlural. ' found',
'not_found_in_trash' => 'No ' . $postNamePlural. ' found in trash'
),
'public' => true,
'show_ui' => true,
'capability_type' => 'post',
'menu_icon' => $postDashIcon,
'hierarchical' => true,
'rewrite' => array('slug' => $postNameSlug),
'query_var' => true,
'show_in_nav_menus' => true,
'exclude_from_search' => false,
'has_archive' => false,
'supports' => array(
'title',
'editor',
'author',
'thumbnail', //featured image, theme must also support thumbnails
'excerpt',
'trackbacks',
'custom-fields',
'comments',
'revisions',
'page-attributes' //template and menu order, hierarchical must be true
)
)
);
// Sample Register Taxonomy
$taxonomyName = 'News Type';
$taxonomyNameSlug = 'news-type';
$taxonomyNameSingular = 'News Type';
$taxonomyNamePlural = 'News Types';
register_taxonomy(
$taxonomyNameSlug, array($postNameSlug), array(
'hierarchical' => true, // Category or Tag functionality
'query_var' => true,
'rewrite' => array('slug' => $taxonomyNameSlug),
'labels' => array(
'name' => $taxonomyName,
'singular_name' => $taxonomyNameSingular,
'search_items' => 'Search ' . $taxonomyNamePlural,
'popular_items' => 'Popular ' . $taxonomyNamePlural,
'all_items' => 'All ' . $taxonomyNamePlural,
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => 'Edit ' . $taxonomyNameSingular,
'update_item' => 'Update ' . $taxonomyNameSingular,
'add_new_item' => 'Add New ' . $taxonomyNameSingular,
'new_item_name' => 'New ' . $taxonomyNameSingular,
'separate_items_with_commas' => 'Separate ' . $taxonomyNamePlural . ' with commas',
'add_or_remove_items' => 'Add or remove ' . $taxonomyNamePlural,
'choose_from_most_used' => 'Choose from most used ' . $taxonomyNamePlural
)
)
);
*/
<file_sep>/wp-content/themes/uppababy/template-compatability.php
<?php
/*
Template Name: Compatability
*/
get_header(); the_post(); ?>
<?php $pageBannerImage = get_field('top_banner');
$global_rows = get_field('default_accessories_banner', 'options'); // get all the rows
$rand_global_row = $global_rows[ array_rand( $global_rows ) ]; // get a random row
$rand_global_row_image = $rand_global_row['accessories_banner' ]; // get the sub field value
if($pageBannerImage) {
?>
<section id="hero-banner" style="background-image:url('<?php echo $pageBannerImage['sizes']['hero-banner']; ?>'); background-size:cover; background-repeat:no-repeat;">
<?php } elseif($rand_global_row_image) { ?>
<section id="hero-banner" style="background-image:url('<?php echo $rand_global_row_image['sizes']['hero-banner']; ?>'); background-size:cover; background-repeat:no-repeat;">
<?php } ?>
</section>
<section id="compat-chart">
<?php if(have_rows('chart')) {
$counterOut = 1;
$counterIn = 20;?>
<h2>Compatability Chart</h2>
<?php the_field('instructions') ?>
<?php while(have_rows('chart')) { the_row(); ?>
<div class="acc-product-extra-info">
<input id="tab-<?php echo $counterOut; ?>" type="checkbox" name="tabs">
<label for="tab-<?php echo $counterOut; ?>">Upper Seat <?php the_sub_field('upper_seat_name') ?></label>
<div class="tab-content">
<?php if(have_rows('you_will_need_upper')) { ?>
<h3>Upper Seat Adapter</h3>
<div class="upper-list">
<?php while(have_rows('you_will_need_upper')) { the_row();
$upperImg = get_sub_field('image'); ?>
<div class="upper-item">
<img src="<?php echo $upperImg['url'];?>" />
<h4><?php the_sub_field('name'); ?></h4>
<?php the_sub_field('description'); ?>
</div>
<?php } ?>
</div>
<?php } ?>
<?php if(have_rows('lower_seat_options')) {
while(have_rows('lower_seat_options')) { the_row(); ?>
<input id="tab-in-<?php echo $counterIn; ?>" type="checkbox" name="tabs">
<label for="tab-in-<?php echo $counterIn; ?>">Lower Seat <?php the_sub_field('lower_seat_name') ?></label>
<?php $counterIn++; ?>
<div class="tab-content-inner">
<?php if(have_rows('lower_you_will_need')) { ?>
<h3>Lower Seat Adapter</h3>
<div class="lower-list">
<?php while(have_rows('lower_you_will_need')) { the_row();
$lowerImg = get_sub_field('lower_image');?>
<div class="lower-item">
<img src="<?php echo $lowerImg['url'];?>" />
<h4><?php the_sub_field('lower_title'); ?></h4>
<?php the_sub_field('lower_description'); ?>
</div>
<?php } ?>
</div>
<?php }?>
</div>
<?php } ?>
<?php } ?>
</div>
</div>
<?php $counterOut++;
} ?>
<?php } ?>
</section>
<?php get_footer(); ?>
<file_sep>/wp-content/themes/uppababy-uk-child/template-home.php
<?php
/*
Template Name: Home
*/
get_header(); the_post(); ?>
<section id="home-carousel">
<div class="owl-carousel home-slider owl-theme">
<?php if (get_field('slides')) {
while(have_rows('slides')) { the_row();
$heroSlide = get_sub_field('slide_image'); ?>
<div class="item">
<?php if(get_sub_field('slide_link')) { ?>
<a href="<?php the_sub_field('slide_link'); ?>"><img src="<?php echo $heroSlide['sizes']['hero-banner']; ?>" alt="<?php echo $heroSlide['alt']; ?>" /></a>
<?php } else {?>
<img src="<?php echo $heroSlide['sizes']['hero-banner']; ?>" alt="<?php echo $heroSlide['alt']; ?>" />
<?php }?>
</div>
<?php } ?>
<?php }?>
</div>
</section>
<section id="home-promos">
<div class="promo1">
<?php
$promoTop = get_field('promo_top');
$promoBottom = get_field('promo_bottom');
?>
<a href="<?php the_field('promo_top_url'); ?>"><img src="<?php echo $promoTop['sizes']['home-half-promo']; ?>" alt="<?php echo $promoTop['alt']; ?> I AM A TEST" class="top-promo" /></a>
<a href="<?php the_field('promo_bottom_url'); ?>" class="bottom-promo"><img src="<?php echo $promoBottom['sizes']['home-half-promo']; ?>" alt="<?php echo $promoBottom['alt']; ?>" class="bottom-promo" /></a>
</div>
<div class="promo2">
<img src="/ui/images/UbUGC_Homepage_hdr.png" alt="Be part of the UPPAbaby Family" style="padding-bottom:7px;">
<div class="IGfeed"><?php echo do_shortcode('[instagram-feed]') ?></div>
</div>
<div class="promo3">
<?php
$rightTop = get_field('promo_image_right', 22582);
$rightBottom = get_field('right_promo_bottom');
?>
<div class="promo3-top">
<p>
<?php the_field('promo_header_text', 22582); ?>
</p>
<a href="<?php the_field('promo_url_right', 22582); ?>"><img src="<?php echo $rightTop['sizes']['home-right-top-promo'] ?>" alt="<?php echo $rightTop['alt'] ?>" style="padding-bottom:10px;" /></a>
</div>
<a href="<?php the_field('right_promo_bottom_url'); ?>"><img src="<?php echo $rightBottom['sizes']['home-right-bot-promo'] ?>" alt="<?php echo $rightBottom['alt'] ?>" /></a>
</div>
</section>
<section id="mobile-home">
<?php if(have_rows('mobile_promo_images')) {
while(have_rows('mobile_promo_images')) { the_row();
$mobilePromo = get_sub_field('promo_image'); ?>
<div class="mobile-promos">
<?php if(get_sub_field('promo_url')) {?>
<a href="<?php the_sub_field('promo_url'); ?>"><img src="<?php echo $mobilePromo['sizes']['mobile-image']; ?>" alt="<?php echo $mobilePromo['alt']; ?>" /></a>
<?php } else { ?>
<img src="<?php echo $mobilePromo['sizes']['mobile-image']; ?>" alt="<?php echo $mobilePromo['alt']; ?>" />
<?php } ?>
</div>
<?php } ?>
<?php } ?>
<div class="promo3">
<?php
$rightTop = get_field('right_promo_top');
$rightBottom = get_field('right_promo_bottom');
?>
<a href="https://www.youtube.com/watch?v=<?php the_field('right_promo_video_id'); ?>" class="popup-youtube"><img src="<?php echo $rightTop['sizes']['home-right-top-promo'] ?>" alt="<?php echo $rightTop['alt'] ?>" /></a>
</div>
<div class="tune-up-promo">
<?php the_field('tune_up_content');?>
<div class="event-btn">
<a href="<?php the_field('tune_up_url'); ?>"><?php the_field('tune_up_button_text'); ?></a>
</div>
</div>
<div class="alert">
<?php $alertImg = get_field('alert_images'); ?>
<a href="<?php the_field('tune_up_url'); ?>"><img src="<?php echo $alertImg['sizes']['mobile-image']; ?>" alt="<?php echo $alertImg['alt']; ?>" /></a>
</div>
<div class="register">
<a href="<?php the_field('register_url'); ?>"><?php the_field('register_text'); ?></a>
</div>
</section>
<?php get_footer(); ?>
<file_sep>/wp-content/themes/uppababy/template-manuals.php
<?php
/*
Template Name: Support
*/
get_header(); the_post(); ?>
<?php
$pageBannerImage = get_field('banner_image');
$global_rows = get_field('default_accessories_banner', 'options'); // get all the rows
$rand_global_row = $global_rows[ array_rand( $global_rows ) ]; // get a random row
$rand_global_row_image = $rand_global_row['accessories_banner' ]; // get the sub field value
if($pageBannerImage) { ?>
<section id="hero-banner" style="background-image:url('<?php echo $pageBannerImage['sizes']['hero-banner'] ?>'); background-size:cover; background-repeat:no-repeat;">
<div class="hero-content" <?php if(get_field('banner_content_padding')) {?>style="padding:<?php the_field('banner_content_padding');?>;" <?php } ?> <?php if( get_field('do_you_need_dark_text')){ ?>style="color:#666;"<?php } ?>>
<?php the_field('banner_content'); ?>
</div>
<?php } elseif($rand_global_row_image) { ?>
<section id="hero-banner" style="background-image:url('<?php echo $rand_global_row_image['sizes']['hero-banner'] ?>'); background-size:cover; background-repeat:no-repeat;">
<div class="hero-content" <?php if(get_field('banner_content_padding')) {?>style="padding:<?php the_field('banner_content_padding');?>;" <?php } ?> <?php if( get_field('do_you_need_dark_text')){ ?>style="color:#666;"<?php } ?>>
<?php the_field('banner_content'); ?>
</div>
<?php } ?>
</section>
<section id="support">
<div class="content-wrap">
<div class="contact-box">
<?php if(have_rows('address_box', 'option')) {
while(have_rows('address_box', 'option')) { the_row(); ?>
<h3><?php the_sub_field('address_header', 'option'); ?></h3>
<?php the_sub_field('address_text', 'option'); ?>
<?php } ?>
<?php } ?>
</div>
<div class="support-column">
<h2>Product Manuals</h2>
<?php
if(get_field('category_list')) {
$counter = 1;
while(have_rows('category_list')) { the_row();
$prodCat = get_sub_field('category_slug');
$prodSlug = $prodCat->slug;
$prodLabel = $prodCat->name;
$args = array(
'posts_per_page' => '-1',
'manual-category' => $prodSlug,
'post_type' => 'manuals',
'orderby' => 'menu_order',
'order' => 'ASC'
); ?>
<div class="acc-product-extra-info">
<input id="tab-<?php echo $counter; ?>" type="checkbox" name="tabs">
<label for="tab-<?php echo $counter; ?>"><?php echo $prodLabel; ?></label>
<? $query = new WP_Query( $args );
if( $query->have_posts()) {
while( $query->have_posts() ) {
$query->the_post(); ?>
<div class="tab-content">
<?php $file = get_field('product_manual'); ?>
<h4 class="title"><a href="<?php echo $file['url']; ?>"><?php the_title(); ?></a></h4>
</div>
<?php }
}
wp_reset_query();
$counter++;?>
</div>
<?php }
}
?>
</div>
</div>
</section>
<?php get_footer(); ?>
<file_sep>/wp-content/themes/uppababy/single-product.php
<?php get_header(); the_post(); ?>
<?php
$pageBannerImage = get_field('top_banner');
$global_rows = get_field('default_accessories_banner', 'options'); // get all the rows
$rand_global_row = $global_rows[ array_rand( $global_rows ) ]; // get a random row
$rand_global_row_image = $rand_global_row['accessories_banner' ]; // get the sub field value
if($pageBannerImage) { ?>
<section id="hero-banner" class="acc-banner" style="background-image:url('<?php echo $pageBannerImage['sizes']['hero-banner']; ?>'); background-size:cover; background-repeat:no-repeat;">
<?php } elseif($rand_global_row_image) { ?>
<section id="hero-banner" class="acc-banner" style="background-image:url('<?php echo $rand_global_row_image['sizes']['hero-banner']; ?>'); background-size:cover; background-repeat:no-repeat;">
<?php } ?>
</section>
<section id="sub-nav">
<?php wp_nav_menu('menu=accessories-sub-nav&container='); ?>
</section>
<section id="acc-product">
<div class="acc-two-col product">
<div class="wrap clearfix">
<div class="right-col">
<?php if(get_field('product_gallery')) {?>
<div class="img-box">
<div id="slider" class="owl-carousel">
<?php //--- slider images
$rzt_image_counter = 0;
while(have_rows('product_gallery')) {
the_row();
$mainIMG = get_sub_field('product_image');
if ( $rzt_image_counter == 0 ) {
$ny_image_id = ' id="rzt_first_image"';
} else {
$ny_image_id = '';
}
echo '<div class="projectitem rzt-carousel-image">';
echo '<img'.$ny_image_id.' src="'.$mainIMG['sizes']['accessories_main'].'" />';
echo '</div>';
$rzt_image_counter = 1;
}
?>
</div>
<div id="navigation" class="owl-carousel">
<?php //--- slider thumbnails
$rzt_thumb_counter = 0;
while(have_rows('product_gallery')) {
the_row();
$thumbIMG = get_sub_field('product_image');
if ( $rzt_thumb_counter == 0 ) {
$ny_thumb_id = ' id="rzt_first_thumb"';
} else {
$ny_thumb_id = '';
}
echo '<div class="projectitem rzt-carousel-thumb">';
echo '<img'.$ny_thumb_id.' src="'.$thumbIMG['sizes']['accessories_thumb'].'" />';
echo '</div>';
$rzt_thumb_counter = 1;
}
?>
</div>
</div>
<?php }?>
</div>
<div class="left-col">
<div class="acc-product-desc">
<?php wc_print_notices(); ?>
<h2><?php the_title() ?></h2>
<p>
<?php the_field('compatibility_information'); ?>
</p>
<?php the_field('product_information'); ?>
</div>
<?php if(get_field('tech_specs')) { ?>
<div class="acc-product-extra-info">
<input id="tab-one" type="checkbox" name="tabs">
<label for="tab-one">Tech Specs</label>
<div class="tab-content">
<?php the_field('tech_specs'); ?>
</div>
</div>
<?php } ?>
<?php if(get_field('additional_information')) { ?>
<div class="acc-product-extra-info">
<input id="tab-two" type="checkbox" name="tabs">
<label for="tab-two">Additional Information</label>
<div class="tab-content">
<?php the_field('additional_information'); ?>
</div>
</div>
<?php } ?>
<div class="acc-product-links">
<ul>
<?php $post_object = get_field('product_manual');
if( $post_object ){
// override $post
$post = $post_object;
setup_postdata( $post );
$manual = get_field('product_manual');
?>
<li><strong><a href="<?php echo $manual['url']; ?>">Download Manual ></strong></a></li>
<?php wp_reset_postdata();
} ?>
<?php $post_object = get_field('configuration_chart');
if( $post_object ){
// override $post
$post = $post_object;
setup_postdata( $post );
$chart = get_field('chart_image');
?>
<li><strong><a href="<?php echo $manual['url']; ?>">Configuration Chart ></strong></a></li>
<?php wp_reset_postdata();
} ?>
<?php if(get_field('older_model')) {
$pageLink = get_field('older_model'); ?>
<li><strong><a href="<?php echo $pageLink; ?>">View Older Model ></a></strong></li>
<?php }?>
<?php if(get_field('additional_urls')) {
while(have_rows('additional_urls')) { the_row(); ?>
<li><strong><a href="<?php the_sub_field('url'); ?>"><?php the_sub_field('url_text'); ?> ></a></strong></li>
<?php } ?>
<?php }?>
</ul>
</div>
<?php
//---
//---
include 'include-mini-cart-accessories.php';
//---
//---
?>
</div>
</div>
</div>
</div>
</section>
<?php get_footer(); ?>
<file_sep>/wp-content/themes/uppababy/template-accessories.php
<?php
/*
Template Name: Accessories
*/
get_header(); the_post(); ?>
<?php
$pageBannerImage = get_field('banner_image');
$global_rows = get_field('default_accessories_banner', 'options'); // get all the rows
$rand_global_row = $global_rows[ array_rand( $global_rows ) ]; // get a random row
$rand_global_row_image = $rand_global_row['accessories_banner' ]; // get the sub field value
if($pageBannerImage) { ?>
<section id="hero-banner" style="background-image:url('<?php echo $pageBannerImage['sizes']['hero-banner']; ?>'); background-size:cover; background-repeat:no-repeat;">
<?php } elseif($rand_global_row_image) { ?>
<section id="hero-banner" style="background-image:url('<?php echo $rand_global_row_image['sizes']['hero-banner']; ?>'); background-size:cover; background-repeat:no-repeat;">
<?php } ?>
</section>
<section id="sub-nav">
<?php
$subNav = get_field('select_sub_nav');
wp_nav_menu(
array(
'menu' => $subNav,
'container' => ''
)
);
?>
</section>
<section id="accessories-list">
<div class="acc-logo">
<?php $prodLogo = get_field('product_family_logo'); ?>
<img src="<?php echo $prodLogo['url']; ?>" alt=""/>
</div>
<?php the_field('product_category_heading'); ?>
<?php
if(get_field('category_list')) {
while(have_rows('category_list')) { the_row();
$prodCat = get_sub_field('category_slug');
$prodSlug = $prodCat->slug;
$prodLabel = $prodCat->name;
$args = array(
'posts_per_page' => '-1',
'product_cat' => $prodSlug,
'post_type' => 'product',
'orderby' => 'menu_order',
'order' => 'ASC',
); ?>
<div class="acc-section">
<h2><?php echo $prodLabel; ?></h2>
<? $query = new WP_Query( $args );
if( $query->have_posts()) {
while( $query->have_posts() ) {
$query->the_post(); ?>
<div class="item">
<?php $accIMG = get_field('hero_thumbnail');?>
<a href="<?php the_permalink();?>"><img src="<?php echo $accIMG['sizes']['acc-list-img'];?>" alt="<?php echo $accIMG['alt']; ?>" /></a>
<h4 class="title"><a href="<?php the_permalink();?>"><?php the_title(); ?></a></h4>
<p class="price">
<a href="<?php the_permalink();?>"><?php echo $product->get_price_html(); ?></a>
</p>
</div>
<?php }
}
wp_reset_query(); ?>
</div>
<?php }
}?>
</section>
<?php get_footer(); ?>
<file_sep>/wp-content/themes/uppababy/woocommerce/checkout/payment.php
<?php // Checkout Payment Section
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! is_ajax() ) {
do_action( 'woocommerce_review_order_before_payment' );
}
?>
<div id="payment" class="woocommerce-checkout-payment">
<p class="rzt-checkout-blue-subtitle"><?php _e( '2. Payment method', 'uppababy' ); ?></p>
<div id="rzt-cards-logo">
<ul>
<li><img src="https://cdn.shptrn.com/media/mfg/639/design_content/0//cc_mastercard.png" alt="Mastercard" title="Mastercard" width="46" height="25"></li>
<li><img src="https://cdn.shptrn.com/media/mfg/639/design_content/0//cc_visa.png" alt="Visa" title="Visa" width="46" height="25"></li>
<li><img src="https://cdn.shptrn.com/media/mfg/639/design_content/0//cc_amex.png" alt="American Express" title="American Express" width="46" height="25"></li>
<li><img src="https://cdn.shptrn.com/media/mfg/639/design_content/0//cc_discover.png" alt="Discover" title="Discover" width="46" height="25"></li>
<!-- <li><img src="https://www.paypalobjects.com/webstatic/en_US/i/buttons/pp-acceptance-small.png" alt="Buy now with PayPal"></li> -->
</ul>
</div>
<?php if ( WC()->cart->needs_payment() ) : ?>
<ul class="wc_payment_methods payment_methods methods">
<?php
if ( ! empty( $available_gateways ) ) {
foreach ( $available_gateways as $gateway ) {
wc_get_template( 'checkout/payment-method.php', array( 'gateway' => $gateway ) );
}
} else {
echo '<li>' . apply_filters( 'woocommerce_no_available_payment_methods_message', WC()->customer->get_country() ? __( 'Sorry, it seems that there are no available payment methods for your state. Please contact us if you require assistance or wish to make alternate arrangements.', 'woocommerce' ) : __( 'Please fill in your details above to see available payment methods.', 'woocommerce' ) ) . '</li>';
}
?>
</ul>
<?php endif; ?>
<div class="form-row place-order">
<noscript>
<?php _e( 'Since your browser does not support JavaScript, or it is disabled, please ensure you click the <em>Update Totals</em> button before placing your order. You may be charged more than the amount stated above if you fail to do so.', 'woocommerce' ); ?>
<br/><input type="submit" class="button alt" name="woocommerce_checkout_update_totals" value="<?php esc_attr_e( 'Update totals', 'woocommerce' ); ?>" />
</noscript>
<?php wc_get_template( 'checkout/terms.php' ); ?>
<?php do_action( 'woocommerce_review_order_before_submit' ); ?>
<?php echo apply_filters( 'woocommerce_order_button_html', '<input type="submit" class="button alt rzt-place-order-new" name="woocommerce_checkout_place_order" id="place_order" value="' . esc_attr( $order_button_text ) . '" data-value="' . esc_attr( $order_button_text ) . '" />' ); ?>
<?php do_action( 'woocommerce_review_order_after_submit' ); ?>
<?php wp_nonce_field( 'woocommerce-process_checkout' ); ?>
</div>
</div>
<?php
if ( ! is_ajax() ) {
do_action( 'woocommerce_review_order_after_payment' );
}
<file_sep>/ui/js/jquery.init.js
/* ========================================================================= */
/* BE SURE TO COMMENT CODE/IDENTIFY PER PLUGIN CALL */
/* ========================================================================= */
jQuery(function($){
// ORPHANIZER
$(".orphan").each(function() {
var txt = $(this).html().trim().replace(' ',' ');
var wordArray = txt.split(" ");
if (wordArray.length > 1) {
wordArray[wordArray.length-2] += " " + wordArray[wordArray.length-1];
wordArray.pop();
$(this).html(wordArray.join(" "));
}
});
//contact even when online
window.zESettings = {
webWidget: {
contactOptions: {
enabled: true
}
}
};
//popup videos
$('.popup-youtube, .popup-vimeo, .popup-gmaps').magnificPopup({
disableOn: 700,
type: 'iframe',
mainClass: 'mfp-fade',
removalDelay: 160,
preloader: false,
fixedContentPos: false
});
//mobile nav toggle
$('#m-toggle').on('click',function(){
$(this).toggleClass('x');
$('.menu-normal').toggleClass('menu-open');
$('#body').toggleClass('stop-scroll');
$('.mobile-nav').slideToggle(150);
});
$(window).on('resize',function(){
var ww = $(window).width();
if(ww > 960){
$('.mobile-nav').removeAttr('style');
$('#m-toggle').removeClass('x');
}
})
$('#menu-mobile-nav>li').on('click', function() {
$('#menu-mobile-nav li .sub-menu').each(function() {
if($(this).is(":visible")) {
$(this).toggleClass('x').slideUp();
}
});
if($(this).children('.sub-menu').length) {
$(this).toggleClass('x');
if(!$(this).children('.sub-menu').is(":visible")) {
$(this).children('.sub-menu').slideToggle();
}
return false;
}
});
$('a').on('click',function(e){
e.stopPropagation();
});
// sub-menu accordion
$("a").on('click', function() {
$('.sub-menu').css('display', 'none');
$(this).parent().children("ul").slideToggle( {
duration: 'fast',
step: function() {
if ($(this).css('display') == 'block') {
$(this).css('display', 'table');
}
},
complete: function() {
if ($(this).css('display') == 'block') {
$(this).css('display', 'table');
}
}
});
})
//OWLS HOME PAGE
$('.home-slider').owlCarousel({
loop:true,
autoplay:true,
nav:false,
items:1
})
//mobile slider
$('.mobile-info').owlCarousel({
loop:true,
autoplay:true,
nav:false,
items:1
})
//OWLS ACC IMG CONTROLS
jQuery(document).ready(function(){
var sync1 = $("#slider");
var sync2 = $("#navigation");
var flag = false;
var slides = sync1.owlCarousel({
items:1,
loop:true,
margin:10,
autoplay:false,
autoplayTimeout:6000,
autoplayHoverPause:false,
nav: false,
dots: true,
autoHeight:true
});
var thumbs = sync2.owlCarousel({
items:4,
loop:false,
margin:10,
autoplay:false,
nav: false,
dots: false
}).on('click', '.owl-item', function(e) {
e.preventDefault();
sync1.trigger('to.owl.carousel', [$(e.target).parents('.owl-item').index(), 300, true]);
}).on('change.owl.carousel', function(e) {
if (e.namespace && e.property.name === 'position' && !flag) {
//nsole.log('...');
}
}).data('owl.carousel');
});
$('#searchform input[type=checkbox]').on('click', function() {
$('.hm-search').focus();
});
// PARALLAX
/*
$(document).scroll(function(){
var nm = $("html").scrollTop();
var nw = $("body").scrollTop();
var n = (nm > nw ? nm : nw);
$('#element').css({
'webkitTransform' : 'translate3d(0, ' + n + 'px, 0)',
'MozTransform' : 'translate3d(0, ' + n + 'px, 0)',
'msTransform' : 'translateY(' + n + 'px)',
'OTransform' : 'translate3d(0, ' + n + 'px, 0)',
'transform' : 'translate3d(0, ' + n + 'px, 0)',
});
// if transform3d isn't available, use top over background-position
//$('#element').css('top', Math.ceil(n/2) + 'px');
});
*/
/* ====== Twitter API Call =============================================
This script automatically adds <li> before and after template. Don't forget to setup Auth info in /twitter/index.php */
/*
$('#tweets-loading').tweet({
modpath: '/path/to/twitter/', // only needed if twitter folder is not in root
username: 'jackrabbits',
count: 1,
template: '<p>{text}</p><p class="tweetlink">{time}</p>'
});
$('.tweet_text a').each(function(){
$(this).attr('target','_blank');
});
*/
});
<file_sep>/wp-content/themes/uppababy/rzt_main_functions.php
<?php
/*
if ( !defined('ABSPATH') || !class_exists( 'WooCommerce' )) {
exit;
}
*/
//---
if ( defined('RZT_MOBILE_CHECK') && RZT_MOBILE_CHECK === true ) {
function rzt_header_cart_content( $fragments ) {
global $woocommerce;
echo ' <a class="cart-contents" href="'.wc_get_checkout_url().'" title="">'
.$woocommerce->cart->cart_contents_count
.' </a>';
$fragments['a.cart-contents'] = ob_get_clean();
return $fragments;
}
add_filter('woocommerce_add_to_cart_fragments', 'rzt_header_cart_content');
} else {
function rzt_header_cart_content( $fragments ) {
global $woocommerce;
echo ' <a class="cart-contents" href="'
.wc_get_checkout_url().'" title="" onclick="rzt_show_the_mini_cart_widget(); return false;">'
.$woocommerce->cart->cart_contents_count
.' </a>';
$fragments['a.cart-contents'] = ob_get_clean();
return $fragments;
}
add_filter('woocommerce_add_to_cart_fragments', 'rzt_header_cart_content');
}
//---
function rzt_remove_item_href( $cart_item_key ) {
$ny_cart_item_key = explode( '?remove_item=', $cart_item_key );
$ny_rest = explode( '&_wpnonce', $ny_cart_item_key[1] );
if ( $ny_rest[0] ) {
return $ny_rest[0];
} else {
return $cart_item_key;
}
}
add_filter( 'woocommerce_get_remove_url', 'rzt_remove_item_href');
//---
//---
function rzt_run_ajax_to_remove_item() {
if( $_REQUEST["ny_cart_item_key"] ) {
$ny_cart_item_key = sanitize_text_field( $_REQUEST["ny_cart_item_key"] );
$cart_item_key = explode( 'http://', $ny_cart_item_key );
$cart_item_key = $cart_item_key[1];
echo "ny found cart item key ".$cart_item_key;
if ( $cart_item = WC()->cart->get_cart_item( $cart_item_key ) ) {
WC()->cart->remove_cart_item( $cart_item_key );
$product = wc_get_product( $cart_item['product_id'] );
$item_removed_title = apply_filters( 'woocommerce_cart_item_removed_title', $product ? $product->get_title() : __( 'Item', 'woocommerce' ), $cart_item );
// no undo for out of stock
if ( $product->is_in_stock() && $product->has_enough_stock( $cart_item['quantity'] ) ) {
$removed_notice = sprintf( __( '%s removed.', 'woocommerce' ), $item_removed_title );
$removed_notice .= ' <a href="' . esc_url( WC()->cart->get_undo_url( $cart_item_key ) ) . '">' . __( 'Undo?', 'woocommerce' ) . '</a>';
} else {
$removed_notice = sprintf( __( '%s removed.', 'woocommerce' ), $item_removed_title );
}
wc_add_notice( $removed_notice );
}
}
wp_die();
}
add_action( 'wp_ajax_rzt_ajax_to_remove_item', 'rzt_run_ajax_to_remove_item' );
add_action( 'wp_ajax_nopriv_rzt_ajax_to_remove_item', 'rzt_run_ajax_to_remove_item' );
//---
function rzt_add_to_cart_function() {
global $woocommerce;
$product_id = intval($_POST['product_id']);
$variation_id = intval($_POST['variation_id']);
$quantity = intval($_POST['quantity']);
$quantity = $quantity ? $quantity : 1;
if($variation_id){
$attribute_values = wc_get_product_variation_attributes($variation_id);
$cart_success = $woocommerce->cart->add_to_cart( $product_id, $quantity, $variation_id, $attribute_values );
}
elseif($variation_id === 0){
$cart_success = $woocommerce->cart->add_to_cart( $product_id, $quantity );
}
if($cart_success){
$cart_item_key = $cart_success;
$cart_data = $woocommerce->cart->get_cart();
$cart_item_data = $cart_data[$cart_item_key];
$item_cart_qty = $cart_item_data['quantity'];
if($variation_id) {
$product = new WC_product_variation($variation_id);
$attributes = wc_get_formatted_variation($product);
}
else {
$product = new WC_product($product_id);
}
$product_title = $product->get_title();
$product_price = $product->get_price();
$product_image = $product->get_image('shop_thumbnail');
$is_sold_single = $product->is_sold_individually();
$product_total = $product_price * $item_cart_qty;
$html = htmlentities( json_encode(array('key' => $cart_item_key, 'pname' => $product_title)) );
$html .= '<br>'.$product_price.'<br>';
$html .= $item_cart_qty;
$html .= '<br>'.$product_total;
$message = '"'.$product_title.'" added to cart.';
$message = apply_filters( 'wc_add_to_cart_message', $message, $product_id );
wc_add_notice( $message );
//wp_send_json( array('pname' => $product_title , 'cp_html' => "$html" ) );
} else {
if(wc_notice_count('error') > 0){
echo wc_print_notices();
}
}
die();
}
add_action( 'wp_ajax_rzt_add_to_cart_action', 'rzt_add_to_cart_function' );
add_action( 'wp_ajax_nopriv_rzt_add_to_cart_action', 'rzt_add_to_cart_function' );
//---
//---
function rzt_hide_show_shopping_cart() {
if ( defined('RZT_MOBILE_CHECK') && RZT_MOBILE_CHECK === true ) {
echo '<script>
//jQuery("#rzt-cart").css({display:"block"}).stop().animate({opacity:1});
jQuery( "ul.cart_list > li.mini_cart_item:not(:last-child)" ).hide();
</script>';
}
global $woocommerce;
if( $woocommerce->cart->cart_contents_count > 0 ) {
echo '<script>
jQuery(".upTopNav .upShopping, #rzt-cart-top-icon").show();
</script>';
}
}
add_action( 'woocommerce_after_mini_cart', 'rzt_hide_show_shopping_cart');
//---
function rzt_continue_shopping_cart($message, $product_id) {
$message = str_replace( '<a href="https://uppababy.com/cart/" class="button wc-forward">View Cart</a>', '', $message );
return $message;
}
add_filter( 'wc_add_to_cart_message', 'rzt_continue_shopping_cart', 10, 2 );
//---
function rzt_shipping_method_label( $label, $method ) {
if ( is_checkout() ) {
$label = str_replace($method->get_label(), '', $label);
$label = str_replace(':', '', $label);
} else {
$label = str_replace($method->get_label(), '', $label);
}
return $label;
}
add_filter('woocommerce_cart_shipping_method_full_label', 'rzt_shipping_method_label', 30, 2);
//---
//---
function rzt_remove_checkout_fields( $fields ) {
unset($fields['billing']['billing_company']);
unset($fields['shipping']['shipping_company']);
if ( defined('RZT_MOBILE_CHECK') && RZT_MOBILE_CHECK === true ) {
unset($fields['order']['order_comments']);
}
$fields['shipping']['shipping_phone'] = array(
'label' => __('Phone', 'woocommerce'),
'placeholder' => _x('Phone', 'placeholder', 'woocommerce'),
'required' => false,
'class' => array('form-row-wide'),
'clear' => true
);
return $fields;
}
add_filter( 'woocommerce_checkout_fields' , 'rzt_remove_checkout_fields' );
//---
function rzt_checkout_field_admin_display( $order ){
echo '<p><strong>'.__('Shipping Phone', 'uppababy').':</strong> ' . get_post_meta( $order->id, '_shipping_phone', true ) . '</p>';
}
add_action( 'woocommerce_admin_order_data_after_shipping_address', 'rzt_checkout_field_admin_display', 10, 1 );
//---
//---
function rzt_get_product_id_by_slug( $product_slug ) {
global $wpdb;
$ny_query = $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type= 'product' AND post_status = 'publish'", $product_slug );
$product_id = $wpdb->get_var( $ny_query );
return (int) $product_id;
}
//---
//---
function rzt_new_footer_menu() {
?>
<div class="udClear rzt_new_footer_menu" style="clear: both;">
<p> </p>
<ul class="udClear rzt-footer-menu">
<li><a href="https://uppababy.com/ordering-info-and-policy/" target="_blank">Ordering info</a></li>
<li><a href=" https://uppababy.com/privacy/" target="_blank">Privacy</a></li>
<li><a href="https://uppababy.com/terms/" target="_blank">Policies</a></li>
<li><a href="https://uppababy.com/safety-security/" target="_blank">Safety and Security</a></li>
<li><a href=" https://kibocommerce.com" target="_blank">Who is Kibo?</a></li>
</ul>
<div class="udClear"></div>
</div>
<?php
}
//---
//---
function rzt_cart_thumbnail( $product_get_image, $cart_item, $cart_item_key ) {
$ny_hero_thumbnail_id = get_post_meta( $cart_item['variation_id'], 'ny_hero_thumbnail_id', true );
if ( $ny_hero_thumbnail_id ) {
$ny_hero_thumbnail = wp_get_attachment_image_src( $ny_hero_thumbnail_id )[0];
$product_get_image = '<img src="'.$ny_hero_thumbnail.'" class="attachment-shop_thumbnail size-shop_thumbnail wp-post-image" alt="" />';
return $product_get_image;
}
$ny_product = wc_get_product( $cart_item['product_id'] );
$ny_attachment_ids = $ny_product->get_gallery_attachment_ids();
if ( count($ny_attachment_ids) > 0 ) {
$ny_classes = array( "class" => "attachment-shop_thumbnail size-shop_thumbnail wp-post-image" );
// wp_get_attachment_image( $ny_attachment_ids[0], array('187', '172'), "", $ny_classes );
$product_get_image = wp_get_attachment_image( $ny_attachment_ids[0], "", "", $ny_classes );
}
return $product_get_image;
}
add_filter( 'woocommerce_cart_item_thumbnail', 'rzt_cart_thumbnail', 10, 3 );
//---
//---
function rzt_force_add_to_cart_twice( $cart_item_data, $product_id ) {
$unique_cart_item_key = md5( microtime().rand()."rzt_cart" );
$cart_item_data['unique_key'] = $unique_cart_item_key;
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data','rzt_force_add_to_cart_twice', 10, 2 );
//---
function rzt_add_to_cart_text_for_out_of_stock( $ny_add_to_cart_text, $ny_product ) {
if( ! $ny_product->is_in_stock() ) {
$ny_add_to_cart_text = 'Out of Stock';
}
return $ny_add_to_cart_text;
}
add_filter( 'woocommerce_product_add_to_cart_text','rzt_add_to_cart_text_for_out_of_stock', 10, 2 );
//---
//---
if ( ! function_exists( 'rzt_get_product_colors' ) ) {
function rzt_get_product_colors( $ny_attribute ) {
switch ( $ny_attribute ) {
case 'ALX': return '#dc885a'; break;
case 'ani': return '#F6892D'; break;
case 'ani-orange': return '#F6892D'; break;
case 'austin': return '#1A452E'; break;
case 'BSL': return '#327974'; break;
case 'carbon': return '#636466'; break;
case 'CLN': return '#818f84'; break;
case 'COL': return '#5a6a82'; break;
case 'dennison': return '#5F2A3A'; break;
case 'denny': return '#D93440'; break;
case 'denny-red': return '#D93440'; break;
case 'DRW': return '#dd733f'; break;
case 'ella': return '#008C7A'; break;
case 'ella-jade': return '#008C7A'; break;
case 'BLK': return '#231F20'; break;
case 'SDL': return '#774d2f'; break;
case 'Jordan': return '#696c73'; break;
case 'JOR': return '#696c73'; break;
case 'espresso': return '#473d3b'; break;
case 'grey': return '#989896'; break;
case 'georgie': return '#00B4ED'; break;
case 'georgie-marine-blue': return '#00B4ED'; break;
case 'gregory': return '#7D97A4'; break;
case 'henry': return '#7399B1'; break;
case 'henry-bluemarl': return '#7399B1'; break;
case 'henry-coming-soon': return '#7399B1'; break;
case 'henry-bluemarel': return '#7399B1'; break;
case 'imagination-red': return '#D93440'; break;
case 'jake': return '#231F20'; break;
case 'black': return '#231F20'; break;
case 'jade-black': return '#231F20'; break;
case 'jake-black': return '#231F20'; break;
case 'KYL': return '#cac745'; break;
case 'loic': return '#EEEDE8'; break;
case 'lindsey': return '#DDD2BA'; break;
case 'maeve': return '#b7a9c2'; break;
case 'makena': return '#982c6a'; break;
case 'MAY': return '#ddc772'; break;
case 'maya': return '#F2CD14'; break;
case 'MCA': return '#C9CACC'; break;
case 'MYL': return '#80abcb'; break;
case 'OLV': return '#c23883'; break;
case 'pascal': return '#C6CBCC'; break;
case 'pascal-grey': return '#C6CBCC'; break;
case 'uppahaus-raspberry-purple': return '#ba5284'; break;
case 'sabrina': return '#D6A5C2'; break;
case 'saddle': return '#4c3328'; break;
case 'samantha': return '#B04891'; break;
case 'sebby': return '#3388a4'; break;
case 'SDY': return '#f6d145'; break;
case 'silver': return '#C9CACC'; break;
case 'taylor': return '#003F70'; break;
case 'taylor-indigo': return '#003F70'; break;
case 'TYL': return '#b6cad5'; break;
case 'white': return '#f1eee7'; break;
default: return '';
}
}
}
//---
if ( ! function_exists( 'rzt_color_box_for_rebuild' ) ) {
function rzt_color_box_for_rebuild( $product ) {
// to generate color boxes using the attribute names
if ( ! $product->get_type() == 'variable' ) {
return;
}
// for variations
$ny_hide_or_show_js_object = "";
$available_variations = $product->get_available_variations();
foreach ( $available_variations as $available_variation ) {
$ny_variation_object = new WC_Product_variation( $available_variation['variation_id'] );
$ny_variation_stock = absint( $ny_variation_object->get_stock_quantity() );
print_r($available_variation);
$ny_variation_color = $available_variation['attributes']['attribute_pa_uppababy-color'];
$ny_hide_or_show_js_object .= 'ny_hide_or_show_per_variation["'.$ny_variation_color.'"] = '.$ny_variation_stock.';';
}
echo '<script>
var ny_hide_or_show_per_variation = {};'
.$ny_hide_or_show_js_object.'
</script>';
// for attributes
$attributes = $product->get_variation_attributes();
//$selected_attributes = $product->get_default_attributes();
$attribute_keys = array_keys( $attributes );
echo '<div id="rzt-color-boxes" class="product-colors"> <!-- variations color icons -->';
echo '<ul class="color-select-radio-wrap">';
foreach ( $attributes as $attribute_name => $options ) {
foreach ( $options as $sub_attribute_name => $sub_option ) {
$ny_product_color_code = rzt_get_product_colors( $sub_option );
$ny_id = 'color-'.$sub_option;
?>
<li
class="rzt-color-box <?php echo $sub_option; ?>"
id="<?php echo $ny_id; ?>"
onclick="rzt_set_selected_color('<?php echo $sub_option."','".$ny_product_color_code."','#".$ny_id; ?>');">
</li>
<?php
}
}
echo '</ul>';
echo '</div> <!-- // variations color icons -->';
?>
<script>
function rzt_set_selected_color(ny_attribute_key,ny_color_code,ny_id) {
jQuery(".summary p.price.product-price").hide();
jQuery('#pa_uppababy-color').val(ny_attribute_key.trim());
//jQuery('#pa_uppababy-color').trigger('change');
jQuery('#pa_uppababy-color').change();
jQuery('form.variations_form').trigger('reload_product_variations');
//jQuery('#pa_uppababy-color').trigger('chosen:updated');
jQuery('#rzt-color-boxes input+label').css('box-shadow', '');
jQuery(ny_id+'+label').css('box-shadow', '0 0 0 1px '+ny_color_code);
if( ny_hide_or_show_per_variation[ny_attribute_key] == 1 ) {
jQuery('.retailer-btn,#lcly-button-0').addClass('full');
jQuery('.single_add_to_cart_button').hide();
} else {
jQuery('.retailer-btn,#lcly-button-0').removeClass('full');
jQuery('.single_add_to_cart_button').show();
}
}
</script>
<?php
}
}
//---
//---
//---
/**/
?><file_sep>/wp-content/themes/uppababy/functions/functions-comments.php
<?php
/* ========================================================================= */
/* !WORDPRESS COMMENTS HTML FUNCTION */
/* ========================================================================= */
function jhfn_comment($comment, $args, $depth) {
$GLOBALS['comment'] = $comment;
//print_r($comment);
/* Check if post is by Author for special styling */
$isByAuthor = false;
if($comment->comment_author_email == get_the_author_meta('email')) {
$isByAuthor = true;
}
?>
<li>
<h4><span><?php echo $comment->comment_author; ?></span> wrote:</h4>
<?php comment_text(); ?>
<p class="commentDate">
Written on <?php printf(__('%1$s at %2$s'), get_comment_date('n/j/Y'), get_comment_time('g:ia')); ?> <?php edit_comment_link(__('Edit'),' ','') ?>
</p>
</li>
<?php }<file_sep>/wp-content/themes/uppababy/404.php
<?php
get_header(); ?>
<a href="/"><img src="/ui/images/404.jpg" style="text-align:center; padding-bottom:100px;" /></a>
<p style="text-align:center; padding-bottom:100px;"> To contact us with website issues or feedback, please <a href="/support/">click here</a> </p>
<?php get_footer(); ?>
<file_sep>/wp-content/themes/uppababy/woocommerce/content-single-accessory.php
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
global $post, $product;
$ny_product_id = get_the_ID();
/**
* hook : woocommerce_before_single_product
* @hooked wc_print_notices #10
*/
// do_action( 'woocommerce_before_single_product' );
if ( post_password_required() ) {
echo get_the_password_form();
return;
}
$ny_classes = get_post_class( array('rzt-accessory-shortcode') );
echo '<div itemscope itemtype="'.woocommerce_get_product_schema().'" id="product-'.get_the_ID().'" class = "'.implode(" ", $ny_classes).'">';
echo '<div class = "accContain">';
$ny_old_id = rzt_get_page_id_from_product_id( $ny_product_id );
$ny_accessory_title = get_the_title( $ny_old_id );
$ny_page = get_post( $ny_old_id );
/*if ( strpos $ny_accessory_title != 'protected' && $ny_accessory_title != 'private') {*/
// if ( !post_password_required() )
$ny_accessory_content = apply_filters( 'the_content', $ny_page->post_content );
/*}*/
if( is_page(13768) ){ // /travelsafe/
echo '
<style type="text/css">
.single-product {
background-image: url('.$src[0] .');
background-repeat:no-repeat;
background-position:right top;
}
</style>';
echo '<div class="accCopy">'.$ny_accessory_content.'</div>';
} else {
echo '<div class="accCopy">';
echo '<h1 class="agendabold" style="width:482px; margin-bottom:">';
echo $ny_accessory_title;
$product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );
if(get_field('accessory_for_text', $product_id)) {
echo '<span class="agendalight" style="font-weight:normal; font-family:Agenda Light; font-size:15px;"><br />',the_field('accessory_for_text', $product_id),'</span>';
} else {
// echo '<span class="agendamedium" style="font-size:24px;"><br />This Item is Missing Compatibility Text! content-single-accessory.php</span>';
}
// if(get_field('acc_for_text', $ny_old_id)) {
// $myStrollers = get_field('acc_for_text', $ny_old_id);
// echo '<span class="agendalight" style="font-weight:normal; font-family:Agenda Light; font-size:15px;"><br /> '.__("for", "uppababy").' '.$myStrollers;
// } else {
// $myStrollers = get_field('acc_for', $ny_old_id);
//
//
// $xy = '';
//
// if ( $myStrollers ) {
//
// foreach ($myStrollers as $s) {
//
// $s=strtolower($s);
//
// if($s != 'g-series') {
//
// $xy.= $s;
// $xy.= ', ';
// }
// }
// }
//
// $xy = strtoupper($xy);
//
// $xy = substr($xy, 0, -2);
//
// $accessory_for_what = str_lreplace2(", ", ' '.__("and", "uppababy").' ', $xy);
//
//
// echo '<span class="agendalight" style="font-weight:normal; font-family:Agenda Light; font-size:15px;"><br /> '.__("for", "uppababy").' '.$accessory_for_what;
// }
// if( is_page( array( 2569, 2907, 2948 ) )) {
//
// echo get_field('productYear', $ny_old_id);
// }
// echo '</span>';
if( get_field('text_under_model', $ny_old_id) == 1){
echo '<br />
<span class="agendalight" style="font-weight:normal; font-family:Agenda Light; font-size:15px; display:block; margin-top:-9px">';
echo get_field('text_under_model_txt', $ny_old_id);
echo '</span>';
}
echo '</h1> <!-- // page title -->';
if( get_field('dis', $ny_old_id) == 1) {
echo '<br /><span style="color:red;font-size:16px;">*Discontinued</span>';
}
if( get_field('old_acc', $ny_old_id) == 1){
//echo '<div style="overflow:hidden; padding-bottom:8px; height:50px; margin-top:-15px;">
//<a class="link agendabold" href="'.get_field('old_acc_link', $ny_old_id).'">';
//echo get_field('old_acc_text', $ny_old_id);
//echo '</a></div>';
}
/*
if( get_field('hideADD', $ny_old_id) == 1){
<style>.cartADD {display:none;}</style>
<script>
jQuery(function () {
document.getElementById("findRET").className = "yellowBUY2";
});
</script>
}
*/
echo $ny_accessory_content.'<br /><br />';
echo '<div class="udClear"></div>';
/*disable infant car seat base
if (is_page(4896548)){
}else{
<form
*/
/**
* hook : woocommerce_before_single_product_summary
*/
// do_action( 'woocommerce_before_single_product_summary' );
//---
// Single Product Sale Flash function woocommerce_show_product_sale_flash #10
// sale-flash.php
if ( $product->is_on_sale() ) {
echo apply_filters(
'woocommerce_sale_flash',
'<span class="onsale rzt_sale_promo_image">' . __( 'ON SALE TODAY', 'uppababy' ) . '</span>',
$post,
$product
);
}
//---
echo '<div class="summary entry-summary" style="float:none; width:355px; padding-top:0px;">';
/**
* hook : woocommerce_single_product_summary
*/
//do_action( 'woocommerce_single_product_summary' );
//---
// Single Product title function woocommerce_template_single_title 5
// title.php
//the_title( '<h1 itemprop="name" class="product_title entry-title">', '</h1>' );
//---
// Single Product Price, including microdata for SEO function woocommerce_template_single_price 10
// price.php
echo '<div itemprop="offers" itemscope itemtype="http://schema.org/Offer">';
echo '<p class="price agendabold">'.$product->get_price_html().'</p>';
echo '<meta itemprop="price" content="'.esc_attr( $product->get_display_price() ).'" />';
echo '<meta itemprop="priceCurrency" content="'.esc_attr( get_woocommerce_currency() ).'" />';
echo '<link itemprop="availability" href="http://schema.org/'.$product->is_in_stock() ? " " : "OutOfStock".'" />';
//---
// Add to cart function woocommerce_template_single_add_to_cart 30
// do_action( 'woocommerce_' . $product->product_type . '_add_to_cart' );
if ( $product->is_purchasable() ) {
if ( $product->product_type == 'simple') {
// Simple product add to cart
// add-to-cart/simple.php
// Availability
$availability = $product->get_availability();
$availability_html = empty( $availability['availability'] ) ? '' : '<p class="stock ' . esc_attr( $availability['class'] ) . '">' . esc_html( $availability['availability'] ) . '</p>';
echo apply_filters( 'woocommerce_stock_html', $availability_html, $availability['availability'], $product );
if ( $product->is_in_stock() ) {
do_action( 'woocommerce_before_add_to_cart_form' );
echo '<form class="cart" method="post" enctype="multipart/form-data">';
do_action( 'woocommerce_before_add_to_cart_button' );
if ( ! $product->is_sold_individually() ) {
woocommerce_quantity_input( array(
'min_value' => apply_filters( 'woocommerce_quantity_input_min', 1, $product ),
'max_value' => apply_filters( 'woocommerce_quantity_input_max', $product->backorders_allowed() ? '' : $product->get_stock_quantity(), $product ),
'input_value' => ( isset( $_POST['quantity'] ) ? wc_stock_amount( $_POST['quantity'] ) : 1 )
) );
}
echo '<input type="hidden" name="add-to-cart" value="'.esc_attr( $product->id ).'" />';
echo '<button type="submit" class="single_add_to_cart_button button alt">'.esc_html( $product->single_add_to_cart_text() ).'</button>';
echo '<div id="lcly-button-0">
<a id="lcly-link-0" href="http://www.locally.com" target="_blank"></a>
</div>';
echo '<script id="lcly-script-0" src="https://uppababy.locally.com/stores/map.js?company_id=24146&style='.ltrim( $product->get_sku()).'&show_location_switcher=0&show_dealers=0&show_unauthed_dealers=1&no_link=1&button_id=HTML&company_name=UPPAbaby&button_text=FIND+IT+LOCALLY&css=2" async>
</script>';
do_action( 'woocommerce_after_add_to_cart_button' );
echo '</form>';
/*echo '<div style="position:absolute; right:150px;top:265px;"><a href="/warranty/"><img style="width:135px;height:135px;" src="http://uppababy.com/wp-content/uploads/2016/01/ubExtend.png"></a></div>';
*/
do_action( 'woocommerce_after_add_to_cart_form' );
} else {
echo '<form class="cart">';
echo '<button type="submit" class="single_add_to_cart_button button alt disabled out-of-stock">Out of Stock</button>';
echo '</form>';
}
} else {
// Variable product add to cart
// function woocommerce_variable_add_to_cart() + add-to-cart/variable.php
// Enqueue variation scripts
wp_enqueue_script( 'wc-add-to-cart-variation' );
// Get Available variations?
$get_variations = sizeof( $product->get_children() ) <= apply_filters( 'woocommerce_ajax_variation_threshold', 30, $product );
// Load the template
//wc_get_template( 'rzt-single-variable.php', array(
$available_variations = $get_variations ? $product->get_available_variations() : false;
$attributes = $product->get_variation_attributes();
$selected_attributes = $product->get_variation_default_attributes();
$attribute_keys = array_keys( $attributes );
do_action( 'woocommerce_before_add_to_cart_form' );
echo '<form class="variations_form cart" method="post" enctype="multipart/form-data" data-product_id="'.absint( $product->id ).'" data-product_variations="'.htmlspecialchars( json_encode( $available_variations )) .'">';
do_action( 'woocommerce_before_variations_form' );
if ( empty( $available_variations ) && false !== $available_variations ) {
echo '<p class="stock out-of-stock">'.__( "This product is currently out of stock and unavailable.", "woocommerce" ).'</p>';
} else {
echo '<table class="variations" cellspacing="0">
<tbody>';
foreach ( $attributes as $attribute_name => $options ) {
echo '<tr>
<!--
<td class="label"><label for="'.sanitize_title( $attribute_name ).'">'.wc_attribute_label( $attribute_name ).'</label></td>
-->
<td class="value">';
$selected = isset( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) ?
wc_clean( urldecode( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] )) :
$product->get_variation_default_attribute( $attribute_name );
wc_dropdown_variation_attribute_options( array(
'options' => $options,
'attribute' => $attribute_name,
'product' => $product,
'selected' => $selected,
'show_option_none' => __('Please choose a color', 'uppababy'),
)
);
/*echo end( $attribute_keys ) === $attribute_name ?
apply_filters( 'woocommerce_reset_variations_link', '<a class="reset_variations" href="#" title="reset"> X </a>' ) :
'';*/
echo '</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
do_action( 'woocommerce_before_add_to_cart_button' );
if ( ! $product->is_in_stock() ) {
echo '<button type="submit" class="single_add_to_cart_button button alt disabled out-of-stock">Out of Stock</button>';
} else {
echo '<div class="single_variation_wrap">';
/*
Hook : woocommerce_before_single_variation
*/
do_action( 'woocommerce_before_single_variation' );
/*
Hook : woocommerce_single_variation .
to output the cart button and placeholder for variation data.
@hooked function : woocommerce_single_variation #10 (Empty div for variation data).
@hooked function : woocommerce_single_variation_add_to_cart_button #20 (Qty and cart button).
*/
//do_action( 'woocommerce_single_variation' );
echo '<div class="woocommerce-variation single_variation" style="position: absolute; top: -15px; right: 25px; text-align: center;"></div>';
echo '<div class="woocommerce-variation-add-to-cart variations_button">';
if ( ! $product->is_sold_individually() ) {
woocommerce_quantity_input( array( 'input_value' => isset( $_POST['quantity'] ) ? wc_stock_amount( $_POST['quantity'] ) : 1 ) );
}
echo '<button type="submit" class="single_add_to_cart_button button alt">'.esc_html( $product->single_add_to_cart_text() ).'</button>';
echo '<input type="hidden" name="add-to-cart" value="'.absint( $product->id ).'" />';
echo '<input type="hidden" name="product_id" value="'.absint( $product->id ).'" />';
echo '<input type="hidden" name="variation_id" class="variation_id" value="0" />';
if( is_page(1162)) {
} else {
echo '<div id="lcly-button-0">
<a id="lcly-link-0" href="http://www.locally.com" target="_blank"></a>
</div>';
echo '<script id="lcly-script-0" src="https://uppababy.locally.com/stores/map.js?company_id=24146&style='.ltrim( $product->get_sku()).'&show_location_switcher=0&show_dealers=0&show_unauthed_dealers=1&no_link=1&button_id=HTML&company_name=UPPAbaby&button_text=FIND+IT+LOCALLY&css=2" async>
</script>';
}
echo '</div>';
/*
Hook : woocommerce_after_single_variation
*/
do_action( 'woocommerce_after_single_variation' );
echo '</div>';
}
do_action( 'woocommerce_after_add_to_cart_button' );
}
do_action( 'woocommerce_after_variations_form' );
echo '</form>';
do_action( 'woocommerce_after_add_to_cart_form' );
} // End of variable product add to cart
}
/* OUT OF STOCK FIELD */
if( get_field('outOfStock', $ny_old_id) == 1) {
//echo '<span style="color:red;font-size:16px;font-weight:bold;">*Out Of Stock</span>';
}
echo '</div>';
//---
//--- variations color icons and variations descriptions
// function to generate border color using the attribute name
if ( $product->product_type == 'variable' ) {
echo '<div id="rzt-variations-icons"> <!-- variations color icons -->';
echo '<ul>';
$imgSlot = 1;
foreach ( $available_variations as $available_variation ) {
$ny_full_size_image = wp_get_attachment_image_src( get_post_thumbnail_id( $available_variation['variation_id'] ), 'full' );
$ny_swatch = get_field('color_images'.$imgSlot, $ny_old_id);
$ny_lightbox_thumbnail_id = get_post_meta( $available_variation['variation_id'], 'ny_lightbox_thumbnail_id', true );
if ( $ny_lightbox_thumbnail_id ) {
$ny_swatch = wp_get_attachment_image_src( $ny_lightbox_thumbnail_id )[0];
}
echo '<li class="rzt-variation-icon">';
echo '<a href="'.$ny_full_size_image[0].'" class="thickbox">';
echo '<img src="'.$ny_swatch.'" class="rzt-color" rel="about-us" alt="'.$available_variation['variation_description'].'" data-zoom-image="'.$ny_full_size_image[0].'" />';
echo '</a>';
echo '</li>';
$imgSlot++;
}
echo '</ul>';
echo '</div> <!-- // variations color icons -->';
}
//--- // variations color icons and descriptions
//---
//--- download manual
$download_manuel_link = rzt_get_field_with_conditional( 'download_manuel_link', $ny_product_id );
$config_chart = rzt_get_field_with_conditional( 'config_chart', $ny_product_id );
$ny_old_model_url = get_field( 'old_model_url', $ny_product_id );
echo '<div class="BUYlinks2" style="position: initial !important;"> <!-- assets -->';
if ( $download_manuel_link ) {
echo '<div class="BUYlinkBOX2">';
echo '<a href="'.$download_manuel_link.'" class="BUYlink BUYmanual">'.__("Download manual", "uppababy").'</a>';
echo '</div>';
}
if ( $config_chart ){
echo '<div class="BUYlinkBOX2">';
echo '<a href="'.$config_chart.' class="BUYlink BUYbrochure thickbox">'.__("Configuration Chart", "uppababy").'</a>';
echo '</div>';
}
if ( $ny_old_model_url ) {
echo '<div class="BUYlinkBOX2">
<a class="BUYlink BUY-older-versions" href="'.$ny_old_model_url.'">Older Models</a>
</div>';
}
echo '</div> <!-- //assets -->';
echo '</div> <!-- .summary -->';
//---
//--- // download manual
/* end disable infant car seat base */
echo '</div> <!-- // .accCopy -->';
} // if( 13768 ) /travelsafe
//---
//---
//---
echo '<div class = "rzt-accessory-image-second-div">';
//---
// Single Product Image function woocommerce_show_product_images #20
// product-image.php
// if not product page (ex : travelsafe), just add the background image from get_field('')
echo '<div class="images_">';
if ( has_post_thumbnail() ) {
the_post_thumbnail('full');
// $attachment_count = count( $product->get_gallery_attachment_ids() );
// $gallery = $attachment_count > 0 ? '[product-gallery]' : '';
//
// $props = wc_get_product_attachment_props( get_post_thumbnail_id(), $post );
//
// $image = get_the_post_thumbnail(
// $post->ID,
// apply_filters( 'single_product_large_thumbnail_size', 'shop_single' ),
// array(
// 'title' => $props['title'],
// 'alt' => $props['alt'],
// 'class' => "rzt-zoom",
// )
// );
//
// $ny_image_zoom = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
//
// echo apply_filters(
// 'woocommerce_single_product_image_html',
// sprintf(
// '<a href="%s" itemprop="image" class="woocommerce-main-image zoom" title="%s" data-rel="prettyPhoto%s" data-zoom-image="%s">%s</a>',
// esc_url( $props['url'] ),
// esc_attr( $props['caption'] ),
// $gallery,
// $ny_image_zoom[0],
// $image
// ),
// $post->ID
// );
} else {
echo apply_filters(
'woocommerce_single_product_image_html',
sprintf( '<img src="%s" alt="%s" />', wc_placeholder_img_src(), __( 'Placeholder', 'woocommerce' ) ),
$post->ID
);
}
do_action( 'woocommerce_product_thumbnails' );
echo '</div>';
//---
//---acc_2nd_img
if ( is_page(651981651) ) {
echo do_shortcode( '[rzt-image-with-text]');
} else {
$acc_2nd_img = rzt_get_field_with_conditional( 'acc_2nd_img', $ny_product_id );
if ( $acc_2nd_img ) {
echo '<div class="rzt-accPIC2">';
echo '<img src="'.$acc_2nd_img.'" />';
echo '</div>';
}
}
//--- //acc_2nd_img
echo '</div> <!-- // .rzt-accessory-image-second-div -->';
//---
echo '<div class="udClear"></div>';
echo '</div> <!-- // .accContain -->';
//---
//---bottom_image_1 - 3
if(is_page(2359)){
echo '</div>';
echo '<div style="overflow:hidden;padding-left:20px;margin-bottom:40px">';
}
$bottom_image_1 = rzt_get_field_with_conditional( 'bottom_image_1', $ny_product_id );
$image_description1 = rzt_get_field_with_conditional( 'image_description1', $ny_product_id );
$bottom_image_2 = rzt_get_field_with_conditional( 'bottom_image_2', $ny_product_id );
$image_description2 = rzt_get_field_with_conditional( 'image_description2', $ny_product_id );
$bottom_image_3 = rzt_get_field_with_conditional( 'bottom_image_3', $ny_product_id );
$image_description3 = rzt_get_field_with_conditional( 'image_description3', $ny_product_id );
if ( $bottom_image_2 || $bottom_image_3 || is_page(1032) ) {
echo '<table cellpadding="0" cellspacing="0" style="margin-top:15px;">';
echo '<tr valign="top">';
echo '<td '.((is_page(1032))? 'width="300"' : "").'>';
if ( $bottom_image_1 ) {
echo '<img src="'.$bottom_image_1.'" class="hero-image hero1" style="margin-right:30px; margin-bottom:6px" alt="'.bloginfo( 'name' ).'" />';
}
echo '</td>';
echo '<td>';
if ( $bottom_image_2 ){
echo '<img src="'.$bottom_image_2.'" class="hero-image hero2" style="margin-right:30px; margin-bottom:6px" />';
}
echo '</td>';
echo '<td>';
if ( $bottom_image_3 ){
echo '<img src="'.$bottom_image_3.'" class="hero-image hero3" style="" />';
}
echo '</td>';
echo '</tr>';
echo '<tr>';
echo '<td>';
if ( $image_description1 ){
echo '<div align="left" style="font-size:13px; width:300px; margin-bottom:5px;">' .$image_description1.'</div>';
}
echo '</td>';
echo '<td>';
if ( $image_description2 ){
echo '<div align="left" style="font-size:13px; width:300px">' .$image_description2.'</div>';
}
echo '</td>';
echo '<td>';
echo '<div '
.((is_page( 1032 ))? "align='right' " : "align='left' ")
.((is_page( 1032 ))? "style='width:auto; margin-right:45px; font-size:13px'" : "style='font-size:13px; width:300px'").'>';
echo $image_description3;
echo '</div>';
echo '</td>';
echo '</tr>';
echo '</table>';
}
/**
* hook : woocommerce_after_single_product_summary
*/
//do_action( 'woocommerce_after_single_product_summary' );
// end div lavabe udclear misy background image na atao margin-left: -53px;
echo '</div> <!-- div lavabe udclear -->';
//---
// similar
// Single Product Up-Sells function woocommerce_upsell_display 15
// up-sells.php
global $woocommerce_loop;
if ( !$upsells = $product->get_upsells() ) {
echo '<div class="span-21 overview last" style="margin-left:-52px;">';
echo '<div class="prepend-1 udClear advice" style="padding-top:25px;padding-bottom:25px;/*padding-left:0px;*/">';
echo '<h2 style="font-size:13px; margin-bottom:9px">'.__( 'You may also be interested in', 'uppababy' ).'</h2>';
$posts = get_field('products_sim', $ny_old_id);
if( $posts ) {
echo '<ul class="udClear" style="margin-bottom:5px;">';
foreach( $posts as $post) {
setup_postdata($post);
echo '<li>';
echo '<a href="'.get_permalink().'" >';
echo '<div align="center">';
echo '<img src="'.get_field('hero_thumbnail').'" width="120" alt="'.get_the_title().'">';
echo '</div>';
echo '</a>';
echo '<div align="center" style="line-height:15px;">';
echo '<a href="'.get_permalink().'">'.get_the_title().'</a>';
echo '</div>';
echo '</li>';
}
echo '</ul>';
wp_reset_postdata();
}
echo '</div>';
echo '</div>';
} else {
$args = array(
'post_type' => 'product',
'ignore_sticky_posts' => 1,
'no_found_rows' => 1,
'posts_per_page' => 5,
'orderby' => 'rand',
'post__in' => $upsells,
'post__not_in' => array( $product->id ),
'meta_query' => WC()->query->get_meta_query()
);
$products = new WP_Query( $args );
$woocommerce_loop['name'] = 'up-sells';
$woocommerce_loop['columns'] = 5;
if ( $products->have_posts() ) {
echo '<div class="up-sells upsells products">';
echo '<h2>'.__( 'You may also be interested in', 'uppababy' ).'</h2>';
woocommerce_product_loop_start();
while ( $products->have_posts() ) {
$products->the_post();
wc_get_template_part( 'content', 'product' ); // Template for products in loops
}
woocommerce_product_loop_end();
echo '</div>';
}
wp_reset_postdata();
}
//---
echo '<meta itemprop="url" content="'.get_the_permalink().'" />';
do_action( 'woocommerce_after_single_product' );
//---
//---
<file_sep>/_wp-config.php
<?php
//define('WP_HOME','http://WWW.DOMAIN.COM');
//define('WP_SITEURL','http://WWW.DOMAIN.COM');
define('UPLOADS', 'assets'); // Define website URL assets folder
define('DISALLOW_FILE_EDIT', true);
/* Define FTP connection info */
/*
define('FTP_HOST', '');
define('FTP_USER', '');
define('FTP_PASS', '!');
define('FTP_METHOD', 'ftpext');
*/
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', '');
/** MySQL database username */
define('DB_USER', '');
/** MySQL database password */
define('DB_PASSWORD', '');
/** MySQL hostname */
define('DB_HOST', 'localhost');
/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');
/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');
/**#@+
* Authentication Unique Keys and Salts.
*
* Change these to different unique phrases!
* You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
* You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
*
* @since 2.6.0
*/
define('AUTH_KEY', <KEY>');
define('SECURE_AUTH_KEY', '<KEY>');
define('LOGGED_IN_KEY', <KEY>FC+W&b5t.-wbd#GDu}p_7Tr+iHz+ff');
define('NONCE_KEY', '<KEY>:2/4>o*+2=ioeN|Fj[tXW)-4oV');
define('AUTH_SALT', ',_rjxZ%0I+U:O.4~k+YK7BCAO)mNu8`1@f!>900x(+KB*_^R`RFJ6Im<2/2+-!=x');
define('SECURE_AUTH_SALT', 'rrkHd6X;5#kZi99_6g~/,`G-n&N|wdi~~Cnw(VeB![#]k#;+QZy!m;US-ks=8=%G');
define('LOGGED_IN_SALT', 'r<_Q+PY4u8u}Mp<Kom.udDG=JO(;t<W-@Bds#f<n*goCM:fs4Oq(3a_O: -se Ft');
define('NONCE_SALT', 'A?,Qp.ok/+SW {F~9Pfr(,p-dg-J++.dn(Rg3)w,m4r2++!&N]nd90>h!SgFJmV ');
/**#@-*/
/**
* WordPress Database Table prefix.
*
* You can have multiple installations in one database if you give each a unique
* prefix. Only numbers, letters, and underscores please!
*/
$table_prefix = 'wp_';
/**
* If possible, change this to a prefix similar to below
* $table_prefix = 'uppa_';
*/
/**
* WordPress Localized Language, defaults to English.
*
* Change this to localize WordPress. A corresponding MO file for the chosen
* language must be installed to wp-content/languages. For example, install
* de_DE.mo to wp-content/languages and set WPLANG to 'de_DE' to enable German
* language support.
*/
define('WPLANG', '');
/**
* For developers: WordPress debugging mode.
*
* Change this to true to enable the display of notices during development.
* It is strongly recommended that plugin and theme developers use WP_DEBUG
* in their development environments.
*/
if(isset($_GET['debug'])){
define('WP_DEBUG', true);
}else{
define('WP_DEBUG', false);
}
/* REVISION SETTINGS */
define('WP_POST_REVISIONS', 5);
define('WP_POST_REVISIONS', false );
define('AUTOSAVE_INTERVAL', 160 );
/* That's all, stop editing! Happy blogging. */
/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
<file_sep>/wp-content/themes/uppababy/template-registration.php
<?php
/*
Template Name: Registration
*/
get_header(); the_post(); ?>
<?php
$pageBannerImage = get_field('top_banner');
$global_rows = get_field('default_accessories_banner', 'options'); // get all the rows
$rand_global_row = $global_rows[ array_rand( $global_rows ) ]; // get a random row
$rand_global_row_image = $rand_global_row['accessories_banner' ]; // get the sub field value
if($pageBannerImage) { ?>
<section id="hero-banner" style="background-image:url('<?php echo $pageBannerImage['sizes']['hero-banner']; ?>'); background-size:cover; background-repeat:no-repeat;">
<?php } elseif($rand_global_row_image) { ?>
<section id="hero-banner" style="background-image:url('<?php echo $rand_global_row_image['sizes']['hero-banner']; ?>'); background-size:cover; background-repeat:no-repeat;">
<?php } ?>
</section>
<section id="contact">
<div class="wrap clearfix">
<div class="address-info">
<div class="contact-info">
<?php if(have_rows('address_box', 'option')) {
while(have_rows('address_box', 'option')) { the_row(); ?>
<h3><?php the_sub_field('address_header', 'option'); ?></h3>
<?php the_sub_field('address_text', 'option'); ?>
<?php } ?>
<?php } ?>
</div>
</div>
<div class="contact-box">
<!-- <div class="registration-box"> -->
<?php
$regPage = get_field('which_registration_page_is_this');
if($regPage == 'stroller') {
include 'include-registration-stroller.php';
}
if($regPage == 'carseat') {
include 'include-registration-carseat.php';
}
if($regPage == 'accessories') {
include 'include-registration-accessories.php';
}
?>
</div>
<?php if(get_field('sidebar_images')) { ?>
<div class="did-you-know rzt-registration-sidebar">
<?php
if( $regPage != 'carseat' && $regPage != 'stroller') {
while(have_rows('sidebar_images')) { the_row();?>
<div class="dyk-item">
<?php if(get_sub_field('sidebar_image')) {
$subIMG = get_sub_field('sidebar_image');?>
<img src="<?php echo $subIMG['sizes']['']; ?>" alt="<?php echo $subIMG['alt'];?>" />
<?php }
the_sub_field('sidebar_content');?>
</div>
<?php
}
} else if( $regPage == 'stroller') {
// taken from the current US site //
?>
<style>
.slidingDiv, .slidingDiv2, .slidingDiv3, .slidingDiv4 {
min-height:300px;
padding:20px;
margin-top:10px;
}
.show_hide a, .show_hide2 a, .show_hide3 a, .show_hide4 a {
background-image: url(/wp-content/themes/UPPAbaby/images/more-link.jpg);
background-repeat: no-repeat;
padding-left: 11px;
cursor: pointer;
}
h2{
text-transform: uppercase;
color: #2482B6;
font-size: 15px;
font-style: normal;
font-weight: 700;
}
.ui-accordion-header{
color: #79bde8;
font-family: 'agenda-bold', Arial, Helvetica, sans-serif;
font-size: 16px;
font-style: normal;
height: auto;
line-height: 20px;
border: none;
}
.ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default {
background-color: transparent;
background-image: none;
}
.ui-accordion, ui-accordion-content{
border: none;
}
.ui-accordion .ui-accordion-content {
border: 0;
}
.ui-accordion .ui-accordion-icons {
padding-left: 1.5em;
}
.ui-accordion .ui-accordion-content {
font-size: 14px;
}
.ui-accordion .ui-accordion-header .ui-icon {
position: relative;
left: -5px;
top: 0px;
margin-top: 0px;
float: left;
}
.ui-icon-triangle-1-s {
background-position: -64px -15px;
}
.ui-accordion .ui-accordion-icons {
padding-left: 0px;
}
#contact .did-you-know.rzt-registration-sidebar {
width: 350px;
background: #fff;
padding: 0px;
}
</style>
<script type="text/javascript">
jQuery(document).ready(function (){
jQuery( "#accordion" ).accordion({
collapsible: true,
heightStyle: "content",
active: false
});
<!-- jQuery('#accordion').accordion('activate', -1);-->
});
</script>
<div style="/*width:261px;float:left;margin-right:0px;margin-left:15px*/">
<h2 style="margin-bottom:10px; margin-top:10px;">Where To Find Your Serial Number</h2>
<div id="accordion" class="rzt-sidebar-accordion">
<?php
while( have_rows('sidebar_images') ) {
the_row();
if( get_sub_field('sidebar_title') ) {
echo '<h4>'.get_sub_field('sidebar_title').'</h4>';
}
echo '<div class="dyk-item">';
if( get_sub_field('sidebar_content') ) {
echo '<h4>'.get_sub_field('sidebar_content').'</h4>';
}
if( get_sub_field('sidebar_image') ) {
$subIMG = get_sub_field('sidebar_image');
echo '<img src="'.$subIMG['sizes']['medium_large'].'" alt="'.$subIMG['alt'].'" style="border: 0px; margin:20px 0px;" width="200" />';
}
echo '</div>';
}
?>
</div>
</div>
<?php
} else if( $regPage == 'carseat' ) {
?>
<style> /* styles taken from the current US site */
h2{
text-transform: uppercase;
color: #2482B6;
font-size: 15px;
font-style: normal;
font-weight: 700;
}
.ui-accordion-header{
color: #79bde8;
font-family: 'agenda-bold', Arial, Helvetica, sans-serif;
font-size: 16px;
font-style: normal;
height: auto;
line-height: 20px;
border: none;
}
.ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default {
background-color: transparent;
background-image: none;
}
.ui-accordion, .ui-accordion-content {
border: none;
}
.ui-accordion .ui-accordion-content {
border: 0;
}
.ui-accordion .ui-accordion-icons {
padding-left: 1.5em;
}
.ui-accordion .ui-accordion-content {
font-size: 14px;
}
.ui-accordion .ui-accordion-header .ui-icon {
position: relative;
left: -5px;
top: 0px;
margin-top: 0px;
float: left;
}
.ui-icon-triangle-1-s {
background-position: -6px 0px;
}
.ui-accordion .ui-accordion-icons {
padding-left: 0px;
}
#contact .did-you-know.rzt-registration-sidebar {
width: 350px;
background: #fff;
padding: 0px;
}
</style>
<div style="width:261px;float:left;margin-right:0px;margin-left:15px">
<h2 style="margin-bottom:10px">Where To Find Your Serial Number</h2>
<div id="accordion">
<?php
while(have_rows('sidebar_images')) {
the_row();
echo '<div class="dyk-item">';
if( get_sub_field('sidebar_content') ) {
echo '<h4>'.get_sub_field('sidebar_content').'</h4>';
}
if( get_sub_field('sidebar_image') ) {
$subIMG = get_sub_field('sidebar_image');
echo '<img src="'.$subIMG['sizes']['medium_large'].'" alt="'.$subIMG['alt'].'" style="border: 0px; margin:20px 0px;" width="200" />';
}
echo '</div>';
}
?>
</div>
</div>
<?php } ?>
</div>
<?php } ?>
</div>
</section>
<?php get_footer(); ?>
<file_sep>/wp-content/themes/uppababy/template-contact.php
<?php
/*
Template Name: Contact
*/
get_header('contact'); the_post(); ?>
<?php
$pageBannerImage = get_field('top_banner');
$global_rows = get_field('default_accessories_banner', 'options'); // get all the rows
$rand_global_row = $global_rows[ array_rand( $global_rows ) ]; // get a random row
$rand_global_row_image = $rand_global_row['accessories_banner' ]; // get the sub field value
if($pageBannerImage) { ?>
<section id="hero-banner" style="background-image:url('<?php echo $pageBannerImage['sizes']['hero-banner']; ?>'); background-size:cover; height:520px; width:1024px; background-repeat:no-repeat;">
<?php } elseif($rand_global_row_image) { ?>
<section id="hero-banner" style="background-image:url('<?php echo $rand_global_row_image['sizes']['hero-banner']; ?>'); background-size:cover; height:520px; width:1024px; background-repeat:no-repeat;">
<?php } ?>
</section>
<!-- TO MAKE CHAT WIDGET OPTIONS ACTIVE-->
<script type="text/javascript">
window.zESettings = {
webWidget: {
contactOptions: {
enabled: true,
contactButton: { '*': 'Contact Button' },
chatLabelOnline: { '*': 'Live Chat' },
chatLabelOffline: { '*': 'Chat is unavailable' },
contactFormLabel: { '*': 'Leave us a message' }
}
}
};
</script>
<section id="contact">
<div class="wrap clearfix">
<div class="address-info">
<div class="contact-info">
<?php if(have_rows('address_box', 'option')) {
while(have_rows('address_box', 'option')) { the_row(); ?>
<h3><?php the_sub_field('address_header', 'option'); ?></h3>
<?php the_sub_field('address_text', 'option'); ?>
<?php } ?>
<?php } ?>
</div>
</div>
<div class="contact-box">
<h2><?php the_field('contact_module_header'); ?></h2>
<?php the_field('module_introduction'); ?>
<?php if(have_rows('contact_module')) {
$counter = 1;
while(have_rows('contact_module')) { the_row(); ?>
<div class="zoo-box">
<div class="zoo-left">
<ul>
<li>
<?php if($counter == 1) { ?>
<a onclick="zE.activate();" class="contact-btn" style="cursor:pointer;">EMAIL</a>
<!-- <a href="https://support.uppababy.com/hc/requests/new" class="contact-btn" style="cursor:pointer;">EMAIL</a> -->
<?php } else { ?>
<a href="<?php the_sub_field('contact_button_url'); ?>" class="contact-btn"><?php the_sub_field('contact_button_text'); ?></a>
<?php } ?>
</li>
</ul>
</div>
<div class="zoo-right">
<?php the_sub_field('contact_information'); ?>
</div>
</div>
<?php $counter++; ?>
<?php } ?>
<?php } ?>
</div>
<div class="did-you-know">
<h5><?php the_field('section_header'); ?></h5>
<div class="dyk-item">
<div class="dyk-text">
<?php if(have_rows('section_items')) { ?>
<ul>
<?php while(have_rows('section_items')) { the_row(); ?>
<li>
<a href="<?php the_sub_field('item_link'); ?>" ><?php the_sub_field('item_name'); ?></a>
</li>
<?php } ?>
</ul>
<?php } ?>
</div>
</div>
</div>
</div>
</section>
<div id="TB_inline" style="display:none;">
<div class="typeform-widget" data-url="https://uppababy.typeform.com/to/K35Aq9" style="width: 100%; height: 500px;" > </div> <script> (function() { var qs,js,q,s,d=document, gi=d.getElementById, ce=d.createElement, gt=d.getElementsByTagName, id="typef_orm", b="https://embed.typeform.com/"; if(!gi.call(d,id)) { js=ce.call(d,"script"); js.id=id; js.src=b+"embed.js"; q=gt.call(d,"script")[0]; q.parentNode.insertBefore(js,q) } })() </script> <div style="font-family: 'agenda_new';font-size: 12px;color: #999;opacity: 0.5; padding-top: 5px;" > powered by <a href="https://www.typeform.com/examples/forms/contact-form-template/?utm_campaign=K35Aq9&utm_source=typeform.com-51674-Pro&utm_medium=typeform&utm_content=typeform-embedded-contactform&utm_term=EN" style="color: #999" target="_blank">Typeform</a> </div>
</div>
<script>
$zopim(function() {
$zopim.livechat.hideAll();
});
</script>
<?php get_footer(); ?>
<file_sep>/_build/09_about.html
<!DOCTYPE html>
<html lang="en-US" prefix="og: http://ogp.me/ns#">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<title>Title</title>
<link type="text/plain" rel="author" href="../authors.txt" />
<link type="image/x-icon" rel="shortcut icon" href="../favicon.ico" />
<!-- Remove When Adding <?php wp_head(); ?> -->
<link type="text/css" rel="stylesheet" media="all" href="../ui/css/style.css" />
<script src="../ui/js/modernizr.js"></script>
<script src="../ui/js/jquery.js" type="text/javascript"></script>
<!-- End Remove -->
</head>
<body>
<!--
When starting wp replace body with this
<body <?php body_class(); ?>>
-->
<div id="site-center">
<section id="header">
<div class="wrap">
<div class="util-nav">
<div class="country-selector">
<ul>
<li>
<div class="select-country">
<select name="country" class="spare-select">
<option selected="">United States</option>
<option value="SABRINA (Orchid)">Canada</option>
<option value="TAYLOR (Indigo)">UK</option>
</select>
</div>
</li>
</ul>
</div>
<div class="top-nav">
<ul>
<li><a href="#">Retail Locator</a></li>
<li><a href="#">Product Registration</a></li>
<li><a href="#">Support</a></li>
<li><a href="#">Contact</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Tune-Up Tour</a></li>
</ul>
</div>
</div>
<div class="logo">
<img src="/ui/images/logo-uppababy.png" alt="Uppababy Logo" />
</div>
<div class="main-nav">
<ul id="menu">
<li class="run-css">
<a href="#">Car Seats</a>
<ul class="sub-menu">
<li><a href="#">Mesa</a></li>
<li><a href="#">Seat Two</a></li>
</ul>
</li>
<li class="run-css">
<a href="#">Strolers</a>
<ul class="sub-menu">
<li><a href="#">Vista</a></li>
<li><a href="#">Cruz</a></li>
<li><a href="#">Stroller Three</a></li>
</ul>
</li>
<li class="run-css">
<a href="#">Lite Strollers</a>
<ul class="sub-menu">
<li><a href="#">G-Lite</a></li>
<li><a href="#">G-Lux</a></li>
<li><a href="#">Option Three</a></li>
<li><a href="#">Option Four</a></li>
</ul>
</li>
</ul>
</div>
</div>
</section>
<section id="hero-banner" style="background-image:url('/ui/images/VISTA17_hdr.jpg'); background-size:cover; height:520px; width:1024px; background-repeat:no-repeat;">
</section>
<section id="support">
<div class="content-wrap">
<div class="contact-box">
<h3>World Headquarters</h3>
<p>
UPPAbaby<br>
60 Sharp Street Ste. 3<br>
Hingham, MA 02043<br>
United States<br>
Main: <a href="tel:1-844-823-3132">(844) 823-3132</a><br>
Fax: (339) 499-7461
</p>
<h3>International</h3>
<p>
<a href="https://uppababy.com/contact-uppababy/">Global Distributors</a>
</p>
<h3>Customer Service</h3>
<p>
<a href="https://uppababy.com/register-stroller/" target="_blank" rel="noopener noreferrer">Product Registration</a><br>
<a href="tel:1-844-823-3132">(844) 823-3132</a>
</p>
</div>
<div class="support-column">
<h2>ABOUT OUR COMPANY</h2>
<p>
UPPAbaby is an innovative American company with one mission: To make high-quality baby products that fit the needs of your new life as a parent, while appealing to the sense of style you’ve always had. To do this successfully, UPPAbaby draws on a three decades of experience in the juvenile industry and on our own inspirations as parents of young children. We look for ways to make our strollers and baby products lighter, more savvy, easier-to-use, even fun. We explore ways to deliver greater comfort and safety for baby, with convenience and style for Mom and Dad. We even challenge the homogenous look of most baby products, by creating sleek designs and more sophisticated, modern fashions. UPPAbaby strives to deliver the personal attention and customer service that you expect and deserve.
</p>
<p>
By pushing the edge on so many levels, UPPAbaby delivers the higher standards of innovation and style that discriminating parents appreciate. For us, it’s a matter of pride. For parents, it’s one more source of joy.
</p>
<p>
<strong>Bob</strong>, <em>Owner and Product Development</em><br />
Bob has spent more than a few years inventing and developing products for companies such as Ford, Reebok, The First Years and Safety First. Although he suffered some bangs and bruises along the way, we believe that his experience gives each stroller a well-rounded and robust spirit.
</p>
<p>
<strong>Lauren</strong>, <em>Owner and Sales</em><br />
In addition to battling 3 test subjects/temperamental models and running our test facility (ie: home), Lauren is often referred to as MOBI (Mitigator of Bad Ideas). Day in, day out, she provides a breath of sanity to Bob’s sometimes impulsive decisions. She also uses her Reebok licensing experience to provide strategic and legal input.
</p>
<h2>WHAT MAKES US DIFFERENT</h2>
<p>
Our products meet the most stringent industry standards required by the Juvenile Product Manufacturing Association (JPMA) and the Consumer Product Safety Commission (CPSC). What makes us different though, is that we rely on our own real life experiences as parents to continuously set and raise the standards for safety, style and performance for which we’ve become known.
</p>
<p>
<strong>Customer Service</strong><br />
A recommendation from one parent to another is the highest form of flattery! A large part of our success is due to our incredible customer service team. We can’t say enough about them! We truly believe we have the most responsive customer service in the industry — and we provide the ultimate in personalized care and attention. Robin and her team would love to hear from you! See what actual users say about their experience with our team.
</p>
<p>
<strong>Warranty</strong>
We stand by our products and are committed to supporting our customers and their families. Once we have confirmed your claim, we will try our best to repair or ship replacement parts (free via FedEx) within 24 hours. That’s the best warranty program in the industry. Read more information about our warranty here.
</p>
<h2>UPPA GIVES BACK</h2>
<p>
UPPAbaby is committed to giving back and supporting worthy causes and organizations that align with our mission and core company ethos. We encourage you to join the UPPAbaby team and support these worthy causes. Check out all of our charity news here.
</p>
</div>
</div>
</section>
<!-- Remove when adding <?php wp_footer(); ?> -->
<section id="footer">
<div class="wrap">
<ul class="social-foot">
<li class="icon-facebook"><a href="#" target="_blank"></a></li>
<li class="icon-instagram"><a href="#" target="_blank"></a></li>
<li class="icon-twitter"><a href="#" target="_blank"></a></li>
<li class="icon-youtube"><a href="#" target="_blank"></a></li>
<li class="icon-pinterest"><a href="#" target="_blank"></a></li>
</ul>
<ul class="links-foot">
<li>©2017 UPPAbaby</li>
<li>Hingham, MA</li>
<li><a href="#">Terms</a></li>
<li><a href="#"><img src=""/>Retailers</a></li>
</ul>
<div id="newsletterSignup" class="newsLetterBox" style="margin-top:0px;">
<div class="newsletter-box">
<div class="newsletter-left">
<a href="https://experiences.wyng.com/campaign/?experience=5924a64823847f1cae7f3d67" target="_blank" class="newsletter-link">Sign up for UPPAbaby News & Updates</a>
</div>
<div class="newsletter-right">
<a href="https://experiences.wyng.com/campaign/?experience=5924a64823847f1cae7f3d67" target="_blank"><img src="https://uppababy.com/wp-content/themes/UPPAbaby_2017/img/subscribe-arrow.jpg"></a>
</div>
</div>
</div>
</div>
</section>
</div>
<script src="../ui/js/svgxuse.js"></script> <!-- SVG Polyfill -->
<script src="../ui/js/jquery.plugins.js" type="text/javascript"></script>
<script src="../ui/js/jquery.init.js" type="text/javascript"></script>
<!-- End Remove -->
</body>
</html>
<file_sep>/wp-content/themes/uppababy/include-geo-forward.php
<?php if ( is_user_logged_in() ) {
$geo = WPEngine\GeoIp::instance();
if(isset($_COOKIE['override'])) {
// Do Nothing
} else {
$country = getenv('HTTP_GEOIP_COUNTRY_CODE');
$country = strtolower($country);
setcookie('location',$country,time() + 24 * 3600); // 24 hours
if(isset($_COOKIE['location']) && $_COOKIE['location'] == 'us'){
if(isset($_COOKIE['dontLoop']) && $_COOKIE['dontLoop'] == 'stop'){
} else {
setcookie('dontLoop','stop',time() + 24 * 3600); // 24 hours?>
<script language="javascript">
window.location.href = "https://uppababy.com"
</script>
<?php }
} elseif(isset($_COOKIE['location']) && $_COOKIE['location'] == 'ca') {
if(isset($_COOKIE['dontLoop']) && $_COOKIE['dontLoop'] == 'stop'){
} else {
setcookie('dontLoop','stop',time() + 24 * 3600); // 24 hours?>
<script language="javascript">
window.location.href = "https://uppababy.com/ca"
</script>
<?php }
} elseif(isset($_COOKIE['location']) && $_COOKIE['location'] == 'uk') {
if(isset($_COOKIE['dontLoop']) && $_COOKIE['dontLoop'] == 'stop'){
} else {
setcookie('dontLoop','stop',time() + 24 * 3600); // 24 hours?>
<script language="javascript">
window.location.href = "https://uk.uppababy.com"
</script>
<?php }
}
}
} else {
}?>
<!-- // New method once all sites are moved
<?php if(isset($_COOKIE['location'])){
if(isset($_COOKIE['dontLoop']) && $_COOKIE['dontLoop'] == 'stop'){
} else {
setcookie('dontLoop','stop',time() + 24 * 3600); // 24 hours?>
<script language="javascript">
window.location.href = "https://uppababy.com"
</script>
<?php }
} ?>
-->
<file_sep>/wp-content/themes/uppababy/search.php
<?php
/*
Template Name: Search Page
*/
get_header(); the_post(); ?>
<?php $swp_query = new SWP_Query(
array(
's' => $_GET['s'], // search query
)
); ?>
<section id="search-results">
<div class="wrap clearfix">
<h2>Your search for "<span><?php echo $_GET['s'] ?></span>" yielded <span><?php echo $swp_query->post_count ?></span> results.</h2>
<?php if ( ! empty( $swp_query->posts ) ) { ?>
<div class="result-container">
<?php foreach( $swp_query->posts as $post ) : setup_postdata( $post ); ?>
<div class="results">
<h4><a href="<?php echo get_permalink(); ?>"><?php the_title(); ?></a></h4>
<?php if(get_field('hero_thumbnail')) {
$heroIMG = get_field('hero_thumbnail'); ?>
<img src="<?php echo $heroIMG['sizes']['acc-list-img']; ?>" alt="<?php echo $heroIMG['alt']; ?>" />
<?php } ?>
<?php the_excerpt(); ?>
<p>
<a href="<?php echo get_permalink(); ?>" class="more">Read More</a>
</p>
</div>
<?php endforeach; wp_reset_postdata(); ?>
</div>
<?php } ?>
</div>
</section>
<?php get_footer(); ?>
<file_sep>/wp-content/themes/uppababy/single-post.php
<?php get_header(); the_post(); ?>
<section id="news-post">
<div class="wrap clearfix">
<?php the_post_thumbnail('news-image'); ?>
<h2><?php the_title(); ?></h2>
<h4><?php the_date(); ?></h4>
<?php the_content(); ?>
<?php wp_link_pages(); ?>
</div>
</section>
<?php get_footer(); ?>
|
4c124ee7b10f5dddf0bff7f6ec67205dc7635f0b
|
[
"Markdown",
"JavaScript",
"HTML",
"PHP"
] | 38
|
PHP
|
GerryHolt/upby
|
df9dd7f46ebac2a19ddc9e3fcd6b54412f73ed2e
|
b59f11151b96d08812a36a93f1177df469825671
|
refs/heads/master
|
<repo_name>f-xyz/console-mock<file_sep>/README.md
# consoleMock
[](https://travis-ci.org/f-xyz/console-mock)
Mocked console.log, .info, .table, etc. for node and browsers.
```javascript
// basic use
var consoleMock = require('console-mock');
var console = consoleMock.create();
console.log(1, 2, 3); // 1 2 3
// disabling output
consoleMock.enabled(false); // disables output, but internal history is still written
console.log(3, 2, 1); // does nothing
// retrieving history
var history = consoleMock.history();
console.log(history); // does nothing
consoleMock.enabled(true); // enables output
console.log(history); // outputs:
// [ { method: 'log', arguments: [ 1, 2, 3 ] },
// { method: 'log', arguments: [ 3, 2, 1 ] } ]
// clearing history
console.historyClear()
console.log(consoleMock.history()); // outputs: []
```<file_sep>/index.js
var nativeConsole = global.console;
var isEnabled = true;
var historyStorage = [];
var toArray = [].slice.call.bind([].slice);
function create() {
if (typeof nativeConsole !== 'object') {
nativeConsole = {};
}
return {
log: callNative(nativeConsole.log, 'log'),
info: callNative(nativeConsole.info, 'info'),
warn: callNative(nativeConsole.warn, 'warn'),
error: callNative(nativeConsole.error, 'error'),
time: callNative(nativeConsole.time, 'time'),
timeEnd: callNative(nativeConsole.timeEnd, 'timeEnd'),
table: callNative(nativeConsole.table, 'table'),
trace: callNative(nativeConsole.trace, 'trace'),
group: callNative(nativeConsole.group, 'group'),
groupEnd: callNative(nativeConsole.groupEnd, 'groupEnd'),
groupCollapsed: callNative(nativeConsole.groupCollapsed, 'groupCollapsed')
};
}
function callNative(fn, name) {
return function () {
if (typeof fn === 'function') {
if (isEnabled) {
fn.apply(root.console, arguments);
}
historyStorage.push({
method: name,
arguments: toArray(arguments)
});
}
};
}
function getSetEnabled(value) {
if (value === undefined) {
return isEnabled;
} else {
isEnabled = value;
return this;
}
}
function history() {
return historyStorage;
}
function historyClear() {
historyStorage = [];
return this;
}
module.exports = {
_setNativeConsole: function (value) { nativeConsole = value },
create: create,
enabled: getSetEnabled,
history: history,
historyClear: historyClear
};
|
ce479cbf5acf91537b8a52ae1fea9d854bdc4790
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
f-xyz/console-mock
|
69d5d12204fae2800c3cecbee3e03256b18969cb
|
ae603d500d22c2fe5c24fee1293b605ff465be3c
|
refs/heads/master
|
<repo_name>jw8903/Distributed-Travel-Reservation-System<file_sep>/src/project/transaction/TransactionManagerImpl.java~
package transaction;
import java.rmi.*;
import java.util.*;
/**
* Transaction Manager for the Distributed Travel Reservation System.
*
* Description: toy implementation of the TM
*/
public class TransactionManagerImpl
extends java.rmi.server.UnicastRemoteObject
implements TransactionManager {
Hashtable active_list;
int xidCounter;
protected ResourceManager rmFlights = null;
protected ResourceManager rmRooms = null;
protected ResourceManager rmCars = null;
protected ResourceManager rmCustomers = null;
public static void main(String args[]) {
System.setSecurityManager(new RMISecurityManager());
String rmiPort = System.getProperty("rmiPort");
if (rmiPort == null) {
rmiPort = "";
} else if (!rmiPort.equals("")) {
rmiPort = "//:" + rmiPort + "/";
}
try {
TransactionManagerImpl obj = new TransactionManagerImpl();
Naming.rebind(rmiPort + TransactionManager.RMIName, obj);
System.out.println("TM bound");
}
catch (Exception e) {
System.err.println("TM not bound:" + e);
System.exit(1);
}
}
public TransactionManagerImpl() throws RemoteException {
active_list=new Hashtable();
xidCounter=1;
}
public int start()
throws RemoteException
{
int xid=xidCounter++;
Vector<String> v=new Vector<String> ();
active_list.put(xid, v);
return xid;
}
public boolean enlist(int xid, String rmiName)
throws RemoteException
{
if(!active_list.containsKey(xid))
{
return false;
}
try
{
Vector <String> vs=(Vector <String>)active_list.get(xid);
vs.add(rmiName);
active_list.put(xid, vs);
String rmiPort = System.getProperty("rmiPort");
if (rmiPort == null) {
rmiPort = "";
} else if (!rmiPort.equals("")) {
rmiPort = "//:" + rmiPort + "/";
}
if(rmiName.equals("RMFlights"))
{
rmFlights =
(ResourceManager)Naming.lookup(rmiPort +
ResourceManager.RMINameFlights);
System.out.println("WC bound to RMFlights");
}
if(rmiName.equals("RMRooms"))
{
rmRooms =
(ResourceManager)Naming.lookup(rmiPort +
ResourceManager.RMINameRooms);
System.out.println("WC bound to RMRooms");
}
if(rmiName.equals("RMCars"))
{
rmCars =
(ResourceManager)Naming.lookup(rmiPort +
ResourceManager.RMINameCars);
System.out.println("WC bound to RMCars");
}
if(rmiName.equals("RMCustomers"))
{
rmCustomers =
(ResourceManager)Naming.lookup(rmiPort +
ResourceManager.RMINameCustomers);
System.out.println("WC bound to RMCustomers");
}
}
catch(Exception e)
{
e.printStackTrace();
}
return true;
}
public boolean commit(int xid)
throws RemoteException,
TransactionAbortedException,
InvalidTransactionException
{
if(!active_list.containsKey(xid))
{
return false;
}
Vector <String> v1= (Vector <String>)active_list.get(xid);
Iterator it=v1.iterator();
while(it.hasNext())
{
String rName=(String)it.next();
if(rName.equals("RMFlights"))
{
if(rmFlights.flight_commit(xid))
{
System.out.println("Flights Committed");
}
else
{ System.out.println("Flight issue");
return false;
}
}
if(rName.equals("RMRooms"))
{
if(rmRooms.hotel_commit(xid))
{
System.out.println("Hotels Committed");
}
else
{ System.out.println("Room issue");
return false;
}
}
if(rName.equals("RMCars"))
{
if(rmCars.car_commit(xid))
{
System.out.println("Cars Committed");
}
else
{ System.out.println("car issue");
return false;
}
}
if(rName.equals("RMCustomers"))
{
if(rmCustomers.customer_commit(xid))
{
System.out.println("Customers Committed");
}
else
{
return false;
}
}
}
return true;
}
public void abort(int xid)
throws RemoteException,
InvalidTransactionException
{
if(!active_list.containsKey(xid))
{
System.out.print("Inactive transaction");
}
Vector <String> v1= (Vector <String>)active_list.get(xid);
Iterator it=v1.iterator();
while(it.hasNext())
{
String rName=(String)it.next();
if(rName.equals("RMFlights"))
{
rmFlights.flight_abort(xid);
}
if(rName.equals("RMRooms"))
{
rmRooms.hotel_abort(xid);
}
if(rName.equals("RMCars"))
{
rmCars.car_abort(xid);
}
if(rName.equals("RMCustomers"))
{
rmCustomers.customer_abort(xid);
}
}
}
public boolean dieNow()
throws RemoteException {
System.exit(1);
return true; // We won't ever get here since we exited above;
// but we still need it to please the compiler.
}
}
|
4c5a01b53b2556623dac9924cd86d2be9d98c683
|
[
"Java"
] | 1
|
Java
|
jw8903/Distributed-Travel-Reservation-System
|
59193672afc614a9315ccfcb599e502b87d065b1
|
e6ef5df2156470373014d2ad648bf268aa414cb1
|
refs/heads/master
|
<repo_name>eliseak/eh-loja<file_sep>/index.js
const express = require('express');
const expressMongoDB = require('express-mongo-db');
const cors = require('cors');
const ObjectID = require('mongodb').ObjectID;
const bodyParser = require('body-parser');
const app = express();
//app.use(expressMongoDB('mongodb://localhost/ehloja')); //localhost
app.use(expressMongoDB('mongodb://ehloja:ehloja123@192.168.3.11/ehloja')); //servidor mastertech
app.use(bodyParser.json());
app.use(cors());
app.get('/', (req, res) => {
res.send('Servidor ok!');
})
// INSERIR novo cliente
app.post('/cliente', (req, res) => {
let cliente = {
cpf: req.body.cpf,
nome: req.body.nome,
email: req.body.email
};
req.db.collection('clientes').insert(cliente, (error) => {
if (error){
res.status(500).send();
return;
}
res.send(cliente);
})
});
// LER todos os clientes no banco
app.get('/clientes', (req, res) => {
req.db.collection('clientes').find().toArray((error, data) => {
if (error){
res.status(500).send();
return;
}
res.send(data);
})
})
// LER o cliente no banco por EMAIL
app.get('/cliente/:id', (req, res) => {
let query = {
_id: ObjectID(req.params.id)
}
req.db.collection('clientes').findOne(query, (error, data) => {
if (error){
res.status(500).send();
return;
}
res.send(data);
})
})
// Primeira porta para o Heroku, caso não encontrado: utiliza porta 3000
app.listen(process.env.PORT||3000, () => console.log('Aplicacao iniciada'));
|
54b2949c08493345bc88cb5468c2a7ec7ab8ff7b
|
[
"JavaScript"
] | 1
|
JavaScript
|
eliseak/eh-loja
|
0700616abf44b6c4895afd3fdf4e0c1d725a5638
|
a9ad7b709532c61c158f7da7be3b265af5b8a5fa
|
refs/heads/main
|
<repo_name>castillo05/giphyApp<file_sep>/src/hooks/useStorage.js
import { useState, useEffect } from "react";
const useStorage = (category) => {
const [state, setstate] = useState([]);
useEffect(() => {
if (localStorage.getItem("categories")) {
const data = localStorage.getItem("categories");
const newListCategories = data.split(",");
if (category.length > 0) {
console.log(category);
newListCategories.push(category[0]);
localStorage.setItem("categories", newListCategories);
}
setstate(newListCategories);
} else {
localStorage.setItem("categories", category);
const data = localStorage.getItem("categories");
const newListCategories = data.split(",");
setstate(newListCategories);
}
}, [category]);
return state;
};
export default useStorage;
<file_sep>/src/GifExpertApp.js
import React, { useState } from "react";
import AddCategory from "./components/AddCategory";
import GifGrid from "./components/GifGrid";
import useStorage from "./hooks/useStorage";
const GifExpertApp = () => {
const [categories, setCategories] = useState([]);
const storage = useStorage(categories);
return (
<div>
<h2>GiphyApi-reactjs</h2>
<AddCategory setCategories={setCategories}></AddCategory>
<hr></hr>
<ol>
{storage.map((category) => (
<GifGrid category={category} key={category}></GifGrid>
))}
</ol>
</div>
);
};
export default GifExpertApp;
|
111950344febac619057480589e7bc7c06c73882
|
[
"JavaScript"
] | 2
|
JavaScript
|
castillo05/giphyApp
|
cd9d42ef5dbedc0c9b39ba2bd0b5fdf8db606cbf
|
11181b2f39d71415c24245dbdedadc51ce2c9df1
|
refs/heads/master
|
<file_sep>export * from './event.service';
export * from './event.modal';
export * from './restricted-words.validator';
export * from './duration.pipe';
|
3150744a630c13f8e9dbba4b4ec37e69cd5cdf6d
|
[
"TypeScript"
] | 1
|
TypeScript
|
collinewait/fundermentals-ng
|
b58ce1caa5c0f52cfb60090dfa545725161800af
|
a869a5d89ff4b7e7e5ede38d0822c8703c949351
|
refs/heads/master
|
<repo_name>gergelykoncz/deepstream-rxjs<file_sep>/src/record/test/record.spec.ts
import { Observable } from 'rxjs';
import { Record } from '..';
import { Client } from '../../client';
import { EventEmitter } from 'events';
interface TestData {
foo: string;
name?: string;
}
describe('Test Record', () => {
let setDataSpy: any;
let snapshotSpy: any;
let getRecordSpy: any;
let hasSpy: any;
let offSpy: jasmine.Spy;
let deleteSpy;
let recordName = 'recordName';
let data: TestData = {
foo: 'bar'
};
let data2: TestData = {
foo: 'bar2'
};
class MockClient extends Client {}
beforeEach(() => {
offSpy = jasmine.createSpy('off');
deleteSpy = jasmine.createSpy('delete');
spyOn(Client, 'GetDependencies').and.callFake(() => {
return {
deepstream: jasmine.createSpy('deepstreamStub').and.returnValue({
record: {
setData: setDataSpy,
snapshot: snapshotSpy,
getRecord: getRecordSpy,
has: hasSpy,
delete: deleteSpy
},
on: () => {
/* EMPTY */
},
off: offSpy
})
};
});
});
describe('When we try to get the data', () => {
beforeEach(() => {
getRecordSpy = jasmine.createSpy('getRecord').and.callFake(name => {
return {
whenReady: callback => callback(),
subscribe: (path, callback) => {
callback(data);
},
unsubscribe: () => {
/* Empty */
}
};
});
});
it('it should return an observable', async () => {
let client = new MockClient('atyala');
let record = new Record<TestData>(client, recordName);
let record$ = record.get();
expect(record$ instanceof Observable).toBeTruthy();
let result = await record$.take(1).toPromise();
let args = getRecordSpy.calls.mostRecent().args;
expect(args[0]).toEqual(recordName);
expect(result instanceof Object).toBeTruthy();
expect(result.foo).toEqual(data.foo);
expect(offSpy).toHaveBeenCalled();
});
it('should work without type definitions', async () => {
let client = new MockClient('atyala');
let record = new Record(client, recordName);
let record$ = record.get();
expect(record$ instanceof Observable).toBeTruthy();
let result = await record$.take(1).toPromise();
let args = getRecordSpy.calls.mostRecent().args;
expect(args[0]).toEqual(recordName);
expect(result instanceof Object).toBeTruthy();
expect(result.foo).toEqual(data.foo);
expect(offSpy).toHaveBeenCalled();
});
it("should call observer's next when data changed", done => {
getRecordSpy = jasmine.createSpy('getRecord').and.callFake(name => {
return {
whenReady: callback => callback(),
subscribe: (path, callback) => {
callback(data);
setTimeout(() => {
callback(data2);
}, 100);
},
unsubscribe: () => {
/* Empty */
}
};
});
let client = new MockClient('atyala');
let record = new Record<TestData>(client, recordName);
let record$ = record.get();
expect(record$ instanceof Observable).toBeTruthy();
record$.skip(1).subscribe(_record => {
expect(_record instanceof Object).toBeTruthy();
expect(_record.foo).toEqual('bar2');
done();
}, done.fail);
});
});
describe('When we try to set any data', () => {
it('should do it', async () => {
setDataSpy = jasmine.createSpy('setData').and.callFake((name, pathOrData, ...rest) => {
let cb = rest[rest.length - 1];
cb();
});
let client = new MockClient('atyala');
let record = new Record<TestData>(client, recordName);
let result = await record.set(data).toPromise();
let args = setDataSpy.calls.mostRecent().args;
expect(args[0]).toEqual(recordName);
expect(args[1]).toEqual(data);
});
it('should set only a property value', async () => {
setDataSpy = jasmine.createSpy('setData').and.callFake((name, pathOrData, ...rest) => {
let cb = rest[rest.length - 1];
cb();
});
let client = new MockClient('atyala');
let record = new Record<TestData>(client, recordName);
let result = await record.set('name', 'test').toPromise();
let args = setDataSpy.calls.mostRecent().args;
expect(args[0]).toEqual(recordName);
expect(args[1]).toEqual('name');
expect(args[2]).toEqual('test');
});
});
describe('When the callback returns error', () => {
it('should throw error', async done => {
setDataSpy = jasmine.createSpy('setData').and.callFake((name, path, ...rest) => {
let cb = rest[rest.length - 1];
cb('error');
});
let client = new MockClient('atyala');
let record = new Record<TestData>(client, recordName);
await record
.set(data)
.toPromise()
.catch(err => {
expect(err).toEqual('error');
done();
});
});
});
describe('When we try to unset fields', () => {
it('should do it', async () => {
setDataSpy = jasmine.createSpy('setData').and.callFake((name, pathOrData, ...rest) => {
let cb = rest[rest.length - 1];
cb();
});
let client = new MockClient('atyala');
let record = new Record<TestData>(client, recordName);
let result = await record.unset('foo').toPromise();
let args = setDataSpy.calls.mostRecent().args;
expect(args[0]).toEqual(recordName);
expect(args[1]).toEqual('foo');
expect(args[2]).toBeUndefined();
});
});
describe('When the unset callback returns error', () => {
it('should throw error', async done => {
setDataSpy = jasmine.createSpy('setData').and.callFake((name, path, ...rest) => {
let cb = rest[rest.length - 1];
cb('error');
});
let client = new MockClient('atyala');
let record = new Record<TestData>(client, recordName);
await record
.unset('foo')
.toPromise()
.catch(err => {
expect(err).toEqual('error');
done();
});
});
});
describe('When the callback returns error', () => {
it('should throw error', async done => {
setDataSpy = jasmine.createSpy('setData').and.callFake((name, path, ...rest) => {
let cb = rest[rest.length - 1];
cb('error');
});
let client = new MockClient('atyala');
let record = new Record<TestData>(client, recordName);
await record
.set(data)
.toPromise()
.catch(err => {
expect(err).toEqual('error');
done();
});
});
});
describe('When we try to get the snapshot of any data', () => {
it('should do return', async () => {
snapshotSpy = jasmine.createSpy('snapshot').and.callFake((name, cb) => {
cb(null, data);
});
let client = new MockClient('atyala');
let record = new Record<TestData>(client, recordName);
spyOn(record, 'get').and.returnValue(Observable.of({}));
let result = await record.snapshot().toPromise();
expect(record.get).toHaveBeenCalled();
});
});
describe('When the record subscription has error', () => {
let unsubscribeSpy = jasmine.createSpy('unsubscribe');
class MockDeepstream extends EventEmitter {
record = {
getRecord: jasmine.createSpy('getRecord').and.callFake(name => {
return {
unsubscribe: unsubscribeSpy,
subscribe: (path, callback) => {
callback(data);
}
};
}),
subscribe: jasmine.createSpy('subscribeSpy')
};
off = offSpy;
}
beforeEach(() => {
jasmine.clock().uninstall();
jasmine.clock().install();
});
afterEach(() => {
jasmine.clock().uninstall();
});
it('it should pass the error to the rxjs observable', done => {
class MockEventClient extends Client {
public client = new MockDeepstream();
}
let mockClient = new MockEventClient('connstr');
let record = new Record<TestData>(mockClient, 'record');
let subs = record.get().subscribe(
() => {
/* EMPTY */
},
err => {
expect(err).toEqual('MESSAGE');
subs.unsubscribe();
expect(offSpy.calls.mostRecent().args[0]).toEqual('error');
// This is for bug https://github.com/deepstreamIO/deepstream.io-client-js/issues/204
jasmine.clock().tick(501);
done();
}
);
mockClient.client.emit('error', 'ERR', 'MESSAGE');
});
});
describe('When we try to check if a record exists', () => {
it('should invoke the has method on ds', async () => {
hasSpy = jasmine.createSpy('has').and.callFake((name, cb) => cb(null, true));
let mockClient = new MockClient('connstr');
let record = new Record<TestData>(mockClient, 'existingRecord');
let result = await record.exists().toPromise();
expect(hasSpy).toHaveBeenCalledWith('existingRecord', jasmine.any(Function));
expect(result).toBeTruthy();
});
});
describe('When we try to check if a record exists', () => {
it('should emit error if the operation errors', async done => {
hasSpy = jasmine.createSpy('has').and.callFake((name, cb) => cb('ERROR', false));
let mockClient = new MockClient('connstr');
let record = new Record<TestData>(mockClient, 'existingRecord');
let result = await record
.exists()
.toPromise()
.catch(err => {
expect('ERROR').toEqual(err);
done();
});
});
});
describe('When removing an existing object', () => {
let client;
let unsubscribeSpy;
let mockRecord;
class MockRecord extends EventEmitter {
constructor() {
super();
}
delete = deleteSpy;
off = offSpy;
}
beforeEach(() => {
mockRecord = new MockRecord();
getRecordSpy = jasmine.createSpy('getRecord').and.returnValue(mockRecord);
client = new MockClient('connstr');
});
it('it should be ok', done => {
unsubscribeSpy = { unsubscribe: jasmine.createSpy('unsubscribeSpy') };
spyOn(client.errors$, 'subscribe').and.returnValue(unsubscribeSpy);
let record = new Record<TestData>(client, 'record');
let subs$ = record.remove().subscribe(res => {
expect(res).toBeTruthy();
expect(getRecordSpy).toHaveBeenCalled();
expect(deleteSpy).toHaveBeenCalled();
expect(client.errors$.subscribe).toHaveBeenCalled();
// Wait for the unsubscription
setTimeout(() => {
expect(offSpy).toHaveBeenCalledTimes(2);
expect(unsubscribeSpy.unsubscribe).toHaveBeenCalled();
done();
}, 10);
});
mockRecord.emit('delete');
});
it('should call the error handlers if there is any record error', done => {
unsubscribeSpy = { unsubscribe: jasmine.createSpy('unsubscribeSpy') };
spyOn(client.errors$, 'subscribe').and.returnValue(unsubscribeSpy);
let record = new Record<TestData>(client, 'record');
let subs$ = record.remove().subscribe(
res => {
/* EMPTY */
},
error => {
expect(error).toEqual('ERROR');
expect(getRecordSpy).toHaveBeenCalled();
expect(deleteSpy).toHaveBeenCalled();
expect(client.errors$.subscribe).toHaveBeenCalled();
// Wait for the unsubscription
setTimeout(() => {
expect(offSpy).toHaveBeenCalledTimes(2);
expect(unsubscribeSpy.unsubscribe).toHaveBeenCalled();
done();
}, 10);
}
);
mockRecord.emit('error', 'ERROR');
});
it('should call the error handlers if there is any client error', done => {
let record = new Record<TestData>(client, 'record');
let subs$ = record.remove().subscribe(
res => {
/* EMPTY */
},
error => {
expect(error).toEqual('ERROR');
expect(getRecordSpy).toHaveBeenCalled();
expect(deleteSpy).toHaveBeenCalled();
// Wait for the unsubscription
setTimeout(() => {
expect(offSpy).toHaveBeenCalledTimes(2);
expect(unsubscribeSpy.unsubscribe).toHaveBeenCalled();
done();
}, 10);
}
);
client.errors$.next('ERROR');
});
});
});
<file_sep>/src/event/test/event.spec.ts
import { Subscription } from 'rxjs';
import { Event } from '..';
import { Client } from '../../client';
import { EventEmitter } from 'events';
interface TestData {
foo: string;
}
describe('Test Record', () => {
let subscribeSpy: jasmine.Spy;
let emitSpy: jasmine.Spy;
let unsubscribeSpy: jasmine.Spy;
let topicName = 'topic';
let data: TestData = {
foo: 'bar'
};
class MockClient extends Client {}
beforeEach(() => {
subscribeSpy = jasmine.createSpy('subscribeSpy');
emitSpy = jasmine.createSpy('emitSpy');
unsubscribeSpy = jasmine.createSpy('unsubscribeSpy');
spyOn(Client, 'GetDependencies').and.callFake(() => {
return {
deepstream: jasmine.createSpy('deepstreamStub').and.returnValue({
event: {
subscribe: subscribeSpy,
unsubscribe: unsubscribeSpy,
emit: emitSpy
}
})
};
});
});
describe('When we subscribe to the topic', () => {
it('it should return an observable, and emit should be called properly', () => {
let client = new MockClient('atyala');
let event = new Event<TestData>(client, topicName);
let event$ = event.receive().subscribe();
expect(event$ instanceof Subscription).toBeTruthy();
expect(subscribeSpy).toHaveBeenCalledWith(topicName, jasmine.any(Function));
event$.unsubscribe();
expect(unsubscribeSpy).toHaveBeenCalledWith(topicName);
event.emit(data);
expect(emitSpy).toHaveBeenCalledWith(topicName, data);
});
});
});
<file_sep>/README.md
# deepstream rxjs
[](https://travis-ci.org/garlictech/deepstream-rxjs)
[](https://github.com/semantic-release/semantic-release)
[](http://commitizen.github.io/cz-cli/)
[](https://stackshare.io/garlic-tech-ltd/garlic-tech-ltd)
Rxjs wrapper for [deepstream Javascript Client](https://deepstreamhub.com/docs/client-js/client/).
TBD
<file_sep>/src/rpc/index.ts
import { Observable, Observer } from 'rxjs';
import * as util from 'util';
import { Client } from '../client';
export class Rpc {
constructor(private _client: Client) {}
public make(name, data): Observable<any> {
return new Observable<any>((obs: Observer<any>) => {
let errSubscription$ = this._client.errors$.subscribe(error => obs.error(error));
this._client.client.rpc.make(name, data, (err, result) => {
errSubscription$.unsubscribe();
if (err) {
try {
obs.error(JSON.parse(err));
} catch (e) {
obs.error(err);
}
} else {
obs.next(result);
obs.complete();
}
});
return () => {
errSubscription$.unsubscribe();
};
});
}
public provide(name, providerFv) {
this._client.client.rpc.provide(name, providerFv);
}
}
<file_sep>/src/query/index.ts
import { Observable, Observer } from 'rxjs';
import { Client } from '../client';
import { Record } from '../record';
import { Logger } from '../logger';
export class Query<T = any> {
constructor(protected _client: Client) {}
queryForEntries(queryOrHash: any): Observable<string[]> {
let queryString = queryOrHash;
if (typeof queryOrHash !== 'string') {
queryString = JSON.stringify(queryOrHash);
}
let liveQueryName = `search?${queryString}`;
let listName = `live_${queryString}`;
let liveQuery = this._client.client.record.getList(liveQueryName);
let list = this._client.client.record.getList(listName);
let observable = new Observable<string[]>((obs: Observer<string[]>) => {
this._client.client.on('error', (err, msg) => {
obs.error(msg);
});
list.subscribe(data => {
obs.next(data);
});
return () => {
this._client.client.removeEventListener('error');
list.discard();
};
});
return observable;
}
queryForData(queryOrHash: any, table?: string): Observable<T[]> {
return this.queryForEntries(queryOrHash).switchMap((recordNames: string[]) => {
if (recordNames.length === 0) {
return Observable.of([]);
}
let recordObservables = recordNames.map(recordName => {
let tableName = table || queryOrHash.table;
let recordFQN = `${tableName}/${recordName}`;
Logger.debug('theres a record' + recordFQN);
let record = this._createRecord(recordFQN);
return record.snapshot();
});
return Observable.combineLatest(recordObservables);
});
}
pageableQuery(queryOrHash, start, end, table?): Observable<T[]> {
return this.queryForEntries(queryOrHash).switchMap((recordNames: string[]) => {
if (recordNames.length === 0) {
return Observable.of([]);
}
let records = recordNames.slice(start, end);
let recordObservables = records.map(recordName => {
let tableName = table || queryOrHash.table;
let recordFQN = `${tableName}/${recordName}`;
let record = this._createRecord(recordFQN);
return record.snapshot();
});
return Observable.combineLatest(recordObservables);
});
}
protected _createRecord(recordName: string): Record<T> {
return new Record<T>(this._client, recordName);
}
}
<file_sep>/src/client/index.ts
import { Observable, Observer, Subject, Subscription } from 'rxjs';
let deepstream = require('deepstream.io-client-js'); // tslint:disable-line:no-var-requires
import { Logger } from '../logger';
import { IProviderConnectionData, IConnectionData } from '../interfaces';
export interface IClientData {
id: string;
roles?: string[];
permissionRecord?: string;
}
export class Client {
public client;
public states$: Subject<any>;
public errors$: Subject<any>;
private subscribtion: Subscription;
private errorSubscribtion: Subscription;
static GetDependencies() {
return {
deepstream: deepstream
};
}
public constructor(private _connectionString: string, options?: any) {
this.states$ = new Subject<any>();
this.errors$ = new Subject<Error>();
this.client = Client.GetDependencies().deepstream(this._connectionString, options);
}
public login(authData: IProviderConnectionData | IConnectionData): Observable<IClientData> {
let loginSubject = new Subject<IClientData>();
Logger.debug('Deepstream client is logging in.');
Logger.debug('Login data: ', JSON.stringify(authData, null, 2));
this.client.login(authData, (success, data) => {
if (success === true) {
// Return the clientData
loginSubject.next(data);
loginSubject.complete();
} else {
// Close the connection if error happened
this.close().subscribe(() => {
loginSubject.error(new Error('Login Failed'));
}, loginSubject.error);
}
});
// Create the subscribtions
this.errorSubscribtion = Observable.fromEvent(this.client, 'error')
.do(state => {
Logger.debug('Error happened: ');
Logger.debug(JSON.stringify(state, null, 2));
})
.subscribe(state => this.errors$.next(state));
this.subscribtion = Observable.fromEvent(this.client, 'connectionStateChanged')
.do(state => Logger.debug('Deepstream client connection state: ', state))
.subscribe(state => this.states$.next(state));
return loginSubject;
}
public close(): Observable<void> {
// Unsubscribe from the active subscribtions
if (this.subscribtion) {
this.subscribtion.unsubscribe();
}
if (this.errorSubscribtion) {
this.errorSubscribtion.unsubscribe();
}
// Call the native close event
if (this.client && this.isClosed() !== true) {
let obs$ = Observable.create(observer => {
this.client.on('connectionStateChanged', state => {
if (state === 'CLOSED') {
observer.next();
observer.complete();
}
});
this.client.close();
}).do(() => Logger.debug(`Deepstream client is closed`));
return obs$;
} else {
return Observable.of(undefined);
}
}
public isClosed(): boolean {
return this.client && this.client.getConnectionState() === deepstream.CONSTANTS.CONNECTION_STATE.CLOSED;
}
public isConnected(): boolean {
return this.client && this.client.getConnectionState() === deepstream.CONSTANTS.CONNECTION_STATE.OPEN;
}
}
<file_sep>/src/list/index.ts
import { Observable, Observer, Subject } from 'rxjs';
import { Client } from '../client';
import { Logger } from '../logger';
import { Record } from '../record';
export interface IRecordAdded<T> {
data: T;
position: number;
};
export class List<T = any> {
protected _list;
constructor(protected _client: Client, private _name: string) {
this._list = this._client.client.record.getList(this._name);
}
subscribeForEntries(): Observable<string[]> {
let observable = new Observable<any>((obs: Observer<any>) => {
let callback = data => {
obs.next(data);
};
let errorCallback = (err, msg) => obs.error(msg);
this._list.on('error', errorCallback);
let errSubscription$ = this._client.errors$.subscribe(error => errorCallback(null, error));
this._list.subscribe(callback, true);
return () => {
this._list.unsubscribe(callback);
errSubscription$.unsubscribe();
this._list.off('error', errorCallback);
this._list.discard();
};
});
return observable;
}
subscribeForData(): Observable<T[]> {
return this.subscribeForEntries().switchMap((recordNames: string[]) => {
let recordObservables = recordNames.map(recordName => this._createRecord(recordName).get());
return recordObservables.length ? Observable.combineLatest(recordObservables) : Observable.of([]);
});
}
addEntry(entry: string, index?: number): void {
this._list.addEntry(entry, index);
}
removeEntry(entry: string, index?: number): void {
this._list.removeEntry(entry, index);
}
addRecord(data: T, index?: number): Observable<void> {
let entryId = `${this._name}/${this._client.client.getUid()}`;
this.addEntry(entryId, index);
let record = new Record<T>(this._client, entryId);
return record.set(data);
}
discard() {
this._list.discard();
}
recordAdded() {
let observable = new Observable<IRecordAdded<T>>((obs: Observer<IRecordAdded<T>>) => {
let callback = (entry, pos) => {
let record = this._createRecord(entry);
record.get().take(1).subscribe(data => obs.next({ data: data, position: pos }));
};
this._list.on('entry-added', callback);
return () => this._list.off('entry-added', callback);
});
return observable;
}
isEmpty(): Observable<boolean> {
let subj = new Subject<boolean>();
this._list.whenReady(list => {
subj.next(list.isEmpty());
subj.complete();
});
return subj;
}
protected _createRecord(recordName: string): Record<T> {
return new Record<T>(this._client, recordName);
}
}
<file_sep>/src/record/index.ts
import { Observable, Observer, Subject } from 'rxjs';
import { Client } from '../client';
import { Logger } from '../logger';
export class Record<T = any> {
constructor(private _client: Client, private _name: string) {}
public get(path?: string): Observable<T> {
let record = this._client.client.record.getRecord(this._name);
let observable = new Observable<T>((obs: Observer<T>) => {
let errHandler = (err, msg) => obs.error(msg);
this._client.client.on('error', errHandler);
let statusChanged = data => {
obs.next(<T>data);
};
record.subscribe(path, statusChanged, true);
return () => {
this._client.client.off('error', errHandler);
record.unsubscribe(this._name, statusChanged);
};
});
return observable;
}
public set(value: T): Observable<void>;
public set(field: string, value: any): Observable<void>;
public set(fieldOrValue: string | T, value?: any): Observable<void> {
return new Observable<void>((obs: Observer<void>) => {
let callback = err => {
if (err) {
obs.error(err);
}
obs.next(null);
obs.complete();
};
if (typeof value === 'undefined') {
this._client.client.record.setData(this._name, fieldOrValue, callback);
} else {
this._client.client.record.setData(this._name, fieldOrValue, value, callback);
}
});
}
public unset(field): Observable<void> {
return new Observable<void>((obs: Observer<void>) => {
let callback = err => {
if (err) {
obs.error(err);
}
obs.next(null);
obs.complete();
};
this._client.client.record.setData(this._name, field, undefined, callback);
});
}
public exists(): Observable<boolean> {
return new Observable<boolean>((obs: Observer<boolean>) => {
let callback = (err, exists) => {
obs.next(exists);
if (err) {
obs.error(err);
}
obs.complete();
};
this._client.client.record.has(this._name, callback);
});
}
public snapshot() {
return this.get().take(1);
}
public remove(): Observable<boolean> {
return new Observable<boolean>((obs: Observer<boolean>) => {
let errSubscription$ = this._client.errors$.subscribe(error => obs.error(error));
let record = this._client.client.record.getRecord(this._name);
let cleanup = () => {
errSubscription$.unsubscribe();
record.off('error', errorCb);
record.off('delete', deleteCb);
};
let deleteCb = record.on('delete', () => {
obs.next(true);
obs.complete();
});
let errorCb = record.on('error', err => obs.error(err));
record.delete();
return () => cleanup();
});
}
}
<file_sep>/src/logger.ts
import * as debug from 'debug';
let logger = {
debug: debug('deepstream-rxjs')
};
export { logger as Logger };
<file_sep>/src/client/test/client.spec.ts
import { EventEmitter } from 'events';
import sms = require('source-map-support');
sms.install();
let deepstream = require('deepstream.io-client-js');
import { Observable } from 'rxjs';
import { Client } from '..';
import { Record } from '../../record';
describe('When the deepstream client is up and running, the client', () => {
let emitCloseEvent = false;
class MockDeepstream extends EventEmitter {
private _state = deepstream.CONSTANTS.CONNECTION_STATE.CLOSED;
constructor() {
super();
}
public login = jasmine.createSpy('login').and.callFake((authData, callback = (success, data) => {
/* Empty */
}) => {
this._state = deepstream.CONSTANTS.CONNECTION_STATE.OPEN;
this.on('connectionStateChanged', state => {
switch (state) {
case 'OPEN':
callback(true, {
id: 'foobar',
roles: ['user']
});
break;
case 'TESTFAIL':
this._state = deepstream.CONSTANTS.CONNECTION_STATE.AWAITING_AUTHENTICATION;
callback(false, null);
break;
}
});
});
public close = jasmine.createSpy('close').and.callFake(() => {
this._state = deepstream.CONSTANTS.CLOSED;
if (emitCloseEvent === true) {
this.emit('connectionStateChanged', 'CLOSED');
}
});
public getConnectionState() {
return this._state;
}
}
let mockDeepstream: any;
let deepstreamStub;
let loginData = { providerName: 'UNIT TEST PROVIDER', jwtToken: 'foobar' };
let connectionString = 'foobar';
beforeEach(() => {
emitCloseEvent = false;
mockDeepstream = new MockDeepstream();
deepstreamStub = jasmine.createSpy('deepstreamStub').and.callFake(() => {
return mockDeepstream;
});
spyOn(Client, 'GetDependencies').and.callFake(() => {
return { deepstream: deepstreamStub };
});
});
it('should connect', done => {
let options = { foo: 'bar' };
let client = new Client(connectionString, options);
expect(client.isConnected()).toBeFalsy();
client.login(loginData).subscribe(loginResponse => {
let args;
expect(deepstreamStub).toHaveBeenCalledWith(connectionString, options);
expect(Client.GetDependencies).toHaveBeenCalled();
expect(mockDeepstream.login).toHaveBeenCalled();
args = mockDeepstream.login.calls.mostRecent().args;
expect(args[0]).toEqual(loginData);
expect(loginResponse.id).toEqual('foobar');
expect(client.isConnected()).toBeTruthy();
done();
}, done.fail);
mockDeepstream.emit('connectionStateChanged', 'OPEN');
});
it('should subscribe to state changes', done => {
let client = new Client(connectionString);
client.login(loginData).subscribe(() => {
// Do nothing
}, done.fail);
client.states$.subscribe(state => {
expect(state).toEqual('TESTSTATE');
done();
});
mockDeepstream.emit('connectionStateChanged', 'TESTSTATE');
});
it('should subscribe to errors', done => {
let client = new Client(connectionString);
client.login(loginData).subscribe(() => {
// Do nothing
}, done.fail);
client.errors$.subscribe(state => {
expect(state).toEqual('TESTERROR');
done();
});
mockDeepstream.emit('error', 'TESTERROR');
});
it('should throw error when login fails', done => {
let client = new Client(connectionString);
expect(client.isConnected()).toBeFalsy();
emitCloseEvent = true;
client.login(loginData).subscribe(
loginResponse => {
done.fail(new Error('Not failed'));
},
err => {
let args;
expect(deepstreamStub).toHaveBeenCalledWith(connectionString, undefined);
expect(Client.GetDependencies).toHaveBeenCalled();
expect(mockDeepstream.login).toHaveBeenCalled();
expect(mockDeepstream.close).toHaveBeenCalled();
args = mockDeepstream.login.calls.mostRecent().args;
expect(args[0]).toEqual(loginData);
expect(client.isConnected()).toBeFalsy();
done();
}
);
mockDeepstream.emit('connectionStateChanged', 'TESTFAIL');
});
it('should retry when some calls failed', done => {
let client = new Client(connectionString);
let subscripion = client.login(loginData).subscribe(() => done());
mockDeepstream.emit('connectionStateChanged', 'ERROR');
mockDeepstream.emit('connectionStateChanged', 'ERROR');
mockDeepstream.emit('error', 'ERROR');
mockDeepstream.emit('connectionStateChanged', 'OPEN');
});
it('should be able to close the connection', async done => {
let client = new Client(connectionString);
client
.login(loginData)
.do(() => expect(client.isConnected()).toBeTruthy())
.switchMap(() => {
let res$ = client.close();
return res$;
})
.subscribe(() => {
// This means that at the "FOOBAR" event no close is called
expect(mockDeepstream.close).toHaveBeenCalledTimes(1);
expect(client.isConnected()).toBeFalsy();
done();
});
mockDeepstream.emit('connectionStateChanged', 'OPEN');
// This will test if the close observer emits only at the 'close' event
mockDeepstream.emit('connectionStateChanged', 'FOOBAR');
mockDeepstream.emit('connectionStateChanged', 'CLOSED');
});
it('should handle close request even if the client is not connected', done => {
let client = new Client(connectionString);
client.close().subscribe(() => {
expect(mockDeepstream.close).not.toHaveBeenCalled();
done();
});
});
it('should handle re-login: if the client is logged in, close the connection', done => {
let client = new Client(connectionString);
emitCloseEvent = true;
client
.login(loginData)
.do(() => {
expect(mockDeepstream.close).not.toHaveBeenCalled();
})
.switchMap(() => {
let res$ = client.login(loginData);
return res$;
})
.subscribe(() => {
expect(mockDeepstream.close).not.toHaveBeenCalled();
done();
});
mockDeepstream.emit('connectionStateChanged', 'OPEN');
mockDeepstream.emit('connectionStateChanged', 'OPEN');
});
});
describe('Without mocking the deepstream dependencies', () => {
it('GetDependencies should return the deepstream factory', () => {
expect(Client.GetDependencies()).not.toBeNull();
});
});
<file_sep>/src/query/test/query.spec.ts
import { Observable } from 'rxjs';
import * as _ from 'lodash';
import { Query } from '..';
import { Client } from '../../client';
import { Record } from '../../record';
import { List } from '../../list';
import { EventEmitter } from 'events';
describe('Test Query', () => {
let getListSpy: jasmine.Spy;
let snapshotSpy: jasmine.Spy;
let subscribeSpy: jasmine.Spy;
let data = ['data1', 'data2'];
let data2 = ['data3', 'data4'];
let allData = [data, data2];
let tableName = 'tableName';
let recordNames = ['record1', 'record2'];
class MockClient extends Client {}
class MockRecord extends Record<string> {
static getSpy;
constructor(_client, recordName) {
super(_client, recordName);
MockRecord.getSpy = jasmine.createSpy('get').and.returnValue(Observable.of('value'));
this.get = MockRecord.getSpy;
}
}
class MockRecordAny extends Record {
static getSpy;
constructor(_client, recordName) {
super(_client, recordName);
MockRecord.getSpy = jasmine.createSpy('get').and.returnValue(Observable.of('value'));
this.get = MockRecord.getSpy;
}
}
class MockQuery extends Query<string> {
_createRecord(recordName) {
return new MockRecord(this._client, recordName);
}
}
class MockQueryAny extends Query {
_createRecord(recordName) {
return new MockRecordAny(this._client, recordName);
}
}
beforeEach(() => {
subscribeSpy = jasmine.createSpy('subscribe').and.callFake(callback => {
callback(recordNames);
});
snapshotSpy = jasmine
.createSpy('snapshot')
.and.callFake((name, callback) => callback(null, _.flatten(allData)[snapshotSpy.calls.count() - 1]));
getListSpy = jasmine.createSpy('getList').and.callFake(name => {
return {
whenReady: callback => callback(),
subscribe: subscribeSpy,
unsubscribe: () => {
// Empty
},
discard: () => {
// Empty
}
};
});
spyOn(Client, 'GetDependencies').and.callFake(() => {
return {
deepstream: jasmine.createSpy('deepstreamStub').and.returnValue({
record: {
getList: getListSpy,
snapshot: snapshotSpy
},
on: () => {
/* EMPTY */
}
})
};
});
});
describe('When we try get only the entries with the query', () => {
it('should return an observable', async () => {
let client = new MockClient('atyala');
let query = new Query(client);
let queryObject = {
tableName: tableName,
query: [['title', 'match', 'test']]
};
let query$ = query.queryForEntries(queryObject);
expect(query$ instanceof Observable).toBeTruthy();
let result = await query$.take(1).toPromise();
let args = getListSpy.calls.mostRecent().args;
let queryString = JSON.stringify(queryObject);
expect(args[0]).toEqual(`live_${queryString}`);
expect(result instanceof Array).toBeTruthy();
expect(result).toEqual(recordNames);
});
});
describe('When we try get the data with the query', () => {
it('should return an observable', async () => {
let client = new MockClient('atyala');
let query = new MockQuery(client);
let queryObject = {
tableName: tableName,
query: [['title', 'match', 'test']]
};
let query$ = query.queryForData(queryObject);
expect(query$ instanceof Observable).toBeTruthy();
let result = await query$.take(1).toPromise();
let args = getListSpy.calls.mostRecent().args;
let queryString = JSON.stringify(queryObject);
expect(args[0]).toEqual(`live_${queryString}`);
expect(result instanceof Array).toBeTruthy();
expect(result).toEqual(['value', 'value']);
let argsSubscribe = subscribeSpy.calls.mostRecent().args;
expect(subscribeSpy).toHaveBeenCalled();
expect(argsSubscribe[0] instanceof Function).toBeTruthy();
expect(argsSubscribe[1]).toBeUndefined();
// Just check if we can get the next data
result = await query$.take(1).toPromise();
expect(result).toEqual(['value', 'value']);
});
it('should work without type definition', async () => {
let client = new MockClient('atyala');
let query = new MockQueryAny(client);
let queryObject = {
tableName: tableName,
query: [['title', 'match', 'test']]
};
let query$ = query.queryForData(queryObject);
expect(query$ instanceof Observable).toBeTruthy();
let result = await query$.take(1).toPromise();
let args = getListSpy.calls.mostRecent().args;
let queryString = JSON.stringify(queryObject);
expect(args[0]).toEqual(`live_${queryString}`);
expect(result instanceof Array).toBeTruthy();
expect(result).toEqual(['value', 'value']);
let argsSubscribe = subscribeSpy.calls.mostRecent().args;
expect(subscribeSpy).toHaveBeenCalled();
expect(argsSubscribe[0] instanceof Function).toBeTruthy();
expect(argsSubscribe[1]).toBeUndefined();
// Just check if we can get the next data
result = await query$.take(1).toPromise();
expect(result).toEqual(['value', 'value']);
});
it('should fire for empty results', async () => {
getListSpy = jasmine.createSpy('getList').and.callFake(name => {
return {
whenReady: callback => callback(),
subscribe: callback => {
callback([]);
},
unsubscribe: () => {
/* Empty */
}
};
});
let client = new MockClient('atyala');
let query = new MockQuery(client);
let queryObject = {
tableName: tableName,
query: [['title', 'match', 'noresult']]
};
let query$ = query.queryForData(queryObject);
expect(query$ instanceof Observable).toBeTruthy();
let result = await query$.take(1).toPromise();
let args = getListSpy.calls.mostRecent().args;
let queryString = JSON.stringify(queryObject);
expect(args[0]).toEqual(`live_${queryString}`);
expect(result instanceof Array).toBeTruthy();
expect(result).toEqual([]);
});
});
describe('When we try to get a page of data with the query', () => {
it('should return an observable', async () => {
let client = new MockClient('atyala');
let query = new MockQuery(client);
let queryObject = {
tableName: tableName,
query: [['title', 'match', 'test']]
};
let query$ = query.pageableQuery(queryObject, 1, 2);
expect(query$ instanceof Observable).toBeTruthy();
let result = await query$.take(1).toPromise();
let args = getListSpy.calls.mostRecent().args;
let queryString = JSON.stringify(queryObject);
expect(args[0]).toEqual(`live_${queryString}`);
expect(result instanceof Array).toBeTruthy();
expect(result).toEqual(['value']);
let argsSubscribe = subscribeSpy.calls.mostRecent().args;
expect(subscribeSpy).toHaveBeenCalled();
expect(argsSubscribe[0] instanceof Function).toBeTruthy();
expect(argsSubscribe[1]).toBeUndefined();
// Just check if we can get the next data
result = await query$.take(1).toPromise();
expect(result).toEqual(['value']);
});
it('should fire for empty results', async () => {
getListSpy = jasmine.createSpy('getList').and.callFake(name => {
return {
whenReady: callback => callback(),
subscribe: callback => {
callback([]);
},
unsubscribe: () => {
/* Empty */
}
};
});
let client = new MockClient('atyala');
let query = new MockQuery(client);
let queryObject = {
tableName: tableName,
query: [['title', 'match', 'noresult']]
};
let query$ = query.pageableQuery(queryObject, 1, 2);
expect(query$ instanceof Observable).toBeTruthy();
let result = await query$.take(1).toPromise();
let args = getListSpy.calls.mostRecent().args;
let queryString = JSON.stringify(queryObject);
expect(args[0]).toEqual(`live_${queryString}`);
expect(result instanceof Array).toBeTruthy();
expect(result).toEqual([]);
// Just check if we can get the next data
result = await query$.take(1).toPromise();
expect(result).toEqual([]);
});
});
describe('When data changed', () => {
it("should call observer's next", done => {
getListSpy = jasmine.createSpy('getList').and.callFake(name => {
return {
whenReady: callback => callback(),
subscribe: callback => {
callback(data);
setTimeout(() => {
callback(data2);
}, 100);
},
unsubscribe: () => {
/* Empty */
}
};
});
let client = new MockClient('atyala');
let query = new Query(client);
let query$ = query.queryForEntries({
tableName: tableName,
query: [['title', 'match', 'test']]
});
expect(query$ instanceof Observable).toBeTruthy();
query$.skip(1).subscribe(result => {
expect(result instanceof Array).toBeTruthy();
expect(result).toEqual(data2);
done();
}, done.fail);
});
});
it('Test the dependency creator functions', () => {
class MockQueryForCoverage extends Query<string> {
public record;
public createDependencyInstances() {
this.record = this._createRecord('name');
}
}
let list = new MockQueryForCoverage(null);
list.createDependencyInstances();
expect(list.record instanceof Record).toBeTruthy();
});
describe('When the query has an error', () => {
let discardSpy = jasmine.createSpy('discard');
class MockDeepstream extends EventEmitter {
record = {
getRecord: jasmine.createSpy('getRecord').and.callFake(record => {
return {
discard: jasmine.createSpy('discard'),
subscribe: (path, callback) => {
callback(data);
}
};
}),
getList: jasmine.createSpy('getList').and.callFake(name => {
return {
discard: discardSpy,
subscribe: callback => {
callback(data);
}
};
}),
subscribe: jasmine.createSpy('subscribeSpy')
};
removeEventListener = jasmine.createSpy('removeEventListener');
}
it('it should pass the error to the rxjs observable', done => {
class MockEventClient extends Client {
public client = new MockDeepstream();
}
let mockClient = new MockEventClient('connstr');
let query = new Query(mockClient);
let query$ = query.queryForEntries({ tableName: tableName, query: [['title', 'match', 'test']] });
let subs = query$.subscribe(
() => {
/* EMPTY */
},
err => {
expect(err).toEqual('MESSAGE');
subs.unsubscribe();
expect(mockClient.client.removeEventListener).toHaveBeenCalledWith('error');
expect(discardSpy).toHaveBeenCalled();
done();
}
);
mockClient.client.emit('error', 'ERR', 'MESSAGE');
});
});
});
<file_sep>/src/list/test/list.spec.ts
import { Observable } from 'rxjs';
import * as _ from 'lodash';
import * as uuid from 'uuid/v1';
import { EventEmitter } from 'events';
import { List } from '..';
import { Client } from '../../client';
import { Record } from '../../record';
describe('Test List', () => {
let addEntrySpy: jasmine.Spy;
let removeEntrySpy: jasmine.Spy;
let getListSpy: jasmine.Spy;
let subscribeSpy: jasmine.Spy;
let isEmptySpy = jasmine.createSpy('isEmpty').and.returnValue(false);
let client;
let snapshotSpy: jasmine.Spy;
let setDataSpy: jasmine.Spy;
let listName = 'listName';
let getRecordSpy: jasmine.Spy;
let discardSpy: jasmine.Spy;
let listOffSpy: jasmine.Spy;
let listOnSpy: jasmine.Spy;
let data = ['data1', 'data2'];
let data2 = ['data3', 'data4'];
let allData = [data, data2];
let generatedUid = uuid();
// The getListSpy.addEntry uses it
let internalList;
let recordNames = ['record1', 'record2'];
let rawList: MockRawList;
class MockClient extends Client {}
class MockRecord extends Record<string> {
static getSpy;
constructor(_client, recordName) {
super(_client, recordName);
MockRecord.getSpy = jasmine.createSpy('get').and.returnValue(Observable.of('value'));
this.get = MockRecord.getSpy;
}
}
class MockRecordAny extends Record {
static getSpy;
constructor(_client, recordName) {
super(_client, recordName);
MockRecord.getSpy = jasmine.createSpy('get').and.returnValue(Observable.of('value'));
this.get = MockRecord.getSpy;
}
}
class MockList extends List<string> {
public _createRecord(recordName) {
return new MockRecord(this._client, recordName);
}
}
class MockListAny extends List {
public _createRecord(recordName) {
return new MockRecordAny(this._client, recordName);
}
}
class MockRawList extends EventEmitter {
// constructor() {
// super();
// this.on = listOnSpy;
// }
whenReady = callback => setTimeout(() => callback(rawList), 100);
subscribe = subscribeSpy;
isEmpty = isEmptySpy;
unsubscribe() {
/* EMPTY */
}
addEntry = addEntrySpy;
removeEntry = removeEntrySpy;
discard = discardSpy;
off = listOffSpy;
}
beforeEach(() => {
subscribeSpy = jasmine.createSpy('subscribe').and.callFake(callback => {
callback(recordNames);
});
setDataSpy = jasmine.createSpy('setDataSpy').and.callFake((name, value, callback) => {
callback(null, null);
});
snapshotSpy = jasmine
.createSpy('snapshot')
.and.callFake((name, callback) => callback(null, _.flatten(allData)[snapshotSpy.calls.count() - 1]));
addEntrySpy = jasmine.createSpy('addEntry');
getRecordSpy = jasmine.createSpy('getRecordSpy');
removeEntrySpy = jasmine.createSpy('removeEntry');
discardSpy = jasmine.createSpy('discardSpy');
listOffSpy = jasmine.createSpy('listOffSpy');
listOnSpy = jasmine.createSpy('listOnSpy');
getListSpy = jasmine.createSpy('getList').and.callFake(name => {
rawList = new MockRawList();
return rawList;
});
internalList = [];
class MockRawDeepstream extends EventEmitter {
record = { getList: getListSpy, snapshot: snapshotSpy, setData: setDataSpy, getRecord: getRecordSpy };
getUid = () => generatedUid;
}
spyOn(Client, 'GetDependencies').and.callFake(() => {
return {
deepstream: jasmine.createSpy('deepstreamStub').and.returnValue(new MockRawDeepstream())
};
});
client = new MockClient('atyala');
});
describe('When we try to get the data as stream of entries', () => {
it('should return an observable', async () => {
let list = new MockList(client, listName);
let list$ = list.subscribeForEntries();
expect(list$ instanceof Observable).toBeTruthy();
let result = await list$.take(1).toPromise();
let args = getListSpy.calls.mostRecent().args;
expect(args[0]).toEqual(listName);
let argsSubscribe = subscribeSpy.calls.mostRecent().args;
expect(subscribeSpy).toHaveBeenCalled();
expect(argsSubscribe[1]).toBeTruthy();
});
it('should work without type definition', async () => {
let list = new MockListAny(client, listName);
let list$ = list.subscribeForEntries();
expect(list$ instanceof Observable).toBeTruthy();
let result = await list$.take(1).toPromise();
let args = getListSpy.calls.mostRecent().args;
expect(args[0]).toEqual(listName);
let argsSubscribe = subscribeSpy.calls.mostRecent().args;
expect(subscribeSpy).toHaveBeenCalled();
expect(argsSubscribe[1]).toBeTruthy();
});
});
describe('When we try to get the data as stream of data objects', () => {
it('should return an observable', async () => {
let list = new MockList(client, listName);
let list$ = list.subscribeForData();
expect(list$ instanceof Observable).toBeTruthy();
let result = await list$.take(1).toPromise();
expect(result).toEqual(['value', 'value']);
let args = getListSpy.calls.mostRecent().args;
expect(args[0]).toEqual(listName);
let argsSubscribe = subscribeSpy.calls.mostRecent().args;
expect(subscribeSpy).toHaveBeenCalled();
expect(argsSubscribe[0] instanceof Function).toBeTruthy();
expect(argsSubscribe[1]).toBeTruthy();
});
describe('When the list on deepstream is empty', () => {
it('should return an empty list', async () => {
let list = new MockList(client, listName);
spyOn(list, 'subscribeForEntries').and.returnValue(Observable.of([]));
let list$ = list.subscribeForData();
let result = await list$.take(1).toPromise();
expect(result).toEqual([]);
});
});
describe('When data changed', () => {
it("should call observer's next when data changed", done => {
getListSpy = jasmine.createSpy('getList').and.callFake(name => {
return {
whenReady: callback => callback(),
subscribe: callback => {
callback(data);
setTimeout(() => {
callback(data2);
}, 100);
},
unsubscribe: () => {
/* EMPTY */
},
on: () => {
/* EMPTY */
},
isEmpty: () => {
return false;
}
};
});
client = new MockClient('atyala');
let list = new List(client, listName);
let list$ = list.subscribeForEntries();
expect(list$ instanceof Observable).toBeTruthy();
list$.skip(1).subscribe(_list => {
expect(_list).toEqual(data2);
done();
}, done.fail);
});
});
});
describe('When we try to add any data', () => {
it('should do it', () => {
let list = new List(client, listName);
list.addEntry('5');
let args = addEntrySpy.calls.mostRecent().args;
expect(args[0]).toEqual('5');
});
});
describe('When we try to remove any data', () => {
it('should do it', () => {
let list = new List(client, listName);
list.removeEntry('5');
let args = removeEntrySpy.calls.mostRecent().args;
expect(args[0]).toEqual('5');
});
});
describe('When adding data with addRecord', () => {
let dataToAdd = { foo: 'bar' };
let list;
beforeEach(() => {
list = new List(client, 'testList');
});
it('Should add an entry to the list and insert the data', async () => {
await list.addRecord(dataToAdd).toPromise();
expect(addEntrySpy).toHaveBeenCalledWith(`testList/${generatedUid}`, undefined);
let args = setDataSpy.calls.mostRecent().args;
expect(args[0]).toEqual(`testList/${generatedUid}`);
expect(args[1]).toEqual(dataToAdd);
expect(args[2] instanceof Function).toBeTruthy();
});
it('Should add an entry to the list and insert the data to the specified index if given', async () => {
let index = 2;
await list.addRecord(dataToAdd, index).toPromise();
expect(addEntrySpy).toHaveBeenCalledWith(`testList/${generatedUid}`, index);
});
});
describe('When calling discard', () => {
it('should call the raw deepstream discard function', () => {
let list = new List(client, 'testList');
list.discard();
expect(discardSpy).toHaveBeenCalled();
});
});
it('Test the dependency creator functions', () => {
class MockListForCoverage extends List<string> {
public record;
public createDependencyInstances() {
this.record = this._createRecord('name');
}
}
let list = new MockListForCoverage(client, 'listname');
list.createDependencyInstances();
expect(list.record instanceof Record).toBeTruthy();
});
describe('When subscribing for the "entry-added" event by recordAdded', () => {
it('should return the new entry', done => {
const position = 898;
const entryName = 'entryName';
let list = new MockList(client, listName);
spyOn(list, '_createRecord').and.callThrough();
let subscription = list.recordAdded().subscribe(newRecord => {
expect(newRecord).toEqual({ data: 'value', position: position });
expect(list._createRecord).toHaveBeenCalledWith(entryName);
subscription.unsubscribe();
let args = listOffSpy.calls.mostRecent().args;
expect(args[0]).toEqual('entry-added');
expect(args[1] instanceof Function).toBeTruthy();
done();
});
rawList.emit('entry-added', entryName, position);
});
});
it('should throw error when a list operation fails', done => {
let list = new MockList(client, listName);
list.subscribeForEntries().subscribe(
() => {
/* EMPTY */
},
err => {
expect('TESTERROR').toEqual(err);
done();
}
);
client.errors$.next('TESTERROR');
});
it('isEmpty should return true when the list is empty', async done => {
let list = new MockList(client, listName);
rawList.isEmpty = jasmine.createSpy('isEmpty').and.returnValue(true);
let res$ = list.isEmpty().subscribe(res => {
expect(res).toBeTruthy();
expect(res$.closed);
done();
});
});
it('isEmpty should return false when the list is not empty', async done => {
let list = new MockList(client, listName);
rawList.isEmpty = jasmine.createSpy('isEmpty').and.returnValue(false);
let res$ = list.isEmpty().subscribe(res => {
expect(res).toBeFalsy();
expect(res$.closed);
done();
});
});
});
<file_sep>/src/event/index.ts
import { Observable, Observer } from 'rxjs';
import { Client } from '../client';
import { Logger } from '../logger';
export class Event<T = any> {
constructor(private _client: Client, private _topic: string) {
/* EMPTY */
}
public receive(): Observable<T> {
return Observable.create(observer => {
this._client.client.event.subscribe(this._topic, observer.next);
return () => this._client.client.event.unsubscribe(this._topic);
});
}
public emit(data: T) {
this._client.client.event.emit(this._topic, data);
}
}
|
8bd0b71b6ced32ccb68452e077ec81d49e232ae4
|
[
"Markdown",
"TypeScript"
] | 13
|
TypeScript
|
gergelykoncz/deepstream-rxjs
|
2df417109bc72eba276d8061e17daba44a1c5d45
|
4e3c15097954ee54de9a0912354eadd244a7cc43
|
refs/heads/main
|
<file_sep>import sys
num1 = int(input("Enter number 1:"))
num2 = int(input("Enter number 2:"))
n = int(input("Number of registers:"))
def checknumber(val):
global n
if val > 2**(n-1)-1 or val < -(2**(n-1)):
print("Input value out of range ")
print("Input must lie between " + str(2**(n-1)-1) + " to " + str(-(2**(n-1))))
return -1000
return val
def converttobin(s):
while len(s) != n:
s = "0" + s
return s
def bincheck(s):
if len(s) == n:
return s
elif len(s) > n:
s = s[::-1]
s[:n]
s[::-1]
return s
elif len(s) < n:
return converttobin(s)
def TwosCompliment (s):
#help from geeksforgeeks
n = len(s)
i = n-1
while i >= 0:
if s[i] == '1':
break
i = i-1
if i == -1:
return '1' + s
k = i-1
while k >= 0:
if s[k] == '1':
s = list(s)
s[k] = '0'
s = ''.join(s)
else:
s = list(s)
s[k] = '1'
s = ''.join(s)
k -= 1
return s
def asr():
global ac
global q0
global q1
global plusM
global minnusM
statement = ac + q1 + q0
statement= statement[:-1]
if statement[0]=="1":
statement= "1"+statement
else:
statement= "0"+ statement
return statement
def summ( val):
global ac
global q0
global q1
global plusM
global minnusM
temp = "0"*n
i = n-1
while(i>-1):
if i>0:
if ac[i] == "0":
if val[i] == "0":
if temp[i] == "0":
temp = temp[:i] + "0" + temp[i + 1:]
elif temp[i] == "1":
temp = temp[:i] + "1" + temp[i + 1:]
elif val[i] == "1":
if temp[i] == "0":
temp = temp[:i] + "1" + temp[i + 1:]
elif temp[i] == "1":
temp = temp[:i] + "0" + temp[i + 1:]
temp = temp[:i-1] + "1" + temp[i :]
elif ac[i] == "1":
if val[i] == "0":
if temp[i] == "0":
temp = temp[:i] + "1" + temp[i + 1:]
elif temp[i] == "1":
temp = temp[:i] + "0" + temp[i + 1:]
temp = temp[:i-1] + "1" + temp[i :]
elif val[i] == "1":
if temp[i] == "0":
temp = temp[:i] + "0" + temp[i + 1:]
temp = temp[:i-1] + "1" + temp[i :]
elif temp[i] == "1":
temp = temp[:i] + "1" + temp[i + 1:]
temp = temp[:i-1] + "1" + temp[i :]
elif i==0:
if ac[i] == "0":
if val[i] == "0":
if temp[i] == "0":
temp = temp[:i] + "0" + temp[i + 1:]
elif temp[i] == "1":
temp = temp[:i] + "1" + temp[i + 1:]
elif val[i] == "1":
if temp[i] == "0":
temp = temp[:i] + "1" + temp[i + 1:]
elif temp[i] == "1":
temp = temp[:i] + "0" + temp[i + 1:]
elif ac[i] == "1":
if val[i] == "0":
if temp[i] == "0":
temp = temp[:i] + "1" + temp[i + 1:]
elif temp[i] == "1":
temp = temp[:i] + "0" + temp[i + 1:]
elif val[i] == "1":
if temp[i] == "0":
temp = temp[:i] + "0" + temp[i + 1:]
elif temp[i] == "1":
temp = temp[:i] + "1" + temp[i + 1:]
i = i - 1
ac =temp
def whichFlow():
global ac
global q0
global q1
global plusM
global minnusM
checkS = q1[-1] + q0
if checkS == "10":
summ( minnusM)
return asr()
elif checkS == "01":
summ(plusM)
return asr()
else:
return asr()
final_check = ""
final = True
if checknumber(num1) == -1000 or checknumber(num2) == -1000:
final = False
if num1>0 and num2>0:
plusM = str(bin(num1))
plusM = plusM[2:]
Q = str(bin(num2))
Q = Q[2:]
plusM = bincheck(plusM)
Q = bincheck(Q)
minnusM = TwosCompliment(plusM)
final_check = "++"
elif num1>0 and num2<0:
num2 = num2*-1
plusM = str(bin(num1))
plusM = plusM[2:]
Q = str(bin(num2))
Q = Q[2:]
plusM = bincheck(plusM)
Q = bincheck(Q)
minnusM = plusM
final_check = "+-"
plusM = TwosCompliment(minnusM)
elif num1<0 and num2>0:
num1 = num1*-1
plusM = str(bin(num1))
plusM = plusM[2:]
Q = str(bin(num2))
Q = Q[2:]
plusM = bincheck(plusM)
Q = bincheck(Q)
minnusM = plusM
final_check = "-+"
plusM=TwosCompliment(minnusM)
else:
num1 = num1 * -1
num2 = num2 * -1
plusM = str(bin(num1))
plusM = plusM[2:]
Q = str(bin(num2))
Q = Q[2:]
plusM = bincheck(plusM)
Q = bincheck(Q)
minnusM = plusM
plusM= TwosCompliment(minnusM)
final_check = "--"
Q=TwosCompliment(Q)
q0 = "0"
q1 = Q
ac = "0"
ac = bincheck(ac)
i=0
while final and i<n:
i=i+1
statement= whichFlow()
ac=statement[0:n]
q1=statement[n:2*n]
q0=statement[-1]
print(ac,q1,q0)
if final:
ans= ac+q1
if final_check == "++" :
print("+",int(ans,2))
elif final_check == "-+" :
print("-",int(TwosCompliment(ans),2))
elif final_check == "+-":
print("-",int(TwosCompliment(ans),2))
elif final_check=="--":
print("+",int(ans,2))
sys.exit()
|
e38315d99c02b9361c8e27099111fd99d217c03c
|
[
"Python"
] | 1
|
Python
|
Sambhav307/Booth-Multiplication-Algorithm
|
b2a4505956bca60ea7c7f7653414480058a4fa11
|
fed561819f983fc7daac693ba852529748cffe09
|
refs/heads/master
|
<repo_name>lhdgriver/leetcode<file_sep>/easy/count_and_say_38.cpp
class Solution {
public:
string countAndSay(int n) {
if (n == 1) return "1";
string prev_say = "1";
string now_say = "";
for(int turn = 2; turn <= n; turn++) {
char prev_char;
int prev_count = 0;
for(int i = 0; i < prev_say.length(); i++) {
if (i == 0) {
prev_char = prev_say[i];
prev_count = 1;
continue;
}
if (prev_say[i] == prev_char) {
prev_count++;
continue;
} else {
now_say += to_string(prev_count) + prev_char;
prev_char = prev_say[i];
prev_count = 1;
continue;
}
}
now_say += to_string(prev_count) + prev_char;
prev_say = now_say;
now_say = "";
}
return prev_say;
}
};
<file_sep>/easy/two_sum_2_167.cpp
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int start = 0, end = numbers.size() - 1;
vector<int> ret;
while(start < end) {
int sum = numbers[start] + numbers[end];
if (sum == target) {
ret.push_back(start+1);
ret.push_back(end+1);
return ret;
} else if (sum < target) {
start++;
continue;
} else {
end--;
continue;
}
}
return ret;
}
};
<file_sep>/easy/intersection_of_two_arrays_349.cpp
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
vector<int> ret;
set<int> s1 = get_set(nums1);
set<int> s2 = get_set(nums2);
for(set<int>::iterator it=s1.begin(); it!=s1.end(); it++) {
if (s2.find(*it) != s2.end())
ret.push_back(*it);
}
return ret;
}
private:
set<int> get_set(vector<int>& nums) {
set<int> ret;
for(int i=0; i<nums.size(); i++)
ret.insert(nums[i]);
return ret;
}
};
<file_sep>/easy/count_numbers_with_unique_digits_357.cpp
#include<iostream>
using namespace std;
class Solution {
public:
int countNumbersWithUniqueDigits(int n) {
if (n == 0) return 1;
if (n == 1) return 10;
int ret = 10;
int prev_prod = 9;
for(int i = 2; i <= n; i++) {
if (i == 11) break;
prev_prod *= (10 - i + 1);
ret += prev_prod;
}
return ret;
}
};
int main() {
Solution s;
cout << s.countNumbersWithUniqueDigits(2) << endl;
cout << s.countNumbersWithUniqueDigits(3) << endl;
return 0;
}
<file_sep>/easy/power_of_three_326.cpp
class Solution {
public:
bool isPowerOfThree(int n) {
double lg3 = log(n) / log(3);
return abs(lg3 - round(lg3)) < 0.00000000001;
}
};
<file_sep>/easy/plus_one_66.cpp
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
vector<int> ret;
int carry = 1;
for(int i = digits.size() - 1; i >= 0; i--) {
ret.push_back((carry + digits[i]) % 10);
carry = (carry + digits[i]) / 10;
}
if (carry == 1)
ret.push_back(1);
std::reverse(ret.begin(), ret.end());
return ret;
}
};
<file_sep>/easy/bulb_switcher_319.cpp
class Solution {
public:
int bulbSwitch(int n) {
int ret = int(sqrt(n));
return ret;
}
};
<file_sep>/easy/length_of_last_word_58.cpp
class Solution {
public:
int lengthOfLastWord(string s) {
if (s == "") return 0;
int word_length = 0;
int end = s.length() - 1;
while(end >=0 && s[end] == ' ') {
end--;
}
for(int i = 0; i <= end; i++) {
if (s[i] == ' ') {
word_length = 0;
continue;
}
word_length++;
}
return word_length;
}
};
<file_sep>/easy/house_robber_198.cpp
class Solution {
public:
int rob(vector<int>& nums) {
if (nums.size() == 0) return 0;
if (nums.size() == 1) return nums[0];
if (nums.size() == 2) return max(nums[0], nums[1]);
int max_profit = 0;
int prev_2 = nums[0];
int prev_1 = max(nums[0], nums[1]);
for(int i = 2; i < nums.size(); i++) {
int now = max(nums[i] + prev_2, prev_1);
if (now > max_profit) max_profit = now;
prev_2 = prev_1;
prev_1 = now;
}
return max_profit;
}
};
<file_sep>/easy/min_stack_155.cpp
class MinStack {
public:
MinStack() {
}
void push(int x) {
master_stack.push(x);
if (min_stack.empty() || min_stack.top() > x)
min_stack.push(x);
else
min_stack.push(min_stack.top());
}
void pop() {
master_stack.pop();
min_stack.pop();
}
int top() {
return master_stack.top();
}
int getMin() {
return min_stack.top();
}
private:
stack<int> master_stack;
stack<int> min_stack;
};
<file_sep>/easy/top_k_frequent_elements_347.cpp
class Solution(object):
def topKFrequent(self, nums, k):
from collections import defaultdict
count_map = defaultdict(int)
for _ in nums:
count_map[_] += 1
l = sorted(count_map.items(), key=lambda _: _[1], reverse=True)
ret = []
for _ in range(k):
ret.append(l[_][0])
return ret
<file_sep>/easy/integer_break_343.cpp
class Solution {
public:
int integerBreak(int n) {
if (n == 2) return 1;
if (n == 3) return 2;
if (n % 3 == 0) {
return pow_of_3(n/3);
}
if (n % 3 == 1) {
return 4 * pow_of_3(n/3-1);
}
if (n % 3 == 2) {
return 2 * pow_of_3(n/3);
}
return 0;
}
private:
int pow_of_3(int n) {
if (n == 0) return 1;
int ret = 1;
while(n--) ret *= 3;
return ret;
}
};
<file_sep>/easy/majority_element_169.cpp
class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int, int> count_map;
for(int i = 0; i < nums.size(); i++) {
if (count_map.find(nums[i]) == count_map.end())
count_map[nums[i]] = 0;
count_map[nums[i]]++;
}
for(unordered_map<int, int>::iterator it = count_map.begin(); it != count_map.end(); it++) {
if (it->second > nums.size()/2) return it->first;
}
return 0;
}
};
<file_sep>/easy/bulls_and_cows_299.cpp
class Solution {
public:
string getHint(string secret, string guess) {
int same_num = 0;
int diff_num = 0;
unordered_map<char, int> a_count_map;
unordered_map<char, int> b_count_map;
for(int i = 0; i < secret.length(); i++) {
if (secret[i] == guess[i])
same_num++;
else {
if (a_count_map.find(secret[i]) == a_count_map.end())
a_count_map[secret[i]] = 0;
a_count_map[secret[i]]++;
if (b_count_map.find(guess[i]) == b_count_map.end())
b_count_map[guess[i]] = 0;
b_count_map[guess[i]]++;
}
}
for(unordered_map<char, int>::iterator it = a_count_map.begin(); it != a_count_map.end(); it++) {
if (b_count_map.find(it->first) != b_count_map.end()) {
diff_num += min(it->second, b_count_map[it->first]);
}
}
string ret;
ret = to_string(same_num) + "A" + to_string(diff_num) + "B";
return ret;
}
};
<file_sep>/easy/power_of_four_342.cpp
class Solution {
public:
bool isPowerOfFour(int num) {
double lg4 = log(num) / log(4);
return abs(lg4 - round(lg4)) < 0.00000000001;
}
};
<file_sep>/easy/zigzag_conversion_6.cpp
class Solution {
public:
string convert(string s, int numRows) {
vector<vector<char>> col_vec;
string ret;
for(int i = 0; i < numRows; i++) {
vector<char> tmp;
col_vec.push_back(tmp);
}
int row_num = 0;
int direct = 1;
for(int i = 0; i < s.length(); i++) {
col_vec[row_num].push_back(s[i]);
if (numRows == 1)
direct = 0;
else if (row_num == 0)
direct = 1;
else if (row_num == numRows - 1)
direct = -1;
row_num += direct;
}
for(int i = 0; i < numRows; i++) {
for(int j = 0; j < col_vec[i].size(); j++)
ret = ret + col_vec[i][j];
}
return ret;
}
};
<file_sep>/easy/move_zeroes_283.cpp
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int put_non_zero_pos = 0;
int index = 0;
while(index < nums.size()){
if (nums[index] != 0) {
swap(nums[put_non_zero_pos], nums[index]);
put_non_zero_pos++;
}
index++;
}
}
};
<file_sep>/easy/count_primes_204.cpp
class Solution {
public:
int countPrimes(int n) {
vector<int> is_prime(n, 1);
int prime_num = 0;
for(int i = 2; i < n; i++) {
if (is_prime[i] == 0) continue;
prime_num++;
for(int j = 2*i; j < n; j += i)
is_prime[j] = 0;
}
return prime_num;
}
};
<file_sep>/easy/range_sum_query_immutable_303.cpp
class NumArray {
public:
NumArray(vector<int> &nums) {
int sum = 0;
for(int i = 0; i < nums.size(); i++) {
sum += nums[i];
sum_vec.push_back(sum);
}
}
int sumRange(int i, int j) {
if (i == 0) return sum_vec[j];
return sum_vec[j] - sum_vec[i-1];
}
private:
vector<int> sum_vec;
};
<file_sep>/easy/isomorphic_strings_205.cpp
class Solution {
public:
bool isIsomorphic(string s, string t) {
set<char> distinct_t;
unordered_map<char, char> m;
for(int i = 0; i < s.length(); i++) {
if (m.find(s[i]) == m.end()) {
if (distinct_t.find(t[i]) != distinct_t.end())
return false;
distinct_t.insert(t[i]);
m[s[i]] = t[i];
} else {
if (m[s[i]] != t[i]) return false;
}
}
return true;
}
};
<file_sep>/easy/implement_queue_using_stacks_232.cpp
class Queue{
public:
void push(int x) {
main_stack.push(x);
}
void pop(void) {
dump(main_stack, slave_stack);
slave_stack.pop();
dump(slave_stack, main_stack);
}
int peek(void) {
int ret;
dump(main_stack, slave_stack);
ret = slave_stack.top();
dump(slave_stack, main_stack);
return ret;
}
bool empty(void) {
return main_stack.empty();
}
private:
stack<int> main_stack, slave_stack;
void dump(stack<int>& from_stack, stack<int>& to_stack) {
while(!from_stack.empty()) {
to_stack.push(from_stack.top());
from_stack.pop();
}
}
};
<file_sep>/easy/pascals_triangle_118.cpp
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<int> now;
vector<vector<int>> prev_result;
if (numRows == 0) {
return prev_result;
}
if (numRows == 1){
now.push_back(1);
prev_result.push_back(now);
return prev_result;
}
prev_result = generate(numRows-1);
vector<int> prev = prev_result[prev_result.size()-1];
for(int i = 0; i < prev.size(); i++) {
if (i==0) {
now.push_back(1);
continue;
}
now.push_back(prev[i-1] + prev[i]);
}
now.push_back(1);
prev_result.push_back(now);
return prev_result;
}
};
<file_sep>/easy/contains_duplicate_2_219.cpp
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> pos_map;
for(int i = 0; i < nums.size(); i++) {
if (pos_map.find(nums[i]) == pos_map.end()) {
pos_map[nums[i]] = i;
continue;
}
if (i - pos_map[nums[i]] <= k) return true;
pos_map[nums[i]] = i;
}
return false;
}
};
<file_sep>/easy/rectangle_area_223.cpp
class Solution {
public:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int area_1 = (C-A)*(D-B);
int area_2 = (G-E)*(H-F);
int overlap = computeOverlap(A, B, C, D, E, F, G, H);
return area_1 + area_2 - overlap;
}
private:
int computeOverlap(int A, int B, int C, int D, int E, int F, int G, int H) {
if (F >= D || B >= H || C <= E || G <= A)
return 0;
int length = min(G, C) - max(A, E);
int height = min(D, H) - max(B, F);
int area = length * height;
return area;
}
};
<file_sep>/easy/happy_number_202.cpp
#include<iostream>
#include<set>
using namespace std;
class Solution {
public:
bool isHappy(int n) {
set<int> occur_set;
while(n != 1) {
if (occur_set.find(n) != occur_set.end())
return false;
occur_set.insert(n);
n = calcu(n);
}
return true;
}
private:
int calcu(int n){
int sum = 0;
while(n) {
int t = n % 10;
sum += t*t;
n /= 10;
}
return sum;
}
};
int main() {
Solution s;
cout << s.isHappy(19) << endl;
return 0;
}
<file_sep>/easy/power_of_two_231.cpp
class Solution {
public:
bool isPowerOfTwo(int n) {
double lg2 = log(n) / log(2);
return abs(lg2 - round(lg2)) < 0.00000000001;
}
};
<file_sep>/easy/binary_tree_level_order_traversal_2_107.cpp
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> ret = helper(root);
std::reverse(ret.begin(), ret.end());
return ret;
}
private:
vector<vector<int>> helper(TreeNode* root) {
vector<vector<int>> ret;
vector<int> tmp;
if (root == NULL) {
return ret;
}
vector<vector<int>> left_result = helper(root->left);
vector<vector<int>> right_result = helper(root->right);
tmp.push_back(root->val);
ret.push_back(tmp);
int left_index = 0, right_index = 0;
while(left_index < left_result.size() && right_index < right_result.size()) {
vector<int> left_v = left_result[left_index];
vector<int> right_v = right_result[right_index];
left_v.insert(left_v.end(), right_v.begin(), right_v.end());
ret.push_back(left_v);
left_index++;
right_index++;
}
while(left_index < left_result.size()) {
vector<int> left_v = left_result[left_index];
ret.push_back(left_v);
left_index++;
}
while(right_index < right_result.size()) {
vector<int> right_v = right_result[right_index];
ret.push_back(right_v);
right_index++;
}
return ret;
}
};
<file_sep>/easy/rotate_array_189.cpp
class Solution {
public:
void rotate(vector<int>& nums, int k) {
k = k % nums.size();
vec_swap(nums, nums.size() - k, nums.size() - 1);
vec_swap(nums, 0, nums.size() - k - 1);
vec_swap(nums, 0, nums.size() - 1);
}
private:
void vec_swap(vector<int>& nums, int start, int end) {
while(start < end) {
swap(nums[start], nums[end]);
start++;
end--;
}
}
};
<file_sep>/easy/linked_list_random_node_382.cpp
class Solution {
public:
Solution(ListNode* head) {
fake_head = head;
}
int getRandom() {
ListNode* head = fake_head;
int ret = head->val;
head = head->next;
int count = 2;
while(head != NULL) {
if (rand() % count == 0)
ret = head->val;
count++;
head = head->next;
}
return ret;
}
private:
ListNode* fake_head;
};
<file_sep>/easy/contains_duplicate_217.cpp
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
set<int> occur_set;
for(int i = 0; i < nums.size(); i++) {
if (occur_set.find(nums[i]) != occur_set.end())
return true;
occur_set.insert(nums[i]);
}
return false;
}
};
<file_sep>/easy/number_of_1_bits_191.cpp
class Solution {
public:
int hammingWeight(uint32_t n) {
int num = 0;
while(n) {
num += n % 2;
n = n >> 1;
}
return num;
}
};
<file_sep>/easy/remove_nth_node_from_end_of_list_19.cpp
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* fake_head = new ListNode(0);
fake_head->next = head;
ListNode* p1 = fake_head;
ListNode* p2 = fake_head;
while(n--) {
p2 = p2->next;
}
while(p2->next != NULL) {
p2 = p2->next;
p1 = p1->next;
}
p1->next = p1->next->next;
p1 = fake_head->next;
delete fake_head;
return p1;
}
};
<file_sep>/easy/valid_parentheses_20.cpp
class Solution {
public:
bool isValid(string s) {
stack<char> parentheses_stack;
unordered_map<char, char> pair_map;
pair_map[')'] = '(';
pair_map[']'] = '[';
pair_map['}'] = '{';
for(int i = 0; i < s.length(); i++) {
if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
parentheses_stack.push(s[i]);
continue;
}
if (parentheses_stack.empty() || parentheses_stack.top() != pair_map[s[i]]) return false;
parentheses_stack.pop();
}
return parentheses_stack.empty();
}
};
<file_sep>/easy/word_pattern_290.cpp
class Solution {
public:
bool wordPattern(string pattern, string str) {
unordered_map<char, string> w_str_map;
vector<string> str_vec = split_str(str);
if (pattern.length() != str_vec.size()) return false;
set<string> occur_set;
for (int i = 0; i < pattern.size(); i++) {
if (w_str_map.find(pattern[i]) == w_str_map.end()) {
w_str_map[pattern[i]] = str_vec[i];
if (occur_set.find(str_vec[i]) != occur_set.end())
return false;
occur_set.insert(str_vec[i]);
} else {
if (w_str_map[pattern[i]] != str_vec[i])
return false;
}
}
return true;
}
private:
vector<string> split_str(string str) {
vector<string> ret;
int last_index = 0;
for(int i = 0; i < str.length(); i++) {
if (str[i] == ' ') {
ret.push_back(str.substr(last_index, i-last_index));
last_index = i+1;
}
}
ret.push_back(str.substr(last_index, str.length()-last_index));
return ret;
}
};
<file_sep>/easy/first_unique_character_in_a_string_387.cpp
class Solution {
public:
int firstUniqChar(string s) {
unordered_map<char, int> count_map;
for(int i = 0; i < s.length(); i++) {
if (count_map.find(s[i]) == count_map.end())
count_map[s[i]] = 0;
count_map[s[i]]++;
}
for(int i = 0; i < s.length(); i++) {
if (count_map[s[i]] == 1)
return i;
}
return -1;
}
};
<file_sep>/easy/intersection_of_two_arrays_2_350.cpp
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
vector<int> ret;
unordered_map<int, int> cnt_map_1 = get_count_map(nums1);
unordered_map<int, int> cnt_map_2 = get_count_map(nums2);
for(unordered_map<int, int>::iterator it = cnt_map_1.begin(); it != cnt_map_1.end(); it++) {
if (cnt_map_2.find(it->first) == cnt_map_2.end())
continue;
int count = min(it->second, cnt_map_2[it->first]);
while(count--) {
ret.push_back(it->first);
}
}
return ret;
}
private:
unordered_map<int, int> get_count_map(vector<int>& nums) {
unordered_map<int, int> count_map;
for(int i = 0; i < nums.size(); i++) {
if (count_map.find(nums[i]) == count_map.end())
count_map[nums[i]] = 0;
count_map[nums[i]]++;
}
return count_map;
}
};
<file_sep>/easy/binary_tree_level_order_traversal_102.cpp
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ret;
if (root == NULL) return ret;
vector<vector<int>> left_result = levelOrder(root->left);
vector<vector<int>> right_result = levelOrder(root->right);
vector<int> now;
now.push_back(root->val);
ret.push_back(now);
int left_index = 0, right_index = 0;
while(left_index < left_result.size() && right_index < right_result.size()) {
vector<int> left_v = left_result[left_index];
vector<int> right_v = right_result[right_index];
left_v.insert(left_v.end(), right_v.begin(), right_v.end());
ret.push_back(left_v);
left_index++;
right_index++;
}
while(left_index < left_result.size()) {
vector<int> left_v = left_result[left_index];
ret.push_back(left_v);
left_index++;
}
while(right_index < right_result.size()) {
vector<int> right_v = right_result[right_index];
ret.push_back(right_v);
right_index++;
}
return ret;
}
};
<file_sep>/easy/swap_nodes_in_pairs_24.cpp
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (head == NULL || head->next == NULL) return head;
ListNode* fake_head = new ListNode(0);
fake_head->next = head;
head = fake_head;
while(true) {
if (head->next == NULL) break;
if (head->next->next == NULL) break;
ListNode* tmp = head->next;
head->next = head->next->next;
tmp->next = tmp->next->next;
head->next->next = tmp;
head = head->next->next;
}
return fake_head->next;
}
};
<file_sep>/easy/reverse_linked_list_206.cpp
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* reverseHead = NULL;
ListNode* remainHead = head;
while(remainHead){
ListNode* tmp = remainHead->next;
remainHead->next = reverseHead;
reverseHead = remainHead;
remainHead = tmp;
}
return reverseHead;
}
};
<file_sep>/easy/palindrome_number_9.cpp
class Solution{
public:
bool isPalindrome(int x) {
if (x < 0) return false;
int len = int(log10(x));
int diver = int(pow(10, len));
while(x) {
int first = x / diver;
int remain = x % 10;
if (first != remain) return false;
x = x - first * diver;
x /= 10;
diver /= 100;
}
return true;
}
};
<file_sep>/easy/intersection_of_two_linked_lists_160.cpp
class Solution {
public:
ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
int length_a = getLength(headA);
int length_b = getLength(headB);
if (length_a < length_b) {
for(int i = 0; i < length_b - length_a; i++) {
headB = headB->next;
}
}
if (length_a > length_b) {
for(int i = 0; i < length_a - length_b; i++) {
headA = headA->next;
}
}
while(headA != headB) {
headA = headA->next;
headB = headB->next;
}
return headA;
}
private:
int getLength(ListNode* head) {
int length = 0;
while(head) {
length++;
head = head->next;
}
return length;
}
};
<file_sep>/easy/ransom_note_383.cpp
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
unordered_map<char, int> count_map = construct_count_map(magazine);
for(int i=0; i<ransomNote.length(); i++) {
if (count_map.find(ransomNote[i]) == count_map.end())
return false;
if (count_map[ransomNote[i]] == 0)
return false;
count_map[ransomNote[i]]--;
}
return true;
}
private:
unordered_map<char, int> construct_count_map(string magazine) {
unordered_map<char, int> ret;
for(int i=0; i<magazine.size(); i++) {
if (ret.find(magazine[i]) == ret.end())
ret[magazine[i]] = 0;
ret[magazine[i]]++;
}
return ret;
}
};
<file_sep>/easy/binary_tree_preorder_traversal_144.cpp
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> ret;
if (root == NULL) return ret;
ret.push_back(root->val);
if (root->left != NULL) {
vector<int> tmp = preorderTraversal(root->left);
ret.insert(ret.end(), tmp.begin(), tmp.end());
}
if (root->right != NULL) {
vector<int> tmp = preorderTraversal(root->right);
ret.insert(ret.end(), tmp.begin(), tmp.end());
}
return ret;
}
};
<file_sep>/easy/implement_stack_using_queues_225.cpp
class Stack {
public:
void push(int x) {
master_queue.push(x);
}
void pop() {
while(master_queue.size() > 1) {
slave_queue.push(master_queue.front());
master_queue.pop();
}
master_queue.pop();
while(slave_queue.size() > 0) {
master_queue.push(slave_queue.front());
slave_queue.pop();
}
}
int top() {
int ret;
while(master_queue.size() > 0) {
ret = master_queue.front();
slave_queue.push(ret);
master_queue.pop();
}
while(slave_queue.size() > 0) {
master_queue.push(slave_queue.front());
slave_queue.pop();
}
return ret;
}
bool empty() {
return master_queue.empty();
}
private:
queue<int> master_queue;
queue<int> slave_queue;
};
<file_sep>/easy/palindrome_linked_list_234.cpp
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (head == NULL || head->next == NULL) return true;
int length = getLength(head);
ListNode* first_half_head = head;
for(int i = 0; i < length / 2 - 1; i++) {
head = head->next;
}
ListNode* sec_half_head = reverseList(head->next);
head->next = NULL;
while(first_half_head != NULL && sec_half_head != NULL) {
if (first_half_head->val != sec_half_head->val) return false;
first_half_head = first_half_head->next;
sec_half_head = sec_half_head->next;
}
return true;
}
private:
ListNode* reverseList(ListNode* head) {
if (head == NULL) return NULL;
ListNode* new_head = NULL;
while(head != NULL) {
ListNode* tmp = head->next;
head->next = new_head;
new_head = head;
head = tmp;
}
return new_head;
}
int getLength(ListNode* head) {
int length = 0;
while(head != NULL) {
length++;
head = head->next;
}
return length;
}
};
<file_sep>/easy/linked_list_cycle_141.cpp
class Solution {
public:
bool hasCycle(ListNode *head) {
if (head == NULL) return false;
if (head->next == NULL) return false;
ListNode* step_1 = head;
ListNode* step_2 = head->next;
while(true) {
if (step_1 == step_2) return true;
if (step_2->next == NULL) break;
if (step_2->next->next ==NULL) break;
step_2 = step_2->next->next;
step_1 = step_1->next;
}
return false;
}
};
<file_sep>/easy/reverse_vowels_of_a_string_345.cpp
#include<iostream>
using namespace std;
class Solution {
public:
string reverseVowels(string s) {
int start = 0, end = s.length()-1;
while(start < end) {
while(start <= end && !is_vowel(s[start]))
start++;
while(start <= end && !is_vowel(s[end]))
end--;
if (start >= end) break;
swap(s[start], s[end]);
start++;
end--;
}
return s;
}
private:
bool is_vowel(char c) {
if (c == 'a' || c == 'A' || c == 'e' || c == 'E' || c == 'i' || c == 'I' || c == 'o' || c == 'O' || c == 'u' || c == 'U')
return true;
return false;
}
};
int main()
{
Solution s;
cout << s.reverseVowels("hello") << endl;
return 0;
}
<file_sep>/easy/excel_sheet_column_number_171.cpp
class Solution {
public:
int titleToNumber(string s) {
int carry = 1;
int sum = 0;
for(int i=s.length()-1; i>=0; i--){
sum += carry * get_num(s[i]);
carry *= 26;
}
return sum;
}
private:
int get_num(char c){
return c-'A'+1;
}
};
<file_sep>/easy/remove_linked_list_elements_203.cpp
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if (head == NULL) return NULL;
ListNode* fake_head = new ListNode(0);
fake_head->next = head;
head = fake_head;
while(head->next != NULL) {
if (head->next->val != val) {
head = head->next;
continue;
}
head->next = head->next->next;
}
head = fake_head->next;
delete fake_head;
return head;
}
};
<file_sep>/easy/sum_of_two_integers_371.cpp
#include<iostream>
using namespace std;
class Solution {
public:
int getSum(int a, int b) {
int carry = (a & b) << 1;
int remain = a ^ b;
while(carry != 0) {
int tmp = remain;
remain = remain ^ carry;
carry = (tmp & carry) << 1;
}
return remain;
}
};
int main()
{
Solution s;
cout << s.getSum(1, 2) << endl;
cout << s.getSum(5, 3) << endl;
cout << s.getSum(-5, 3) << endl;
return 0;
}
<file_sep>/easy/implement_strstr_28.cpp
#include<iostream>
using namespace std;
class Solution {
public:
int strStr(string haystack, string needle) {
if (haystack.length() < needle.length()) return -1;
for(int i = 0; i <= haystack.length() - needle.length(); i++) {
bool found = true;
for(int j = 0; j < needle.length(); j++) {
if (haystack[i+j] != needle[j]) {
found = false;
break;
}
}
if (found == true)
return i;
}
return -1;
}
};
int main() {
Solution s;
cout << s.strStr("", "a") << endl;
return 0;
}
<file_sep>/easy/single_number_2_137.cpp
class Solution {
public:
int singleNumber(vector<int>& nums) {
int digits[32];
memset(digits, 0, sizeof(digits));
for(int i = 0; i < nums.size(); i++) {
for(int j = 0; j < 32; j++) {
digits[j] = (digits[j] + (nums[i] >> j & 1)) % 3;
}
}
int ret = 0, carry = 1;
for(int i = 0; i < 32; i++) {
if (digits[i] != 0) {
ret += carry;
}
carry = carry << 1;
}
return ret;
}
};
<file_sep>/easy/binary_tree_paths_257.cpp
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> ret;
if (root == NULL) return ret;
if (root->left == NULL && root->right == NULL) {
ret.push_back(to_string(root->val));
return ret;
}
vector<string> children_result;
if (root->left != NULL) {
vector<string> tmp = binaryTreePaths(root->left);
children_result.insert(children_result.end(), tmp.begin(), tmp.end());
}
if (root->right != NULL) {
vector<string> tmp = binaryTreePaths(root->right);
children_result.insert(children_result.end(), tmp.begin(), tmp.end());
}
for(int i = 0; i < children_result.size(); i++) {
string s = children_result[i];
s = to_string(root->val) + "->" + s;
ret.push_back(s);
}
return ret;
}
};
<file_sep>/easy/add_binary_67.cpp
#include<iostream>
using namespace std;
class Solution {
public:
string addBinary(string a, string b) {
int a_v, b_v, carry = 0, remain;
string ret = "";
for (int i = 0; i < max(a.length(), b.length()); i++) {
if (i < a.length())
a_v = a[a.length() - 1 - i] - '0';
else
a_v = 0;
if (i < b.length())
b_v = b[b.length() - 1 - i] - '0';
else
b_v = 0;
remain = (carry + a_v + b_v) % 2;
carry = (carry + a_v + b_v) / 2;
ret = to_string(remain) + ret;
}
if (carry == 1)
ret = "1" + ret;
return ret;
}
};
int main() {
Solution s;
cout << s.addBinary("1", "11") << endl;
return 0;
}
<file_sep>/easy/excel_sheet_column_title_168.cpp
class Solution {
public:
string convertToTitle(int n) {
string ret;
while(n) {
int remain = n % 26;
ret = get_title(remain) + ret;
n = (n-1) / 26;
}
return ret;
}
private:
char get_title(int n) {
if (n == 0) return 'Z';
return 'A' + n - 1;
}
};
<file_sep>/easy/two_sum_1.cpp
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> num_pos_map;
vector<int> ret;
for(int i = 0; i < nums.size(); i++) {
if (num_pos_map.find(target-nums[i]) != num_pos_map.end()) {
ret.push_back(num_pos_map[target-nums[i]]);
ret.push_back(i);
return ret;
}
num_pos_map[nums[i]] = i;
}
return ret;
}
};
<file_sep>/easy/valid_sudoku_36.cpp
#include<iostream>
#include<vector>
#include<set>
using namespace std;
class Solution {
public:
bool isValidSudoku(vector<vector<char> >& board) {
/*
cout << checkRow(board) << endl;
cout << checkCol(board) << endl;
cout << checkDiagram(board) << endl;
cout << checkBlock(board) << endl;
*/
if (!checkRow(board)) return false;
if (!checkCol(board)) return false;
//if (!checkDiagram(board)) return false;
if (!checkBlock(board)) return false;
return true;
}
private:
bool check_nine(vector<char> & vec) {
set<char> s;
for(int i = 0; i < vec.size(); i++) {
if (vec[i] == '.') continue;
if (s.find(vec[i]) != s.end()) return false;
s.insert(vec[i]);
}
return true;
}
bool checkRow(vector<vector<char> >& board) {
for (int i = 0; i <= 8; i++) {
vector<char> nine;
for (int j = 0; j <= 8; j++) {
nine.push_back(board[i][j]);
}
if (!check_nine(nine)) return false;
}
return true;
}
bool checkCol(vector<vector<char> >& board){
for (int i = 0; i <= 8; i++) {
vector<char> nine;
for (int j = 0; j <= 8; j++) {
nine.push_back(board[j][i]);
}
if (!check_nine(nine)) return false;
}
return true;
}
bool checkDiagram(vector<vector<char> >& board) {
vector<char> nine;
for (int i = 0; i <= 8; i++) {
nine.push_back(board[i][i]);
}
if (!check_nine(nine)) return false;
nine.clear();
for (int i = 0; i <= 8; i++) {
nine.push_back(board[i][8-i]);
cout << board[i][8-i];
}
if (!check_nine(nine)) return false;
return true;
}
bool checkBlock(vector<vector<char> >& board) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
vector<char> nine;
for (int row = i*3; row < i*3+3; row++) {
for (int col = j*3; col < j*3+3; col++)
nine.push_back(board[row][col]);
}
if (!check_nine(nine)) return false;
}
}
return true;
}
};
int main() {
vector<vector<char> > board;
vector<char> v;
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('2');
board.push_back(v);
v.clear();
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('6');
v.push_back('.');
v.push_back('.');
board.push_back(v);
v.clear();
v.push_back('.');
v.push_back('.');
v.push_back('1');
v.push_back('4');
v.push_back('.');
v.push_back('.');
v.push_back('8');
v.push_back('.');
v.push_back('.');
board.push_back(v);
v.clear();
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('.');
board.push_back(v);
v.clear();
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('.');
board.push_back(v);
v.clear();
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('3');
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('.');
board.push_back(v);
v.clear();
v.push_back('5');
v.push_back('.');
v.push_back('8');
v.push_back('6');
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('.');
board.push_back(v);
v.clear();
v.push_back('.');
v.push_back('9');
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('4');
v.push_back('.');
v.push_back('.');
board.push_back(v);
v.clear();
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('5');
v.push_back('.');
v.push_back('.');
v.push_back('.');
v.push_back('.');
board.push_back(v);
v.clear();
Solution s;
cout << s.isValidSudoku(board) << endl;
return 0;
}
<file_sep>/easy/remove_duplicates_from_sorted_list_83.cpp
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (head == NULL or head->next == NULL) return head;
ListNode* fake_head = head;
int prev = head->val;
while(head->next) {
if (head->next->val == prev) {
head->next = head->next->next;
} else{
prev = head->next->val;
head = head->next;
}
}
return fake_head;
}
};
<file_sep>/easy/longest_common_prefix_14.cpp
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.size() == 0) return "";
string ret = "";
int index = 0;
while(true) {
char common_char;
for(int i = 0; i < strs.size(); i++) {
if (index >= strs[i].size()) return ret;
if (i == 0) {
common_char = strs[i][index];
continue;
}
if (common_char != strs[i][index]) return ret;
}
index++;
ret = ret + common_char;
}
return ret;
}
};
<file_sep>/easy/pascals_triangle_2_119.cpp
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> ret;
ret.push_back(1);
if (rowIndex == 0) {
return ret;
}
ret.push_back(1);
if (rowIndex == 1) {
return ret;
}
for(int row = 2; row <= rowIndex; row++) {
for(int col = row - 1; col > 0; col-- {
ret[col] += ret[col-1];
}
ret.push_back(1);
}
return ret;
}
};
<file_sep>/easy/single_number_3_260.cpp
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int xor_result = 0;
for(int i = 0; i < nums.size(); i++)
xor_result ^= nums[i];
int mask = 1;
while((xor_result & mask) == 0) {
mask = mask << 1;
}
int a = 0, b = 0;
for(int i = 0; i < nums.size(); i++) {
if (nums[i] & mask) {
a ^= nums[i];
} else {
b ^= nums[i];
}
}
vector<int> ret;
ret.push_back(a);
ret.push_back(b);
return ret;
}
};
int main() {
Solution s;
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(1);
v.push_back(3);
v.push_back(2);
v.push_back(5);
vector<int> ret = s.singleNumber(v);
for(int i = 0; i < ret.size(); i++) {
cout << ret[i] << endl;
}
return 0;
}
<file_sep>/easy/valid_anagram_242.cpp
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length()) return false;
unordered_map<char, int> count_map = get_count_map(s);
for(int i=0; i<t.length(); i++) {
if (count_map.find(t[i]) == count_map.end()) return false;
if (count_map[t[i]] == 0) return false;
count_map[t[i]]--;
}
return true;
}
private:
unordered_map<char, int> get_count_map(string s) {
unordered_map<char, int> count_map;
for(int i=0; i<s.length(); i++){
if (count_map.find(s[i]) == count_map.end())
count_map[s[i]] = 0;
count_map[s[i]]++;
}
return count_map;
}
};
<file_sep>/easy/balanced_binary_tree_110.cpp
class Solution {
public:
bool isBalanced(TreeNode* root) {
int depth = 0;
return helper(root, &depth);
}
private:
bool helper(TreeNode* root, int* depth) {
if (root == NULL) {
*depth = 0;
return true;
}
int left_depth = 0, right_depth = 0;
if (!helper(root->left, &left_depth)) return false;
if (!helper(root->right, &right_depth)) return false;
if (abs(left_depth - right_depth) > 1) return false;
*depth = max(left_depth, right_depth) + 1;
return true;
}
};
<file_sep>/easy/valid_palindrome_125.cpp
class Solution {
public:
bool isPalindrome(string s) {
int start = 0, end = s.length() - 1;
while(start < end) {
char start_c = get_char(s[start]);
char end_c = get_char(s[end]);
if (start_c == ' ') {
start++;
continue;
}
if (end_c == ' ') {
end--;
continue;
}
if (start_c != end_c) return false;
start++;
end--;
}
return true;
}
private:
/*全部转为小写, 非法字符全部转为空格*/
char get_char(char c) {
if (c >= 'A' && c <= 'Z')
return 'a' + (c - 'A');
if (c >= '0' && c <= '9')
return c;
if (c >= 'a' && c <= 'z')
return c;
return ' ';
}
};
<file_sep>/easy/climbing_stairs_70.cpp
class Solution {
public:
int climbStairs(int n) {
if (n == 1) return 1;
if (n == 2) return 2;
int prev_2 = 1, prev_1 = 2;
int now = 0;
for (int i = 3; i <= n; i++) {
now = prev_1 + prev_2;
prev_2 = prev_1;
prev_1 = now;
}
return now;
}
};
<file_sep>/easy/reverse_string_344.cpp
#include<iostream>
using namespace std;
class Solution {
public:
string reverseString(string s) {
for(int i=0; i<s.length()/2; i++) {
swap(s[i], s[s.length()-i-1]);
}
return s;
}
};
int main()
{
Solution s;
string i = "hello";
cout << s.reverseString(i) << endl;
cout << i << endl;
return 0;
}
<file_sep>/easy/first_bad_version_278.cpp
bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n) {
int start = 1, end = n, mid;
while(start <= end) {
mid = start + (end - start)/2;
if (isBadVersion(mid)) {
if (mid == 1) return 1;
if (!isBadVersion(mid-1))
return mid;
else
end = mid - 1;
continue;
} else {
start = mid + 1;
continue;
}
}
return 0;
}
};
<file_sep>/easy/counting_bits_338.cpp
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
vector<int> countBits(int num) {
vector<int> ret;
ret.push_back(0);
if (num == 0)
return ret;
ret.push_back(1);
if (num == 1)
return ret;
int num_of_one = 2;
int start_pow_of_2 = 2;
int end_pow_of_2 = 4;
while(start_pow_of_2 <= num) {
for(int i = start_pow_of_2; i < end_pow_of_2; i++) {
if (i > num) break;
int tmp = num_of_one - ret[end_pow_of_2-1-i];
ret.push_back(tmp);
}
num_of_one++;
start_pow_of_2 = end_pow_of_2;
end_pow_of_2 = end_pow_of_2 * 2;
}
return ret;
}
};
int main() {
Solution s;
vector<int> ret = s.countBits(10);
for(int i = 0; i < ret.size(); i++)
cout << ret[i] << endl;
return 0;
}
<file_sep>/easy/merge_sorted_array_88.cpp
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int index_1 = m - 1;
int index_2 = n - 1;
for(int i = m + n - 1; i >= 0; i--) {
if (index_1 < 0) {
nums1[i] = nums2[index_2--];
continue;
}
if (index_2 < 0) {
nums1[i] = nums1[index_1--];
continue;
}
if (nums1[index_1] < nums2[index_2]) {
nums1[i] = nums1[index_1--];
continue;
} else {
nums1[i] = nums2[index_2--];
continue;
}
}
}
};
<file_sep>/easy/guess_number_highter_or_lower_374.cpp
int guess(int num);
class Solution {
public:
int guessNumber(int n) {
int start = 1, end = n;
while(start <= end) {
int mid = start + (end-start) / 2;
if (guess(mid) == 0) return mid;
if (guess(mid) == -1) {
end = mid - 1;
continue;
}
if (guess(mid) == 1) {
start = mid + 1;
continue;
}
}
return -1;
}
};
|
8f6c1679a7e39d75d929ada14ef2c1197f9fb8bb
|
[
"C++"
] | 70
|
C++
|
lhdgriver/leetcode
|
ba11bdfbd7de9bcd0f42ffe4990ade7232804fe0
|
6446c237eff4d78bdaeabdf6f1c12b965e48eaad
|
refs/heads/master
|
<repo_name>adit77799/codetastrophe<file_sep>/bob/2009/03/hha_physfs/hha.c
/*
* HHA support routines for PhysicsFS.
*
* This driver handles Hothead archives (HHA), developed by
* Hothead Games, Inc.
*
*
*
* Based on grp.c and zip.c
*/
//#if (defined PHYSFS_SUPPORTS_HHA)
/* TODO move this */
# define HHA_ARCHIVE_DESCRIPTION "Hothead archive"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef _WIN32_WCE
#include <errno.h>
#endif
#include "physfs.h"
#include "zlib.h"
#define __PHYSICSFS_INTERNAL__
#include "physfs_internal.h"
/* see zip.c for explanation */
#define ZIP_READBUFSIZE (16 * 1024)
#define HHA_COMPRESS_NONE 0
#define HHA_COMPRESS_ZLIB 1
#define HHA_COMPRESS_LZMA 2
/* magic numbers */
#define HHA_FILE_MAGIC 0xAC2FF34F
#define HHA_FILE_VERSION 0x00010000
/* file metadata structure */
typedef struct
{
char *dir; /* directory name */
char *name; /* file name */
PHYSFS_uint32 compress; /* compression level (0-2) */
PHYSFS_uint32 offset; /* offset from start of file */
PHYSFS_uint32 uncompressed_size; /* compressed size */
PHYSFS_uint32 compressed_size; /* uncompressed size */
} HHAentry;
/* HHA file header and metadata */
typedef struct
{
PHYSFS_uint32 entryCount; /* number of files */
char *filenames; /* filename list */
HHAentry *entries; /* file metadata */
/* filesystem info for PhysFS */
char *filename;
PHYSFS_sint64 last_mod_time;
} HHAinfo;
typedef struct
{
void *handle;
HHAentry *entry;
PHYSFS_uint32 compressed_position; /* offset in compressed data. */
PHYSFS_uint32 uncompressed_position; /* tell() position. */
PHYSFS_uint8 *buffer; /* decompression buffer. */
z_stream zlib_stream; /* zlib stream state. */
/*TODO LZMA stream */
} HHAfileinfo;
/* ZLIB functions copied from zip.c */
/*
* Bridge physfs allocation functions to zlib's format...
*/
static voidpf zlibPhysfsAlloc(voidpf opaque, uInt items, uInt size)
{
return(((PHYSFS_Allocator *) opaque)->Malloc(items * size));
} /* zlibPhysfsAlloc */
/*
* Bridge physfs allocation functions to zlib's format...
*/
static void zlibPhysfsFree(voidpf opaque, voidpf address)
{
((PHYSFS_Allocator *) opaque)->Free(address);
} /* zlibPhysfsFree */
/*
* Construct a new z_stream to a sane state.
*/
static void initializeZStream(z_stream *pstr)
{
memset(pstr, '\0', sizeof (z_stream));
pstr->zalloc = zlibPhysfsAlloc;
pstr->zfree = zlibPhysfsFree;
pstr->opaque = &allocator;
} /* initializeZStream */
static const char *zlib_error_string(int rc)
{
switch (rc)
{
case Z_OK: return(NULL); /* not an error. */
case Z_STREAM_END: return(NULL); /* not an error. */
#ifndef _WIN32_WCE
case Z_ERRNO: return(strerror(errno));
#endif
case Z_NEED_DICT: return(ERR_NEED_DICT);
case Z_DATA_ERROR: return(ERR_DATA_ERROR);
case Z_MEM_ERROR: return(ERR_MEMORY_ERROR);
case Z_BUF_ERROR: return(ERR_BUFFER_ERROR);
case Z_VERSION_ERROR: return(ERR_VERSION_ERROR);
default: return(ERR_UNKNOWN_ERROR);
} /* switch */
return(NULL);
} /* zlib_error_string */
/*
* Wrap all zlib calls in this, so the physfs error state is set appropriately.
*/
static int zlib_err(int rc)
{
const char *str = zlib_error_string(rc);
if (str != NULL)
__PHYSFS_setError(str);
return(rc);
} /* zlib_err */
static void HHA_dirClose(dvoid *opaque)
{
HHAinfo *info = ((HHAinfo *) opaque);
allocator.Free(info->filename);
allocator.Free(info->filenames);
allocator.Free(info->entries);
allocator.Free(info);
} /* HHA_dirClose */
static PHYSFS_sint64 HHA_read(fvoid *opaque, void *buffer,
PHYSFS_uint32 objSize, PHYSFS_uint32 objCount)
{
HHAfileinfo *finfo = (HHAfileinfo *) opaque;
HHAentry *entry = finfo->entry;
PHYSFS_sint64 retval = 0;
PHYSFS_sint64 maxread = ((PHYSFS_sint64) objSize) * objCount;
PHYSFS_sint64 avail = entry->uncompressed_size -
finfo->uncompressed_position;
BAIL_IF_MACRO(maxread == 0, NULL, 0); /* quick rejection. */
if (avail < maxread)
{
maxread = avail - (avail % objSize);
objCount = (PHYSFS_uint32) (maxread / objSize);
BAIL_IF_MACRO(objCount == 0, ERR_PAST_EOF, 0); /* quick rejection. */
__PHYSFS_setError(ERR_PAST_EOF); /* this is always true here. */
} /* if */
if (entry->compress == HHA_COMPRESS_NONE)
{
retval = __PHYSFS_platformRead(finfo->handle, buffer, objSize, objCount);
}
else if (entry->compress == HHA_COMPRESS_ZLIB)
{
finfo->zlib_stream.next_out = buffer;
finfo->zlib_stream.avail_out = objSize * objCount;
while (retval < maxread)
{
PHYSFS_uint32 before = finfo->zlib_stream.total_out;
int rc;
if (finfo->zlib_stream.avail_in == 0)
{
PHYSFS_sint64 br;
br = entry->compressed_size - finfo->compressed_position;
if (br > 0)
{
if (br > ZIP_READBUFSIZE)
br = ZIP_READBUFSIZE;
br = __PHYSFS_platformRead(finfo->handle,
finfo->buffer,
1, (PHYSFS_uint32) br);
if (br <= 0)
break;
finfo->compressed_position += (PHYSFS_uint32) br;
finfo->zlib_stream.next_in = finfo->buffer;
finfo->zlib_stream.avail_in = (PHYSFS_uint32) br;
} /* if */
} /* if */
rc = zlib_err(inflate(&finfo->zlib_stream, Z_SYNC_FLUSH));
retval += (finfo->zlib_stream.total_out - before);
if (rc != Z_OK)
break;
} /* while */
retval /= objSize;
}
if (retval > 0)
finfo->uncompressed_position += (PHYSFS_uint32) (retval * objSize);
return(retval);
} /* HHA_read */
static PHYSFS_sint64 HHA_write(fvoid *opaque, const void *buffer,
PHYSFS_uint32 objSize, PHYSFS_uint32 objCount)
{
BAIL_MACRO(ERR_NOT_SUPPORTED, -1);
} /* HHA_write */
static int HHA_eof(fvoid *opaque)
{
HHAfileinfo *finfo = (HHAfileinfo *) opaque;
return(finfo->uncompressed_position >= finfo->entry->uncompressed_size);
} /* HHA_eof */
static PHYSFS_sint64 HHA_tell(fvoid *opaque)
{
return(((HHAfileinfo *) opaque)->uncompressed_position);
} /* HHA_tell */
static int HHA_seek(fvoid *opaque, PHYSFS_uint64 offset)
{
HHAfileinfo *finfo = (HHAfileinfo *) opaque;
HHAentry *entry = finfo->entry;
void *in = finfo->handle;
BAIL_IF_MACRO(offset < 0, ERR_INVALID_ARGUMENT, 0);
BAIL_IF_MACRO(offset >= entry->uncompressed_size, ERR_PAST_EOF, 0);
if (entry->compress == HHA_COMPRESS_NONE)
{
PHYSFS_sint64 newpos = offset + entry->offset;
BAIL_IF_MACRO(!__PHYSFS_platformSeek(in, newpos), NULL, 0);
finfo->uncompressed_position = (PHYSFS_uint32) offset;
}
else if (entry->compress == HHA_COMPRESS_ZLIB)
{
/*
* If seeking backwards, we need to redecode the file
* from the start and throw away the compressed bits until we hit
* the offset we need. If seeking forward, we still need to
* decode, but we don't rewind first.
*/
if (offset < finfo->uncompressed_position)
{
/* we do a copy so state is sane if inflateInit2() fails. */
z_stream str;
initializeZStream(&str);
if (zlib_err(inflateInit2(&str, -MAX_WBITS)) != Z_OK)
return(0);
if (!__PHYSFS_platformSeek(in, entry->offset))
return(0);
inflateEnd(&finfo->zlib_stream);
memcpy(&finfo->zlib_stream, &str, sizeof (z_stream));
finfo->uncompressed_position = finfo->compressed_position = 0;
} /* if */
while (finfo->uncompressed_position != offset)
{
PHYSFS_uint8 buf[512];
PHYSFS_uint32 maxread;
maxread = (PHYSFS_uint32) (offset - finfo->uncompressed_position);
if (maxread > sizeof (buf))
maxread = sizeof (buf);
if (HHA_read(finfo, buf, maxread, 1) != 1)
return(0);
} /* while */
} /* else */
else
printf("LZMA file: %s/%s\n", entry->dir, entry->name);
return(1);
} /* HHA_seek */
static PHYSFS_sint64 HHA_fileLength(fvoid *opaque)
{
HHAfileinfo *finfo = (HHAfileinfo *) opaque;
return((PHYSFS_sint64) finfo->entry->uncompressed_size);
} /* HHA_fileLength */
static int HHA_fileClose(fvoid *opaque)
{
HHAfileinfo *finfo = (HHAfileinfo *) opaque;
BAIL_IF_MACRO(!__PHYSFS_platformClose(finfo->handle), NULL, 0);
if (finfo->entry->compress == HHA_COMPRESS_ZLIB)
inflateEnd(&finfo->zlib_stream);
if (finfo->buffer != NULL)
allocator.Free(finfo->buffer);
allocator.Free(finfo);
return(1);
} /* HHA_fileClose */
static int hha_open(const char *filename, int forWriting,
void **fh, PHYSFS_uint32 *filenameSize, PHYSFS_uint32 *count)
{
PHYSFS_uint32 magic[2];
*fh = NULL;
BAIL_IF_MACRO(forWriting, ERR_ARC_IS_READ_ONLY, 0);
*fh = __PHYSFS_platformOpenRead(filename);
BAIL_IF_MACRO(*fh == NULL, NULL, 0);
if (__PHYSFS_platformRead(*fh, magic, sizeof(PHYSFS_uint32), 2) != 2)
goto openHHA_failed;
magic[0] = PHYSFS_swapULE32(magic[0]);
magic[1] = PHYSFS_swapULE32(magic[1]);
if (!(magic[0] == HHA_FILE_MAGIC && magic[1] == HHA_FILE_VERSION))
{
__PHYSFS_setError(ERR_UNSUPPORTED_ARCHIVE);
goto openHHA_failed;
} /* if */
if (__PHYSFS_platformRead(*fh, filenameSize, sizeof (PHYSFS_uint32), 1) != 1)
goto openHHA_failed;
*filenameSize = PHYSFS_swapULE32(*filenameSize);
if (__PHYSFS_platformRead(*fh, count, sizeof (PHYSFS_uint32), 1) != 1)
goto openHHA_failed;
*count = PHYSFS_swapULE32(*count);
return(1);
openHHA_failed:
if (*fh != NULL)
__PHYSFS_platformClose(*fh);
*filenameSize = -1;
*count = -1;
*fh = NULL;
return(0);
} /* HHA_open */
static int HHA_isArchive(const char *filename, int forWriting)
{
void *fh;
PHYSFS_uint32 nameSize;
PHYSFS_uint32 fileCount;
int retval = hha_open(filename, forWriting, &fh, &nameSize, &fileCount);
if (fh != NULL)
__PHYSFS_platformClose(fh);
return(retval);
} /* HHA_isArchive */
static int HHA_entry_cmp(void *_a, PHYSFS_uint32 one, PHYSFS_uint32 two)
{
if (one != two)
{
int retval = 0;
const HHAentry *a = (const HHAentry *) _a;
retval = strcmp(a[one].dir, a[two].dir);
if (!retval)
retval = strcmp(a[one].name, a[two].name);
return retval;
} /* if */
return 0;
} /* HHA_entry_cmp */
static void HHA_entry_swap(void *_a, PHYSFS_uint32 one, PHYSFS_uint32 two)
{
if (one != two)
{
HHAentry tmp;
HHAentry *first = &(((HHAentry *) _a)[one]);
HHAentry *second = &(((HHAentry *) _a)[two]);
memcpy(&tmp, first, sizeof (HHAentry));
memcpy(first, second, sizeof (HHAentry));
memcpy(second, &tmp, sizeof (HHAentry));
} /* if */
} /* HHA_entry_swap */
static int HHA_load_entries(const char *name, int forWriting, HHAinfo *info)
{
void *fh = NULL;
PHYSFS_uint32 fileNameSize;
PHYSFS_uint32 fileCount;
HHAentry *entry;
PHYSFS_uint32 buf[6];
BAIL_IF_MACRO(!hha_open(name, forWriting, &fh, &fileNameSize, &fileCount), NULL, 0);
info->entryCount = fileCount;
info->filenames = (char *) allocator.Malloc(fileNameSize);
if (info->filenames == NULL)
{
__PHYSFS_platformClose(fh);
BAIL_MACRO(ERR_OUT_OF_MEMORY, 0);
} /* if */
info->entries = (HHAentry *) allocator.Malloc(sizeof(HHAentry)*fileCount);
if (info->entries == NULL)
{
__PHYSFS_platformClose(fh);
BAIL_MACRO(ERR_OUT_OF_MEMORY, 0);
} /* if */
if (__PHYSFS_platformRead(fh, info->filenames, 1, fileNameSize) != fileNameSize)
{
__PHYSFS_platformClose(fh);
return(0);
}
for (entry = info->entries; fileCount > 0; fileCount--, entry++)
{
if (__PHYSFS_platformRead(fh, buf, sizeof(PHYSFS_uint32), 6) != 6)
{
__PHYSFS_platformClose(fh);
return(0);
} /* if */
entry->dir = info->filenames + PHYSFS_swapULE32(buf[0]);
entry->name = info->filenames + PHYSFS_swapULE32(buf[1]);
entry->compress = PHYSFS_swapULE32(buf[2]);
entry->offset = PHYSFS_swapULE32(buf[3]);
entry->uncompressed_size = PHYSFS_swapULE32(buf[4]);
entry->compressed_size = PHYSFS_swapULE32(buf[5]);
} /* for */
__PHYSFS_platformClose(fh);
__PHYSFS_sort(info->entries, info->entryCount,
HHA_entry_cmp, HHA_entry_swap);
return(1);
} /* HHA_load_entries */
static void *HHA_openArchive(const char *name, int forWriting)
{
PHYSFS_sint64 modtime = __PHYSFS_platformGetLastModTime(name);
HHAinfo *info = (HHAinfo *) allocator.Malloc(sizeof (HHAinfo));
BAIL_IF_MACRO(info == NULL, ERR_OUT_OF_MEMORY, 0);
memset(info, '\0', sizeof (HHAinfo));
info->filename = (char *) allocator.Malloc(strlen(name) + 1);
GOTO_IF_MACRO(!info->filename, ERR_OUT_OF_MEMORY, HHA_openArchive_failed);
if (!HHA_load_entries(name, forWriting, info))
goto HHA_openArchive_failed;
strcpy(info->filename, name);
info->last_mod_time = modtime;
return(info);
HHA_openArchive_failed:
if (info != NULL)
{
if (info->filename != NULL)
allocator.Free(info->filename);
if (info->entries != NULL)
allocator.Free(info->entries);
allocator.Free(info);
} /* if */
return(NULL);
} /* HHA_openArchive */
static HHAentry *HHA_find_entry(HHAinfo *info, const char *name)
{
HHAentry *a = info->entries;
PHYSFS_sint32 lo = 0;
PHYSFS_sint32 hi = (PHYSFS_sint32) (info->entryCount - 1);
PHYSFS_sint32 middle;
char dirname[256];
char filename[256];
int rc;
char *fpart = strrchr(name, '/');
if (fpart != NULL)
{
strcpy(filename, fpart + 1);
strncpy(dirname, name, fpart - name);
dirname[fpart - name] = '\0';
}
else
{
strcpy(dirname, name);
filename[0] = '\0';
}
while (lo <= hi)
{
middle = lo + ((hi - lo) / 2);
rc = strcmp(dirname, a[middle].dir);
if (rc == 0 && filename[0])
rc = strcmp(filename, a[middle].name);
if (rc == 0) /* found it! */
return(&a[middle]);
else if (rc > 0)
lo = middle + 1;
else
hi = middle - 1;
} /* while */
BAIL_MACRO(ERR_NO_SUCH_FILE, NULL);
} /* HHA_find_entry */
static int HHA_isDirectory(dvoid *opaque, const char *name, int *fileExists)
{
HHAinfo *info = (HHAinfo *) opaque;
HHAentry *a = info->entries;
PHYSFS_sint32 lo = 0;
PHYSFS_sint32 hi = (PHYSFS_sint32) (info->entryCount - 1);
PHYSFS_sint32 middle;
int len = strlen(name);
int rc;
/* emulate finding a directory by finding a file in the directory */
while (lo <= hi)
{
middle = lo + ((hi - lo) / 2);
rc = strncmp(name, a[middle].dir, len);
if (rc == 0 && (a[middle].dir[len] == '\0'
|| a[middle].dir[len] == '/'))
{
*fileExists = 1;
return(1);
}
else if (rc < 0)
hi = middle - 1;
else
lo = middle + 1;
} /* while */
*fileExists = (HHA_find_entry((HHAinfo *) opaque, name) != NULL);
return(0);
} /* HHA_isDirectory */
static int HHA_exists(dvoid *opaque, const char *name)
{
/* check if file or directory */
int exists;
(void)HHA_isDirectory(opaque, name, &exists);
return exists;
} /* HHA_exists */
static int HHA_isSymLink(dvoid *opaque, const char *name, int *fileExists)
{
*fileExists = HHA_exists(opaque, name);
return(0); /* never symlinks in HHA. */
} /* HHA_isSymLink */
/*
* Moved to seperate function so we can use alloca then immediately throw
* away the allocated stack space...
*/
static void doEnumCallback(PHYSFS_EnumFilesCallback cb, void *callbackdata,
const char *odir, const char *str, PHYSFS_sint32 ln)
{
char *newstr = __PHYSFS_smallAlloc(ln + 1);
if (newstr == NULL)
return;
memcpy(newstr, str, ln);
newstr[ln] = '\0';
cb(callbackdata, odir, newstr);
__PHYSFS_smallFree(newstr);
} /* doEnumCallback */
static void HHA_enumerateFiles(dvoid *opaque, const char *dname,
int omitSymLinks, PHYSFS_EnumFilesCallback cb,
const char *origdir, void *callbackdata)
{
size_t dlen = strlen(dname),
dlen_inc = dlen + ((dlen > 0) ? 1 : 0);
HHAinfo *info = (HHAinfo *) opaque;
HHAentry *entry = info->entries;
HHAentry *lastEntry = &info->entries[info->entryCount];
char lastDir[256];
lastDir[0] = '\0';
if (dlen)
{
while (entry < lastEntry)
{
if (!strncmp(dname, entry->dir, dlen))
break;
entry++;
}
}
while (entry < lastEntry)
{
if(!strcmp(dname, entry->dir))
doEnumCallback(cb, callbackdata, origdir, entry->name, strlen(entry->name));
if(strlen(entry->dir) > dlen)
{
char *fname = entry->dir + dlen_inc;
char *dirNameEnd = strchr(fname, '/');
size_t dirNameLen = dirNameEnd - fname;
if (dirNameEnd == NULL)
dirNameLen = strlen(fname);
if (dlen && strncmp(dname, entry->dir, dlen))
break;
if (strncmp(lastDir, fname, dirNameLen))
{
doEnumCallback(cb, callbackdata, origdir, fname, dirNameLen);
strncpy(lastDir, fname, dirNameLen);
lastDir[dirNameLen] = '\0';
}
}
entry++;
}
} /* HHA_enumerateFiles */
static PHYSFS_sint64 HHA_getLastModTime(dvoid *opaque,
const char *name,
int *fileExists)
{
HHAinfo *info = (HHAinfo *) opaque;
PHYSFS_sint64 retval = -1;
*fileExists = (HHA_find_entry(info, name) != NULL);
if (*fileExists) /* use time of HHA file itself on disk. */
retval = info->last_mod_time;
return(retval);
} /* HHA_getLastModTime */
static fvoid *HHA_openRead(dvoid *opaque, const char *fnm, int *fileExists)
{
HHAinfo *info = (HHAinfo *) opaque;
HHAfileinfo *finfo;
HHAentry *entry;
entry = HHA_find_entry(info, fnm);
*fileExists = (entry != NULL);
BAIL_IF_MACRO(entry == NULL, NULL, NULL);
finfo = (HHAfileinfo *) allocator.Malloc(sizeof (HHAfileinfo));
BAIL_IF_MACRO(finfo == NULL, ERR_OUT_OF_MEMORY, NULL);
memset(finfo, '\0', sizeof (HHAfileinfo));
finfo->handle = __PHYSFS_platformOpenRead(info->filename);
if ( (finfo->handle == NULL) ||
(!__PHYSFS_platformSeek(finfo->handle, entry->offset)) )
{
allocator.Free(finfo);
return(NULL);
} /* if */
finfo->entry = entry;
if (finfo->entry->compress == HHA_COMPRESS_ZLIB)
{
initializeZStream(&finfo->zlib_stream);
if (zlib_err(inflateInit2(&finfo->zlib_stream, -MAX_WBITS)) != Z_OK)
{
HHA_fileClose(finfo);
return(NULL);
} /* if */
finfo->buffer = (PHYSFS_uint8 *) allocator.Malloc(ZIP_READBUFSIZE);
if (finfo->buffer == NULL)
{
HHA_fileClose(finfo);
BAIL_MACRO(ERR_OUT_OF_MEMORY, NULL);
} /* if */
} /* if */
return(finfo);
} /* HHA_openRead */
static fvoid *HHA_openWrite(dvoid *opaque, const char *name)
{
BAIL_MACRO(ERR_NOT_SUPPORTED, NULL);
} /* HHA_openWrite */
static fvoid *HHA_openAppend(dvoid *opaque, const char *name)
{
BAIL_MACRO(ERR_NOT_SUPPORTED, NULL);
} /* HHA_openAppend */
static int HHA_remove(dvoid *opaque, const char *name)
{
BAIL_MACRO(ERR_NOT_SUPPORTED, 0);
} /* HHA_remove */
static int HHA_mkdir(dvoid *opaque, const char *name)
{
BAIL_MACRO(ERR_NOT_SUPPORTED, 0);
} /* HHA_mkdir */
const PHYSFS_ArchiveInfo __PHYSFS_ArchiveInfo_HHA =
{
"HHA",
HHA_ARCHIVE_DESCRIPTION,
"<NAME> <<EMAIL>>",
"http://icculus.org/physfs/",
};
const PHYSFS_Archiver __PHYSFS_Archiver_HHA =
{
&__PHYSFS_ArchiveInfo_HHA,
HHA_isArchive, /* isArchive() method */
HHA_openArchive, /* openArchive() method */
HHA_enumerateFiles, /* enumerateFiles() method */
HHA_exists, /* exists() method */
HHA_isDirectory, /* isDirectory() method */
HHA_isSymLink, /* isSymLink() method */
HHA_getLastModTime, /* getLastModTime() method */
HHA_openRead, /* openRead() method */
HHA_openWrite, /* openWrite() method */
HHA_openAppend, /* openAppend() method */
HHA_remove, /* remove() method */
HHA_mkdir, /* mkdir() method */
HHA_dirClose, /* dirClose() method */
HHA_read, /* read() method */
HHA_write, /* write() method */
HHA_eof, /* eof() method */
HHA_tell, /* tell() method */
HHA_seek, /* seek() method */
HHA_fileLength, /* fileLength() method */
HHA_fileClose /* fileClose() method */
};
//#endif /* defined PHYSFS_SUPPORTS_HHA */
/* end of hha.c ... */
<file_sep>/projects/cellfinder/src/com/codetastrophe/cellfinder/listeners/MyLocationListener.java
/*
* Copyright (C) 2008 <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.codetastrophe.cellfinder.listeners;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import com.codetastrophe.cellfinder.CellFinderMapActivity;
import com.codetastrophe.cellfinder.R;
import com.codetastrophe.cellfinder.overlays.ImageOverlay;
import com.codetastrophe.cellfinder.overlays.LineOverlay;
import com.codetastrophe.cellfinder.utils.StyledResourceHelper;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.ibm.util.CoordinateConversion;
import com.ibm.util.CoordinateConversion.LatLon2MGRUTM;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Environment;
//import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MyLocationListener implements LocationListener {
public static final int AUTO_CENTER_GPS = 0;
public static final int AUTO_CENTER_NETWORK = 1;
public static final int AUTO_CENTER_MIDPOINT = 2;
public static final int AUTO_CENTER_NONE = 3;
public static final int UNITS_METERS = 0;
public static final int UNITS_FEET = 1;
public static final int UNITS_MILES = 2;
public static final int LOCATION_FMT_DDM = 0;
public static final int LOCATION_FMT_DDMS = 1;
public static final int LOCATION_FMT_DD = 2;
public static final int LOCATION_FMT_MGRS = 3;
private Context mContext = null;
private GeoPoint mCoarseLastGP = null;
private GeoPoint mFineLastGP = null;
private Location mCoarseLastLocation = null;
private Location mFineLastLocation = null;
private TextView mTvLocationCoarseName = null;
private TextView mTvLocationCoarse = null;
private TextView mTvLocationFine = null;
private MapView mMapView = null;
private String mCoarseLocationProvider = null;
private String mFineLocationProvider = null;
private ImageOverlay mCoarseLocationOverlay = null;
private ImageOverlay mFineLocationOverlay = null;
private LineOverlay mLineOverlay = null;
private TextView mTvCellBearing = null;
private TextView mTvCellDirection = null;
private boolean mAutoZoom = false;
private int mAutoCenter = 0;
private int mUnits = 0;
private int mLocationFmt = 0;
private boolean mCompass = false;
private LatLon2MGRUTM mMgrsConversion;
private File mOutputFile = null;
private MyPhoneStateListener mPhoneStateListener;
private boolean mSaveData = false;
private boolean mDirectQuery = false;
private MyLocationOverlay mMyLocationOverlay;
private LinearLayout mZoomLayout = null;
private LinearLayout mZoom = null;
private static String sSaveDataFile;
private static String[] mDirs = new String[] { "N", "NE", "E", "SE", "S",
"SW", "W", "NW", "N" };
public MyLocationListener(Activity a, MyPhoneStateListener phoneStateListener) {
mContext = a;
mPhoneStateListener = phoneStateListener;
CellFinderMapActivity cf = (CellFinderMapActivity) a;
mCoarseLocationProvider = cf.getCoarseLocationProvider();
mFineLocationProvider = cf.getFineLocationProvider();
mTvLocationCoarseName = (TextView) a.findViewById(R.id.tv_location_coarse_name);
mTvLocationCoarseName.setText(StyledResourceHelper.GetStyledString(mContext,
R.string.bold_fmt, mCoarseLocationProvider));
mTvLocationCoarse = (TextView) a.findViewById(R.id.tv_location_coarse);
mTvLocationFine = (TextView) a.findViewById(R.id.tv_location_fine);
mMapView = (MapView) a.findViewById(R.id.map_view);
mZoomLayout = (LinearLayout) a.findViewById(R.id.layout_zoom);
mZoom = (LinearLayout) mMapView.getZoomControls();
mTvCellBearing = (TextView) a.findViewById(R.id.tv_cell_bearing);
mTvCellDirection = (TextView) a.findViewById(R.id.tv_cell_direction);
mCoarseLocationOverlay = new ImageOverlay(a.getResources().getDrawable(
R.drawable.star_small), null);
// only set up the fine location overlay and line overlay if the
// gps is enabled
if(mFineLocationProvider != null) {
mFineLocationOverlay = new ImageOverlay(a.getResources().getDrawable(
R.drawable.reticle), null);
Paint paint = new Paint();
paint.setStrokeWidth(3);
paint.setColor(Color.parseColor("#00B000"));
mLineOverlay = new LineOverlay(null, null, paint);
}
// set text labels for location providers
TextView tmp = (TextView) a.findViewById(R.id.tv_location_fine_name);
if(mFineLocationProvider != null) {
tmp.setText(StyledResourceHelper.GetStyledString(mContext,
R.string.bold_fmt, mFineLocationProvider));
} else {
// if we have no fine location provider, set the location
// text to disabled
tmp.setText(StyledResourceHelper.GetStyledString(mContext,
R.string.bold_fmt, a.getResources().getString(
R.string.provider_gps)));
mTvLocationFine.setText(R.string.provider_disabled);
}
mMgrsConversion = new CoordinateConversion().new LatLon2MGRUTM();
clearBearing();
}
public void onLocationChanged(Location location) {
//Log.d(CellFinderMapActivity.CELLFINDER, String.format(
// "MyLocationListener.onLocationChanged() - provider %s, lat %s, lon %s",
// location.getProvider(), location.getLatitude(),
// location.getLongitude()));
GeoPoint gp = getGeoPoint(location);
String prov = location.getProvider();
if (prov.equals(mFineLocationProvider)) {
//Log.d(CellFinderMapActivity.CELLFINDER,
// "updating fine location");
mFineLastLocation = location;
// update the location text
mTvLocationFine.setText(getNiceLocation(location));
// if this is a new location, update the map
if (!gp.equals(mFineLastGP)) {
mFineLastGP = gp;
UpdateOverlays();
zoomAndCenterMap();
}
updateBearing();
} else if(prov.equals(mCoarseLocationProvider)) {
//Log.d(CellFinderMapActivity.CELLFINDER,
// "updating coarse location");
// if we're using direct query, ignore the coarse location
if(!mDirectQuery) {
mCoarseLastLocation = location;
// update the location text
mTvLocationCoarseName.setText(StyledResourceHelper.GetStyledString(mContext,
R.string.bold_fmt, location.getProvider()));
mTvLocationCoarse.setText(getNiceLocation(location));
if (!gp.equals(mCoarseLastGP)) {
mCoarseLastGP = gp;
UpdateOverlays();
zoomAndCenterMap();
}
updateBearing();
}
}
if(mSaveData) {
CellLocation celllocation = new CellLocation(
mPhoneStateListener.getOperStr(),
mPhoneStateListener.getMcc(),
mPhoneStateListener.getMnc(),
mPhoneStateListener.getLac(),
mPhoneStateListener.getCid(),
mPhoneStateListener.getDbm(),
location);
saveLocation(celllocation);
}
}
public void directQueryLocationChanged(String oper, int mcc, int mnc, int lac, int cid,
int signal, Location location) {
GeoPoint gp = getGeoPoint(location);
if(mDirectQuery) {
mCoarseLastLocation = location;
// update the location text
mTvLocationCoarseName.setText(StyledResourceHelper.GetStyledString(mContext,
R.string.bold_fmt, location.getProvider()));
mTvLocationCoarse.setText(getNiceLocation(location));
if (!gp.equals(mCoarseLastGP)) {
mCoarseLastGP = gp;
UpdateOverlays();
zoomAndCenterMap();
}
updateBearing();
}
if(mSaveData) {
CellLocation celllocation = new CellLocation(
oper, mcc, mnc, lac, cid, signal, location);
saveLocation(celllocation);
}
}
private GeoPoint getGeoPoint(Location location) {
Double lat = location.getLatitude() * 1E6;
Double lon = location.getLongitude() * 1E6;
return new GeoPoint(lat.intValue(), lon.intValue());
}
public void onProviderDisabled(String provider) {
TextView tv = getTextViewForProvider(provider);
if (tv != null) {
tv.setText(mContext.getString(R.string.provider_disabled));
clearBearing();
}
}
public void onProviderEnabled(String provider) {
TextView tv = getTextViewForProvider(provider);
if (tv != null) {
tv.setText(mContext.getString(R.string.provider_waiting));
clearBearing();
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {
TextView tv = getTextViewForProvider(provider);
switch (status) {
case LocationProvider.TEMPORARILY_UNAVAILABLE:
// if it's temporarily unavailable but we have the most recent
// location, italicize the previous one
Location loc = getLastLocationForProvider(provider);
if (loc != null) {
tv.setText(StyledResourceHelper.GetStyledString(mContext,
R.string.italics_fmt, getNiceLocation(loc)));
} else {
tv.setText(mContext.getString(R.string.provider_waiting));
clearBearing();
}
break;
case LocationProvider.OUT_OF_SERVICE:
tv.setText(mContext.getString(R.string.provider_out_of_service));
clearBearing();
break;
}
}
public void pause() {
if(mMyLocationOverlay != null && mCompass) {
mMyLocationOverlay.disableCompass();
}
}
public void resume() {
if(mMyLocationOverlay != null && mCompass) {
mMyLocationOverlay.enableCompass();
}
}
public void setAutoCenter(int autocenter) {
mAutoCenter = autocenter;
zoomAndCenterMap();
}
public void setAutoZoom(boolean enabled) {
mAutoZoom = enabled;
mZoomLayout.removeView(mZoom);
if (!mAutoZoom) {
// add zoom control back if auto-zoom is disabled
mZoomLayout.addView(mZoom);
}
zoomAndCenterMap();
}
public void setLocationFormat(int fmt) {
mLocationFmt = fmt;
}
public void setSatellite(boolean enabled) {
mMapView.setSatellite(enabled);
}
public void setUnits(int units) {
mUnits = units;
}
public void setCompass(boolean enabled) {
mCompass = enabled;
if(enabled) {
mMyLocationOverlay = new MyLocationOverlay(mContext, mMapView);
mMyLocationOverlay.disableMyLocation();
mMyLocationOverlay.enableCompass();
} else {
mMyLocationOverlay = null;
}
}
private void clearBearing() {
mTvCellBearing.setText("");
mTvCellDirection.setText("");
}
private String getDDM(double coord) {
if (coord < 0)
coord = -coord;
int deg = (int) Math.floor(coord);
coord -= deg;
coord *= 60;
DecimalFormat df = new DecimalFormat(mContext.getString(R.string.min_fmt));
return String.format(mContext.getString(R.string.ddm_fmt), deg, df.format(coord));
}
private String getDDMS(double coord) {
if (coord < 0)
coord = -coord;
int deg = (int) Math.floor(coord);
coord -= deg;
coord *= 60;
int min = (int) Math.floor(coord);
coord -= min;
coord *= 60;
DecimalFormat df = new DecimalFormat(mContext.getString(R.string.sec_fmt));
return String.format(mContext.getString(R.string.ddms_fmt), deg, min, df.format(coord));
}
private String getDD(double coord) {
if (coord < 0)
coord = -coord;
DecimalFormat df = new DecimalFormat(mContext.getString(R.string.deg_fmt));
return String.format(mContext.getString(R.string.dd_fmt), df.format(coord));
}
private String getMGRS(double lat, double lon) {
return mMgrsConversion.convertLatLonToMGRUTM(lat, lon);
}
private Location getLastLocationForProvider(String provider) {
if (provider.equals(mFineLocationProvider)) {
return mFineLastLocation;
} else if (provider.equals(mCoarseLocationProvider)) {
return mCoarseLastLocation;
}
return null;
}
private String getNiceDirection(float bearing) {
if (bearing < -180 || bearing > 180)
return "ERROR";
if (bearing < 0)
bearing += 360;
bearing += 22.5;
return mDirs[(int) (bearing / 45)];
}
private String getNiceLocation(Location loc) {
StringBuilder sb = new StringBuilder();
double lat = loc.getLatitude();
double lon = loc.getLongitude();
String latStr, lonStr;
switch (mLocationFmt) {
case LOCATION_FMT_DD:
latStr = getDD(lat);
lonStr = getDD(lon);
break;
case LOCATION_FMT_DDM:
latStr = getDDM(lat);
lonStr = getDDM(lon);
break;
case LOCATION_FMT_MGRS:
sb.append(getMGRS(lat, lon));
default: // LOCATION_FMT_DDMS
latStr = getDDMS(lat);
lonStr = getDDMS(lon);
break;
}
if (mLocationFmt != LOCATION_FMT_MGRS) {
sb.append(latStr);
if (lat > 0)
sb.append("N");
else
sb.append("S");
sb.append(", ");
sb.append(lonStr);
if (lon > 0)
sb.append("E");
else
sb.append("W");
}
return sb.toString();
}
private TextView getTextViewForProvider(String provider) {
if (provider.equals(mFineLocationProvider)) {
return mTvLocationFine;
} else if (provider.equals(mCoarseLocationProvider)) {
return mTvLocationCoarse;
}
return null;
}
private double metersToFeet(double meters) {
return meters * 3.28;
}
private double metersToMiles(double meters) {
return meters / 1609;
}
private void updateBearing() {
if (mFineLastLocation != null && mCoarseLastLocation != null) {
int bearing = (int) mFineLastLocation
.bearingTo(mCoarseLastLocation);
int distance = (int) mFineLastLocation
.distanceTo(mCoarseLastLocation);
String direction = getNiceDirection(bearing);
int nicebearing = bearing;
if (nicebearing < 0)
nicebearing += 360;
mTvCellBearing.setText(StyledResourceHelper.GetStyledString(
mContext, R.string.bearing_fmt, direction, nicebearing));
switch (mUnits) {
case UNITS_MILES:
mTvCellDirection.setText(StyledResourceHelper.GetStyledString(
mContext, R.string.distance_fmt_miles,
metersToMiles(distance)));
break;
case UNITS_FEET:
mTvCellDirection.setText(StyledResourceHelper.GetStyledString(
mContext, R.string.distance_fmt_feet,
(int) metersToFeet(distance)));
break;
default:
mTvCellDirection.setText(StyledResourceHelper.GetStyledString(
mContext, R.string.distance_fmt_meters, distance));
}
}
}
private void UpdateOverlays() {
mCoarseLocationOverlay.setLocation(mCoarseLastGP);
if(mFineLocationOverlay != null) {
mFineLocationOverlay.setLocation(mFineLastGP);
mLineOverlay.setPositions(mFineLastGP, mCoarseLastGP);
}
// add overlays
List<Overlay> overlays = mMapView.getOverlays();
overlays.clear();
// only add the line and the fine overlay if the fine location overlay
// exists
if(mFineLocationOverlay != null) {
overlays.add(mLineOverlay);
overlays.add(mFineLocationOverlay);
}
overlays.add(mCoarseLocationOverlay);
if(mMyLocationOverlay != null && mCompass) {
overlays.add(mMyLocationOverlay);
}
}
private void zoomAndCenterMap() {
MapController mc = mMapView.getController();
if (mFineLastGP != null && mCoarseLastGP != null) {
int lat1 = mFineLastGP.getLatitudeE6();
int lon1 = mFineLastGP.getLongitudeE6();
int lat2 = mCoarseLastGP.getLatitudeE6();
int lon2 = mCoarseLastGP.getLongitudeE6();
int latspan = Math.max(lat1, lat2) - Math.min(lat1, lat2);
int lonspan = Math.max(lon1, lon2) - Math.min(lon1, lon2);
// handle zooming
if (mAutoZoom) {
mc.zoomToSpan(latspan, lonspan);
// if we're using a centering option that isn't the midpoint, we
// have to
// zoom out one level to see both points
if (mAutoCenter != AUTO_CENTER_MIDPOINT)
mc.setZoom(mMapView.getZoomLevel() - 1);
}
if (mAutoCenter == AUTO_CENTER_GPS) {
mc.setCenter(mFineLastGP);
} else if (mAutoCenter == AUTO_CENTER_NETWORK) {
mc.setCenter(mCoarseLastGP);
} else if (mAutoCenter == AUTO_CENTER_MIDPOINT) {
int latcen = (Math.max(lat1, lat2) + Math.min(lat1, lat2)) / 2;
int loncen = (Math.max(lon1, lon2) + Math.min(lon1, lon2)) / 2;
mc.setCenter(new GeoPoint(latcen, loncen));
}
} else if(mFineLastGP != null) {
// auto center on gps if that's enabled
if(mAutoCenter != AUTO_CENTER_NONE) {
mc.setCenter(mFineLastGP);
}
// set zoom level to something reasonable - autozoom is designed
// for when there's 2 points, doesn't really matter when there's
// only one point
if(mAutoZoom) {
mc.setZoom(mMapView.getMaxZoomLevel() - 2);
}
} else if(mCoarseLastGP != null) {
// auto center on network if that's enabled
if(mAutoCenter != AUTO_CENTER_NONE) {
mc.setCenter(mCoarseLastGP);
}
if(mAutoZoom) {
mc.setZoom(mMapView.getMaxZoomLevel() - 2);
}
}
}
private synchronized void saveLocation(CellLocation location) {
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
FileWriter writer = null;
try {
if(mOutputFile == null) {
File sdcard = Environment.getExternalStorageDirectory();
mOutputFile = new File(sdcard, sSaveDataFile);
}
Date now = new Date();
SimpleDateFormat sdf =
new SimpleDateFormat(mContext.getString(R.string.datafile_csv_datefmt));
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
writer = new FileWriter(mOutputFile, true);
String s = String.format("%s,%s,%d,%d,%d,%d,%d,%s,%.6f,%.6f,%d,%d\n",
sdf.format(now),
location.Operator,
location.MCC,
location.MNC,
location.LAC,
location.CID,
location.Signal,
location.Location.getProvider(),
location.Location.getLatitude(),
location.Location.getLongitude(),
((Double)location.Location.getAltitude()).intValue(),
((Float)location.Location.getAccuracy()).intValue());
writer.write(s);
} catch (IOException ioe) {
} finally {
if(writer != null) {
try {
writer.flush();
writer.close();
} catch (IOException ioe2) { }
}
}
}
}
public void setSaveData(boolean saveData) {
Activity a = (Activity)mContext;
if(saveData) {
a.setTitle(a.getString(R.string.app_name) + a.getString(R.string.saving_data));
// only create a new data file if the name has been null'd
if(sSaveDataFile == null) {
sSaveDataFile = getSaveDataFilename();
}
} else {
a.setTitle(a.getString(R.string.app_name));
sSaveDataFile = null;
}
mSaveData = saveData;
}
private String getSaveDataFilename() {
SimpleDateFormat sdf = new SimpleDateFormat(
mContext.getString(R.string.datafile_datefmt));
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
return String.format(mContext.getString(R.string.datafile_namefmt),
sdf.format(new Date()));
}
public void setDirectQueryMode(boolean directQuery) {
mDirectQuery = directQuery;
}
public static class CellLocation {
public String Operator;
public int MCC;
public int MNC;
public int LAC;
public int CID;
public int Signal;
public Location Location;
public CellLocation(String operator, int mcc, int mnc, int lac,
int cid, int signal, Location location) {
Operator = operator;
MCC = mcc;
MNC = mnc;
LAC = lac;
CID = cid;
Signal = signal;
Location = location;
}
}
}
<file_sep>/projects/cellfinder/src/com/codetastrophe/cellfinder/LocationFetcher.java
/* Hacked up code to get latitude and longitude for a cell id from google's servers.
*
* Most of this code came from the Android Open Source Project and carries the
* copyright and license information below.
*/
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.codetastrophe.cellfinder;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Locale;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import com.android.internal.location.ProtoRequestListener;
import com.android.internal.location.protocol.GCell;
import com.android.internal.location.protocol.GCellularProfile;
import com.android.internal.location.protocol.GDeviceLocation;
import com.android.internal.location.protocol.GLatLng;
import com.android.internal.location.protocol.GLocReply;
import com.android.internal.location.protocol.GLocReplyElement;
import com.android.internal.location.protocol.GLocRequest;
import com.android.internal.location.protocol.GLocRequestElement;
import com.android.internal.location.protocol.GLocation;
import com.android.internal.location.protocol.GPlatformProfile;
import com.android.internal.location.protocol.GPrefetchMode;
import com.android.internal.location.protocol.GcellularMessageTypes;
import com.android.internal.location.protocol.GlocationMessageTypes;
import com.android.internal.location.protocol.LocserverMessageTypes;
import com.android.internal.location.protocol.ResponseCodes;
import com.google.common.Config;
import com.google.common.android.AndroidConfig;
import com.google.common.io.protocol.ProtoBuf;
import com.google.masf.MobileServiceMux;
import com.google.masf.ServiceCallback;
import com.google.masf.protocol.PlainRequest;
import com.google.masf.protocol.Request;
public class LocationFetcher {
private static final String TAG = "LOCATIONFETCHER";
private static final String REQUEST_QUERY_LOC = "g:loc/ql";
private static final String MASF_SERVER_ADDRESS = "http://www.google.com/loc/m/api";
private static final String APPLICATION_NAME = "location";
private static final String APPLICATION_VERSION = "1.0";
private static final String PLATFORM_ID = "android";
private static final String DISTRIBUTION_CHANNEL = "android";
private static final String PLATFORM_BUILD = "android";
private static final String KEY_FILE = "gls.key";
private static final double E7 = 10000000.0;
private String mPlatformKey;
private Context mContext;
public interface LocationCallback {
public void GotLocation(int lac, int cid, int mcc, int mnc, double lat, double lon, int alt, int acc, int locType);
public void Error(String msg);
}
public LocationFetcher(Context context) {
AndroidConfig config = new AndroidConfig(context);
Config.setConfig(config);
MobileServiceMux.initialize
(MASF_SERVER_ADDRESS,
APPLICATION_NAME,
APPLICATION_VERSION,
PLATFORM_ID,
DISTRIBUTION_CHANNEL);
mContext = context;
}
public void getLocationFromCell(int lac, int cid, int mcc, int mnc, final LocationCallback callback) {
Log.d(TAG, String.format("looking for location for %d %d %d %d", mcc, mnc, lac, cid));
ProtoBuf requestElement = new ProtoBuf(LocserverMessageTypes.GLOC_REQUEST_ELEMENT);
ProtoBuf cellularProfile = getCellularProfile(lac, cid, mcc, mnc);
requestElement.setProtoBuf(GLocRequestElement.CELLULAR_PROFILE, cellularProfile);
// Request to send over wire
ProtoBuf request = new ProtoBuf(LocserverMessageTypes.GLOC_REQUEST);
request.addProtoBuf(GLocRequest.REQUEST_ELEMENTS, requestElement);
// Create a Platform Profile
ProtoBuf platformProfile = createPlatformProfile();
request.setProtoBuf(GLocRequest.PLATFORM_PROFILE, platformProfile);
ByteArrayOutputStream payload = new ByteArrayOutputStream();
try {
request.outputTo(payload);
} catch (IOException e) {
Log.e(TAG, "getNetworkLocation(): unable to write request to payload", e);
return;
}
// Creates request and a listener with a call back function
ProtoBuf reply = new ProtoBuf(LocserverMessageTypes.GLOC_REPLY);
Request plainRequest =
new PlainRequest(REQUEST_QUERY_LOC, (short)0, payload.toByteArray());
ProtoRequestListener listener = new ProtoRequestListener(reply, new ServiceCallback() {
public void onRequestComplete(Object result) {
ProtoBuf response = (ProtoBuf) result;
parseNetworkLocationReply(response, callback);
}
});
plainRequest.setListener(listener);
// Send request
MobileServiceMux serviceMux = MobileServiceMux.getSingleton();
serviceMux.submitRequest(plainRequest, true);
}
private ProtoBuf getCellularProfile(int lac, int cid, int mcc, int mnc) {
Date now = new Date();
ProtoBuf cellularProfile = new ProtoBuf(GcellularMessageTypes.GCELLULAR_PROFILE);
cellularProfile.setLong(GCellularProfile.TIMESTAMP, now.getTime());
cellularProfile.setInt(GCellularProfile.PREFETCH_MODE,
GPrefetchMode.PREFETCH_MODE_MORE_NEIGHBORS);
ProtoBuf primaryCell = new ProtoBuf(GcellularMessageTypes.GCELL);
primaryCell.setInt(GCell.LAC, lac);
primaryCell.setInt(GCell.CELLID, cid);
primaryCell.setInt(GCell.MCC, mcc);
primaryCell.setInt(GCell.MNC, mnc);
cellularProfile.setProtoBuf(GCellularProfile.PRIMARY_CELL, primaryCell);
return cellularProfile;
}
private void parseNetworkLocationReply(ProtoBuf response, LocationCallback callback) {
if (response == null) {
callback.Error("response is null");
return;
}
int status1 = response.getInt(GLocReply.STATUS);
if (status1 != ResponseCodes.STATUS_STATUS_SUCCESS) {
callback.Error("RPC failed with status " + status1);
return;
}
if (response.has(GLocReply.PLATFORM_KEY)) {
String platformKey = response.getString(GLocReply.PLATFORM_KEY);
if (!TextUtils.isEmpty(platformKey)) {
setPlatformKey(platformKey);
}
}
if (!response.has(GLocReply.REPLY_ELEMENTS)) {
callback.Error("no ReplyElement");
return;
}
ProtoBuf replyElement = response.getProtoBuf(GLocReply.REPLY_ELEMENTS);
int status2 = replyElement.getInt(GLocReplyElement.STATUS);
if (status2 != ResponseCodes.STATUS_STATUS_SUCCESS &&
status2 != ResponseCodes.STATUS_STATUS_FAILED) {
callback.Error("failed with status " + status2);
return;
}
double lat = 0, lng = 0;
int mcc = -1, mnc = -1, cid = -1, lac = -1;
int locType = -1;
int acc = -1, alt = 0;
Log.d(TAG, "getNetworkLocation(): Number of prefetched entries " +
replyElement.getCount(GLocReplyElement.DEVICE_LOCATION));
// most of the time there is only one response here, but loop through all of them
// just in case one of them is the real tower location and not just the centroid
for (int i = 0; i < replyElement.getCount(GLocReplyElement.DEVICE_LOCATION); i++ ) {
ProtoBuf device = replyElement.getProtoBuf(GLocReplyElement.DEVICE_LOCATION, i);
if (device.has(GDeviceLocation.LOCATION)) {
ProtoBuf deviceLocation = device.getProtoBuf(GDeviceLocation.LOCATION);
if (deviceLocation.has(GLocation.LAT_LNG)) {
lat = deviceLocation.getProtoBuf(GLocation.LAT_LNG).
getInt(GLatLng.LAT_E7) / E7;
lng = deviceLocation.getProtoBuf(GLocation.LAT_LNG).
getInt(GLatLng.LNG_E7) / E7;
}
if(deviceLocation.has(GLocation.ACCURACY)) {
acc = deviceLocation.getInt(GLocation.ACCURACY);
}
if(deviceLocation.has(GLocation.ALTITUDE)) {
alt = deviceLocation.getInt(GLocation.ALTITUDE);
}
if (deviceLocation.has(GLocation.LOC_TYPE)) {
locType = deviceLocation.getInt(GLocation.LOC_TYPE);
}
}
Log.d(TAG, String.format("lat %f lon %f locType %d",
lat, lng, locType));
// get cell info
if (device.has(GDeviceLocation.CELL)) {
ProtoBuf deviceCell = device.getProtoBuf(GDeviceLocation.CELL);
cid = deviceCell.getInt(GCell.CELLID);
lac = deviceCell.getInt(GCell.LAC);
if (deviceCell.has(GCell.MNC) && deviceCell.has(GCell.MCC)) {
mcc = deviceCell.getInt(GCell.MCC);
mnc = deviceCell.getInt(GCell.MNC);
}
}
Log.d(TAG, String.format("mcc %d mnc %d lac %d cid %d lat %f lon %f locType %d",
mcc, mnc, lac, cid, lat, lng, locType));
// if we have the actual tower location, break, otherwise keep going
// just in case
if(locType == GLocation.LOCTYPE_TOWER_LOCATION) {
break;
}
}
if(cid != -1 && lac != -1) {
callback.GotLocation(lac, cid, mcc, mnc, lat, lng, alt, acc, locType);
} else {
callback.Error("no cell information");
}
}
private ProtoBuf mPlatformProfile;
private ProtoBuf createPlatformProfile() {
if (mPlatformProfile == null) {
mPlatformProfile = new ProtoBuf(GlocationMessageTypes.GPLATFORM_PROFILE);
mPlatformProfile.setString(GPlatformProfile.VERSION, APPLICATION_VERSION);
mPlatformProfile.setString(GPlatformProfile.PLATFORM, PLATFORM_BUILD);
}
// Add Locale
Locale locale = Locale.getDefault();
if ((locale != null) && (locale.toString() != null)) {
mPlatformProfile.setString(GPlatformProfile.LOCALE, locale.toString());
}
// Add Platform Key
String platformKey = getPlatformKey();
if (!TextUtils.isEmpty(platformKey)) {
mPlatformProfile.setString(GPlatformProfile.PLATFORM_KEY, platformKey);
}
// Clear out cellular platform profile
mPlatformProfile.setProtoBuf(GPlatformProfile.CELLULAR_PLATFORM_PROFILE, null);
return mPlatformProfile;
}
private String getPlatformKey() {
if (mPlatformKey != null) {
return mPlatformKey;
}
try {
FileInputStream in = mContext.openFileInput(KEY_FILE);
DataInputStream ind = new DataInputStream(in);
mPlatformKey = ind.readUTF();
Log.d(TAG, "Using existing platform key " + mPlatformKey);
return mPlatformKey;
} catch (IOException e) {
}
Log.d(TAG, "No platform key found");
return null;
}
private void setPlatformKey(String platformKey) {
mPlatformKey = platformKey;
try {
FileOutputStream out = mContext.openFileOutput(KEY_FILE, Context.MODE_PRIVATE);
DataOutputStream outd = new DataOutputStream(out);
outd.writeUTF(platformKey);
outd.flush();
outd.close();
} catch (IOException e) {
}
}
}
<file_sep>/bob/2009/02/hhadump/hhadump.c
/*
* hhadump.c v0.2
*
* Copyright 2008-2009 <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
//file metadata structure
struct hha_file_info {
int dir; //directory name (offset into filename list)
int name; //file (offset into filename list)
int compress; //compression level (0-2)
int offset; //offset from start of file
int full_len; //uncompressed file size
int len; //file size in archive
};
//hha file header and metadata
struct hha_file {
int magic; //0xAC2FF34F
int version; //0x00010000, might represent "0.1.0.0"
int filenames_len; //length of filename list
int num_files; //length of hha_file_info array
char *filenames; //filename list
struct hha_file_info *fileinfo; //file metadata
};
//tidy up before exiting
void cleanup(struct hha_file *file, FILE *fp) {
free(file->filenames);
free(file->fileinfo);
fclose(fp);
}
static int create_dir(char *path) {
char *p;
for (p = path + 1; *p != '\0'; ++p) {
if (*p == '/') {
*p = '\0';
if (mkdir(path, 0755) && errno != EEXIST)
return 1;
*p = '/';
}
}
if (mkdir(path, 0755) && errno != EEXIST)
return 1;
return 0;
}
int main(int argc, char **argv) {
FILE *fp;
struct hha_file file;
int i, len;
if (argc < 2) {
printf("Usage: %s filename.hha\n", argv[0]);
return 1;
}
fp = fopen(argv[1], "rb");
if (!fp) {
perror("Cannot open file");
return 2;
}
len = fread(&file, sizeof(int), 4, fp);
if (len != 4) {
perror("Cannot read from file");
fclose(fp);
return 3;
}
if (file.magic != 0xAC2FF34F) {
printf("File %s is not an HHA file :(\n", argv[1]);
fclose(fp);
return 4;
}
printf("Magic number is: %X\n", file.magic);
printf("Version is: %x\n", file.version);
printf("Length of filenames: %d\n", file.filenames_len);
printf("Number of files: %d\n", file.num_files);
file.filenames = malloc(file.filenames_len);
file.fileinfo = malloc(file.num_files * sizeof(struct hha_file_info));
len = fread(file.filenames, 1, file.filenames_len, fp);
if (len != file.filenames_len) {
perror("Could not read filename list");
cleanup(&file, fp);
return 5;
}
len = fread(file.fileinfo, sizeof(struct hha_file_info), file.num_files, fp);
if (len != file.num_files) {
perror("Could not read file metadata");
cleanup(&file, fp);
return 6;
}
for (i = 0; i < file.num_files; i++) {
char *dirname, *filename;
dirname = file.filenames + file.fileinfo[i].dir;
filename = file.filenames + file.fileinfo[i].name;
if (file.fileinfo[i].compress == 0) {
FILE *nfp;
char *buf, *fullname;
printf("Extracting %s/%s\n", dirname, filename);
if (fseek(fp, file.fileinfo[i].offset, SEEK_SET)) {
perror("Could not seek to file data");
continue;
}
fullname = malloc(strlen(dirname) + strlen(filename) + 2);
sprintf(fullname, "%s/%s", dirname, filename);
buf = malloc(file.fileinfo[i].len);
len = fread(buf, file.fileinfo[i].len, 1, fp);
nfp = fopen(fullname, "wb");
if (!nfp) {
//this usually means the directory does not exist
char dir[256];
strcpy(dir, dirname);
if(create_dir(dir)) {
perror("Could not create directory");
return 7;
}
nfp = fopen(fullname, "wb");
}
if (!nfp) {
perror("Could not open file for writing");
} else {
fwrite(buf, file.fileinfo[i].len, 1, nfp);
fclose(nfp);
}
free(buf);
free(fullname);
} else {
//Compression type 1 is deflate/zlib
//Compression type 2 is LZMA
//too lazy to implement here
printf("Skipping file %s/%s, Compression #%d, %d/%d\n", dirname, filename, file.fileinfo[i].compress, file.fileinfo[i].len, file.fileinfo[i].full_len);
}
}
cleanup(&file, fp);
return 0;
}
<file_sep>/projects/satinfo/src/com/codetastrophe/android/satinfo/SatInfo.java
/*
* Copyright (C) 2008 <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* SatInfo.java
*
* Demonstrates using a 'hidden' Android System Service API call to collect
* data that isn't available through the SDK.
*
* To build this, you'll need to copy a few files from the Android source
* code into this project:
*
* frameworks/base/location/java/android/location/IGpsStatusListener.aidl
* frameworks/base/location/java/android/location/ILocationListener.aidl
* frameworks/base/location/java/android/location/ILocationManager.aidl
* frameworks/base/location/java/android/location/Address.aidl
*
* Place those files in an "android.location" namespace in your project in
* eclipse, and the Android plugin should generate the correct .java files
* that will make this thing run.
*/
package com.codetastrophe.android.satinfo;
import android.app.Activity;
import android.content.Context;
import android.location.IGpsStatusListener;
import android.location.ILocationManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.widget.TextView;
import java.lang.reflect.*;
public class SatInfo extends Activity {
public static final String DF = "DF";
private TextView mTextView = null;
private LocationManager mLocationManager = null;
private ILocationManager mILM;
private IGpsStatusListener mGpsListener = null;
private LocationListener mLocListener = null;
/** Called when the activity is first created. */
@SuppressWarnings("unchecked")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView = (TextView) findViewById(R.id.textview);
try {
// get a handle to the LocationManager system service
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// fix the private mService property to get access to
// the underlying service client
Class c = Class.forName(mLocationManager.getClass().getName());
Field f = c.getDeclaredField("mService");
f.setAccessible(true);
mILM = (ILocationManager) f.get(mLocationManager);
// add our gps status listener
mGpsListener = new GpsListener();
mILM.addGpsStatusListener(mGpsListener);
// add a locationlistener, just to enable the GPS
mLocListener = (LocationListener) mGpsListener;
mLocationManager.requestLocationUpdates("gps", 0, 0, mLocListener);
} catch (SecurityException e) {
Log.d(DF, "Exception: " + e.getMessage());
} catch (ClassNotFoundException e) {
Log.d(DF, "Exception: " + e.getMessage());
} catch (NoSuchFieldException e) {
Log.d(DF, "Exception: " + e.getMessage());
} catch (IllegalArgumentException e) {
Log.d(DF, "Exception: " + e.getMessage());
} catch (IllegalAccessException e) {
Log.d(DF, "Exception: " + e.getMessage());
} catch (RemoteException e) {
Log.d(DF, "Exception: " + e.getMessage());
}
}
@Override
public void onPause() {
super.onPause();
// remove listeners
try {
mILM.removeGpsStatusListener(mGpsListener);
} catch (RemoteException e) {
}
mLocationManager.removeUpdates(mLocListener);
}
private class GpsListener extends IGpsStatusListener.Stub implements
LocationListener {
// IGpsStatusListener overrides
@Override
public void onFirstFix(int ttff) throws RemoteException {
Log.d(DF, "onFirstFix");
}
@Override
public void onGpsStarted() throws RemoteException {
Log.d(DF, "onGpsStarted");
}
@Override
public void onGpsStopped() throws RemoteException {
Log.d(DF, "onGpsStopped");
}
@Override
public void onSvStatusChanged(int svCount, int[] prns, float[] snrs,
float[] elevations, float[] azimuths, int ephemerisMask,
int almanacMask, int usedInFixMask) throws RemoteException {
Log.d(DF, "onSvStatusChanged, svCount " + svCount);
try {
// build a new text string for our textview
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < svCount; i++) {
if (prns.length > i && snrs.length > i
&& elevations.length > i && azimuths.length > i) {
String s = String.format(
"PRN %d, SNR %.0f, ELEV %.0f, AZIM %.0f\n",
prns[i], snrs[i] * 10, elevations[i],
azimuths[i]);
sb.append(s);
}
}
// we can't set the textview text directly from this
// thread
mTextView.post(new Runnable() {
@Override
public void run() {
mTextView.setText(sb.toString());
}
});
} catch (Exception e) {
Log.d(DF, "Exception: " + e.toString());
}
}
// LocationListener implements
@Override
public void onLocationChanged(Location location) {
Log.d(DF, "onLocationChanged");
}
@Override
public void onProviderDisabled(String provider) {
Log.d(DF, "onProviderDisabled");
}
@Override
public void onProviderEnabled(String provider) {
Log.d(DF, "onProviderEnabled");
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(DF, "onStatusChanged");
}
}
}
<file_sep>/projects/cellfinder/src/com/codetastrophe/cellfinder/AboutActivity.java
/*
* Copyright (C) 2008 <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.codetastrophe.cellfinder;
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.view.Window;
public class AboutActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_LEFT_ICON);
setContentView(R.layout.about);
Window window = getWindow();
window.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
R.drawable.icon_48x48);
PackageManager packageManager = getPackageManager();
PackageInfo packageInfo;
try {
String me = getString(R.string.app_package);
packageInfo = packageManager.getPackageInfo(me, 0);
} catch (NameNotFoundException e) {
// oh well
return;
}
setTitle(String.format(getString(R.string.about_title_fmt, packageInfo.versionName)));
}
}
|
ec33df4246376ebb800361478a0757a6f9238e77
|
[
"Java",
"C"
] | 6
|
C
|
adit77799/codetastrophe
|
3a5c0a042e7393b3c4bc5062da76dc3c859c5958
|
42f2e02fadd9c317d42eac385aed8373dd4bc4f6
|
refs/heads/main
|
<repo_name>Heesu-H/D3-challenge<file_sep>/README.md
# D3-challenge
This project is to create a scatter plot using D3.js based on data taken from the 2014 American Community Survey (ACS) 1-year estimates to show any trends between different variables.
[Link to visualisation](https://heesu-h.github.io/D3-challenge/D3_data_journalism/)
## Objectives
- Create a scatter plot to visualise relationships between different variables concerning health.
- The plot should update upon selecting a new variable on either the x or y axis.
- A summary popup should appear when hovering over a data point.
## Technologies:
- CSS
- D3.js
- Github Pages
- HTML
- Javascript
<file_sep>/D3_data_journalism/assets/js/appBonus.js
// @TODO: YOUR CODE HERE!
//creating row for graph. will append a g group later
rowGraph = d3.select('.container').append('div').attr("class","row graph")
//defining svg area
var svgHeight = 600;
var svgWidth = 960;
//defining chart's margins as an object
var margin = {
top: 20,
right: 40,
bottom: 80,
left: 100
};
//centering graph
var chartHeight = svgHeight - margin.top - margin.bottom
var chartWidth = svgWidth - margin.right - margin.left
//appending svg area and setting dimensions
var svg = rowGraph.append('svg').attr('height', svgHeight).attr('width', svgWidth);
// appending a group to svg area and translating it to the right and down
var chartGroup = svg.append('g').attr('transform',`translate(${margin.left},${margin.top})`)
//Initial Parameters
var chosenXAxis = 'poverty';
var chosenYAxis = 'healthcare';
//creating scales FUNCTION
// x scale
function xScale(data, chosenXAxis) {
var xLinearScale = d3.scaleLinear()
.domain( [ d3.min(data, d => d[chosenXAxis])*0.85, d3.max(data, d => d[chosenXAxis]*1.1)] )
.range([0,chartWidth])
return xLinearScale
}
//y scale
function yScale(data, chosenYAxis) {
var yLinearScale = d3.scaleLinear()
.domain( [d3.min(data, d=>d[chosenYAxis]*0.5) ,d3.max(data, d=>d[chosenYAxis]*1.1)] )
.range([chartHeight,0])
return yLinearScale
}
//creating functions FUNCTION
// xAxis
function renderXAxis(newXScale, xAxis) {
var bottomAxis = d3.axisBottom(newXScale);
xAxis.transition()
.duration(1000)
.call(bottomAxis)
return xAxis;
}
// //yAxis
function renderYAxis(newYScale, yAxis) {
var leftAxis = d3.axisLeft(newYScale);
yAxis.transition()
.duration(1000)
.call(leftAxis)
return yAxis;
}
// appending x axis FUNCTION
// appending y axis
//function for updating circles group with transition to new circles
//x axis
function renderXCircles(circlesGroup,newXScale, chosenXAxis) {
circlesGroup.transition()
.duration(1000)
.attr('cx', d => newXScale(d[chosenXAxis]))
return circlesGroup;
}
//y axis
function renderYCircles(circlesGroup,newYScale,chosenYAxis) {
circlesGroup.transition()
.duration(1000)
.attr('cy', d => newYScale(d[chosenYAxis]))
return circlesGroup;
}
//function for updating abbrGroup
// x axis
function abbrGroupXAxis(abbrGroupX,newXScale,chosenXAxis) {
abbrGroupX.transition()
.duration(1000)
.attr('x', d=> newXScale(d[chosenXAxis]))
return abbrGroupX
}
// y axis
function abbrGroupYAxis(abbrGroupY,newYScale,chosenYAxis) {
abbrGroupY.transition()
.duration(1000)
.attr('y', d=> newYScale(d[chosenYAxis])+6)
return abbrGroupY
}
// Retrieve data from CSV file and create graph
d3.csv('assets/data/data.csv').then(data => {
//parsing data
var stateAbbr = data.map(d => d.abbr);
//x axis
var percentPoverty = data.map(d => +d.poverty);
var ageMedian = data.map(d => +d.age);
var householdIncome = data.map(d => +d.income);
//y axis
var percentLacksHealth = data.map(d => +d.healthcare);
var obese = data.map(d => +d.obesity);
var smokers = data.map(d => +d.smokes);
//checking if values are int
console.log(percentPoverty);
//creating initial scales
// xLinearScale
var xLinearScale = xScale(data, chosenXAxis);
// yLinearScale
var yLinearScale = yScale(data, chosenYAxis);
console.log(yLinearScale(data[0]['poverty']))
//creating initial axis functions
var bottomAxis = d3.axisBottom(xLinearScale)
var leftAxis = d3.axisLeft(yLinearScale)
// appending initial x axis
xAxis = chartGroup.append('g')
.classed('x-axis',true)
.attr("transform",`translate(0,${chartHeight})`)
.call(bottomAxis)
// appending initial y axis
yAxis = chartGroup.append('g')
.classed('y-axis',true)
.call(leftAxis)
//append initial group for circles
var circlesGroup = chartGroup.append('g').selectAll('circle')
.data(data)
.enter()
.append('circle')
.attr('cx', d => xLinearScale(d[chosenXAxis]))
.attr('cy', d => yLinearScale(d[chosenYAxis]))
.attr("r", 15)
.classed('stateCircle',true);
// group for state abbreviations
var abbrGroup = chartGroup.append('g').selectAll('text')
.data(data)
.enter()
.append('text')
.attr('x', d => xLinearScale(d[chosenXAxis]))
.attr('y', d => yLinearScale(d[chosenYAxis])+6)
.text(d=> d.abbr)
.classed('stateText',true)
// labels group
//x labels
var xLabelsGroup = chartGroup.append('g')
.attr("transform", `translate(${chartWidth/2},${chartHeight})`)
var povertyXLabel = xLabelsGroup.append('text')
.attr('x',-30).attr('y',35)
.attr('value','poverty')
.classed('active',true)
.text("In Poverty (%)")
var ageXLabel = xLabelsGroup.append('text')
.attr('x',-32).attr('y',55)
.attr('value','age')
.classed('inactive',true)
.text("Age (Median)")
var householdIncomeXLabel = xLabelsGroup.append('text')
.attr('x',-30).attr('y',75)
.attr('value','income')
.classed('inactive',true)
.text("Household Income (Median)")
// y labels
var yLabelsGroup = chartGroup.append('g')
.attr('transform',`translate(0,${chartHeight/2}) rotate(-90)`);
var healthcareYLabel = yLabelsGroup
.append('text')
.attr('x',0).attr('y',-40)
.attr('value','healthcare')
.classed('active',true)
.text('Lacks Healthcare (%)')
var smokesYlabel = yLabelsGroup
.append('text')
.attr('x',0).attr('y',-60)
.attr('value','smokes')
.classed('inactive', true)
.text('Smokes (%)')
var obeseYLabel = yLabelsGroup
.append('text')
.attr('x',0).attr('y',-80)
.attr('value','obesity')
.classed('inactive', true)
.text('Obese (%)');
//initialising tooltip
var xAxisTab = 'In Poverty (%)'
var yAxisTab = 'Lacks Healthcare (%)'
var toolTip = d3.tip().attr('class','tooltip d3-tip')
.offset([80,60])
.html(d => `<strong>State: ${d.state}</strong></br><strong> ${xAxisTab}: ${d[chosenXAxis]}</strong></br><strong>${yAxisTab}: ${d[chosenYAxis]}</strong>`);
chartGroup.call(toolTip);
circlesGroup.on('mouseover', d => {
toolTip.show(d,this);
}).on('mouseout', d => toolTip.hide(d));
abbrGroup.on('mouseover', d => {
toolTip.show(d,this);
}).on('mouseout', d => toolTip.hide(d));
xLabelsGroup.selectAll("text")
.on("click", function() {
var value = d3.select(this).attr('value');
if (value !== chosenXAxis) {
chosenXAxis = value;
//updating x scale and x axis
xLinearScale = xScale(data, chosenXAxis);
xAxis = renderXAxis(xLinearScale, xAxis);
//updating circles with new x values
circlesGroup = renderXCircles(circlesGroup,xLinearScale,chosenXAxis);
//updating abbreviations locations on x axis
abbrGroup = abbrGroupXAxis(abbrGroup,xLinearScale,chosenXAxis)
if (chosenXAxis === 'age') {
ageXLabel
.classed('active',true)
.classed('inactive', false);
povertyXLabel
.classed('active',false)
.classed('inactive',true);
householdIncomeXLabel
.classed('active',false)
.classed('inactive', true);
xAxisTab = 'Age';
} else if (chosenXAxis === 'income') {
ageXLabel
.classed('active',false)
.classed('inactive', true);
povertyXLabel
.classed('active',false)
.classed('inactive',true);
householdIncomeXLabel
.classed('active',true)
.classed('inactive', false);
xAxisTab = 'Median Household Income ($)';
} else {
ageXLabel
.classed('active',false)
.classed('inactive', true);
povertyXLabel
.classed('active',true)
.classed('inactive',false);
householdIncomeXLabel
.classed('active',false)
.classed('inactive', true);
xAxisTab = 'In Poverty (%)';
}
// end of if statement
}
//end of x axis on-click function
})
//updating circles position on y axis
yLabelsGroup.selectAll("text")
.on("click", function() {
var value = d3.select(this).attr('value');
if (value !== chosenYAxis) {
chosenYAxis = value;
//updating x scale and x axis
yLinearScale = yScale(data, chosenYAxis);
yAxis = renderYAxis(yLinearScale, yAxis);
//updating circles with new x values
circlesGroup = renderYCircles(circlesGroup,yLinearScale,chosenYAxis);
//updating abbreviations locations on x axis
abbrGroup = abbrGroupYAxis(abbrGroup,yLinearScale,chosenYAxis)
if (chosenYAxis === 'smokes') {
healthcareYLabel
.classed('active',false)
.classed('inactive', true);
smokesYlabel
.classed('active',true)
.classed('inactive', false);
obeseYLabel
.classed('active',false)
.classed('inactive', true);
yAxisTab = 'Smokes (%)';
} else if (chosenYAxis === 'obesity') {
healthcareYLabel
.classed('active',false)
.classed('inactive', true)
smokesYlabel
.classed('active',false)
.classed('inactive', true)
obeseYLabel
.classed('active',true)
.classed('inactive', false)
yAxisTab = 'Is Obese (%)';
} else {
healthcareYLabel
.classed('active',true)
.classed('inactive', false)
smokesYlabel
.classed('active',false)
.classed('inactive', true)
obeseYLabel
.classed('active',false)
.classed('inactive', true)
yAxisTab = 'Lacks Healthcare (%)';
}
// end of if statement
}
// end of y axis on click function
})
//end of 'then'
})
|
688d1675931532b12cc046bd333633fa7aab6fc7
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
Heesu-H/D3-challenge
|
930dc2c3ca0af906004b71059b68c69962adf1b1
|
d4192d143d85c9bb49a6207e69d890321ff4edfe
|
refs/heads/master
|
<file_sep>import turtle
def drawSquare(t, sz):
for i in range(4):
t.forward(sz)
t.left(90)
def Instruct(t, sz, axis, iter):
for j in range(iter):
drawSquare(t, sz)
t.penup()
t.goto(axis, axis)
t.pendown()
sz = sz + 20
axis = axis -10
wn = turtle.Screen()
wn.bgcolor("lightgreen")
alex = turtle.Turtle()
alex.color("hotpink")
alex.pensize(3)
Instruct(alex, 20, -10.0, 6)
wn.exitonclick()<file_sep># squareDesign
A practice exercise from "How to Think Like a Computer Scientist" where you have to make a turtle draw a square within a square 6 times.
|
89f6e05f49c37d5c722671f6f139454a2c2a6105
|
[
"Markdown",
"Python"
] | 2
|
Python
|
iamanissa/squareDesign
|
fae0eb5cf3da00fce0a8a7ef5b3f982cd6ea44fb
|
3f6637fd7cba5261948d26e4a69963256986658f
|
refs/heads/master
|
<file_sep>package autosms.ankur.com.autosms;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.ArraySet;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* Created by arpit on 7/17/2016.
*/
public class SelectMessage extends AppCompatActivity implements ConnectivityReceiver.ConnectivityReceiverListener{
private ListView list = null;
private Button addNew = null;
private EditText newMessage = null;
private List<String> messageList = null;
private SharedPreference sharedPreference = null;
private String messageSelected = null ;
private Spinner spinner = null ;
private Button go = null ;
private Message_list_adapter adapter ;
private TextView display_selected_message = null ;
@Override
public void onNetworkConnectionChanged(boolean isConnected) {
if (!isConnected)
Toast.makeText(SelectMessage.this, "No Internet Connection....", Toast.LENGTH_LONG).show();
}
private boolean checkConnection() {
boolean isConnected = ConnectivityReceiver.isConnected();
if (!isConnected)
Toast.makeText(SelectMessage.this, "No Internet Connection !!", Toast.LENGTH_SHORT).show();
return isConnected;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_message);
sharedPreference = new SharedPreference();
list = (ListView)findViewById(R.id.list);
spinner = (Spinner) findViewById(R.id.senderid_spinner);
go = (Button)findViewById(R.id.buttonGo) ;
addNew = (Button)findViewById(R.id.btnNew);
newMessage = (EditText)findViewById(R.id.etmessage);
newMessage.setVisibility(View.INVISIBLE);
display_selected_message = (TextView)findViewById(R.id.displayMessage) ;
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> spinner_adapter = ArrayAdapter.createFromResource(this,
R.array.senderid_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
spinner_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(spinner_adapter);
spinner.setSelected(false);
messageList = sharedPreference.getMessages(getApplicationContext());
if(messageList == null)
messageList = new ArrayList<>() ;
/*adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, messageList);*/
adapter = new Message_list_adapter(this, messageList) ;
list.setAdapter(adapter);
if(messageList != null) {
adapter.notifyDataSetChanged();
}
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
newMessage.setVisibility(View.INVISIBLE);
messageSelected = messageList.get(position);
display_selected_message.setText(messageSelected);
Toast.makeText(SelectMessage.this, "Selected Message :: " + messageSelected, Toast.LENGTH_SHORT).show();
}
});
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
AlertDialog diaBox = AskOption(position);
diaBox.show();
return false;
}
});
go.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(messageSelected != null) {
String items = spinner.getSelectedItem().toString();
Bundle b = new Bundle();
b.putString("Message", messageSelected);
b.putString("Senderid", items);
Intent i = new Intent(SelectMessage.this, Receipents.class);
i.putExtras(b);
startActivity(i);
}else{
Toast.makeText(SelectMessage.this, "No Message is selected !! :(", Toast.LENGTH_SHORT).show();
}
}
});
addNew.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
newMessage.setVisibility(View.VISIBLE);
String message = newMessage.getText().toString();
//Toast.makeText(SelectMessage.this, "Written Text = " + message, Toast.LENGTH_SHORT).show();
if(message != null && !"".equalsIgnoreCase(message)){
Log.d("ButtonClicked ::", "Message=" + message);
sharedPreference.addMessages(getApplicationContext(), message);
messageSelected = message ;
display_selected_message.setText(messageSelected);
messageList.add(0,message) ;
adapter.notifyDataSetChanged();
Log.d("ButtonClicked ::", "Message=" + message + " is now add size = " + messageList.size());
newMessage.setText(null);
newMessage.setVisibility(View.INVISIBLE);
}
}
});
}
private AlertDialog AskOption(final int pos)
{
AlertDialog myQuittingDialogBox =new AlertDialog.Builder(this)
//set message, title, and icon
.setTitle("Delete")
.setMessage("Do you want to Delete")
.setIcon(R.drawable.delete)
.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//your deleting code
messageList.remove(pos) ;
adapter.notifyDataSetChanged();
dialog.dismiss();
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create();
return myQuittingDialogBox;
}
}
<file_sep>package autosms.ankur.com.autosms;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import java.util.List;
/**
* Created by Ankur on 7/19/2016.
*/
public class Message_list_adapter extends ArrayAdapter<String> {
private List<String> messages ;
private Context c ;
public Message_list_adapter(Context con, List<String> numbers) {
super(con, 0,numbers);
this.c = con ;
this.messages = numbers;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(c);
v = vi.inflate(R.layout.message_list_elements, null);
}
TextView tv = (TextView) v.findViewById(R.id.messageid);
tv.setText(messages.get(position));
//Toast.makeText(v.getContext(), "Number Added " + numbers.get(position).toString(), Toast.LENGTH_SHORT).show();
Log.d("ListAdapter element ", messages.get(position));
return v ;
}
}
<file_sep># AutoSms
Processes the contacts on the phone.
Allows you to send same/saved messages to multiple people at a time.
Phone number inputs can be from phone contacts or via direct input from user.
<file_sep>package autosms.ankur.com.autosms;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
public class Receipents extends AppCompatActivity implements ConnectivityReceiver.ConnectivityReceiverListener{
private Button getPhone ;
private EditText getPhoneNUmber ;
private Button setPhoneNumber ;
private List<String> numberList ;
private List_Adapter adapter ;
private ListView list ;
private Button send ;
private String message ;
private String senderId ;
private String finalStringUrl ;
private String pattern = "^[A-Za-z0-9. ]+$";
final int PICK_CONTACT = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receipents);
message = getIntent().getExtras().getString("Message");
senderId = getIntent().getExtras().getString("Senderid");
message = getGoodMessage(message) ;
getPhone = (Button)findViewById(R.id.getPhoneBook) ;
getPhoneNUmber = (EditText)findViewById(R.id.setPhoneNumber) ;
setPhoneNumber = (Button)findViewById(R.id.setNumber) ;
list = (ListView)findViewById(R.id.listDisplay) ;
send = (Button)findViewById(R.id.sendMessage) ;
numberList = new ArrayList<>() ;
adapter = new List_Adapter(Receipents.this,numberList) ;
//numberList.add("Default Number") ;
list.setAdapter(adapter);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkConnection()){
//Toast.makeText(Receipents.this, "No Internet Connection....", Toast.LENGTH_LONG).show();
String number_to_add = "";
if (numberList.size() > 0) {
for (int i = 0; i < numberList.size(); i++) {
number_to_add = number_to_add + numberList.get(i) + ",";
}
if (message.matches(pattern))
finalStringUrl = "http://my.b2bsms.co.in/API/WebSMS/Http/v1.0a/index.php?username=petrol&password=<PASSWORD>&sender=" + senderId + "&to=";
else
finalStringUrl = "http://my.b2bsms.co.in/API/WebSMS/Http/v1.0a/index.php?username=petrol&password=<PASSWORD>&sender=" + senderId + "&to=";
finalStringUrl = finalStringUrl + number_to_add + "&message=" + message + "&reqid=1&format=" +
"text&route_id=&sendondate=16-07-2016T11:39:33";
if (!message.matches(pattern))
finalStringUrl = finalStringUrl + "&msgtype=unicode";
//Toast.makeText(Receipents.this, finalStringUrl, Toast.LENGTH_SHORT).show();
Log.d("Recepients : ", finalStringUrl);
String resp1 = volleyCall(finalStringUrl);
if (resp1 != null) {
finish();
} else {
Toast.makeText(Receipents.this, "Message Sending Failed !!", Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(Receipents.this, "No numbers are Selected !! :(", Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(Receipents.this, "No Internet Connection....", Toast.LENGTH_LONG).show();
}
}
});
getPhone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT);
} catch (Exception e) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
});
setPhoneNumber.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String phone_number = getGoodNumber(getPhoneNUmber.getText().toString()) ;
//Toast.makeText(Receipents.this, "Phone Number = " + phone_number + " and length = " + phone_number.length(), Toast.LENGTH_SHORT).show();
if (phone_number.length() > 10) {
Toast.makeText(Receipents.this, "Number entered is greater that 10 digits", Toast.LENGTH_SHORT).show();
} else if(phone_number.length() < 10){
Toast.makeText(Receipents.this, "Phone number has less that 10 integers and length = " + phone_number.length(), Toast.LENGTH_SHORT).show();
}else if(phone_number.length() == 10){
phone_number = "91" + phone_number ;
numberList.add(0,phone_number) ;
adapter.notifyDataSetChanged();
}
getPhoneNUmber.setText(null);
}
});
}
private String getGoodMessage(String message) {
String returnMessage = "" ;
for(int i = 0; i < message.length(); i++){
if(Character.isWhitespace(message.charAt(i)))
returnMessage = returnMessage + "+" ;
else
returnMessage = returnMessage + message.charAt(i) ;
}
return returnMessage;
}
private boolean checkConnection() {
boolean isConnected = ConnectivityReceiver.isConnected();
if (!isConnected)
Toast.makeText(Receipents.this, "No Internet Connection !!", Toast.LENGTH_SHORT).show();
return isConnected;
}
public String volleyCall(String url) {
final List<String> resp = new ArrayList<>();
RequestQueue queue = Volley.newRequestQueue(this);
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
resp.add(response);
Toast.makeText(Receipents.this, "Message is delivered", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Receipents.this, "Message Not Sent, Connection Error", Toast.LENGTH_SHORT).show();
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
return ("response");
}
public String getGoodNumber(String number){
String final_number = "" ;
for(int i = 0; i < number.length(); i++){
if(Character.isDigit(number.charAt(i))) {
final_number = final_number + number.charAt(i) ;
}
}
return final_number ;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
try
{
if (requestCode == PICK_CONTACT)
{
Cursor cursor = managedQuery(intent.getData(), null, null, null, null);
cursor.moveToNext();
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
String phone=cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER));
String phoneNumber="test";
if ( phone.equalsIgnoreCase("1"))
phone = "true";
else
phone = "false" ;
if (Boolean.parseBoolean(phone))
{
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
while (phones.moveToNext())
{
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
}
//Toast.makeText(this, "You are selected Contact name "+name, Toast.LENGTH_LONG).show();
//Toast.makeText(Receipents.this, "Phone Number = " + phoneNumber, Toast.LENGTH_SHORT).show();
if (phoneNumber.length() > 10) {
String one = getGoodNumber(phoneNumber) ;
//Toast.makeText(Receipents.this, "One string = " + one, Toast.LENGTH_SHORT).show();
String p = "91" + one.substring(one.length() - 10).toString();//phoneNumber.substring(phoneNumber.length() - 3).toString();
numberList.add(0,p) ;
adapter.notifyDataSetChanged();
} else if(phoneNumber.length() < 10){
Toast.makeText(Receipents.this, "Phone number has less that 10 integers", Toast.LENGTH_SHORT).show();
}else if(phoneNumber.length() == 10){
numberList.add(0,phoneNumber.toString()) ;
adapter.notifyDataSetChanged();
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onNetworkConnectionChanged(boolean isConnected) {
if (!isConnected)
Toast.makeText(Receipents.this, "No Internet Connection....", Toast.LENGTH_LONG).show();
else
Toast.makeText(Receipents.this, "Internet Connection Back Again....", Toast.LENGTH_LONG).show();
}
}
|
06338bd12e30ecee59b009ad919ffed1dc5c6672
|
[
"Markdown",
"Java"
] | 4
|
Java
|
ankurshukla1993/AutoSms
|
026ba07f5129749d5270d7f042b1f202bd2ef668
|
a38459339e561efe040d5e9f303c7d8271473c99
|
refs/heads/master
|
<file_sep>const EXTENSION_ID = 'ggofbbndaeneibofhcakocmknlcoleaa'
let programList = []
let isRepeat = false
let isSound = false
let isPlay = false
let timer = null
/**
* プログラムタイマーのプログラム要素
*/
class SettingProgram {
constructor (time, defaultTime, token) {
this.time = time
this.defaultTime = defaultTime
this.token = token
}
}
/**
* Popupからのリクエスト受信
*/
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
let response = {}
switch (request.type) {
case 'get':
updateView()
break
case 'insert':
let settingProgram = new SettingProgram(request.time, request.defaultTime, request.token)
programList.push(settingProgram)
updateView()
break
case 'delete':
for (let i in programList) {
if (programList[i].token === request.token) {
programList.splice(i, 1)
}
}
updateView()
break
case 'order':
let program = programList[request['oldIndex']];
programList.splice(request['oldIndex'], 1)
programList.splice(request['newIndex'], 0, program);
break
case 'repeat':
isRepeat = request.isRepeat
break
case 'sound':
isSound = request.isSound
break
case 'start':
startTimer()
break
case 'end':
stopTimer()
break
case 'reset':
resetTimer()
break
}
sendResponse(response)
})
/**
* タイマー更新
*/
function updateTimer () {
let currentRap = getCurrentRap()
let updateComplete = false
if (currentRap.currentSecond > 0) {
currentRap.currentSecond--
updateComplete = true
}
if (!updateComplete && currentRap.currentMinute > 0) {
currentRap.currentMinute--
currentRap.currentSecond = 59
updateComplete = true
}
if (!updateComplete) {
currentRap.currentHour--
currentRap.currentMinute = 59
currentRap.currentSecond = 59
}
const targetProgram = programList[currentRap.currentProgram]
targetProgram.time.hour = currentRap.currentHour
targetProgram.time.minute = currentRap.currentMinute
targetProgram.time.second = currentRap.currentSecond
const updateParam = {
type: 'updateTime',
currentRap: currentRap
}
chrome.runtime.sendMessage(EXTENSION_ID, updateParam)
// chrome.runtime.sendMessage(updateParam)
// 0秒になったか
const isZero = currentRap.currentHour === 0 && currentRap.currentMinute === 0 && currentRap.currentSecond === 0
if (isZero) {
let message = 'Finished : ' + currentRap.currentDefaultTime + '\n'
if (currentRap.nextDefaultTime) {
message += 'Next : ' + currentRap.nextDefaultTime
}
// ポップアップを表示する
chrome.notifications.create({
type: 'basic',
iconUrl: '../images/icon-32.png',
title: 'Good Job !',
message: message,
requireInteraction: false,
silent: true,
priority: 0
})
// アラームを鳴らす
if (isSound) {
play()
}
// タイマーを止める
if (currentRap.currentProgram === programList.length - 1) {
if (isRepeat) {
resetTimer()
} else {
stopTimer()
}
}
}
}
function getCurrentRap () {
let currentProgram = 0
let currentHour = 0
let currentMinute = 0
let currentSecond = 0
let currentToken = ''
let currentDefaultTime = ''
let nextDefaultTime = ''
for (let i in programList) {
if (programList[i]) {
const program = programList[i]
currentHour = program.time.hour
currentMinute = program.time.minute
currentSecond = program.time.second
currentToken = program.token
currentProgram = parseInt(i)
currentDefaultTime = zeroPadding(program.defaultTime.hour) + ':' + zeroPadding(program.defaultTime.minute) + ':' + zeroPadding(program.defaultTime.second)
if (programList.length - 1 > parseInt(i)) {
let nextProgram = programList[parseInt(i) + 1]
nextDefaultTime = zeroPadding(nextProgram.defaultTime.hour) + ':' + zeroPadding(nextProgram.defaultTime.minute) + ':' + zeroPadding(nextProgram.defaultTime.second)
} else if (isRepeat) {
let nextProgram = programList[0]
nextDefaultTime = zeroPadding(nextProgram.defaultTime.hour) + ':' + zeroPadding(nextProgram.defaultTime.minute) + ':' + zeroPadding(nextProgram.defaultTime.second)
} else {
nextDefaultTime = ''
}
if (currentHour !== 0 || currentMinute !== 0 || currentSecond !== 0) {
break
}
}
}
const result = {
'currentProgram': currentProgram,
'currentHour': currentHour,
'currentMinute': currentMinute,
'currentSecond': currentSecond,
'currentToken': currentToken,
'currentDefaultTime': currentDefaultTime,
'nextDefaultTime': nextDefaultTime
}
return result
}
function startTimer () {
if (timer) {
return
}
isPlay = true
timer = window.setInterval(updateTimer, 1000)
chrome.browserAction.setBadgeText({text: 'ON'})
chrome.browserAction.setBadgeBackgroundColor({color: '#4688F1'})
updateView()
}
function stopTimer () {
clearInterval(timer)
timer = null
isPlay = false
chrome.browserAction.setBadgeText({text: 'OFF'})
chrome.browserAction.setBadgeBackgroundColor({color: '#b3b3b4'})
updateView()
}
function resetTimer () {
for (let i in programList) {
const program = programList[i]
program.time.hour = program.defaultTime.hour
program.time.minute = program.defaultTime.minute
program.time.second = program.defaultTime.second
}
updateView()
}
function updateView () {
const param = {
type: 'updateView',
programList: programList,
isRepeat: isRepeat,
isSound: isSound,
isPlay: isPlay
}
chrome.runtime.sendMessage(EXTENSION_ID, param)
// chrome.runtime.sendMessage(param)
}
// 0埋め処理
function zeroPadding (num) {
return ('0' + num).slice(-2)
}
// audio要素作成
const audio = document.createElement('audio')
// 音声ファイルを登録
const source = audio.appendChild(document.createElement('source'))
source.setAttribute('src', '../sounds/default.mp3')
audio.appendChild(source)
document.body.appendChild(audio)
// 音声再生
function play () {
// 音声再生
audio.play()
.then(function (result) {
})
.catch(function (exception) {
})
.finally(function (result) {
})
}
<file_sep># Interval Timer for Chrome Extensions
## Usage

## Install
https://chrome.google.com/webstore/detail/interval-timer/ggofbbndaeneibofhcakocmknlcoleaa
## Develop
### Install Package
```
npm install
```
### Watch and build
```
npm run dev:chrome
```
### Build extension
```
npm run build:chrome
```
## Docs
[generator-chrome-extension-kickstart](https://github.com/HaNdTriX/generator-chrome-extension-kickstart)
<file_sep>import $ from 'jquery'
import Sortable from 'sortablejs'
const EXTENSION_ID = 'ggofbbndaeneibofhcakocmknlcoleaa'
let sortableList = null
init()
let param = {
type: 'get'
}
chrome.runtime.sendMessage(EXTENSION_ID, param)
/**
* Init
*/
function init () {
// 設定した時間を表示するリストを作成
const el = $('#items')[0]
sortableList = Sortable.create(el, {
animation: 150,
onUpdate: function (evt) {
let param = {
type: 'order',
oldIndex: evt.oldIndex,
newIndex: evt.newIndex,
}
chrome.runtime.sendMessage(EXTENSION_ID, param)
}
})
initInputField()
initController()
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.type === 'updateTime') {
// 数値を更新する
const currentRap = request.currentRap
const time = setTime(currentRap.currentHour, currentRap.currentMinute, currentRap.currentSecond)
const timeText = zeroPadding(time.hour) + ':' + zeroPadding(time.minute) + ':' + zeroPadding(time.second)
$('#' + currentRap.currentToken + ' span').text(timeText)
}
if (request.type === 'updateView') {
// 数値を更新する
updateView(request)
}
sendResponse({})
})
}
/**
* InitInputField
*/
function initInputField () {
$('.input-field input').on('input', function () {
insertCheck()
})
// 時間を増やす
$('.up').on('click', (e) => up(e))
// 時間を減らす
$('.down').on('click', (e) => down(e))
}
/**
* InitController
*/
function initController () {
// Startボタン
$('#startBtn').on('click', function () {
chrome.runtime.sendMessage(EXTENSION_ID, { type: 'start' })
})
// Stopボタン
$('#stopBtn').on('click', function () {
chrome.runtime.sendMessage(EXTENSION_ID, { type: 'end' })
})
// Resetボタン
$('#resetBtn').on('click', function () {
chrome.runtime.sendMessage(EXTENSION_ID, { type: 'reset' })
})
// Repeatボタン
$('#repeat').on('change', function (e) {
let param = {
type: 'repeat',
isRepeat: e.currentTarget.checked
}
chrome.runtime.sendMessage(EXTENSION_ID, param)
})
// Soundボタン
$('#sound').on('change', function (e) {
let param = {
type: 'sound',
isSound: e.currentTarget.checked
}
chrome.runtime.sendMessage(EXTENSION_ID, param)
})
}
/**
* updateView
*/
function updateView (responseData) {
let programList = responseData.programList
$('#repeat').prop('checked', responseData.isRepeat)
$('#sound').prop('checked', responseData.isSound)
$('#items').empty()
if (programList.length === 0) {
$('.controller').removeClass('is-show')
} else {
$('.controller').addClass('is-show')
}
for (let i in programList) {
if (programList.hasOwnProperty(i)) {
const program = programList[i]
const time = setTime(program.time.hour, program.time.minute, program.time.second)
const timeText = zeroPadding(time.hour) + ':' + zeroPadding(time.minute) + ':' + zeroPadding(time.second)
const token = program.token
const timer = '<li id="' + token + '" class="timer"><span>' + timeText + '</span><div class="close icon"></div></li>'
$('#items').append(timer)
// 削除の処理を定義しておく
$('#' + token + ' .close').on('click', function () {
const param = {
type: 'delete',
token: token
}
chrome.runtime.sendMessage(EXTENSION_ID, param)
})
}
}
$('.up').off('click')
$('.down').off('click')
$('#setBtn').off('click')
$('#startBtn').off('click')
$('#stopBtn').off('click')
$('#resetBtn').off('click')
if (responseData.isPlay) {
$('.btn-layout').addClass('disabled')
$('#setBtn').removeClass('filled')
$('.close.icon').addClass('disabled')
$('.input-field div').addClass('disabled')
$('.program li').addClass('disabled')
$('.input-field input').prop('disabled', true)
sortableList.option('disabled', true)
$('#repeat').prop('disabled', true)
$('#sound').prop('disabled', true)
$('#startBtn').addClass('disabled')
$('#stopBtn').removeClass('disabled')
$('#resetBtn').addClass('disabled')
$('#stopBtn').on('click', function () {
chrome.runtime.sendMessage(EXTENSION_ID, { type: 'end' })
})
} else {
$('.btn-layout').removeClass('disabled')
$('.close.icon').removeClass('disabled')
$('.input-field div').removeClass('disabled')
$('.program li').removeClass('disabled')
$('.input-field input').prop('disabled', false)
sortableList.option('disabled', false)
$('#repeat').prop('disabled', false)
$('#sound').prop('disabled', false)
$('#stopBtn').addClass('disabled')
$('.up').on('click', (e) => up(e))
$('.down').on('click', (e) => down(e))
if (!isAllZero()) {
$('#startBtn').removeClass('disabled')
$('#startBtn').on('click', function () {
chrome.runtime.sendMessage(EXTENSION_ID, { type: 'start' })
})
} else {
$('#startBtn').addClass('disabled')
}
$('#resetBtn').removeClass('disabled')
$('#resetBtn').on('click', function () {
chrome.runtime.sendMessage(EXTENSION_ID, { type: 'reset' })
})
insertCheck()
}
}
// プログラムがすべて 0 か
function isAllZero () {
const programs = $('.program li')
for (let i = 0, max = programs.length; i < max; i++) {
if (programs[i].innerText !== '00:00:00') {
return false
}
}
return true
}
// プログラムタイマー追加
function insertProgram () {
const hour = $('#hour')
const minute = $('#minute')
const second = $('#second')
const time = setTime(hour.val(), minute.val(), second.val())
const token = Math.random().toString(36).slice(-8)
let param = {
type: 'insert',
time: {
hour: time.hour,
minute: time.minute,
second: time.second
},
defaultTime: {
hour: time.hour,
minute: time.minute,
second: time.second
},
token: token
}
chrome.runtime.sendMessage(EXTENSION_ID, param)
// 初期化
hour.val('')
minute.val('')
second.val('')
minute.focus()
insertCheck()
}
function up (e) {
const parent = $(e.currentTarget).parent()
const input = parent.find('input')
let value = input.val()
value++
input.val(value)
insertCheck()
}
function down (e) {
const parent = $(e.currentTarget).parent()
const input = parent.find('input')
let value = input.val()
if (value > 0) {
value--
}
input.val(value)
insertCheck()
}
// 0埋め処理
function zeroPadding (num) {
return ('0' + num).slice(-2)
}
// 時間を作る
function setTime (hour, minute, second) {
hour = parseInt(hour)
minute = parseInt(minute)
second = parseInt(second)
if (!second) {
second = 0
}
if (!minute) {
minute = 0
}
if (!hour) {
hour = 0
}
if (second >= 60) {
minute += parseInt(second / 60)
second = second % 60
}
if (minute >= 60) {
hour += parseInt(minute / 60)
minute = minute % 60
}
return {
hour: hour,
minute: minute,
second: second
}
}
// 追加ボタン
function insertCheck () {
const hour = $('#hour').val() ? parseInt($('#hour').val()) : 0
const minute = $('#minute').val() ? parseInt($('#minute').val()) : 0
const second = $('#second').val() ? parseInt($('#second').val()) : 0
$('#setBtn').off('click')
if (hour === 0 && minute === 0 && second === 0) {
$('#setBtn').removeClass('filled')
} else {
$('#setBtn').addClass('filled')
$('#setBtn').on('click', insertProgram)
}
}
|
a32a5b0e10264a0a857247927d6c3e333fe8c0ba
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
belltreeSzk/chrome-program-timer
|
0fede0fb3e81aef8c4f5d8432faa28aa8f6a62ac
|
a4d24e7fe491b81c85811c1be8ba2730a60100c4
|
refs/heads/master
|
<repo_name>Chacaroon/DevArtNotepad<file_sep>/MyNotepad/Presenter/Interfaces/INewFileNameView.cs
using System;
namespace MyNotepad.Presenter.Interfaces
{
public interface INewFileNameView : IView
{
event Action<string> SetNewFileName;
}
}<file_sep>/MyNotepad/View/OpenFileForm.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using MyNotepad.Presenter.Interfaces;
namespace MyNotepad.View
{
/// <summary>
/// Form for opening file from Database
/// </summary>
public partial class OpenFileForm : Form, IOpenFileView, IView
{
public event Action<string> ChoseFile;
public event Func<List<string>> FormLoad;
public OpenFileForm()
{
InitializeComponent();
}
private void OnFormLoad(object sender, EventArgs e)
{
listBox1.DataSource = FormLoad();
}
private void FileClick(object sender, MouseEventArgs e)
{
ChoseFile(listBox1.SelectedItem?.ToString());
}
private void OkButtonClick(object sender, EventArgs e)
{
ChoseFile(listBox1.SelectedItem?.ToString());
}
/// <summary>
/// Opens form as a dialog
/// </summary>
public new void Show()
{
ShowDialog();
}
/// <summary>
/// Show error message in messagebox
/// </summary>
/// <param name="errorMessage">Message to dispaly </param>
public void ShowError(string errorMessage)
{
MessageBox.Show(errorMessage);
}
}
}
<file_sep>/MyNotepad/Presenter/NotepadPresenter.cs
using MyNotepad.Helpers;
using MyNotepad.Presenter.Interfaces;
using MyNotepad.View;
using System.Data.Entity;
using System.Threading.Tasks;
using MyNotepad.DataAccess.Interfaces;
using MyNotepad.DataAccess.Repositories;
using File = MyNotepad.Model.File;
namespace MyNotepad.Presenter
{
public class NotepadPresenter : IPresenter
{
private readonly INotepadView _view;
private readonly IRepository<File> _fileRepository;
private File CurrentFile { get; set; }
public NotepadPresenter(INotepadView view, IRepository<File> fileRepository)
{
_view = view;
_fileRepository = fileRepository;
CurrentFile = new File();
_view.SaveFile += SaveFile;
_view.OpenFile += OpenFile;
_view.NewFile += () => { CurrentFile = new File(); };
}
public void Run()
{
_view.Show();
}
private async void SaveFile(string data)
{
if (!string.IsNullOrEmpty(CurrentFile.Name))
{
CurrentFile.Data = CompressionHelper.CompressToByteArray(data, CurrentFile.Name);
await _fileRepository.UpdateAsync(CurrentFile);
return;
}
var newFileNamePresenter = new NewFileNamePresenter(new EnterFileNameForm(), new FileRepository());
newFileNamePresenter.Run();
if (string.IsNullOrEmpty(newFileNamePresenter.NewFileName))
return;
CurrentFile.Name = newFileNamePresenter.NewFileName;
CurrentFile.Data = CompressionHelper.CompressToByteArray(data, newFileNamePresenter.NewFileName);
await _fileRepository.CreateAsync(CurrentFile);
}
private async Task<string> OpenFile()
{
var openFilePresenter = new OpenFilePresenter(new OpenFileForm(), new FileRepository());
openFilePresenter.Run();
if (string.IsNullOrEmpty(openFilePresenter.ChosenFile))
return null;
CurrentFile = await _fileRepository
.GetAll()
.SingleAsync(f => f.Name == openFilePresenter.ChosenFile);
return CompressionHelper.ExtractToString(CurrentFile.Data);
}
}
}<file_sep>/MyNotepad/View/EnterFileNameForm.cs
using System;
using System.Windows.Forms;
using MyNotepad.Presenter.Interfaces;
namespace MyNotepad.View
{
/// <summary>
/// Form for entering and validating new file name
/// </summary>
public partial class EnterFileNameForm : Form, INewFileNameView
{
public event Action<string> SetNewFileName;
public EnterFileNameForm()
{
InitializeComponent();
}
private void SaveButtonClick(object sender, EventArgs e)
{
SetNewFileName(fileNameTextBox.Text);
}
/// <summary>
/// Opens form as a dialog
/// </summary>
public new void Show()
{
ShowDialog();
}
/// <summary>
/// Show error message in messagebox
/// </summary>
/// <param name="errorMessage"> Message to dispaly </param>
public void ShowError(string errorMessage)
{
MessageBox.Show(errorMessage);
}
}
}
<file_sep>/MyNotepad/DataAccess/ApplicationContext.cs
using System.Data.Entity;
using MyNotepad.Model;
namespace MyNotepad.DataAccess
{
public class ApplicationContext : DbContext
{
public ApplicationContext() : base("DefaultConnection") { }
public DbSet<File> Files { get; set; }
}
}<file_sep>/MyNotepad/DataAccess/Interfaces/IRepository.cs
using System.Linq;
using System.Threading.Tasks;
namespace MyNotepad.DataAccess.Interfaces
{
public interface IRepository<T>
where T : class
{
IQueryable<T> GetAll();
Task<T> GetByIdAsync(long id);
Task CreateAsync(T item);
Task UpdateAsync(T item);
Task DeleteByIdAsync(long id);
}
}<file_sep>/MyNotepad/Presenter/Interfaces/IView.cs
namespace MyNotepad.Presenter.Interfaces
{
public interface IView
{
void Show();
void Close();
void ShowError(string errorMessage);
}
}<file_sep>/MyNotepad/View/Notepad.cs
using MyNotepad.Presenter.Interfaces;
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MyNotepad.View
{
public partial class NotepadForm : Form, INotepadView
{
private bool HasChanged { get; set; }
public event Action<string> SaveFile;
public event Func<Task<string>> OpenFile;
public event Action NewFile;
public NotepadForm()
{
InitializeComponent();
}
private void OnFormClosing(object sender, FormClosingEventArgs e)
{
if (!HasChanged)
return;
var window = MessageBox.Show(
"Do you want save file?",
"Notepad Closing",
MessageBoxButtons.YesNoCancel);
switch (window)
{
case DialogResult.Yes:
SaveFile(dataTextBox.Text);
break;
case DialogResult.Cancel:
e.Cancel = true;
break;
}
}
private void NewMenuItemClick(object sender, EventArgs e)
{
if (HasChanged)
{
var result = MessageBox.Show(
"All unsaved data will be lost! Do you want to continue?",
"Create new file",
MessageBoxButtons.OKCancel);
if (result == DialogResult.Cancel)
return;
}
NewFile();
dataTextBox.Text = "";
HasChanged = false;
}
private async void OpenMenuItemClick(object sender, EventArgs e)
{
if (HasChanged)
{
var result = MessageBox.Show(
"All unsaved data will be lost! Do you want to continue?",
"Create new file",
MessageBoxButtons.OKCancel);
if (result == DialogResult.Cancel)
return;
}
var text = await OpenFile();
if (string.IsNullOrEmpty(text))
return;
dataTextBox.Clear();
focusLable.Focus();
dataTextBox.Text = text;
HasChanged = false;
}
private void SaveMenuItemClick(object sender, EventArgs e)
{
SaveFile(dataTextBox.Text);
HasChanged = false;
}
public new void Show()
{
Application.Run(this);
}
public void ShowError(string errorMessage)
{
MessageBox.Show(errorMessage);
}
private void DataTextBox_TextChanged(object sender, EventArgs e)
{
HasChanged = true;
}
}
}
<file_sep>/MyNotepad/Helpers/CompressionHelper.cs
using System;
using System.IO;
using System.Text;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
namespace MyNotepad.Helpers
{
public static class CompressionHelper
{
private const int LEVEL_OF_COMPRESSION = 9;
public static byte[] CompressToByteArray(string data, string zipEntryName)
{
var dataToStream = new MemoryStream(Encoding.UTF8.GetBytes(data));
var outputMemStream = new MemoryStream();
var zipStream = new ZipOutputStream(outputMemStream);
zipStream.SetLevel(LEVEL_OF_COMPRESSION);
var newEntry = new ZipEntry(zipEntryName)
{
DateTime = DateTime.Now
};
zipStream.PutNextEntry(newEntry);
StreamUtils.Copy(dataToStream, zipStream, new byte[4096]);
zipStream.CloseEntry();
zipStream.IsStreamOwner = false;
zipStream.Close();
outputMemStream.Position = 0;
return outputMemStream.ToArray();
}
public static string ExtractToString(byte[] archiveFilenameIn)
{
var fs = new MemoryStream(archiveFilenameIn);
var zf = new ZipFile(fs);
var buffer = new byte[4096];
string result = null;
try
{
foreach (ZipEntry zipEntry in zf)
{
var zipStream = zf.GetInputStream(zipEntry);
using (var stream = new MemoryStream())
{
StreamUtils.Copy(zipStream, stream, buffer);
stream.Position = 0;
result = Encoding.UTF8.GetString(stream.ToArray());
}
}
}
finally
{
zf.IsStreamOwner = true;
zf.Close();
}
return result;
}
}
}<file_sep>/MyNotepad/Presenter/Interfaces/IOpenFileView.cs
using System;
using System.Collections.Generic;
namespace MyNotepad.Presenter.Interfaces
{
public interface IOpenFileView : IView
{
event Action<string> ChoseFile;
event Func<List<string>> FormLoad;
}
}<file_sep>/MyNotepad/Presenter/Interfaces/IPresenter.cs
namespace MyNotepad.Presenter.Interfaces
{
public interface IPresenter
{
void Run();
}
}<file_sep>/MyNotepad/Presenter/NewFileNamePresenter.cs
using MyNotepad.Model;
using MyNotepad.Presenter.Interfaces;
using System.Linq;
using MyNotepad.DataAccess.Interfaces;
namespace MyNotepad.Presenter
{
public class NewFileNamePresenter : IPresenter
{
private readonly INewFileNameView _view;
private readonly IRepository<File> _fileRepository;
public string NewFileName { get; private set; }
public NewFileNamePresenter(INewFileNameView view, IRepository<File> fileRepository)
{
_view = view;
_fileRepository = fileRepository;
_view.SetNewFileName += SetNewFileName;
}
public void Run()
{
_view.Show();
}
private void SetNewFileName(string fileName)
{
if (string.IsNullOrEmpty(fileName))
{
_view.ShowError("Filename in empty!");
return;
}
if (_fileRepository
.GetAll()
.Select(f => f.Name)
.Any(name => fileName == name))
{
_view.ShowError("Filename already exists");
return;
}
NewFileName = fileName;
_view.Close();
}
}
}<file_sep>/MyNotepad/Program.cs
using System;
using System.Windows.Forms;
using MyNotepad.DataAccess.Repositories;
using MyNotepad.Presenter;
using MyNotepad.View;
namespace MyNotepad
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var presenter = new NotepadPresenter(new NotepadForm(), new FileRepository());
presenter.Run();
}
}
}
<file_sep>/MyNotepad/DataAccess/Repositories/Repository.cs
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using MyNotepad.DataAccess.Interfaces;
using MyNotepad.Model;
namespace MyNotepad.DataAccess.Repositories
{
public class Repository<T> : IRepository<T>
where T : Entity
{
protected readonly ApplicationContext Context;
protected Repository()
{
Context = new ApplicationContext();
}
public IQueryable<T> GetAll()
{
return Context.Set<T>().AsQueryable();
}
public Task<T> GetByIdAsync(long id)
{
return Context.Set<T>().Where(i => i.Id == id).SingleOrDefaultAsync();
}
public async Task CreateAsync(T item)
{
Context.Set<T>().Add(item);
await Context.SaveChangesAsync();
}
public async Task UpdateAsync(T item)
{
Context.Entry(item).State = EntityState.Modified;
await Context.SaveChangesAsync();
}
public async Task DeleteByIdAsync(long id)
{
var item = await GetByIdAsync(id);
Context.Set<T>().Remove(item);
await Context.SaveChangesAsync();
}
}
}
<file_sep>/MyNotepad/DataAccess/Repositories/FilesRepository.cs
using MyNotepad.Model;
namespace MyNotepad.DataAccess.Repositories
{
public class FileRepository : Repository<File>
{
}
}<file_sep>/MyNotepad/Presenter/Interfaces/INotepadView.cs
using System;
using System.Threading.Tasks;
namespace MyNotepad.Presenter.Interfaces
{
public interface INotepadView : IView
{
event Action<string> SaveFile;
event Func<Task<string>> OpenFile;
event Action NewFile;
}
}<file_sep>/MyNotepad/Presenter/OpenFilePresenter.cs
using System.Linq;
using MyNotepad.DataAccess.Interfaces;
using MyNotepad.Model;
using MyNotepad.Presenter.Interfaces;
namespace MyNotepad.Presenter
{
public class OpenFilePresenter : IPresenter
{
public string ChosenFile { get; private set; }
private readonly IOpenFileView _view;
public OpenFilePresenter(IOpenFileView view, IRepository<File> fileRepository)
{
_view = view;
_view.FormLoad += () => fileRepository
.GetAll()
.Select(f => f.Name)
.ToList();
_view.ChoseFile += ChoseFile;
}
public void Run()
{
_view.Show();
}
private void ChoseFile(string fileName)
{
ChosenFile = fileName;
_view.Close();
}
}
}
|
d4c1d0b93fd09fad3619019a38de8dc3b7fac4b0
|
[
"C#"
] | 17
|
C#
|
Chacaroon/DevArtNotepad
|
4cab3cfcb8d68952f45d137cd4d09c4fdc1fcd66
|
5153ced4cfdb064e8e8c52a9b099f8a33559ed41
|
refs/heads/master
|
<file_sep>package nl.bongers.testdome;
import java.util.function.Function;
public class Train {
//private Hashtable<Integer, Integer> wagons;
private int[] wagons; //Van hashtable naar int[] niet veel sneller.
public Train(int wagonCount, Function<Integer, Integer> fillWagon) {
//wagons = new Hashtable<>(wagonCount);
wagons = new int[wagonCount];
for (int i = 0; i < wagonCount; i++) {
wagons[i] = fillWagon.apply(i);
//wagons.put(i, fillWagon.apply(i));
}
}
public static void main(String[] args) {
final long start = System.currentTimeMillis();
final int wagonCount = 100_000_000; //Dit is alleen acceptabel met int array. Niet met hashtable
final Train train = new Train(wagonCount, x -> x);
for (int i = 0; i < wagonCount; i++) {
System.out.println("Wagon: " + i + ", cargo: " + train.peekWagon(i)); //Log weglaten scheelt uiteraard veel tijd, maar lijkt me niet gewenst
}
System.out.println("Time: " + (System.currentTimeMillis() - start));
}
public int peekWagon(int wagonIndex) {
//return wagons.get(wagonIndex);
return wagons[wagonIndex];
}
}<file_sep>package nl.bongers.testdome;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
/**
* Implement a function folderNames, which accepts a string containing an XML file that specifies folder structure and returns
* all folder names that start with startingLetter. The XML format is given in the main below.
*
* For example, for the letter 'u' and the given XML file the function should return a collection
* with items "uninstall information" and "users" (in any order).
*/
public class Folders {
public static void main(String[] args) throws Exception {
String xml =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<folder name=\"c\">" +
"<folder name=\"program files\">" +
"<folder name=\"uninstall information\" />" +
"</folder>" +
"<folder name=\"users\" />" +
"</folder>";
final Folders folders = new Folders();
Collection<String> names = folders.folderNames(xml, 'u');
for(String name: names)
System.out.println(name);
}
public Collection<String> folderNames(String xml, char startingLetter) throws Exception {
final Document document = createDocumentFromXML(xml);
final List<String> folderNames = parseChildNodes(document.getChildNodes());
return folderNames
.stream()
.filter(f -> f.startsWith(Character.toString(startingLetter)))
.collect(Collectors.toList());
}
private Document createDocumentFromXML(String xml) throws Exception {
final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final InputSource inputSource = new InputSource(new StringReader(xml));
return builder.parse(inputSource);
}
private List<String> parseChildNodes(NodeList nodeList) {
final List<String> items = new ArrayList<>();
for (int i = 0; i < nodeList.getLength(); i++) {
final Node node = nodeList.item(i);
if (node.hasChildNodes()) {
items.addAll(parseChildNodes(node.getChildNodes()));
}
items.addAll(parseNodeAttributes(node.getAttributes()));
}
return items;
}
private List<String> parseNodeAttributes(NamedNodeMap attributes) {
final List<String> items = new ArrayList<>(attributes.getLength());
for (int i = 0; i < attributes.getLength(); i++) {
final String value = attributes.item(i).getNodeValue();
items.add(value);
}
return items;
}
}
|
021e4348a57f3a4ad945157e38875ee9e5baa959
|
[
"Java"
] | 2
|
Java
|
JanBongers/TestDome
|
1cccb18d766b82dd733c35e7d0f2adbe617e1696
|
893577bedac492a08522acf5b1a4654e74a50a5f
|
refs/heads/main
|
<file_sep>namespace FinalYearProject.Enums
{
public enum ControlStage
{
Completed,
InProgress,
InReview
}
}<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Word = Microsoft.Office.Interop.Word;
using System.Threading.Tasks;
using FinalYearProject.Enums;
using FinalYearProject.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.JSInterop;
using MudBlazor;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Color = Syncfusion.Drawing.Color;
namespace FinalYearProject.Services
{
public class ControlsService
{
private readonly DatabaseContext _context;
private readonly IWebHostEnvironment _environment;
private readonly IJSRuntime _jsRuntime;
public ControlsService(DatabaseContext context, IWebHostEnvironment environment, IJSRuntime jsRuntime)
{
_context = context;
_environment = environment;
_jsRuntime = jsRuntime;
}
// imports all new controls. User can force update already exists controls that match on control summary.
public async Task ImportControls(List<Control> listOfControls, bool forceUpdate = true)
{
foreach (var control in listOfControls)
{
if (await _context.Controls.AnyAsync(x => x.ControlSummary == control.ControlSummary))
{
if (forceUpdate)
{
var controlQuery = await _context.Controls.Where(x => x.ControlSummary == control.ControlSummary)
.ToListAsync();
foreach (var element in controlQuery)
{
element.ControlExpected = control.ControlExpected;
element.ControlTest = control.ControlTest;
}
}
}
else
{
await _context.AddAsync(control);
}
}
await _context.SaveChangesAsync();
}
public async Task<List<Control>> FetchAllControls()
{
return await _context.Controls.ToListAsync();
}
public async Task<List<ControlEvaluations>> FetchAllInReviewControlEvals()
{
return await _context.ControlEvaluations.Where(x => x.ControlStage == ControlStage.InReview).ToListAsync();
}
public async Task CreateControlEvaluationDocument(ControlEvaluations controlEvaluation)
{
const string templateUrl = "WordTemplate/Control_Evaluation.doc";
string controlName = $"ControlEvaluation-{controlEvaluation.AuditName}";
string controlUrl = $"WordControlEvaluations/{controlName}";
WordDocument wordDocument = new WordDocument();
FileStream fileStreamPath =
new FileStream($@"{templateUrl}", FileMode.Open, FileAccess.Read, FileShare.Write);
wordDocument.Open(fileStreamPath, FormatType.Automatic);
InsertHeadingsDocument(new BookmarksNavigator(wordDocument), controlEvaluation);
InsertControlTableDocument(wordDocument.Sections[0], controlEvaluation);
MemoryStream stream = new MemoryStream();
wordDocument.Save(stream, FormatType.Docx);
wordDocument.Close();
stream.Position = 0;
await _jsRuntime.SaveAs("ControlEvaluation.docx", stream.ToArray());
}
private void InsertHeadingsDocument(BookmarksNavigator bookmarksNavigator, ControlEvaluations controlEvaluation)
{
bookmarksNavigator.MoveToBookmark("headerAuditor");
bookmarksNavigator.InsertText(controlEvaluation.LeadAuditor);
bookmarksNavigator.MoveToBookmark("headerDateCreated");
bookmarksNavigator.InsertText(DateTimeOffset.Now.ToString("d"));
bookmarksNavigator.MoveToBookmark("headerJobName");
bookmarksNavigator.InsertText(controlEvaluation.AuditName);
bookmarksNavigator.MoveToBookmark("headerJobRef");
bookmarksNavigator.InsertText(controlEvaluation.Id.ToString());
}
private void InsertControlTableDocument(WSection section, ControlEvaluations controlEvaluation)
{
var table = section.Tables[0] as WTable;
int reference = 1;
if (table == null)
{
throw new Exception("An error has occurred. Please try again.");
}
foreach (var controlList in controlEvaluation.ControlsList)
{
reference = InsertRowIntoTable(table.AddRow(), controlList.Control, reference);
}
}
private int InsertRowIntoTable(WTableRow row, Control control, int reference)
{
var cellCollection = row.Cells;
row.RowFormat.BackColor = Color.White;
ChangeFontDetails(cellCollection[0].AddParagraph().AppendText(reference.ToString()));
ChangeFontDetails(cellCollection[1].AddParagraph().AppendText(control.ControlSummary));
ChangeFontDetails(cellCollection[2].AddParagraph().AppendText(control.ControlExpected));
ChangeFontDetails(cellCollection[3].AddParagraph().AppendText(control.ControlTest));
return ++reference;
}
private void ChangeFontDetails(
IWTextRange textRange, string font = "Century Gothic", int fontSize = 10, bool bold = false)
{
textRange.CharacterFormat.FontName = font;
textRange.CharacterFormat.FontSize = fontSize;
textRange.CharacterFormat.Bold = bold;
}
}
}<file_sep>using System;
using System.Threading.Tasks;
using FinalYearProject.Enums;
using FinalYearProject.Models;
using FinalYearProject.Services;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
using MudBlazor.Services;
namespace FinalYearProject
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddMudServices();
var builder = new SqlConnectionStringBuilder(
Configuration.GetConnectionString("Database"));
builder.Password = Configuration["DatabasePassword"];
services.AddDbContext<DatabaseContext>(options => options.UseSqlServer(builder.ConnectionString));
services.AddScoped<UserService>();
services.AddScoped<SignInOutService>();
services.AddScoped<ControlsService>();
services.AddScoped<EmailService>();
services.AddIdentityCore<User>().AddRoles<IdentityRole>()
.AddEntityFrameworkStores<DatabaseContext>()
.AddSignInManager()
.AddDefaultTokenProviders();
services.AddScoped<PasswordHasher<User>>();
services.AddAuthentication(options =>
{
options.DefaultScheme = "MyScheme";
}).AddCookie("MyScheme", options =>
{
options.Cookie.Name = "AuditControlGenAuth";
});
services.Configure<IdentityOptions>(options =>
{
options.User.RequireUniqueEmail = true;
});
services.AddScoped<IHostEnvironmentAuthenticationStateProvider>(sp => {
var provider = (ServerAuthenticationStateProvider) sp.GetRequiredService<AuthenticationStateProvider>();
return provider;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider ServiceProvider)
{
Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense(Configuration["SyncFusionKey"]);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
CreateRoles(ServiceProvider).Wait();
}
private async Task CreateRoles(IServiceProvider ServiceProvider)
{
//initializing custom roles
var roleManager = ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var UserManager = ServiceProvider.GetRequiredService<UserManager<User>>();
foreach (Role roleName in Enum.GetValues(typeof(Role)))
{
var roleExist = await roleManager.RoleExistsAsync(roleName.ToString());
if (!roleExist)
{
//create the roles and seed them to the database.
await roleManager.CreateAsync(new IdentityRole(roleName.ToString()));
}
}
// Create superUser. Password will be changed on setup
var poweruser = new User
{
UserName = "admin",
Email = "admin@admin",
EmailConfirmed = true,
};
var tempUser = new User
{
FirstName = "temp",
LastName = "temp",
UserName = "temp",
Email = "temp@temp",
EmailConfirmed = true
};
string password = "!!<PASSWORD>";
var user = await UserManager.FindByEmailAsync("admin");
var tUser = await UserManager.FindByEmailAsync("temp");
if (user == null)
{
Console.WriteLine("Creating Admin Account...");
var createPowerUser = await UserManager.CreateAsync(poweruser, password);
if (createPowerUser.Succeeded)
{
await UserManager.AddToRoleAsync(poweruser, Role.Developer.ToString());
Console.WriteLine("Admin Account Created...");
}
}
else
{
Console.WriteLine("Admin Account Already Exists...");
}
if (tUser == null)
{
Console.WriteLine("Creating Temp User...");
var createTempUser = await UserManager.CreateAsync(tempUser, password);
if (createTempUser.Succeeded)
{
await UserManager.AddToRoleAsync(tempUser, Role.Auditor.ToString());
Console.WriteLine("Temp User Created...");
}
}
else
{
Console.WriteLine("Temp User Already Exists...");
}
}
}
}
<file_sep>namespace FinalYearProject.Enums
{
public enum Role
{
Auditor,
Reviewer,
Developer
}
}<file_sep>using System.Collections.Generic;
using FinalYearProject.Enums;
using Microsoft.AspNetCore.Identity;
namespace FinalYearProject.Models
{
public class User : IdentityUser
{
public List<ControlEvaluations> ControlEvaluations { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}<file_sep>namespace FinalYearProject.Models
{
public class ControlEvaluationControls
{
public int Id { get; set; }
public Control Control { get; set; }
}
}<file_sep>namespace FinalYearProject.Models
{
public class Control
{
public int Id { get; set; }
public string ControlSummary { get; set; }
public string ControlExpected { get; set; }
public string ControlTest { get; set; }
}
}<file_sep>namespace FinalYearProject.Models.ViewModels
{
public class RegisteredUsersViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public string Role { get; set; }
}
}<file_sep>using FinalYearProject.Enums;
namespace FinalYearProject.Models.Payloads
{
public class EditProfilePayload
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public Role Role { get; set; }
}
}<file_sep>using System.ComponentModel.DataAnnotations;
namespace FinalYearProject.Models.Payloads
{
public class SignInPayload
{
public string EmailAddress { get; set; }
public string Password { get; set; }
}
}<file_sep>using Microsoft.EntityFrameworkCore.Migrations;
namespace FinalYearProject.Migrations
{
public partial class AddedUserTableAndAddedPluralToTables : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_ControlEvaluationControl_Control_ControlId",
table: "ControlEvaluationControl");
migrationBuilder.DropForeignKey(
name: "FK_ControlEvaluationControl_ControlEvaluation_ControlEvaluationsId",
table: "ControlEvaluationControl");
migrationBuilder.DropPrimaryKey(
name: "PK_ControlEvaluationControl",
table: "ControlEvaluationControl");
migrationBuilder.DropPrimaryKey(
name: "PK_ControlEvaluation",
table: "ControlEvaluation");
migrationBuilder.DropPrimaryKey(
name: "PK_Control",
table: "Control");
migrationBuilder.RenameTable(
name: "ControlEvaluationControl",
newName: "ControlEvaluationControls");
migrationBuilder.RenameTable(
name: "ControlEvaluation",
newName: "ControlEvaluations");
migrationBuilder.RenameTable(
name: "Control",
newName: "Controls");
migrationBuilder.RenameIndex(
name: "IX_ControlEvaluationControl_ControlId",
table: "ControlEvaluationControls",
newName: "IX_ControlEvaluationControls_ControlId");
migrationBuilder.RenameIndex(
name: "IX_ControlEvaluationControl_ControlEvaluationsId",
table: "ControlEvaluationControls",
newName: "IX_ControlEvaluationControls_ControlEvaluationsId");
migrationBuilder.AddColumn<int>(
name: "UserId",
table: "ControlEvaluations",
type: "int",
nullable: true);
migrationBuilder.AddPrimaryKey(
name: "PK_ControlEvaluationControls",
table: "ControlEvaluationControls",
column: "Id");
migrationBuilder.AddPrimaryKey(
name: "PK_ControlEvaluations",
table: "ControlEvaluations",
column: "Id");
migrationBuilder.AddPrimaryKey(
name: "PK_Controls",
table: "Controls",
column: "Id");
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
UserName = table.Column<string>(type: "nvarchar(max)", nullable: true),
UserRole = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_ControlEvaluations_UserId",
table: "ControlEvaluations",
column: "UserId");
migrationBuilder.AddForeignKey(
name: "FK_ControlEvaluationControls_ControlEvaluations_ControlEvaluationsId",
table: "ControlEvaluationControls",
column: "ControlEvaluationsId",
principalTable: "ControlEvaluations",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_ControlEvaluationControls_Controls_ControlId",
table: "ControlEvaluationControls",
column: "ControlId",
principalTable: "Controls",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_ControlEvaluations_Users_UserId",
table: "ControlEvaluations",
column: "UserId",
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_ControlEvaluationControls_ControlEvaluations_ControlEvaluationsId",
table: "ControlEvaluationControls");
migrationBuilder.DropForeignKey(
name: "FK_ControlEvaluationControls_Controls_ControlId",
table: "ControlEvaluationControls");
migrationBuilder.DropForeignKey(
name: "FK_ControlEvaluations_Users_UserId",
table: "ControlEvaluations");
migrationBuilder.DropTable(
name: "Users");
migrationBuilder.DropPrimaryKey(
name: "PK_Controls",
table: "Controls");
migrationBuilder.DropPrimaryKey(
name: "PK_ControlEvaluations",
table: "ControlEvaluations");
migrationBuilder.DropIndex(
name: "IX_ControlEvaluations_UserId",
table: "ControlEvaluations");
migrationBuilder.DropPrimaryKey(
name: "PK_ControlEvaluationControls",
table: "ControlEvaluationControls");
migrationBuilder.DropColumn(
name: "UserId",
table: "ControlEvaluations");
migrationBuilder.RenameTable(
name: "Controls",
newName: "Control");
migrationBuilder.RenameTable(
name: "ControlEvaluations",
newName: "ControlEvaluation");
migrationBuilder.RenameTable(
name: "ControlEvaluationControls",
newName: "ControlEvaluationControl");
migrationBuilder.RenameIndex(
name: "IX_ControlEvaluationControls_ControlId",
table: "ControlEvaluationControl",
newName: "IX_ControlEvaluationControl_ControlId");
migrationBuilder.RenameIndex(
name: "IX_ControlEvaluationControls_ControlEvaluationsId",
table: "ControlEvaluationControl",
newName: "IX_ControlEvaluationControl_ControlEvaluationsId");
migrationBuilder.AddPrimaryKey(
name: "PK_Control",
table: "Control",
column: "Id");
migrationBuilder.AddPrimaryKey(
name: "PK_ControlEvaluation",
table: "ControlEvaluation",
column: "Id");
migrationBuilder.AddPrimaryKey(
name: "PK_ControlEvaluationControl",
table: "ControlEvaluationControl",
column: "Id");
migrationBuilder.AddForeignKey(
name: "FK_ControlEvaluationControl_Control_ControlId",
table: "ControlEvaluationControl",
column: "ControlId",
principalTable: "Control",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_ControlEvaluationControl_ControlEvaluation_ControlEvaluationsId",
table: "ControlEvaluationControl",
column: "ControlEvaluationsId",
principalTable: "ControlEvaluation",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
}
<file_sep>namespace FinalYearProject.Enums
{
public enum EditProfileSelect
{
EditFirstName,
EditLastName,
EditRole,
EditEmailAddress
}
}<file_sep>using FinalYearProject.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace FinalYearProject
{
public class DatabaseContext : IdentityDbContext<User>
{
public DatabaseContext(DbContextOptions<DatabaseContext> Options)
: base(Options)
{ }
public DbSet<Control> Controls { get; set; }
public DbSet<ControlEvaluationControls> ControlEvaluationControls { get; set; }
public DbSet<ControlEvaluations> ControlEvaluations { get; set; }
}
}<file_sep>using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
namespace FinalYearProject.Services
{
public class EmailService
{
public EmailService(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public async Task SendEmailAsync(string Email, string Subject, string HtmlMessage)
{
var emailPassword = Configuration["EmailPassword"];
const string CompanyEmailAddress = "<EMAIL>";
var client = new SmtpClient("smtp.gmail.com", 587)
{
UseDefaultCredentials = false,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(CompanyEmailAddress, emailPassword),
EnableSsl = true
};
await client.SendMailAsync(CompanyEmailAddress, Email, Subject, HtmlMessage);
}
}
}<file_sep>using Microsoft.EntityFrameworkCore.Migrations;
namespace FinalYearProject.Migrations
{
public partial class AddedNewTables : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Controls");
migrationBuilder.CreateTable(
name: "Control",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ControlSummary = table.Column<string>(type: "nvarchar(max)", nullable: true),
ControlExpected = table.Column<string>(type: "nvarchar(max)", nullable: true),
ControlTest = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Control", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ControlEvaluation",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1")
},
constraints: table =>
{
table.PrimaryKey("PK_ControlEvaluation", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ControlEvaluationControl",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ControlId = table.Column<int>(type: "int", nullable: true),
ControlEvaluationsId = table.Column<int>(type: "int", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ControlEvaluationControl", x => x.Id);
table.ForeignKey(
name: "FK_ControlEvaluationControl_Control_ControlId",
column: x => x.ControlId,
principalTable: "Control",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_ControlEvaluationControl_ControlEvaluation_ControlEvaluationsId",
column: x => x.ControlEvaluationsId,
principalTable: "ControlEvaluation",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_ControlEvaluationControl_ControlEvaluationsId",
table: "ControlEvaluationControl",
column: "ControlEvaluationsId");
migrationBuilder.CreateIndex(
name: "IX_ControlEvaluationControl_ControlId",
table: "ControlEvaluationControl",
column: "ControlId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ControlEvaluationControl");
migrationBuilder.DropTable(
name: "Control");
migrationBuilder.DropTable(
name: "ControlEvaluation");
migrationBuilder.CreateTable(
name: "Controls",
columns: table => new
{
id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ControlExpectedValue = table.Column<string>(type: "nvarchar(max)", nullable: true),
ControlSummary = table.Column<string>(type: "nvarchar(max)", nullable: true),
ControlTestValue = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Controls", x => x.id);
});
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using FinalYearProject.Enums;
using FinalYearProject.Models;
using FinalYearProject.Models.Payloads;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.EntityFrameworkCore;
using MudBlazor;
using Flurl;
namespace FinalYearProject.Services
{
public class UserService
{
private readonly DatabaseContext _context;
private readonly UserManager<User> _userManager;
private readonly PasswordHasher<User> _passwordHasher;
private readonly SignInOutService _signInOutService;
private readonly ISnackbar _snackbar;
private readonly NavigationManager _navigationManager;
private readonly AuthenticationStateProvider _authenticationStateProvider;
private readonly EmailService _emailService;
private readonly ControlsService _controlsService;
public UserService(DatabaseContext Context, UserManager<User> UserManager, PasswordHasher<User> PasswordHasher, SignInOutService SignInOutService, ISnackbar Snackbar, NavigationManager NavigationManager, AuthenticationStateProvider AuthenticationStateProvider, EmailService EmailService, ControlsService ControlsService)
{
_context = Context;
_userManager = UserManager;
_passwordHasher = PasswordHasher;
_signInOutService = SignInOutService;
_snackbar = Snackbar;
_navigationManager = NavigationManager;
_authenticationStateProvider = AuthenticationStateProvider;
_emailService = EmailService;
_controlsService = ControlsService;
}
public async Task RegisterUser(RegisterPayload RegisterPayload)
{
var user = new User
{
UserName = RegisterPayload.EmailAddress,
Email = RegisterPayload.EmailAddress,
FirstName = RegisterPayload.FirstName,
LastName = RegisterPayload.LastName,
// #if DEBUG
// EmailConfirmed = true
// #endif
};
var result = await _userManager.CreateAsync(user, RegisterPayload.Password);
if (!result.Succeeded)
{
foreach (var error in result.Errors)
{
throw new Exception(error.Description);
}
}
await _userManager.AddToRoleAsync(user, Role.Auditor.ToString());
// #if RELEASE
await SendConfirmationEmail(user.Email);
// #endif
_snackbar.Add("Registeration Successful!", Severity.Success, config => { config.ShowCloseIcon = false; });
_navigationManager.NavigateTo("/", true);
}
public async Task Login(SignInPayload SignInPayload)
{
var user = await _context.Users.SingleOrDefaultAsync(x => x.Email == SignInPayload.EmailAddress);
if (user == null)
{
throw new Exception("Login was unsuccessful. Please try again.");
}
if (_passwordHasher.VerifyHashedPassword(user, user.PasswordHash, SignInPayload.Password) !=
PasswordVerificationResult.Success)
{
throw new Exception("Login was unsuccessful. Please try again.");
}
if (!user.EmailConfirmed)
{
throw new Exception("Account has not been confirmed.");
}
await _signInOutService.SignInAsync(user);
_snackbar.Add("Login Successful!", Severity.Success, config => { config.ShowCloseIcon = false; });
_navigationManager.NavigateTo("/", true);
}
public async Task Logout()
{
await _signInOutService.SignOutAsync();
_snackbar.Add("Logout successful!", Severity.Success, config => { config.ShowCloseIcon = false; });
_navigationManager.NavigateTo("/", true);
}
public async Task<User> FetchUserProfile(string Email)
{
if (Email == "admin")
{
Email = "admin@admin";
}
return await _context.Users.SingleOrDefaultAsync(x => x.NormalizedEmail == Email.ToUpper());
}
public async Task<User> FetchUserWithControlEval(string Email)
{
return await _context.Users.Include(x => x.ControlEvaluations).ThenInclude(x => x.ControlsList).SingleOrDefaultAsync(x => x.NormalizedEmail == Email.ToUpper());
}
public async Task<List<User>> FetchAllUsersWithControlEval()
{
return await _context.Users.Include(x => x.ControlEvaluations).ThenInclude(x => x.ControlsList)
.ToListAsync();
}
public async Task<List<ControlEvaluations>> FetchUserControlEvaluations(string Email)
{
return await _context.Users.Where(x => x.NormalizedEmail == Email.ToUpper())
.SelectMany(x => x.ControlEvaluations).Include(x => x.ControlsList).ToListAsync();
}
public async Task CreateUserControlEvaluation(string Email, ControlEvaluationPayload ControlEvaluationPayload)
{
var user = await FetchUserWithControlEval(Email);
ControlEvaluations controlEvaluation = new()
{
AuditName = ControlEvaluationPayload.AuditTitle,
DateCreated = DateTimeOffset.Now,
LeadAuditor = ControlEvaluationPayload.LeadAuditor,
ControlStage = ControlStage.InProgress
};
user.ControlEvaluations.Add(controlEvaluation);
await _context.SaveChangesAsync();
}
public async Task<List<User>> FetchAllUserProfiles()
{
return await _context.Users.ToListAsync();
}
public async Task EditUserSaveChanges(User User, string role)
{
await _userManager.UpdateAsync(User);
var roles = await _userManager.GetRolesAsync(User);
await _userManager.RemoveFromRolesAsync(User, roles);
await _userManager.AddToRoleAsync(User, role);
await _context.SaveChangesAsync();
}
public async Task<string> ExtractUserRole(User user)
{
var rolesAsync = await _userManager.GetRolesAsync(user);
return rolesAsync[0];
}
public async Task<User> GetCurrentUserAsync()
{
var authenticationState = await _authenticationStateProvider.GetAuthenticationStateAsync();
var authenticationStateUser = authenticationState.User;
return await _userManager.FindByNameAsync(authenticationStateUser.Identity.Name);
}
public async Task UpdatePasswordAsync(PasswordResetPayload ResetPayload)
{
var user = await GetCurrentUserAsync();
var changePasswordResult =
await _userManager.ChangePasswordAsync(user, ResetPayload.CurrentPassword, ResetPayload.NewPassword);
if (!changePasswordResult.Succeeded)
{
throw new Exception();
}
await _signInOutService.ResetUserLoginAsync(user);
}
public async Task UpdateEmailAddressAsync(string Email)
{
if (string.IsNullOrEmpty(Email))
{
throw new Exception();
}
var user = await GetCurrentUserAsync();
var currentEmail = await _userManager.GetEmailAsync(user);
if (currentEmail == "admin@admin")
{
throw new Exception("This is the admin account. You can only do this manually in the SQL server.");
}
var userId = await _userManager.GetUserIdAsync(user);
var resetCode = await _userManager.GenerateChangeEmailTokenAsync(user, Email);
resetCode = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(resetCode));
Email = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(Email));
userId = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(userId));
var confirmationUrl = _navigationManager.BaseUri.AppendPathSegments("ConfirmEmailChange", userId, Email, resetCode);
var emailMessage = $"Hi {user.FirstName} {user.LastName}, \n\n" +
"You have requested an email address change, to confirm this please follow the url. \n\n" +
$"{HtmlEncoder.Default.Encode(confirmationUrl)} /n/n" +
"If you did not request this change, please disregard this email. \n\n" +
"Thanks \n" +
"Audit Controls Gen";
await _emailService.SendEmailAsync(currentEmail, "Confirm your email address change", emailMessage);
}
public async Task SendConfirmationEmail(string Email)
{
var user = await _userManager.FindByEmailAsync(Email);
var userId = await _userManager.GetUserIdAsync(user);
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
userId = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(userId));
Url confirmationUrl = _navigationManager.BaseUri.AppendPathSegments("ConfirmAccount", userId, code);
var emailMessage = $"Hi {user.FirstName} {user.LastName}. \n\n" +
"You have created an account using our software, to confirm your account please follow the url. \n\n" +
$"{HtmlEncoder.Default.Encode(confirmationUrl)}\n\n" +
"Have a nice day.\n" +
"Audit Controls Gen";
await _emailService.SendEmailAsync(Email, "Confirm your account", emailMessage);
}
public async Task RemoveUser(User user)
{
// first remove from any roles
var rolesAsync = await _userManager.GetRolesAsync(user);
await _userManager.RemoveFromRolesAsync(user, rolesAsync);
// check if any ControlEvaluations exist.
if (user.ControlEvaluations != null)
{
// next remove any linking ControlEvaluations Controls
var controlsList = await _controlsService.FetchAllControls();
foreach (var controlEval in user.ControlEvaluations)
{
if (controlEval.ControlsList != null)
{
controlEval.ControlsList.RemoveRange(0, controlEval.ControlsList.Count);
}
}
// next remove any linking ControlEvaluations
user.ControlEvaluations.RemoveRange(0, user.ControlEvaluations.Count);
}
// lastly remove user
var result = await _userManager.DeleteAsync(user);
if (!result.Succeeded)
{
throw new Exception($"An unexpected error occurred whilst attempting to delete the user '{user.FirstName} {user.LastName}'.");
}
}
public async Task<User> FetchUserFromControlEval(ControlEvaluations controlEvaluations)
{
var user = await _context.Users.SingleOrDefaultAsync(x => x.ControlEvaluations.Contains(controlEvaluations));
return await FetchUserWithControlEval(user.Email);
}
}
}<file_sep>using System.ComponentModel.DataAnnotations;
using FinalYearProject.Enums;
namespace FinalYearProject.Models.Payloads
{
public class RegisterPayload
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string EmailAddress { get; set; }
[Required]
public string Password { get; set; }
[Required]
[Compare(nameof(Password))]
public string ConfirmPassword { get; set; }
public Role UserRole { get; set; }
}
}<file_sep>using System.ComponentModel.DataAnnotations;
namespace FinalYearProject.Models.Payloads
{
public class PasswordResetPayload
{
[Required]
public string CurrentPassword { get; set; }
[Required]
public string NewPassword { get; set; }
[Required]
public string NewPasswordConfirm { get; set; }
}
}<file_sep>using System;
using System.ComponentModel.DataAnnotations;
namespace FinalYearProject.Models.Payloads
{
public class ControlEvaluationPayload
{
[Required]
public string AuditTitle { get; set; }
[Required]
public string LeadAuditor { get; set; }
public DateTimeOffset DateCreated { get; set; }
}
}<file_sep>using System.Security.Claims;
using System.Threading.Tasks;
using FinalYearProject.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using Microsoft.JSInterop;
namespace FinalYearProject.Services
{
public class SignInOutService
{
private readonly CookieAuthenticationOptions _cookieAuthenticationOptions;
private readonly IHostEnvironmentAuthenticationStateProvider _hostAuthentication;
private readonly IJSRuntime _jsRuntime;
private readonly SignInManager<User> _signInManager;
public SignInOutService(IOptionsMonitor<CookieAuthenticationOptions> cookieAuthenticationOptionsMonitor,
IHostEnvironmentAuthenticationStateProvider hostAuthentication,
IJSRuntime jsRuntime,
SignInManager<User> signInManager)
{
_signInManager = signInManager;
_hostAuthentication = hostAuthentication;
_jsRuntime = jsRuntime;
_cookieAuthenticationOptions = cookieAuthenticationOptionsMonitor.Get("MyScheme");
}
public async Task SignInAsync(User user)
{
var principal = await _signInManager.CreateUserPrincipalAsync(user);
var identity = new ClaimsIdentity(
principal.Claims,
"MyScheme"
);
principal = new ClaimsPrincipal(identity);
_signInManager.Context.User = principal;
_hostAuthentication.SetAuthenticationState(Task.FromResult(new AuthenticationState(principal)));
// this is where we create a ticket, encrypt it, and invoke a JS method to save the cookie
var ticket = new AuthenticationTicket(principal, null, "MyScheme");
var value = _cookieAuthenticationOptions.TicketDataFormat.Protect(ticket);
await _jsRuntime.InvokeVoidAsync("blazorExtensions.WriteCookie", "AuditControlGenAuth", value, _cookieAuthenticationOptions.ExpireTimeSpan.TotalDays);
}
public async Task SignOutAsync()
{
var principal = _signInManager.Context.User = new ClaimsPrincipal(new ClaimsIdentity());
_hostAuthentication.SetAuthenticationState(Task.FromResult(new AuthenticationState(principal)));
await _jsRuntime.InvokeVoidAsync("blazorExtensions.DeleteCookie", "AuditControlGenAuth");
await Task.CompletedTask;
}
public async Task ResetUserLoginAsync(User user) // used in case of user changing details.
{
await SignOutAsync();
await SignInAsync(user);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using FinalYearProject.Enums;
namespace FinalYearProject.Models
{
public class ControlEvaluationsVault
{
public int Id { get; set; }
public string AuditName { get; set; }
public string LeadAuditor { get; set; }
public DateTimeOffset DateCreated { get; set; }
public string ReviewerEmail { get; set; }
public List<ControlEvaluationControls> ControlsList { get; set; }
}
}
|
d334b32195dc26088ffc39fecc0f34a39c53031f
|
[
"C#"
] | 21
|
C#
|
LeonWinstanley/Audit-Controls-Gen
|
e26677863b034a00176713f03c8face5a3d0aba9
|
38b488713f6e0f0f76cb205b8d04328f1009f99b
|
refs/heads/master
|
<repo_name>diemorales/copyloto<file_sep>/www/templates/infraccion.html
<ion-view view-title="Infracción">
<ion-content ng-controller="InfraDetCtrl">
<div class="card">
<div class="item item-divider item-text-wrap titulos">
{{nombre}}
</div>
<div class="item item-text-wrap desc">
<p class="subTitulo">Artículo nro: {{articulo}}, inciso {{inciso}}</p>
<hr>
<p>
{{descripcion}}
<br></p>
</div>
<div class="item item-text-wrap desc">
<p class="subTitulo">Autoridades Competentes</p>
<hr>
<p>
<strong>Patrulla Caminera:</strong> Rutas nacionales y departamentales, así como ramales y caminos vecinales que atraviesen los municipios.
<br><br>
<strong>Policía Municipal:</strong> Zona urbana de su respectiva jurisdicción .
</p>
</div>
<div class="item item-text-wrap desc">
<p class="subTitulo">Sanción</p>
<hr>
<p>
{{sancion_desc}}
<br>
<strong>Multa:</strong> {{sancion_mul}} Jornales Mínimos. <br>
<strong>Equivalencia:</strong> {{sancion_gs}} Gs.
<br><br>
</p>
</div>
</div>
</ion-content>
</ion-view><file_sep>/README.md
# Copyloto
Es una aplicación multiplataforma colaborativa, compañera y guía con la que accedes de forma práctica a herramientas e información sobre la ley de tránsito y seguridad vial.
**Copyloto** está desarrollado con [Ionic Framework](http://ionicframework.com/), Ionic está optimizado con [AngularJS](https://angularjs.org/) que a la vez está integrado con [cordova](https://cordova.apache.org/) para utilizar funciones nativas de hardware, con sus plugins.
**Atención**
Las versiones utilizadas para el desarrollo de esta versión, ya están desfasadas.
**Cordova** v5.1.1
**Ionic** v1.7.8
<file_sep>/www/js/controllers.js
angular.module('starter.controllers', [])
.controller('AppCtrl', function($scope, $ionicModal, $cordovaSocialSharing, $timeout) {
//recomendar
var URL_SHARE = "www.copyloto.com.py";
var TXT_SHARE = "COPYLOTO es tu amigo que te guía en el tránsito víal :) Descargalo ya!";
var IMG_SHARE = "www/img/logo-prueba.png";
$scope.shareAnywhere = function() {
$cordovaSocialSharing.share(TXT_SHARE, null, IMG_SHARE, URL_SHARE);
}
})
//HOME
.controller('HomeCtrl', function($scope) {
})
//INFRACIONES
.controller('InfraCtrl', function($scope, $cordovaSQLite, $rootScope) {
$scope.infracciones = [];
var query = "SELECT * FROM inf_detalles";
$rootScope.db.transaction(function(tx) {
tx.executeSql(query, [], function(tx, res) {
for(var i = 0; i < res.rows.length; i++){
$scope.infracciones.push({
nombre: res.rows.item(i).nombre,
id: res.rows.item(i).id,
inciso: res.rows.item(i).inciso,
articulo: res.rows.item(i).articulo
});
$scope.$apply();
}
});
}, function(error) {
// OK to close here:
console.log('transaction error: ' + error.message);
db.close();
}, function() {
// OK to close here:
console.log('transaction ok');
});
})
//INFRACIONES
.controller('InfraDetCtrl', function($scope, $stateParams, $cordovaSQLite, $rootScope) {
var parId = $stateParams.pInfraccion;
$scope.articulo='';
$scope.nombre='';
$scope.descripcion='';
$scope.inciso='';
$scope.sancion_desc='';
$scope.sancion_mul='';
$scope.sancion_gs='';
var query = "SELECT * FROM inf_detalles WHERE id = ?";
$rootScope.db.transaction(function(tx) {
tx.executeSql(query, [parId], function(tx, res) {
if(res.rows.length > 0) {
$scope.articulo=res.rows.item(0).articulo;
$scope.nombre=res.rows.item(0).nombre;
$scope.descripcion=res.rows.item(0).descripcion;
$scope.inciso=res.rows.item(0).inciso;
$scope.sancion_desc=res.rows.item(0).sancion_desc;
$scope.sancion_mul=res.rows.item(0).sancion_mul;
$scope.sancion_gs=res.rows.item(0).sancion_gs;
$scope.$apply();
} else {
//console.log("no hay resultados");
}
});
}, function(error) {
console.log('transaction error: ' + error.message);
db.close();
}, function() {
//console.log('transaction ok');
});
})
//TEMAS VIALES
.controller('TemViaCtrl', function($scope, $cordovaSQLite, $rootScope) {
$scope.items = [];
var query = "SELECT * FROM temas_viales";
$rootScope.db.transaction(function(tx) {
tx.executeSql(query, [], function(tx, res) {
for(var i = 0; i < res.rows.length; i++){
$scope.items.push({
title: res.rows.item(i).nombre,
id: res.rows.item(i).id
});
$scope.$apply();
}
});
}, function(error) {
// OK to close here:
console.log('transaction error: ' + error.message);
db.close();
}, function() {
//console.log('transaction ok');
});
})
//TEMAS VIALES
.controller('TVArtsCtrl', function($scope, $stateParams, $cordovaSQLite, $rootScope) {
var parId = $stateParams.pTemavial;
$scope.articulos = [];
var query = "SELECT * FROM tv_articulos WHERE tv_id = ?";
$rootScope.db.transaction(function(tx) {
tx.executeSql(query, [parId], function(tx, res) {
for(var i = 0; i < res.rows.length; i++){
$scope.articulos.push({
nombre: res.rows.item(i).nombre,
articulo: res.rows.item(i).articulo
});
$scope.$apply();
}
});
}, function(error) {
// OK to close here:
console.log('transaction error: ' + error.message);
db.close();
}, function() {
//console.log('transaction ok');
});
})
//TEMAS VIALES
.controller('TVArtCtrl', function($scope, $stateParams, $cordovaSQLite, $rootScope) {
var parArt = $stateParams.pArticulo;
$scope.articulo = '';
$scope.nombre = '';
$scope.descripcion = '';
var query = "SELECT * FROM tv_articulos WHERE articulo = ?";
$rootScope.db.transaction(function(tx) {
tx.executeSql(query, [parArt], function(tx, res) {
if(res.rows.length > 0) {
$scope.articulo=res.rows.item(0).articulo;
$scope.nombre=res.rows.item(0).nombre;
$scope.descripcion=res.rows.item(0).descripcion;
$scope.$apply();
} else {
//console.log("no hay resultados");
}
});
}, function(error) {
// OK to close here:
console.log('transaction error: ' + error.message);
db.close();
}, function() {
//console.log('transaction ok');
});
})
//REGLAMENTOS
.controller('ReglCtrl', function($scope, $window) {
$scope.OpenLink = function(link) {
window.open( link, '_system');
};
})
//TIPS
.controller('TipsCatCtrl', function($scope) {
})
//TIPS
.controller('TipsCtrl', function($scope, $stateParams) {
var par = $stateParams.pTipsId;
$scope.myActiveSlide = 0;
var automovil = [
{titulo:' Respete las normas de tránsito, mantenga distancia de seguridad y velocidad adecuada.', age:25, desc:''},
{titulo:' No transporte más pasajeros de la capacidad del vehículo.', desc:''},
{titulo:' Lleve encendida las luces bajas siempre.', desc:''},
{titulo:' Si ingirió alcohol no conduzca, por más mínima que haya sido la cantidad.', desc:''},
{titulo:' Todos los ocupantes del vehículo deben llevar puesto el cinturón de seguridad, los niños siempre viajan atrás. Recuerde que los niños menores a 5 años deben usar la silla especial.', desc:''},
{titulo:' Contar con la documentación obligatoria para desplazarse con su vehículo, licencia de conducir, cedula de identidad, cedula verde, seguro obligatorio contra accidentes de tránsito e inspección técnica vehicular aprobada, habilitación municipal.', desc:''},
{titulo:' Los automóviles deben contar con juego de balizas, extintor de incendio debidamente cargado, señaleros, luces trasera y luces de freno.', desc:''},
{titulo:' Para desplazarse el vehículo deben contar obligatoriamente con las chapas en ambos lados.', desc:''}
];
var peaton = [
{titulo:' Caminar por la vereda y no por la calle, además de jamás cruzar en el medio de una cuadra, sino hacerlo en las esquinas.', age:25, desc:''},
{titulo:' Recuerda que no debes caminar ni atravesar las autopistas.', desc:''},
{titulo:' Circular siempre por el lado izquierdo de la calzada de tal manera que al caminar siempre vea a los coches venir de frente.', desc:''},
{titulo:' Al llegar al paso de peatones nos detendremos en la vereda/acera, no en la calzada, mostraremos la intención de cruzar mirando a los coches y a sus conductores.', desc:''},
{titulo:' Evite el uso de elementos distractores como celulares, tabletas, periódicos y otros mientras se movilice por las calles con mucho tránsito.', desc:''}
];
var moto = [
{titulo:' No conduzca cuando las condiciones climáticas sean desfavorables, pues los riesgos de accidentes se verán aumentadas.', age:25, desc:''},
{titulo:' Evite ir muy detrás de un camión u otro vehículo.', desc:''},
{titulo:' No exceda los límites de velocidad.', desc:''},
{titulo:' El uso del casco y del chaleco reflectivo es obligatorio.', desc:''},
{titulo:' No circule por las aceras y paseos públicos destinados a los peatones.', desc:''},
{titulo:' No transporte en la motocicleta menores de 12 años.', desc:''}
];
var otros = [
{titulo:' En caso de accidente deberá de detenerse inmediatamente en el lugar del hecho, si existiesen víctimas, ejercer y buscar el inmediato socorro de las personas lesionadas, señalizar adecuadamente el lugar, para evitar riesgos a terceros. No retirar los rodados involucrados y suministrar a la otra parte y a la autoridad interviniente, sus datos personales y los del vehículo.', desc:''},
{titulo:' La patrulla caminera tienen autoridad de aplicación en rutas nacionales e internacionales y caminos vecinales, en cambio la jurisdicción de la policía caminera se limita sólo a la zona urbana del distrito en cuestión.', age:25, desc:''},
{titulo:' Los pagos de las multas deberán de realizarse dentro de los 5 días hábiles desde su imposición.', desc:''},
{titulo:' Las multas pueden ser abonadas al instante dependiendo de la clasificación de las infracciones si son leves o directamente dentro de los 5 días hábiles deberán acudir a las regionales o jefaturas de la patrulla caminera o municipalidades de acuerdo a las áreas de aplicación y competencias jurídicas.', desc:''},
{titulo:' En caso de accidente de tránsito deberá someterse a las pruebas expresamente autorizadas, para determinar su estado de intoxicación alcohólica o por sustancias estupefacientes o sicotrópicas en el momento del hecho.', desc:''}
];
switch (par) {
case 'automovil':
$scope.items=automovil;
break;
case 'peaton':
$scope.items=peaton;
break;
case 'moto':
$scope.items=moto;
break;
default:
$scope.items=otros;
}
})
//MAPA
.controller('MapCtrl', function($scope, $compile) {
var peajes = [
{titulo: '<NAME>, Asu-Chaco', direccion: 'Ruta Transchaco Ruta 9', lat: '-25.187437', lon: '-57.542611'},
{titulo: 'Ypacarai, Asu-CDE', direccion: 'Mcal. J. <NAME>ia', lat: '-25.393201', lon: '-57.2790994'},
{titulo: '<NAME>, Enc-Asu', direccion: 'Mcal. Francisco Solano Lopez, Ruta 1', lat: '-26.406032', lon: '-57.129585'},
{titulo: 'CERRITO, Chaco-Asu', direccion: 'Carlos Antonio Lopez Ruta 9', lat: '-24.944861', lon: '-57.553107'},
{titulo: 'EMBOSCADA, Lim-SanEst', direccion: 'General Aquino Ruta 3', lat: '-25.113749', lon: '-57.429791'},
{titulo: 'ACCESO SUR, Asu-Gua', direccion: 'Acceso Sur', lat: '-25.507309', lon: '-57.433358'},
{titulo: 'CNEL. OVIEDO, CDE-Asu', direccion: 'Mcal. Estigarribia Ruta 2', lat: '-25.474837', lon: '-56.535000'}
];
var destacamentos = [
{titulo: 'Jefatura Zona Central', direccion: 'Mcal. Estigarribia Ruta 2, San Lorenzo', lat: '-25.339638', lon: '-57.521067'},
{titulo: 'Destacamento Hernandarias', direccion: 'Supercarretera', lat: '-25.322805', lon: '-54.664540'},
{titulo: 'Jefatura Nº 8 Zona CDE', direccion: 'Av. Mcal. López c/ <NAME> de Francia', lat: '-25.507502 ', lon: '-54.638513'},
{titulo: 'Jefatura Nº 1 Zona Carapeguá', direccion: 'Mcal. López Ruta Nº 1 Km. 84', lat: '-25.767418 ', lon: '-57.238773'},
{titulo: 'Jefatura Nº 7 Zona Cnel. Oviedo', direccion: 'Dr. <NAME>', lat: '-25.466452 ', lon: '-56.448022'}
];
var tacpy = [
{titulo: 'Casa Central', direccion: '25 de Mayo c/ Brasil, Asunción', lat: '-25.288585', lon: '-57.624762'},
{titulo: 'Sucursal Villa Aurelia', direccion: 'Nicolás Bliloff 7070 c/ Victoriano Bueno', lat: '-25.30556', lon: '-57.560303'},
{titulo: 'Base Villa Florida', direccion: 'Ruta 1 Mcal. López Km. 156, Parador Tebicuary', lat: '-26.405449', lon: '-57.129277'},
{titulo: 'Delegación Cnel. Oviedo', direccion: 'Ruta 2 Mcal. Estigarribia c/ Itapúa', lat: '-25.466156', lon: '-56.449547'},
{titulo: 'Delegación CDE', direccion: 'Avda. San Blás Km. 1,5', lat: '-25.509553 ', lon: '-54.618596'},
{titulo: 'Delegación Encarnación', direccion: 'Gral. Artigas c/ Villarrica', lat: '-27.329847', lon: '-55.869825'},
{titulo: 'Delegación San Estanislao (Santaní)', direccion: 'Avda. Rosita Melo c/ <NAME>', lat: '-24.671184', lon: '-56.445786'},
{titulo: 'Delegación Pozo Colorado', direccion: 'Ruta Transchaco Km. 270', lat: '-23.493959', lon: '-58.793669'},
{titulo: '<NAME>', direccion: 'Avda. San Blás Km. 1,5', lat: '-22.964', lon: '-56.541208'},
{titulo: '<NAME>', direccion: 'Ruta 7 Km. 248', lat: '-25.422395', lon: '-55.377544'}
];
$scope.initialize = function() {
//console.log('init map');
var myLatlng = new google.maps.LatLng(-25.3421689,-57.5046647);
var mapOptions = {
center: myLatlng,
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
$scope.map = map;
$scope.markers = [];
};
//marker adicionales peajes
$scope.fPeajes = function () {
deleteAllMarkers();
$scope.markers = [];
var infoWindow = new google.maps.InfoWindow();
//Add markers
var createMarker = function (info){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(info.lat, info.lon),
map: $scope.map,
animation: google.maps.Animation.DROP,
title: info.titulo
});
marker.content = '<div class="infoWindowContent">' + info.direccion + '</div>';
google.maps.event.addListener(marker, 'click', function(){
infoWindow.setContent('<h3>' + marker.title + '</h3>' + marker.content);
infoWindow.open($scope.map, marker);
});
$scope.markers.push(marker);
};
for (i = 0; i < peajes.length; i++){
createMarker(peajes[i]);
}
};
//marker adicionales destacamentos
$scope.fDestacamentos = function () {
deleteAllMarkers();
//console.log('markers borrados');
$scope.markers = [];
var infoWindow = new google.maps.InfoWindow();
//Add markers
var createMarker = function (info){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(info.lat, info.lon),
map: $scope.map,
animation: google.maps.Animation.DROP,
title: info.titulo
});
marker.content = '<div class="infoWindowContent">' + info.direccion + '</div>';
google.maps.event.addListener(marker, 'click', function(){
infoWindow.setContent('<h3>' + marker.title + '</h3>' + marker.content);
infoWindow.open($scope.map, marker);
});
$scope.markers.push(marker);
};
for (i = 0; i < destacamentos.length; i++){
createMarker(destacamentos[i]);
}
};
//marker adicionales destacamentos
$scope.fTacpy = function () {
deleteAllMarkers();
//console.log('markers borrados');
$scope.markers = [];
var infoWindow = new google.maps.InfoWindow();
//Add markers
var createMarker = function (info){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(info.lat, info.lon),
map: $scope.map,
animation: google.maps.Animation.DROP,
title: info.titulo
});
marker.content = '<div class="infoWindowContent">' + info.direccion + '</div>';
google.maps.event.addListener(marker, 'click', function(){
infoWindow.setContent('<h3>' + marker.title + '</h3>' + marker.content);
infoWindow.open($scope.map, marker);
});
$scope.markers.push(marker);
};
for (i = 0; i < tacpy.length; i++){
createMarker(tacpy[i]);
}
};
//Delete all Markers
var deleteAllMarkers = function(){
if($scope.markers.length == 0){
//console.log('no ha markers')
return;
}
for (var i = 0; i < $scope.markers.length; i++) {
//Remove the marker from Map
$scope.markers[i].setMap(null);
}
//Remove the marker from array.
$scope.markers.length = 0;
$scope.markerId = 0;
};
})
//DENUNCIAS
.controller('DenCtrl', function($scope) {
})
//NOSOTROS
.controller('NosCtrl', function($scope) {
})
//INFORMACIONES UTILES
.controller('InfoCtrl', function($scope) {
$scope.llamar = function (ptel) {
window.location.href = 'tel:'+ ptel;
}
$scope.utiles = [
{nombre: "<NAME>", telefono: "+59521582689", direccion: "Ruta No. 2 Mcal. Estigarribia c/ San José, km. 14", ciudad:"San Lorenzo"},
{nombre: "MOPC", telefono: "+595214149000", direccion: "Oliva y Alberdi Nº 411, C.P. Nº 1221", ciudad:"Asunción"},
{nombre: "Emergencia Policial", telefono: "+59521911", direccion: "--", ciudad: "--"},
{nombre: "Emergencia Médicas", telefono: "+59521204800", direccion: "Avenida Gral. M. Santos", ciudad: "Asunción"},
{nombre: "S.O.S. Person<NAME>", telefono: "+59521440997", direccion: "--", ciudad:"--"},
{nombre: "S.O.S. Niños & Mujer", telefono: "+59521140", direccion: "--", ciudad:"--"},
{nombre: "Touring y Automovil Club", telefono: "+59521233160", direccion: "25 de Mayo 1086 Esq. Brasil", ciudad: "Asunción"},
{nombre: "Escuela de Conducción TACPY", telefono: "+59521210550", direccion: "Choferes del Chaco", ciudad: "Asunción"},
{nombre: "<NAME>", telefono: "*822", direccion: "--", ciudad: "Paraguay"},
{nombre: "<NAME>", telefono: "*823", direccion: "--", ciudad: "Paraguay"},
{nombre: "<NAME>", telefono: "+59521211387", direccion: "Brasil 216 c/ <NAME>", ciudad: "Asunción"},
{nombre: "<NAME>", telefono: "+59521645600", direccion: "Aviadores del Chaco", ciudad: "Luque"},
{nombre: "Fiscalía", telefono: "+595214155000", direccion: "--", ciudad: "--"},
{nombre: "<NAME>", telefono: "+59521551740", direccion: "Rca. Argentina esq. Fdo. de la Mora", ciudad: "Asunción"},
];
})
// fin
;
|
82d9bbd3651f7d5208e6dfb62861c2e0831f56e2
|
[
"Markdown",
"JavaScript",
"HTML"
] | 3
|
HTML
|
diemorales/copyloto
|
4a8bd23c809c7139a359d49f0a52ce72a1409817
|
91e03086bf8073cb254306834acd17585d791ed2
|
refs/heads/master
|
<file_sep>// JavaScript Document
$(document).ready(function(){
$('#demo1').flexImages({rowHeight: 140});
//logoimg定位
/*$(window).scroll(function(){
var scrollTop = $(this).scrollTop();
if(scrollTop>366){
$(".logoimg").css({"position":"fixed","top":"0","z-index":"1000","height":"68px"});
}
else{
$(".logoimg").css("cssText","top:366 !important");
}
});*/
// 基于准备好的dom,初始化echarts图表
var myChart = echarts.init(document.getElementById('map'));
option = {
title : {
text: '那些年留下的足迹',
subtext: '行者智也',
textStyle:{
fontSize: 30,
fontWeight: 'bolder',
color: '#333'
},
sublink: '',
x:'center'
},
tooltip : {
trigger: 'item'
},
/*legend: {
orient: 'vertical',
x:'left',
y: 'top',
data:[{name:"生活过的城市",textStyle : {color:"auto"}},{name:"走过的城市",textStyle : {color:"auto"}},{name:"计划中的城市",textStyle : {color:"auto"}}]
},*/
series : [
{
name: '生活过的城市',
type: 'map',
mapType: 'china',
hoverable: false,
roam:false,
data : [],
markPoint : {
symbolSize: 8, // 标注大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
itemStyle: {
normal: {
/*color: '#00AB4F',
borderColor: '#87cefa',
borderWidth: 1, */ // 标注边线线宽,单位px,默认为1
label: {
show: false
}
},
emphasis: {
/* borderColor: '#1e90ff',*/
borderWidth: 5,
label: {
show: false
}
}
},
data : [
{name: "无锡",value: ""},
{name: "江阴", value: ""},
{name: "上海", value: ""},
{name: "东台", value: ""}
]
},
geoCoord: {
"北京":[116.3,39.9],
"东台":[120.23,32.45],
"徐州":[117.11,34.15],
"舟山":[122.207216,29.985295],
"盐城":[120.13,33.38],
"青岛":[120.33,36.07],
"南通":[121.05,32.08],
"拉萨":[91.11,29.97],
"上海":[121.48,31.22],
"厦门":[118.1,24.46],
"湖州":[120.1,30.86],
"连云港":[119.16,34.59],
"泰州":[119.9,32.49],
"江阴":[120.26,31.91],
"深圳":[114.07,22.62],
"苏州":[120.62,31.32],
"张家港":[120.555821,31.875428],
"桂林":[110.28,25.29],
"扬州":[119.42,32.39],
"常州":[119.95,31.79],
"南京":[118.78,32.04],
"无锡":[120.29,31.59],
"秦皇岛":[119.57,39.95],
"张家港":[120.32,31.52],
"昆山":[120.58,31.24 ],
"稻城":[100.3,29.03],
"拉萨":[91.15,29.30],
"张家界":[110.27,29.20]
}
},
{
name: '走过的城市',
type: 'map',
mapType: 'china',
hoverable: false,
roam:false,
data : [ ],
markPoint : {
symbolSize: 8, // 标注大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
itemStyle: {
normal: {
/* borderColor: '#87cefa',
color: '#F44336', */
borderWidth: 1, // 标注边线线宽,单位px,默认为1
label: {
show: false
}
},
emphasis: {
/* borderColor: '#1e90ff',*/
borderWidth: 5,
label: {
show: false
}
}
},
data : [
{name: "北京", value:"" },
{name: "湖州", value: ""},
{name: "徐州", value: ""},
{name: "南京", value:""},
{name: "苏州", value:""},
{name: "常州", value:""},
{name: "昆山", value:""},
{name: "张家港", value:""},
]
}
},
{
name: '计划中的城市',
type: 'map',
mapType: 'china',
data:[],
markPoint : {
symbol:'emptyCircle',
symbolSize : function (v){
return 10 + v/100
},
effect : {
show: true,
shadowBlur : 0
},
itemStyle:{
normal:{
label:{show:false}
}
},
data : [
{name: "稻城", value:""},
{name: "拉萨", value: ""},
{name: "张家界", value:"" },
]
}
}
]
};
// 为echarts对象加载数据
myChart.setOption(option);
})
|
3369c84acd8fb7f59ac636ad87079381079b3b95
|
[
"JavaScript"
] | 1
|
JavaScript
|
TaoyuProxy/Taobs-site
|
98639990f98a595bb10cee03b6095f06808db137
|
cf6351ce27a47fb28bf9f05290cabc26ed9ca2ec
|
refs/heads/master
|
<file_sep># Endomondo-Analyzer
A project developed in Python to analyse trainigs on endomondo.com and compare them to each other
## How to use it
Either download the python file and config file to run it in Python. (You need to enter your credentials into the config file). Or download the folder containing the exe file to run it on a windows machine with no running Python install.
<file_sep>import tkinter
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
import requests
from scipy.signal import medfilt
from copy import deepcopy
from json import loads
import numpy as np
with open('endomondo.config', 'r') as conf:
username = conf.readline()[:-1]
password = conf.readline()
class Requester:
def __init__(self, email, password):
self.email = email
self.password = <PASSWORD>
self.session = requests.session()
self.cookies = {}
self.headers = {
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0',
'Accept': 'application/json, text/plain, */*',
'Accept-Language': 'en-US,en;q=0.5',
'Referer': 'https://www.endomondo.com/home',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'Cache-Control': 'max-age=0',
'TE': 'Trailers',
}
self.data = '{"email":"' + self.email + '","password":"' + self.password + '","remember":true}'
def login(self):
# getting csrf token, jsessionid and awselb
response = self.session.get('https://www.endomondo.com/', headers=self.headers, cookies=self.cookies)
self.headers["X-CSRF-TOKEN"] = response.cookies["CSRF_TOKEN"]
self.headers["Referer"] = "https://www.endomondo.com/login"
self.headers["Origin"] = "https://www.endomondo.com"
self.headers["Content-Type"] = "application/json;charset=utf-8"
response2 = self.session.post('https://www.endomondo.com/rest/session', headers=self.headers,
cookies=self.cookies, data=self.data)
def get_workout(self, url):
self.headers["Referer"] = url
response = self.session.get("https://www.endomondo.com/rest/v1/" + url[26:], headers=self.headers,
cookies=self.cookies)
return response.content.decode('utf-8')
class Training:
class Plot:
def __init__(self, data, y_label, line_color):
self.raw_data = data
self.data = data
self.y_label = y_label
self.line_color = line_color
self.visible = True
self.inherited = None
def set_visible(self, boolean):
self.visible = boolean
def average(self, _i):
self.data = medfilt(self.raw_data, _i)
def __init__(self, json, line_type):
self.decoded = loads(json)
self.line_type = line_type
self.name = self.decoded['id']
# creating all plots
heart_rate = []
for i in range(len(self.decoded['points']['points'])):
if "heart_rate" in self.decoded['points']['points'][i]['sensor_data']:
heart_rate.append(self.decoded['points']['points'][i]['sensor_data']['heart_rate'])
else:
if heart_rate:
heart_rate.append(heart_rate[-1])
else:
heart_rate.append(0)
self.plot_heart_rate = self.Plot(heart_rate, "[heart rate] = bpm", 'tab:red')
self.distance = [self.decoded["points"]["points"][i]["distance"]
for i in range(len(self. decoded['points']['points']))]
speed = []
for i in range(len(self.decoded['points']['points'])):
if "speed" in self.decoded['points']['points'][i]['sensor_data']:
speed.append(self.decoded['points']['points'][i]['sensor_data']['speed'])
else:
if speed:
speed.append(speed[-1])
else:
speed.append(0)
avg = np.average(speed)
for j, i in enumerate(speed):
try:
speed[j] = 60 / i
except ZeroDivisionError:
speed[j] = 60 / avg
self.plot_speed = self.Plot(speed, "[speed] = minpkm", 'tab:blue')
alt = []
for i in range(len(self.decoded['points']['points'])):
if "altitude" in self.decoded['points']['points'][i]:
alt.append(self.decoded['points']['points'][i]['altitude'])
else:
if alt:
alt.append(alt[-1])
else:
alt.append(None)
for j, i in enumerate(alt):
if i is None:
for el in alt[j:]:
if el:
alt[j] = el
self.plot_altitude = self.Plot(alt, "[altitude] = m", 'tab:green')
self.plot_speed.inherited = [self.distance, self.line_type, self.name]
self.plot_altitude.inherited = [self.distance, self.line_type, self.name]
self.plot_heart_rate.inherited = [self.distance, self.line_type, self.name]
self.date = self.decoded["local_start_time"]
self.empty_plot = self.Plot([0 for _ in range(len(self.decoded['points']['points']))], "", "tab:blue")
self.empty_plot.set_visible(False)
self.empty_plot.inherited = [self.distance, self.line_type, self.name]
def txt_changed_0(txt):
if len(txt) >= 50:
Trainings[0] = Training(user.get_workout(txt), '-')
plot(states)
def txt_changed_1(txt):
if not txt:
Trainings.pop(1)
if len(txt) >= 50:
if len(Trainings) >= 2:
Trainings[1] = Training(user.get_workout(txt), '--')
else:
Trainings.append(Training(user.get_workout(txt), '--'))
plot(states)
def txt_changed_2(txt):
if not txt:
Trainings.pop(2)
if len(txt) >= 50:
if len(Trainings) >= 3:
Trainings[2] = Training(user.get_workout(txt), ':')
else:
Trainings.append(Training(user.get_workout(txt), ':'))
plot(states)
def txt_changed_3(txt):
if not txt:
Trainings.pop(3)
if len(txt) >= 50:
if len(Trainings) >= 4:
Trainings[3] = Training(user.get_workout(txt), '-.')
else:
Trainings.append(Training(user.get_workout(txt), '-.'))
plot(states)
def slide(numb):
numb = int(numb)
for training in Trainings:
training.plot_speed.average(numb)
training.plot_heart_rate.average(numb)
plot(states)
def slide_change(n):
n = int(n)
if not n % 2:
slider.set(n + 1)
def btn_slide():
slide(int(slider.get()))
def check_box():
global states
states['plot_speed'] = varSpeed.get()
states['plot_altitude'] = varAltitude.get()
states['plot_heart_rate'] = varHeart.get()
plot(states)
def submit():
global txtBoxes
temp = [txtBox0.get(), txtBox1.get(), txtBox2.get(), txtBox3.get()]
for i, element in enumerate(temp):
if not element == txtBoxes[i]:
if i == 0:
txt_changed_0(element)
if i == 1:
txt_changed_1(element)
if i == 2:
txt_changed_2(element)
if i == 3:
txt_changed_3(element)
txtBoxes[i] = element
user = Requester(username, password)
user.login()
Trainings = [Training(user.get_workout("https://www.endomondo.com/users/19154541/workouts/1458780940"), '-')]
states = {'plot_speed': True, 'plot_altitude': True, 'plot_heart_rate': False}
txtBoxes = ['', '', '', '']
root = tkinter.Tk()
root.wm_title("Endomondo Analyzer")
fig = Figure(figsize=(5, 4), dpi=100)
fig.add_subplot(111)
ax1 = fig.subplots()
ax2 = ax1.twinx()
canvas = FigureCanvasTkAgg(fig, master=root) # A tk.DrawingArea.
canvas.draw()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
toolbar = NavigationToolbar2Tk(canvas, root)
toolbar.update()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
txtBox0 = tkinter.Entry(root)
txtBox0.place(x=20, y=40)
lbl0 = tkinter.Label(root, text="durchgezogen")
lbl0.place(x=150, y=40)
lbl1 = tkinter.Label(root, text="gestrichelt")
lbl1.place(x=150, y=80)
lbl0 = tkinter.Label(root, text="gepunktet")
lbl0.place(x=150, y=120)
lbl1 = tkinter.Label(root, text="gestrichpunktet")
lbl1.place(x=150, y=160)
txtBox1 = tkinter.Entry(root)
txtBox1.place(x=20, y=80)
txtBox2 = tkinter.Entry(root)
txtBox2.place(x=20, y=120)
txtBox3 = tkinter.Entry(root)
txtBox3.place(x=20, y=160)
slider = tkinter.Scale(root, from_=1, to=35, orient=tkinter.HORIZONTAL, length=300, command=slide_change)
slider.place(x=20, y=580)
varSpeed = tkinter.BooleanVar()
chckSpeed = tkinter.Checkbutton(root, text="Speed", command=check_box, variable=varSpeed)
chckSpeed.place(x=20, y=410)
chckSpeed.select()
varAltitude = tkinter.BooleanVar()
chckAltitude = tkinter.Checkbutton(root, text="Altitude", command=check_box, variable=varAltitude)
chckAltitude.place(x=20, y=450)
chckAltitude.select()
varHeart = tkinter.BooleanVar()
chckHeart = tkinter.Checkbutton(root, text="Heart Rate", command=check_box, variable=varHeart)
chckHeart.place(x=20, y=490)
btnSubmit = tkinter.Button(root, command=submit, text="Submit")
btnSubmit.place(x=20, y=200)
btnChangeScale = tkinter.Button(root, command=btn_slide, text="Change Average")
btnChangeScale.place(x=20, y=540)
Dates = tkinter.StringVar(root)
lblDates = tkinter.Label(root, textvariable=Dates)
lblDates.place(x=20, y=250)
def _quit():
root.quit() # stops mainloop
root.destroy() # this is necessary on Windows to prevent
# Fatal Python Error: PyEval_RestoreThread: NULL tstate
def plot(_dict):
# choosing which plots to show on which axis
plot1 = None
plot2 = None
dictionary = deepcopy(_dict)
for element in dictionary:
if dictionary[element]:
plot1 = element
dictionary[element] = 0
break
for element in dictionary:
if dictionary[element]:
plot2 = element
dictionary[element] = 0
break
global ax1
global ax2
color = ""
ax1.clear()
ax2.clear()
# defining lists of plots
if plot1 == "plot_speed":
plots1 = [i.plot_speed for i in Trainings]
elif plot1 == "plot_altitude":
plots1 = [i.plot_altitude for i in Trainings]
elif plot1 == "plot_heart_rate":
plots1 = [i.plot_heart_rate for i in Trainings]
if plot2 == "plot_altitude":
plots2 = [i.plot_altitude for i in Trainings]
elif plot2 == "plot_heart_rate":
plots2 = [i.plot_heart_rate for i in Trainings]
if plot1 is None:
plots1 = [Trainings[0].empty_plot]
if plot2 is None:
plots2 = [Trainings[0].empty_plot]
color = plots1[0].line_color
ax1.set_xlabel('[distance] = km')
ax1.set_ylabel(plots1[0].y_label, color=color)
dates = "Dates:\n"
for training in Trainings:
dates = dates + training.date[:10] + "\n"
Dates.set(dates)
for pl in plots1:
ax1.plot(pl.inherited[0], pl.data, color=color, visible=pl.visible, linestyle=pl.inherited[1])
ax1.tick_params(axis='y', labelcolor=color)
color = plots2[0].line_color
ax2.set_xlabel('[distance] = km')
ax2.set_ylabel(plots2[0].y_label, color=color)
for pl in plots2:
ax2.plot(pl.inherited[0], pl.data, color=color, visible=pl.visible, linestyle=pl.inherited[1])
ax2.tick_params(axis='y', labelcolor=color)
fig.subplots_adjust(left=0.2)
fig.canvas.draw_idle()
plot(states)
fig.canvas.draw_idle()
button = tkinter.Button(master=root, text="Quit", command=_quit)
button.pack(side=tkinter.BOTTOM)
tkinter.mainloop()
|
c30a47060a7cfeafefbece265ec999ed60de85d8
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
lade043/Endomondo-Analyzer
|
ce91770f4f712d18917507d80dde1e75134aca37
|
8cd0b8de8cd3e0793531921bb8196928c00bb83d
|
refs/heads/main
|
<file_sep>#include <stdio.h>
int main() {
int test;
scanf("%d", &test);
while (test--) {
int n, m, sum = 0, count, k;
scanf("%d", &n); // n은 가로, 세로길이다.
if (n % 2 == 0) { // m은 출력하는 최고 숫자
m = n / 2;
}
else {
m = n / 2 + 1;
}
if (n == 1) {
printf("1\n");
}
else {
for (int i = 1; i <= m; i++) { // i = 행
count = 0;
k = 1;
for (;;) { // k = 반복
printf("%d", k);
if (k < i) {
k++;
}
count++;
if (count == m) {
break;
}
}
if (n % 2 == 1) {
count++;
}
for (;;) {
if (k == m) {
if (n % 2 == 1) {
k--;
}
}
printf("%d", k);
if (2 * m - count == k) {
k--;
}
count++;
if (count >= 2 * m) {
break;
}
}
printf("\n");
}
int su;
if (n % 2 == 0) {
su = m;
}
else {
su = m - 1;
}
for (int i = su; i >= 1; i--) { // i = 행
count = 0;
k = 1;
for (;;) { // k = 반복
printf("%d", k);
if (k < i) {
k++;
}
count++;
if (count == m) {
break;
}
}
if (n % 2 == 1) {
count++;
}
for (;;) {
if (k == m) {
if (n % 2 == 1) {
k--;
}
}
printf("%d", k);
if (2 * m - count == k) {
k--;
}
count++;
if (count >= 2 * m) {
break;
}
}
printf("\n");
}
}
printf("\n");
}
return 0;
}
<file_sep>#include <stdio.h>
int main() {
int test;
scanf("%d", &test);
while (test--) {
int nn, ban, ban1, result;
scanf("%d", &nn);
ban = nn / 2;
ban1 = ban;
if (nn % 2 == 1) {
ban++;
}
for (int i = 0; i < ban; i++) {
for (int j = 0; j < ban; j++) {
if (i >= j) {
result = j + 65;
if (result == 68)
result = 71;
else if (result == 69)
result = 74;
else if (result == 70)
result = 76;
else if (result == 71)
result = 77;
else if (result == 72)
result = 80;
else if (result == 73)
result = 84;
printf("%c", result);
}
else {
result = i + 65;
if (result == 68)
result = 71;
else if (result == 69)
result = 74;
else if (result == 70)
result = 76;
else if (result == 71)
result = 77;
else if (result == 72)
result = 80;
else if (result == 73)
result = 84;
printf("%c", result);
}
}
for (int j = ban1; j > 0; j--) {
if (i < j) {
result = i + 65;
if (result == 68)
result = 71;
else if (result == 69)
result = 74;
else if (result == 70)
result = 76;
else if (result == 71)
result = 77;
else if (result == 72)
result = 80;
else if (result == 73)
result = 84;
printf("%c", result);
}
else {
result = j + 64;
if (result == 68)
result = 71;
else if (result == 69)
result = 74;
else if (result == 70)
result = 76;
else if (result == 71)
result = 77;
else if (result == 72)
result = 80;
else if (result == 73)
result = 84;
printf("%c", result);
}
}
printf("\n");
}
for (int i = ban1; i > 0; i--) {
for (int j = 0; j < ban; j++) {
if (i <= j) {
result = i + 64;
if (result == 68)
result = 71;
else if (result == 69)
result = 74;
else if (result == 70)
result = 76;
else if (result == 71)
result = 77;
else if (result == 72)
result = 80;
else if (result == 73)
result = 84;
printf("%c", result);
}
else {
result = j + 65;
if (result == 68)
result = 71;
else if (result == 69)
result = 74;
else if (result == 70)
result = 76;
else if (result == 71)
result = 77;
else if (result == 72)
result = 80;
else if (result == 73)
result = 84;
printf("%c", result);
}
}
for (int j = ban1; j > 0; j--) {
if (i >= j) {
result = j + 64;
if (result == 68)
result = 71;
else if (result == 69)
result = 74;
else if (result == 70)
result = 76;
else if (result == 71)
result = 77;
else if (result == 72)
result = 80;
else if (result == 73)
result = 84;
printf("%c", result);
}
else {
result = i + 64;
if (result == 68)
result = 71;
else if (result == 69)
result = 74;
else if (result == 70)
result = 76;
else if (result == 71)
result = 77;
else if (result == 72)
result = 80;
else if (result == 73)
result = 84;
printf("%c", result);
}
}
printf("\n");
}
printf("\n");
}
return 0;
}<file_sep>#include <stdio.h>
int main(void){
int test, a, b, c, d;
scanf("%d", &test);
while (test--){
scanf("%d %d %d %d", &a, &b, &c, &d);
if ( a==b && c==d){
if (a < c)
printf("Kim DS wins\n");
else if (c < a)
printf("Yoo HJ wins\n");
else if ( a == c)
printf("Draw\n");}
else if ( a==b && c != d)
printf("Kim DS wins\n");
else if ( a!=b && c == d)
printf("Yoo HJ wins\n");
else if (a != b && c != d){
if(a>=b && c>=d){
if ((a-b)>(c-d))
printf("Yoo HJ wins\n");
else if ((a-b)<(c-d))
printf("Kim DS wins\n");
else if ((a-b)==(c-d))
printf("Draw\n");}
else if (a<b && c>=d){
if ((b-a)>(c-d))
printf("Yoo HJ wins\n");
else if ((b-a)<(c-d))
printf("Kim DS wins\n");
else if ((b-a)==(c-d))
printf("Draw\n");}
else if (a>=b && c<d){
if ((a-b)>(d-c))
printf("Yoo HJ wins\n");
else if ((a-b)<(d-c))
printf("Kim DS wins\n");
else if ((a-b)==(d-c))
printf("Draw\n");}
else if (a<b && c<d){
if ((b-a)>(d-c))
printf("Yoo HJ wins\n");
else if ((b-a)<(d-c))
printf("Kim DS wins\n");
else if ((b-a)==(d-c))
printf("Draw\n");}
}
}
return 0;
}<file_sep>#include <stdio.h>
int main(void)
{
int a, b, c, x, y, z, sum1, sum2, sum3, total, test;
scanf("%d", &test);
while (test--) {
scanf("%d %d %d", &a, &b, &c);
scanf("%d %d %d", &x, &y, &z);
if (x - a <= 5 && x - a >= -5) {
if (x >= a)
sum1 = x - a;
else
sum1 = a - x;
}
else {
if (x >= a)
sum1 = 10 - (x - a);
else
sum1 = 10 - (a - x);
}
if (y - b <= 5 && y - b >= -5) {
if (y >= b)
sum2 = y - b;
else
sum2 = b - y;
}
else {
if (y >= b)
sum2 = 10 - y + b;
else
sum2 = 10 - b + y;
}
if (z - c <= 5 && z - c >= -5) {
if (z >= c)
sum3 = z - c;
else
sum3 = c - z;
}
else {
if (z >= c)
sum3 = 10 - z + c;
else
sum3 = 10 - c + z;
}
total = sum1 + sum2 + sum3;
printf("%d\n", total);
}
return 0;
}<file_sep>#include<stdio.h>
int main() {
int i, sum, test;
scanf("%d", &test);
while (test--) {
scanf("%d", &i);
sum = i % 10 * 1000 + (i % 100 - i % 10) * 10 + (i % 1000 - i % 100) / 10 + i / 1000;
if (sum >= i) {
printf("%d\n", sum);
}
else {
printf("%d\n", i);
}
}
return 0;
}<file_sep># Solving lavida.us
laved.us solved in 2018, freshman.
If you want to download all of your lavida.us code, please download all_of_codes_in_lavida_down.py.
Edit variable, my_id and my_password.
115 solve
- 1000 A+B
- 1002 URI decoding
- 1005 존 류의 금고
- 1006 이놈의 시간표
- 1007 납세의 의무
- 1008 문자열 암호화
- 1009 복소수의 곱셈
- 1020 화이트 데이
- 1022 돈 심은데 돈난다.
- 1024 추(追)우(牛)
- 1027 1부터 N까지의 합 구하기 1
- 1037 용돈 기입장
- 1038 자물쇠 열기
- 1039 존 류의 관찰일기Ⅰ
- 1040 류주의 매점투어Ⅰ
- 1041 Kimgori's Factorial
- 1042 Ryuju의 식사 모임
- 1043 Sum of Sum
- 1044 소수 구하기 I
- 1045 소수 구하기 II
- 1046 숫자 야구 게임
- 1048 평범한 놈 찾기
- 1060 Ryuju는 영어를 싫어해
- 1062 소수 구하기 III
- 1068 Matrix의 합
- 1080 Transposing A Matrix
- 1082 숫자의 합 구하기 1
- 1086 최대공약수 구하기 1
- 1087 최대 공약수 구하기 2
- 1091 이차 방정식의 해
- 1092 직각삼각형의 넓이 구하기
- 1117 Subsequence
- 1127 계산기 만들기
- 1138 원수관계
- 1162 점수 집계
- 1169 검증수
- 1170 주사위 게임
- 1301 Hay Points
- 1329 Mispelling4
- 1704 류주와 20
- 1705 콩라의 계산기
- 1708 4개의 주사위
- 1709 등차수열
- 1710 콩의 돌 쌓기
- 1711 털 은행의 이자율은 800%까지
- 1712 피타고라스의 삼각형
- 1713 미래의 국흘사원 KTY
- 1714 별이 다섯개!
- 1715 여니의 아메바실험
- 1718 KTY의 학점
- 1719 자판기
- 1725 도와줘요 턱털
- 1726 이상한 계산기
- 1729 수 뒤집기
- 1736 진보된 자판기
- 1738 스마트폰 구매 대작전 #1
- 1743 부처님 오신날 탑 그리기
- 1744 평균 관객수 구하기 1745 배수인가?
- 1770 시간 공간 그리고 우주
- 1801 달팽이 1908 아스가르드의 전사들
- 1927 Repeating Characters
- 1977 IP Address #2
- 1994 몇 명이 관람한 것일까?
- 1995 신비의 탑 그리기
- 1996 스마트폰 구매 대작전 #1-B
- 1997 자판기의 거스름돈은 얼마인가?
- 2054 아스가르드의 전사들 #2
- 2055 준플레이오프
- 2083 돈이 열리는 나무
- 2086 근의 판별
- 2087 가위바위보 게임
- 2088 구간합이 배수인가?
- 2089 공약수인가?
- 2090 한 자리 소수
- 2091 홀수합이 배수인가
- 2092 탑 그리기 #2
- 2093 2의 n승 구하기
- 2095 탑 그리기
- 2096 최대, 최소의 차이는 5의 배수?
- 2126 아스가르드의 전사들 #3
- 2127 산학협력관 자판기
- 2128 주사위게임
- 2131 호날두의 영문 채점
- 2133 Transposing A Matrix
- 2136 주사위 게임
- 2138 태블릿PC 구매 대작전
- 2141 태블릿PC 구매하기
- 2144 수소(emirp)
- 2145 벼 심기
- 2146 바이러스 확인하기
- 2150 어디로 갔을까?
- 2162 복권 긁기
- 2368 Matrix의 차
- 2370 평범하거나 그렇지 않은 후배 찾기
- 2402 몇 대가 지나간 것일까?
- 2403 공배수인가?
- 2404 구구단 출력
- 2406 재미있는 주사위 게임
- 2420 자판기 거스름돈
- 2766 별 찍기 - 마름모
- 2783 통과 차량은 몇 대인가?
- 2784 평균 관객수 및 수입 구하기
- 2785 간단한 주사위 게임
- 2786 복잡한 주사위 게임
- 2787 둘 다 공배수인가?
- 2788 투명 다이아몬드 #2
- 2789 스마트폰 구매 대작전 #3
- 2790 최대, 최소의 차이는 짝수?
- 2791 쌍둥이 소수(twin prime)
- 2792 홀수만 내림차순으로 출력하기
- 2793 같은 정수 세기
- 2802 특정 문자열 확인하기
- 2803 커피나무 심기
<file_sep>#include <stdio.h>
int main()
{
int n, sum;
scanf("%d", &n);
sum = 3 * n - 9;
printf("%d", sum);
}<file_sep>#include <stdio.h>
int main(){
int test, a, b, c, d;
scanf("%d", &test);
while (test--){
scanf("%d %d %d %d", &a, &b, &c, &d);
if ( a==b && c != d)
printf("Park wins\n");
else if ( a!=b && c == d)
printf("Shin wins\n");
else if ( a==b&&c==d){
if (a>c)
printf("Park wins\n");
else if (c>a)
printf("Shin wins\n");
else if ( a=c)
printf("draw\n");}
else if (a != b && c !=d){
if ((a+b)>(c+d))
printf("Park wins\n");
else if ((a+b)<(c+d))
printf("Shin wins\n");
else
printf("draw\n");}
}
}<file_sep>#include<stdio.h>
int main(){
int a, sum, test, t, i;
scanf("%d", &test);
while(test--){
scanf("%d", &a);
t=0;
for(i=1; i<=a; i++){
sum = i*(i+1)/2;
t = t+sum;
}
printf("%d\n", t);
}
return 0;
}<file_sep>#include <stdio.h>
int main()
{
int a, b, c, d, sum1, sum2, test;
scanf("%d", &test);
while(test--){
scanf("%d %d %d %d", &a, &b, &c, &d);
sum1 = a*c-b*d;
sum2 = a*d+b*c;
printf("%d %d\n", sum1, sum2);
}
return 0;
}<file_sep>#include <stdio.h>
int main()
{
int m, n, i, t, sum;
while (1) {
i = 1;
scanf("%d %d", &m, &n);
if (m == 0 && n == 0) {
break;
}
t = m;
while (t >= i) {
m = m + i;
i = i + 2;
}
sum = m % n;
if (sum == 0) {
printf("YES\n");
}
else {
printf("NO\n");
}
}
return 0;
}<file_sep>#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<time.h>
int IsPrime(int n) {
int i, limit;
if (n <= 1) return 0;
if (n == 2) return 1;
if (n % 2 == 0) return 0;
limit = (int)sqrt((double)n);
for (i = 3; i <= limit; i = i + 2) {
if (n%i == 0) {
return 0;
}
}
return 1;
}
int main(void) {
int test;
scanf("%d", &test);
while (test--) {
int min,max,i, a, b, prime, sum, q;
min = 1000001;
max = 0;
sum = 0;
scanf("%d %d", &a, &b);
if (a > b) {
int tmp = a;
a = b;
b = tmp;
}
for (i = a; i <= b;i++) {
if (IsPrime(i) == 1 && i>9) {
int result = 0;
if (i == 100000) {
result = 1;
}
else if (i >= 10000) {
result += i / 10000 + i % 10000 / 1000 * 10;
result += i % 1000 / 100 * 100 + i % 100 / 10 * 1000;
result += i % 10 * 10000;
}
else if (i >=1000&&i<10000) {
result += i / 1000 + i % 1000 / 100 * 10;
result += i % 100 / 10 * 100;
result += i % 10 * 1000;
}
else if (i >=100&& i<1000) {
result = i / 100 + i % 100/10 * 10 + i % 10 * 100;
}
else if (i >=10&& i<100) {
result = i / 10 + i % 10 * 10;
}
if (IsPrime(result) == 1 && i != result) {
sum++;
if (max <= i) {
max = i;
}
if (min >= i) {
min = i;
}
}
}
}
if (sum == 0) {
printf("0 0 0\n");
}
else {
printf("%d %d %d\n", max, min, sum);
}
}
return 0;
}
<file_sep>#include <stdio.h>
int main(void) {
int a, b, c, d, e;
while (1) {
scanf("%d", &a);
if (a == 0) {
break;
}
if (a % 2 == 0) {
b = a / 2;
}
else {
b = a;
}
if (b % 3 == 0) {
c = b / 3;
}
else {
c = b;
}
if (c % 5 == 0) {
d = c / 5;
}
else {
d = c;
}
if (d % 7 == 0) {
e = d / 7;
}
else {
e = d;
}
printf("%d\n", e);
}
}<file_sep>#include <stdio.h>
#include <string.h>
int main() {
int test;
scanf("%d", &test);
while (test--) {
int x1, y1;
char go[80];
scanf("%d %d", &x1, &y1);
scanf("%s", &go);
int len = strlen(go);
for (int i = 0; i < len; i++) {
if (go[i] == '1')
y1++;
else if (go[i] == '2') {
y1++;
x1++;
}
else if (go[i] == '3')
x1++;
else if (go[i] == '4') {
x1++;
y1--;
}
else if (go[i] == '5') {
y1--;
}
else if (go[i] == '6') {
x1--;
y1--;
}
else if (go[i] == '7')
x1--;
else if (go[i] == '8') {
x1--;
y1++;
}
}
printf("%d %d\n", x1, y1);
}
return 0;
}<file_sep>#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int pass[4];
int i = 0;
scanf("%s", str);
for (int i = 0; i < 4; i++) {
scanf("%d", &pass[i]);
}
for (int i = 0; i < 4; i++) {
int j = pass[i];
printf("%c", str[j]);
}
printf("\n");
return 0;
}
<file_sep>#include <stdio.h>
int main()
{
int time;
int sum;
scanf("%d", &time);
sum = 8 + time;
printf("%d:00", sum);
return 0;
}<file_sep>#include <stdio.h>
int main(void) {
int a, i, b, c, d, e, f;
scanf("%d", &a);
for (c = 1; c <= a; c++) {
for (d = 1; d < c; d++) {
printf(" ");
}
for (e = a; e >= c; e--) {
printf("@");
}
for (f = a; f > c; f--) {
printf("@");
}
printf("\n");
}
for (i = 1; i <= 2*a-1; i++) {
for (b = 1; b <= 2*a-1; b++) {
printf("@");
}
printf("\n");
}
return 0;
}<file_sep>#include <stdio.h>
int main(void){
int a, b, q, i, t;
scanf("%d", &a);
for(i=1; i<=a; i++){
for(b=a; b>i;b--){
printf(" ");
}
for(t=1; t<i*2+1; t=t+2){
if(t==1){
printf("&");
}
else{
printf("&&");}
}
printf("\n");
}
return 0;
}<file_sep>#include <stdio.h>
int main()
{
int a;
int b;
int c;
int sum;
scanf("%d %d %d", &a, &b, &c);
sum = 20 - (a + b + c);
printf("%d", sum);
return 0;
}<file_sep>#include<stdio.h>
int main() {
int test, price, sum, sum1;
scanf("%d", &test);
while (test--) {
scanf("%d", &price);
sum = price / 30000;
if (price > 50 * 30000) {
printf("No\n");
}
else {
if (price % 30000 == 0) {
printf("%d\n", sum);
}
else if (price % 30000 != 0) {
printf("%d\n", sum + 1);
}
}
}
return 0;
}<file_sep>#include <stdio.h>
int main() {
int price, day, haru, test;
scanf("%d", &test);
while (test--) {
scanf("%d", &price);
haru = 2950;
day = 0;
while (1) {
if (price > 0) {
haru = haru + 50;
price = price - haru;
}
else {
break;
}
day++;
}
if (day > 100) {
printf("NO\n");
}
else {
printf("%d\n", day);
}
}
return 0;
}<file_sep>#include <stdio.h>
#define MAX 10
int main() {
int i, j, a, b, test;
int x, y;
int n[MAX][MAX], m[MAX][MAX];
scanf("%d", &test);
while (test--) {
scanf("%d %d", &i, &j);
for (a = 0; a < i; a++) {
for (b = 0; b < j; b++) {
scanf("%d", &n[b][a]);
}
}
scanf("%d %d", &x, &y);
for (a = 0; a < x; a++) {
for (b = 0; b < y; b++) {
scanf("%d", &m[b][a]);
}
}
if (x == i&&y == j) {
for (a = 0; a < i; a++) {
for (b = 0; b < j; b++) {
m[b][a] += n[b][a];
printf("%d", m[b][a]);
if (b<j-1){
printf(" ");
}
}
printf("\n");
}
}
else {
printf("Impossible\n");
}
}
return 0;
}<file_sep>#include <stdio.h>
int main() {
long long t;
scanf("%lld", &t);
printf("%lld", t * 4);
return 0;
}<file_sep>#include <stdio.h>
#include <math.h>
#include <string.h>
int main() {
while (1) {
char input[129];
int virus[16][8], result[16] = { 0, };
char qu[6];
scanf("%s %s", qu, input);
if (strcmp(qu, "NULL") == 0 && strcmp(input, "NULL") == 0) {
break;
}
int k = 0;
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 8; j++) {
virus[i][j] = input[k++] - 48;
}
}
char save[16];
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 8; j++) {
result[i] += pow(2, 7 - j) * virus[i][j];
}
save[i] = result[i];
}
char *a = NULL;
a = strstr(save, qu);
if (a != 0) {
printf("Found!\n");
}
else {
printf("Not found!\n");
}
}
}<file_sep>#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<time.h>
int IsPrime(int n){
int i, limit;
if(n<=1) return 0;
if(n==2) return 1;
if(n%2==0) return 0;
limit=(int)sqrt((double)n);
for(i=3; i<=limit; i=i+2){
if(n%i==0){
return 0;
}
}
return 1;
}
int main(void){
int test, a, prime;
scanf("%d", &test);
while(test--){
scanf("%d", &a);
if(IsPrime(a)==0){
printf("Not Prime\n");
}
else if(IsPrime(a)==1){
printf("Prime\n");
}
}
return 0;
}<file_sep>#include <stdio.h>
int main(void){
int x,y, test, n;
scanf("%d", &test);
while(test--){
scanf("%d %d", &x, &y);
while(y!=0){
n=x%y;
x = y;
y = n;
}
printf("%d\n", x);
}
return 0;
}<file_sep>#include <stdio.h>
#include <string.h>
int main() {
int test;
scanf("%d", &test);
while (test--) {
char n1[100], n2[100];
scanf("%s %s", n1, n2);
int len1 = strlen(n1);
int len2 = strlen(n2);
int len;
if (len1 >= len2) {
for (int i = len2; i < len1; i++) {
n2[i] = '@';
}
len = len1;
}
else {
for (int i = len1; i < len2; i++) {
n1[i] = '@';
}
len = len2;
}
int sum = 0;
for (int i = 0; i < len; i++) {
sum += (n1[i] - n2[i])*(n1[i] - n2[i]);
}
sum = sum / len;
printf("%d\n", sum);
}
return 0;
}<file_sep>#include <stdio.h>
int main(void){
int test, t, in, max, min, sum;
scanf("%d", &test);
while(test--){
max = -1001;
min = 1001;
scanf("%d", &t);
while(t--){
scanf("%d", &in);
if(in>max){
max = in;
}
if(in<min){
min = in;
}
}
sum = max - min;
if (sum % 5 == 0){
printf("YES\n");
}
else{
printf("NO\n");
}
}
return 0;
}
<file_sep>#include <stdio.h>
#include <string.h>
typedef struct chaar {
int num;
int re;
char cc[21];
}CH;
int main() {
int test;
CH co[1000];
scanf("%d", &test);
for (int i = 0; i < test; i++) {
scanf("%d %d %s", &co[i].num, &co[i].re, co[i].cc);
}
for (int i = 0; i < test; i++) {
printf("%d ", co[i].num);
int len = strlen(co[i].cc);
for (int j = 0; j < len; j++) {
for (int k = 0; k < co[i].re; k++) {
printf("%c", co[i].cc[j]);
}
}
printf("\n");
}
return 0;
}<file_sep>#include <stdio.h>
int main() {
int test;
scanf("%d", &test);
while (test--) {
int deon, jeon;
scanf("%d %d", &deon, &jeon);
int level[10][10], twice[20];
for (int i = 0; i < deon; i++) {
for (int j = 0; j < jeon; j++) {
scanf("%d", &level[i][j]);
}
}
for (int i = 0; i < deon; i++) {
int max = 0;
int min = 501;
for (int j = 0; j < jeon; j++) {
if (level[i][j] > max) {
max = level[i][j];
}
if (level[i][j] < min) {
min = level[i][j];
}
}
twice[i] = max;
twice[i + deon] = min;
}
for (int i = 0; i < 2*deon - 1; i++) {
for (int j = i + 1; j < 2*deon; j++) {
if (twice[i] < twice[j]) {
int tmp = twice[i];
twice[i] = twice[j];
twice[j] = tmp;
}
}
}
for (int i = 0; i < 2*deon; i++) {
printf("%d", twice[i]);
if (i != 2*deon - 1) {
printf(" ");
}
}
printf("\n");
}
}<file_sep>#include <stdio.h>
int main() {
int test;
scanf("%d", &test);
while (test--) {
char a[4] = { 0, }, b[4] = { 0. };
int ball = 0, strike = 0;
scanf("%s %s", a, b);
for (int i = 0; i < 3; i++) {
if (a[i] == b[i]) {
strike++;
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (a[i] == b[j]) {
ball++;
}
}
}
ball = ball - strike;
printf("%dS %dB\n", strike, ball);
}
return 0;
}<file_sep>#include<stdio.h>
int main(void) {
int i, a, b, c, e;
int test;
scanf("%d", &test);
while (test--) {
scanf("%d", &i);
if (i % 2 == 0) {
i = i + 1;
i = (i + 1) / 2;
}
else {
i = i;
i = (i + 1) / 2;
}
for (a = 1; a <= i; a++) {
for (b = i; b > a; b--) {
printf(" ");
}
printf("$");
if (a > 1) {
for (c = 1; c <= 2 * a - 3; c++) {
printf(" ");
}
printf("$");
}
printf("\n");
}
for (a = 2; a <= i; a++) {
for (b = 1; b < a; b++) {
printf(" ");
}
printf("$");
for (c = i; c > a; c--) {
printf(" ");
}
for (e = i - 1; e > a; e--) {
printf(" ");
}
if (a < i) {
printf("$");
}
printf("\n");
}
}
return 0;
}<file_sep>#include <stdio.h>
#include <math.h>
#include <string.h>
int main() {
int test;
scanf("%d", &test);
while (test--) {
char input[129];
int virus[16][8], result[16] = { 0, };
scanf("%s", input);
int k = 0;
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 8; j++) {
virus[i][j] = input[k++] - 48;
}
}
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 8; j++) {
result[i] += pow(2, 7 - j) * virus[i][j];
(char)result[i];
}
}
char compare[7] = "SHBaek";
char com[7];
int t = 1;
for (int i = 0; i < 16; i++) {
if (result[i] == 'S') {
if (i + 5 < 16) {
com[6] = NULL;
for (int j = 0; j < 6; j++) {
com[j] = result[i++];
}
t = strcmp(com, compare);
}
}
}
if (t == 0) {
printf("VIRUS_ALERT!\n");
}
else {
printf("NORMAL\n");
}
}
return 0;
}<file_sep>#include<stdio.h>
int main() {
int a, b, c, d, e, f;
scanf("%d", &a);
for (c = 1; c <= a; c++) {
for (b = a - c; b > 0; b--) {
printf(" ");
}
for (d = 1; d <= c * 2 - 1; d++) {
printf("*");
}
printf("\n");
}
for (e = 1; e < a; e++) {
for (b = 1; b <= e; b++) {
printf(" ");
}
for (d = e; d < a; d++) {
printf("*");
}
for (f = a-1; f > e; f--) {
printf("*");
}
printf("\n");
}
return 0;
}<file_sep>#include <stdio.h>
int main(void)
{
int a, b;
float c;
scanf("%d", &b);
scanf("%d", &a);
c = a / (1 + 0.01 * b);
printf("%.2f\n", c);
return 0;
}<file_sep>#include <stdio.h>
int main(void) {
int a, b, c, max, sum, test;
float mm;
scanf("%d", &test);
while (test--) {
scanf("%d %d %d", &a, &b, &c);
if (b*b - 4 * a*c >0) {
printf("This Equation has two answers\n");
}
else if (b*b - 4 * a*c == 0) {
printf("This Equation has only one answer\n");
}
else {
printf("This Equation has no answer\n");
}
}
return 0;
}<file_sep>#include <stdio.h>
int main() {
int test;
scanf("%d", &test);
while (test--) {
int num[7] = { 0, };
int myNum[6] = { 0, };
int sum = 0;
for (int i = 0;i < 7;i++) {
scanf("%d", &num[i]);
}
for (int i = 0;i < 6;i++) {
scanf("%d", &myNum[i]);
}
for (int i = 0;i < 6;i++) {
for (int j = 0;j < 6;j++) {
if (num[i] == myNum[j]) {
sum++;
}
}
}
if (sum == 6) {
printf("1\n");
}
else if (sum == 5) {
for (int j = 0;j < 6;j++) {
if (num[6] == myNum[j]) {
sum++;
}
}
if (sum == 6) {
printf("2\n");
}
else {
printf("3\n");
}
}
else if (sum == 4) {
printf("4\n");
}
else if (sum == 3) {
printf("5\n");
}
else {
printf("Fail\n");
}
}
return 0;
}<file_sep>#include <stdio.h>
#include <string.h>
int main() {
int test;
scanf("%d", &test);
while (test--) {
char str[100];
scanf("%s", &str);
int len = strlen(str);
for (int i = 0; i < len; i = i + 2) {
printf("%c", str[i]);
}
for (int i = 1; i < len; i = i + 2) {
printf("%c", str[i]);
}
printf("\n");
}
return 0;
}
<file_sep>#include <stdio.h>
#include <string.h>
int main() {
char yeol[80] = {0,};
scanf("%s", &yeol);
int len = strlen(yeol);
for (int i = 0; i < len; i++) {
if (yeol[i] == '%') {
if (i + 1 >= len) {
printf("%%");
}
else if (yeol[i + 1] == '2') {
if (i + 2 >= len) {
printf("%2");
}
else if (yeol[i + 2] == '0') {
printf(" ");
}
else if (yeol[i + 2] == '1') {
printf("!");
}
else if (yeol[i + 2] == '4') {
printf("$");
}
else if (yeol[i + 2] == '5') {
printf("%%");
}
else if (yeol[i + 2] == '8') {
printf("(");
}
else if (yeol[i + 2] == '9') {
printf(")");
}
else if (yeol[i + 2] == 'a') {
printf("*");
}
else {
printf("%%2%c", yeol[i + 2]);
}
i = i + 2;
}
else {
printf("%c", yeol[i + 1]);
}
}
else {
printf("%c", yeol[i]);
}
}
printf("\n");
return 0;
}
<file_sep>#include <stdio.h>
int main(void) {
int a, b, c, d, e;
int test;
scanf("%d", &test);
while (test--) {
scanf("%d %d %d %d", &a, &b, &c, &d);
if (b*b == a * c) {
e = (b / a)*d;
}
else {
e = (b - a) + d;
}
printf("%d\n", e);
}
return 0;
}<file_sep>#include <stdio.h>
int main(void) {
int a, b, c, k, max, min, test;
min = 0;
scanf("%d", &test);
while (test--) {
scanf("%d %d %d", &a, &b, &c);
if (a == b && a == c && b == c) {
k = 10000 + a * 1000;
}
else if (a != b && b != c && a != c) {
max = 0;
if (a >= max) {
max = a;
}
if (b >= max) {
max = b;
}
if (c >= max) {
max = c;
}
k = max * 100;
}
else {
if (a == b && a != c && b != c) {
k = 1000 + a * 100;
}
else if (b == c && c != a) {
k = 1000 + b * 100;
}
else {
k = 1000 + a * 100;
}
}
if (min <= k) {
min = k;
}
}
printf("%d\n", min);
return 0;
}<file_sep>#include<stdio.h>
int main(void) {
int test, price, day, money;
scanf("%d", &test);
while (test--) {
scanf("%d", &price);
day = 0;
money = 0;
while (1) {
day++;
if (day % 7 == 1 || day % 7 == 2|| day % 7 == 3|| day % 7 == 4|| day % 7 == 5) {
money = money + 27000;
}
else if (day % 7 == 6) {
money = money + 54000;
}
else if(day%7==0){
money = money + 72000;
}
if (money >= price) {
break;
}
}
printf("%d\n", day);
}
return 0;
}<file_sep>#include <stdio.h>
int main(void) {
int test, t, sum;
scanf("%d", &test);
while (test--) {
scanf("%d", &t);
sum = 1;
if (t < 0) {
printf("Impossible\n");
}
else if(t>30) {
printf("Impossible\n");
}
else if (t == 0) {
printf("1\n");
}
else {
while (t--) {
sum = sum * 2;
}
printf("%d\n", sum);
}
}
}<file_sep>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from bs4 import BeautifulSoup
import pyperclip
chrome_path = "chromedriver"
url_login = "https://lavida.us/index.php"
url_submit = "https://lavida.us/status.php?&user_id=20183172&jresult=4"
driver = webdriver.Chrome(chrome_path)
driver.get(url_login)
time.sleep(1)
# id, pw 입력할 곳을 찾기
tag_id = driver.find_element_by_name('user_id')
tag_pw = driver.find_element_by_name('password')
tag_id.clear()
tag_pw.clear()
time.sleep(1)
# id 입력
tag_id.click()
pyperclip.copy('20183172')
tag_id.send_keys(Keys.COMMAND, 'v')
time.sleep(1)
# pw 입력
tag_pw.click()
pyperclip.copy('2127732')
tag_pw.send_keys(Keys.COMMAND, 'v')
time.sleep(1)
# # 로그인
tag_pw.send_keys(Keys.ENTER)
#바로 하면 페이지 이동이 안될 수 있다.
time.sleep(3)
# submit page data 가져오기
driver.get(url_submit)
while True:
driver.get(driver.current_url)
links = driver.find_elements_by_link_text("C++11")
links += driver.find_elements_by_link_text("C")
if len(links) == 0:
break
for link in links:
link.click()
# 새페이지로 switch
driver.switch_to.window(driver.window_handles[-1])
driver.get(driver.current_url)
# 페이지 소스 가져오기
html = driver.page_source
# soup에 넣어주기
soup = BeautifulSoup(html, 'html.parser')
code = soup.textarea.text
file_name = soup.find_all('td')[1].text + '.c'
file = open('lavida.us/' + file_name, 'w')
for line in code:
file.write(line)
file.close()
driver.close()
driver.switch_to.window(driver.window_handles[0])
time.sleep(3)
driver.find_element_by_class_name("btn.btn-info").click()
driver.quit()<file_sep>#include <stdio.h>
int main() {
int test;
scanf("%d", &test);
while (test--) {
int p, people[20] = { 0, };
scanf("%d", &p);
for (int i = 0; i < p; i++) {
scanf("%d", &people[i]);
}
int min;
double sum = 0.0;
for (int i = 0; i < p; i++) {
sum += people[i];
}
sum = sum / p;
min = people[0];
for (int i = 1; i < p; i++) {
/*
평균값이 people[i]보다 큰 경우 / 작은 경우
min의 값이 sum값 보다 큰 경우/ 작은 경우
*/
if (sum >= people[i]) {
if (min >= sum) {
if (sum - people[i] <= min - sum) {
min = people[i];
}
}
else {
if (sum - people[i] <= sum - min) {
min = people[i];
}
}
}
else {
if (min >= sum) {
if (people[i] - sum <= min - sum) {
min = people[i];
}
}
else {
if (people[i] - sum <= sum - min) {
min = people[i];
}
}
}
}
printf("%d\n", min);
}
return 0;
}<file_sep>#include <stdio.h>
#include <string.h>
int main() {
int test;
scanf("%d", &test);
while (test--) {
char ryu[30];
scanf("%s", &ryu);
int len = strlen(ryu);
int sum = 0;
for (int i = 0; i < len; i++) {
sum += (ryu[i] - 96);
}
printf("%d\n", sum);
}
}
<file_sep>#include <stdio.h>
int main()
{
int k, sum;
scanf("%d", &k);
sum = (1 + k) * k / 2;
printf("%d", sum);
}<file_sep>#include <stdio.h>
int main() {
int arr[5];
int len = sizeof(arr) / sizeof(int);
int i,sum;
int test;
scanf("%d", &test);
while (test--) {
sum = 0;
for (i = 0; i < len; i++) {
scanf("%d", &arr[i]);
}
for (i = 0; i < len - 1; i++) {
for (int j = i + 1; j < len; j++) {
if (arr[i] > arr[j]) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
for (i = 1; i < len - 1; i++) {
sum += arr[i];
}
if (arr[3] - arr[1] >= 4) {
printf("KIN\n");
}
else {
printf("%d\n", sum);
}
}
return 0;
}<file_sep>#include <stdio.h>
int main(void) {
int test, a, b, sum1, sum2;
scanf("%d", &test);
while (test--) {
scanf("%d %d", &a, &b);
if (a > b) {
sum1 = (a - b) /25000;
sum2 = (a-b) % 25000;
if (sum2 != 0)
printf("%d\n", sum1 + 1);
else
printf("%d\n", sum1);
}
else if (a <= b)
printf("0\n");
}
return 0;
}<file_sep>#include <stdio.h>
#include <string.h>
typedef struct JA {
char menuName[21];
int money;
}JA;
int main(void) {
int test;
scanf("%d", &test);
while (test--) {
int price, menu, sum = 0,num;
JA sa[30];
char buy[21];
scanf("%d", &menu);
for (int i = 0; i < menu; i++) {
scanf("%s %d", sa[i].menuName, &sa[i].money);
}
scanf("%d", &price);
for (int i = 0; i < price; i++) {
scanf("%s %d", buy,&num);
for (int j = 0; j < menu; j++) {
int o = strcmp(buy, sa[j].menuName);
if (o == 0) {
sum += sa[j].money*num;
}
}
}
printf("%d\n", sum);
}
return 0;
}<file_sep>#include <stdio.h>
int main() {
int test;
scanf("%d", &test);
while (test--) {
int arr[100] = { 0, }, arr2[100] = { 0, };
int num, result = 0, len;
scanf("%d", &num);
for (int i = 0; i < num; i++) {
scanf("%d", &arr[i]);
}
for (int i = 0; i < num - 1; i++) {
for (int j = i + 1; j < num; j++) {
if (arr[i] <= arr[j]) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
int a = 0;
for (int i = 0; i < num; i++) {
if (arr[i] % 2 == 1) {
printf("%d ", arr[i]);
a++;
}
}
if (a == 0) {
printf("None");
}
printf("\n");
}
return 0;
}<file_sep>#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<time.h>
int IsPrime(int n) {
int i, limit;
if (n <= 1) return 0;
if (n == 2) return 1;
if (n % 2 == 0) return 0;
limit = (int)sqrt((double)n);
for (i = 3; i <= limit; i = i + 2) {
if (n%i == 0) {
return 0;
}
}
return 1;
}
int main(void) {
int a, b, x, q, r;
while (1) {
scanf("%d %d", &a, &b);
if (a == 0 && b == 0) {
break;
}
x = 1;
q = r = 0;
if(b>=a){
for (a = a; a + 2 <= b; a++) {
if (IsPrime(a) == 1 && IsPrime(a + 2) == 1) {
printf("%d:(%d,%d)\n", x, a, a + 2);
x++;
}
else {
q++;
}
r++;
}
if (q == r) {
printf("No Twin Primes!\n");
}
}
else{
for (b = b; b + 2 <= a; b++) {
if (IsPrime(b) == 1 && IsPrime(b + 2) == 1) {
printf("%d:(%d,%d)\n", x, b, b + 2);
x++;
}
else {
q++;
}
r++;
}
if (q == r) {
printf("No Twin Primes!\n");
}
}
}
return 0;
}<file_sep>#include <stdio.h>
int main() {
int a, b, test, sum;
scanf("%d", &test);
while (test--) {
scanf("%d %d", &a, &b);
sum = a / 100 + (a / 10 - a / 100 * 10) + a - a / 10 * 10+ b / 100 + (b / 10 - b / 100 * 10) + b - b / 10 * 10;
sum = sum / 10 + sum % 10;
printf("%d\n", sum);
}
return 0;
}<file_sep>#include <stdio.h>
int main(void){
int test, a, b, c, d;
scanf("%d", &test);
while(test--){
scanf("%d %d %d %d",&a, &b, &c, &d);
if (a+b>c+d)
printf("Kim DS wins\n");
else if (a+b<c+d)
printf("Yoo HJ wins\n");
else if (a+b==c+d)
printf("Draw\n");
}
return 0;
}<file_sep>#include <stdio.h>
#include <string.h>
int main() {
int test;
scanf("%d", &test);
while (test--) {
char subs[101], seq[101];
scanf("%s %s", seq, subs);
int len1 = strlen(seq);
int len2 = strlen(subs);
int check = 0;
int count = 0;
for (int i = 0; i < len2; i++) {
for (int j = check; j < len1; j++) {
if (seq[j] == subs[i]) {
check = j + 1;
count++;
break;
}
}
}
if (count == len2) {
printf("YES\n");
}
else {
printf("NO\n");
}
}
return 0;
}<file_sep>#include <stdio.h>
int main(void)
{
int test,price, day, don, p;
scanf("%d", &test);
while(test--){
don = 0;
day = 1;
scanf("%d", &price);
while(1){
don = 5000 + don + 200*(day / 10);
if(don>=price)
break;
day++;
}
printf("%d\n", day);
}
return 0;
}<file_sep>#include <stdio.h>
int main(void)
{
int test, a, b, first;
scanf("%d", &test);
while (test--) {
scanf("%d", &first);
a = 2;
b = first - 2;
if (b >= 2) {
if (b % 2 == 0) {
printf("%d %d\n", a, b);
}
else
printf("NO\n");
}
else
printf("NO\n");
}
return 0;
}<file_sep>#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<time.h>
int IsPrime(int n){
int i, limit;
if(n<=1) return 0;
if(n==2) return 1;
if(n%2==0) return 0;
limit=(int)sqrt((double)n);
for(i=3; i<=limit; i=i+2){
if(n%i==0){
return 0;
}
}
return 1;
}
int main(void){
int test, a, b, prime, sum, q;
scanf("%d", &test);
while(test--){
sum=0;
scanf("%d %d", &a, &b);
for(q=a; q<=b; q++){
if(IsPrime(q)==1){
sum++;
}
}
printf("%d\n", sum);
}
return 0;
}<file_sep>#include <stdio.h>
int main(void)
{
int number;
number <= 6;
scanf("%d", &number);
if (number == 1) {
printf("%d", 500);
}
else if (number == 2) {
printf("600");
}
else if (number == 3) {
printf("%d", 500);
}
else if (number == 4) {
printf("%d", 500);
}
else if (number == 5) {
printf("1000");
}
else if ( number == 6) {
printf("600");
}
return 0;
}<file_sep>#include <stdio.h>
#include <string.h>
struct JA {
char menuName[21];
int money;
};
int main(void) {
int test;
scanf("%d", &test);
while (test--) {
int price, menu, sum = 0, paper, s1, s5, s10;
struct JA sa[30];
char buy[21];
scanf("%d %d", &menu, &price);
for (int i = 0; i < menu; i++) {
scanf("%s %d", sa[i].menuName, &sa[i].money);
}
for (int i = 0; i < price; i++) {
scanf("%s", buy);
for (int j = 0; j < menu; j++) {
int o = strcmp(buy, sa[j].menuName);
if (o == 0) {
sum += sa[j].money;
}
}
}
int sum3;
if (sum % 1000 != 0) {
sum3 = sum / 1000;
sum3 += 1;
sum3 = sum3 * 1000;
}
else {
sum3 = sum;
}
s10 = sum3 / 10000;
s5 = sum3 / 5000 - s10 * 2;
s1 = sum3 / 1000 - (s5 * 5 + s10 * 10);
paper = s10 + s5 + s1;
int input = sum / 1000;
if (sum % 1000 != 0)
input++;
int ininput = input * 1000 - sum;
int d5, d1;
d5 = ininput / 500;
d1 = ininput / 100 - 5 * d5;
int sum2 = d1 + d5;
printf("%d %d %d %d %d\n", sum, input * 1000, paper, ininput, sum2);
}
return 0;
}<file_sep>#include <stdio.h>
int main()
{
int a, b, c, d, e, f, g;
int sum1, sum2;
scanf("%d %d %d %d %d %d %d", &a, &b, &c, &d, &e, &f, &g);
sum1 = a + b + c + d + e + f + g;
printf("%d\n", sum1);
sum2 = (sum1 - sum1 % 7) / 7;
printf("%d", sum2);
return 0;
}<file_sep>#include <stdio.h>
#include <string.h>
int main() {
int test;
scanf("%d", &test);
while (test--) {
int x, y;
char str[50];
scanf("%d %d", &x, &y);
scanf("%s", &str);
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (str[i] == 'L') {
x = x - 1;
}
else if (str[i] == 'R') {
x = x + 1;
}
else if (str[i] == 'D') {
y = y - 1;
}
else if (str[i] == 'U') {
y = y + 1;
}
}
printf("%d %d\n", x, y);
}
return 0;
}
<file_sep>#include<stdio.h>
int main(void) {
int b, day;
long long a, v, sum;
sum = 0;
day =1 ;
scanf("%d %d %d", &a, &b, &v);
while (1) {
sum = sum + a;
if (sum>= v) {
break;
}
else {
sum = sum - b;
day++;
}
}
printf("%d\n", day);
return 0;
}<file_sep>#include <stdio.h>
int main() {
int a, b, c, sum, max;
int test;
max = 0;
scanf("%d", &test);
while (test--) {
scanf("%d %d %d", &a, &b, &c);
if (a == b && b == c) {
sum = 10000 + a * 1000;
}
else if (a != b && b != c && c != a) {
if (a >= b) {
if (a >= c) {
sum = a * 100;
}
else {
sum = c * 100;
}
}
else if (b >= a) {
if (b >= c) {
sum = b * 100;
}
else {
sum = c * 100;
}
}
}
else {
if (a == b) {
sum = 1000 + 100 * a;
}
else if (b == c) {
sum = 1000 + 100 * c;
}
else {
sum = 1000 + 100 * a;
}
}
if (sum >= max) {
max = sum;
}
}
printf("%d\n", max);
return 0;
}<file_sep>#include <stdio.h>
int main()
{
int r;
int sum;
scanf("%d", &r);
sum = 4 * r * r;
printf("%d", sum);
return 0;
}<file_sep>#include <stdio.h>
int main()
{
int m, n, k, sum, sum2;
while (1) {
scanf("%d %d %d", &m, &n, &k);
if (m == 0 && n == 0 && k == 0) {
break;
}
sum = n * (n + 1) / 2 - m * (m - 1) / 2;
sum2 = sum % k;
if (sum2 == 0) {
printf("YES\n");
}
else {
printf("NO\n");
}
}
}<file_sep>#include <stdio.h>
int main() {
int test;
scanf("%d", &test);
while (test--) {
int deon, jeon;
scanf("%d %d", &deon, &jeon);
int level[12][15], twice[30];
for (int i = 0; i < deon; i++) {
for (int j = 0; j < jeon; j++) {
scanf("%d", &level[i][j]);
}
}
for (int i = 0; i < deon; i++) {
int max = 0;
int min = 501;
for (int j = 0; j < jeon; j++) {
if (level[i][j] > max) {
max = level[i][j];
}
if (level[i][j] < min) {
min = level[i][j];
}
}
twice[i] = max;
twice[i + deon] = min;
}
int twice2[30];
for (int i = 0; i < deon; i++) {
twice2[i] = twice[i];
}
for (int i = 0; i < 2 * deon - 1; i++) {
for (int j = i+1; j < 2 * deon; j++) {
if (twice[i] < twice[j]) {
int tmp = twice[i];
twice[i] = twice[j];
twice[j] = tmp;
}
}
}
printf("%d %d\n", twice[0], twice[2 * deon - 1]);
for (int i = 0; i < deon - 1; i++) {
for (int j = i+1; j < deon; j++) {
if (twice2[i] > twice2[j]) {
int tmp = twice2[i];
twice2[i] = twice2[j];
twice2[j] = tmp;
}
}
}
for (int i = 0; i < deon; i++) {
printf("%d", twice2[i]);
if (i != deon - 1) {
printf(" ");
}
else {
printf("\n");
}
}
}
return 0;
}<file_sep>#include <stdio.h>
int main(void) {
int a, i, b, c, d, e;
scanf("%d", &a);
for (i = 1; i <= a; i++) {
for (b = 1; b <= 2*a-1; b++) {
printf("%%");
}
printf("\n");
}
for (c = 1; c <= a; c++) {
for (e = a; e > c; e--) {
printf(" ");
}
for (d = 1; d <= 2*c-1; d++) {
printf("%%");
}
printf("\n");
}
return 0;
}<file_sep>#include <stdio.h>
int main(void) {
int a,b;
int test;
float x, y;
scanf("%d", &test);
while (test--) {
scanf("%d:%d", &a, &b);
x = a * 30+b*0.5;
y = b * 6;
printf("%.1f %.1f\n", x, y);
}
return 0;
}<file_sep>#include <stdio.h>
#include <math.h>
int main() {
int test;
scanf("%d", &test);
while (test--) {
int ip[4], sum[4];
char c;
scanf("%d %c %d %c %d %c %d", &ip[0], &c, &ip[1], &c, &ip[2], &c, &ip[3]);
for (int i = 0; i < 4; i++) {
sum[i] = 0;
int count = 0;
while (ip[i] != 1 && ip[i] != 0) {
sum[i] += (ip[i] % 2) * pow(10, count);
ip[i] = ip[i] / 2;
count++;
}
sum[i] += ip[i] * pow(10, count);
}
for (int i = 0; i < 4; i++) {
printf("%08d", sum[i]);
}
printf("\n");
}
return 0;
}
<file_sep>#include <stdio.h>
int main(void){
int a, b, c, d, e, f, g, h, sum1, sum2;
scanf("%d %d %d %d %d %d %d %d", &a, &b, &c, &d, &e, &f, &g, &h);
sum1 = a + c+e+g;
sum2 = b + d + f+ h;
printf("%d %d\n", sum2, sum1);
return 0;
}<file_sep>#include <stdio.h>
int main(void)
{
int test, x, y;
char c;
scanf("%d", &test);
while (test--) {
scanf("%d %d %c", &x, &y, &c);
if (c == '+')
printf("%d\n", x + y);
else if (c == '*')
printf("%d\n", x * y);
else if (c == '/') {
if (y == 0)
printf("-9999\n");
else
printf("%d\n", x / y);
}
else if (c == '-')
printf("%d\n", x - y);
}
}
<file_sep>#include <stdio.h>
#include <string.h>
int main() {
int test,num=1;
scanf("%d", &test);
while (test--) {
int pass;
char word[1000] = { 0, };
scanf("%d %s", &pass, word);
int len = strlen(word);
printf("%d ", num++);
for (int i = 0; i < pass-1; i++) {
printf("%c", word[i]);
}
for (int i = pass; i < len; i++) {
printf("%c", word[i]);
}
printf("\n");
}
return 0;
}<file_sep>#include <stdio.h>
int main(void)
{
int x;
int y;
int z;
int h;
int o;
int sum;
scanf("%d %d %d %d %d", &x, &y, &z, &h, &o);
sum =( x * x + y * y + z * z + h * h + o * o ) % 10;
printf("%d\n", sum);
return 0; // 0을 외부로 반환
}<file_sep>#include <stdio.h>
int main(void)
{
int test, mo, wo, my, wy;
scanf("%d", &test);
while(test--){
scanf("%d %d %d %d", &mo, &wo, &my, &wy);
if ( wo == 0 && wy == 0 && my >= 1)
printf("1\n");
else if ( wo >=1 || wy >=1)
printf("%d\n", wo + wy);
else if ( mo>=1 && wo == 0 && wy == 0 && my == 0)
printf("Not Attended\n");
}
}<file_sep>#include <stdio.h>
int main(void)
{
int x;
int y;
int sum;
scanf("%d %d", &x, &y);
sum = x * y;
printf("%d\n", sum);
return 0; // 0을 외부로 반환
}<file_sep>#include <stdio.h>
int main() {
int test;
scanf("%d", &test);
while (test--) {
int num, find, input[100] = { 0, };
scanf("%d", &num);
for (int i = 0; i < num; i++) {
scanf("%d", &input[i]);
}
scanf("%d", &find);
int result = 0;
for (int i = 0; i < num; i++) {
if (find == input[i]) {
result++;
}
}
if (result == 0) {
printf("None\n");
}
else {
printf("%d\n", result);
}
}
return 0;
}<file_sep>#include <stdio.h>
int main(void) {
int a, b;
while (1) {
scanf("%d %d", &a, &b);
if (a == 0 && b == 0) {
break;
}
if (a == b) {
printf("draw!\n");
}
else if ((a == 1 && b == 2)||(a==2&&b==3)||(a==3&&b==1)) {
printf("JJH wins!\n");
}
else {
printf("PEJ wins!\n");
}
}
}<file_sep>#include <stdio.h>
int main(void) {
int sum, t, i;
int test;
scanf("%d", &test);
while (test--) {
i = 1;
sum = 1;
scanf("%d", &t);
while (t >= i) {
if (sum%i == 0) {
sum = sum / i;
}
else {
sum = sum * i;
}
i++;
}
printf("%d\n", sum);
}
return 0;
}<file_sep>#include<stdio.h>
int main(void){
int max, min, t, in, sum;
while (1) {
max = 0;
min = 1001;
scanf("%d", &t);
if (t == 0) {
break;
}
while (t--) {
scanf("%d", &in);
if (in > max) {
max = in;
}
if (in < min) {
min = in;
}
}
sum = max - min;
if (sum % 2 == 0) {
printf("Yes\n");
}
else {
printf("No\n");
}
}
return 0;
}<file_sep>#include <stdio.h>
int main(void) {
int a, b, c, max, sum, test;
float mm;
scanf("%d", &test);
while (test--) {
max = 0;
scanf("%d %d %d", &a, &b, &c);
if (a >= max) {
max = a;
}
if (b >= max) {
max = b;
}
if (c >= max) {
max = c;
}
if (max == a && a <= b + c) {
sum = a * a;
if (sum == b * b + c * c) {
mm = b * c / 2;
printf("%.2f\n", mm);
}
else {
printf("-2\n");
}
}
else if (max == b && b <= a + c) {
sum = b * b;
if (sum == a * a + c * c) {
mm = a * c / 2;
printf("%.2f\n", mm);
}
else {
printf("-2\n");
}
}
else if (max == c && c <= b + a) {
sum = c * c;
if (sum == b * b + a * a) {
mm = b * a / 2;
printf("%.2f\n", mm);
}
else {
printf("-2\n");
}
}
else {
printf("-1\n");
}
}
return 0;
}<file_sep>#include <stdio.h>
void main() {
int n[100][100];
int a, b;
int test;
scanf("%d", &test);
while (test--) {
scanf("%d %d", &a, &b);
for (int i = 0; i < a; i++) {
for (int j = 0; j < b; j++) {
scanf("%d", &n[i][j]);
}
}
for (int i = 0; i < b; i++) {
for (int j = 0; j < a; j++) {
printf("%d", n[j][i]);
if (j < a - 1) {
printf(" ");
}
}
printf("\n");
}
}
}<file_sep>#include <stdio.h>
int main() {
int test;
scanf("%d", &test);
while (test--) {
int i, q;
scanf("%d", &i);
for (int k = 0; k < i; k++) {
for (int j = k; j < i - 1; j++) {
printf(" ");
}
q = i;
for (int u = 0; u <= k; u++) {
printf("%d", q);
q--; // 마지막에 0만들어 버림
}
q = q + 2;
for (int u = 0; u < k; u++) {
printf("%d", q);
if (q < i) {
q++;
}
}
printf("\n");
}
for (int k = 1; k < i; k++) {
for (int u = 0; u < k; u++) {
printf(" ");
}
q = i;
for (int u = 0; u < i - k; u++) {
printf("%d", q);
q--;
}
q = q + 2;
for (int u = 0; u < i - k - 1; u++) {
printf("%d", q);
q++;
}
printf("\n");
}
}
return 0;
}<file_sep>#include <stdio.h>
int main(void)
{
int x, grade;
scanf("%d", &x);
if (x == 100)
printf("A++");
else if (x >=97)
printf("A+");
else if (x >= 93)
printf("A");
else if (x >= 90)
printf("A-");
else if (x >= 87)
printf("B+");
else if (x >= 83)
printf("B");
else if (x >= 80)
printf("B-");
else if (x >= 77)
printf("C+");
else if (x >= 73)
printf("C");
else if (x >= 70)
printf("C-");
else if (x >= 67)
printf("D+");
else if (x >= 63)
printf("D");
else if (x >= 60)
printf("D-");
else if (x < 60)
printf("F");
}
<file_sep>#include <stdio.h>
#include <math.h>
int main(){
int test, a, b, c, d, e, f, m,j, x, y, z, t, u, v, sum1, sum2;
scanf("%d", &test);
while(test--){
scanf("%d %d %d %d %d %d", &a, &b, &c, &d, &e, &f);
j = a+b+c;
m = d + e +f;
if(j>m)
printf("Joo-Ahn wins\n");
else if (j<m)
printf("Min-Gwang wins\n");
else if (j=m){
x = a % 2;
y = b % 2;
z = c % 2;
t = d %2;
u = e %2;
v = f %2;
sum1 = x + y +z;
sum2 = t + u + v;
if (sum1>sum2)
printf("Joo-Ahn wins\n");
else if (sum2>sum1)
printf("Min-Gwang wins\n");
else
printf("Draw\n");
}
}
}<file_sep>#include <stdio.h>
int main(void) {
int a, b, c, sum;
while (1) {
scanf("%d %d %d", &a, &b, &c);
if (a == 0 && b == 0 && c==0) {
break;
}
sum = b * b - 4 * a*c;
if (sum>0) {
printf("real\n");
}
else if (sum == 0) {
printf("multiple\n");
}
else {
printf("imaginary\n");
}
}
return 0;
}<file_sep>#include<stdio.h>
int main() {
int i, a, b, t, c, d, e, f, g, h, q, test;
scanf("%d", &test);
while (test--) {
scanf("%d", &i);
for (d = 1; d <= i; d++) {
for (g = i; g > d; g--) {
printf(" ");
}
for (f = 1; d >= f; f++) {
printf("%d", f);
}
for (h = 1; h < d; h++) {
printf("%d", f - 2);
f--;
}
printf("\n");
}
for (a = 2; a <= i; a++) {
for (b = 1; b < a; b++) {
printf(" ");
}
q = 1;
for (c = i; c >= a; c--) {
printf("%d", q);
q++;
}
for (e = i; e > a; e--) {
printf("%d", q - 2);
q--;
}
printf("\n");
}
}
return 0;
}<file_sep>#include <stdio.h>
int main() {
int test;
scanf("%d", &test);
while (test--) {
int deon, jeon;
scanf("%d %d", &deon, &jeon);
int level[7][20], twice[14];
for (int i = 0; i < deon; i++) {
for (int j = 0; j < jeon; j++) {
scanf("%d", &level[i][j]);
}
}
for (int i = 0; i < deon; i++) {
int max = 0;
int min = 501;
for (int j = 0; j < jeon; j++) {
if (level[i][j] > max) {
max = level[i][j];
}
if (level[i][j] < min) {
min = level[i][j];
}
}
twice[i] = max;
twice[i + deon] = min;
}
int max = twice[0];
for (int i = 1; i < deon * 2; i++) {
if (twice[i] > max) {
max = twice[i];
}
}
printf("%d\n", max);
for (int i = 0; i < deon; i++) {
printf("%d %d\n", twice[i], twice[i + deon]);
}
}
return 0;
}<file_sep>#include <stdio.h>
typedef struct lotte {
char name[16];
int age;
char position[21];
int backNum;
}lotte;
int main() {
int n, oldest = 0,a,youngest=100,b;
long long int sum = 0;
lotte sun[15];
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%s %d %s %d", sun[i].name, &sun[i].age, sun[i].position, &sun[i].backNum);
if (oldest <= sun[i].age) {
oldest = sun[i].age;
a = i;
}
if (youngest >= sun[i].age) {
youngest = sun[i].age;
b = i;
}
}
for (int i = 0; i < n; i++) {
sum += sun[i].age;
}
sum = sum / n;
printf("average age : %d\n", sum);
printf("the oldest : %s %s %d\n", sun[a].name,sun[a].position, sun[a].backNum);
printf("the youngest : %s %s %d\n", sun[b].name, sun[b].position, sun[b].backNum);
return 0;
}<file_sep>#include <stdio.h>
int main(void){
int test, m, n ,d1, d2;
scanf("%d", &test);
while(test--){
scanf("%d %d %d %d", &m, &n, &d1, &d2);
if ( m%d1==0 && m%d2==0 && n%d1==0 && n%d2==0)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}<file_sep>#include <stdio.h>
#include <string.h>
typedef struct input {
char word[17];
int score;
}input;
int main() {
input in[1000];
int mun, say;
scanf("%d %d", &say, &mun);
for (int i = 0; i < say; i++) {
scanf("%s %d", in[i].word, &in[i].score);
}
for (int i = 0; i < mun; i++) {
int sum = 0; // 점수매기기용
while(1){
char munz[17]; // 단어 입력받기
scanf("%s", munz);
if (strcmp(munz,".")==0) {// . 일경우에는 이 반복문 종료
break;
}
for (int j = 0; j < say; j++) {
int result = strcmp(munz, in[j].word); // 아니면 munz랑 사전 단어 비교
if (result == 0) { // strcmp 같으면 0 반환
sum += in[j].score; // 점수 쁘라스
break; // 끝
}
}
}
printf("%d\n", sum);
// 점수 출력
}
return 0;
}<file_sep>#include <stdio.h>
#include <string.h>
typedef struct word {
char words[26];
int score;
}word;
int main() {
int test;
scanf("%d", &test);
while (test--) {
int wordSu, sentence;
word W[10];
scanf("%d %d", &wordSu, &sentence);
for (int i = 0; i < wordSu; i++) {
scanf("%s %d", W[i].words, &W[i].score);
}
for (int j = 0; j < wordSu; j++) {
int len = strlen(W[j].words);
for (int i = 0; i < len; i++) {
if (W[j].words[i] >= 65 && W[j].words[i] <= 90) {
W[j].words[i] += 32;
}
}
}
for (int i = 0; i < sentence; i++) {
int sum = 0;
while (1) {
char al[26];
scanf("%s", al);
if (strcmp(al, ".") == 0)
break;
int len = strlen(al);
for (int j = 0; j < len; j++) {
if (al[j] >= 65 && al[j] <= 90) {
al[j] += 32;
}
}
int count = 0;
for (int j = 0; j < wordSu; j++) {
if (strcmp(W[j].words, al) == 0) {
sum -= W[j].score;
}
else {
count++;
}
}
if (count == wordSu) {
sum += len%10;
}
}
printf("%d\n", sum);
}
}
return 0;
}<file_sep>#include <stdio.h>
int main(void)
{
int m, d1, d2, d3, test;
scanf("%d", &test);
while (test--) {
scanf("%d %d %d %d", &m, &d1, &d2, &d3);
if (m%d1 == 0 && m%d2 == 0 && m%d3 == 0)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}<file_sep>#include <stdio.h>
int main(void)
{
int day, money, sum, test, b;
scanf("%d", &test);
while (test--) {
scanf("%d", &day);
b = day;
sum = 0;
while (day--) {
scanf("%d", &money);
sum = money + sum;
}
printf("%d %d\n", sum, sum / b);
}
return 0;
}
<file_sep>/* 두 개의 숫자의 합을 계산하는 프로그램 */
#include <stdio.h>
int main(void)
{
int x; // 첫 번째 정수를 저장할 변수
int y; // 두 번째 정수를 저장할 변수
int sum; // 두 정수의 합을 저장하는 변수
scanf("%d %d", &x, &y); // 하나의 정수를 받아서 x에 저장
sum = x + y; // 변수 2개를 더한다.
printf("%d\n", sum); // sum의 값을 10 진수 형태로 출력
return 0; // 0을 외부로 반환
}<file_sep>#include<stdio.h>
int main(void){
int i, test, a;
long long sum;
scanf("%d", &test);
while(test--){
scanf("%d %d", &a, &i);
sum=0;
while(a<=i){
sum = sum+a;
a++;
}
printf("%ld\n", sum);
}
return 0;
}<file_sep>#include <stdio.h>
int main(void) {
int a, b, c, d, e, f, g;
float sum;
scanf("%d %d %d %d %d %d %d", &a, &b, &c, &d, &e, &f, &g);
sum = (a + b + c + d + e + f + g);
printf("%.2f", sum / 7);
return 0;
}
|
aa9a5e20429bcf2daa49991dfe12757d4dd235a9
|
[
"Markdown",
"C",
"Python"
] | 97
|
C
|
YooJ-K/lavida.us
|
edd9048f2409ab8d84491220629c59b453e37fb1
|
2f35ca44e14cf54168108be8ebc6f2f614069604
|
refs/heads/master
|
<file_sep>SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema forum_system
-- -----------------------------------------------------
DROP SCHEMA IF EXISTS `forum_system` ;
CREATE SCHEMA IF NOT EXISTS `forum_system` DEFAULT CHARACTER SET utf8 ;
USE `forum_system` ;
-- -----------------------------------------------------
-- Table `forum_system`.`users`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `forum_system`.`users` ;
CREATE TABLE IF NOT EXISTS `forum_system`.`users` (
`user_id` INT(11) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(50) NOT NULL,
`password` VARCHAR(150) NOT NULL,
`email` VARCHAR(50) NOT NULL,
`avatar_path` VARCHAR(100) NULL,
`auth_token` VARCHAR(150) NULL DEFAULT NULL,
`registered_on` DATETIME NOT NULL DEFAULT NOW(),
PRIMARY KEY (`user_id`),
UNIQUE INDEX `username_UNIQUE` (`username` ASC),
UNIQUE INDEX `email_UNIQUE` (`email` ASC))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
-- -----------------------------------------------------
-- Table `forum_system`.`categories`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `forum_system`.`categories` ;
CREATE TABLE IF NOT EXISTS `forum_system`.`categories` (
`category_id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(80) NOT NULL,
PRIMARY KEY (`category_id`),
UNIQUE INDEX `name_UNIQUE` (`name` ASC))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `forum_system`.`questions`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `forum_system`.`questions` ;
CREATE TABLE IF NOT EXISTS `forum_system`.`questions` (
`question_id` INT(11) NOT NULL AUTO_INCREMENT,
`title` VARCHAR(50) NOT NULL,
`text` TEXT NOT NULL,
`user_id` INT(11) NOT NULL,
`category_id` INT NOT NULL,
PRIMARY KEY (`question_id`),
INDEX `fk_questions_users1_idx` (`user_id` ASC),
INDEX `fk_questions_categories1_idx` (`category_id` ASC),
CONSTRAINT `fk_questions_users1`
FOREIGN KEY (`user_id`)
REFERENCES `forum_system`.`users` (`user_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_questions_categories1`
FOREIGN KEY (`category_id`)
REFERENCES `forum_system`.`categories` (`category_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
-- -----------------------------------------------------
-- Table `forum_system`.`tags`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `forum_system`.`tags` ;
CREATE TABLE IF NOT EXISTS `forum_system`.`tags` (
`tag_id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(40) NOT NULL,
PRIMARY KEY (`tag_id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
-- -----------------------------------------------------
-- Table `forum_system`.`questions_tags`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `forum_system`.`questions_tags` ;
CREATE TABLE IF NOT EXISTS `forum_system`.`questions_tags` (
`question_id` INT(11) NOT NULL,
`tag_id` INT(11) NOT NULL,
INDEX `fk_questions_tags_questions_idx` (`question_id` ASC),
INDEX `fk_questions_tags_tags1_idx` (`tag_id` ASC),
CONSTRAINT `fk_questions_tags_questions`
FOREIGN KEY (`question_id`)
REFERENCES `forum_system`.`questions` (`question_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_questions_tags_tags1`
FOREIGN KEY (`tag_id`)
REFERENCES `forum_system`.`tags` (`tag_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `forum_system`.`answers`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `forum_system`.`answers` ;
CREATE TABLE IF NOT EXISTS `forum_system`.`answers` (
`answer_id` INT NOT NULL AUTO_INCREMENT,
`text` TEXT NOT NULL,
`date_created` DATETIME NOT NULL DEFAULT NOW(),
`question_id` INT(11) NOT NULL,
`users_user_id` INT(11) NOT NULL,
PRIMARY KEY (`answer_id`),
INDEX `fk_answers_questions1_idx` (`question_id` ASC),
INDEX `fk_answers_users1_idx` (`users_user_id` ASC),
CONSTRAINT `fk_answers_questions1`
FOREIGN KEY (`question_id`)
REFERENCES `forum_system`.`questions` (`question_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_answers_users1`
FOREIGN KEY (`users_user_id`)
REFERENCES `forum_system`.`users` (`user_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;<file_sep><?php
class UserController extends \BaseController {
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create() {
return View::make('user.register');
}
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store() {
$userData = Input::all();
$user = new User();
if($user->validate($userData)) {
$user->setData($userData);
$user->save();
return Redirect::to('/');
} else {
return Redirect::to('user/register')->withErrors($user->errors)->withInput();
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show($id) {
if (Auth::check()) {
echo Auth::user()->username;
} else {
echo 'no user';
}
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return Response
*/
public function edit($id) {
//
}
/**
* Update the specified resource in storage.
*
* @param int $id
* @return Response
*/
public function update($id) {
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
*/
public function destroy($id) {
//
}
public function login() {
if (Auth::attempt(['username' => Input::get('username'), 'password' => Input::get('password')])) {
// $arr = ['user' => Auth::user()->username, 'id' => Auth::id()];
return View::make('secure');
} else {
return Redirect::to('user.login');
}
}
public function logged() {
// echo Auth::check();
$questions = Questions::all();
$arr = [];
foreach ($questions as $question) {
$arr['n'.$question->id]['id' . $question->id]['title'] = $question->title;
$arr['n'.$question->id][$question->id]['text'] = $question->text;
$arr['n'.$question->id][$question->id]['tags'] = $question->tags;
$arr['n'.$question->id][$question->id]['category'] = $question->category;
}
$arr['count']= count($arr);
if (Auth::check()) {
$arr['user'] = Auth::user()->username;
// print_r($arr);exit;
}
// echo '<pre>'.print_r($arr,true).'</pre>';exit; //ДЕНИС, тук пробвам данните към вюто!
return View::make('hello', $arr);
}
public function logged1() {
if (Auth::check()) {
$arr = ['user' => Auth::user()->username, 'id' => Auth::id()];
return View::make('secure', $arr);
} else {
return View::make('login');
}
}
public function logout() {
Auth::logout();
Session::flush();
return Redirect::to('/');
}
}
|
776fd53f9bcded5d769e83ac07bd2efb63633288
|
[
"SQL",
"PHP"
] | 2
|
SQL
|
evgenitochev/Forum-System
|
320c10f58f3559f2ae04a51cbd681726e44cc85e
|
1a740c8770cb9e9da6a1cee7092cd9dd9aa32512
|
refs/heads/master
|
<repo_name>rgynn/golang_vagrant<file_sep>/README.md
## Golang dev enviroment with vagrant
This is a project explaining how to easily setup a golang dev environment running:
* Ubuntu - 16.04.1 LTS
* Golang - 1.7.4
* Vim-Go
* Delve
* Gin
<file_sep>/bootstrap.sh
#!/bin/bash
# install git
sudo apt-get install -y git
# golang installation variables
VERSION='1.7.4'
OS='linux'
ARCH='amd64'
# install golang
wget https://storage.googleapis.com/golang/go$VERSION.$OS-$ARCH.tar.gz
sudo tar -C /usr/local -xzf ./go$VERSION.$OS-$ARCH.tar.gz
rm -rf ./go$VERSION.$OS-$ARCH.tar.gz
mkdir -p /home/vagrant/go/bin
mkdir -p /home/vagrant/go/pkg
mkdir -p /home/vagrant/go/src
# set environment variables
export PATH=$PATH:/usr/local/go/bin:/home/vagrant/go/bin
export GOPATH=/home/vagrant/go
echo "export GOPATH=/home/vagrant/go" >> /home/vagrant/.bashrc
echo "PATH=\$PATH:/usr/local/go/bin:/home/vagrant/go/bin" >> /home/vagrant/.bashrc
# print the go enviroment variables
go env
# go get tools
go get -u -v github.com/nsf/gocode
go get -u -v github.com/rogpeppe/godef
go get -u -v github.com/zmb3/gogetdoc
go get -u -v github.com/golang/lint/golint
go get -u -v github.com/lukehoban/go-outline
go get -u -v sourcegraph.com/sqs/goreturns
go get -u -v golang.org/x/tools/cmd/gorename
go get -u -v github.com/tpng/gopkgs
go get -u -v github.com/newhook/go-symbols
go get -u -v golang.org/x/tools/cmd/guru
go get -u -v github.com/cweill/gotests/...
go get -u -v github.com/derekparker/delve/cmd/dlv
go get -u -v github.com/codegangsta/gin
# install vim-plug and vim-go
curl -fLo /home/vagrant/.vim/autoload/plug.vim --create-dirs https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
git clone https://github.com/fatih/vim-go.git /home/vagrant/.vim/plugged/vim-go
cat <<EOT >> /home/vagrant/.vimrc
call plug#begin()
Plug 'fatih/vim-go', { 'do': ':GoInstallBinaries' }
call plug#end()
EOT
sudo chown -R vagrant:vagrant /home/vagrant/.vim
sudo chown -R vagrant:vagrant /home/vagrant/.vimrc
sudo chown -R vagrant:vagrant /home/vagrant/go
sudo chmod -R 0770 /home/vagrant/.vim
sudo chmod -R 0770 /home/vagrant/.vimrc
sudo chmod -R 0770 /home/vagrant/go
|
65f24b98c2fb61f14247772620519b6ddf6935c8
|
[
"Markdown",
"Shell"
] | 2
|
Markdown
|
rgynn/golang_vagrant
|
666baef710af6e44efac6054bc58a457233a5528
|
7297a01dd06b17747c151437470e84dc8e6f74f4
|
refs/heads/master
|
<repo_name>jdruid/AppStudio-SoundCloudAPI<file_sep>/AppStudio.Shared/Common/ActionCommands.cs
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved
using System;
using System.Windows.Input;
using AppStudio.Services;
namespace AppStudio
{
public class ActionCommands
{
static public ICommand ShowImage
{
get
{
return new RelayCommandEx<string>((param) =>
{
if (!String.IsNullOrEmpty(param))
{
NavigationServices.NavigateToPage("ImageViewer", param);
}
});
}
}
static public ICommand MailTo
{
get
{
return new RelayCommandEx<string>((param) =>
{
if (!String.IsNullOrEmpty(param))
{
string url = String.Format("mailto:{0}", param);
NavigationServices.NavigateTo(new Uri(url));
}
});
}
}
static public ICommand CallToPhone
{
get
{
return new RelayCommandEx<string>((param) =>
{
if (!String.IsNullOrEmpty(param))
{
string url = String.Format("tel:{0}", param);
NavigationServices.NavigateTo(new Uri(url));
}
});
}
}
static public ICommand NavigateToUrl
{
get
{
return new RelayCommandEx<string>((param) =>
{
if (!String.IsNullOrEmpty(param))
{
string url = param;
NavigationServices.NavigateTo(new Uri(url));
}
});
}
}
static public ICommand MusicPlayArtistMix
{
get
{
return new RelayCommandEx<string>(async (param) =>
{
if (!String.IsNullOrEmpty(param))
{
await NokiaMusicServices.PlayArtistMix(param);
}
});
}
}
static public ICommand MusicLaunchSearch
{
get
{
return new RelayCommandEx<string>(async (param) =>
{
if (!String.IsNullOrEmpty(param))
{
await NokiaMusicServices.LaunchSearch(param);
}
});
}
}
static public ICommand MusicLaunchArtist
{
get
{
return new RelayCommandEx<string>(async (param) =>
{
if (!String.IsNullOrEmpty(param))
{
await NokiaMusicServices.LaunchArtist(param);
}
});
}
}
static public ICommand MapsPosition
{
get
{
return new RelayCommandEx<string>(async (param) =>
{
if (!String.IsNullOrEmpty(param))
{
await NokiaMapsServices.MapPosition(param);
}
});
}
}
static public ICommand MapsHowToGet
{
get
{
return new RelayCommandEx<string>(async (param) =>
{
if (!String.IsNullOrEmpty(param))
{
await NokiaMapsServices.HowToGet(param);
}
});
}
}
private static void NavigateTo(string protocol, string param)
{
if (!String.IsNullOrEmpty(param))
{
string url = String.Format("{0}:{1}", protocol, param);
var uri = new Uri(url);
NavigationServices.NavigateTo(uri);
}
}
/// <summary>
/// SoundCloudLaunchTrack take the paramater from the 'click' and looks up the proper track id and returns
/// the stream url to launch in the WebBrowser
/// </summary>
static public ICommand SoundCloudLaunchTrack
{
get
{
return new RelayCommandEx<string>(async (param) =>
{
if (!String.IsNullOrEmpty(param))
{
string streamUrl = await SoundCloudMusicService.LaunchTrack(param);
NavigationServices.NavigateTo(new Uri(streamUrl));
}
});
}
}
}
}
<file_sep>/AppStudio.Data/DataSchemas/SoundCloudTrackSchema.cs
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppStudio.Data.SoundCloud
{
public class User
{
public int id { get; set; }
public string kind { get; set; }
public string permalink { get; set; }
public string username { get; set; }
public string last_modified { get; set; }
public string uri { get; set; }
public string permalink_url { get; set; }
public string avatar_url { get; set; }
}
public class SoundCloudTrackSchema
{
public string kind { get; set; }
public int id { get; set; }
public string created_at { get; set; }
public int user_id { get; set; }
public int duration { get; set; }
public bool commentable { get; set; }
public string state { get; set; }
public int original_content_size { get; set; }
public string last_modified { get; set; }
public string sharing { get; set; }
public string tag_list { get; set; }
public string permalink { get; set; }
public bool streamable { get; set; }
public string embeddable_by { get; set; }
public bool downloadable { get; set; }
public object purchase_url { get; set; }
public object label_id { get; set; }
public object purchase_title { get; set; }
public string genre { get; set; }
public string title { get; set; }
public string description { get; set; }
public string label_name { get; set; }
public string release { get; set; }
public string track_type { get; set; }
public string key_signature { get; set; }
public string isrc { get; set; }
public object video_url { get; set; }
public object bpm { get; set; }
public object release_year { get; set; }
public object release_month { get; set; }
public object release_day { get; set; }
public string original_format { get; set; }
public string license { get; set; }
public string uri { get; set; }
public User user { get; set; }
public string permalink_url { get; set; }
public object artwork_url { get; set; }
public string waveform_url { get; set; }
public string stream_url { get; set; }
public string download_url { get; set; }
public int playback_count { get; set; }
public int download_count { get; set; }
public int favoritings_count { get; set; }
public int comment_count { get; set; }
public string attachments_uri { get; set; }
public string policy { get; set; }
}
}
<file_sep>/BackgroundAudioTask/BackgroundAudioTask.cs
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved
using System;
using System.Diagnostics;
using System.Threading; //AutoResetEvent
using Windows.ApplicationModel.Background;
using Windows.Foundation.Collections;
using Windows.Media;
using Windows.Media.Playback;
namespace BackgroundAudioTask
{
/// <summary>
/// Enum to identify foreground app state
/// </summary>
enum ForegroundAppStatus
{
Active,
Suspended,
Unknown
}
/// <summary>
/// Impletements IBackgroundTask to provide an entry point for app code to be run in background.
/// Also takes care of handling UVC and communication channel with foreground
/// </summary>
public sealed class BackgroundAudioTask: IBackgroundTask
{
private BackgroundTaskDeferral _deferral;
private SystemMediaTransportControls _systemMediaTransportControl;
private ForegroundAppStatus foregroundAppState = ForegroundAppStatus.Unknown;
private AutoResetEvent BackgroundTaskStarted = new AutoResetEvent(false);
private bool backgroundtaskrunning = false;
public void Run(IBackgroundTaskInstance taskInstance)
{
Debug.WriteLine("Background Audio Task " + taskInstance.Task.Name + " starting...");
_systemMediaTransportControl = SystemMediaTransportControls.GetForCurrentView();
_systemMediaTransportControl.IsEnabled = true;
//Add handlers for MediaPlayer
BackgroundMediaPlayer.MessageReceivedFromForeground += MessageReceivedFromForeground;
//Initialize message channel
BackgroundMediaPlayer.Current.CurrentStateChanged += BackgroundMediaPlayerCurrentStateChanged;
// Associate a cancellation and completed handlers with the background task.
taskInstance.Canceled += OnCanceled;
taskInstance.Task.Completed += Taskcompleted;
var value = ApplicationSettingsHelper.ReadResetSettingsValue(Constants.AppState);
if (value == null)
foregroundAppState = ForegroundAppStatus.Unknown;
else
foregroundAppState = (ForegroundAppStatus)Enum.Parse(typeof(ForegroundAppStatus), value.ToString());
//Send information to foreground that background task has been started if app is active
if (foregroundAppState != ForegroundAppStatus.Suspended)
{
ValueSet message = new ValueSet();
message.Add(Constants.BackgroundTaskStarted, "");
BackgroundMediaPlayer.SendMessageToForeground(message);
}
BackgroundTaskStarted.Set();
backgroundtaskrunning = true;
ApplicationSettingsHelper.SaveSettingsValue(Constants.BackgroundTaskState, Constants.BackgroundTaskRunning);
_deferral = taskInstance.GetDeferral();
}
/// <summary>
/// Fires when a message is recieved from the foreground app
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MessageReceivedFromForeground(object sender, MediaPlayerDataReceivedEventArgs e)
{
ValueSet valueSet = e.Data;
foreach (string key in valueSet.Keys)
{
switch (key.ToLower())
{
case Constants.StartPlayback:
Debug.WriteLine("Starting Playback");
Play(valueSet[key].ToString());
break;
}
}
}
private void Play(string toPlay)
{
string[] trackInfo = toPlay.Split('|');
MediaPlayer mediaPlayer = BackgroundMediaPlayer.Current;
mediaPlayer.AutoPlay = true;
mediaPlayer.SetUriSource(new Uri(trackInfo[0]));
//Update the universal volume control
_systemMediaTransportControl.ButtonPressed += MediaTransportControlButtonPressed;
_systemMediaTransportControl.IsPauseEnabled = true;
_systemMediaTransportControl.IsPlayEnabled = true;
_systemMediaTransportControl.DisplayUpdater.Type = MediaPlaybackType.Music;
_systemMediaTransportControl.DisplayUpdater.MusicProperties.Artist = trackInfo[1];
_systemMediaTransportControl.DisplayUpdater.MusicProperties.Title = trackInfo[2];
_systemMediaTransportControl.DisplayUpdater.Update();
}
/// <summary>
/// The MediaPlayer's state changes, update the Universal Volume Control to reflect the correct state.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void BackgroundMediaPlayerCurrentStateChanged(MediaPlayer sender, object args)
{
if (sender.CurrentState == MediaPlayerState.Playing)
{
_systemMediaTransportControl.PlaybackStatus = MediaPlaybackStatus.Playing;
}
else if (sender.CurrentState == MediaPlayerState.Paused)
{
_systemMediaTransportControl.PlaybackStatus = MediaPlaybackStatus.Paused;
}
}
/// <summary>
/// Handle the buttons on the Universal Volume Control
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void MediaTransportControlButtonPressed(SystemMediaTransportControls sender,
SystemMediaTransportControlsButtonPressedEventArgs args)
{
switch (args.Button)
{
case SystemMediaTransportControlsButton.Play:
BackgroundMediaPlayer.Current.Play();
break;
case SystemMediaTransportControlsButton.Pause:
BackgroundMediaPlayer.Current.Pause();
break;
}
}
private void Taskcompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
{
BackgroundMediaPlayer.Shutdown();
_deferral.Complete();
}
/// <summary>
/// Handles background task cancellation. Task cancellation happens due to :
/// 1. Another Media app comes into foreground and starts playing music
/// 2. Resource pressure. Your task is consuming more CPU and memory than allowed.
/// In either case, save state so that if foreground app resumes it can know where to start.
/// </summary>
private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
try
{
//save state - need to save state for track url, name, artist AND position
ApplicationSettingsHelper.SaveSettingsValue(Constants.BackgroundTaskState, Constants.BackgroundTaskCancelled);
ApplicationSettingsHelper.SaveSettingsValue(Constants.AppState, Enum.GetName(typeof(ForegroundAppStatus), foregroundAppState));
backgroundtaskrunning = false;
BackgroundMediaPlayer.Shutdown(); // shutdown media pipeline
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
_deferral.Complete(); // signals task completion.
Debug.WriteLine("MyBackgroundAudioTask Cancel complete...");
}
}
}
<file_sep>/BackgroundAudioTask/Constants.cs
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BackgroundAudioTask
{
/// <summary>
/// Collection of string constants used in the entire solution. This file is shared for all projects
/// </summary>
class Constants
{
public const string CurrentTrack = "trackname";
public const string BackgroundTaskStarted = "BackgroundTaskStarted";
public const string BackgroundTaskRunning = "BackgroundTaskRunning";
public const string BackgroundTaskCancelled = "BackgroundTaskCancelled";
public const string AppSuspended = "appsuspend";
public const string AppResumed = "appresumed";
public const string StartPlayback = "startplayback";
public const string SkipNext = "skipnext";
public const string Position = "position";
public const string AppState = "appstate";
public const string BackgroundTaskState = "backgroundtaskstate";
public const string SkipPrevious = "skipprevious";
public const string Trackchanged = "songchanged";
public const string ForegroundAppActive = "Active";
public const string ForegroundAppSuspended = "Suspended";
public const string TrackStreamUrl = "trackstreamurl";
public const string TrackTitle = "tracktitle";
public const string TrackArtist = "trackartist";
public const string TrackImage = "trackimage";
}
}
<file_sep>/AppStudio.Shared/Services/SoundCloudService.cs
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved
using System;
using System.Threading.Tasks;
using Windows.System;
using AppStudio.Data.SoundCloud; //Schema
namespace AppStudio.Services
{
static public class SoundCloudMusicService
{
//Get your client key at developers.soundcloud.com
private const string _clientId = "YOUR_KEY_HERE";
public static SoundCloudTrackSchema trackModel { get; private set; }
/// <summary>
/// Used to "Launch" the track in the media player. No background audio.
/// </summary>
/// <param name="trackUrl"></param>
/// <returns></returns>
public static async Task<string> LaunchTrack(string trackUrl)
{
try
{
var serviceProvider = new AppStudio.Data.SoundCloudProvider(_clientId, trackUrl);
SoundCloudTrackSchema track = await serviceProvider.LoadTrack<SoundCloudTrackSchema>();
return string.Format("{0}?client_id={1}", track.stream_url, _clientId);
}
catch (Exception ex)
{
AppLogs.WriteError("SoundCloudMusicService", ex.ToString());
return "";
}
}
/// <summary>
/// Returns the full Track JSON in object format
/// </summary>
/// <param name="trackUrl"></param>
/// <returns></returns>
public static async Task<SoundCloudTrackSchema> GetTrackInfo(string trackUrl)
{
try
{
var serviceProvider = new AppStudio.Data.SoundCloudProvider(_clientId, trackUrl);
return await serviceProvider.LoadTrack<SoundCloudTrackSchema>();
}
catch (Exception ex)
{
AppLogs.WriteError("SoundCloudMusicService", ex.ToString());
return null;
}
}
/// <summary>
/// Returns the streaming url with the auth in the request
/// </summary>
/// <param name="streamUrl"></param>
/// <returns></returns>
public static String AuthUrl(string streamUrl)
{
return string.Format("{0}?client_id={1}", streamUrl, _clientId);
}
}
}
<file_sep>/AppStudio.Data/DataSchemas/TracksSchema.cs
using System;
using System.Collections;
using Newtonsoft.Json;
namespace AppStudio.Data
{
/// <summary>
/// Implementation of the TracksSchema class.
/// </summary>
public class TracksSchema : BindableSchemaBase, IEquatable<TracksSchema>, ISyncItem<TracksSchema>
{
private string _trackTitle;
private string _trackUrl;
private string _image;
[JsonProperty("_id")]
public string Id { get; set; }
public string TrackTitle
{
get { return _trackTitle; }
set { SetProperty(ref _trackTitle, value); }
}
public string TrackUrl
{
get { return _trackUrl; }
set { SetProperty(ref _trackUrl, value); }
}
public string Image
{
get { return _image; }
set { SetProperty(ref _image, value); }
}
public override string DefaultTitle
{
get { return TrackTitle; }
}
public override string DefaultSummary
{
get { return null; }
}
public override string DefaultImageUrl
{
get { return Image; }
}
public override string DefaultContent
{
get { return null; }
}
override public string GetValue(string fieldName)
{
if (!String.IsNullOrEmpty(fieldName))
{
switch (fieldName.ToLowerInvariant())
{
case "tracktitle":
return String.Format("{0}", TrackTitle);
case "trackurl":
return String.Format("{0}", TrackUrl);
case "image":
return String.Format("{0}", Image);
case "defaulttitle":
return DefaultTitle;
case "defaultsummary":
return DefaultSummary;
case "defaultimageurl":
return DefaultImageUrl;
default:
break;
}
}
return String.Empty;
}
public bool Equals(TracksSchema other)
{
if (ReferenceEquals(this, other)) return true;
if (ReferenceEquals(null, other)) return false;
return this.Id == other.Id;
}
public bool NeedSync(TracksSchema other)
{
return this.Id == other.Id && (this.TrackTitle != other.TrackTitle || this.TrackUrl != other.TrackUrl || this.Image != other.Image);
}
public void Sync(TracksSchema other)
{
this.TrackTitle = other.TrackTitle;
this.TrackUrl = other.TrackUrl;
this.Image = other.Image;
}
public override bool Equals(object obj)
{
return Equals(obj as TracksSchema);
}
public override int GetHashCode()
{
return this.Id.GetHashCode();
}
}
}
<file_sep>/AppStudio.Data/DataSources/TracksDataSource.cs
using System;
using System.Windows;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace AppStudio.Data
{
public class TracksDataSource : DataSourceBase<TracksSchema>
{
private const string _appId = "a2a8169b-40e2-41c0-b95b-aaca3fda8123";
private const string _dataSourceName = "c8c710b7-ea9f-4781-aa0d-25af84e19bb9";
protected override string CacheKey
{
get { return "TracksDataSource"; }
}
public override bool HasStaticData
{
get { return false; }
}
public async override Task<IEnumerable<TracksSchema>> LoadDataAsync()
{
try
{
var serviceDataProvider = new ServiceDataProvider(_appId, _dataSourceName);
return await serviceDataProvider.Load<TracksSchema>();
}
catch (Exception ex)
{
AppLogs.WriteError("TracksDataSource.LoadData", ex.ToString());
return new TracksSchema[0];
}
}
}
}
<file_sep>/AppStudio.Shared/ViewModels/AboutViewModel.cs
using System;
using System.Windows;
using System.Windows.Input;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using AppStudio.Services;
using AppStudio.Data;
namespace AppStudio.ViewModels
{
public class AboutViewModel : ViewModelBase<HtmlSchema>
{
private RelayCommandEx<HtmlSchema> itemClickCommand;
public RelayCommandEx<HtmlSchema> ItemClickCommand
{
get
{
if (itemClickCommand == null)
{
itemClickCommand = new RelayCommandEx<HtmlSchema>(
(item) =>
{
NavigationServices.NavigateToPage("", item);
});
}
return itemClickCommand;
}
}
override protected DataSourceBase<HtmlSchema> CreateDataSource()
{
return new AboutDataSource(); // HtmlDataSource
}
override public ViewTypes ViewType
{
get { return ViewTypes.Detail; }
}
public RelayCommandEx<Slider> IncreaseSlider
{
get
{
return new RelayCommandEx<Slider>(s => s.Value++);
}
}
public RelayCommandEx<Slider> DecreaseSlider
{
get
{
return new RelayCommandEx<Slider>(s => s.Value--);
}
}
}
}
<file_sep>/AppStudio.Data/DataProviders/SoundCloudProvider.cs
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.ObjectModel;
namespace AppStudio.Data
{
public class SoundCloudProvider
{
//Endpoint to RESOLVE a track id or playlist id
const string RESOLVE_URL_ENDPOINT = "http://api.soundcloud.com/resolve.json?url={0}&client_id={1}";
private Uri _uri;
public SoundCloudProvider(string clientId, string resolveUrl)
{
string url = String.Format(RESOLVE_URL_ENDPOINT, resolveUrl, clientId);
_uri = new Uri(url);
}
public async Task<T> LoadTrack<T>()
{
try
{
string data = await DownloadAsync(_uri);
return JsonConvert.DeserializeObject<T>(data);
}
catch (Exception ex)
{
AppLogs.WriteError("SoundCloudProvider.LoadTrack", ex);
return default(T);
}
}
public async Task<string> DownloadAsync(Uri url)
{
HttpClient client = new HttpClient();
var message = new HttpRequestMessage(HttpMethod.Get, url);
using (var response = await client.SendAsync(message))
{
return await response.Content.ReadAsStringAsync();
}
}
}
}
<file_sep>/README.md
# AppStudio SoundCloudAPI
Integration of the SoundCloud API into a Windows Phone App Studio Project
## Installation
Clone or download this repository and use replace your wp-config.php.
## Usage
You can follow the step by step instructions here - More info can be found @ http://drew5.net/code/windows-phone-app-studio-soundcloud-music-apps/
## History
None at this time
## Credits
<NAME>
Sr Technical Evangelist - Microsoft
@jdruid
Drew5.net
## License
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses
## DISCLAIMER:
The sample code described herein is provided on an "as is" basis, without warranty of any kind, to the fullest extent permitted by law. Both Microsoft and I do not warrant or guarantee the individual success developers may have in implementing the sample code on their development platforms or in using their own Web server configurations.
Microsoft and I do not warrant, guarantee or make any representations regarding the use, results of use, accuracy, timeliness or completeness of any data or information relating to the sample code. Microsoft and I disclaim all warranties, express or implied, and in particular, disclaims all warranties of merchantability, fitness for a particular purpose, and warranties related to the code, or any service or software related thereto.
Microsoft and I shall not be liable for any direct, indirect or consequential damages or costs of any type arising out of any action taken by you or others related to the sample code.
<file_sep>/AppStudio.WindowsPhone/Views/MusicPlayer.xaml.cs
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Diagnostics;
using Windows.UI.Core;
using Windows.Media.Playback;
using BackgroundAudioTask;
using Windows.ApplicationModel.DataTransfer; //DataTransferManager
using AppStudio.ViewModels;//TracksViewModel
using AppStudio.Services; //SoundCloudService
using AppStudio.Data.SoundCloud; //Schema
namespace AppStudio.Views
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MusicPlayer : Page
{
//standard app studio
private NavigationHelper _navigationHelper;
private DataTransferManager _dataTransferManager;
public NavigationHelper NavigationHelper
{
get { return _navigationHelper; }
}
public TracksViewModel TracksModel { get; private set; }
/// <summary>
/// Storage of current flip index
/// </summary>
public int FlipSelectedItem { get; set; }
/// <summary>
/// Gets the information about background task is running or not by reading the setting saved by background task
/// </summary>
private bool isBackgroundTaskRunning = false;
/// <summary>
/// Gets the information about background task is running or not by reading the setting saved by background task
/// </summary>
private bool IsBackgroundTaskRunning
{
get
{
if (isBackgroundTaskRunning)
return true;
object value = ApplicationSettingsHelper.ReadResetSettingsValue(Constants.BackgroundTaskState);
if (value == null)
{
return false;
}
else
{
isBackgroundTaskRunning = ((String)value).Equals(Constants.BackgroundTaskRunning);
return isBackgroundTaskRunning;
}
}
}
public MusicPlayer()
{
this.InitializeComponent();
_navigationHelper = new NavigationHelper(this);
TracksModel = new TracksViewModel();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
_dataTransferManager = DataTransferManager.GetForCurrentView();
_dataTransferManager.DataRequested += OnDataRequested;
_navigationHelper.OnNavigatedTo(e);
if (TracksModel != null)
{
await TracksModel.LoadItemsAsync();
if (e.NavigationMode != NavigationMode.Back)
{
TracksModel.SelectItem(e.Parameter);
}
TracksModel.ViewType = ViewTypes.Detail;
}
FlipSelectedItem = Flip.SelectedIndex;
DataContext = this;
//Adding App suspension handlers here so that we can unsubscribe handlers
//that access to BackgroundMediaPlayer events
App.Current.Suspending += ForegroundApp_Suspending;
App.Current.Resuming += ForegroundApp_Resuming;
ApplicationSettingsHelper.SaveSettingsValue(Constants.AppState, Constants.ForegroundAppActive);
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
_navigationHelper.OnNavigatedFrom(e);
_dataTransferManager.DataRequested -= OnDataRequested;
}
private void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
}
#region Foreground App Lifecycle Handlers
/// <summary>
/// Sends message to background informing app has resumed
/// Subscribe to MediaPlayer events
/// </summary>
void ForegroundApp_Resuming(object sender, object e)
{
ApplicationSettingsHelper.SaveSettingsValue(Constants.AppState, Constants.ForegroundAppActive);
// Verify if the task was running before
if (IsBackgroundTaskRunning)
{
//if yes, reconnect to media play handlers
AddMediaPlayerEventHandlers();
//send message to background task that app is resumed, so it can start sending notifications
ValueSet messageDictionary = new ValueSet();
messageDictionary.Add(Constants.AppResumed, DateTime.Now.ToString());
BackgroundMediaPlayer.SendMessageToBackground(messageDictionary);
if (BackgroundMediaPlayer.Current.CurrentState == MediaPlayerState.Playing)
{
AppBarPlayButton.Icon = new SymbolIcon(Symbol.Pause); // Change to pause button
}
else
{
AppBarPlayButton.Icon = new SymbolIcon(Symbol.Play); // Change to play button
}
}
else
{
AppBarPlayButton.Icon = new SymbolIcon(Symbol.Play); // Change to play button
}
}
/// <summary>
/// Send message to Background process that app is to be suspended
/// Stop clock and slider when suspending
/// Unsubscribe handlers for MediaPlayer events
/// </summary>
void ForegroundApp_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
ValueSet messageDictionary = new ValueSet();
messageDictionary.Add(Constants.AppSuspended, DateTime.Now.ToString());
BackgroundMediaPlayer.SendMessageToBackground(messageDictionary);
RemoveMediaPlayerEventHandlers();
ApplicationSettingsHelper.SaveSettingsValue(Constants.AppState, Constants.ForegroundAppSuspended);
deferral.Complete();
}
#endregion
#region UI Click event handlers
private void PlayButton_Click(object sender, RoutedEventArgs e)
{
System.Diagnostics.Debug.WriteLine("Play button pressed from App");
if (IsBackgroundTaskRunning)
{
if (MediaPlayerState.Playing == BackgroundMediaPlayer.Current.CurrentState)
{
//Audio is playing..need to Pause
BackgroundMediaPlayer.Current.Pause();
}
else if (MediaPlayerState.Paused == BackgroundMediaPlayer.Current.CurrentState)
{
//Audio is paused so start playing
BackgroundMediaPlayer.Current.Play();
}
else if (MediaPlayerState.Closed == BackgroundMediaPlayer.Current.CurrentState)
{
//No audio playing
StartBackgroundAudio();
}
}
else
{
StartBackgroundAudio();
}
}
/// <summary>
/// Restarts the media from the beginning
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RefreshButton_Click(object sender, RoutedEventArgs e)
{
if (IsBackgroundTaskRunning)
{
RefreshBackgroundAudio();
}
}
private void PrevButton_Click(object sender, RoutedEventArgs e)
{
if (Flip.SelectedIndex > 0)
{
Flip.SelectedIndex = FlipSelectedItem - 1;
}
}
private void NextButton_Click(object sender, RoutedEventArgs e)
{
if (Flip.Items.Count-1 > FlipSelectedItem)
{
Flip.SelectedIndex = FlipSelectedItem + 1;
}
}
#endregion
private void Flip_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//start new media
FlipSelectedItem = Flip.SelectedIndex;
//enable or disable buttons
if (Flip.Items.Count-1 < FlipSelectedItem) AppBarNextButton.IsEnabled = false; else AppBarNextButton.IsEnabled = true;
if (Flip.SelectedIndex == 0) AppBarPrevButton.IsEnabled = false; else AppBarPrevButton.IsEnabled = true;
//Play new media
StartBackgroundAudio();
}
private async void StartBackgroundAudio()
{
SoundCloudTrackSchema trackSchema = await SoundCloudMusicService.GetTrackInfo(TracksModel.SelectedItem.TrackUrl.ToString());
ValueSet message = new ValueSet();
message.Add(Constants.StartPlayback, String.Format("{0}|{1}|{2}",
SoundCloudMusicService.AuthUrl(trackSchema.stream_url),
trackSchema.user.username,
trackSchema.title));
AddMediaPlayerEventHandlers();
BackgroundMediaPlayer.SendMessageToBackground(message);
}
//private void StopBackgroundAudio()
//{
// AppBarPlayButton.Icon = new SymbolIcon(Symbol.Play);
//}
private void RefreshBackgroundAudio()
{
StartBackgroundAudio();
}
#region Media Playback Helper methods
/// <summary>
/// Unsubscribes to MediaPlayer events. Should run only on suspend
/// </summary>
private void RemoveMediaPlayerEventHandlers()
{
BackgroundMediaPlayer.Current.CurrentStateChanged -= this.MediaPlayer_CurrentStateChanged;
BackgroundMediaPlayer.MessageReceivedFromBackground -= this.BackgroundMediaPlayer_MessageReceivedFromBackground;
}
/// <summary>
/// Subscribes to MediaPlayer events
/// </summary>
private void AddMediaPlayerEventHandlers()
{
BackgroundMediaPlayer.Current.CurrentStateChanged += this.MediaPlayer_CurrentStateChanged;
BackgroundMediaPlayer.MessageReceivedFromBackground += this.BackgroundMediaPlayer_MessageReceivedFromBackground;
}
/// <summary>
/// MediaPlayer state changed event handlers.
/// Note that we can subscribe to events even if Media Player is playing media in background
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
async void MediaPlayer_CurrentStateChanged(MediaPlayer sender, object args)
{
switch (sender.CurrentState)
{
case MediaPlayerState.Playing:
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
AppBarPlayButton.Icon = new SymbolIcon(Symbol.Pause);
}
);
break;
case MediaPlayerState.Paused:
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
AppBarPlayButton.Icon = new SymbolIcon(Symbol.Play); // Change to play button
}
);
break;
}
}
/// <summary>
/// This event fired when a message is recieved from Background Process
/// </summary>
async void BackgroundMediaPlayer_MessageReceivedFromBackground(object sender, MediaPlayerDataReceivedEventArgs e)
{
foreach (string key in e.Data.Keys)
{
switch (key)
{
case Constants.Trackchanged:
//When foreground app is active change track based on background message
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
//To Do: Possible swap out image
}
);
break;
case Constants.BackgroundTaskStarted:
//Wait for Background Task to be initialized before starting playback
Debug.WriteLine("Background Task started");
//To Do: Handle anything before playback
break;
}
}
}
#endregion
}
}
<file_sep>/BackgroundAudioTask/ApplicationSettingsHelper.cs
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Windows.Storage;
namespace BackgroundAudioTask
{
/// <summary>
/// Collection of string constants used in the entire solution. This file is shared for all projects
/// </summary>
static class ApplicationSettingsHelper
{
/// <summary>
/// Function to read a setting value and clear it after reading it
/// </summary>
public static object ReadResetSettingsValue(string key)
{
Debug.WriteLine(key);
if (!ApplicationData.Current.LocalSettings.Values.ContainsKey(key))
{
Debug.WriteLine("null returned");
return null;
}
else
{
var value = ApplicationData.Current.LocalSettings.Values[key];
ApplicationData.Current.LocalSettings.Values.Remove(key);
Debug.WriteLine("value found " + value.ToString());
return value;
}
}
/// <summary>
/// Save a key value pair in settings. Create if it doesn't exist
/// </summary>
public static void SaveSettingsValue(string key, object value)
{
Debug.WriteLine(key + ":" + value.ToString());
if (!ApplicationData.Current.LocalSettings.Values.ContainsKey(key))
{
ApplicationData.Current.LocalSettings.Values.Add(key, value);
}
else
{
ApplicationData.Current.LocalSettings.Values[key] = value;
}
}
}
}
<file_sep>/AppStudio.Shared/ViewModels/TracksViewModel.cs
using System;
using System.Windows;
using System.Windows.Input;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using AppStudio.Services;
using AppStudio.Data;
namespace AppStudio.ViewModels
{
public class TracksViewModel : ViewModelBase<TracksSchema>
{
private RelayCommandEx<TracksSchema> itemClickCommand;
/// <summary>
/// NOTE: We are changing the "navigate" page to go to the new page MusicPlayer to work with the Windows PHone 8.1 BackgroundAudio task. This will not
/// work with Windows 8.1 Store apps. Please comment and put back prior line. Fix for Windows 8.1 is coming in the future.
/// </summary>
public RelayCommandEx<TracksSchema> ItemClickCommand
{
get
{
if (itemClickCommand == null)
{
itemClickCommand = new RelayCommandEx<TracksSchema>(
(item) =>
{
//NavigationServices.NavigateToPage("TracksDetail", item);
NavigationServices.NavigateToPage("MusicPlayer", item);
});
}
return itemClickCommand;
}
}
override protected DataSourceBase<TracksSchema> CreateDataSource()
{
return new TracksDataSource(); // CollectionDataSource
}
override public Visibility RefreshVisibility
{
get { return ViewType == ViewTypes.List ? Visibility.Visible : Visibility.Collapsed; }
}
public RelayCommandEx<Slider> IncreaseSlider
{
get
{
return new RelayCommandEx<Slider>(s => s.Value++);
}
}
public RelayCommandEx<Slider> DecreaseSlider
{
get
{
return new RelayCommandEx<Slider>(s => s.Value--);
}
}
override public void NavigateToSectionList()
{
NavigationServices.NavigateToPage("TracksList");
}
override protected void NavigateToSelectedItem()
{
//NavigationServices.NavigateToPage("TracksDetail");
NavigationServices.NavigateToPage("SoundCloudPlayer");
}
}
}
<file_sep>/AppStudio.Shared/Converters/IncreaseConverter.cs
using System;
using System.Collections.Generic;
using System.Text;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;
namespace AppStudio.Controls
{
public class IncreaseConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
int increment = 0;
if (parameter is int)
{
increment = (int)parameter;
}
else if (parameter is string)
{
int.TryParse(parameter as string, out increment);
}
if (value is int)
{
value = (int)value + increment;
}
else if (value is decimal)
{
value = (decimal)value + increment;
}
else if (value is double)
{
value = (double)value + increment;
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
}
|
377d1ea3338996959bf3cc65bd50dd8df6a840ae
|
[
"Markdown",
"C#"
] | 14
|
C#
|
jdruid/AppStudio-SoundCloudAPI
|
7a7dcb30699af687305741cd4ed917927638be5c
|
0fdfde614621cef7487a39da95238ec823406545
|
refs/heads/master
|
<repo_name>carello/cicd-virl<file_sep>/cicd-virl-prep/cleanup.sh
#!/bin/bash
docker-compose down
rm -rf gogs
rm -rf drone
#rm -rf .git
<file_sep>/cicd-virl-prep/tmp-container-builds/virlstart.sh
#!/bin/sh
echo "Starting script...."
#virl ls --all
#virl up -f virl/topology.virl
#virl ls --all
#virl up -f ${VIRL_FILE}
<file_sep>/README.md
# CI/CD using VIRL, DRONE and GOGS
### Overview
This application is a CI/CD case study using Cisco VIRL simulator, DRONE and GOGS. Images are pulled from hub.docker.com. This case study doesn't cover installing or configuring VIRL. There are many ways to set up management access into VIRL. I set up a Shared Flat Network toplogy to allow Ansible access to the virtual devices within VIRL. This can be accomplished through simple routing or using an OpenVPN connection. Documentation can be found at [here](http://virl.cisco.com). This app was developed on MAC OS X.
### Software (prerequisites)
You'll need to following software installed:
* [Docker for Desktop](https://docs.docker.com/docker-for-mac/install/#download-docker-for-mac)
* Git. There are a couple of installation option/choices:
* [Git using Homebrew](https://www.atlassian.com/git/tutorials/install-git)
* [Git software installer](https://git-scm.com/downloads)
* [Drone CLI](https://docs.drone.io/cli/install/)
* [Docker Hub](docker.io) account.
* VIRL is available via subscription or there's free access on Cisco DevNet. However this app was developed on a dedicated VIRL server. I haven't tested this app on the hosted VIRL on Cisco DevNet.
* [VIRL](http://virl.cisco.com)
* [Cisco DeveNet](http://developer.cisco.com)
* [Cisco CICD lab](https://developer.cisco.com/learning/modules/netcicd)
## How to Use
### Section 1: Bootstrapping
* Open a terminal:
* clone this repo
* `cd cicd-virl`
* `cd cicd-virl-prep`
* Enter `source ./drone-env.sh` to load environmental variables.
* Enter `./startup.sh` to start up Drone and Gogs
### Section 2: Set up GOGS
- Open a browser to `http://localhost:3000` (port 3000 is defined in the yaml file).
* Use SQLite3
* Set the Domain to: `dc-gogs`
* SSH port: clear this field (blank).
* Set 'Application URL' to: dc-gogs and port 3000 . ie,` http://dc-gogs:3000`
* Create an admin user
* Hit submit. Note that the browser might not refresh. Just open another browser to `http://localhost:3000` , login and create a repo called: `network_cicd_lab`. You must name this exactly as indicated.
- Open another terminail window and navigate into your cloned repo `cicd-virl`
* `cd cicd-virl-data`
* `cd network_cicd_lab`
* Enter the following commands:
* `git init`
* `git add .`
* `git commit -m "first commit"`
* `git remote add origin http://localhost:3000/<repo-name>/network_cicd_lab.git`
* `git push -u origin master`
* `git branch dev`
* `git checkout dev`
* `git push -u origin dev`
* Check your GOGS repo, you should now have two branches: master and dev
### Section 3: Set up Webex Teams (Optional)
- In a new broswer window, go to: `https://developer.webex.com` and login. (If you don't have an account, sign up for a free account).
- Click on your avatar in the upper right corner and select "My Webex Teams Apps"
- Click "Create a New App"
- Click "Create a Bot"
- Create your bot with the following information:
* Name: CICD BOT
* Bot Username: Enter any avaiable name, (indicated in green when you enter a name).
* Icon: Select a default choice
* Description: CICD-VIRL Bot
* Click: "Add Bot"
* A new screen will appear. Click the button to copy the "Bot's Access Token"
* We will need the Bot's Access Token in the next section; save it somewhere temporarily.
### Section 4: Set up Drone
- Open another browser to `http://localhost`and enter your user info you created earlier in the Gogs setup. Wait for DRONE to sync. __Do not activate the repo yet__.
- We need to grab a few Drone environmental variables. Go to `User Settings` (upper right ICON) and copy the DRONE\_SERVER and DRONE\_TOKEN variables. It looks something like this:
export DRONE_SERVER=http://localhost
export DRONE_TOKEN=<KEY>
- Go back to your open terminal and paste these in. Run `drone info` to check if things are working.
- We'll need to setup several secret keys next. We'll use the DRONE GUI to set up the keys but this can also be accomplished using CLI. The keys we'll be configuring are:
* VIRL_HOST="VIRL IP Address"
* VIRL_USERNAME=guest (NOTE: this is the default username in VIRL)
* VIRL_PASSWORD=<PASSWORD> (NOTE: this is the default password in VIRL)
* GOGS_USER="Account name you used to set up GOGs earlier"
* GOGS_PASS="<PASSWORD> up GOGs earlier"
* DOCKER_USERNAME="Your Docker Hub username"
* DOCKER_PASSWORD="<PASSWORD>"
* SPARK_TOKEN="Access Token you copied from Section 3 above)
* PERSONEMAIL="Email address from you Webex Teams account"
- Select `Activate` repository in Drone
* Check the `Trusted` in the Project Settings. (Don't hit SAVE yet)
* Scroll down to the Secrets section and enter the keys. For example enter:
* `VIRL_HOST` in the Secret Name field
* `[IP Address of the VIRL host]` in the Secret Value field.
* Click: Add a Secret
* Repeat these setps for all the keys mentioned above
* Select SAVE when done entering all the keys
* Select Repositories (located on the top of the page) to bring you back to your repo
- Go to your Gogs browser and into your repo, (you should already at this location).
* On the right hand side select the `settings` link.
* On the left hand side, select the tab for `webhooks`.
* You should then see a link in the center of the page for `http://dc-drone-server/hook`, select it, and scroll towards the bottom of the page; there is a button for `Test Delivery`. If things are correct you should make a successful connection, (scroll down the page to see the result).
### Section 5: CI/CD in Action
- Go back to your 2nd terminal window. You should be in the `network_cicd_lab` directory.
- Enter `git branch -a` to verify which branch you are currently in.
- Enter `git checkout dev` to switch to the dev branch.
- We need to make a change to kick off the workflow. A simple way to do this is create a empty file. Enter the following commands:
* `touch dummy.txt`
* `git add .`
* `git commit -m "2nd commit on DEV"` (or whatever message you'd like)
* `git push`
- Go back to the Drone browser and watch your workflow execute. It will take about 3-4 mins to complete.
### Section 6: Cleanup
- Go back to your 1st terminal window. You should be in the `cics-virl-prep` directory.
- enter: `./cleanup.sh`
### To Do
- Create a robust/flexible app within the drone plugins and not rely on 'commands' within the .drone.yml file. This would allow for more flexible use cases in the future.
- Webex BOT isn't working accurately due to drone plugin compatibility.
<file_sep>/cicd-virl-prep/tmp-container-builds/Dockerfile
FROM carello/virlutils:v1
COPY . /app
WORKDIR /app
RUN chmod +x /app/virlstart.sh
#CMD [ "/bin/sh", "-c", "./virlstart.sh" ]
#ENTRYPOINT [ "/bin/sh", "virl up -f topology.virl" ]
#CMD [ "/bin/sh", "-c", "virl up -f topology.virl" ]
ENTRYPOINT /app/virlstart.sh
<file_sep>/cicd-virl-data/network_cicd_lab/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
config.vm.box = "iosxe/16.06.02"
config.vm.network :private_network, virtualbox__intnet: "link1", auto_config: false
config.vm.network :private_network, virtualbox__intnet: "link2", auto_config: false
end
<file_sep>/cicd-virl-prep/README.md
### Refer to the main README.md file in the `cicd-virl` main directory
|
544126adc9a44fca35815ef1fa154e11c8bea9d9
|
[
"Markdown",
"Ruby",
"Dockerfile",
"Shell"
] | 6
|
Shell
|
carello/cicd-virl
|
4e368340b9e9103e9cc051bd52f3e8c70a0c4bd2
|
88cee1e5d1d1ca193d1155f8ab15af2dd8586683
|
refs/heads/master
|
<file_sep>-- MySQL dump 10.13 Distrib 5.5.57, for debian-linux-gnu (x86_64)
--
-- Host: 0.0.0.0 Database: mvc
-- ------------------------------------------------------
-- Server version 5.5.57-0ubuntu0.14.04.1
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `category`
--
DROP TABLE IF EXISTS `category`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `category` (
`id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `category`
--
LOCK TABLES `category` WRITE;
/*!40000 ALTER TABLE `category` DISABLE KEYS */;
INSERT INTO `category` VALUES (1,'Home'),(2,'Shoes'),(3,'Books'),(5,'Outdoors'),(7,'Games'),(9,'Jewelery'),(12,'Health'),(13,'Grocery'),(14,'Tools'),(15,'Movies'),(16,'Computers'),(18,'Automotive'),(19,'Sports'),(20,'Beauty'),(21,'Other'),(22,'Health');
/*!40000 ALTER TABLE `category` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2017-11-07 18:56:46
<file_sep><?php
class Vehicle
{
protected $price;
public $state = 'static';
public function __construct($price)
{
$this->setPrice($price);
}
public function drive()
{
$this->state = 'moving';
}
public function stop()
{
if ($this->isMoving()) {
echo 'You are not moving!';
} else {
$this->state = 'static';
}
}
public function isMoving()
{
return $this->state != 'moving';
}
public function setPrice($price)
{
if (!is_numeric($price)) {
die('Invalid price');
}
$this->price = round($price, 2);
return $this;
}
public function getPrice()
{
return $this->price;
}
public function getFormattedPrice($price){
return number_format($price,2, ".","");
}
}<file_sep><?php
spl_autoload_register(function($className) {
$file = "{$className}.php";
$file = str_replace(
'\\',
DIRECTORY_SEPARATOR,
$file
);
if (!file_exists($file)) {
die("{$file} not found");
}
require_once $file;
});
function printName(Figure $figure)
{
echo $figure->getName() . '<br>';
}
$figureNames = ['Circle', 'Triangle', 'Rectangle'];
$length = count($figureNames);
$figures = [];
for ($i = 1; $i <= 10; $i++) {
$index = rand(0, $length - 1);
$figure = $figureNames[$index];
$figure = new $figure();
$figures[] = $figure;
}
foreach ($figures as $figure) {
printName($figure);
}
$in = new Car("bmw", "x6", "159.333");
print_r($in->toArray());
// var_dump($figures);
// $className = 'Car';
// $vehicle = new Vehicle(1000);
// $vehicle->stop();
// var_dump($vehicle);
// $car = new Car('a', 'b',90876);
// // $car->setPrice(10230);
// $car->stop();
// var_dump($car);
// echo $car;
// new Circle();
// $car2 = new Car('BMW', 'E92');
// echo $car1;
// var_dump($car1, $car2);<file_sep><?php
abstract class Figure
{
abstract public function getName();
}<file_sep><?php
class Rectangle extends Figure
{
public function getName()
{
return 'Rectangle';
}
}<file_sep><?php
namespace One;
class Car
{
public $brand;
public $model;
private $price;
private $state = 'static';
public function __construct($brand, $model)
{
echo 'This is class car 1';
$this->brand = $brand;
$this->model = $model;
}
public function __destruct()
{
echo 'destroyed';
}
public function __toString()
{
return $this->brand . ' ' . $this->model;
}
// function test()
// {
// var_dump($this);
// }
public function drive()
{
$this->state = 'moving';
$waste = new \Nuclear\Waste();
}
public function stop()
{
if ($this->isMoving()) {
echo 'You are not moving!';
} else {
$this->state = 'static';
}
}
public function isMoving()
{
return $this->state != 'moving';
}
public function setPrice($price)
{
if (!is_numeric($price)) {
die('Invalid price');
}
$this->price = $price;
return $this;
}
public function getPrice()
{
return $this->price;
}
public function toArray()
{
$a = [$this->brand, $this->model];
return $a;
}
}<file_sep><?php
class Car extends Vehicle
{
public $brand;
public $model;
public function __construct($brand, $model, $price)
{
$this->brand = $brand;
$this->model = $model;
parent::__construct($price);
}
public function stop()
{
if ($this->isMoving()) {
echo 'Car is not moving!';
} else {
$this->state = 'static';
}
}
public function __toString()
{
return $this->price . ' ' . $this->model;
}
public function toArray()
{
$a = [$this->brand, $this->model, $this->price];
return $a;
}
}<file_sep><?php
session_start();
var_dump($_SESSION);
echo session_save_path();
// $_SESSION['first_session_value'] = 'Hello session';
$_SESSION['arr'] = ['one' => 'einz', 'two' => 'zwei'];
// PHPSESSID
// u3eag8f15dhl2rqvn1a1m55ef2
// first_session_value|s:13:"Hello session";
// first_session_value|s:13:"Hello session";arr|a:2:{s:3:"one";s:4:"einz";s:3:"two";s:4:"zwei";}
// $time = time() + 30 * 60;
// // setcookie('test', 123);
// setcookie('test3', 256, time() - 1);
// setcookie('test4', 512, time()+100000000000, '/form');
// var_dump($_COOKIE);
<file_sep><?php
class Circle extends Figure
{
public function getName()
{
return 'Circle';
}
}<file_sep><?php
class Triangle extends Figure
{
public function getName()
{
return 'Triangle';
}
}<file_sep><?php
namespace Nuclear;
class Waste
{
}
|
55909522785572381cf7530acf4e484d40ae071b
|
[
"SQL",
"PHP"
] | 11
|
SQL
|
Pashkalab/PHPAcedemy4
|
32ec0878a5862035ec7bea0308cb0dddf2bc4105
|
f292c930b649081b5d61d9e552cc76d70ba3c259
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using mshtml;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Drawing;
namespace RankHelper
{
public class Qihu : WebBase
{
public Qihu(WebForm webForm, string strSiteUrl, string strhtml):base(webForm, strSiteUrl, strhtml)
{
nPos_x = 30;
nPos_y = 80;
webForm.webBrowser_new.Navigate("www.so.com");
}
public override void webBrowser_DocumentCompleted_Search(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (e.Url.ToString().Contains("so"))
{
webForm.currentTask.webState = EWebbrowserState.none;
webForm.textBox_url.Text = e.Url.ToString();
HtmlElement ele_search;
if (webForm.currentTask.webBrowser == eWebBrowser.IE || webForm.currentTask.webBrowser == eWebBrowser.Chrome || webForm.currentTask.webBrowser == eWebBrowser.Qihu || webForm.currentTask.webBrowser == eWebBrowser.Sogou || webForm.currentTask.webBrowser == eWebBrowser.QQ || webForm.currentTask.webBrowser == eWebBrowser.maxthon || webForm.currentTask.webBrowser == eWebBrowser.theworld)
{
ele_search = webForm.webBrowser_new.Document.GetElementById("input");
}
else//移动端
{
ele_search = webForm.webBrowser_new.Document.GetElementById("input");
}
if (ele_search == null)
{
webForm.currentTask.webState = EWebbrowserState.Search;
webForm.webBrowser_new.Refresh();
return;
}
Point point_search = GetPoint(ele_search);
webForm.webBrowser_new.Document.Window.ScrollTo(0, point_search.Y);
int top = webForm.webBrowser_new.Document.GetElementsByTagName("HTML")[0].ScrollTop;//滚动条垂直位置
KeyUtils.SetCursorPos(point_search.X + nPos_x, point_search.Y + nPos_y - top);
KeyUtils.MouseLBUTTON();
this.taskIntervalTimer.Start();
KeyUtils.Copy(webForm.currentTask.strKeyword);
Sleep(3000);
HtmlElement ele_submit;
if (webForm.currentTask.webBrowser == eWebBrowser.IE || webForm.currentTask.webBrowser == eWebBrowser.Chrome || webForm.currentTask.webBrowser == eWebBrowser.Qihu || webForm.currentTask.webBrowser == eWebBrowser.Sogou || webForm.currentTask.webBrowser == eWebBrowser.QQ || webForm.currentTask.webBrowser == eWebBrowser.maxthon || webForm.currentTask.webBrowser == eWebBrowser.theworld)
{
ele_submit = webForm.webBrowser_new.Document.GetElementById("search-button");
}
else
{
ele_submit = webForm.webBrowser_new.Document.GetElementById("search-button");
}
if (ele_submit == null)
{
webForm.currentTask.webState = EWebbrowserState.Search;
webForm.webBrowser_new.Refresh();
return;
}
Point point_submit = GetPoint(ele_submit);
webForm.webBrowser_new.Document.Window.ScrollTo(0, point_submit.Y);
int top2 = webForm.webBrowser_new.Document.GetElementsByTagName("HTML")[0].ScrollTop;//滚动条垂直位置
KeyUtils.SetCursorPos(point_submit.X + nPos_x, point_submit.Y + nPos_y - top2);
KeyUtils.MouseLBUTTON();
this.taskIntervalTimer.Start();
if (webForm.currentTask == null)
{
return;
}
webForm.currentTask.webState = EWebbrowserState.Search;
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("开始搜索关键词,任务{0}", webForm.currentTask.nID) });
}
}
public override void webBrowser_DocumentCompleted_SearchSite(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//if (e.Url.ToString().Equals("http://www.so.com/") || e.Url.ToString().Equals("https://www.so.com/"))
if (!e.Url.ToString().Contains("www.so.com/s?ie=utf-8&fr=none&src=360sou_newhome&q=")&&
!e.Url.ToString().Contains("www.so.com/s?q="))
{
return;
}
nItem = 0;
if (e.Url.ToString().Contains("so"))
{
webForm.currentTask.webState = EWebbrowserState.none;
webForm.textBox_url.Text = e.Url.ToString();
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("开始查找网站,当前页码{0},任务{1}", nPageIndex, webForm.currentTask.nID) });
Sleep(3000);
//List<tagSearchResult> listSearch = new List<tagSearchResult>();
//搜索项目
//HtmlElement ele_search;
HtmlElementCollection eleCol = webForm.webBrowser_new.Document.GetElementsByTagName("li");
if (eleCol != null)
{
for (int i = 0; i < eleCol.Count; i++)//1~10项
{
if (eleCol[i].GetAttribute("className") ==null)
{
continue;
}
if (eleCol[i].GetAttribute("className") == "res-list")
{
nItem++;
if (!webForm.currentTask.strTitle.Trim().Equals("") && !webForm.currentTask.strSiteUrl.Trim().Equals(""))
{
if (eleCol[i].InnerText.Contains(webForm.currentTask.strTitle) || eleCol[i].InnerText.Contains(webForm.currentTask.strSiteUrl))
{
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("查找到符合的网站,当前页码{0},任务{1}", nPageIndex, webForm.currentTask.nID) });
webForm.currentTask.webState = EWebbrowserState.AccessSite;
webForm.webBrowser_new.Document.Window.ScrollTo(0, 10000);
Sleep(3000);
Point point_ele = GetPoint(eleCol[i]);
int nPos_y = 60;
webForm.webBrowser_new.Document.Window.ScrollTo(0, point_ele.Y - nPos_y);
int top2 = webForm.webBrowser_new.Document.GetElementsByTagName("HTML")[0].ScrollTop;//滚动条垂直位置
//KeyUtils.SetCursorPos(point_ele.X + nPos_x - 900, point_ele.Y + nPos_y - top2);
KeyUtils.SetCursorPos(point_ele.X + nPos_x, point_ele.Y + nPos_y - top2);
Sleep(3000);
webForm.currentTask.webState = EWebbrowserState.AccessSite;
KeyUtils.MouseLBUTTON();
this.taskIntervalTimer.Start();
return;
}
}
else if (!webForm.currentTask.strTitle.Trim().Equals(""))
{
if (eleCol[i].InnerText.Contains(webForm.currentTask.strTitle))
{
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("查找到符合的网站,当前页码{0},任务{1}", nPageIndex, webForm.currentTask.nID) });
webForm.currentTask.webState = EWebbrowserState.AccessSite;
webForm.webBrowser_new.Document.Window.ScrollTo(0, 10000);
Sleep(3000);
Point point_ele = GetPoint(eleCol[i]);
int nPos_y = 60;
webForm.webBrowser_new.Document.Window.ScrollTo(0, point_ele.Y - nPos_y);
int top2 = webForm.webBrowser_new.Document.GetElementsByTagName("HTML")[0].ScrollTop;//滚动条垂直位置
//KeyUtils.SetCursorPos(point_ele.X + nPos_x - 900, point_ele.Y + nPos_y - top2);
KeyUtils.SetCursorPos(point_ele.X + nPos_x, point_ele.Y + nPos_y - top2);
Sleep(3000);
webForm.currentTask.webState = EWebbrowserState.AccessSite;
KeyUtils.MouseLBUTTON();
this.taskIntervalTimer.Start();
return;
}
}
else if (!webForm.currentTask.strSiteUrl.Trim().Equals(""))
{
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("查找到符合的网站,当前页码{0},任务{1}", nPageIndex, webForm.currentTask.nID) });
webForm.currentTask.webState = EWebbrowserState.AccessSite;
webForm.webBrowser_new.Document.Window.ScrollTo(0, 10000);
Sleep(3000);
Point point_ele = GetPoint(eleCol[i]);
int nPos_y = 60;
webForm.webBrowser_new.Document.Window.ScrollTo(0, point_ele.Y - nPos_y);
int top2 = webForm.webBrowser_new.Document.GetElementsByTagName("HTML")[0].ScrollTop;//滚动条垂直位置
//KeyUtils.SetCursorPos(point_ele.X + nPos_x - 900, point_ele.Y + nPos_y - top2);
KeyUtils.SetCursorPos(point_ele.X + nPos_x, point_ele.Y + nPos_y - top2);
Sleep(3000);
webForm.currentTask.webState = EWebbrowserState.AccessSite;
KeyUtils.MouseLBUTTON();
this.taskIntervalTimer.Start();
return;
}
}
}
//当前搜索页未找到
//if (nItem == -1)
{
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("没有找到符合的网站,开始查找下一页,当前页码{0},任务{1}", nPageIndex, webForm.currentTask.nID) });
GetNextPageurl();
}
}
}
}
public override void webBrowser_DocumentCompleted_AccessSite(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (e.Url.ToString().Equals("http://www.so.com/") || e.Url.ToString().Equals("https://www.so.com/"))
{
return;
}
//if (e.Url.ToString().Contains("so"))
//{
// return;
//}
webForm.textBox_url.Text = e.Url.ToString();
webForm.currentTask.webState = EWebbrowserState.none;
webForm.textBox_url.Text = e.Url.ToString();
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("进入网站,当前页码{0},任务{1}", 1, webForm.currentTask.nID) });
Sleep(5000);
switch (webForm.currentTask.pageAccessType)
{
case ePageAccessType.None:
{
EndTask(true);
}
break;
case ePageAccessType.Rand:
{
HtmlElementCollection aCol = webForm.webBrowser_new.Document.GetElementsByTagName("a");
if (aCol == null || aCol.Count == 0)
{
EndTask(true);
return;
}
Random ra = new Random(unchecked((int)DateTime.Now.Ticks));//保证产生的数字的随机性
int index = ra.Next() % aCol.Count;
index = (index >= aCol.Count) ? aCol.Count - 1 : index;
aCol[index].InvokeMember("click");
//if (aCol[index].GetAttribute("href") == null)
//{
// EndTask(true);
// break;
//}
//else
//{
// webForm.textBox_url.Text = aCol[index].GetAttribute("href");
// webForm.webBrowser_new.Navigate(aCol[index].GetAttribute("href"));
//}
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("访问内页{0}", aCol[index].GetAttribute("href")) });
webForm.currentTask.webState = EWebbrowserState.AccessPage;
this.taskIntervalTimer.Start();
}
break;
case ePageAccessType.Appoint:
{
HtmlElementCollection aCol = webForm.webBrowser_new.Document.GetElementsByTagName("a");
if (aCol == null || aCol.Count == 0)
{
EndTask(true);
return;
}
Random ra = new Random(unchecked((int)DateTime.Now.Ticks));//保证产生的数字的随机性
int index = ra.Next() % aCol.Count;
index = (index >= aCol.Count) ? aCol.Count - 1 : index;
for (int i = 0; i < aCol.Count; i++)
{
if (aCol[i].GetAttribute("href") == null)
{
EndTask(true);
continue;
}
else if (aCol[i].GetAttribute("href") == webForm.currentTask.strPageUrl)
{
aCol[i].InvokeMember("click");
break;
}
}
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("访问内页{0}", webForm.currentTask.strPageUrl) });
webForm.currentTask.webState = EWebbrowserState.AccessPage;
this.taskIntervalTimer.Start();
}
break;
default:
break;
}
}
public override void webBrowser_DocumentCompleted_AccessPage(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webForm.textBox_url.Text = e.Url.ToString();
webForm.currentTask.webState = EWebbrowserState.none;
webForm.textBox_url.Text = e.Url.ToString();
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("访问内页{0}", webForm.currentTask.strPageUrl) });
Sleep(5000);
EndTask(true);
}
public override void GetNextPageurl()
{
HtmlElement ele_page;
ele_page = webForm.webBrowser_new.Document.GetElementById("page");
if (ele_page == null)
{
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("只有一页,结束任务,当前页码{0},任务{1}", nPageIndex, webForm.currentTask.nID) });
EndTask(false);
}
nPageIndex += 1;
HtmlElementCollection eleCol = ele_page.GetElementsByTagName("a");
foreach (HtmlElement element in eleCol)
{
if (element.InnerText == nPageIndex.ToString())
{
webForm.currentTask.webState = EWebbrowserState.SearchSite;
Point point_ele = GetPoint(element);
webForm.webBrowser_new.Document.Window.ScrollTo(0, point_ele.Y);
int top = webForm.webBrowser_new.Document.GetElementsByTagName("HTML")[0].ScrollTop;//滚动条垂直位置
KeyUtils.SetCursorPos(point_ele.X + nPos_x, point_ele.Y + nPos_y - top);
Sleep(3000);
KeyUtils.MouseLBUTTON();
this.taskIntervalTimer.Start();
return;
}
}
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("已经是最后一页,结束任务,当前页码{0},任务{1}", nPageIndex, webForm.currentTask.nID) });
Sleep(5000);
EndTask(false);
}
}
}
<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;
using log4net;
using mshtml;
using Microsoft.Win32;
namespace RankHelper
{
public partial class WebForm : Form
{
private static ILog Logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public tagTask currentTask;
public event EventHandler ShowTaskEvent;
public event EventHandler EndTaskEvent;
public event EventHandler StopTaskEvent;
private WebBase webBase;
public WebForm()
{
InitializeComponent();
InitializeBrowser();
this.webBrowser_new.DocumentCompleted += WebBrowser_new_DocumentCompleted;
this.webBrowser_new.NewWindow += WebBrowser_new_NewWindow;
}
public void ShowTask(AppEventArgs arg)
{
//ShowTaskEvent(this, new AppEventArgs() { message_string = str });
ShowTaskEvent(this, arg);
}
public void EndTask(AppEventArgs arg)
{
EndTaskEvent(this, arg);
}
private void WebBrowser_new_NewWindow(object sender, CancelEventArgs e)
{
e.Cancel = true;
webBrowser_new.Navigate(webBrowser_new.StatusText);
}
public void InitializeBrowser()
{
}
void InitWebBrowser()
{
//设置webBrowser
webBrowser_new.ScriptErrorsSuppressed = true; //禁用错误脚本提示
//webBrowser_new.IsWebBrowserContextMenuEnabled = false; //禁用右键菜单
//webBrowser_new.WebBrowserShortcutsEnabled = false; //禁用快捷键
//webBrowser_new.AllowWebBrowserDrop = false;//禁止拖拽
//webBrowser_new.ScrollBarsEnabled = true;//禁止滚动条
}
~WebForm()
{
//需要关闭浏览器负载程序时操作
try
{
}
catch { }
}
private void OnApplicationExit(object sender, EventArgs e)
{
}
private void WebBrowser_new_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
////将所有的链接的目标,指向本窗体
//foreach (HtmlElement archor in this.webBrowser_new.Document.Links)
//{
// archor.SetAttribute("target", "_self");
//}
////将所有的FORM的提交目标,指向本窗体
//foreach (HtmlElement form in this.webBrowser_new.Document.Forms)
//{
// form.SetAttribute("target", "_self");
//}
if (currentTask == null)
{
return;
}
if (webBrowser_new.ReadyState != WebBrowserReadyState.Complete)// || e.Url.ToString() != webBrowser_new.Url.ToString())
{
return;
}
if (currentTask == null)
{
return;
}
switch (currentTask.webState)
{
case EWebbrowserState.Start://step1
{
webBase.webBrowser_DocumentCompleted_Search(sender, e);
}
break;
case EWebbrowserState.Search://step2
{
webBase.webBrowser_DocumentCompleted_SearchSite(sender, e);
}
break;
case EWebbrowserState.SearchSite://step3
{
webBase.webBrowser_DocumentCompleted_SearchSite(sender, e);
}
break;
case EWebbrowserState.AccessSite://step4
{
webBase.webBrowser_DocumentCompleted_AccessSite(sender, e);
}
break;
case EWebbrowserState.AccessPage://step5
{
webBase.webBrowser_DocumentCompleted_AccessPage(sender, e);
}
break;
default:
break;
}
}
private void WebBrowser_LoadError(object sender, CefSharp.LoadErrorEventArgs e)
{
//重置任务
if (e.Frame.IsMain)
{
if (currentTask != null && (currentTask.webState == EWebbrowserState.Start || currentTask.webState == EWebbrowserState.Search
|| currentTask.webState == EWebbrowserState.SearchSite || currentTask.webState == EWebbrowserState.AccessSite
|| currentTask.webState == EWebbrowserState.AccessPage))
{
e.Browser.StopLoad();
ShowTaskEvent(this, new AppEventArgs() { message_string = string.Format("加载网页发生错误{0}网址{1},重新执行,任务{2}", e.ErrorText, e.FailedUrl, currentTask.nID) });
StartSearch(this, new AppEventArgs() { message_task = currentTask });
}
}
//throw new NotImplementedException();
}
internal void StartSearch(object sender, EventArgs e)
{
//webBrowser.ShowDevTools();
AppEventArgs arg = e as AppEventArgs;
InitWebBrowser();
currentTask = arg.message_task;
currentTask.webState = EWebbrowserState.Start;
if (currentTask.engine == eEngines.Sm)
{
if(currentTask.webBrowser == eWebBrowser.IE_mobile
|| currentTask.webBrowser == eWebBrowser.Chrome_mobile
|| currentTask.webBrowser == eWebBrowser.Qihu_mobile
|| currentTask.webBrowser == eWebBrowser.Sogou_mobile
|| currentTask.webBrowser == eWebBrowser.QQ_mobile
|| currentTask.webBrowser == eWebBrowser.maxthon_mobile
|| currentTask.webBrowser == eWebBrowser.theworld_mobile
)
{
currentTask.webBrowser += 1;
}
}
switch (currentTask.webBrowser)
{
case eWebBrowser.IE:
{
Appinfo.strUserAgent = "Mozilla / 4.0(compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident / 7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)";
}
break;
case eWebBrowser.IE_mobile:
{
Appinfo.strUserAgent = "Mozilla/5.0 (Linux; Android 8.0.0; SM-G9350 Build/R16NW; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/70.0.3538.17 Mobile Safari/537.36 MicroMessenger/6.7.2.1340(0x260702A3) NetType/WIFI Language/zh_CN";
}
break;
case eWebBrowser.Chrome:
{
Appinfo.strUserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";
}
break;
case eWebBrowser.Chrome_mobile:
{
Appinfo.strUserAgent = "Mozilla/5.0 (Linux; Android 8.0.0; MHA-AL00 Build/HUAWEIMHA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 HuaweiBrowser/9.0.1.319 Mobile Safari/537.36";
}
break;
case eWebBrowser.Qihu:
{
Appinfo.strUserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";
}
break;
case eWebBrowser.Qihu_mobile:
{
Appinfo.strUserAgent = "Mozilla/5.0 (Linux; Android 8.0.0; MHA-AL00 Build/HUAWEIMHA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 HuaweiBrowser/9.0.1.319 Mobile Safari/537.36";
}
break;
case eWebBrowser.QQ:
{
Appinfo.strUserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";
}
break;
case eWebBrowser.QQ_mobile:
{
Appinfo.strUserAgent = "Mozilla/5.0 (Linux; Android 8.0.0; MHA-AL00 Build/HUAWEIMHA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 HuaweiBrowser/9.0.1.319 Mobile Safari/537.36";
}
break;
case eWebBrowser.Sogou:
{
Appinfo.strUserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";
}
break;
case eWebBrowser.Sogou_mobile:
{
Appinfo.strUserAgent = "Mozilla/5.0 (Linux; Android 8.0.0; MHA-AL00 Build/HUAWEIMHA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 HuaweiBrowser/9.0.1.319 Mobile Safari/537.36";
}
break;
case eWebBrowser.maxthon:
{
Appinfo.strUserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";
}
break;
case eWebBrowser.maxthon_mobile:
{
Appinfo.strUserAgent = "Mozilla/5.0 (Linux; Android 8.0.0; MHA-AL00 Build/HUAWEIMHA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 HuaweiBrowser/9.0.1.319 Mobile Safari/537.36";
}
break;
case eWebBrowser.theworld:
{
Appinfo.strUserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";
}
break;
case eWebBrowser.theworld_mobile:
{
Appinfo.strUserAgent = "Mozilla/5.0 (Linux; Android 8.0.0; MHA-AL00 Build/HUAWEIMHA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 HuaweiBrowser/9.0.1.319 Mobile Safari/537.36";
}
break;
}
switch (currentTask.engine)
{
case eEngines.Baidu:
{
if(currentTask.searchType == eSearchType.OnSite)
{
webBase = new Baidu(this, "", "");
}
else
{
webBase = new Baidu_Inside(this, "", "");
}
}
break;
case eEngines.Qihu:
{
webBase = new Qihu(this, "", "");
}
break;
case eEngines.Sogou:
{
webBase = new Sogou(this, "", "");
}
break;
case eEngines.Sm:
{
webBase = new Sm(this, "", "");
}
break;
default:
break;
}
}
internal void StopSearch(object sender, EventArgs e)
{
currentTask = null;
webBrowser_new.Stop();
}
private void WebForm_FormClosing(object sender, FormClosingEventArgs e)
{
this.Hide();
StopTaskEvent(this, new AppEventArgs(){});
return;
}
/// <summary>
/// 获取webbrowser中html元素的屏幕坐标
/// </summary>
/// <param name="webBrowser"></param>
/// <param name="htmlElem"></param>
/// <returns></returns>
public Point GetHtmlElementClientPoint(HtmlElement htmlElement)
{
Point p = GetOffset(htmlElement);
HTMLDocument doc = webBrowser_new.Document.DomDocument as HTMLDocument;
int sl = int.Parse(doc.documentElement.getAttribute("ScrollLeft").ToString());
int st = int.Parse(doc.documentElement.getAttribute("ScrollTop").ToString());
int nPos_x = 0;
int nPos_y = 0;
//加上窗体的位置及控件的位置及窗体边框,50和8是窗体边框,不同的元素宽高不一样,需要可适当调整
p.X += htmlElement.OffsetRectangle.Left + this.Left + webBrowser_new.Left + nPos_x - sl;
p.Y += htmlElement.OffsetRectangle.Top + this.Top + webBrowser_new.Top + nPos_y - st;
return p;
}
private Point GetOffset(HtmlElement el)
{
//get element pos
Point pos = new Point(el.OffsetRectangle.Left, el.OffsetRectangle.Top);
//get the parents pos
HtmlElement tempEl = el.OffsetParent;
while (tempEl != null)
{
pos.X += tempEl.OffsetRectangle.Left;
pos.Y += tempEl.OffsetRectangle.Top;
tempEl = tempEl.OffsetParent;
}
return pos;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
using SQLite;
using SQLitePCL;
namespace RankHelper
{
public class Appinfo
{
private static ILog Logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public static string strVersion = "1.0";
public static string strTitleName = "流量精灵助手";
public static string strServiceVersion = "1.0";
public static string strServiceTitleName = "流量精灵助手监控器";
public static bool bWork = false;
public static string strUrl_RechargePoint = "www.baidu.com";
public static string strUserAgent;
public static List<tagTask> listTask;
private static string dbPath;
public static void Init()
{
Appinfo.dbPath = $"{Environment.CurrentDirectory}\\Tasks.db";
Appinfo.LoadTask();
}
public static void LoadTask()
{
Appinfo.listTask = new List<tagTask>();
Appinfo.listTask.Clear();
using (var db = new TaskDB(Appinfo.dbPath))
{
var tasks = db.Tasks.ToList();
Appinfo.listTask = tasks;
}
using (var db = new TempleTimeDB(Appinfo.dbPath))
{
var tasks = db.TempleTimes.ToList();
for (int i = 0; i < tasks.Count; i++)
{
for (int j = 0; j < Appinfo.listTask.Count; j++)
{
if (Appinfo.listTask[j].nID == tasks[i].nID)
{
Appinfo.listTask[j].tagtempleTime = tasks[i];
continue;
}
}
}
}
}
public static void AddTask(tagTask task)
{
//int nID = 0;
//for (int i = Appinfo.listTask.Count-1; i >= 0; i--)
//{
// nID = Appinfo.listTask[i].nID + 1;
// break;
//}
//task.nID = nID;
Appinfo.listTask.Add(task);
using (var db = new TaskDB(Appinfo.dbPath))
{
try
{
int count = db.Insert(task);
Logger.Info($"{DateTime.Now}, 插入{count}条记录");
}
catch (Exception e)
{
throw;
}
}
Appinfo.LoadTask();
task.tagtempleTime.nID = Appinfo.listTask[Appinfo.listTask.Count - 1].nID;
using (var db = new TempleTimeDB(Appinfo.dbPath))
{
try
{
int count = db.Insert(task.tagtempleTime);
}
catch (Exception e)
{
throw;
}
}
Appinfo.LoadTask();
task = Appinfo.listTask[Appinfo.listTask.Count-1];
}
public static bool ChangeTask(tagTask task)
{
for (int i = 0; i < Appinfo.listTask.Count; i++)
{
if (Appinfo.listTask[i].nID == task.nID)
{
Appinfo.listTask[i].engine = task.engine;
Appinfo.listTask[i].searchType = task.searchType;
Appinfo.listTask[i].strKeyword = task.strKeyword;
Appinfo.listTask[i].strTitle = task.strTitle;
Appinfo.listTask[i].strSiteUrl = task.strSiteUrl;
Appinfo.listTask[i].nEngineTime = task.nEngineTime;
Appinfo.listTask[i].nCountPage = task.nCountPage;
Appinfo.listTask[i].webBrowser = task.webBrowser;
Appinfo.listTask[i].nCountLimit = task.nCountLimit;
Appinfo.listTask[i].nSiteTime = task.nSiteTime;
Appinfo.listTask[i].pageAccessType = task.pageAccessType;
Appinfo.listTask[i].strPageUrl = task.strPageUrl;
Appinfo.listTask[i].nPageTime = task.nPageTime;
Appinfo.listTask[i].tagtempleTime.bCheck00 = task.tagtempleTime.bCheck00;
Appinfo.listTask[i].tagtempleTime.bCheck01 = task.tagtempleTime.bCheck01;
Appinfo.listTask[i].tagtempleTime.bCheck02 = task.tagtempleTime.bCheck02;
Appinfo.listTask[i].tagtempleTime.bCheck03 = task.tagtempleTime.bCheck03;
Appinfo.listTask[i].tagtempleTime.bCheck04 = task.tagtempleTime.bCheck04;
Appinfo.listTask[i].tagtempleTime.bCheck05 = task.tagtempleTime.bCheck05;
Appinfo.listTask[i].tagtempleTime.bCheck06 = task.tagtempleTime.bCheck06;
Appinfo.listTask[i].tagtempleTime.bCheck07 = task.tagtempleTime.bCheck07;
Appinfo.listTask[i].tagtempleTime.bCheck08 = task.tagtempleTime.bCheck08;
Appinfo.listTask[i].tagtempleTime.bCheck09 = task.tagtempleTime.bCheck09;
Appinfo.listTask[i].tagtempleTime.bCheck10 = task.tagtempleTime.bCheck10;
Appinfo.listTask[i].tagtempleTime.bCheck11 = task.tagtempleTime.bCheck11;
Appinfo.listTask[i].tagtempleTime.bCheck12 = task.tagtempleTime.bCheck12;
Appinfo.listTask[i].tagtempleTime.bCheck13 = task.tagtempleTime.bCheck13;
Appinfo.listTask[i].tagtempleTime.bCheck14 = task.tagtempleTime.bCheck14;
Appinfo.listTask[i].tagtempleTime.bCheck15 = task.tagtempleTime.bCheck15;
Appinfo.listTask[i].tagtempleTime.bCheck16 = task.tagtempleTime.bCheck16;
Appinfo.listTask[i].tagtempleTime.bCheck17 = task.tagtempleTime.bCheck17;
Appinfo.listTask[i].tagtempleTime.bCheck18 = task.tagtempleTime.bCheck18;
Appinfo.listTask[i].tagtempleTime.bCheck19 = task.tagtempleTime.bCheck19;
Appinfo.listTask[i].tagtempleTime.bCheck20 = task.tagtempleTime.bCheck20;
Appinfo.listTask[i].tagtempleTime.bCheck21 = task.tagtempleTime.bCheck21;
Appinfo.listTask[i].tagtempleTime.bCheck22 = task.tagtempleTime.bCheck22;
Appinfo.listTask[i].tagtempleTime.bCheck23 = task.tagtempleTime.bCheck23;
Appinfo.listTask[i].tagtempleTime.nCount00 = task.tagtempleTime.nCount00;
Appinfo.listTask[i].tagtempleTime.nCount01 = task.tagtempleTime.nCount01;
Appinfo.listTask[i].tagtempleTime.nCount02 = task.tagtempleTime.nCount02;
Appinfo.listTask[i].tagtempleTime.nCount03 = task.tagtempleTime.nCount03;
Appinfo.listTask[i].tagtempleTime.nCount04 = task.tagtempleTime.nCount04;
Appinfo.listTask[i].tagtempleTime.nCount05 = task.tagtempleTime.nCount05;
Appinfo.listTask[i].tagtempleTime.nCount06 = task.tagtempleTime.nCount06;
Appinfo.listTask[i].tagtempleTime.nCount07 = task.tagtempleTime.nCount07;
Appinfo.listTask[i].tagtempleTime.nCount08 = task.tagtempleTime.nCount08;
Appinfo.listTask[i].tagtempleTime.nCount09 = task.tagtempleTime.nCount09;
Appinfo.listTask[i].tagtempleTime.nCount10 = task.tagtempleTime.nCount10;
Appinfo.listTask[i].tagtempleTime.nCount11 = task.tagtempleTime.nCount11;
Appinfo.listTask[i].tagtempleTime.nCount12 = task.tagtempleTime.nCount12;
Appinfo.listTask[i].tagtempleTime.nCount13 = task.tagtempleTime.nCount13;
Appinfo.listTask[i].tagtempleTime.nCount14 = task.tagtempleTime.nCount14;
Appinfo.listTask[i].tagtempleTime.nCount15 = task.tagtempleTime.nCount15;
Appinfo.listTask[i].tagtempleTime.nCount16 = task.tagtempleTime.nCount16;
Appinfo.listTask[i].tagtempleTime.nCount17 = task.tagtempleTime.nCount17;
Appinfo.listTask[i].tagtempleTime.nCount18 = task.tagtempleTime.nCount18;
Appinfo.listTask[i].tagtempleTime.nCount19 = task.tagtempleTime.nCount19;
Appinfo.listTask[i].tagtempleTime.nCount20 = task.tagtempleTime.nCount20;
Appinfo.listTask[i].tagtempleTime.nCount21 = task.tagtempleTime.nCount21;
Appinfo.listTask[i].tagtempleTime.nCount22 = task.tagtempleTime.nCount22;
Appinfo.listTask[i].tagtempleTime.nCount23 = task.tagtempleTime.nCount23;
Appinfo.listTask[i].templeTime = task.templeTime;
using (var db = new TaskDB(Appinfo.dbPath))
{
try
{
int count = db.Update(Appinfo.listTask[i]);
Logger.Info($"{DateTime.Now}, 修改1条记录,{Appinfo.listTask[i].nID}");
}
catch (Exception e)
{
throw;
}
}
using (var db = new TempleTimeDB(Appinfo.dbPath))
{
try
{
int count = db.Update(Appinfo.listTask[i].tagtempleTime);
}
catch (Exception e)
{
throw;
}
}
return true;
}
}
return false;
}
public static bool CountTask(tagTask task)
{
for (int i = 0; i < Appinfo.listTask.Count; i++)
{
if (Appinfo.listTask[i].nID == task.nID)
{
Appinfo.listTask[i].nCountVaildToday = task.nCountVaildToday;
Appinfo.listTask[i].nCountInvaildToday = task.nCountInvaildToday;
Appinfo.listTask[i].nCountTotal = task.nCountTotal;
Appinfo.listTask[i].nCountExcuteToday = task.nCountExcuteToday;
Appinfo.listTask[i].nCountPageVaildToday = task.nCountPageVaildToday;
Appinfo.listTask[i].nCountPageInvaildToday = task.nCountPageInvaildToday;
Appinfo.listTask[i].nCountPageTotal = task.nCountPageTotal;
using (var db = new TaskDB(Appinfo.dbPath))
{
try
{
int count = db.Update(Appinfo.listTask[i]);
Logger.Info($"{DateTime.Now}, 统计1条记录,{Appinfo.listTask[i].nID}");
}
catch (Exception e)
{
throw;
}
}
return true;
}
}
return false;
}
public static bool DeleteTask(tagTask task)
{
for (int i = 0; i < Appinfo.listTask.Count; i++)
{
if (Appinfo.listTask[i].nID == task.nID)
{
Appinfo.listTask.Remove(Appinfo.listTask[i]);
using (var db = new TaskDB(Appinfo.dbPath))
{
try
{
int count = db.Delete(task);
Logger.Info($"{DateTime.Now}, 删除{count}条记录,{task.nID}");
}
catch (Exception e)
{
throw;
}
}
using (var db = new TempleTimeDB(Appinfo.dbPath))
{
try
{
int count = db.Delete(task.tagtempleTime);
}
catch (Exception e)
{
throw;
}
}
return true;
}
}
return false;
}
public static tagTask QueryTask(int nTaskID)
{
foreach (var item in Appinfo.listTask)
{
if (item.nID.Equals(nTaskID))
{
return item;
}
}
return null;
}
public static tagSetting QuerySetting()
{
using (var db = new SettingDB(Appinfo.dbPath))
{
try
{
tagSetting setting = db.Query<tagSetting>("SELECT * FROM tagSetting;").FirstOrDefault();
if(setting==null)
{
setting = new tagSetting();
db.Insert(setting);
}
return setting;
}
catch (Exception e)
{
throw;
}
}
return null;
}
public static bool UpdateSetting(tagSetting setting)
{
using (var db = new SettingDB(Appinfo.dbPath))
{
try
{
string sql = string.Format("UPDATE tagSetting SET bCheck ='{0}',strUsername = '{1}', strPwd = '{2}',connectionType = '{3}',connectionInvert = '{4}',nCount = '{5}',IP = '{6}' WHERE nID = '{7}'",
TypeUtils.BoolToInt(setting.bCheck),
setting.strUsername,
setting.strPwd,
setting.connectionType,
setting.connectionInvert,
setting.nCount,
setting.IP,
setting.nID);
int count = db.Execute(sql);
Logger.Info($"{DateTime.Now}, 更新设置");
}
catch (Exception e)
{
throw;
}
}
return true;
}
public static bool UpdateIP(string strIP)
{
using (var db = new SettingDB(Appinfo.dbPath))
{
try
{
string sql = string.Format("UPDATE tagSetting SET IP = '{0}' WHERE nID = '0'", strIP);
int count = db.Execute(sql);
if(count == 0)
{
count = db.Insert(new tagSetting());
count = db.Execute(sql);
}
Logger.Info($"{DateTime.Now}, 更新IP,{strIP}");
}
catch (Exception e)
{
throw;
}
}
return true;
}
public static string GetIP()
{
using (var db = new SettingDB(Appinfo.dbPath))
{
try
{
var info = db.Setting.FirstOrDefault();
if (info!=null)
{
return info.IP;
}
}
catch (Exception e)
{
throw;
}
}
return "";
}
}
}
<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 log4net;
using System.Net.NetworkInformation;
using DotRas;
using System.Collections.ObjectModel;
using System.Net;
namespace RankHelper
{
public partial class AdslForm : Form
{
private static ILog Logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public AdslForm()
{
InitializeComponent();
Init();
InitData();
}
void Init()
{
foreach (eConnectionType item in Enum.GetValues(typeof(eConnectionType)))
{
comboBox_Connect.Items.Add(define.GetEnumName(item));
}
comboBox_Connect.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox_Connect.Enabled = false;
foreach (eConnectionInvert item in Enum.GetValues(typeof(eConnectionInvert)))
{
comboBox_Invert.Items.Add(define.GetEnumName(item));
}
comboBox_Invert.DropDownStyle = ComboBoxStyle.DropDownList;
}
void InitData()
{
tagSetting setting = Appinfo.QuerySetting();
if (setting == null)
{
setting = new tagSetting();
}
SetSetting(setting);
}
void SetSetting(tagSetting setting)
{
checkBox_AutoStart.Checked = setting.bCheck;
textBox_Username.Text = setting.strUsername;
textBox_Pwd.Text = setting.strPwd;
comboBox_Connect.SelectedIndex = (int)setting.connectionType;
comboBox_Invert.SelectedIndex = (int)setting.connectionInvert;
textBox_Count.Text = setting.nCount.ToString();
}
void GetSetting(tagSetting setting)
{
setting.bCheck = checkBox_AutoStart.Checked;
setting.strUsername = textBox_Username.Text;
setting.strPwd = <PASSWORD>_Pwd.Text;
setting.connectionType = (eConnectionType)comboBox_Connect.SelectedIndex;
setting.connectionInvert = (eConnectionInvert)comboBox_Invert.SelectedIndex;
setting.nCount = textBox_Count.Text.Trim().Equals("") ? 0 : int.Parse(textBox_Count.Text);
}
private void checkBox_AutoStart_CheckedChanged(object sender, EventArgs e)
{
AppUtils.AutoStart(checkBox_AutoStart.Checked);
tagSetting setting = Appinfo.QuerySetting();
GetSetting(setting);
Appinfo.UpdateSetting(setting);
}
private void textBox_Count_Leave(object sender, EventArgs e)
{
TextBox textBox = (TextBox)sender;
if (textBox.Text.Trim().Equals(""))
{
textBox.Text = "9999";
}
int nTime = int.Parse(textBox.Text);
if (nTime < 1)
{
textBox.Text = "1";
}
else if (nTime > 9999)
{
textBox.Text = "9999";
}
tagSetting setting = Appinfo.QuerySetting();
GetSetting(setting);
Appinfo.UpdateSetting(setting);
}
private void textBox_Username_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
checkBox_AutoStart.Select();
}
}
private void textBox_Username_Leave(object sender, EventArgs e)
{
tagSetting setting = Appinfo.QuerySetting();
GetSetting(setting);
Appinfo.UpdateSetting(setting);
}
/// <summary>
/// 创建或更新一个PPPOE连接(指定PPPOE名称)
/// </summary>
public void CreateOrUpdatePPPOE(string updatePPPOEname)
{
RasDialer dialer = new RasDialer();
RasPhoneBook allUsersPhoneBook = new RasPhoneBook();
string path = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
allUsersPhoneBook.Open(path);
// 如果已经该名称的PPPOE已经存在,则更新这个PPPOE服务器地址
if (allUsersPhoneBook.Entries.Contains(updatePPPOEname))
{
allUsersPhoneBook.Entries[updatePPPOEname].PhoneNumber = " ";
// 不管当前PPPOE是否连接,服务器地址的更新总能成功,如果正在连接,则需要PPPOE重启后才能起作用
allUsersPhoneBook.Entries[updatePPPOEname].Update();
}
// 创建一个新PPPOE
else
{
string adds = string.Empty;
ReadOnlyCollection<RasDevice> readOnlyCollection = RasDevice.GetDevices();
// foreach (var col in readOnlyCollection)
// {
// adds += col.Name + ":" + col.DeviceType.ToString() + "|||";
// }
// _log.Info("Devices are : " + adds);
// Find the device that will be used to dial the connection.
RasDevice device = RasDevice.GetDevices().Where(o => o.DeviceType == RasDeviceType.PPPoE).First();
RasEntry entry = RasEntry.CreateBroadbandEntry(updatePPPOEname, device); //建立宽带连接Entry
entry.PhoneNumber = " ";
allUsersPhoneBook.Entries.Add(entry);
}
}
/// <summary>
/// 断开 宽带连接
/// </summary>
public void Disconnect()
{
ReadOnlyCollection<RasConnection> conList = RasConnection.GetActiveConnections();
foreach (RasConnection con in conList)
{
con.HangUp();
}
}
/// <summary>
/// 宽带连接,成功返回true,失败返回 false
/// </summary>
/// <param name="PPPOEname">宽带连接名称</param>
/// <param name="username">宽带账号</param>
/// <param name="password"><PASSWORD></param>
/// <returns></returns>
public bool Connect(string PPPOEname, string username, string password, ref string msg)
{
try
{
CreateOrUpdatePPPOE(PPPOEname);
using (RasDialer dialer = new RasDialer())
{
dialer.EntryName = PPPOEname;
dialer.AllowUseStoredCredentials = true;
dialer.Timeout = 1000;
dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
dialer.Credentials = new NetworkCredential(username, password);
dialer.Dial();
return true;
}
}
catch (RasException re)
{
msg = re.ErrorCode + " " + re.Message;
MessageBox.Show(msg);
return false;
}
}
private void button_connect_Click(object sender, EventArgs e)
{
string msg = null;
tagSetting setting = Appinfo.QuerySetting();
bool isok = Connect(define.GetEnumName(setting.connectionType), setting.strUsername.ToString(), setting.strPwd.ToString(), ref msg);
}
private void button_disconnect_Click(object sender, EventArgs e)
{
Disconnect();
}
private void button_reconnect_Click(object sender, EventArgs e)
{
Disconnect();
string msg = null;
tagSetting setting = Appinfo.QuerySetting();
bool isok = Connect(define.GetEnumName(setting.connectionType), setting.strUsername.ToString(), setting.strPwd.ToString(), ref msg);
}
private void button_getIP_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
foreach (RasConnection connection in RasConnection.GetActiveConnections())
{
RasIPInfo ipAddresses = (RasIPInfo)connection.GetProjectionInfo(RasProjectionType.IP);
if (ipAddresses != null)
{
sb.AppendFormat("ClientIP:{0}\r\n", ipAddresses.IPAddress.ToString());
sb.AppendFormat("ServerIP:{0}\r\n", ipAddresses.ServerIPAddress.ToString());
}
sb.AppendLine();
}
MessageBox.Show(sb.ToString());
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Reflection;
namespace RankHelper
{
public class UserAgentHelper
{
private static string defaultUserAgent = null;
[DllImport("urlmon.dll", CharSet = CharSet.Ansi)]
private static extern int UrlMkSetSessionOption(int dwOption, string pBuffer, int dwBufferLength, int dwReserved);
const int URLMON_OPTION_USERAGENT = 0x10000001;
/// <summary>
/// 在默认的UserAgent后面加一部分
/// </summary>
public static void AppendUserAgent(string appendUserAgent)
{
if (string.IsNullOrEmpty(defaultUserAgent))
defaultUserAgent = GetDefaultUserAgent();
string ua = defaultUserAgent + ";" + appendUserAgent;
ChangeUserAgent(ua);
}
/// <summary>
/// 修改UserAgent
/// </summary>
public static void ChangeUserAgent(string userAgent)
{
UrlMkSetSessionOption(URLMON_OPTION_USERAGENT, userAgent, userAgent.Length, 0);
}
/// <summary>
/// 一个很BT的获取IE默认UserAgent的方法
/// </summary>
public static string GetDefaultUserAgent()
{
WebBrowser wb = new WebBrowser();
wb.Navigate("about:blank");
while (wb.IsBusy) Application.DoEvents();
object window = wb.Document.Window.DomWindow;
Type wt = window.GetType();
object navigator = wt.InvokeMember("navigator", BindingFlags.GetProperty,
null, window, new object[] { });
Type nt = navigator.GetType();
object userAgent = nt.InvokeMember("userAgent", BindingFlags.GetProperty,
null, navigator, new object[] { });
return userAgent.ToString();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
namespace RankHelper
{
static class Program
{
private static System.Threading.Mutex mutex;
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
mutex = new System.Threading.Mutex(true, "RankHelper");
if (mutex.WaitOne(0, false))
{
LogHelper.InitLog4Net();
if (args != null && args.Length > 0) //打印出参数
{
Appinfo.bWork = true;
}
Application.Run(new MainForm());
}
else
{
//MessageBox.Show("程序已经在运行!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
Application.Exit();
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using mshtml;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Drawing;
using System.Timers;
namespace RankHelper
{
public class WebBase
{
public WebForm webForm;
public string strhtml;
public string strSiteUrl;
public int nPos_x;
public int nPos_y;
public int nPageIndex = 1;//第几页
public int nItem = -1;//第几项
//每次访问网页超时定时器
public System.Timers.Timer taskIntervalTimer;
public WebBase(WebForm webForm, string strSiteUrl, string strhtml)
{
this.webForm = webForm;
this.strSiteUrl = strSiteUrl;
this.strhtml = strhtml;
nPageIndex = 1;
this.taskIntervalTimer = new System.Timers.Timer();
this.taskIntervalTimer.Elapsed += new System.Timers.ElapsedEventHandler(taskIntervalTimer_Elapsed);
this.taskIntervalTimer.AutoReset = true;
this.taskIntervalTimer.Interval = 1000 * 60 * 2;
this.taskIntervalTimer.Enabled = false;
}
public virtual void StartSearch(object sender, EventArgs e)
{
}
public virtual void webBrowser_DocumentCompleted_Search(object sender, WebBrowserDocumentCompletedEventArgs e)
{
this.taskIntervalTimer.Stop();
}
public virtual void webBrowser_DocumentCompleted_SearchSite(object sender, WebBrowserDocumentCompletedEventArgs e)
{
this.taskIntervalTimer.Stop();
}
public virtual void webBrowser_DocumentCompleted_AccessSite(object sender, WebBrowserDocumentCompletedEventArgs e)
{
this.taskIntervalTimer.Stop();
}
public virtual void webBrowser_DocumentCompleted_AccessPage(object sender, WebBrowserDocumentCompletedEventArgs e)
{
this.taskIntervalTimer.Stop();
}
public void EndTask(bool bSuccess)
{
this.taskIntervalTimer.Stop();
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("任务超时,重置") });
webForm.webBrowser_new.Stop();
webForm.EndTask(new AppEventArgs() { message_bool = bSuccess, message_task = webForm.currentTask });
}
public virtual void GetNextPageurl()
{
}
/// <summary>
/// 等待一段时间
/// </summary>
public void Sleep(int milliseconds)
{
var start = DateTime.Now;
var stop = start.AddMilliseconds(milliseconds);
while (DateTime.Now < stop)
{
Application.DoEvents();
}
}
public Point GetPoint(HtmlElement el)
{
Point pos = new Point(el.OffsetRectangle.Left, el.OffsetRectangle.Top);
//循环获取父级的坐标
HtmlElement tempEl = el.OffsetParent;
while (tempEl != null)
{
pos.X += tempEl.OffsetRectangle.Left;
pos.Y += tempEl.OffsetRectangle.Top;
tempEl = tempEl.OffsetParent;
}
return pos;
}
private void taskIntervalTimer_Elapsed(object sender, ElapsedEventArgs e)
{
EndTask(true);
}
}
}
<file_sep># RankHelper
搜索引擎搜索关键词提升网站流量
远程连接:172.16.31.10:20229
用户名:administrator
密码:<PASSWORD>
宽带帐号:Fadsl
宽带密码:<PASSWORD>
云服务器名:hz899945
注意事项
1.安装net4.6.5
2.设置ie禁止拨号.https://www.pc841.com/article/20180303-87904.html
3.禁止安装360等安全软件,防止弹出选择
4.任务设置,关闭软件要停止挂机后进行
5.每执行一次任务重启一下软件,拨号,删除缓存,执行任务<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Net.NetworkInformation;
namespace RankHelper
{
public class AdslReconnect
{
//找主窗口句柄
[DllImport("user32.dll")]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
//找子窗口句柄
[DllImport("user32.dll", EntryPoint = "FindWindowEx")]
private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
//发送字符串
[DllImport("User32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam);
//枚举窗口
[DllImport("user32.dll", EntryPoint = "EnumChildWindows")]
private static extern bool EnumChildWindows(IntPtr hWndParent, EnumChildWindowsProc lpEnumFunc, int lParam);
//获取指定句柄类名
[DllImport("user32.dll", EntryPoint = "GetClassName")]
private static extern int GetClassName(IntPtr hwnd, StringBuilder lpClassName, int nMaxCount);
const int WM_SETTEXT = 0x000C;//发送文本
const int WM_CLICK = 0x00F5;//鼠标单击
delegate bool EnumChildWindowsProc(IntPtr hwnd, uint lParam);
delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
static IntPtr reconnection = IntPtr.Zero;//重新连接按钮句柄
///<summary>
/// ADSL拨号
///</summary>
///<param name="adslUserName">adsl用户名</param>
///<param name="adslPasswd">adsl密码</param>
///<returns></returns>
public static bool DoAdsl(string adslUserName, string adslPasswd)
{
string username = adslUserName;
string passwd = <PASSWORD>;
//下面的这些参数都可以用Spy++查到
string lpszParentClass = "#32770"; //整个窗口的类名
string lpszParentWindow = "连接 宽带连接"; //窗口标题
string lpszClass = "Edit"; //需要查找的子窗口的类名,也就是输入框
string lpszClass_Submit = "Button"; //需要查找的Button的类名
string lpszName_Submit = "连接(&C)"; //需要查找的Button的标题
IntPtr parentHWND = new IntPtr(0);
//查到窗体,得到整个主窗口句柄
while (true)
{
parentHWND = FindWindow(lpszParentClass, lpszParentWindow);
if (parentHWND != IntPtr.Zero)
break;
Thread.Sleep(100);
}
if (!parentHWND.Equals(IntPtr.Zero))
{
IntPtr childHWND = new IntPtr(0);
childHWND = FindWindowEx(parentHWND, childHWND, lpszClass, string.Empty);//得到User Name这个子窗体
SendMessage(childHWND, WM_SETTEXT, IntPtr.Zero, username);//调用SendMessage方法设置其内容
childHWND = FindWindowEx(parentHWND, childHWND, lpszClass, string.Empty);//得到Password这个子窗体
SendMessage(childHWND, WM_SETTEXT, IntPtr.Zero, passwd);
childHWND = FindWindowEx(parentHWND, childHWND, lpszClass_Submit, lpszName_Submit);//得到Button这个子窗体
SendMessage(childHWND, WM_CLICK, IntPtr.Zero, "0");//触发Click事件
Thread.Sleep(500);
while (true)
{
if (FindWindow("#32770", "正在连接 宽带连接...") == IntPtr.Zero)//表示连接成功
break;
IntPtr errorParent = FindWindow("#32770", "连接到 宽带连接 时出错");
if (errorParent != IntPtr.Zero)
{
//获取'重拨(&R)'按钮句柄
EnumChildWindowsProc myEnumChild = new EnumChildWindowsProc(EumWinChiPro);
try
{
EnumChildWindows(errorParent, myEnumChild, 0);
}
catch (Exception ex)
{
throw new Exception(ex.Message + "\r\n " + ex.Source + "\r\n\r\n " + ex.StackTrace.ToString());
}
if (reconnection != IntPtr.Zero)
SendMessage(reconnection, WM_CLICK, (IntPtr)0, "0");
}
Thread.Sleep(1000);
}
}
else
{
return false;
}
return true;
}
private static bool EumWinChiPro(IntPtr hWnd, uint lParam)
{
StringBuilder s = new StringBuilder(50);
GetClassName(hWnd, s, 50);
if (s.ToString() == "Button")
{
reconnection = hWnd;
return false;
}
return true;
}
///<summary>
/// 断网或打开adsl连接窗口
///</summary>
///<param name="status">false断网,true打开adsl窗口</param>
///<returns></returns>
//private static bool SetNetworkAdapter(bool status, string adslName)
//{
// string discVerb = "断开(&O)";
// string connVerb = "连接(&O)";
// string network = "网络连接";
// string networkConnection = adslName;
// string sVerb;
// if (status)
// {
// sVerb = connVerb;
// }
// else
// {
// sVerb = discVerb;
// }
// Shell32.Shell sh = new Shell32.Shell();
// Shell32.Folder folder;
////Shell32.ShellSpecialFolderConstants.ssfCONTROLS
// folder = sh.NameSpace(3);
// try
// {
////进入控制面板的所有选项
// foreach (Shell32.FolderItem myItem in folder.Items())
// {
////进入网络和拔号连接
// if (myItem.Name == network)
// {
// Shell32.Folder fd = (Shell32.Folder)myItem.GetFolder;
// foreach (Shell32.FolderItem fi in fd.Items())
// {
////找到本地连接
// if (fi.Name.IndexOf(networkConnection) > -1)
// {
////找本地连接的所有右键功能菜单
// foreach (Shell32.FolderItemVerb Fib in fi.Verbs())//在多线程中,此处会报错
// {
// if (Fib.Name == sVerb)
// {
// Fib.DoIt();
// return true;
// }
// }
// }
// }
// }
// }
// }
// catch (Exception ex)
// {
// MessageBox.Show(ex.Message);
// return false;
// }
// return false;
//}
///<summary>
/// adsl重连
///</summary>
///<param name="adslUserName">用户名</param>
///<param name="adslPasswd">密码</param>
///<returns>true成功,false失败</returns>
//public static bool AdslConnection(string adslUserName, string adslPasswd, string adslName)
//{
// try
// {
// SetNetworkAdapter(false, adslName);//断开
// Thread.Sleep(3000);
// bool isSuccess = SetNetworkAdapter(true, adslName);//重连
// if (isSuccess)
// {
// int result = DoAdsl(adslUserName, adslPasswd);
// if (result == 3)
// return true;
// else
// return false;
// }
// else
// {
// return false;
// }
// }
// catch
// {
// return false;
// }
//}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting.Messaging;
namespace AsyncCall
{
public class AsyncEvent
{
/// <summary>
/// 声明委托
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public delegate T MyAsyncDelegate<T>();
public delegate T MyAsyncDelegate2<T>(int a, int b);
/// <summary>
/// 回调函数得到异步线程的返回结果
/// </summary>
/// <param name="iasync"></param>
public static T CallBack<T>(IAsyncResult iasync)
{
AsyncResult async = (AsyncResult)iasync;
MyAsyncDelegate<T> del = (MyAsyncDelegate<T>)async.AsyncDelegate;
return (T)del.EndInvoke(iasync);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.IO;
using Microsoft.Win32;
namespace AccessWeb
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public List<Domain> list_Domain;
public MainWindow()
{
InitializeComponent();
InitListView_domain();
DatePicker_interval.SelectedDateFormat = DatePickerFormat.Short;
}
public void InitListView_domain()
{
list_Domain = new List<Domain>();
listView_domain.ItemsSource = list_Domain;
}
private void button_deleteAll_Click(object sender, RoutedEventArgs e)
{
list_Domain.Clear();
listView_domain.Items.Refresh();
}
private void button_delete_Click(object sender, RoutedEventArgs e)
{
if (listView_domain.SelectedItem != null)
{
list_Domain.RemoveAt(listView_domain.SelectedIndex);
}
listView_domain.Items.Refresh();
}
private void button_Import_Click(object sender, RoutedEventArgs e)
{
TextRange textRange = new TextRange(richTextBox_domain.Document.ContentStart, richTextBox_domain.Document.ContentEnd);
string[] arrayDomain = textRange.Text.Split(new string[] {"\r\n"}, StringSplitOptions.None);
int nCount = 0;
foreach (var item in arrayDomain)
{
if (item != String.Empty && item.Contains("."))
{
Domain domain;
if (list_Domain.Count == 0)
{
domain = new Domain(list_Domain.Count+1, item);
}
else
{
domain = new Domain(list_Domain.Last().ID + 1, item);
}
list_Domain.Add(domain);
listView_domain.Items.Refresh();
nCount++;
}
}
textRange.Text = String.Empty;
string strInfo = String.Format("成功导入 {0} 个地址。", nCount);
TextRange textRange_log = new TextRange(richTextBox_log.Document.ContentStart, richTextBox_log.Document.ContentEnd);
//MessageBox.Show(strInfo, "Information", MessageBoxButton.OK, MessageBoxImage.Information);
textRange_log.Text = strInfo +"\r\n"+ textRange_log.Text;
}
private void button_importTXT_Click(object sender, RoutedEventArgs e)
{
LoadTxt();
}
private void button_run_Click(object sender, RoutedEventArgs e)
{
//richTextBox_domain.
}
private void button_stop_Click(object sender, RoutedEventArgs e)
{
}
private void LoadTxt()
{
Microsoft.Win32.OpenFileDialog openfile = new Microsoft.Win32.OpenFileDialog();
openfile.DefaultExt = ".txt";
openfile.Filter = "Text documents (.txt)|*.txt";
bool? result = openfile.ShowDialog();
if (result == true)
{
//textBlock.Text = openfile.FileName;
StreamReader readfile = new StreamReader(openfile.FileName);
TextRange textRange = new TextRange(richTextBox_domain.Document.ContentStart, richTextBox_domain.Document.ContentEnd);
textRange.Text = readfile.ReadToEnd();
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using mshtml;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Drawing;
namespace RankHelper
{
public class Sogou : WebBase
{
public Sogou(WebForm webForm, string strSiteUrl, string strhtml) : base(webForm, strSiteUrl, strhtml)
{
nPos_x = 30;
nPos_y = 80;
webForm.webBrowser_new.Navigate("www.sogou.com");
}
public override void webBrowser_DocumentCompleted_Search(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (e.Url.ToString().Contains("sogou"))
{
webForm.currentTask.webState = EWebbrowserState.none;
webForm.textBox_url.Text = e.Url.ToString();
HtmlElement ele_search;
if (webForm.currentTask.webBrowser == eWebBrowser.IE || webForm.currentTask.webBrowser == eWebBrowser.Chrome || webForm.currentTask.webBrowser == eWebBrowser.Qihu || webForm.currentTask.webBrowser == eWebBrowser.Sogou || webForm.currentTask.webBrowser == eWebBrowser.QQ || webForm.currentTask.webBrowser == eWebBrowser.maxthon || webForm.currentTask.webBrowser == eWebBrowser.theworld)
{
ele_search = webForm.webBrowser_new.Document.GetElementById("query");
}
else//移动端
{
ele_search = webForm.webBrowser_new.Document.GetElementById("query");
}
if (ele_search == null)
{
webForm.currentTask.webState = EWebbrowserState.Search;
webForm.webBrowser_new.Refresh();
return;
}
KeyUtils.SetCursorPos(500, 280);
KeyUtils.MouseLBUTTON();
this.taskIntervalTimer.Start();
KeyUtils.Copy(webForm.currentTask.strKeyword);
Sleep(3000);
HtmlElement ele_submit;
if (webForm.currentTask.webBrowser == eWebBrowser.IE || webForm.currentTask.webBrowser == eWebBrowser.Chrome || webForm.currentTask.webBrowser == eWebBrowser.Qihu || webForm.currentTask.webBrowser == eWebBrowser.Sogou || webForm.currentTask.webBrowser == eWebBrowser.QQ || webForm.currentTask.webBrowser == eWebBrowser.maxthon || webForm.currentTask.webBrowser == eWebBrowser.theworld)
{
ele_submit = webForm.webBrowser_new.Document.GetElementById("stb");
}
else
{
ele_submit = webForm.webBrowser_new.Document.GetElementById("stb");
}
if (ele_submit == null)
{
webForm.currentTask.webState = EWebbrowserState.Search;
webForm.webBrowser_new.Refresh();
return;
}
KeyUtils.SetCursorPos(760, 280);
KeyUtils.MouseLBUTTON();
this.taskIntervalTimer.Start();
if (webForm.currentTask == null)
{
return;
}
webForm.currentTask.webState = EWebbrowserState.Search;
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("开始搜索关键词,任务{0}", webForm.currentTask.nID) });
}
}
public override void webBrowser_DocumentCompleted_SearchSite(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (!e.Url.ToString().Contains("www.sogou.com/web?query="))
{
return;
}
nItem = 0;
if (e.Url.ToString().Contains("sogou"))
{
webForm.currentTask.webState = EWebbrowserState.none;
webForm.textBox_url.Text = e.Url.ToString();
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("开始查找网站,当前页码{0},任务{1}", nPageIndex, webForm.currentTask.nID) });
Sleep(3000);
//List<tagSearchResult> listSearch = new List<tagSearchResult>();
//搜索项目
//HtmlElement ele_search;
HtmlElementCollection divCol = webForm.webBrowser_new.Document.GetElementsByTagName("div");
if (divCol != null)
{
for (int i = 0; i < divCol.Count; i++)//1~10项
{
if (divCol[i].GetAttribute("className") == null)
{
continue;
}
if (divCol[i].GetAttribute("className") == "results")
{
HtmlElementCollection eleCol = divCol[i].Children;
if (eleCol != null)
{
for (int j = 0; j < eleCol.Count; j++)//1~10项
{
if (eleCol[j].GetAttribute("className") == null)
{
continue;
}
if (eleCol[j].GetAttribute("className") == "rb"|| eleCol[j].GetAttribute("className") == "vrwrap")
{
nItem++;
if (!webForm.currentTask.strTitle.Trim().Equals("") && !webForm.currentTask.strSiteUrl.Trim().Equals(""))
{
if (eleCol[j].InnerText.Contains(webForm.currentTask.strTitle) || eleCol[j].InnerText.Contains(webForm.currentTask.strSiteUrl))
{
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("查找到符合的网站,当前页码{0},任务{1}", nPageIndex, webForm.currentTask.nID) });
webForm.currentTask.webState = EWebbrowserState.AccessSite;
Sleep(3000);
Point point_ele = GetPoint(eleCol[j]);
int nPos_y = 60;
webForm.webBrowser_new.Document.Window.ScrollTo(0, point_ele.Y - nPos_y);
int top2 = webForm.webBrowser_new.Document.GetElementsByTagName("HTML")[0].ScrollTop;//滚动条垂直位置
//KeyUtils.SetCursorPos(point_ele.X + nPos_x - 900, point_ele.Y + nPos_y - top2);
KeyUtils.SetCursorPos(point_ele.X + nPos_x, point_ele.Y + nPos_y - top2);
Sleep(3000);
webForm.currentTask.webState = EWebbrowserState.AccessSite;
KeyUtils.MouseLBUTTON();
this.taskIntervalTimer.Start();
return;
}
}
else if (!webForm.currentTask.strTitle.Trim().Equals(""))
{
if (eleCol[j].InnerText.Contains(webForm.currentTask.strTitle))
{
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("查找到符合的网站,当前页码{0},任务{1}", nPageIndex, webForm.currentTask.nID) });
webForm.currentTask.webState = EWebbrowserState.AccessSite;
Sleep(3000);
Point point_ele = GetPoint(eleCol[j]);
int nPos_y = 60;
webForm.webBrowser_new.Document.Window.ScrollTo(0, point_ele.Y - nPos_y);
int top2 = webForm.webBrowser_new.Document.GetElementsByTagName("HTML")[0].ScrollTop;//滚动条垂直位置
//KeyUtils.SetCursorPos(point_ele.X + nPos_x - 900, point_ele.Y + nPos_y - top2);
KeyUtils.SetCursorPos(point_ele.X + nPos_x, point_ele.Y + nPos_y - top2);
Sleep(3000);
webForm.currentTask.webState = EWebbrowserState.AccessSite;
KeyUtils.MouseLBUTTON();
this.taskIntervalTimer.Start();
return;
}
}
else if (!webForm.currentTask.strSiteUrl.Trim().Equals(""))
{
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("查找到符合的网站,当前页码{0},任务{1}", nPageIndex, webForm.currentTask.nID) });
webForm.currentTask.webState = EWebbrowserState.AccessSite;
Sleep(3000);
Point point_ele = GetPoint(eleCol[j]);
int nPos_y = 60;
webForm.webBrowser_new.Document.Window.ScrollTo(0, point_ele.Y - nPos_y);
int top2 = webForm.webBrowser_new.Document.GetElementsByTagName("HTML")[0].ScrollTop;//滚动条垂直位置
//KeyUtils.SetCursorPos(point_ele.X + nPos_x - 900, point_ele.Y + nPos_y - top2);
KeyUtils.SetCursorPos(point_ele.X + nPos_x, point_ele.Y + nPos_y - top2);
Sleep(3000);
webForm.currentTask.webState = EWebbrowserState.AccessSite;
KeyUtils.MouseLBUTTON();
this.taskIntervalTimer.Start();
return;
}
}
}
//当前搜索页未找到
//if (nItem == -1)
{
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("没有找到符合的网站,开始查找下一页,当前页码{0},任务{1}", nPageIndex, webForm.currentTask.nID) });
GetNextPageurl();
}
}
break;
}
}
}
}
}
public override void webBrowser_DocumentCompleted_AccessSite(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (e.Url.ToString().Equals("http://www.sogou.com/") || e.Url.ToString().Equals("https://www.sogou.com/"))
{
return;
}
//if (e.Url.ToString().Contains("so"))
//{
// return;
//}
webForm.textBox_url.Text = e.Url.ToString();
webForm.currentTask.webState = EWebbrowserState.none;
webForm.textBox_url.Text = e.Url.ToString();
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("进入网站,当前页码{0},任务{1}", 1, webForm.currentTask.nID) });
Sleep(5000);
switch (webForm.currentTask.pageAccessType)
{
case ePageAccessType.None:
{
EndTask(true);
}
break;
case ePageAccessType.Rand:
{
HtmlElementCollection aCol = webForm.webBrowser_new.Document.GetElementsByTagName("a");
if (aCol == null || aCol.Count == 0)
{
EndTask(true);
return;
}
Random ra = new Random(unchecked((int)DateTime.Now.Ticks));//保证产生的数字的随机性
int index = ra.Next() % aCol.Count;
index = (index >= aCol.Count) ? aCol.Count - 1 : index;
aCol[index].InvokeMember("click");
//if (aCol[index].GetAttribute("href") == null)
//{
// EndTask(true);
// break;
//}
//else
//{
// webForm.textBox_url.Text = aCol[index].GetAttribute("href");
// webForm.webBrowser_new.Navigate(aCol[index].GetAttribute("href"));
//}
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("访问内页{0}", aCol[index].GetAttribute("href")) });
webForm.currentTask.webState = EWebbrowserState.AccessPage;
this.taskIntervalTimer.Start();
}
break;
case ePageAccessType.Appoint:
{
HtmlElementCollection aCol = webForm.webBrowser_new.Document.GetElementsByTagName("a");
if (aCol == null || aCol.Count == 0)
{
EndTask(true);
return;
}
Random ra = new Random(unchecked((int)DateTime.Now.Ticks));//保证产生的数字的随机性
int index = ra.Next() % aCol.Count;
index = (index >= aCol.Count) ? aCol.Count - 1 : index;
for (int i = 0; i < aCol.Count; i++)
{
if (aCol[i].GetAttribute("href") == null)
{
EndTask(true);
continue;
}
else if(aCol[i].GetAttribute("href")== webForm.currentTask.strPageUrl)
{
aCol[i].InvokeMember("click");
break;
}
}
//if (aCol[index].GetAttribute("href") == null)
//{
// EndTask(true);
// break;
//}
//else
//{
// webForm.textBox_url.Text = aCol[index].GetAttribute("href");
// webForm.webBrowser_new.Navigate(aCol[index].GetAttribute("href"));
//}
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("访问内页{0}", webForm.currentTask.strPageUrl) });
webForm.currentTask.webState = EWebbrowserState.AccessPage;
this.taskIntervalTimer.Start();
}
break;
default:
break;
}
}
public override void webBrowser_DocumentCompleted_AccessPage(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webForm.textBox_url.Text = e.Url.ToString();
webForm.currentTask.webState = EWebbrowserState.none;
webForm.textBox_url.Text = e.Url.ToString();
Sleep(5000);
EndTask(true);
}
public override void GetNextPageurl()
{
HtmlElement ele_page;
ele_page = webForm.webBrowser_new.Document.GetElementById("pagebar_container");
if (ele_page == null)
{
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("只有一页,结束任务,当前页码{0},任务{1}", nPageIndex, webForm.currentTask.nID) });
EndTask(false);
}
nPageIndex += 1;
HtmlElementCollection eleCol = ele_page.GetElementsByTagName("a");
foreach (HtmlElement element in eleCol)
{
if (element.InnerText == nPageIndex.ToString())
{
webForm.currentTask.webState = EWebbrowserState.SearchSite;
Point point_ele = GetPoint(element);
webForm.webBrowser_new.Document.Window.ScrollTo(0, point_ele.Y);
int top = webForm.webBrowser_new.Document.GetElementsByTagName("HTML")[0].ScrollTop;//滚动条垂直位置
KeyUtils.SetCursorPos(point_ele.X + nPos_x, point_ele.Y + nPos_y - top);
Sleep(3000);
KeyUtils.MouseLBUTTON();
this.taskIntervalTimer.Start();
return;
}
}
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("已经是最后一页,结束任务,当前页码{0},任务{1}", nPageIndex, webForm.currentTask.nID) });
Sleep(5000);
EndTask(false);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RankHelperService
{
class Appinfo
{
public static string strVersion = "1.0";
public static string strTitleName = "流量精灵助手";
public static string strTitleName_en = "RankHelper.exe";
public static string strServiceVersion = "1.0";
public static string strServiceTitleName = "流量精灵助手监控器";
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace RankHelper
{
public class LogHelper
{
public static void InitLog4Net()
{
//log4net.Config.XmlConfigurator.Configure();
var configFile = new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log4net.config"));
log4net.Config.XmlConfigurator.ConfigureAndWatch(configFile);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Windows.Forms;
namespace RankHelper
{
class AppUtils
{
[DllImport("User32.dll", EntryPoint = "FindWindow")]
public static extern int FindWindow(string lpClassName, string lpWindowName);
[DllImport("User32.dll", EntryPoint = "FindWindowEx")]
public static extern int FindWindowEx(IntPtr lpClassName, IntPtr lpWindowName, string isnull, string anniu);
[DllImport("user32.dll", EntryPoint = "SendMessageA")]
public static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
[DllImport("shell32.dll")]
public static extern int ShellExecute(IntPtr hwnd, StringBuilder lpszOp, StringBuilder lpszFile, StringBuilder lpszParams, StringBuilder lpszDir, int FsShowCmd);
[System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
public static extern bool SetForegroundWindow(IntPtr hWnd);//设置此窗体为活动窗体
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int y, int Width, int Height, int flags);// 得到当前活动的窗口
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern System.IntPtr GetForegroundWindow();
[DllImport("user32.dll",CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetWindow(HandleRef hWnd, int nCmd);
[DllImport("user32.dll")]
public static extern IntPtr SetParent(IntPtr child, IntPtr parent);
[DllImport("user32.dll", EntryPoint = "GetDCEx",CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetDCEx(IntPtr hWnd, IntPtr hrgnClip, int flags);
[DllImport("user32.dll",CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern bool SetWindowPos(HandleRef hWnd, HandleRef hWndInsertAfter, int x, int y, int cx, int cy, int flags);
[DllImport("user32.dll")]
public static extern int ReleaseDC(IntPtr window, IntPtr handle);
[System.Runtime.InteropServices.DllImport("user32", EntryPoint = "SetForegroundWindow")]
public static extern bool SetFocus(IntPtr hWnd);//设置此窗体为活动窗体
const int WM_CLOSE = 0x10; //关闭
const uint WM_DESTROY = 0x02;
const uint WM_QUIT = 0x12;
public static void CloseOtherApp(string appName)
{
IntPtr Window_Handle = (IntPtr)FindWindow(null, appName);//查找所有的窗体,看看想查找的句柄是否存在,Microsoft Word 句柄 //
if (Window_Handle == IntPtr.Zero) //如果没有查找到相应的句柄
{
}
else //查找到相应的句柄
{
SendMessage(Window_Handle, WM_CLOSE, 0, 0); //关闭窗体
}
}
public static void CloseExternalApp(string appName)
{
IntPtr Window_Handle = (IntPtr)FindWindow(null, appName);//查找所有的窗体,看看想查找的句柄是否存在,Microsoft Word 句柄 //
if (Window_Handle == IntPtr.Zero) //如果没有查找到相应的句柄
{
}
else //查找到相应的句柄
{
SendMessage(Window_Handle, WM_CLOSE, 0, 0); //关闭窗体
}
}
public static int OpenExternalApp(string appName)
{
return 0;
AppUtils.CloseOtherApp("流量精灵助手监控器");
int nResult = ShellExecute(IntPtr.Zero, new StringBuilder("Open"), new StringBuilder(appName), new StringBuilder(""), new StringBuilder(System.Environment.CurrentDirectory), 1);
return nResult;
}
// <summary>
// 修改程序在注册表中的键值
// </summary>
// <param name="isAuto">true:开机启动,false:不开机自启</param>
public static void AutoStart(bool isAuto)
{
try
{
if (isAuto == true)
{
RegistryKey R_local = Registry.LocalMachine;//RegistryKey R_local = Registry.CurrentUser;
RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Run");
//R_run.SetValue("RankHelperService", Application.ExecutablePath);
R_run.SetValue("RankHelperService", string.Format("{0}\\RankHelperService.exe", System.Environment.CurrentDirectory));
R_run.Close();
RegistryKey R_run2 = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
//R_run.SetValue("RankHelperService", Application.ExecutablePath);
R_run2.SetValue("RankHelperService", string.Format("{0}\\RankHelperService.exe", System.Environment.CurrentDirectory));
R_run2.Close();
R_local.Close();
}
else
{
RegistryKey R_local = Registry.LocalMachine;//RegistryKey R_local = Registry.CurrentUser;
RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Run");
R_run.DeleteValue("RankHelperService", false);
R_run.Close();
RegistryKey R_run2 = R_local.CreateSubKey(@"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Run");
R_run2.DeleteValue("RankHelperService", false);
R_run2.Close();
R_run2.Close();
R_local.Close();
}
//GlobalVariant.Instance.UserConfig.AutoStart = isAuto;
}
catch (Exception)
{
//MessageBoxDlg dlg = new MessageBoxDlg();
//dlg.InitialData("您需要管理员权限修改", "提示", MessageBoxButtons.OK, MessageBoxDlgIcon.Error);
//dlg.ShowDialog();
MessageBox.Show("您需要管理员权限修改!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using mshtml;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Drawing;
namespace RankHelper
{
public class Sm : WebBase
{
public Sm(WebForm webForm, string strPageurl, string strhtml):base(webForm, strPageurl, strhtml)
{
webForm.webBrowser_new.Navigate("www.m.sm.cn");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CefSharp;
using System.IO;
namespace RankHelper
{
public class RequestHandler : CefSharp.Handler.DefaultRequestHandler //CefSharp.Example.Handlers
{
public string _directory = "DownloadFile/";
private Dictionary<UInt64, MemoryStreamResponseFilter> responseDictionary = new Dictionary<UInt64, MemoryStreamResponseFilter>();
public IRequestHandler _requestHeandler;
public RequestHandler(IRequestHandler rh) : base()
{
_requestHeandler = rh;
}
public override CefReturnValue OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback)
{
if (request.ResourceType == ResourceType.MainFrame)
{
var headers = request.Headers;
headers["User-Agent"] = Appinfo.strUserAgent;
request.Headers = headers;
}
return CefReturnValue.Continue;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using DotRas;
using System.Collections.ObjectModel;
using System.Net;
namespace RankHelper
{
class NetworkUtils
{
/// <summary>
/// 获取本地IP地址信息
/// </summary>
//public static string GetIpAddress()
//{
// string hostName = Dns.GetHostName(); //获取本机名
// IPHostEntry localhost = Dns.GetHostByName(hostName); //方法已过期,可以获取IPv4的地址
// //IPHostEntry localhost = Dns.GetHostEntry(hostName); //获取IPv6地址
// IPAddress localaddr = localhost.AddressList[0];
// return localaddr.ToString();
//}
public static string GetIpAddress()
{
foreach (RasConnection connection in RasConnection.GetActiveConnections())
{
RasIPInfo ipAddresses = (RasIPInfo)connection.GetProjectionInfo(RasProjectionType.IP);
if (ipAddresses != null)
{
return ipAddresses.IPAddress.ToString();
}
}
return "";
}
}
}
<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 CefSharp.WinForms;
namespace RankHelper
{
public partial class CefTestForm : Form
{
private readonly ChromiumWebBrowser browser;
public CefTestForm()
{
InitializeComponent();
//browser = new ChromiumWebBrowser("https://ie.icoa.cn/")
browser = new ChromiumWebBrowser("www.jianshu.com")
{
Dock = DockStyle.Fill,
};
this.Controls.Add(browser);
}
~CefTestForm()
{
browser.Dispose();
}
}
}
<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.Runtime.InteropServices;
namespace RankHelperService
{
public partial class MainForm : Form
{
[DllImport("User32.dll", EntryPoint = "FindWindow")]
private static extern int FindWindow(string lpClassName, string lpWindowName);
[DllImport("User32.dll", EntryPoint = "FindWindowEx")]
private static extern int FindWindowEx(IntPtr lpClassName, IntPtr lpWindowName, string isnull, string anniu);
[DllImport("shell32.dll")]
public static extern int ShellExecute(IntPtr hwnd, StringBuilder lpszOp, StringBuilder lpszFile, StringBuilder lpszParams, StringBuilder lpszDir, int FsShowCmd);
private System.Timers.Timer monitorTimer;
public MainForm()
{
InitializeComponent();
InitNotifyIcon();
Init();
InitTimer();
}
public void Init()
{
//设置标题
this.Text = string.Format("{0}", Appinfo.strServiceTitleName, Appinfo.strServiceVersion);
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.Hide();
this.ShowInTaskbar = false;
}
public void InitNotifyIcon()
{
//设置标题
notifyIcon.Text = string.Format("{0}监控程序,开始挂机将会自动运行,完成一个任务或者{0}停止运行将会自动重启,停止挂机自动停止监控", Appinfo.strTitleName);
notifyIcon.BalloonTipTitle = string.Format("{0}", Appinfo.strServiceTitleName);
notifyIcon.BalloonTipText = string.Format("开始挂机将会自动运行,完成一个任务或者{0}停止运行将会自动重启,停止挂机自动停止监控", Appinfo.strTitleName);
}
void InitTimer()
{
this.monitorTimer = new System.Timers.Timer();
this.monitorTimer.Elapsed += MonitorTimer_Elapsed;
this.monitorTimer.AutoReset = true;
this.monitorTimer.Interval = 1000 * 10 * 1;//1000 * 60 * 1;
this.monitorTimer.Enabled = true;
}
private void MonitorTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
IntPtr Window_Handle = (IntPtr)FindWindow(null, Appinfo.strTitleName);//查找所有的窗体,看看想查找的句柄是否存在,Microsoft Word 句柄 //
if (Window_Handle == IntPtr.Zero) //如果没有查找到相应的句柄
{
if(OpenExternalApp("RankHelper.exe") == 42)
{
notifyIcon.BalloonTipText = string.Format("开始运行{0}", Appinfo.strTitleName);
notifyIcon.ShowBalloonTip(30000);
}
else if (OpenExternalApp("RankHelper") == 42)
{
notifyIcon.BalloonTipText = string.Format("开始运行{0}", Appinfo.strTitleName);
notifyIcon.ShowBalloonTip(30000);
}
}
}
public int OpenExternalApp(string appName)
{
string fileName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
int index = fileName.LastIndexOf("\\");
string filePath = fileName.Substring(0, index);
int nResult = ShellExecute(IntPtr.Zero, new StringBuilder("Open"), new StringBuilder(appName), new StringBuilder("Work"), new StringBuilder(filePath), 1);
notifyIcon.BalloonTipText = string.Format("启动{0}状态{1}", Appinfo.strTitleName, nResult);
notifyIcon.ShowBalloonTip(30000);
return nResult;
}
private void MainForm_Resize(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized) //最小化到系统托盘
{
if (!notifyIcon.BalloonTipText.Equals(""))
{
notifyIcon.Visible = true; //显示托盘图标
notifyIcon.ShowBalloonTip(30000);
}
this.Hide(); //隐藏窗口
}
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
//注意判断关闭事件Reason来源于窗体按钮,否则用菜单退出时无法退出!
//if (e.CloseReason == CloseReason.UserClosing)
//{
// e.Cancel = true; //取消"关闭窗口"事件
// this.WindowState = FormWindowState.Minimized; //使关闭时窗口向右下角缩小的效果
// notifyIcon.Visible = true;
// this.Hide();
// return;
//}
notifyIcon.Visible = false;
}
private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
{
}
private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
{
notifyIcon.Visible = false;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RankHelper
{
class TypeUtils
{
public static int BoolToInt(object obj)
{
if (Convert.ToBoolean(obj) == true)
return 1;
else
return 0;
}
// 整型转换为布尔类型
public static bool IntToBool(object obj)
{
if (Convert.ToInt32(obj) == 1)
return true;
else
return false;
}
}
}
<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 AsyncCall;
using log4net;
using System.Timers;
using DotRas;
using System.Collections.ObjectModel;
using System.Net;
namespace RankHelper
{
public partial class StatisticsForm : Form
{
private static ILog Logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
AsyncEvent.MyAsyncDelegate<int> del;
public event EventHandler StartTaskEvent; //使用默认的事件处理委托
public event EventHandler StopTaskEvent;
public event EventHandler ChangeTaskEvent;
public event EventHandler ShowTaskEvent;
public event EventHandler ShowIPEvent;
private System.Timers.Timer taskTimer;
private System.Timers.Timer taskIntervalTimer;
private System.Timers.Timer showTaskTimer;
private System.Timers.Timer resetTaskTimer;
private System.Timers.Timer CheckIntervalTimer;
private DateTime lastDate;
public bool bWork { get; private set; }
bool bExecuteTask = false;
tagTask LastTask = new tagTask();
//数据库文件路径
private string dbPath;
public StatisticsForm()
{
InitializeComponent();
Init();
InitDB();
InitTimer();
InitTask();
}
void Init()
{
this.listView_statistics.GridLines = true; //显示表格线
this.listView_statistics.View = View.Details;//显示表格细节
//this.listView_statistics.LabelEdit = true; //是否可编辑,ListView只可编辑第一列。
this.listView_statistics.Scrollable = true;//有滚动条
this.listView_statistics.HeaderStyle = ColumnHeaderStyle.Nonclickable;//对表头进行设置
this.listView_statistics.FullRowSelect = true;//是否可以选择行
//this.listView_statistics.CheckBoxes = true;
//添加表头
//this.listView_statistics.Columns.Add("", 0);
this.listView_statistics.Columns.Add("选择", 60);//0
this.listView_statistics.Columns.Add("编号", 60);//1
this.listView_statistics.Columns.Add("关键字", 110);//2
this.listView_statistics.Columns.Add("网站标题", 110);//3
this.listView_statistics.Columns.Add("网站链接", 110);//4
this.listView_statistics.Columns.Add("搜索引擎", 110);//5
this.listView_statistics.Columns.Add("搜索引擎停留时间", 110);//6
this.listView_statistics.Columns.Add("站内地址", 110);//7
this.listView_statistics.Columns.Add("搜索页码", 110);//8
this.listView_statistics.Columns.Add("浏览器", 110);//9
this.listView_statistics.Columns.Add("今天有效流量", 110);//10
this.listView_statistics.Columns.Add("今天无效流量", 110);//11
this.listView_statistics.Columns.Add("总流量", 110);//12
this.listView_statistics.Columns.Add("今天执行次数", 110);//13
this.listView_statistics.Columns.Add("日限制", 110);//14
this.listView_statistics.Columns.Add("首页停留时间", 110);//15
this.listView_statistics.Columns.Add("上次访问时间", 110);//16
this.listView_statistics.Columns.Add("今天内页有效流量", 110);//17
this.listView_statistics.Columns.Add("今天内页无效流量", 130);//18
this.listView_statistics.Columns.Add("内页总流量", 110);//19
this.listView_statistics.Columns.Add("内页停留时间", 110);//20
this.listView_statistics.Columns.Add("上次访问时间", 110);//21
this.listView_statistics.Columns.Add("发布时间", 110);//22
//添加各项
//ListViewItem[] p = new ListViewItem[2];
//p[0] = new ListViewItem(new string[] { "", "aaaa", "bbbb" });
//this.listView_statistics.Items.AddRange(p);
this.listView_statistics.Scrollable = true;
}
void InitDB()
{
//数据库文件路径就在运行目录下
dbPath = $"{Environment.CurrentDirectory}\\task.db";
}
void InitTimer()
{
this.taskTimer = new System.Timers.Timer();
this.taskTimer.Elapsed += new System.Timers.ElapsedEventHandler(taskTimer_Elapsed);
this.taskTimer.AutoReset = true;
this.taskTimer.Interval = 1000 * 60 * 5;
this.taskTimer.Enabled = false;
this.taskIntervalTimer = new System.Timers.Timer();
this.taskIntervalTimer.Elapsed += new System.Timers.ElapsedEventHandler(taskIntervalTimer_Elapsed);
this.taskIntervalTimer.AutoReset = true;
this.taskIntervalTimer.Interval = 1000 * 60 * 1;
this.taskIntervalTimer.Enabled = false;
this.showTaskTimer = new System.Timers.Timer();
this.showTaskTimer.Elapsed += new System.Timers.ElapsedEventHandler(showTaskTimer_Elapsed);
this.showTaskTimer.AutoReset = true;
this.showTaskTimer.Interval = 1000 * 5;
this.showTaskTimer.Enabled = false;
this.resetTaskTimer = new System.Timers.Timer();
this.resetTaskTimer.Elapsed += new System.Timers.ElapsedEventHandler(resetTaskTimer_Elapsed);
this.resetTaskTimer.AutoReset = true;
this.resetTaskTimer.Interval = 1000 * 60;
this.resetTaskTimer.Enabled = false;
this.resetTaskTimer.Start();
this.CheckIntervalTimer = new System.Timers.Timer();
this.CheckIntervalTimer.Elapsed += CheckIntervalTimer_Elapsed;
this.CheckIntervalTimer.AutoReset = true;
this.CheckIntervalTimer.Interval = 1000 * 5;
this.CheckIntervalTimer.Enabled = false;
this.CheckIntervalTimer.SynchronizingObject = this;
this.timer_checkbox.Interval = 1000 * 3;
this.timer_checkbox.Enabled = false;
this.timer_checkbox.Tick += Timer_checkbox_Tick;
lastDate = DateTime.Now;
}
internal void CheckWork(object sender, EventArgs e)
{
checkBox_work.Checked = true;
}
void InitTask()
{
button_wait.Hide();
bWork = false;
del = new AsyncEvent.MyAsyncDelegate<int>(DoAsyncEvent);
}
void AddTask(tagTask task)
{
//ListViewItem[] item = new ListViewItem[1];
//item[0] = new string[] { "", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
//this.listView_statistics.Items.AddRange(item);
string[] arrayTask = new string[23];
string strCheck = task.bCheck ? "启用" : "未启用";
arrayTask = new string[] {
strCheck,//0
task.nID.ToString(),//1
task.strKeyword,//2
task.strTitle,//3
task.strSiteUrl,//4
define.GetEnumName(task.engine),//5
task.nEngineTime.ToString(),//6
define.GetEnumName(task.pageAccessType),//7
task.nCountPage.ToString(),//8
define.GetEnumName(task.webBrowser),//9
task.nCountVaildToday.ToString(),//10
task.nCountInvaildToday.ToString(),//11
task.nCountTotal.ToString(),//12
task.nCountExcuteToday.ToString(),//13
task.nCountLimit.ToString(),//14
task.nSiteTime.ToString(),//15
task.tViewSiteLastTime.ToString(),//16
task.nCountPageVaildToday.ToString(),//17
task.nCountInvaildToday.ToString(),//18
task.nCountPageTotal.ToString(),//19
task.nPageTime.ToString(),//20
"21",//21
"22"//22
};
ListViewItem item = new ListViewItem(arrayTask);
this.listView_statistics.Items.Add(item);
for (int i = 0; i < this.listView_statistics.CheckedItems.Count; i++)
{
this.listView_statistics.CheckedItems[i].Checked = true;
//this.listView_statistics.CheckedItems[i].Selected = false;
}
}
void ChangeTask(tagTask task)
{
for (int i = 0; i < this.listView_statistics.Items.Count; i++)
{
string strID = this.listView_statistics.Items[i].SubItems[1].Text; //用我们刚取到的index取被选中的某一列的值从0开始
if (strID == task.nID.ToString())
{
string strCheck = task.bCheck ? "启用" : "未启用";
this.listView_statistics.Items[i].SubItems[0].Text = strCheck;
this.listView_statistics.Items[i].SubItems[2].Text = task.strKeyword;
this.listView_statistics.Items[i].SubItems[3].Text = task.strTitle;
this.listView_statistics.Items[i].SubItems[4].Text = task.strSiteUrl;
this.listView_statistics.Items[i].SubItems[5].Text = define.GetEnumName(task.engine);
this.listView_statistics.Items[i].SubItems[7].Text = define.GetEnumName(task.pageAccessType);
this.listView_statistics.Items[i].SubItems[8].Text = task.nCountPage.ToString();
this.listView_statistics.Items[i].SubItems[9].Text = define.GetEnumName(task.webBrowser);
this.listView_statistics.Items[i].SubItems[13].Text = task.nCountExcuteToday.ToString();
this.listView_statistics.Items[i].SubItems[14].Text = task.nCountLimit.ToString();
break;
}
}
}
void DeleteTask(tagTask task)
{
bool bFind = false;
for (int i = 0; i < this.listView_statistics.Items.Count; i++)
{
string strID = this.listView_statistics.Items[i].SubItems[1].Text; //用我们刚取到的index取被选中的某一列的值从0开始
if (strID == task.nID.ToString())
{
this.listView_statistics.Items[i].Remove();
bFind = true;
break;
}
}
}
void CountTask(tagTask task)
{
for (int i = 0; i < this.listView_statistics.Items.Count; i++)
{
string strID = this.listView_statistics.Items[i].SubItems[1].Text; //用我们刚取到的index取被选中的某一列的值从0开始
if (strID == task.nID.ToString())
{
this.listView_statistics.Items[i].SubItems[10].Text = task.nCountVaildToday.ToString();
this.listView_statistics.Items[i].SubItems[11].Text = task.nCountInvaildToday.ToString();
this.listView_statistics.Items[i].SubItems[12].Text = task.nCountTotal.ToString();
this.listView_statistics.Items[i].SubItems[13].Text = task.nCountExcuteToday.ToString();
this.listView_statistics.Items[i].SubItems[17].Text = task.nCountPageVaildToday.ToString();
this.listView_statistics.Items[i].SubItems[18].Text = task.nCountPageInvaildToday.ToString();
this.listView_statistics.Items[i].SubItems[19].Text = task.nCountPageTotal.ToString();
break;
}
}
}
internal void RefreshStatistics(object sender, EventArgs e)
{
AppEventArgs arg = e as AppEventArgs;
switch (arg.message_task.taskAcion)
{
case eTaskAcion.Add:
{
AddTask(arg.message_task);
arg.message_task.taskAcion = eTaskAcion.Change;
}
break;
case eTaskAcion.Change:
{
ChangeTask(arg.message_task);
}
break;
case eTaskAcion.Delete:
{
DeleteTask(arg.message_task);
}
break;
default:
break;
}
}
internal void RefreshStatisticsAll(object sender, EventArgs e)
{
foreach (var task in Appinfo.listTask)
{
AddTask(task);
}
}
private void checkBox_work_CheckedChanged(object sender, EventArgs e)
{
tagSetting setting = Appinfo.QuerySetting();
if (setting.strUsername.Trim().Equals("")|| setting.strPwd.Trim().Equals(""))
{
MessageBox.Show("ADSL拨号未设置账号密码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
if (!checkBox_work.Checked)
{
checkBox_work.Text = "开始挂机";
AppUtils.CloseOtherApp("流量精灵助手监控器");
}
else
{
checkBox_work.Text = "停止挂机";
if (AppUtils.OpenExternalApp("RankHelperService.exe") ==42)
{
}
else if (AppUtils.OpenExternalApp("RankHelperService") == 42)
{
}
}
DoAsyncEvent();
//IAsyncResult result = del.BeginInvoke(new AsyncCallback(CallBack), null);
}
/// <summary>
/// 回调函数得到异步线程的返回结果
/// </summary>
/// <param name="iasync"></param>
public void CallBack(IAsyncResult iasync)
{
if (AsyncEvent.CallBack<int>(iasync) > 0)
{
//MessageBox.Show("成功");
}
}
/// <summary>
/// 执行方法
/// </summary>
/// <returns></returns>
private int DoAsyncEvent()
{
try
{
//foreach (var item in Appinfo.listTask)
//{
// if (item.nID.Equals(nTaskID))
// {
// return item;
// }
//}
this.taskTimer.Stop();
this.taskIntervalTimer.Stop();
this.showTaskTimer.Stop();
//停止挂机
if (!checkBox_work.Checked)
{
bWork = false;
bExecuteTask = false;
StopTaskEvent(this, new AppEventArgs() { });
ShowTaskEvent(this, new AppEventArgs() { message_string = "未开始挂机" });
}
else
{
bWork = true;
bExecuteTask = false;
//删除缓存、cookie文件
//FileUtils.DeleteFolder(System.Environment.CurrentDirectory+"\\"+ "BrowserCache");
//清除缓存
string cachePath = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);
//获取缓存路径
//DirectoryInfo di = new DirectoryInfo(cachePath);
//foreach (FileInfo fi in di.GetFiles("*.*", SearchOption.AllDirectories))//遍历所有的文件夹 删除里面的文件
//{
// try
// {
// fi.Delete();
// }
// catch
// {
// }
//}
//BrowserUtils.ClearCache();
ShowTaskEvent(this, new AppEventArgs() { message_string = "删除缓存、cookie文件......" });
System.Threading.Thread.Sleep(5000);
ShowTaskEvent(this, new AppEventArgs() { message_string = "删除完成" });
//更换IP
if (!Appinfo.GetIP().Equals(NetworkUtils.GetIpAddress())|| Appinfo.GetIP().Equals(""))
{
ShowTaskEvent(this, new AppEventArgs() { message_string = "更换IP" });
//this.taskIntervalTimer.Start();
//return -1;
Disconnect();
string msg = null;
tagSetting setting = Appinfo.QuerySetting();
bool isok = Connect(define.GetEnumName(setting.connectionType), setting.strUsername.ToString(), setting.strPwd.ToString(), ref msg);
ShowIPEvent(this, new AppEventArgs() { });
}
bool bNewTurn = false;
foreach (var task in Appinfo.listTask)
{
if (LastTask != null && LastTask.nID == Appinfo.listTask[Appinfo.listTask.Count - 1].nID)
{
bNewTurn = true;
}
}
foreach (var task in Appinfo.listTask)
{
//每轮任务顺序执行
if (!task.bCheck)
{
continue;
}
if (!bNewTurn && task.nID <= LastTask.nID)
{
continue;
}
if (task.nCountExcuteToday >= task.nCountLimit)
{
continue;
}
//todo 执行时间检查
int nCount = 0;
int nCountExcute = 0;
switch (DateTime.Now.Hour)
{
case 0:
{
nCount = task.tagtempleTime.nCount00;
nCountExcute = task.tagtempleTime.nCount00_Excute;
}
break;
case 1:
{
nCount = task.tagtempleTime.nCount01;
nCountExcute = task.tagtempleTime.nCount01_Excute;
}
break;
case 2:
{
nCount = task.tagtempleTime.nCount02;
nCountExcute = task.tagtempleTime.nCount02_Excute;
}
break;
case 3:
{
nCount = task.tagtempleTime.nCount03;
nCountExcute = task.tagtempleTime.nCount03_Excute;
}
break;
case 4:
{
nCount = task.tagtempleTime.nCount04;
nCountExcute = task.tagtempleTime.nCount04_Excute;
}
break;
case 5:
{
nCount = task.tagtempleTime.nCount05;
nCountExcute = task.tagtempleTime.nCount05_Excute;
}
break;
case 6:
{
nCount = task.tagtempleTime.nCount06;
nCountExcute = task.tagtempleTime.nCount06_Excute;
}
break;
case 7:
{
nCount = task.tagtempleTime.nCount07;
nCountExcute = task.tagtempleTime.nCount07_Excute;
}
break;
case 8:
{
nCount = task.tagtempleTime.nCount08;
nCountExcute = task.tagtempleTime.nCount08_Excute;
}
break;
case 9:
{
nCount = task.tagtempleTime.nCount09;
nCountExcute = task.tagtempleTime.nCount09_Excute;
}
break;
case 10:
{
nCount = task.tagtempleTime.nCount10;
nCountExcute = task.tagtempleTime.nCount10_Excute;
}
break;
case 11:
{
nCount = task.tagtempleTime.nCount11;
nCountExcute = task.tagtempleTime.nCount11_Excute;
}
break;
case 12:
{
nCount = task.tagtempleTime.nCount12;
nCountExcute = task.tagtempleTime.nCount12_Excute;
}
break;
case 13:
{
nCount = task.tagtempleTime.nCount13;
nCountExcute = task.tagtempleTime.nCount13_Excute;
}
break;
case 14:
{
nCount = task.tagtempleTime.nCount14;
nCountExcute = task.tagtempleTime.nCount14_Excute;
}
break;
case 15:
{
nCount = task.tagtempleTime.nCount15;
nCountExcute = task.tagtempleTime.nCount15_Excute;
}
break;
case 16:
{
nCount = task.tagtempleTime.nCount16;
nCountExcute = task.tagtempleTime.nCount16_Excute;
}
break;
case 17:
{
nCount = task.tagtempleTime.nCount17;
nCountExcute = task.tagtempleTime.nCount17_Excute;
}
break;
case 18:
{
nCount = task.tagtempleTime.nCount18;
nCountExcute = task.tagtempleTime.nCount18_Excute;
}
break;
case 19:
{
nCount = task.tagtempleTime.nCount19;
nCountExcute = task.tagtempleTime.nCount19_Excute;
}
break;
case 20:
{
nCount = task.tagtempleTime.nCount20;
nCountExcute = task.tagtempleTime.nCount20_Excute;
}
break;
case 21:
{
nCount = task.tagtempleTime.nCount21;
nCountExcute = task.tagtempleTime.nCount21_Excute;
}
break;
case 22:
{
nCount = task.tagtempleTime.nCount22;
nCountExcute = task.tagtempleTime.nCount22_Excute;
}
break;
case 23:
{
nCount = task.tagtempleTime.nCount23;
nCountExcute = task.tagtempleTime.nCount23_Excute;
}
break;
default: break;
}
if (nCountExcute >= nCount)
{
continue;
}
LastTask.nID = task.nID;
bExecuteTask = true;
StartTaskEvent(this, new AppEventArgs() { message_task = task });
this.taskTimer.Start();
return 1;
}
this.taskIntervalTimer.Start();
this.showTaskTimer.Start();
ShowTaskEvent(this, new AppEventArgs() { message_string = "未找到可以执行的任务,1分钟后开始查找下一个任务" });
}
return 1;
}
catch (Exception e)
{
Logger.Info(string.Format("方法DoAsyncEvent: "), e);
return -1;
}
}
private void listView_statistics_DoubleClick(object sender, EventArgs e)
{
ListView listView = sender as ListView;
if (listView.SelectedItems.Count > 0) //判断listview有被选中项
{
int nIndex = listView.SelectedItems[0].Index; //取当前选中项的index,SelectedItems[0]这必须为0
string strID = listView.Items[nIndex].SubItems[1].Text; //用我们刚取到的index取被选中的某一列的值从0开始
tagTask task = Appinfo.QueryTask(int.Parse(strID));
if (task != null)
{
task.taskAcion = eTaskAcion.Change;
ChangeTaskEvent(this, new AppEventArgs() { message_task = task });
}
else
{
MessageBox.Show("打开任务失败", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
else
{
MessageBox.Show("选择一项任务", "警告", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
}
}
//taskTimer定时器执行的任务
private void taskTimer_Elapsed(object sender, ElapsedEventArgs e)
{
this.taskTimer.Stop();
if (bWork)
{
//停止当前任务
if (bExecuteTask)
{
bExecuteTask = false;
StopTaskEvent(this, new AppEventArgs() { });
ShowTaskEvent(this, new AppEventArgs() { message_string = "限定时间内未完成当前任务,开始执行下一个任务" });
IAsyncResult result = del.BeginInvoke(new AsyncCallback(CallBack), null);
}
else
{
//ChangeTaskEvent(this, new AppEventArgs() { message_string = "开始执行下一个任务" });
}
}
}
private void taskIntervalTimer_Elapsed(object sender, ElapsedEventArgs e)
{
this.taskIntervalTimer.Stop();
if (bWork)
{
ShowTaskEvent(this, new AppEventArgs() { message_string = "开始查找下一个任务" });
IAsyncResult result = del.BeginInvoke(new AsyncCallback(CallBack), null);
}
}
private void showTaskTimer_Elapsed(object sender, ElapsedEventArgs e)
{
this.showTaskTimer.Stop();
ShowTaskEvent(this, new AppEventArgs() { message_string = "开始挂机,当前状态空闲" });
}
private void resetTaskTimer_Elapsed(object sender, ElapsedEventArgs e)
{
if (DateTime.Now.Hour == 0 && DateTime.Now.Minute >= 0 && DateTime.Now.Minute <= 5)
{
if (lastDate.ToString("yyyy-MM-dd").Equals(DateTime.Now.ToString("yyyy-MM-dd")))
{
return;
}
else
{
resetTaskTimer.Stop();
lastDate = DateTime.Now;
for (int i = 0; i < Appinfo.listTask.Count; i++)
{
Appinfo.listTask[i].nCountExcuteToday = 0;
Appinfo.listTask[i].tagtempleTime.nCount00_Excute = 0;
Appinfo.listTask[i].tagtempleTime.nCount01_Excute = 0;
Appinfo.listTask[i].tagtempleTime.nCount02_Excute = 0;
Appinfo.listTask[i].tagtempleTime.nCount03_Excute = 0;
Appinfo.listTask[i].tagtempleTime.nCount04_Excute = 0;
Appinfo.listTask[i].tagtempleTime.nCount05_Excute = 0;
Appinfo.listTask[i].tagtempleTime.nCount06_Excute = 0;
Appinfo.listTask[i].tagtempleTime.nCount07_Excute = 0;
Appinfo.listTask[i].tagtempleTime.nCount08_Excute = 0;
Appinfo.listTask[i].tagtempleTime.nCount09_Excute = 0;
Appinfo.listTask[i].tagtempleTime.nCount10_Excute = 0;
Appinfo.listTask[i].tagtempleTime.nCount11_Excute = 0;
Appinfo.listTask[i].tagtempleTime.nCount12_Excute = 0;
Appinfo.listTask[i].tagtempleTime.nCount13_Excute = 0;
Appinfo.listTask[i].tagtempleTime.nCount14_Excute = 0;
Appinfo.listTask[i].tagtempleTime.nCount15_Excute = 0;
Appinfo.listTask[i].tagtempleTime.nCount16_Excute = 0;
Appinfo.listTask[i].tagtempleTime.nCount17_Excute = 0;
Appinfo.listTask[i].tagtempleTime.nCount18_Excute = 0;
Appinfo.listTask[i].tagtempleTime.nCount19_Excute = 0;
Appinfo.listTask[i].tagtempleTime.nCount20_Excute = 0;
Appinfo.listTask[i].tagtempleTime.nCount21_Excute = 0;
Appinfo.listTask[i].tagtempleTime.nCount22_Excute = 0;
Appinfo.listTask[i].tagtempleTime.nCount23_Excute = 0;
}
ShowTaskEvent(this, new AppEventArgs() { message_string = "0点开始执行当天任务" });
resetTaskTimer.Start();
}
}
}
internal void EndTask(object sender, EventArgs e)
{
AppEventArgs arg = e as AppEventArgs;
for (int i = 0; i < Appinfo.listTask.Count; i++)
{
if (arg.message_task.nID == Appinfo.listTask[i].nID)
{
switch (arg.message_task.webState)
{
case EWebbrowserState.Start:
{
}
break;
case EWebbrowserState.Search:
{
}
break;
case EWebbrowserState.SearchSite:
{
Appinfo.listTask[i].nCountExcuteToday += 1;
AddExcuteCount(Appinfo.listTask[i]);
if (arg.message_bool)
{
Appinfo.listTask[i].nCountVaildToday += 1;
}
else
{
Appinfo.listTask[i].nCountInvaildToday += 1;
ShowTaskEvent(this, new AppEventArgs() { message_string = string.Format("未在搜索引擎找到符合的标题或链接,结束该任务,任务{0}", Appinfo.listTask[i].nID) });
}
Appinfo.listTask[i].nCountTotal += 1;
Appinfo.UpdateIP(NetworkUtils.GetIpAddress());
bExecuteTask = false;
}
break;
case EWebbrowserState.AccessSite:
{
Appinfo.listTask[i].nCountExcuteToday += 1;
Appinfo.listTask[i].nCountVaildToday += 1;
AddExcuteCount(Appinfo.listTask[i]);
Appinfo.listTask[i].nCountTotal += 1;
Appinfo.UpdateIP(NetworkUtils.GetIpAddress());
bExecuteTask = false;
}
break;
case EWebbrowserState.AccessPage:
{
Appinfo.listTask[i].nCountExcuteToday += 1;
Appinfo.listTask[i].nCountVaildToday += 1;
Appinfo.listTask[i].nCountTotal += 1;
if (arg.message_task.pageAccessType == ePageAccessType.None)
{
}
else
{
if (arg.message_bool)
{
Appinfo.listTask[i].nCountPageVaildToday += 1;
ShowTaskEvent(this, new AppEventArgs() { message_string = string.Format("访问内页成功,结束该任务,任务{0}", Appinfo.listTask[i].nID) });
Appinfo.listTask[i].nCountPageTotal += 1;
}
else
{
Appinfo.listTask[i].nCountPageInvaildToday += 1;
Appinfo.listTask[i].nCountPageTotal += 1;
ShowTaskEvent(this, new AppEventArgs() { message_string = string.Format("未找到符合的内页,结束该任务,任务{0}", Appinfo.listTask[i].nID) });
}
}
bExecuteTask = false;
}
break;
default:
break;
}
Appinfo.CountTask(Appinfo.listTask[i]);
//执行完成一个任务关闭程序
System.Environment.Exit(0);
break;
}
}
}
internal void AddExcuteCount(tagTask task)
{
switch (DateTime.Now.Hour)
{
case 0:
{
task.tagtempleTime.nCount00+=1;
}
break;
case 1:
{
task.tagtempleTime.nCount01 += 1;
}
break;
case 2:
{
task.tagtempleTime.nCount02 += 1;
}
break;
case 3:
{
task.tagtempleTime.nCount03 += 1;
}
break;
case 4:
{
task.tagtempleTime.nCount04 += 1;
}
break;
case 5:
{
task.tagtempleTime.nCount05 += 1;
}
break;
case 6:
{
task.tagtempleTime.nCount06 += 1;
}
break;
case 7:
{
task.tagtempleTime.nCount07 += 1;
}
break;
case 8:
{
task.tagtempleTime.nCount08 += 1;
}
break;
case 9:
{
task.tagtempleTime.nCount09 += 1;
}
break;
case 10:
{
task.tagtempleTime.nCount10 += 1;
}
break;
case 11:
{
task.tagtempleTime.nCount11 += 1;
}
break;
case 12:
{
task.tagtempleTime.nCount12 += 1;
}
break;
case 13:
{
task.tagtempleTime.nCount13 += 1;
}
break;
case 14:
{
task.tagtempleTime.nCount14 += 1;
}
break;
case 15:
{
task.tagtempleTime.nCount15 += 1;
}
break;
case 16:
{
task.tagtempleTime.nCount16 += 1;
}
break;
case 17:
{
task.tagtempleTime.nCount17 += 1;
}
break;
case 18:
{
task.tagtempleTime.nCount18 += 1;
}
break;
case 19:
{
task.tagtempleTime.nCount19 += 1;
}
break;
case 20:
{
task.tagtempleTime.nCount20 += 1;
}
break;
case 21:
{
task.tagtempleTime.nCount21 += 1;
}
break;
case 22:
{
task.tagtempleTime.nCount22 += 1;
}
break;
case 23:
{
task.tagtempleTime.nCount23 += 1;
}
break;
default: break;
}
}
private void checkBox_work_MouseDown(object sender, MouseEventArgs e)
{
button_wait.Show();
checkBox_work.Hide();
this.CheckIntervalTimer.Start();
}
private void CheckIntervalTimer_Elapsed(object sender, ElapsedEventArgs e)
{
this.CheckIntervalTimer.Stop();
checkBox_work.Checked = !checkBox_work.Checked;
checkBox_work.Show();
button_wait.Hide();
}
private void Timer_checkbox_Tick(object sender, EventArgs e)
{
}
/// <summary>
/// 断开 宽带连接
/// </summary>
public void Disconnect()
{
ReadOnlyCollection<RasConnection> conList = RasConnection.GetActiveConnections();
foreach (RasConnection con in conList)
{
con.HangUp();
}
}
/// <summary>
/// 宽带连接,成功返回true,失败返回 false
/// </summary>
/// <param name="PPPOEname">宽带连接名称</param>
/// <param name="username">宽带账号</param>
/// <param name="password">宽带密码</param>
/// <returns></returns>
public bool Connect(string PPPOEname, string username, string password, ref string msg)
{
try
{
CreateOrUpdatePPPOE(PPPOEname);
using (RasDialer dialer = new RasDialer())
{
dialer.EntryName = PPPOEname;
dialer.AllowUseStoredCredentials = true;
dialer.Timeout = 1000;
dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
dialer.Credentials = new NetworkCredential(username, password);
dialer.Dial();
return true;
}
}
catch (RasException re)
{
msg = re.ErrorCode + " " + re.Message;
MessageBox.Show(msg);
return false;
}
}
/// <summary>
/// 创建或更新一个PPPOE连接(指定PPPOE名称)
/// </summary>
public void CreateOrUpdatePPPOE(string updatePPPOEname)
{
RasDialer dialer = new RasDialer();
RasPhoneBook allUsersPhoneBook = new RasPhoneBook();
string path = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers);
allUsersPhoneBook.Open(path);
// 如果已经该名称的PPPOE已经存在,则更新这个PPPOE服务器地址
if (allUsersPhoneBook.Entries.Contains(updatePPPOEname))
{
allUsersPhoneBook.Entries[updatePPPOEname].PhoneNumber = " ";
// 不管当前PPPOE是否连接,服务器地址的更新总能成功,如果正在连接,则需要PPPOE重启后才能起作用
allUsersPhoneBook.Entries[updatePPPOEname].Update();
}
// 创建一个新PPPOE
else
{
string adds = string.Empty;
ReadOnlyCollection<RasDevice> readOnlyCollection = RasDevice.GetDevices();
// foreach (var col in readOnlyCollection)
// {
// adds += col.Name + ":" + col.DeviceType.ToString() + "|||";
// }
// _log.Info("Devices are : " + adds);
// Find the device that will be used to dial the connection.
RasDevice device = RasDevice.GetDevices().Where(o => o.DeviceType == RasDeviceType.PPPoE).First();
RasEntry entry = RasEntry.CreateBroadbandEntry(updatePPPOEname, device); //建立宽带连接Entry
entry.PhoneNumber = " ";
allUsersPhoneBook.Entries.Add(entry);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace RankHelper
{
public class KeyUtils
{
[DllImport("user32.dll", EntryPoint = "keybd_event")]
public static extern void keybd_event(
byte bVk,
byte bScan,
int dwFlags, //这里是整数类型 0 为按下,2为释放
int dwExtraInfo //这里是整数类型 一般情况下设成为 0
);
[DllImport("User32.dll")]
public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
[DllImport("User32.dll")]
public extern static void SetCursorPos(int x, int y);
[DllImport("user32.dll")]
internal static extern bool OpenClipboard(IntPtr hWndNewOwner);
[DllImport("user32.dll")]
internal static extern bool CloseClipboard();
[DllImport("user32.dll")]
internal static extern bool SetClipboardData(uint uFormat, IntPtr data);
//复制黏贴剪贴板
//http://www.aiuxian.com/article/p-9717.html
//鼠标左键
public static void MouseLBUTTON()
{
mouse_event(2, 0, 0, 0, 0);
mouse_event(4, 0, 0, 0, 0);
}
public static void Copy(string str)
{
Clipboard.SetDataObject(str, true);
//OpenClipboard(IntPtr.Zero);
//var ptr = Marshal.StringToHGlobalUni(str);
//SetClipboardData(13, ptr);
//CloseClipboard();
//Marshal.FreeHGlobal(ptr);
Paste();
}
public static void Paste()
{
keybd_event(17, 0, 0, 0);//ctrl按下
keybd_event(86, 0, 0, 0);//V按下
keybd_event(17, 0, 2, 0);//ctrl释放
keybd_event(86, 0, 2, 0);//V释放
}
//鼠标左键
public static void Keybd_Enter()
{
keybd_event(13, 0, 0, 0);
keybd_event(13, 0, 2, 0);
}
}
}
<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 CefSharp.WinForms;
using CefSharp;
using System.IO;
using log4net;
namespace RankHelper
{
public partial class WebForm_bak : Form
{
private static ILog Logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private readonly ChromiumWebBrowser webBrowser;
private static string lib, browser, locales, res;
int nPos_x = 60;
int nPos_y = 130;
string strhtml;
string strPageurl;
int nPageIndex = -1;//第几页
int nItem = -1;//第几项
private tagTask currentTask;
public event EventHandler ShowTaskEvent;
public event EventHandler EndTaskEvent;
public event EventHandler StopTaskEvent;
public WebForm_bak()
{
InitializeComponent();
InitializeBrowser();
var settings = new CefSettings()
{
//BrowserSubprocessPath = browser,
//LocalesDirPath = locales,
//ResourcesDirPath = res
};
settings.Locale = "zh-CN";
//缓存路径
settings.CachePath = "BrowserCache";
settings.CefCommandLineArgs.Add("disable-application-cache", "1");
settings.CefCommandLineArgs.Add("disable-session-storage", "1");
//浏览器引擎的语言
settings.AcceptLanguageList = "zh-CN,zh;q=0.9";
//settings.LocalesDirPath = "localeDir";
//日志文件
settings.LogFile = "LogData";
settings.PersistSessionCookies = false;
settings.PersistUserPreferences = false;
//settings.UserAgent = "Mozilla/5.0 (Linux; Android 8.0.0; SM-G9350 Build/R16NW; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/70.0.3538.17 Mobile Safari/537.36 MicroMessenger/6.7.2.1340(0x260702A3) NetType/WIFI Language/zh_CN";
settings.UserDataPath = "userData";
Cef.Initialize(settings);
webBrowser = new ChromiumWebBrowser()
{
Dock = DockStyle.Fill,
};
this.panel_webbrowser.Controls.Add(webBrowser);
webBrowser.FrameLoadEnd += webBrowser_DocumentCompleted;
webBrowser.LoadError += WebBrowser_LoadError;
//webBrowser.RequestHandler = new RequestHandler(webBrowser.RequestHandler);
webBrowser.FrameLoadStart += WebBrowser_FrameLoadStart;
}
public void InitializeBrowser()
{
lib = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"resources\cefsharp_x86\libcef.dll");
browser = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"resources\cefsharp_x86\CefSharp.BrowserSubprocess.exe");
locales = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"resources\cefsharp_x86\locales\");
res = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"resources\cefsharp_x86\");
var libraryLoader = new CefLibraryHandle(lib);
var isValid = !libraryLoader.IsInvalid;
if (isValid)
{
}
}
void InitWebBrowser()
{
//设置webBrowser
//webBrowser.ScriptErrorsSuppressed = true; //禁用错误脚本提示
//webBrowser.IsWebBrowserContextMenuEnabled = false; //禁用右键菜单
//webBrowser.WebBrowserShortcutsEnabled = false; //禁用快捷键
//webBrowser.AllowWebBrowserDrop = false;//禁止拖拽
//webBrowser.ScrollBarsEnabled = true;//禁止滚动条
}
~WebForm_bak()
{
//需要关闭浏览器负载程序时操作
try
{
webBrowser.CloseDevTools();
webBrowser.GetBrowser().CloseBrowser(true);
}
catch { }
try
{
if (webBrowser != null)
{
webBrowser.Dispose();
Cef.Shutdown();
}
}
catch { }
if (CefSharpSettings.ShutdownOnExit)
{
Application.ApplicationExit += OnApplicationExit;
}
}
private void OnApplicationExit(object sender, EventArgs e)
{
if (CefSharpSettings.ShutdownOnExit)
{
Cef.Shutdown();
}
}
private void WebBrowser_FrameLoadStart(object sender, CefSharp.FrameLoadStartEventArgs e)
{
//throw new NotImplementedException();
}
private void webBrowser_DocumentCompleted(object sender, CefSharp.FrameLoadEndEventArgs e)
{
if (currentTask == null)
{
return;
}
//var list = webBrowser.GetBrowser().GetFrameNames();
//if (webBrowser.ReadyState != WebBrowserReadyState.Complete || e.Url.ToString() != webBrowser.Url.ToString())
//if (!e.Task.WebView.IsReady)
//{
// return;
//}
//if (e.Url.ToString().Contains("google"))
//{
// return;
//}
if (currentTask == null)
{
return;
}
switch (currentTask.webState)
{
case EWebbrowserState.Start://step1
{
webBrowser_DocumentCompleted_Search(sender, e);
}
break;
case EWebbrowserState.Search://step2
{
//MessageBox.Show("请输入指定访问链接", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
if (e.Url.ToString().Equals("http://www.baidu.com/") || e.Url.ToString().Equals("https://www.baidu.com/"))
{
return;
}
bool bLoad = false;
if (e.Frame.IsMain)
{
//strhtml = webBrowser.GetBrowser().MainFrame.GetSourceAsync().Result;
//webBrowser.GetBrowser().MainFrame.ViewSource();
//webBrowser.GetBrowser().MainFrame.GetSourceAsync().ContinueWith(taskHtml =>
//{
// if (!bLoad)
// {
// strhtml = taskHtml.Result;
// }
// bLoad = true;
//});
webBrowser_DocumentCompleted_SearchSite(sender, e);
}
}
break;
case EWebbrowserState.AccessSite://step3
{
//MessageBox.Show("请输入指定访问链接", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
if (e.Url.ToString().Equals("http://www.baidu.com/") || e.Url.ToString().Equals("https://www.baidu.com/"))
{
return;
}
bool bLoad = false;
if (e.Frame.IsMain)
{
webBrowser.GetBrowser().MainFrame.ViewSource();
webBrowser.GetBrowser().MainFrame.GetSourceAsync().ContinueWith(taskHtml =>
{
if (!bLoad)
{
strhtml = taskHtml.Result;
}
bLoad = true;
});
webBrowser_DocumentCompleted_SearchSite(sender, e);
}
}
break;
case EWebbrowserState.SearchSite://step3
{
//webBrowser_DocumentCompleted_SearchPage(sender, e);
}
break;
case EWebbrowserState.SearchPage://step3
{
//webBrowser_DocumentCompleted_SearchPage(sender, e);
}
break;
default:
break;
}
}
private void WebBrowser_LoadError(object sender, CefSharp.LoadErrorEventArgs e)
{
//重置任务
if (e.Frame.IsMain)
{
if (currentTask != null && (currentTask.webState == EWebbrowserState.Start || currentTask.webState == EWebbrowserState.Search
|| currentTask.webState == EWebbrowserState.SearchSite || currentTask.webState == EWebbrowserState.SearchPage))
{
e.Browser.StopLoad();
ShowTaskEvent(this, new AppEventArgs() { message_string = string.Format("加载网页发生错误{0}网址{1},重新执行,任务{2}", e.ErrorText, e.FailedUrl, currentTask.nID) });
StartSearch(this, new AppEventArgs() { message_task = currentTask });
}
}
//throw new NotImplementedException();
}
internal void StartSearch(object sender, EventArgs e)
{
//webBrowser.ShowDevTools();
AppEventArgs arg = e as AppEventArgs;
InitWebBrowser();
currentTask = arg.message_task;
//清除缓存
var cookieManager = CefSharp.Cef.GetGlobalCookieManager();
cookieManager.DeleteCookies();
ShowTaskEvent(this, new AppEventArgs() { message_string = string.Format("开始清除缓存,任务{0}", currentTask.nID) });
currentTask.webState = EWebbrowserState.Start;
strPageurl = "";
nPageIndex = 0;
if (currentTask.engine == eEngines.Sm)
{
if(currentTask.webBrowser == eWebBrowser.IE_mobile
|| currentTask.webBrowser == eWebBrowser.Chrome_mobile
|| currentTask.webBrowser == eWebBrowser.Qihu_mobile
|| currentTask.webBrowser == eWebBrowser.Sogou_mobile
|| currentTask.webBrowser == eWebBrowser.QQ_mobile
|| currentTask.webBrowser == eWebBrowser.maxthon_mobile
|| currentTask.webBrowser == eWebBrowser.theworld_mobile
)
{
currentTask.webBrowser += 1;
}
}
switch (currentTask.webBrowser)
{
case eWebBrowser.IE:
{
Appinfo.strUserAgent = "Mozilla / 4.0(compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident / 7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)";
}
break;
case eWebBrowser.IE_mobile:
{
Appinfo.strUserAgent = "Mozilla/5.0 (Linux; Android 8.0.0; SM-G9350 Build/R16NW; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/70.0.3538.17 Mobile Safari/537.36 MicroMessenger/6.7.2.1340(0x260702A3) NetType/WIFI Language/zh_CN";
}
break;
case eWebBrowser.Chrome:
{
Appinfo.strUserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";
}
break;
case eWebBrowser.Chrome_mobile:
{
Appinfo.strUserAgent = "Mozilla/5.0 (Linux; Android 8.0.0; MHA-AL00 Build/HUAWEIMHA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 HuaweiBrowser/9.0.1.319 Mobile Safari/537.36";
}
break;
case eWebBrowser.Qihu:
{
Appinfo.strUserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";
}
break;
case eWebBrowser.Qihu_mobile:
{
Appinfo.strUserAgent = "Mozilla/5.0 (Linux; Android 8.0.0; MHA-AL00 Build/HUAWEIMHA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 HuaweiBrowser/9.0.1.319 Mobile Safari/537.36";
}
break;
case eWebBrowser.QQ:
{
Appinfo.strUserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";
}
break;
case eWebBrowser.QQ_mobile:
{
Appinfo.strUserAgent = "Mozilla/5.0 (Linux; Android 8.0.0; MHA-AL00 Build/HUAWEIMHA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 HuaweiBrowser/9.0.1.319 Mobile Safari/537.36";
}
break;
case eWebBrowser.Sogou:
{
Appinfo.strUserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";
}
break;
case eWebBrowser.Sogou_mobile:
{
Appinfo.strUserAgent = "Mozilla/5.0 (Linux; Android 8.0.0; MHA-AL00 Build/HUAWEIMHA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 HuaweiBrowser/9.0.1.319 Mobile Safari/537.36";
}
break;
case eWebBrowser.maxthon:
{
Appinfo.strUserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";
}
break;
case eWebBrowser.maxthon_mobile:
{
Appinfo.strUserAgent = "Mozilla/5.0 (Linux; Android 8.0.0; MHA-AL00 Build/HUAWEIMHA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 HuaweiBrowser/9.0.1.319 Mobile Safari/537.36";
}
break;
case eWebBrowser.theworld:
{
Appinfo.strUserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";
}
break;
case eWebBrowser.theworld_mobile:
{
Appinfo.strUserAgent = "Mozilla/5.0 (Linux; Android 8.0.0; MHA-AL00 Build/HUAWEIMHA-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.111 HuaweiBrowser/9.0.1.319 Mobile Safari/537.36";
}
break;
}
switch (currentTask.engine)
{
case eEngines.Baidu:
{
webBrowser.Load("www.baidu.com");
}
break;
case eEngines.Qihu:
{
webBrowser.Load("www.so.com");
}
break;
case eEngines.Sogou:
{
webBrowser.Load("www.sogou.com");
}
break;
case eEngines.Sm:
{
webBrowser.Load("www.m.sm.cn");
}
break;
default:
break;
}
}
internal void EndTask(bool bSuccess)
{
webBrowser.GetBrowser().StopLoad();
EndTaskEvent(this, new AppEventArgs(){ message_bool = bSuccess,message_task = currentTask});
}
internal void StopSearch(object sender, EventArgs e)
{
currentTask = null;
webBrowser.GetBrowser().StopLoad();
}
private void webBrowser_DocumentCompleted_Search(object sender, CefSharp.FrameLoadEndEventArgs e)
{
switch (currentTask.engine)
{
case eEngines.Baidu:
{
if (e.Url.ToString().Contains("baidu"))
{
currentTask.webState = EWebbrowserState.none;
e.Browser.StopLoad();
//textBox_url.Text = e.Url.ToString();
//e.Frame.ExecuteJavaScriptAsync("alert('MainFrame finished loading');");
//输入框
/*
string ele_search = (currentTask.webBrowser == eWebBrowser.IE || currentTask.webBrowser == eWebBrowser.Chrome || currentTask.webBrowser == eWebBrowser.Qihu || currentTask.webBrowser == eWebBrowser.Sogou || currentTask.webBrowser == eWebBrowser.QQ || currentTask.webBrowser == eWebBrowser.maxthon || currentTask.webBrowser == eWebBrowser.theworld)
? String.Format("document.getElementById('kw').value= '{0}'", currentTask.strKeyword)//PC版
: String.Format("document.getElementById('index-kw').value= '{0}'", currentTask.strKeyword);//手机版
e.Frame.ExecuteJavaScriptAsync(ele_search);
*/
string ele_search = (currentTask.webBrowser == eWebBrowser.IE || currentTask.webBrowser == eWebBrowser.Chrome || currentTask.webBrowser == eWebBrowser.Qihu || currentTask.webBrowser == eWebBrowser.Sogou || currentTask.webBrowser == eWebBrowser.QQ || currentTask.webBrowser == eWebBrowser.maxthon || currentTask.webBrowser == eWebBrowser.theworld)
? String.Format("document.getElementById('kw').getBoundingClientRect()")//PC版
: String.Format("document.getElementById('index-kw').getBoundingClientRect()");//手机版
var task1 = e.Frame.EvaluateScriptAsync(ele_search).ContinueWith(x =>
{
JavascriptResponse response = x.Result;
dynamic dictionary_object = response.Result;
int pos_x=0, pos_y = 0;
foreach (var item in (IDictionary<string, object>)dictionary_object)
{
if (item.Key == "x")
{
pos_x = Convert.ToInt32(item.Value);
}
if (item.Key == "y")
{
pos_y = Convert.ToInt32(item.Value);
}
}
KeyUtils.SetCursorPos(pos_x+nPos_x, pos_y+nPos_y);
KeyUtils.MouseLBUTTON();
KeyUtils.Copy(currentTask.strKeyword);
KeyUtils.SetCursorPos(750, 110);
KeyUtils.MouseLBUTTON();
if (currentTask == null)
{
return;
}
currentTask.webState = EWebbrowserState.Search;
ShowTaskEvent(this, new AppEventArgs() { message_string = string.Format("开始搜索关键词,任务{0}", currentTask.nID) });
System.Threading.Thread.Sleep(5000);
e.Browser.Reload();
});
//string ele_submit = (currentTask.webBrowser == eWebBrowser.IE || currentTask.webBrowser == eWebBrowser.Chrome || currentTask.webBrowser == eWebBrowser.Qihu || currentTask.webBrowser == eWebBrowser.Sogou || currentTask.webBrowser == eWebBrowser.QQ || currentTask.webBrowser == eWebBrowser.maxthon || currentTask.webBrowser == eWebBrowser.theworld)
// ? String.Format("document.getElementById('su').click()")//PC版
// : String.Format("document.getElementById('index-bn').click()");//手机版
//e.Frame.ExecuteJavaScriptAsync(ele_submit);
//e.Frame.ExecuteJavaScriptAsync(ele_submit);
//var task = e.Frame.EvaluateScriptAsync(ele_submit).ContinueWith(x =>
//{
// var response = x.Result;
// if (response.Success)
// {
// e.Browser.StopLoad();
// //System.Threading.Thread.Sleep(2000);
// e.Browser.Reload();
// }
// if (response.Success && response.Result != null)
// {
// //File.AppendAllText("result.txt", response.Result.ToString());
// }
//});
}
}
break;
case eEngines.Qihu:
{
}
break;
case eEngines.Sogou:
{
if (e.Url.ToString().Contains("www.sogou.com"))
{
currentTask.webState = EWebbrowserState.none;
e.Browser.StopLoad();
KeyUtils.SetCursorPos(300,340);
//System.Threading.Thread.Sleep(1000);
KeyUtils.MouseLBUTTON();
string ele_search = (currentTask.webBrowser == eWebBrowser.IE || currentTask.webBrowser == eWebBrowser.Chrome || currentTask.webBrowser == eWebBrowser.Qihu || currentTask.webBrowser == eWebBrowser.Sogou || currentTask.webBrowser == eWebBrowser.QQ || currentTask.webBrowser == eWebBrowser.maxthon || currentTask.webBrowser == eWebBrowser.theworld)
? String.Format("document.getElementById('query').getBoundingClientRect()")//PC版
: String.Format("document.getElementById('query').getBoundingClientRect()");//手机版
var task1 = e.Frame.EvaluateScriptAsync(ele_search).ContinueWith(x =>
{
JavascriptResponse response = x.Result;
dynamic dictionary_object = response.Result;
int pos_x = 0, pos_y = 0;
foreach (var item in (IDictionary<string, object>)dictionary_object)
{
if (item.Key == "x")
{
pos_x = Convert.ToInt32(item.Value);
}
if (item.Key == "y")
{
pos_y = Convert.ToInt32(item.Value);
}
}
});
}
}
break;
// case eEngines.Sm:
// {
// if (e.Url.ToString().Contains("www.m.sm.cn"))
// {
// textBox_url.Text = e.Url.ToString();
// HtmlDocument doc = webBrowser.Document;
// HtmlElement ele_search = doc.GetElementById("kw");
// if (ele_search == null)
// {
// return;
// }
// ele_search.InnerText = currentTask.strKeyword;
// HtmlElement ele_submit = doc.GetElementById("su");
// if (ele_submit == null)
// {
// return;
// }
// ele_submit.InvokeMember("click");
// }
// }
// break;
default:
break;
}
}
private void webBrowser_DocumentCompleted_SearchSite(object sender, CefSharp.FrameLoadEndEventArgs e)
{
switch (currentTask.engine)
{
case eEngines.Baidu:
{
if (e.Url.ToString().Contains("baidu"))
{
currentTask.webState = EWebbrowserState.none;
ShowTaskEvent(this, new AppEventArgs() { message_string = string.Format("开始查找网站,当前页码{0},任务{1}", 1,currentTask.nID)});
List<tagSearchResult> listSearch = new List<tagSearchResult>();
//搜索项目
for (int i = 1; i <= 10; i++)//1~10项
{
string js="";
if (!currentTask.strTitle.Trim().Equals("")&&!currentTask.strPageUrl.Trim().Equals(""))
{
js = String.Format("document.getElementById('{0}').innerText.match('{1}')||document.getElementById('{0}').innerText.match({'2'})", i, currentTask.strTitle, currentTask.strPageUrl);
}
else if (!currentTask.strTitle.Trim().Equals(""))
{
js = String.Format("document.getElementById('{0}').innerText.match('{1}')", i, currentTask.strTitle);
}
else if (!currentTask.strPageUrl.Trim().Equals(""))
{
js = String.Format("document.getElementById('{0}').innerText.match('{1}')", i, currentTask.strPageUrl);
}
var task_item = e.Frame.EvaluateScriptAsync(js);
//task_item.Id = i;
task_item.ContinueWith(t =>
{
if (!t.IsFaulted)
{
//诺亚娱乐 - 诺亚娱乐平台官方唯一网站
//百度网址安全中心提醒您:该页面可能存在违法信息!
//诺亚娱乐官方权威指定网站是国内知名有效合法代理登录站点,诺亚娱乐平台是彩界唯一一家拥有合法的娱乐平台注册预测走势图,行业首家拥有上下级聊天工具支持网页手机玩法。
//https://www.nuoya115.com/ - 百度快照
string log = string.Format("方法webBrowser_DocumentCompleted_SearchSite: 查找第{0}页第{0}项", nPageIndex, i);
ShowTaskEvent(this, new AppEventArgs() { message_string = log });
var response = t.Result;
var EvaluateJavaScriptResult = response.Success ? (response.Result ?? "null") : response.Message;
tagSearchResult searchResult = new tagSearchResult();
searchResult.nItem = i;
searchResult.bFinish = true;
searchResult.bMatch = (response.Result==null) ? false:true;
listSearch.Add(searchResult);
bool bAllPageFinish = true;
if (listSearch.Count==10)
{
foreach (var item in listSearch)
{
if (item.bFinish == false)
{
bAllPageFinish = false;
}
}
}
if (bAllPageFinish)
{
foreach (var item in listSearch)
{
if (item.bMatch == false)
{
nItem = item.nItem;
currentTask.webState = EWebbrowserState.SearchSite_Match;
e.Browser.Reload();
break;
}
}
}
}
});
}
return;
var task = e.Frame.EvaluateScriptAsync("document.getElementById('page').innerHTML");//异步
task.ContinueWith(t =>
{
if (!t.IsFaulted)
{
var response = t.Result;
var EvaluateJavaScriptResult = response.Success ? (response.Result ?? "null") : response.Message;
GetBaiduPageurl((string)EvaluateJavaScriptResult);
currentTask.webState = EWebbrowserState.SearchSite;
webBrowser.Load(GetBaiduNextPageurl());
}
});
}
}
break;
// case eEngines.Qihu:
// {
// if (e.Url.ToString().Contains("www.so.com"))
// {
// textBox_url.Text = e.Url.ToString();
// HtmlDocument doc = webBrowser.Document;
// HtmlElement ele_search = doc.GetElementById("kw");
// if (ele_search == null)
// {
// return;
// }
// ele_search.InnerText = currentTask.strKeyword;
// HtmlElement ele_submit = doc.GetElementById("su");
// if (ele_submit == null)
// {
// return;
// }
// ele_submit.InvokeMember("click");
// }
// }
// break;
// case eEngines.Sogou:
// {
// if (e.Url.ToString().Contains("www.sogou.com"))
// {
// textBox_url.Text = e.Url.ToString();
// HtmlDocument doc = webBrowser.Document;
// HtmlElement ele_search = doc.GetElementById("kw");
// if (ele_search == null)
// {
// return;
// }
// ele_search.InnerText = currentTask.strKeyword;
// HtmlElement ele_submit = doc.GetElementById("su");
// if (ele_submit == null)
// {
// return;
// }
// ele_submit.InvokeMember("click");
// }
// }
// break;
// case eEngines.Sm:
// {
// if (e.Url.ToString().Contains("www.m.sm.cn"))
// {
// textBox_url.Text = e.Url.ToString();
// HtmlDocument doc = webBrowser.Document;
// HtmlElement ele_search = doc.GetElementById("kw");
// if (ele_search == null)
// {
// return;
// }
// ele_search.InnerText = currentTask.strKeyword;
// HtmlElement ele_submit = doc.GetElementById("su");
// if (ele_submit == null)
// {
// return;
// }
// ele_submit.InvokeMember("click");
// }
// }
// break;
default:
break;
}
}
void GetBaiduPageurl(string pageHtml)
{
string[] sArray = pageHtml.Split(new string[] { "<a href="}, StringSplitOptions.RemoveEmptyEntries);
foreach (string item in sArray)
{
string tmp = string.Format("><span class=\"fk fkd\">");
if (item.Contains(tmp))
{
int index = item.IndexOf(tmp);
strPageurl = item.Substring(0, index).Replace("\"","");
break;
}
}
}
string GetBaiduNextPageurl()
{
string[] sArray = strPageurl.Split(new string[] { "&pn=", "&oq=" }, StringSplitOptions.RemoveEmptyEntries);
string tmp = "";
int index = 0;
foreach (string item in sArray)
{
if(index == 0)
{
tmp += "https://www.baidu.com";
tmp += item;
tmp += "&pn=";
}
else if (index == 1)
{
if(nPageIndex==0)
{
tmp += item;
}
else
{
int nPage = int.Parse(item);
string page = (nPage + 10).ToString();
tmp += page;
}
nPageIndex++;
}
else if(index == 2)
{
tmp += "&oq=";
tmp += item;
}
index++;
}
//
if (tmp.Trim()=="")
{
EndTask(false);
}
return tmp.Replace("amp;","");
}
private void webBrowser_DocumentCompleted_SearchPage(object sender, CefSharp.FrameLoadEndEventArgs e)
{
}
private void WebForm_bak_FormClosing(object sender, FormClosingEventArgs e)
{
this.Hide();
StopTaskEvent(this, new AppEventArgs(){});
return;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using mshtml;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Drawing;
namespace RankHelper
{
public class Baidu_Inside : WebBase
{
public Baidu_Inside(WebForm webForm, string strSiteUrl, string strhtml) : base(webForm, strSiteUrl, strhtml)
{
nPos_x = 30;
nPos_y = 70;
webForm.webBrowser_new.Navigate("www.baidu.com");
}
public override void webBrowser_DocumentCompleted_Search(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (e.Url.ToString().Contains("baidu"))
{
webForm.currentTask.webState = EWebbrowserState.none;
webForm.textBox_url.Text = e.Url.ToString();
HtmlElement ele_search;
if (webForm.currentTask.webBrowser == eWebBrowser.IE || webForm.currentTask.webBrowser == eWebBrowser.Chrome || webForm.currentTask.webBrowser == eWebBrowser.Qihu || webForm.currentTask.webBrowser == eWebBrowser.Sogou || webForm.currentTask.webBrowser == eWebBrowser.QQ || webForm.currentTask.webBrowser == eWebBrowser.maxthon || webForm.currentTask.webBrowser == eWebBrowser.theworld)
{
//webForm.webBrowser_new.Document.GetElementById("kw").Focus();
//webForm.webBrowser_new.Document.GetElementById("kw").InnerText = webForm.currentTask.strKeyword;
ele_search = webForm.webBrowser_new.Document.GetElementById("kw");
}
else//移动端
{
ele_search = webForm.webBrowser_new.Document.GetElementById("kw");
}
if (ele_search == null)
{
webForm.currentTask.webState = EWebbrowserState.Search;
webForm.webBrowser_new.Refresh();
return;
}
Point point_search = GetPoint(ele_search);
//webForm.webBrowser_new.Document.Window.ScrollTo(0, point_search.Y);
int top = webForm.webBrowser_new.Document.GetElementsByTagName("HTML")[0].ScrollTop;//滚动条垂直位置
KeyUtils.SetCursorPos(point_search.X + nPos_x, point_search.Y + nPos_y - top);
//KeyUtils.SetCursorPos(point_search.X, point_search.Y);
//ele_search.Focus();
KeyUtils.MouseLBUTTON();
this.taskIntervalTimer.Start();
string tmp = webForm.currentTask.strKeyword + "site:" + webForm.currentTask.strOnSiteUrl;
KeyUtils.Copy(tmp);
//if (webForm.currentTask.webBrowser == eWebBrowser.IE || webForm.currentTask.webBrowser == eWebBrowser.Chrome || webForm.currentTask.webBrowser == eWebBrowser.Qihu || webForm.currentTask.webBrowser == eWebBrowser.Sogou || webForm.currentTask.webBrowser == eWebBrowser.QQ || webForm.currentTask.webBrowser == eWebBrowser.maxthon || webForm.currentTask.webBrowser == eWebBrowser.theworld)
//{
// ele_search.InnerText = webForm.currentTask.strKeyword;
//}
//else
//{
// ele_search.InnerText = webForm.currentTask.strKeyword;
//}
Sleep(3000);
HtmlElement ele_submit;
if (webForm.currentTask.webBrowser == eWebBrowser.IE || webForm.currentTask.webBrowser == eWebBrowser.Chrome || webForm.currentTask.webBrowser == eWebBrowser.Qihu || webForm.currentTask.webBrowser == eWebBrowser.Sogou || webForm.currentTask.webBrowser == eWebBrowser.QQ || webForm.currentTask.webBrowser == eWebBrowser.maxthon || webForm.currentTask.webBrowser == eWebBrowser.theworld)
{
ele_submit = webForm.webBrowser_new.Document.GetElementById("su");
}
else
{
ele_submit = webForm.webBrowser_new.Document.GetElementById("su");
}
if (ele_submit == null)
{
webForm.currentTask.webState = EWebbrowserState.Search;
webForm.webBrowser_new.Refresh();
return;
}
Point point_submit = GetPoint(ele_submit);
webForm.webBrowser_new.Document.Window.ScrollTo(0, point_submit.Y);
int top2 = webForm.webBrowser_new.Document.GetElementsByTagName("HTML")[0].ScrollTop;//滚动条垂直位置
KeyUtils.SetCursorPos(point_submit.X + nPos_x, point_submit.Y + nPos_y - top2);
//KeyUtils.SetCursorPos(point_submit.X, point_submit.Y);
KeyUtils.MouseLBUTTON();
this.taskIntervalTimer.Start();
if (webForm.currentTask == null)
{
return;
}
webForm.currentTask.webState = EWebbrowserState.Search;
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("开始搜索关键词,任务{0}", webForm.currentTask.nID) });
//e.Browser.Reload();
}
}
public override void webBrowser_DocumentCompleted_SearchSite(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (!e.Url.ToString().Contains("www.baidu.com/s?"))
{
return;
}
nItem = -1;
if (e.Url.ToString().Contains("baidu"))
{
webForm.currentTask.webState = EWebbrowserState.none;
webForm.textBox_url.Text = e.Url.ToString();
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("开始查找网站,当前页码{0},任务{1}", nPageIndex, webForm.currentTask.nID) });
Sleep(3000);
//List<tagSearchResult> listSearch = new List<tagSearchResult>();
//搜索项目
for (int i = 1; i <= 10; i++)//1~10项
{
HtmlElement ele_search;
ele_search = webForm.webBrowser_new.Document.GetElementById(i.ToString());
if (ele_search == null)
{
break;
}
if (!webForm.currentTask.strTitle.Trim().Equals("") && !webForm.currentTask.strSiteUrl.Trim().Equals(""))
{
if (ele_search.InnerText.Contains(webForm.currentTask.strTitle) || ele_search.InnerText.Contains(webForm.currentTask.strSiteUrl))
{
HtmlElementCollection eleCol = ele_search.GetElementsByTagName("a");
foreach (HtmlElement element in eleCol)
{
nItem = i;
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("查找到符合的网站,当前页码{0},任务{1}", nPageIndex, webForm.currentTask.nID) });
webForm.currentTask.webState = EWebbrowserState.AccessSite;
//element.InvokeMember("click");
Sleep(3000);
Point point_ele = GetPoint(element);
int nPos_y = 70;
webForm.webBrowser_new.Document.Window.ScrollTo(0, point_ele.Y - nPos_y);
int top2 = webForm.webBrowser_new.Document.GetElementsByTagName("HTML")[0].ScrollTop;//滚动条垂直位置
Sleep(3000);
KeyUtils.SetCursorPos(point_ele.X + nPos_x, point_ele.Y + nPos_y - top2);
Sleep(3000);
webForm.currentTask.webState = EWebbrowserState.AccessSite;
KeyUtils.MouseLBUTTON();
this.taskIntervalTimer.Start();
break;
}
}
}
else if (!webForm.currentTask.strTitle.Trim().Equals(""))
{
if (ele_search.InnerText.Contains(webForm.currentTask.strTitle))
{
HtmlElementCollection eleCol = ele_search.GetElementsByTagName("a");
foreach (HtmlElement element in eleCol)
{
nItem = i;
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("查找到符合的网站,当前页码{0},任务{1}", nPageIndex, webForm.currentTask.nID) });
webForm.currentTask.webState = EWebbrowserState.AccessSite;
//element.InvokeMember("click");
Sleep(3000);
Point point_ele = GetPoint(element);
int nPos_y = 70;
webForm.webBrowser_new.Document.Window.ScrollTo(0, point_ele.Y - nPos_y);
int top2 = webForm.webBrowser_new.Document.GetElementsByTagName("HTML")[0].ScrollTop;//滚动条垂直位置
Sleep(3000);
KeyUtils.SetCursorPos(point_ele.X + nPos_x, point_ele.Y + nPos_y - top2);
Sleep(3000);
webForm.currentTask.webState = EWebbrowserState.AccessSite;
KeyUtils.MouseLBUTTON();
this.taskIntervalTimer.Start();
break;
}
}
}
else if (!webForm.currentTask.strSiteUrl.Trim().Equals(""))
{
HtmlElementCollection eleCol = ele_search.GetElementsByTagName("a");
foreach (HtmlElement element in eleCol)
{
nItem = i;
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("查找到符合的网站,当前页码{0},任务{1}", nPageIndex, webForm.currentTask.nID) });
webForm.currentTask.webState = EWebbrowserState.AccessSite;
//element.InvokeMember("click");
Sleep(3000);
Point point_ele = GetPoint(element);
int nPos_y = 70;
webForm.webBrowser_new.Document.Window.ScrollTo(0, point_ele.Y - nPos_y);
int top2 = webForm.webBrowser_new.Document.GetElementsByTagName("HTML")[0].ScrollTop;//滚动条垂直位置
Sleep(3000);
KeyUtils.SetCursorPos(point_ele.X + nPos_x, point_ele.Y + nPos_y - top2);
Sleep(3000);
webForm.currentTask.webState = EWebbrowserState.AccessSite;
KeyUtils.MouseLBUTTON();
this.taskIntervalTimer.Start();
break;
}
}
}
//当前搜索页未找到
if (nItem == -1)
{
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("没有找到符合的网站,开始查找下一页,当前页码{0},任务{1}", nPageIndex, webForm.currentTask.nID) });
GetNextPageurl();
}
}
}
public override void webBrowser_DocumentCompleted_AccessSite(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (e.Url.ToString().Equals("http://www.baidu.com/") || e.Url.ToString().Equals("https://www.baidu.com/"))
{
return;
}
//if (e.Url.ToString().Contains("baidu"))
//{
// return;
//}
webForm.textBox_url.Text = e.Url.ToString();
webForm.currentTask.webState = EWebbrowserState.none;
webForm.textBox_url.Text = e.Url.ToString();
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("进入网站,当前页码{0},任务{1}", 1, webForm.currentTask.nID) });
Sleep(5000);
switch (webForm.currentTask.pageAccessType)
{
case ePageAccessType.None:
{
EndTask(true);
return;
}
break;
case ePageAccessType.Rand:
{
HtmlElementCollection aCol = webForm.webBrowser_new.Document.GetElementsByTagName("a");
if (aCol == null || aCol.Count == 0)
{
EndTask(true);
return;
}
Random ra = new Random(unchecked((int)DateTime.Now.Ticks));//保证产生的数字的随机性
int index = ra.Next() % aCol.Count;
index = (index >= aCol.Count) ? aCol.Count - 1 : index;
aCol[index].InvokeMember("click");
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("访问内页{0}", aCol[index].GetAttribute("href")) });
webForm.currentTask.webState = EWebbrowserState.AccessPage;
this.taskIntervalTimer.Start();
}
break;
case ePageAccessType.Appoint:
{
HtmlElementCollection aCol = webForm.webBrowser_new.Document.GetElementsByTagName("a");
if (aCol == null || aCol.Count == 0)
{
EndTask(true);
return;
}
Random ra = new Random(unchecked((int)DateTime.Now.Ticks));//保证产生的数字的随机性
int index = ra.Next() % aCol.Count;
index = (index >= aCol.Count) ? aCol.Count - 1 : index;
for (int i = 0; i < aCol.Count; i++)
{
if (aCol[i].GetAttribute("href") == null)
{
EndTask(true);
continue;
}
else if (aCol[i].GetAttribute("href") == webForm.currentTask.strPageUrl)
{
aCol[i].InvokeMember("click");
break;
}
}
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("访问内页{0}", webForm.currentTask.strPageUrl) });
webForm.currentTask.webState = EWebbrowserState.AccessPage;
this.taskIntervalTimer.Start();
}
break;
default:
break;
}
}
public override void webBrowser_DocumentCompleted_AccessPage(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webForm.textBox_url.Text = e.Url.ToString();
webForm.currentTask.webState = EWebbrowserState.none;
webForm.textBox_url.Text = e.Url.ToString();
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("访问内页{0}", webForm.currentTask.strPageUrl) });
Sleep(5000);
EndTask(true);
}
public override void GetNextPageurl()
{
HtmlElement ele_page;
ele_page = webForm.webBrowser_new.Document.GetElementById("page");
if (ele_page == null)
{
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("只有一页,结束任务,当前页码{0},任务{1}", nPageIndex, webForm.currentTask.nID) });
EndTask(false);
}
nPageIndex += 1;
HtmlElementCollection eleCol = ele_page.GetElementsByTagName("a");
foreach (HtmlElement element in eleCol)
{
HtmlElementCollection pageCol = element.Children;
if (pageCol != null)
{
for (int i = 0; i < pageCol.Count; i++)
{
if (pageCol[i].GetAttribute("className") == null)
{
continue;
}
if (pageCol[i].GetAttribute("className") == "pc")
{
if (pageCol[i].InnerText == nPageIndex.ToString())
{
webForm.currentTask.webState = EWebbrowserState.SearchSite;
Point point_ele = GetPoint(element);
webForm.webBrowser_new.Document.Window.ScrollTo(0, point_ele.Y);
int top = webForm.webBrowser_new.Document.GetElementsByTagName("HTML")[0].ScrollTop;//滚动条垂直位置
KeyUtils.SetCursorPos(point_ele.X + nPos_x, point_ele.Y + nPos_y - top);
Sleep(3000);
KeyUtils.MouseLBUTTON();
this.taskIntervalTimer.Start();
return;
}
}
}
}
}
webForm.ShowTask(new AppEventArgs() { message_string = string.Format("已经是最后一页,结束任务,当前页码{0},任务{1}", nPageIndex, webForm.currentTask.nID) });
Sleep(5000);
EndTask(false);
}
}
}
<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;
using log4net;
using System.Runtime.InteropServices;
namespace RankHelper
{
public partial class MainForm : Form
{
private static ILog Logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
StatisticsForm statisticsForm;
SettingForm settingForm;
WebForm webForm;
AdslForm adslForm;
//定义消息发布的事件 事件是委托的一个特殊实例 事件只能在类的内部触发执行
//public event EventHandler SendMsgEvent; //使用默认的事件处理委托
public event EventHandler RefreshStatisticsAllEvent; //使用默认的事件处理委托
public event EventHandler RefreshStatisticsEvent;
public event EventHandler StartSearchEvent;
public event EventHandler StopTaskEvent;
public event EventHandler EndTaskEvent;
public event EventHandler ChangeTaskEvent;
public event EventHandler ShowTabEvent;
public event EventHandler CheckWorkEvent;
public MainForm()
{
InitializeComponent();
Init();
InitTab();
RegisterEvent();
RefreshStatisticsAllEvent(this, new AppEventArgs() { });
ShowIP();
CheckWork();
}
public void Init()
{
//设置标题
//this.Text = string.Format("{0} (版本{1})", Appinfo.strTitleName, Appinfo.strVersion);
this.Text = string.Format("{0}", Appinfo.strTitleName);
this.FormBorderStyle = FormBorderStyle.FixedSingle;
Appinfo.Init();
toolStripStatusLabel_Status.Text = "未开始挂机";
}
public void InitMenu()
{
//添加菜单一
//ToolStripMenuItem subItem;
//subItem = AddContextMenu("用户:justin", this.menuStrip_main.Items, null);
//AddContextMenu("充值积分", subItem.DropDownItems, new EventHandler(MenuClicked_RechargePoint));
}
public void InitTab()
{
statisticsForm = new StatisticsForm();
statisticsForm.TopLevel = false;
tabControlTop.TabPages[0].Controls.Add(statisticsForm);
//statisticsForm.Parent = tabControlTop.TabPages[0];
statisticsForm.Show();
//statisticsForm.Parent = this;
settingForm = new SettingForm();
settingForm.TopLevel = false;
tabControlTop.TabPages[1].Controls.Add(settingForm);
settingForm.Show();
webForm = new WebForm();
webForm.TopLevel = false;
webForm.Show();
this.panel.Hide();
this.panel.BringToFront();
this.panel.Controls.Add(webForm);
adslForm = new AdslForm();
adslForm.TopLevel = false;
tabControlTop.TabPages[2].Controls.Add(adslForm);
adslForm.Show();
//tabControlTop.SelectedIndexChanged += new EventHandler(SelectedIndexChanged_tabControlTop);
tabControlTop.Dock = DockStyle.Fill;
}
void RegisterEvent()
{
RefreshStatisticsEvent += statisticsForm.RefreshStatistics;
RefreshStatisticsAllEvent += statisticsForm.RefreshStatisticsAll;
settingForm.RefreshStatisticsEvent += RefreshStatistics;
ShowTabEvent += settingForm.ShowTab;
statisticsForm.StartTaskEvent += StartSearch;
statisticsForm.StopTaskEvent += StopSearch;
webForm.StopTaskEvent += StopSearch;
statisticsForm.ChangeTaskEvent += ChangeTask;
statisticsForm.ShowTaskEvent += ShowTaskStatus;
statisticsForm.ShowIPEvent += UpdateIP;
ChangeTaskEvent += settingForm.ChangeTask;
StartSearchEvent += webForm.StartSearch;
StopTaskEvent += webForm.StopSearch;
webForm.EndTaskEvent += EndTask;
EndTaskEvent += statisticsForm.EndTask;
webForm.ShowTaskEvent += ShowTaskStatus;
CheckWorkEvent += statisticsForm.CheckWork;
}
/// <summary>
/// 添加子菜单
/// </summary>
/// <param name="text">要显示的文字,如果为 - 则显示为分割线</param>
/// <param name="cms">要添加到的子菜单集合</param>
/// <param name="callback">点击时触发的事件</param>
/// <returns>生成的子菜单,如果为分隔条则返回null</returns>
ToolStripMenuItem AddContextMenu(string text, ToolStripItemCollection cms, EventHandler callback)
{
if (text == "-")
{
ToolStripSeparator tsp = new ToolStripSeparator();
cms.Add(tsp);
return null;
}
else if (!string.IsNullOrEmpty(text))
{
ToolStripMenuItem tsmi = new ToolStripMenuItem(text);
tsmi.Tag = text + "TAG";
if (callback != null) tsmi.Click += callback;
cms.Add(tsmi);
return tsmi;
}
return null;
}
void MenuClicked_RechargePoint(object sender, EventArgs e)
{
//((sender as ToolStripMenuItem).Tag)强制转换
//MessageBox.Show(((sender as ToolStripMenuItem).Text));
BrowserUtils.OpenBrowserUrl(Appinfo.strUrl_RechargePoint);
}
private void tabControlTop_Selected(object sender, TabControlEventArgs e)
{
switch (tabControlTop.SelectedIndex)
{
case 0:
{
//if (MessageBox.Show("未保存当前任务,需要退出吗?", "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning)== DialogResult.OK)
//{
// ShowTabEvent(this, new AppEventArgs() { });
//}
//else
//{
// tabControlTop.SelectedIndex = 1;
//}
}
break;
case 1:
{
}
break;
case 2:
{
//if (MessageBox.Show("未保存当前任务,需要退出吗?", "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
//{
// ShowTabEvent(this, new AppEventArgs() { });
//}
//else
//{
// tabControlTop.SelectedIndex = 1;
//}
}
break;
default:
break;
}
}
void SelectedIndexChanged_tabControlTop(object sender, EventArgs e)
{
}
internal void RefreshStatistics(object sender, EventArgs e)
{
//RefreshStatisticsEvent(this, new AppEventArgs() { message = tmp });
AppEventArgs arg = e as AppEventArgs;
switch (arg.message_task.taskAcion)
{
case eTaskAcion.Add:
{
RefreshStatisticsEvent(this, e);
}
break;
case eTaskAcion.Change:
{
RefreshStatisticsEvent(this, e);
tabControlTop.SelectedIndex = 0;
}
break;
case eTaskAcion.CancelChange:
{
tabControlTop.SelectedIndex = 0;
}
break;
case eTaskAcion.Delete:
{
RefreshStatisticsEvent(this, e);
tabControlTop.SelectedIndex = 0;
}
break;
case eTaskAcion.Reset:
{
RefreshStatisticsEvent(this, e);
tabControlTop.SelectedIndex = 0;
}
break;
default:
break;
}
}
internal void StartSearch(object sender, EventArgs e)
{
AppEventArgs arg = e as AppEventArgs;
this.panel.Show();
SetForegroundWindow();
SetWindowPos();
ShowTaskStatus(string.Format("开始执行任务{0}", arg.message_task.nID));
StartSearchEvent(this, e);
}
internal void StopSearch(object sender, EventArgs e)
{
AppEventArgs arg = e as AppEventArgs;
//ShowTaskStatus(string.Format("空闲"));
StopTaskEvent(sender, e);
this.panel.Hide();
}
internal void EndTask(object sender, EventArgs e)
{
//ShowTaskStatus(string.Format("空闲"));
EndTaskEvent(sender, e);
}
internal void ChangeTask(object sender, EventArgs e)
{
ChangeTaskEvent(this, e);
tabControlTop.SelectedIndex = 1;
}
internal void ShowTaskStatus(object sender, EventArgs e)
{
AppEventArgs arg = e as AppEventArgs;
ShowTaskStatus(arg.message_string);
}
internal void UpdateIP(object sender, EventArgs e)
{
ShowIP();
}
void ShowTaskStatus(string info)
{
toolStripStatusLabel_Status.Text = info;
Logger.Info(info);
}
void ShowIP()
{
string info = string.Format("当前IP地址:{0}", NetworkUtils.GetIpAddress());
toolStripStatusLabel_IP.Text = info;
Logger.Info(info);
}
void CheckWork()
{
if (Appinfo.bWork == true)
{
CheckWorkEvent(this, new AppEventArgs() { });
}
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("点击确定将会退出程序!", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.Cancel)
{
e.Cancel = true; //取消"关闭窗口"事件
return;
}
AppUtils.CloseOtherApp("流量精灵助手监控器");
}
private void MainForm_Deactivate(object sender, EventArgs e)
{
SetForegroundWindow();
}
//把程序显示在最前方
public void SetForegroundWindow()
{
return;
//IntPtr Window_Handle = (IntPtr)AppUtils.FindWindow(null, Appinfo.strTitleName);//查找所有的窗体,看看想查找的句柄是否存在,Microsoft Word 句柄 //
//if (Window_Handle != IntPtr.Zero)
//{
// this.Show();
// this.Activate();
// //this.SetForegroundWindow();
// //SetWindowPos(Window_Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
// //SetWindowPos(Window_Handle, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
// //SetForegroundWindow(Window_Handle);
// ////::AttachThreadInput(dwCurID, dwForeID, FALSE);
// AppUtils.SetForegroundWindow(Window_Handle);
//}
//this.TopMost = true;
//SetForegroundWindow();
//this.Activate();
//this.Focus();
//AppUtils.SetFocus(this.Handle);
if (statisticsForm.bWork)
{
AppUtils.SetWindowPos(this.Handle, -1, 0, 0, 0, 0, 1 | 2);
}
else
{
AppUtils.SetWindowPos(this.Handle, -2, 0, 0, 0, 0, 1 | 2);
}
}
public void SetWindowPos()
{
if (statisticsForm.bWork)
{
this.Location = new Point(0, 0);
}
}
//禁止移动
protected override void WndProc(ref Message m)
{
if (statisticsForm.bWork)
{
if (m.Msg != 0x0112 && m.WParam != (IntPtr)0xF012)
{
base.WndProc(ref m);
}
}
else
base.WndProc(ref m);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SQLite;
using SQLitePCL;
namespace RankHelper
{
class TaskDB: SQLiteConnection
{
//定义属性,便于外部访问数据表
public TableQuery<tagTask> Tasks { get { return this.Table<tagTask>(); } }
public TaskDB(string dbPath) : base(dbPath)
{
//创建数据表
CreateTable<tagTask>();
}
}
class TempleTimeDB : SQLiteConnection
{
//定义属性,便于外部访问数据表
public TableQuery<tagTempleTime> TempleTimes { get { return this.Table<tagTempleTime>(); } }
public TempleTimeDB(string dbPath) : base(dbPath)
{
//创建数据表
CreateTable<tagTempleTime>();
}
}
class SettingDB : SQLiteConnection
{
//定义属性,便于外部访问数据表
public TableQuery<tagSetting> Setting { get { return this.Table<tagSetting>(); } }
public SettingDB(string dbPath) : base(dbPath)
{
//创建数据表
CreateTable<tagSetting>();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccessWeb
{
public class Domain
{
public int ID { get; set; }
public string Name { get; set; }
public eAccessStatus Status { get; set; }
public Domain(int ID=0, String Name = "",eAccessStatus Status = eAccessStatus.none)
{
this.ID = ID;
this.Name =Name;
this.Status = Status;
}
}
public enum eAccessStatus
{
none,
success,
fail
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.ComponentModel;
using SQLite;
using SQLitePCL;
namespace RankHelper
{
public enum eEngines
{
[Description("百度")]
Baidu,
[Description("360")]
Qihu,
[Description("搜狗")]
Sogou,
[Description("神马搜索")]
Sm
}
public enum eSearchType
{
[Description("百度站内")]
OnSite,
[Description("其他站内")]
OffSite
};
public enum eWebBrowser
{
[Description("IE")]
IE,
[Description("IE(移动版)")]
IE_mobile,
[Description("Chrome")]
Chrome,
[Description("Chrome(移动版)")]
Chrome_mobile,
[Description("360")]
Qihu,
[Description("360(移动版)")]
Qihu_mobile,
[Description("搜狗")]
Sogou,
[Description("搜狗(移动版)")]
Sogou_mobile,
[Description("QQ")]
QQ,
[Description("QQ(移动版)")]
QQ_mobile,
[Description("遨游")]
maxthon,
[Description("遨游(移动版)")]
maxthon_mobile,
[Description("世界之窗")]
theworld,
[Description("世界之窗(移动版)")]
theworld_mobile,
[Description("随机")]
Rand
}
public enum ePageAccessType
{
[Description("不访问")]
None,
[Description("随机访问")]
Rand,
[Description("指定访问")]
Appoint
};
public enum eTempleTime
{
[Description("智能分配")]
Rand,
[Description("模板0")]
Temple0,
[Description("模板1")]
Temple1,
[Description("模板2")]
Temple2
};
public class tagTempleTime
{
[PrimaryKey]
public int nID { get; set; }
public bool bCheck00 { get; set; }
public int nCount00 { get; set; }
public int nCount00_Excute { get; set; }
public bool bCheck01 { get; set; }
public int nCount01 { get; set; }
public int nCount01_Excute { get; set; }
public bool bCheck02 { get; set; }
public int nCount02 { get; set; }
public int nCount02_Excute { get; set; }
public bool bCheck03 { get; set; }
public int nCount03 { get; set; }
public int nCount03_Excute { get; set; }
public bool bCheck04 { get; set; }
public int nCount04 { get; set; }
public int nCount04_Excute { get; set; }
public bool bCheck05 { get; set; }
public int nCount05 { get; set; }
public int nCount05_Excute { get; set; }
public bool bCheck06 { get; set; }
public int nCount06 { get; set; }
public int nCount06_Excute { get; set; }
public bool bCheck07 { get; set; }
public int nCount07 { get; set; }
public int nCount07_Excute { get; set; }
public bool bCheck08 { get; set; }
public int nCount08 { get; set; }
public int nCount08_Excute { get; set; }
public bool bCheck09 { get; set; }
public int nCount09 { get; set; }
public int nCount09_Excute { get; set; }
public bool bCheck10 { get; set; }
public int nCount10 { get; set; }
public int nCount10_Excute { get; set; }
public bool bCheck11 { get; set; }
public int nCount11 { get; set; }
public int nCount11_Excute { get; set; }
public bool bCheck12 { get; set; }
public int nCount12 { get; set; }
public int nCount12_Excute { get; set; }
public bool bCheck13 { get; set; }
public int nCount13 { get; set; }
public int nCount13_Excute { get; set; }
public bool bCheck14 { get; set; }
public int nCount14 { get; set; }
public int nCount14_Excute { get; set; }
public bool bCheck15 { get; set; }
public int nCount15 { get; set; }
public int nCount15_Excute { get; set; }
public bool bCheck16 { get; set; }
public int nCount16 { get; set; }
public int nCount16_Excute { get; set; }
public bool bCheck17 { get; set; }
public int nCount17 { get; set; }
public int nCount17_Excute { get; set; }
public bool bCheck18 { get; set; }
public int nCount18 { get; set; }
public int nCount18_Excute { get; set; }
public bool bCheck19 { get; set; }
public int nCount19 { get; set; }
public int nCount19_Excute { get; set; }
public bool bCheck20 { get; set; }
public int nCount20 { get; set; }
public int nCount20_Excute { get; set; }
public bool bCheck21 { get; set; }
public int nCount21 { get; set; }
public int nCount21_Excute { get; set; }
public bool bCheck22 { get; set; }
public int nCount22 { get; set; }
public int nCount22_Excute { get; set; }
public bool bCheck23 { get; set; }
public int nCount23 { get; set; }
public int nCount23_Excute { get; set; }
public tagTempleTime()
{
nID = -1;
bCheck00 = false;
nCount00 = 0; nCount00_Excute = 0;
bCheck01 = false;
nCount01 = 0; nCount01_Excute = 0;
bCheck02 = false;
nCount02 = 0; nCount02_Excute = 0;
bCheck03 = false;
nCount03 = 0; nCount03_Excute = 0;
bCheck04 = false;
nCount04 = 0; nCount04_Excute = 0;
bCheck05 = false;
nCount05 = 0; nCount05_Excute = 0;
bCheck06 = false;
nCount06 = 0; nCount06_Excute = 0;
bCheck07 = false;
nCount07 = 0; nCount07_Excute = 0;
bCheck08 = false;
nCount08 = 0; nCount08_Excute = 0;
bCheck09 = false;
nCount09 = 0; nCount09_Excute = 0;
bCheck10 = false;
nCount10 = 0; nCount10_Excute = 0;
bCheck11 = false;
nCount11 = 0; nCount11_Excute = 0;
bCheck12 = false;
nCount12 = 0; nCount12_Excute = 0;
bCheck13 = false;
nCount13 = 0; nCount13_Excute = 0;
bCheck14 = false;
nCount14 = 0; nCount14_Excute = 0;
bCheck15 = false;
nCount15 = 0; nCount15_Excute = 0;
bCheck16 = false;
nCount16 = 0; nCount16_Excute = 0;
bCheck17 = false;
nCount17 = 0; nCount17_Excute = 0;
bCheck18 = false;
nCount18 = 0; nCount18_Excute = 0;
bCheck19 = false;
nCount19 = 0; nCount19_Excute = 0;
bCheck20 = false;
nCount20 = 0; nCount20_Excute = 0;
bCheck21 = false;
nCount21 = 0; nCount21_Excute = 0;
bCheck22 = false;
nCount22 = 0; nCount22_Excute = 0;
bCheck23 = false;
nCount23 = 0; nCount23_Excute = 0;
}
//public tagTempleTime(bool bCheck,int nCount)
//{
// this.bCheck = bCheck;
// this.nCount = nCount;
//}
}
public enum eTaskAcion
{
[Description("添加")]
Add,
[Description("修改")]
Change,
[Description("取消修改")]
CancelChange,
[Description("删除")]
Delete,
[Description("重置任务")]
Reset
};
public enum EWebbrowserState
{
Start,//打开搜索引擎
Search,//进行关键词搜索
SearchSite,//搜索站点
AccessSite,//访问站点
AccessPage,//搜索内页
none//搜索内页
}
public class tagTask
{
[PrimaryKey, AutoIncrement]
public int nID { get; set; }
public eTaskAcion taskAcion { get; set; }
public EWebbrowserState webState { get; set; }
public bool bCheck { get; set; }
public string strOnSiteUrl { get; set; }
public string strKeyword { get; set; }
public string strTitle { get; set; }
public string strSiteUrl { get; set; }
public eEngines engine { get; set; }
public eWebBrowser webBrowser { get; set; }
public int nEngineTime { get; set; }
public eSearchType searchType { get; set; }
public int nCountPage { get; set; }
public int nCountVaildToday { get; set; }
public int nCountInvaildToday { get; set; }
public int nCountTotal { get; set; }
public int nCountExcuteToday { get; set; }
public int nCountLimit { get; set; }
public int nSiteTime { get; set; }
public DateTime tViewSiteLastTime { get; set; }
public ePageAccessType pageAccessType { get; set; }
public string strPageUrl { get; set; }
public int nCountPageVaildToday { get; set; }
public int nCountPageInvaildToday { get; set; }
public int nCountPageTotal { get; set; }
public int nPageTime { get; set; }
public DateTime tViewPageLastTime { get; set; }
public DateTime tCreateTime { get; set; }
public tagTempleTime tagtempleTime;// { get; set; }
public eTempleTime templeTime { get; set; }
public tagTask()
{
nID = -1;
taskAcion = eTaskAcion.Add;
webState = EWebbrowserState.none;
bCheck = true;
strKeyword = "";
strTitle = "";
strSiteUrl = "";
engine = eEngines.Baidu;
webBrowser = eWebBrowser.IE;
nEngineTime = 3;
searchType = eSearchType.OffSite;
nCountPage = 50;
nCountVaildToday = 0;
nCountInvaildToday = 0;
nCountTotal = 0;
nCountExcuteToday = 0;
nCountLimit = 30;
nSiteTime = 3;
tViewSiteLastTime = new DateTime();
pageAccessType = ePageAccessType.None;
strPageUrl = "";
nCountPageVaildToday = 0;
nCountPageInvaildToday = 0;
nCountPageTotal = 0;
nPageTime = 3;
tViewPageLastTime = new DateTime();
tCreateTime = DateTime.Now;
tagtempleTime = new tagTempleTime();
tagtempleTime.nID = nID;
templeTime = eTempleTime.Rand;
}
};
public class define
{
public static string GetEnumName(Enum en)
{
Type temType = en.GetType();
MemberInfo[] memberInfos = temType.GetMember(en.ToString());
if (memberInfos != null && memberInfos.Length > 0)
{
object[] objs = memberInfos[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (objs != null && objs.Length > 0)
{
return ((DescriptionAttribute)objs[0]).Description;
}
}
return en.ToString();
}
}
public class AppEventArgs : EventArgs
{
public string message_string;
public bool message_bool;
public tagTask message_task;
}
public enum eConnectionType
{
[Description("宽带连接")]
Broadband
};
public enum eConnectionInvert
{
[Description("30秒")]
s30,
[Description("60秒")]
s60,
[Description("90秒")]
s90
};
public class tagSetting
{
[PrimaryKey]
public int nID { get; set; }
public bool bCheck { get; set; }
public string strUsername { get; set; }
public string strPwd { get; set; }
public eConnectionType connectionType { get; set; }
public eConnectionInvert connectionInvert { get; set; }
public int nCount { get; set; }
public string IP { get; set; }
public tagSetting()
{
nID = 0;
bCheck = true;
strUsername = "";
strPwd = "";
connectionType = eConnectionType.Broadband;
connectionInvert = eConnectionInvert.s60;
nCount = 9999;
IP = "";
}
};
public class tagSearchResult
{
public int nItem;
public bool bFinish;
public bool bMatch;
public tagSearchResult()
{
nItem = 0;
bFinish = true;
bMatch = true;
}
};
}
<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 log4net;
namespace RankHelper
{
public partial class SettingForm : Form
{
private static ILog Logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
tagTask currentTask;
public event EventHandler RefreshStatisticsEvent; //使用默认的事件处理委托
public SettingForm()
{
InitializeComponent();
Init();
InitData();
}
void Init()
{
foreach (eEngines item in Enum.GetValues(typeof(eEngines)))
{
if (item!= eEngines.Sm)
{
comboBox_Engines.Items.Add(define.GetEnumName(item));
}
}
comboBox_Engines.SelectedIndex = 0;
comboBox_Engines.DropDownStyle = ComboBoxStyle.DropDownList;
foreach (eSearchType item in Enum.GetValues(typeof(eSearchType)))
{
comboBox_searchType.Items.Add(define.GetEnumName(item));
}
comboBox_searchType.SelectedIndex = 0;
comboBox_searchType.DropDownStyle = ComboBoxStyle.DropDownList;
foreach (eWebBrowser item in Enum.GetValues(typeof(eWebBrowser)))
{
comboBox_webBrowser.Items.Add(define.GetEnumName(item));
}
comboBox_webBrowser.SelectedIndex = 0;
comboBox_webBrowser.DropDownStyle = ComboBoxStyle.DropDownList;
foreach (ePageAccessType item in Enum.GetValues(typeof(ePageAccessType)))
{
comboBox_PageAccessType.Items.Add(define.GetEnumName(item));
}
comboBox_PageAccessType.SelectedIndex = 0;
comboBox_PageAccessType.DropDownStyle = ComboBoxStyle.DropDownList;
toolTip_title.IsBalloon = true;
toolTip_title.SetToolTip(label_Title, "网站标题和链接至少输入一个");
toolTip_title.SetToolTip(label_siteUrl, "网站标题和链接至少输入一个");
toolTip_time.IsBalloon = true;
toolTip_time.SetToolTip(label_EngineTime, "输入1~59,单位秒");
toolTip_time.SetToolTip(label_siteTime, "输入1~59,单位秒");
toolTip_time.SetToolTip(textBox_pageTime, "输入1~59,单位秒");
toolTip_pageCount.IsBalloon = true;
toolTip_pageCount.SetToolTip(label_CountPage, "搜索的页码数量限制,输入1~99,默认50");
toolTip_siteCount.IsBalloon = true;
toolTip_siteCount.SetToolTip(label_CountLimit, "输入1~9999,默认30");
toolTip_Engines.IsBalloon = true;
toolTip_Engines.SetToolTip(label_Engines, "神马搜索只支持浏览器移动版,选择非移动版默认设为该浏览器移动版");
toolTip_Engines.SetToolTip(label_webBrowser, "神马搜索只支持浏览器移动版,选择非移动版默认设为该浏览器移动版");
foreach (eTempleTime item in Enum.GetValues(typeof(eTempleTime)))
{
comboBox_templeTime.Items.Add(define.GetEnumName(item));
}
comboBox_templeTime.SelectedIndex = 0;
comboBox_templeTime.DropDownStyle = ComboBoxStyle.DropDownList;
textBox_CountLimit.Enabled = false;
}
void InitData()
{
tagTask newTask = new tagTask();
SetTask(newTask);
}
void SetTask(tagTask task)
{
checkBox_check.Checked = task.bCheck;
comboBox_Engines.SelectedIndex = (int)task.engine;
comboBox_searchType.SelectedIndex = (int)task.searchType;
textBox_onSiteUrl.Text = task.strOnSiteUrl;
textBox_keyword.Text = task.strKeyword;
textBox_Title.Text = task.strTitle;
textBox_siteUrl.Text = task.strSiteUrl;
textBox_EngineTime.Text = task.nEngineTime.ToString();
textBox_CountPage.Text = task.nCountPage.ToString();
comboBox_webBrowser.SelectedIndex = (int)task.webBrowser;
textBox_CountLimit.Text = task.nCountLimit.ToString();
textBox_siteTime.Text = task.nSiteTime.ToString();
comboBox_PageAccessType.SelectedIndex = (int)task.pageAccessType;
textBox_pageUrl.Text = task.strPageUrl.ToString();
textBox_pageTime.Text = task.nPageTime.ToString();
comboBox_templeTime.SelectedIndex = (int)task.templeTime;
comboBox_templeTime_SelectedIndexChanged(comboBox_templeTime, new EventArgs());
checkBox_00.Checked = task.tagtempleTime.bCheck00;
checkBox_01.Checked = task.tagtempleTime.bCheck01;
checkBox_02.Checked = task.tagtempleTime.bCheck02;
checkBox_03.Checked = task.tagtempleTime.bCheck03;
checkBox_04.Checked = task.tagtempleTime.bCheck04;
checkBox_05.Checked = task.tagtempleTime.bCheck05;
checkBox_06.Checked = task.tagtempleTime.bCheck06;
checkBox_07.Checked = task.tagtempleTime.bCheck07;
checkBox_08.Checked = task.tagtempleTime.bCheck08;
checkBox_09.Checked = task.tagtempleTime.bCheck09;
checkBox_10.Checked = task.tagtempleTime.bCheck10;
checkBox_11.Checked = task.tagtempleTime.bCheck11;
checkBox_12.Checked = task.tagtempleTime.bCheck12;
checkBox_13.Checked = task.tagtempleTime.bCheck13;
checkBox_14.Checked = task.tagtempleTime.bCheck14;
checkBox_15.Checked = task.tagtempleTime.bCheck15;
checkBox_16.Checked = task.tagtempleTime.bCheck16;
checkBox_17.Checked = task.tagtempleTime.bCheck17;
checkBox_18.Checked = task.tagtempleTime.bCheck18;
checkBox_19.Checked = task.tagtempleTime.bCheck19;
checkBox_20.Checked = task.tagtempleTime.bCheck20;
checkBox_21.Checked = task.tagtempleTime.bCheck21;
checkBox_22.Checked = task.tagtempleTime.bCheck22;
checkBox_23.Checked = task.tagtempleTime.bCheck23;
textBox_00.Text = task.tagtempleTime.nCount00.ToString();
textBox_01.Text = task.tagtempleTime.nCount01.ToString();
textBox_02.Text = task.tagtempleTime.nCount02.ToString();
textBox_03.Text = task.tagtempleTime.nCount03.ToString();
textBox_04.Text = task.tagtempleTime.nCount04.ToString();
textBox_05.Text = task.tagtempleTime.nCount05.ToString();
textBox_06.Text = task.tagtempleTime.nCount06.ToString();
textBox_07.Text = task.tagtempleTime.nCount07.ToString();
textBox_08.Text = task.tagtempleTime.nCount08.ToString();
textBox_09.Text = task.tagtempleTime.nCount09.ToString();
textBox_10.Text = task.tagtempleTime.nCount10.ToString();
textBox_11.Text = task.tagtempleTime.nCount11.ToString();
textBox_12.Text = task.tagtempleTime.nCount12.ToString();
textBox_13.Text = task.tagtempleTime.nCount13.ToString();
textBox_14.Text = task.tagtempleTime.nCount14.ToString();
textBox_15.Text = task.tagtempleTime.nCount15.ToString();
textBox_16.Text = task.tagtempleTime.nCount16.ToString();
textBox_17.Text = task.tagtempleTime.nCount17.ToString();
textBox_18.Text = task.tagtempleTime.nCount18.ToString();
textBox_19.Text = task.tagtempleTime.nCount19.ToString();
textBox_20.Text = task.tagtempleTime.nCount20.ToString();
textBox_21.Text = task.tagtempleTime.nCount21.ToString();
textBox_22.Text = task.tagtempleTime.nCount22.ToString();
textBox_23.Text = task.tagtempleTime.nCount23.ToString();
switch (task.taskAcion)
{
case eTaskAcion.Add:
{
button_batchAdd.Enabled = true;
button_Add.Enabled = true;
button_Change.Enabled = false;
button_Cancel.Enabled = false;
button_Reset.Enabled = false;
button_Delete.Enabled = false;
}
break;
case eTaskAcion.Change:
case eTaskAcion.Delete:
{
button_batchAdd.Enabled = false;
button_Add.Enabled = false;
button_Change.Enabled = true;
button_Cancel.Enabled = true;
button_Reset.Enabled = true;
button_Delete.Enabled = true;
}
break;
default:
break;
}
}
tagTask GetTask(tagTask task)
{
task.bCheck = checkBox_check.Checked;
task.engine = (eEngines)comboBox_Engines.SelectedIndex;
task.searchType = (eSearchType)comboBox_searchType.SelectedIndex;
task.strOnSiteUrl = textBox_onSiteUrl.Text;
task.strKeyword = textBox_keyword.Text;
task.strTitle = textBox_Title.Text;
task.strSiteUrl = textBox_siteUrl.Text;
task.nEngineTime = int.Parse(textBox_EngineTime.Text);
task.nCountPage = int.Parse(textBox_CountPage.Text);
task.webBrowser = (eWebBrowser)comboBox_webBrowser.SelectedIndex;
task.nCountLimit = int.Parse(textBox_CountLimit.Text);
task.nSiteTime = int.Parse(textBox_siteTime.Text);
task.pageAccessType = (ePageAccessType)comboBox_PageAccessType.SelectedIndex;
task.strPageUrl = textBox_pageUrl.Text;
task.nPageTime = int.Parse(textBox_pageTime.Text);
task.tagtempleTime.bCheck00 = checkBox_00.Checked;
task.tagtempleTime.bCheck01 = checkBox_01.Checked;
task.tagtempleTime.bCheck02 = checkBox_02.Checked;
task.tagtempleTime.bCheck03 = checkBox_03.Checked;
task.tagtempleTime.bCheck04 = checkBox_04.Checked;
task.tagtempleTime.bCheck05 = checkBox_05.Checked;
task.tagtempleTime.bCheck06 = checkBox_06.Checked;
task.tagtempleTime.bCheck07 = checkBox_07.Checked;
task.tagtempleTime.bCheck08 = checkBox_08.Checked;
task.tagtempleTime.bCheck09 = checkBox_09.Checked;
task.tagtempleTime.bCheck10 = checkBox_10.Checked;
task.tagtempleTime.bCheck11 = checkBox_11.Checked;
task.tagtempleTime.bCheck12 = checkBox_12.Checked;
task.tagtempleTime.bCheck13 = checkBox_13.Checked;
task.tagtempleTime.bCheck14 = checkBox_14.Checked;
task.tagtempleTime.bCheck15 = checkBox_15.Checked;
task.tagtempleTime.bCheck16 = checkBox_16.Checked;
task.tagtempleTime.bCheck17 = checkBox_17.Checked;
task.tagtempleTime.bCheck18 = checkBox_18.Checked;
task.tagtempleTime.bCheck19 = checkBox_19.Checked;
task.tagtempleTime.bCheck20 = checkBox_20.Checked;
task.tagtempleTime.bCheck21 = checkBox_21.Checked;
task.tagtempleTime.bCheck22 = checkBox_22.Checked;
task.tagtempleTime.bCheck23 = checkBox_23.Checked;
task.tagtempleTime.nCount00 = int.Parse(textBox_00.Text);
task.tagtempleTime.nCount01 = int.Parse(textBox_01.Text);
task.tagtempleTime.nCount02 = int.Parse(textBox_02.Text);
task.tagtempleTime.nCount03 = int.Parse(textBox_03.Text);
task.tagtempleTime.nCount04 = int.Parse(textBox_04.Text);
task.tagtempleTime.nCount05 = int.Parse(textBox_05.Text);
task.tagtempleTime.nCount06 = int.Parse(textBox_06.Text);
task.tagtempleTime.nCount07 = int.Parse(textBox_07.Text);
task.tagtempleTime.nCount08 = int.Parse(textBox_08.Text);
task.tagtempleTime.nCount09 = int.Parse(textBox_09.Text);
task.tagtempleTime.nCount10 = int.Parse(textBox_10.Text);
task.tagtempleTime.nCount11 = int.Parse(textBox_11.Text);
task.tagtempleTime.nCount12 = int.Parse(textBox_12.Text);
task.tagtempleTime.nCount13 = int.Parse(textBox_13.Text);
task.tagtempleTime.nCount14 = int.Parse(textBox_14.Text);
task.tagtempleTime.nCount15 = int.Parse(textBox_15.Text);
task.tagtempleTime.nCount16 = int.Parse(textBox_16.Text);
task.tagtempleTime.nCount17 = int.Parse(textBox_17.Text);
task.tagtempleTime.nCount18 = int.Parse(textBox_18.Text);
task.tagtempleTime.nCount19 = int.Parse(textBox_19.Text);
task.tagtempleTime.nCount20 = int.Parse(textBox_20.Text);
task.tagtempleTime.nCount21 = int.Parse(textBox_21.Text);
task.tagtempleTime.nCount22 = int.Parse(textBox_22.Text);
task.tagtempleTime.nCount23 = int.Parse(textBox_23.Text);
task.templeTime = (eTempleTime)comboBox_templeTime.SelectedIndex;
return task;
}
private void comboBox_PageAccessType_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox comboBox = (ComboBox)sender;
switch((ePageAccessType)comboBox.SelectedIndex)
{
case ePageAccessType.None:
case ePageAccessType.Rand:
{
textBox_pageUrl.Enabled = false;
textBox_pageTime.Enabled = false;
}
break;
case ePageAccessType.Appoint:
{
textBox_pageUrl.Enabled = true;
textBox_pageTime.Enabled = true;
}
break;
default:
break;
}
}
//添加任务
private void button_Add_Click(object sender, EventArgs e)
{
currentTask = new tagTask();
GetTask(currentTask);
if(!CheckVaild(currentTask))
{
return;
}
currentTask.taskAcion = eTaskAcion.Add;
Appinfo.AddTask(currentTask);
//MainForm mainForm = (MainForm)this.Parent;
RefreshStatisticsEvent(this, new AppEventArgs() { message_task = currentTask });
string strInfo;
strInfo = string.Format("添加一个新任务完毕,编号{0}", currentTask.nID);
Logger.Info(strInfo);
MessageBox.Show(strInfo, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
InitData();
}
private bool CheckVaild(tagTask task)
{
if(task.strKeyword.Trim().Equals(""))
{
MessageBox.Show("请输入关键词", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
textBox_keyword.Focus();
return false;
}
if (task.strTitle.Trim().Equals("") && task.strSiteUrl.Trim().Equals(""))
{
MessageBox.Show("请输入网站标题或链接", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
textBox_Title.Focus();
return false;
}
if (task.nCountPage < 0 || task.nCountPage > 999)
{
MessageBox.Show("请输入正确的搜索页码0~999", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
textBox_CountPage.Focus();
return false;
}
if (task.nCountLimit < 0 || task.nCountLimit > 999)
{
MessageBox.Show("请输入正确的每天点击量0~999", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
textBox_CountLimit.Focus();
return false;
}
if(task.pageAccessType == ePageAccessType.Appoint)
{
if (task.strPageUrl.Trim().Equals(""))
{
MessageBox.Show("请输入指定访问链接", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
textBox_pageUrl.Focus();
return false;
}
}
return true;
}
private void comboBox_Engines_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox comboBox = (ComboBox)sender;
switch ((eEngines)comboBox.SelectedIndex)
{
case eEngines.Baidu:
{
comboBox_searchType.Enabled = true;
}
break;
case eEngines.Qihu:
case eEngines.Sogou:
case eEngines.Sm:
{
comboBox_searchType.Enabled = false;
comboBox_searchType.SelectedIndex = 0;
}
break;
default:
break;
}
}
private void textBox_EngineTime_TextChanged(object sender, EventArgs e)
{
TextBox textBox = (TextBox)sender;
if(textBox.Text.Trim().Equals(""))
{
return;
}
int nTime = int.Parse(textBox.Text);
if(nTime<1)
{
textBox.Text = "1";
}
else if (nTime > 59)
{
textBox.Text = "59";
}
}
private void textBox_EngineTime_Leave(object sender, EventArgs e)
{
TextBox textBox = (TextBox)sender;
if (textBox.Text.Trim().Equals(""))
{
textBox.Text = "3";
}
}
private void textBox_EngineTime_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 0x20) e.KeyChar = (char)0; //禁止空格键
if ((e.KeyChar == 0x2D) && (((TextBox)sender).Text.Length == 0)) return; //处理负数
if (e.KeyChar > 0x20)
{
try
{
double.Parse(((TextBox)sender).Text + e.KeyChar.ToString());
}
catch
{
e.KeyChar = (char)0; //处理非法字符
}
}
}
private void textBox_CountPage_TextChanged(object sender, EventArgs e)
{
TextBox textBox = (TextBox)sender;
if (textBox.Text.Trim().Equals(""))
{
return;
}
int nTime = int.Parse(textBox.Text);
if (nTime < 1)
{
textBox.Text = "1";
}
else if (nTime > 99)
{
textBox.Text = "99";
}
}
private void textBox_CountPage_Leave(object sender, EventArgs e)
{
TextBox textBox = (TextBox)sender;
if (textBox.Text.Trim().Equals(""))
{
textBox.Text = "50";
}
}
private void textBox_CountLimit_TextChanged(object sender, EventArgs e)
{
TextBox textBox = (TextBox)sender;
if (textBox.Text.Trim().Equals(""))
{
return;
}
int nTime = int.Parse(textBox.Text);
if (nTime < 0)
{
textBox.Text = "0";
}
else if (nTime > 9999)
{
textBox.Text = "9999";
}
}
private void textBox_CountLimit_Leave(object sender, EventArgs e)
{
TextBox textBox = (TextBox)sender;
if (textBox.Text.Trim().Equals(""))
{
textBox.Text = "0";
}
}
internal void ChangeTask(object sender, EventArgs e)
{
AppEventArgs arg = e as AppEventArgs;
currentTask = arg.message_task;
SetTask(currentTask);
}
private void button_Change_Click(object sender, EventArgs e)
{
GetTask(currentTask);
if (!CheckVaild(currentTask))
{
return;
}
currentTask.taskAcion = eTaskAcion.Change;
if (!Appinfo.ChangeTask(currentTask))
{
MessageBox.Show("未找到符合的任务", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
RefreshStatisticsEvent(this, new AppEventArgs() { message_task = currentTask });
string strInfo;
strInfo = string.Format("修改任务完毕,编号{0}", currentTask.nID);
MessageBox.Show(strInfo, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
InitData();
}
private void button_Delete_Click(object sender, EventArgs e)
{
currentTask.taskAcion = eTaskAcion.Delete;
if (!Appinfo.DeleteTask(currentTask))
{
MessageBox.Show("未找到符合的任务", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
RefreshStatisticsEvent(this, new AppEventArgs() { message_task = currentTask });
string strInfo;
strInfo = string.Format("删除任务完毕,编号{0}", currentTask.nID);
MessageBox.Show(strInfo, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
InitData();
}
private void button_Cancel_Click(object sender, EventArgs e)
{
currentTask.taskAcion = eTaskAcion.CancelChange;
RefreshStatisticsEvent(this, new AppEventArgs() { message_task = currentTask });
InitData();
}
private void button_Reset_Click(object sender, EventArgs e)
{
currentTask.nCountExcuteToday = 0;
currentTask.tagtempleTime.nCount00_Excute = 0;
currentTask.tagtempleTime.nCount01_Excute = 0;
currentTask.tagtempleTime.nCount02_Excute = 0;
currentTask.tagtempleTime.nCount03_Excute = 0;
currentTask.tagtempleTime.nCount04_Excute = 0;
currentTask.tagtempleTime.nCount05_Excute = 0;
currentTask.tagtempleTime.nCount06_Excute = 0;
currentTask.tagtempleTime.nCount07_Excute = 0;
currentTask.tagtempleTime.nCount08_Excute = 0;
currentTask.tagtempleTime.nCount09_Excute = 0;
currentTask.tagtempleTime.nCount10_Excute = 0;
currentTask.tagtempleTime.nCount11_Excute = 0;
currentTask.tagtempleTime.nCount12_Excute = 0;
currentTask.tagtempleTime.nCount13_Excute = 0;
currentTask.tagtempleTime.nCount14_Excute = 0;
currentTask.tagtempleTime.nCount15_Excute = 0;
currentTask.tagtempleTime.nCount16_Excute = 0;
currentTask.tagtempleTime.nCount17_Excute = 0;
currentTask.tagtempleTime.nCount18_Excute = 0;
currentTask.tagtempleTime.nCount19_Excute = 0;
currentTask.tagtempleTime.nCount20_Excute = 0;
currentTask.tagtempleTime.nCount21_Excute = 0;
currentTask.tagtempleTime.nCount22_Excute = 0;
currentTask.tagtempleTime.nCount23_Excute = 0;
currentTask.taskAcion = eTaskAcion.CancelChange;
RefreshStatisticsEvent(this, new AppEventArgs() { message_task = currentTask });
InitData();
}
internal void ShowTab(object sender, EventArgs e)
{
InitData();
}
private void textBox_00_Leave(object sender, EventArgs e)
{
TextBox textBox = (TextBox)sender;
if (textBox.Text.Trim().Equals(""))
{
textBox.Text = "0";
}
RefreshTextBox_CountLimit();
}
private void textBox_00_TextChanged(object sender, EventArgs e)
{
TextBox textBox = (TextBox)sender;
if (textBox.Text.Trim().Equals(""))
{
return;
}
int nTime = int.Parse(textBox.Text);
if (nTime < 0 )
{
textBox.Text = "0";
}
else if (nTime > 99)
{
textBox.Text = "99";
}
RefreshTextBox_CountLimit();
}
private void comboBox_templeTime_SelectedIndexChanged(object sender, EventArgs e)
{
bool[] arrayCheck = new bool[] { };
int[] arrayCount = new int[] { };
ComboBox comboBox = (ComboBox)sender;
switch ((eTempleTime)comboBox.SelectedIndex)
{
case eTempleTime.Rand:
{
Random rd = new Random();
int i = rd.Next()%10;
arrayCheck = new bool[24]{ Convert.ToBoolean(rd.Next()%2),Convert.ToBoolean(rd.Next()%2),Convert.ToBoolean(rd.Next()%2),Convert.ToBoolean(rd.Next()%2),Convert.ToBoolean(rd.Next()%2),Convert.ToBoolean(rd.Next()%2),Convert.ToBoolean(rd.Next()%2),Convert.ToBoolean(rd.Next()%2),Convert.ToBoolean(rd.Next()%2),Convert.ToBoolean(rd.Next()%2),
Convert.ToBoolean(rd.Next()%2),Convert.ToBoolean(rd.Next()%2),Convert.ToBoolean(rd.Next()%2),Convert.ToBoolean(rd.Next()%2),Convert.ToBoolean(rd.Next()%2),Convert.ToBoolean(rd.Next()%2),Convert.ToBoolean(rd.Next()%2),Convert.ToBoolean(rd.Next()%2),Convert.ToBoolean(rd.Next()%2),Convert.ToBoolean(rd.Next()%2),
Convert.ToBoolean(rd.Next()%2),Convert.ToBoolean(rd.Next()%2),Convert.ToBoolean(rd.Next()%2),Convert.ToBoolean(rd.Next()%2)};
arrayCount = new int[24]{ rd.Next()%10,rd.Next()%10,rd.Next()%10,rd.Next()%10,rd.Next()%10,rd.Next()%10,rd.Next()%10,rd.Next()%10,rd.Next()%10,rd.Next()%10,
rd.Next()%10,rd.Next()%10,rd.Next()%10,rd.Next()%10,rd.Next()%10,rd.Next()%10,rd.Next()%10,rd.Next()%10,rd.Next()%10,rd.Next()%10,
rd.Next()%10,rd.Next()%10,rd.Next()%10,rd.Next()%10};
}
break;
case eTempleTime.Temple0:
{
arrayCheck = new bool[24]{ false, false, false, false, false, false, false, false, false, false,
false,false,false,false,false,false,false,false,false,false,
false,false,false,false};
arrayCount = new int[24]{ 0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0};
}
break;
case eTempleTime.Temple1:
{
arrayCheck = new bool[24]{ true, true, true, true, true, true, true, true, true, true,
true,true,true,true,true,true,true,true,true,true,
true,true,true,true};
arrayCount = new int[24]{ 1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1};
}
break;
case eTempleTime.Temple2:
{
arrayCheck = new bool[24]{ true, true, true, true, true, true, true, true, true, true,
true,true,true,true,true,true,true,true,true,true,
true,true,true,true};
arrayCount = new int[24]{ 2,2,2,2,2,2,2,2,2,2,
2,2,2,2,2,2,2,2,2,2,
2,2,2,2};
}
break;
default:
break;
}
checkBox_00.Checked = arrayCheck[0];
checkBox_01.Checked = arrayCheck[1];
checkBox_02.Checked = arrayCheck[2];
checkBox_03.Checked = arrayCheck[3];
checkBox_04.Checked = arrayCheck[4];
checkBox_05.Checked = arrayCheck[5];
checkBox_06.Checked = arrayCheck[6];
checkBox_07.Checked = arrayCheck[7];
checkBox_08.Checked = arrayCheck[8];
checkBox_09.Checked = arrayCheck[9];
checkBox_10.Checked = arrayCheck[10];
checkBox_11.Checked = arrayCheck[11];
checkBox_12.Checked = arrayCheck[12];
checkBox_13.Checked = arrayCheck[13];
checkBox_14.Checked = arrayCheck[14];
checkBox_15.Checked = arrayCheck[15];
checkBox_16.Checked = arrayCheck[16];
checkBox_17.Checked = arrayCheck[17];
checkBox_18.Checked = arrayCheck[18];
checkBox_19.Checked = arrayCheck[19];
checkBox_20.Checked = arrayCheck[20];
checkBox_21.Checked = arrayCheck[21];
checkBox_22.Checked = arrayCheck[22];
checkBox_23.Checked = arrayCheck[23];
textBox_00.Text = arrayCount[0].ToString();
textBox_01.Text = arrayCount[1].ToString();
textBox_02.Text = arrayCount[2].ToString();
textBox_03.Text = arrayCount[3].ToString();
textBox_04.Text = arrayCount[4].ToString();
textBox_05.Text = arrayCount[5].ToString();
textBox_06.Text = arrayCount[6].ToString();
textBox_07.Text = arrayCount[7].ToString();
textBox_08.Text = arrayCount[8].ToString();
textBox_09.Text = arrayCount[9].ToString();
textBox_10.Text = arrayCount[10].ToString();
textBox_11.Text = arrayCount[11].ToString();
textBox_12.Text = arrayCount[12].ToString();
textBox_13.Text = arrayCount[13].ToString();
textBox_14.Text = arrayCount[14].ToString();
textBox_15.Text = arrayCount[15].ToString();
textBox_16.Text = arrayCount[16].ToString();
textBox_17.Text = arrayCount[17].ToString();
textBox_18.Text = arrayCount[18].ToString();
textBox_19.Text = arrayCount[19].ToString();
textBox_20.Text = arrayCount[20].ToString();
textBox_21.Text = arrayCount[21].ToString();
textBox_22.Text = arrayCount[22].ToString();
textBox_23.Text = arrayCount[23].ToString();
RefreshTextBox_CountLimit();
}
private void RefreshTextBox_CountLimit()
{
int nCountLimit = 0;
nCountLimit += checkBox_00.Checked ? int.Parse((textBox_00.Text == "")?"0": textBox_00.Text) : 0;
nCountLimit += checkBox_01.Checked ? int.Parse((textBox_01.Text == "")?"0": textBox_01.Text) : 0;
nCountLimit += checkBox_02.Checked ? int.Parse((textBox_02.Text == "")?"0": textBox_02.Text) : 0;
nCountLimit += checkBox_03.Checked ? int.Parse((textBox_03.Text == "")?"0": textBox_03.Text) : 0;
nCountLimit += checkBox_04.Checked ? int.Parse((textBox_04.Text == "")?"0": textBox_04.Text) : 0;
nCountLimit += checkBox_05.Checked ? int.Parse((textBox_05.Text == "")?"0": textBox_05.Text) : 0;
nCountLimit += checkBox_06.Checked ? int.Parse((textBox_06.Text == "")?"0": textBox_06.Text) : 0;
nCountLimit += checkBox_07.Checked ? int.Parse((textBox_07.Text == "")?"0": textBox_07.Text) : 0;
nCountLimit += checkBox_08.Checked ? int.Parse((textBox_08.Text == "")?"0": textBox_08.Text) : 0;
nCountLimit += checkBox_09.Checked ? int.Parse((textBox_09.Text == "")?"0": textBox_09.Text) : 0;
nCountLimit += checkBox_10.Checked ? int.Parse((textBox_10.Text == "")?"0": textBox_10.Text) : 0;
nCountLimit += checkBox_11.Checked ? int.Parse((textBox_11.Text == "")?"0": textBox_11.Text) : 0;
nCountLimit += checkBox_12.Checked ? int.Parse((textBox_12.Text == "")?"0": textBox_12.Text) : 0;
nCountLimit += checkBox_13.Checked ? int.Parse((textBox_13.Text == "")?"0": textBox_13.Text) : 0;
nCountLimit += checkBox_14.Checked ? int.Parse((textBox_14.Text == "")?"0": textBox_14.Text) : 0;
nCountLimit += checkBox_15.Checked ? int.Parse((textBox_15.Text == "")?"0": textBox_15.Text) : 0;
nCountLimit += checkBox_16.Checked ? int.Parse((textBox_16.Text == "")?"0": textBox_16.Text) : 0;
nCountLimit += checkBox_17.Checked ? int.Parse((textBox_17.Text == "")?"0": textBox_17.Text) : 0;
nCountLimit += checkBox_18.Checked ? int.Parse((textBox_18.Text == "")?"0": textBox_18.Text) : 0;
nCountLimit += checkBox_19.Checked ? int.Parse((textBox_19.Text == "")?"0": textBox_19.Text) : 0;
nCountLimit += checkBox_20.Checked ? int.Parse((textBox_20.Text == "")?"0": textBox_20.Text) : 0;
nCountLimit += checkBox_21.Checked ? int.Parse((textBox_21.Text == "")?"0": textBox_21.Text) : 0;
nCountLimit += checkBox_22.Checked ? int.Parse((textBox_22.Text == "")?"0": textBox_22.Text) : 0;
nCountLimit += checkBox_23.Checked ? int.Parse((textBox_23.Text == "")?"0": textBox_23.Text) : 0;
textBox_CountLimit.Text = nCountLimit.ToString();
}
private void checkBox_00_CheckedChanged(object sender, EventArgs e)
{
RefreshTextBox_CountLimit();
}
private void comboBox_searchType_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox comboBox = (ComboBox)sender;
switch ((eSearchType)comboBox.SelectedIndex)
{
case eSearchType.OnSite:
{
label_onSiteUrl.Visible = false;
textBox_onSiteUrl.Visible = false;
label_tip.Visible = false;
}
break;
case eSearchType.OffSite:
{
label_onSiteUrl.Visible = true;
textBox_onSiteUrl.Visible = true;
label_tip.Visible = true;
}
break;
default:
{
label_onSiteUrl.Visible = false;
textBox_onSiteUrl.Visible = false;
label_tip.Visible = false;
}
break;
}
}
}
}
|
f7b489a8a354874e726b7c15a1671a49b4953f7a
|
[
"Markdown",
"C#"
] | 30
|
C#
|
Unwatch/RankHelper
|
a78a0d2fa7b3d5a4bc6e5dd6bb27296a4285585c
|
57795307b9c03b40df93826fdfe1752d9b5a5708
|
refs/heads/main
|
<repo_name>KanikaChoity/kanikachoity<file_sep>/app.js
const menuBarIcon = document.querySelector(".mobileMenuBar");
const subMenuIcon = document.querySelectorAll(".dropdown");
subMenuIcon.forEach(function(node){
node.querySelector("a").innerHTML += "<i class='fas fa-chevron-down'></i>";
node.addEventListener("click", function (myEvent) {
this.querySelector(".subMenu").classList.toggle("SubMenuShow");
myEvent.stopPropagation();
})
})
menuBarIcon.addEventListener("click", () => {
document.querySelector(".menu").classList.toggle("MenuShow");
})
const sBOXactive = document.querySelector(".sboxwrapper");
const sBoxDactive = document.querySelectorAll(".singlebox");
sBoxDactive.forEach(function (el) {
el.addEventListener('click', function () {
document.querySelector('.sboxactive').classList.remove('sboxactive')
el.classList.add('sboxactive');
})
});
let count = document.querySelectorAll('.singleIcons h2');
count.forEach(e =>{
let datatargetLength = e.getAttribute('data-target');
let index = 0;
setInterval(() => {
if (index < datatargetLength) {
++index;
e.innerHTML = index;
}
}, 1000);
})
|
9d29ad9bf09dcc750fd1ad4545516555e0f47e3a
|
[
"JavaScript"
] | 1
|
JavaScript
|
KanikaChoity/kanikachoity
|
475f91c4eda67f49d58014d035b2182f55743500
|
5243130a7506cad239c41bdcf99cec5c0cfae463
|
refs/heads/master
|
<file_sep># /usr/bin/env python
# -*- coding: utf-8 -*-
# author__ = '<NAME>'
from openpyxl import load_workbook
from openpyxl.chart import PieChart,Reference
def pie_chart(wp):
table = wp.get_sheet_by_name(wp.get_sheet_names()[0])
#生成饼图对象
pie = PieChart()
#图的标题
pie.title = "API接口测试统计"
'''行数和列数都是从1开始的,和遍历用例是一样都是从1开始'''
#获取标签(取范围第一列的最小行数和最大行数)
labels = Reference(table,min_col=4,min_row=6,max_col=4,max_row=7)
#获取数据(取范围第二列的最小行数-1和最大行数)
data = Reference(table,min_col=5,min_row=5,max_col=5,max_row=7)
#添加数据和标签到饼图中
pie.add_data(data,titles_from_data=True)
pie.set_categories(labels)
#放在excel表中
table.add_chart(pie,"A10")
#保存excel
# wb.save("test1.xlsx")
# wb = load_workbook("D:\\PycharmProjects\\test.xlsx")
# pie_chart(wb)<file_sep># /usr/bin/env python
# -*- coding: utf-8 -*-
import requests,openpyxl,re
from api_online_env.bingtu import pie_chart
def read_excel():
path_file = 'D:/PycharmProjects/api_online_requestdata.xlsx'
wp = openpyxl.load_workbook(path_file)
# sheet = wp.get_sheet_by_name("test")
sheet = wp.get_sheet_by_name(wp.get_sheet_names()[1])
for i in range(2,sheet.max_row+1):
if sheet.cell(row=i,column=4).value.replace("\n","").replace("\r","") == "no":
continue
url = sheet.cell(row=i,column=2).value.replace("\n","").replace("\r","")
data = sheet.cell(row=i,column=3).value.replace("\n","").replace("\r","")
#取出检查点
check = sheet.cell(row=i,column=6).value.replace("\n","").replace("\r","")
request_url = url+data
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.4882.400 QQBrowser/9.7.13059.400",
"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Language":"zh-CN,zh;q=0.8",
"Accept-Encoding":"gzip, deflate, sdch"}
res = requests.get(url=request_url,headers=headers)
sheet.cell(row=i,column=5).value = str(res.elapsed.total_seconds())
#检查点校验
if re.search(check,str(res.text)):
sheet.cell(row=i,column=7).value = "成功"
sheet.cell(row=i,column=8).value = str(res.text)
else:
sheet.cell(row=i,column=7).value = "失败"
sheet.cell(row=i,column=8).value = str(res.text)
pie_chart(wp)
wp.save("D:/PycharmProjects/api_online_requestdata_report.xlsx")
# read_excel()
if __name__ == '__main__':
read_excel()
|
65b62647f4c9976e92ca6d624b98af241a31373a
|
[
"Python"
] | 2
|
Python
|
hanshoukai/api_interfaceframe
|
3fc1555e43fc370974aa935bdeef2754ed578b42
|
55d38c90d7467146f1f7e700e99794b33920a561
|
refs/heads/master
|
<repo_name>SlaSerX/highlight<file_sep>/main.go
package main
import (
"bytes"
"io"
"log"
"os"
"regexp"
"sort"
"strconv"
"strings"
"github.com/augustoroman/ansi" // change back to "github.com/mgutz/ansi" when PR is accepted
"github.com/fluxio/iohelpers/line"
)
var usage = `
Usage: highlight <config> <patterns...> [<config> <patterns...>]...
Highlight accepts a sequence of regex patterns to match the input against
and highlight pattern matches. You can optionally also specify configuration
flags that affect how subsequent patterns are highlighted.
Configuration options are:
-w <color> Following patterns apply color to matching words.
-l <color> Following patterns apply color to matching lines.
-lx <color> Following patterns apply color to NON-matching lines.
For line matching, the first pattern to match applies.
For word matching, the first pattern to match applies. Overlapping patterns
are applied with the first match taking precedence.
In addition, the following configuration options are independent of patterns:
-c <color> Set the default color for all unmatched text. If specified
multiple times, the last one takes precedence.
--debug Escape all output, no colors are printed but color codes are
visible.
Colors:
The general form of colors is:
FG[+mod][:BG[+h]]
where FG and BG are colors with optional modifers after a '+'.
Colors may be specified by name:
black red green yellow blue magenta cyan white default
Or via the 256 color palette number:
0 1 2 ...
Modifiers may be combinations of:
d = dim
h = high-intensity
b = bold
u = underline
i = inverse
s = strikethrough
B = blink
h (high-intensity) is the only modifier that can be used for background
colors.
red -> red
red+b -> red bold
red+B -> red blinking
red+u -> red underline
red+bh -> red bold bright
red:white -> red on white
red+b:white+h -> red bold on white bright
red+B:white+h -> red blink on white bright
black+hd -> dark gray
white+d -> dim white
yellow+hb -> bright, bold yellow
red+u:blue+h -> underlined red on a bright blue background
Examples:
Based on a file 'test.txt' with content:
The quick brown fox jumped
over the lazy dog. Pack my box
with five dozen liquor jugs.
cat test.txt | highlight '[Tt]he' '\w{5}'
This will highlight 'The', 'quick' 'brown' and 'jumpe' in the first line,
'the' on the second line, and 'dozen' and 'liquo' on the third.
cat test.txt | highlight -c blue -l yellow lazy -w yellow+bh lazy fox
This will print lines in blue unless they contain 'lazy'. Lines containing
'lazy' will be printed in yellow. The text 'lazy' itself is bright bold
yellow, as is the text 'fox' on any line.
cat test.txt | highlight -c blue -l yellow lazy -l red:blue dog fox -w green 'over.{8}'
This will print lines in blue by default. Lines containing 'lazy' will be
printed in yellow, otherwise lines containig 'dog' or 'fox' will be printed
in red with blue background. Text matching 'over.{8}' will be printed in
green. The final effect will be the first line red, the second line starts
with green and ends in yellow, and the last line will be in the default blue.
`
func main() {
var DefaultWordHighlightColor = ansi.LightBlue
log.SetFlags(0)
colorizer := &ColorizerWriter{Out: os.Stdout}
// The current rule as we are parsing the command-line. This may be either a
// WordRule or a LineRule.
var current Rule
for i := 1; i < len(os.Args); i++ {
arg := os.Args[i]
if strings.HasPrefix(arg, "-") {
mode := strings.TrimLeft(arg, "-")
if mode == "h" || mode == "help" {
log.Println(usage)
os.Exit(0)
} else if mode == "debug" {
colorizer.Out = EscapingWriter{os.Stdout}
continue
}
i++
if i == len(os.Args) {
break
}
color := ansi.ColorCode(os.Args[i])
switch mode {
case "l":
colorizer.AddRuleIfNotNil(current)
current = &LineRule{Color: color}
case "lx":
colorizer.AddRuleIfNotNil(current)
current = &LineRule{Color: color, Inverse: true}
case "w":
colorizer.AddRuleIfNotNil(current)
current = &WordRule{Color: color}
case "c":
colorizer.DefaultColor = color
default:
log.Fatalf("%s\n%sERROR: No such mode: %q",
usage, ansi.Red, mode)
}
} else {
if current == nil {
current = &WordRule{Color: DefaultWordHighlightColor}
}
pattern, err := regexp.Compile(arg)
if err != nil {
log.Fatalf("%s\n%sERROR: Bad matching pattern %q: %v",
usage, ansi.Red, arg, err)
}
current.AddPattern(pattern)
}
}
colorizer.AddRuleIfNotNil(current)
// BoundaryWriter allows us to ensure that we don't write parts of lines.
out := &line.BoundaryWriter{Target: colorizer}
_, err := io.Copy(out, os.Stdin)
if err != nil {
log.Fatal(ansi.Red + err.Error())
}
}
type EscapingWriter struct{ Out io.Writer }
func (e EscapingWriter) Write(p []byte) (int, error) {
newline := []byte("\n")
for _, line := range bytes.SplitAfter(p, newline) {
hasNewline := bytes.HasSuffix(line, newline)
if hasNewline {
line = line[:len(line)-1]
}
quoted := strconv.Quote(string(line))
// Strip the leading and trailing quotation marks: I want all
// the escaping, but not actually the quoting.
quoted = quoted[1 : len(quoted)-1]
io.WriteString(e.Out, quoted)
if hasNewline {
e.Out.Write(newline)
}
}
return len(p), nil
}
type Rule interface {
AddPattern(*regexp.Regexp)
}
type WordRule struct {
Color string
Patterns []*regexp.Regexp
}
type LineRule struct {
Inverse bool
Color string
Patterns []*regexp.Regexp
}
func (w *WordRule) AddPattern(pattern *regexp.Regexp) { w.Patterns = append(w.Patterns, pattern) }
func (l *LineRule) AddPattern(pattern *regexp.Regexp) { l.Patterns = append(l.Patterns, pattern) }
type ColorizerWriter struct {
DefaultColor string
WordRules []WordRule
LineRules []LineRule
Out io.Writer
}
func (c *ColorizerWriter) AddRuleIfNotNil(rule interface{}) {
if rule == nil {
return
}
switch r := rule.(type) {
case *LineRule:
c.LineRules = append(c.LineRules, *r)
case *WordRule:
c.WordRules = append(c.WordRules, *r)
default:
log.Fatalf("Unknown rule type: %T", rule)
}
}
func (c *ColorizerWriter) Write(data []byte) (int, error) {
var err error
var n, written int
for _, line := range bytes.SplitAfter(data, []byte("\n")) {
n, err = c.WriteOneLine(line)
written += n
if err != nil {
break
}
}
return len(data), err
}
func (c *ColorizerWriter) WriteOneLine(line []byte) (int, error) {
N := len(line)
written := 0
hasNewline := bytes.HasSuffix(line, []byte("\n"))
line = bytes.TrimSuffix(line, []byte("\n"))
lineCol := c.pickLineColor(line)
if lineCol != "" {
n, err := c.Out.Write([]byte(lineCol))
if err != nil {
return n, err
}
written += n
} else {
lineCol = ansi.Reset // we should reset for each word if no line col
}
line = c.applyWordRules(line, lineCol)
n, err := c.Out.Write(line)
if err != nil {
return n + written, err
}
written += n
if lineCol != ansi.Reset {
n, err = c.Out.Write([]byte(ansi.Reset))
written += n
}
if hasNewline {
_, err = c.Out.Write([]byte("\n"))
}
return N, err
}
func (c *ColorizerWriter) pickLineColor(line []byte) string {
for _, rule := range c.LineRules {
for _, pat := range rule.Patterns {
colorizeLine := pat.Match(line)
if rule.Inverse {
colorizeLine = !colorizeLine
}
if colorizeLine {
return rule.Color
}
}
}
return c.DefaultColor
}
type event struct {
typ int // true if the color is starting, false if ending
color string
pos int
}
type ByPos []event
func (s ByPos) Len() int { return len(s) }
func (s ByPos) Swap(a, b int) { s[a], s[b] = s[b], s[a] }
func (s ByPos) Less(a, b int) bool { return s[a].pos < s[b].pos }
func (c *ColorizerWriter) applyWordRules(line []byte, lineColor string) []byte {
const (
START = iota
STOP
)
var events []event
NUM_RULES := len(c.WordRules)
for i := range c.WordRules {
rule := c.WordRules[NUM_RULES-i-1]
for _, pat := range rule.Patterns {
for _, pos := range pat.FindAllIndex(line, -1) {
events = append(events,
event{START, rule.Color, pos[0]},
event{STOP, rule.Color, pos[1]})
}
}
}
if len(events) == 0 {
return line // no changes, no need to copy the line
}
// Sort the events by position. This will split up the start/stop events.
sort.Sort(ByPos(events))
colorStack := []string{lineColor}
var lineOut []byte
cur := 0 // current position in the original line
for _, e := range events {
lineOut = append(lineOut, line[cur:e.pos]...)
color := e.color
if e.typ == START {
// Push e.color onto the color stack, it's now the latest color.
colorStack = append(colorStack, e.color)
} else {
// Pop e.color from the color stack. It has to be on the stack somewhere,
// but if another overlapping pattern has been pushed in the meantime then
// it won't be the last item on the stack. Since it's almost certainly
// vert recent and it's likely the color stack is very shallow, just do a
// reverse linear search through the stack looking for this color.
// In fact, since most cases won't be overlapping patterns, this loop will
// probably execute exactly one iteration.
N := len(colorStack)
var pos int
// Use pos > 0 because at worst we end up with pos = 0.
for pos = N - 1; pos > 0; pos-- {
if colorStack[pos] == e.color {
break
}
}
// When we find it, shift the stack down on top of it. As mentioned
// earlier, pos will probably be the last entry of the stack and therefore
// this loop won't have any iterations.
for j := pos + 1; j < N; j++ {
colorStack[j-1] = colorStack[j]
}
// Shorten the stack.
colorStack = colorStack[:N-1]
tail := N - 2
color = colorStack[tail]
}
lineOut = append(lineOut, []byte(color)...)
cur = e.pos
}
// Copy whatever remains in the original line.
lineOut = append(lineOut, line[cur:]...)
return lineOut
}
<file_sep>/README.md
# highlight
highlight is a small command-line utility to colorize stdin via regex matches.
[](https://asciinema.org/a/108469)
## Install
```sh
go get -u github.com/augustoroman/highlight
```
## Example usage
```sh
echo -e "The quick \nbrown fox \njumped over\nthe lazy dog" | highlight -c 'white+d' -l red fox -w 'yellow+b' lazy
```

|
a4123a9a0b9f7903d5cd4ed7919953ae1dd3f2a0
|
[
"Markdown",
"Go"
] | 2
|
Go
|
SlaSerX/highlight
|
780a6a9269988fdea23b089138b5e4d46aefeb6e
|
920f86b919938870f92ecc58fbafde1c74a06a2c
|
refs/heads/master
|
<repo_name>MetalMichael/RegenAwsCredentials<file_sep>/RegenCredentials/Program.cs
using IniParser;
using IniParser.Model;
using Newtonsoft.Json.Linq;
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace RegenCredentials
{
class Program
{
const string FILENAME = "credentials";
const string MASTER = "master";
const string REGION = "eu-west-2"; // Could load this from profile
static void Main(string[] args)
{
var parser = new FileIniDataParser();
IniData ini;
if (File.Exists(FILENAME))
ini = parser.ReadFile(FILENAME);
else
ini = new IniData();
var mfaDevice = LoadOrGetInput(ini[MASTER], "MFA Device");
var profile = (args.Length > 1) ? args[1] : "default";
var credentialSection = ini[profile];
var code = GetInput("Token Code");
var data = Run(mfaDevice, code);
dynamic info = JObject.Parse(data);
credentialSection["aws_access_key_id"] = info.Credentials.AccessKeyId;
credentialSection["aws_secret_access_key"] = info.Credentials.SecretAccessKey;
credentialSection["aws_session_token"] = info.Credentials.SessionToken;
parser.WriteFile(FILENAME, ini, new UTF8Encoding(false));
Console.WriteLine("Successful. Token Expires: " + info.Credentials.Expiration);
}
static string Run(string device, string code)
{
var command = $"/C aws --profile {MASTER} --region {REGION} sts get-session-token --token-code {code} --serial-number {device}";
var cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.Arguments = command;
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.RedirectStandardError = true;
cmd.Start();
cmd.WaitForExit();
var err = cmd.StandardError.ReadToEnd();
if (!string.IsNullOrWhiteSpace(err))
throw new Exception(err);
return cmd.StandardOutput.ReadToEnd();
}
static string LoadOrGetInput(KeyDataCollection section, string request)
{
var key = EscapeString(request);
var x = section[key];
if (x != null)
return x;
x = GetInput(request);
section[key] = x;
return x;
}
static string GetInput(string request)
{
Console.WriteLine("Please provide your " + request);
while (true)
{
var x = Console.ReadLine();
if (x.Length > 0)
{
return x;
}
}
}
static string EscapeString(string s)
{
var x = s.ToLower().Replace(" ", "_");
return char.ToLowerInvariant(x[0]) + x.Substring(1);
}
}
}
|
ea68e61a0876628894ebf52438c3d1f99f07289b
|
[
"C#"
] | 1
|
C#
|
MetalMichael/RegenAwsCredentials
|
4ed899e6feb31f6c9a58a9dce8cf16ca2e9a104a
|
50ad0c533148dde875329411cb80c1262cc250f8
|
refs/heads/master
|
<repo_name>BarakpaevOlzhas/ContWor<file_sep>/DataGrid/DataGrid/Curse.cs
using System.Xml.Serialization;
using System.Collections.Generic;
namespace DataGrid
{
public class Curse
{
public string Id { get; set; }
public string Name_Kaz { get; set; }
public string Edinica_Izmerenia { get; set; }
public string Sootnowenie { get; set; }
public string Name_Rus { get; set; }
public string Kurs { get; set; }
public string Kod { get; set; }
}
}
<file_sep>/DataGrid/DataGrid/MainWindow.xaml.cs
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Windows;
namespace DataGrid
{
/// <summary>
/// Логика взаимодействия для MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
InitializeComponent();
WebRequest request = WebRequest.Create("https://data.egov.kz/api/v2/valutalar_bagamdary4/v501?pretty");
HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
List<Curse> data = new List<Curse>();
using (StreamReader stream = new StreamReader(resp.GetResponseStream(), Encoding.UTF8))
{
string JsonFormat = stream.ReadToEnd();
data = JsonConvert.DeserializeObject<List<Curse>>(JsonFormat);
}
foreach (var i in data)
{
var Shop = new Curse
{
Sootnowenie = i.Sootnowenie,
Name_Rus = "KZT",
Kurs = i.Kurs,
Kod = i.Kod
};
dataG.Items.Add(Shop);
}
}
private void DataGrid_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
}
}
}
|
0b227f18481c90d5710a573c7e971ca591b1472f
|
[
"C#"
] | 2
|
C#
|
BarakpaevOlzhas/ContWor
|
b88a14ba3ef3f890503f9bb54bff96fba3dc027c
|
c14685f8563021f2e399f3dbecbd67f21e8e8a08
|
refs/heads/main
|
<file_sep># test-orionX
NestJS MicroService to get price (buy and sell), RSI, TypicalPrice and Spread of Bitcoin
|
845f87b9c4ddbed020b1564803964213b73f1841
|
[
"Markdown"
] | 1
|
Markdown
|
GustavoVerdugo/microservice-nestjs
|
f31ca06392c556892a41d0f31641ecb49bd4eccb
|
aeb588ad8419f3e4f9c7c90f6ed3d2305547bf82
|
refs/heads/master
|
<repo_name>sbremner/NextStep<file_sep>/nextstep/core/utils_test.py
import unittest
from nextstep.core.utils import rebuild_cmdline
class UtilsTests(unittest.TestCase):
def test_rebuild_cmdline(self):
self.assertEqual(
rebuild_cmdline(['/c', '--input', 'filename with spaces.exe']),
'/c --input "filename with spaces.exe"'
)
self.assertEqual(
rebuild_cmdline(['/c', '--input', 'filename.exe']),
'/c --input "spaces.exe"'
)
self.assertRaises(ValueError, rebuild_cmdline, "bad data")
self.assertRaises(ValueError, rebuild_cmdline, 12345)<file_sep>/nextstep/modules/network.py
import socket
import psutil
import getpass
import argparse
from datetime import datetime
from nextstep.core.utils import rebuild_cmdline
from nextstep.core.module import Module
from nextstep.core.logging import make_event, write_event
class NetworkConnection(Module):
def __init__(self, *args, **kwargs):
super(NetworkConnection, self).__init__(*args, **kwargs)
def run(self, target, message):
if not ":" in target:
raise ValueError("target format must be [addr:port]")
# Split our address to get addr/port
daddr, dport = target.split(":")
# Convert our port to an int (raises ValueError if it fails)
dport = int(dport)
# Build our socket, connect and send the data
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
# Connect
sock.connect((daddr, dport))
# Actual peer name after connection
daddr, dport = sock.getpeername()
# Get the source addr/port
saddr, sport = sock.getsockname()
# Build our "payload" to send
payload = bytes(message + "\n", "utf-8")
payload_sz = len(payload)
# Send our payload
sock.sendall(payload)
# Snag timestamp when we performed our action
ts = datetime.utcnow()
# Get a reference to our process
proc = psutil.Process()
log = make_event(
timestamp=ts.isoformat(),
username=getpass.getuser(),
dest_addr=daddr,
dest_port=dport,
src_addr=saddr,
src_port=sport,
data_sent=payload_sz,
protocol="TCP",
process_name=proc.name(),
command_line=rebuild_cmdline(proc.cmdline()[1:]),
process_id=proc.pid
)
write_event(log)
@staticmethod
def get_parser():
parser = argparse.ArgumentParser(description="Send network message to target")
parser.add_argument('--target', help="destination to send data [addr:port]")
parser.add_argument('--message', help="Data to send to target")
return parser<file_sep>/nextstep/modules/__init__.py
from nextstep.core.errors import ModuleNameError
from .process import StartProcess
from .file import (
CreateFile, ModifyFile, DeleteFile,
)
from .network import NetworkConnection
# Available modules
# TODO: Allow this dictionary to dynamically load from configured locations
MODULES = {
'process.start': StartProcess(),
'file.create': CreateFile(),
'file.modify': ModifyFile(),
'file.delete': DeleteFile(),
'network.send': NetworkConnection(),
}
def get_modules():
return MODULES
def load_module(module):
""" Returns a module object back to the caller """
available_modules = get_modules()
if module not in available_modules:
raise ModuleNameError("Invalid module name: {}".format(module))
# TODO: Add validation that our module is a class maybe?
return available_modules[module]<file_sep>/nextstep/modules/file.py
import os
import shlex
import psutil
import getpass
import argparse
import pathlib
from datetime import datetime
from nextstep.core.utils import rebuild_cmdline
from nextstep.core.module import Module
from nextstep.core.logging import make_event, write_event
class CreateFile(Module):
def __init__(self, *args, **kwargs):
super(CreateFile, self).__init__(*args, **kwargs)
def run(self, path, overwrite=False):
p = pathlib.Path(path)
# Checks if path exists
if p.exists() and overwrite == False:
raise FileExistsError("File at path already exists (use --overwrite to force)")
# Gets our directory
pdir = pathlib.Path(p.parent)
# Create directory if we don't already exist
if not pdir.exists():
pdir.mkdir(parents=True, exist_ok=True)
# Snag timestamp when we performed our action
ts = datetime.utcnow()
# "Touch" the file
p.touch()
# Get a reference to our process
proc = psutil.Process()
log = make_event(
timestamp=ts.isoformat(),
username=getpass.getuser(),
path=path,
activity="CREATE",
process_name=proc.name(),
command_line=rebuild_cmdline(proc.cmdline()[1:]),
process_id=proc.pid
)
write_event(log)
@staticmethod
def get_parser():
parser = argparse.ArgumentParser(description="Creates a new file at specified location")
parser.add_argument('--path', help="Path of file to create")
parser.add_argument('--overwrite', action="store_true", default=False, help="Overwrite file if it exists")
return parser
class ModifyFile(Module):
OPEN_MODES = ('a', 'w',)
def __init__(self, *args, **kwargs):
super(ModifyFile, self).__init__(*args, **kwargs)
def run(self, path, text, mode="a"):
p = pathlib.Path(path)
# Checks if path exists
if not p.exists():
raise FileNotFoundError("File at path does not exist")
# Ensure we are using a valid open mode for our file
if mode not in self.OPEN_MODES:
raise ValueError("Invalid open mode: {}".format(mode))
# Snag timestamp when we performed our action
ts = datetime.utcnow()
# Open our file up and write our text out
with open(str(p), mode=mode) as f:
f.write(text)
# Get a reference to our process
proc = psutil.Process()
log = make_event(
timestamp=ts.isoformat(),
username=getpass.getuser(),
path=path,
activity="MODIFY",
process_name=proc.name(),
command_line=rebuild_cmdline(proc.cmdline()[1:]),
process_id=proc.pid
)
write_event(log)
@staticmethod
def get_parser():
parser = argparse.ArgumentParser(description="Modifies a files content")
parser.add_argument("--path", help="Path of the file to modify")
parser.add_argument("--mode", default="a", type=str, choices=["w", "a"], help="Modify in write or append mode")
parser.add_argument("--text", type=str, help="Data to add to file")
return parser
class DeleteFile(Module):
def __init__(self, *args, **kwargs):
super(DeleteFile, self).__init__(*args, **kwargs)
def run(self, path):
p = pathlib.Path(path)
# Checks if path exists
if not p.exists():
raise FileNotFoundError("File at path does not exist")
# Snag timestamp when we performed our action
ts = datetime.utcnow()
# Remove the file at our provided path
os.remove(str(p))
# Get a reference to our process
proc = psutil.Process()
log = make_event(
timestamp=ts.isoformat(),
username=getpass.getuser(),
path=path,
activity="DELETE",
process_name=proc.name(),
command_line=rebuild_cmdline(proc.cmdline()[1:]),
process_id=proc.pid
)
write_event(log)
@staticmethod
def get_parser():
parser = argparse.ArgumentParser(description="Deletes a specified file")
parser.add_argument("--path", help="Path of the file to delete")
return parser<file_sep>/nextstep/core/logging.py
import json
from settings import LOG_FILE
# TODO: Maybe use a custom logger for write_event?
# import logging
# logger = logging.getLogger("NextStep")
def make_event(**kwargs):
# Just return it as a dictionary for now
return kwargs
def write_event(evt):
# Just dump it to stdout for now
with open(LOG_FILE, "a") as f:
f.write(json.dumps(evt) + '\n')<file_sep>/README.md
# NextStep
A framework built to generate activity on an endpoint. Base capabilities include the ability to spawn a process, create a file,
modify a file, delete a file and establish a network connection to
transmit data.
**Table of Contents**
- [Setup](#setup)
- [Execution](#execution)
- [CLI](#cli)
- [Playbooks](#playbooks)
- [Custom Modules](#custom-modules)
## Setup
Download the git package and install the requirements as follows:
```> pip install -r requirements.txt```
*Note: This has been tested on python 3.6 on Windows and Linux.*
## Execution
The program allows for two primary methods of invocation. It supports single module execution via a command line interface as well as multi-module execution via a playbook model. See below.
### CLI
The command line module allows execution of modules individually. To get a list of all available commands, use the following:
```> python main.py --help```
To see all available modules, use the `--show-module` command as follows:
```> python main.py --show-modules```
To get more information on a specific module, use the `--help` command while providing a module name:
```> python main.py --help --module process.start```
### Playbooks
Playbooks can be useful when it is necessary to execute multiple modules at a time. This allows the user to build a full testing playbook that can be run.
Playbooks are json files which contain a list of modules to execute. They are in the following format:
```json
[
{
"module": "file.create",
"run": {
"path": "sample.txt",
"overwrite": true
}
},
{
"module": "file.modify",
"run": {
"path": "sample.txt",
"mode": "a",
"text": "Hello, Sample!"
}
}
]
```
To view the "run" arguments for a specific module, use the `--help` command while providing a module name:
```> python main.py --help --module file.create```
Playbooks can be executed as follows:
```> python main.py --playbook book.json```
## Custom Modules
The framework is built to be extended easily with custom modules. There are two key methods to override to get a module operational: `run()` and `get_parser()`.
The `get_parser()` method is a static method that exposes the available parameters for the CLI invocation of the module. These parameters will be passed to the `run()` method when the module is executed.
A sample `get_parser()` method might look as follows:
```python
@staticmethod
def get_parser():
parser = argparse.ArgumentParser(description="Starts a process")
parser.add_argument('--path', help="Path of process to execute")
parser.add_argument('--command', help="Command line arguments to include", required=False)
return parser
```
The paired method for this is the `run()` method which should include the parameters exposed by the parser. This method will get called when the module is executed:
```python
def run(self, path, command=None):
pass # Implement the run method here
```
<file_sep>/nextstep/core/module.py
class Module(object):
""" Base module class used to implement new modules
for the tool. Inherit this class and override the
run and get_parser method to expose a new module.
"""
def __init__(self, *args, **kwargs):
pass
def run(self, *args, **kwargs):
""" Override this method for the invocation of a module.
It should accept args that match the exposed arguments
from the get_parser() function.
"""
raise NotImplementedError("{}\n{}".format(
"Run functionnot implemented for module",
"Suggestion: override method run()"
))
def print_help(self):
parser = self.get_parser()
parser.print_help()
@property
def description(self):
""" Returns back the description exposed by the parser """
try:
return self.get_parser().description
except:
pass # Problem loading our argparser
return None
@staticmethod
def get_parser():
""" Override this method with a valid argparser.
It should expose any arguments that would be required to
invoke the run() method.
"""
raise NotImplementedError("{}\n{}".format(
"Argument parser must be implemented for module",
"Suggestion: override staticmethod get_parser()"
))<file_sep>/nextstep/modules/process.py
import os
import shlex
import getpass
import argparse
import subprocess
from pathlib import Path
from datetime import datetime
from nextstep.core.module import Module
from nextstep.core.logging import make_event, write_event
class StartProcess(Module):
def __init__(self, *args, **kwargs):
super(StartProcess, self).__init__(*args, **kwargs)
def run(self, path, command=None, block=False, timeout=None):
# Resolves/validates path is good
p = Path(path).resolve(strict=True)
# Build our execution command
to_exec = shlex.split('"{}" {}'.format(p, command or ""))
# Start our process/save timestamp
ts = datetime.utcnow()
try:
proc = subprocess.Popen(to_exec, stdin=None, stdout=None, stderr=None, close_fds=True)
# Block if we were asked to
if block:
proc.wait(timeout=timeout)
except subprocess.CalledProcessError:
# Another error occured
pass
except subprocess.TimeoutExpired:
# Process expired
proc.kill()
# Returns us back an event that we want to send to our log
log = make_event(
timestamp=ts.isoformat(),
username=getpass.getuser(),
process_name=path,
command_line=command,
process_id=proc.pid
)
# Write the event for our process execution
write_event(log)
return True
@staticmethod
def get_parser():
parser = argparse.ArgumentParser(description="Starts a process")
parser.add_argument('--path', help="Path of process to execute")
parser.add_argument('--command', help="Command line arguments to include", required=False)
parser.add_argument('--block', action="store_true", default=False, help="Block program execution until subprocess completes")
parser.add_argument('--timeout', type=int, required=False, help="Sets timeout in seconds (requires: --block)")
return parser<file_sep>/main.py
import sys
import json
import logging
import inspect
import argparse
import settings
from nextstep.core.errors import ModuleNameError
from nextstep.modules.process import StartProcess
from nextstep.modules import load_module, get_modules
# Use logging module for "printing" info while we run the tool
logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s] - %(name)s - %(levelname)s | %(message)s",
handlers=[
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
def module_banner():
""" Prints available modules to screen """
all_modules = get_modules()
logger.info("Available modules:")
for name, module in all_modules.items():
logger.info("> {} | {}".format(name, module.description))
logger.info('Try "--help --module [name]" for more information')
def run_module(module, *params, **kwargs):
""" Runs our module after parsing provided params """
# Snag our modules parser (it handles the rest of our args)
mp = module.get_parser()
# Parse the arguments for our modules run function
args, unknown = mp.parse_known_args(params)
# Build our our invocation dictionary
_kwargs = {}
_kwargs.update(vars(args))
_kwargs.update(kwargs)
if unknown and len(unknown) > 0:
logger.warning("Unrecognized parameters: {}".format(unknown))
try:
# Invoke the module
module.run(**_kwargs)
except Exception as ex:
logger.error("Module raised exception during execution:\n> {}".format(ex))
return False
return True
def get_parser():
parser = argparse.ArgumentParser(conflict_handler='resolve')
parser.add_argument("--help", action='store_true')
parser.add_argument("--show-modules", action='store_true', help="Prints available modules")
parser.add_argument("--module", help="Name of module to run")
parser.add_argument("--playbook", help="Json file with list of plays to run")
return parser
def main(args=None):
logger.info("NextStep started - loading module arguments")
logger.info("Execution trace information located in: {}".format(settings.LOG_FILE))
# Our NextStep parser
parser = get_parser()
# Grab the args we care about, keep extras for the module
args, extras = parser.parse_known_args()
# Print basic help here (if args.module is set, we print module's help later)
if args.help and not args.module:
parser.print_help()
return
# Check if we just want to show available modules
if args.show_modules:
module_banner()
return
# Ensure we specify a module OR a play book
if not args.module and not args.playbook:
logger.error("Please specify a module name or a target playbook to execute")
parser.print_help()
exit(-1)
# Detect if we run a playbook here, or we are running a single module
if args.playbook:
with open(args.playbook, "r") as f:
playbook = json.load(f)
for play in playbook:
if "module" not in play:
logger.error("Play must contain key: 'module'")
continue
try:
logger.info("Loading module: {}".format(play["module"]))
# Load the module: play["module"]
module = load_module(play["module"])
except ModuleNameError as ex:
logger.error(ex)
continue # Skip the rest, our module didn't load properly
# Invoke our module
run_module(module, **play["run"])
else:
try:
logger.info("Loading module: {}".format(args.module))
# Load the module: args.module
module = load_module(args.module)
except ModuleNameError as ex:
logger.error(ex)
parser.print_help()
exit(-1)
# We just wanted the help for our module
if args.help:
mp = module.get_parser()
mp.print_help()
else:
# run our module
run_module(module, *extras)
if __name__ == "__main__":
try:
main(sys.argv[1:])
except KeyboardInterrupt:
print("Exit caught - quitting")
except Exception as ex:
print("Unhandled exception :: <{}> {}".format(type(ex), ex))
<file_sep>/nextstep/core/utils.py
def rebuild_cmdline(parts):
""" VERY naive rebuilding of command line
TODO: Update this to be more robust with escaping values.
Could use shlex.quote but it only works properly for linux CLI
"""
if not isinstance(parts, (list,tuple)):
raise ValueError("parts must be a list or tuple")
result = []
for item in parts:
# If there is a space, we quote wrap it
if " " in item:
result.append('"{}"'.format(item))
else:
result.append(item)
return " ".join(result)<file_sep>/nextstep/core/errors.py
class NextStepException(Exception):
pass
class ModuleNameError(NextStepException):
pass<file_sep>/settings.py
LOG_FILE = "trace.log"
|
520b0bfc127de2931e545efde879190dcce40b6a
|
[
"Markdown",
"Python"
] | 12
|
Python
|
sbremner/NextStep
|
1946dac4ab24610247464a1f3e98284983f01411
|
569606688338a39b31dc9a598f7b72349ff1f69c
|
refs/heads/master
|
<repo_name>tatellog/myWebsite<file_sep>/src/components/navigation/NavigationBar.js
import React from 'react';
import { Route, Link} from 'react-router-dom';
import HomePage from "./../../pages/HomePage";
import AboutPage from "./../../pages/AboutPage";
import SkillsPage from './../../pages/SkillsPage';
import ContactPage from './../../pages/ContactPage';
const NavigationBar = () => {
const routes =[
{
path: '/',
exact :true,
sidebar : () => <HomePage/>,
},
{
path: '/about',
exact :true,
sidebar : () => <AboutPage/>
},
{
path: '/skills',
exact :true,
sidebar : () => <SkillsPage/>,
},
{
path: '/contact',
exact :true,
sidebar : () => <ContactPage/>,
},
]
return (
<container className='container-nav'>
<div className='menu-nav__header'>
<ul>
<li><Link to = '/'>Home </Link></li>
<li>/ <Link to = '/about'>About </Link></li>
<li>/ <Link to = '/skills'>Skills </Link></li>
<li>/ <Link to = '/contact'>Contact </Link></li>
</ul>
{routes.map((route) => (
<Route
key={route.path}
path={route.path}
exact={route.exact}
component={route.sidebar}
/>
))}
</div>
</container>
)
}
export default NavigationBar<file_sep>/src/components/generic/Slider.js
import React from 'react';
const Slider = () => {
return (
<segment>
<ul>
<li>
<h2>Hello I´m <NAME></h2>
<p>Excepteur sit labore qui ipsum ea cupidatat velit enim aliquip officia nisi fugiat excepteur.</p>
<p>Excepteur sit labore qui ipsum ea cupidatat velit enim aliquip officia nisi fugiat excepteur.</p>
<p>Reprehenderit eiusmod amet ea laboris nulla adipisicing aliquip deserunt occaecat eiusmod nisi.</p>
</li>
<li>
<h2>Nulla irure commodo ipsum ad veniam irure sint consequat.</h2>
<p>Fugiat occaecat culpa officia nisi consectetur amet ullamco ea minim qui.</p>
<p>Tempor qui ut minim elit.</p>
</li>
<li>
<h2>Ad exercitation veniam enim cupidatat ex ullamco aliquip.</h2>
<p>Commodo anim nulla sint proident qui duis elit eu et sit ut.</p>
<p>Non do adipisicing quis et.</p>
</li>
<li>
<h2>Ad exercitation veniam enim cupidatat ex ullamco aliquip.</h2>
<p>Commodo anim nulla sint proident qui duis elit eu et sit ut.</p>
<p>Non do adipisicing quis et.</p>
</li>
</ul>
</segment>
)
}
export default Slider
|
78c225a6062f51f1d854b65fd427b4f4dc651c2f
|
[
"JavaScript"
] | 2
|
JavaScript
|
tatellog/myWebsite
|
35b99e8d219ba33bca1d370751513dbaa35a5089
|
ab7c0a97476cf67cc8ee738e9c9a845797159e67
|
refs/heads/master
|
<file_sep>## AdmitKard Project
- Clone repo from https url to the local machine
- open terminal and go inside project(AdmitKard) folder
- type yarn or npm install to install the required dependencies (make sure you have npm/yarn installed)
- type yarn start or npm start to start the application locally
- open [http://localhost:3000](http://localhost:3000) to view it in the browser.
## Note
For any queries, contact -
<a href="mailto:<EMAIL>" target="_blank"><EMAIL></a>
<br/>
<a href="tel: +91 7011651641" target="_blank">+91 7011651641</a>
<file_sep>import LOGO from "./assets/images/admitkard_logo.svg";
export const Assets = {
LOGO,
};
<file_sep>import QuestionCard from "./QuestionCard/QuestionCard";
import ShowTags from "./ShowTags/ShowTags";
import AddQuestion from "./AddQuestion/AddQuestion";
import Searchbar from "./Searchbar/Searchbar";
import Logo from "./Logo/Logo";
export { QuestionCard, ShowTags, Searchbar, AddQuestion, Logo };
|
e8967f85f3918c53de8af8f0495db8b74532356d
|
[
"Markdown",
"TypeScript"
] | 3
|
Markdown
|
xXD4rkC0d3rXx/admitkard
|
36758a0c51c6325d1749485b5c3c86c844c76134
|
7012994c8c7600daf741cb786ab0249ecf7a2ad5
|
refs/heads/master
|
<repo_name>nightosong/CNNSkeleton<file_sep>/utils/data/data_cursor.py
import os
import random
import threading
from utils import path_utils
class DataCursor:
def top(self): pass
def down(self, span=1): pass
def up(self, span=1): pass
def point(self, spec_dir): pass
def __iter__(self): pass
def __next__(self): pass
def reset_iter(self): pass
def next(self):
return self.__next__()
class FsCursor(DataCursor):
def __init__(self, root_dir):
self.__local = threading.local()
self.root_dir = root_dir
self.cache = {}
self.__reset_pointer()
self._iterator = None
self.reset_iter()
def __check_local(self):
if not hasattr(self.__local, 'has_inited'):
self.__local.has_inited = True
self.__reset_pointer()
def __reset_pointer(self):
self.__local.current_file = self.root_dir
self.__local.current_parent = None
return self.__local.current_file
def top(self):
return self.__reset_pointer()
def down(self, span=1):
self.__check_local()
result = None
for _ in range(span):
result = self.__down()
return result
def up(self, span=1):
self.__check_local()
result = None
for _ in range(span):
result = self.__up()
return result
def point(self, spec_dir):
self.__check_local()
self.__local.current_file = spec_dir
self.__local.current_parent = path_utils.parent_dir_path(self.__local.current_file)
return self.floating()
def floating(self):
self.__check_local()
if self.__local.current_parent is not None:
sub_file_list = self.__get_sub_file_list(self.__local.current_parent)
self.__local.current_file = random.choice(sub_file_list)
reutrn self.__local.current_file
def __down(self):
sub_file_list = self.__get_sub_file_list(self.__local.current_file)
sub_file = random.choice(sub_file_list)
self.__local.current_parent = self.__local.current_file
self.__local.current_file = sub_file
return self.__local.current_file
def __up(self):
self.__local.current_file = path.utils.parent_dir_path(self.__local.current_file)
if self.__local.current_file == self.root_dir:
self.__local.current_parent = None
else:
self.__local.current_parent = path_utils.parent_dir_path(self.__local.current_file)
return self.floating()
def __get_sub_file_list(self, current_dir):
sub_file_list = self.cache.get(current_dir)
if sub_file_list is None:
file_list = os.listdir(current_dir)
sub_file_list = [os.path.join(current_dir, filename) for filename in file_list]
self.cache[current_dir] = sub_file_list
return sub_file_list
def __iter__(self):
return self._iterator
def __next__(self):
return self._iterator.__next__()
def _create_iter(self):
for root, _, files in os.walk(self.root_dir):
for f in files:
path = os.path.join(root, f)
yield path
def reset_iter(self):
self._iterator = self._create_iter()
<file_sep>/utils/path/path_utils.py
import os
import tempfile
import shutil
import time
def parent_dir_path(path):
ret = os.path.dirname(path)
if ret == '':
ret = os.getcwd()
return ret
def dir_name(path, span=1):
d = os.path.dirname(path)
print(d)
paths = (d, None)
for _ in range(span):
paths = os.path.split(paths[0])
return paths[1]
def file_name(path, extension=True):
name = os.path.basename(path)
if not extension:
name, _ = os.path.splitext(name)
return name
def extension_name(path):
_, extension = os.path.splitext(path)
return extension
def sub_files(root_dir, include_file=False, include_dir=True):
names = os.listdir(root_dir)
paths = []
for name in names:
file_path = os.path.join(root_dir, name)
if os.path.isdir(file_path):
if include_dir:
paths.append(file_path)
else:
if include_file:
paths.append(file_path)
return paths
def usr_home_dir():
return os.path.expanduser('~')
def temp_dir():
return tempfile.gettempdir()
def delete_file(file_path):
os.remove(file_path)
def delete_dir(dir_path):
if os.path.exists(dir_path):
shutil.rmtree(dir_path)
def copy_file(src_path, dst_path):
shutil.copyfile(src_path, dst_path)
def copy_dir(src_dir, dst_dir):
shutil.copytree(src_dir, dst_dir)
def mkdir(dir_path):
os.makedirs(dir_path, exist_ok=True)
def move(src_path, dst_path):
shutil.move(src_path, dst_path)
def memory_virtual_dir():
pass
def to_linux_path_format(path):
return path.replace('\\\\', '/').replace('\\', '/')
def absolute_path(path):
return os.path.abspath(path)
def is_same_path(path1, path2):
return os.path.normpath(os.path.abspath(path1)) == os.path.normpath(os.path.abspath(path2))
def subfiles(root_dir, include_dir=False):
ret = []
for filename in os.listdir(root_dir):
path = os.path.join(root_dir, filename)
if include_dir:
ret.append(path)
else:
if os.path.isfile(path):
ret.append(path)
return ret
def subfiles_recursive(root_dir, include_dir=False):
ret = []
for root, sub_dirs, sub_files in os.walk(root_dir):
for sub_filename in sub_files:
path = os.path.join(root, sub_filename)
ret.append(path)
if include_dir:
for sub_dirname in sub_dirs:
path = os.path.join(root, sub_dirname)
ret.append(path)
return ret
<file_sep>/utils/image/image_utils.py
import numpy as np
import imageio
import cv2
from PIL import Image, ImageFilter, ImageEnhance
from scipy import misc
def read(path):
return misc.imread(path)
def save(path, img):
return imageio.imsave(path, img)
def save_batch(paths, imgs):
for i in range(len(paths)):
imageio.imsave(paths[i], imgs[i])
def resize(img, hw, more=False):
if img.shape[0] == hw[0] and img.shape[1] == hw[1]:
return img.copy()
if more:
if hw[0] + hw[1] < img.shape[0] + img.shape[1]:
return cv2.resize(img, (hw[1], hw[0]), interpolation=cv2.INTER_AREA)
else:
return cv2.resize(img, (hw[1], hw[0]), interpolation=cv2.INTER_CUBIC)
else:
return cv2.resize(img, (hw[1], hw[0]), interpolation=cv2.INTER_LINEAR)
def resize_scale(img, scale, more=False):
hw = (int(img.shape[0] * scale), int(img.shape[1] * scale))
return resize(img, hw=hw, more=more)
def auto_binary(img, more=False):
if more:
_, img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
else:
_, img = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
return img
def binary(img, threshold=220):
ret = img.copy()
ret[ret >= threshold] = 255
ret[ret < threshold] = 0
return ret
def is_gray(img):
return img.ndim == 2
def gray(img):
if img.ndim == 3:
if img.shape[2] == 3:
return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
elif img.shape[2] == 4:
img = convert_3_channel(img)
return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
elif img.shape[2] == 2:
return img[:, :, 0]
else:
raise BaseException('unknown image shape: ' + str(img.shape))
elif img.ndim == 2:
return img.copy()
else:
raise BaseException('unknown image shape: ' + str(img.shape))
def is_3_channel(img):
return img.ndim == 3 and img.shape[-1] == 3
def convert_3_channel(img):
if img.ndim == 2:
h, w = img.shape
ret = np.empty((h, w, 3), dtype=np.uint8)
ret[:, :, 0] = ret[:, :, 1] = ret[:, :, 2] = img
return ret
elif img.ndim == 3 and img.shape[-1] == 3:
return img.copy()
elif img.ndim == 3 and img.shape[-1] == 4:
transparency = np.empty(img.shape[:2], np.float32)
ret = np.empty((img.shape[0], img.shape[1], 3), np.float32)
transparency[:, :] = img[:, :, 3] / 255.
for i in range(3):
ret[:, :, i] = 255 * (1 - transparency[:, :]) + img[:, :, i] * transparency[:, :]
return ret.astype(np.uint8)
elif img.ndim == 3 and img.shape[-1] == 2:
ret = img[:, :, 0]
return convert_3_channel(ret)
else:
raise BaseException('unknown image shape: ' + str(img.shape))
def copy_img(img):
return img.copy()
def new_image(shape, fill=255):
zero_img = np.zeros(shape, np.uint8)
ret = np.add(zero_img, fill)
return ret.astype(np.uint8)
def rotation(img, angle, fill=(255, 255, 255)):
h, w = img.shape
m = cv2.getRotationMatrix2D((w / 2, h / 2), angle, 1)
return cv2.warpAffine(img, m, (w, h), borderValue=fill)
def translation(img, h_offset=0, w_offset=0, fill=(255, 255, 255)):
h, w = img.shape
m = np.float32([[1, 0, w_offset], [0, 1, h_offset]])
return cv2.warpAffine(img, m, (w, h), borderValue=fill)
def joins(imgs, axis=0):
"""
图片合并
:param axis: 0 垂直合并, 1 水平合并
"""
return np.concatenate(imgs, axis=axis)
def filters(img, code=0):
"""
图像滤波
:param code: 0~5 SmoothMore,Smooth,锐化,中值滤波,Blur,BoxBlur
"""
ret = Image.fromarray(img)
filter_list = [ImageFilter.SMOOTH_MORE, ImageFilter.SMOOTH, ImageFilter.SHARPEN,
ImageFilter.MedianFilter, ImageFilter.BLUR, ImageFilter.BoxBlur]
ret = ret.filter(filter_list[code])
return np.array(ret)
def bilateral_filter(img, d=40):
"""
双边滤波
:param d:
"""
return cv2.bilateralFilter(img, d, 75, 75)
def contrast(img, contrast_val):
img = Image.fromarray(img)
enh_con = ImageEnhance.Contrast(img)
return np.array(enh_con.enhance(contrast_val))
def flip_heigt(img, code=0):
"""
图像翻转
:param code: 0 垂直翻转, 1 水平翻转
"""
return cv2.flip(img,flipCode=code)
|
f93e5e3d5087d50aa2f7c454fd6be07e45ecc8c2
|
[
"Python"
] | 3
|
Python
|
nightosong/CNNSkeleton
|
7e9f8fbacaca712e120a0575eb9d5a6826ff8a54
|
c9b881438741e2118da04a235eac065fd9aa8f45
|
refs/heads/master
|
<file_sep>/*
Nama : <NAME>
NIM : 118140087
IF : B
Program : Aplikasi Bill Rumah Kayu Itera
*/
#include <iostream>
#include <conio.h>
using namespace std;
void opening(); //mendeklarasi fungsi dengan nama fungsi opening()
void opening() { //fungsi opening
cout<<"(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)\n";
cout<<"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n";
cout<<"| # # ###### # ####### ####### ### ### ###### |\n";
cout<<"| # # # # # # # # # # # # # |\n";
cout<<"| # ## # ###### # # # # # ## # ###### |\n";
cout<<"| # # # # # # # # # # # # |\n";
cout<<"| ### ### ###### ####### ####### ####### # # ###### |\n";
cout<<"|\t\t\t\t\t\t\t\t\t |\n";
cout<<"|\t\t\t TO RUMAH KAYU ITERA\t\t\t |\n";
cout<<"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n";
cout<<"(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)\n";
//digunakan untuk tetap menampilkan output di layar
}
int main ()
{
int p,m,mi,d,pm,pmi,pd,hm,hmi,hd,tm,tmi,td,t; //deklarasi variabel yang digunakan, menggunakan singkatan untuk mempersimple
int meja;
string makanan[8] = {"Rendang","Ikan Bakar","Sambel Udang","Cumi Hitam","Telur Rebus","Jamur Crispy","Sop Iga","None"};
string minuman[6] = {"Coffee","Iced Tea","Mineral Water","Orange Juice","Avocado Juice ","None"}; //deklarasi array
string dessert[4] = {"Cake","Ice Cream","Brownies","None"};
opening();
cout<<"Nomor Meja Anda : ";
cin>>meja;
menu:
cout<<"\t\t\t____________________________________________________________\n\n";
cout<<"\t\t\t ***********[ M E N U ]*********** \n";
cout<<"\t\t\t____________________________________________________________\n\n";
cout<<"\t\t\t [1] Makanan \n";
cout<<"\t\t\t [2] Minuman \n";
cout<<"\t\t\t [3] Dessert \n";
cout<<"\t\t\t____________________________________________________________\n\n";
cout<<"Q: Masukan pilihanmu = ";
cin>>p; //p adalah variabel untuk pilihan
if (p==1){ //memulai percabangan if dengan kondisi pilihan 1
menu1: //label untuk pengembalian
cout<<"\t\t\t____________________________________________________________\n\n";
cout<<"\t\t\t ***********[ M A K A N A N ]*********** \n";
cout<<"\t\t\t____________________________________________________________\n\n\n";
cout<<"\t\t\t 1) Rendang.......................... Rp. 30.000,-\n";
cout<<"\t\t\t 2) Ikan Bakar ...................... Rp. 35.000,-\n";
cout<<"\t\t\t 3) Sambel Udang..................... Rp. 45.000,-\n";
cout<<"\t\t\t 4) Cumi Hitam ...................... Rp. 25.000,-\n";
cout<<"\t\t\t 5) Telur Rebus...................... Rp. 10.000,-\n";
cout<<"\t\t\t 6) Jamur Crispy..................... Rp. 15.000,-\n";
cout<<"\t\t\t 7) Sop Iga.......................... Rp. 50.000,-\n";
cout<<"\t\t\t 8) None \n\n";
cout<<"\t\t\t____________________________________________________________\n";
cout<<"\nQ: Masukan Angka Makanan Yang Akan Anda Pesan = ";
cin>>pm; //pm adalah variabel untuk pilihan makanan
if(pm==1){ //memulai percabangan if dalam percabangan untuk kondisi 1
hm=30000; //hm adalah variabel untuk harga per makanan
cout<<"\nQ: Mau berapa? ";
cin>>m;} //m adalah variabel untuk kuantitas per makanan
else if(pm==2){ //percabangan untuk kondisi 2
hm=35000;
cout<<"\nQ: Mau berapa? ";
cin>>m;}
else if(pm==3){ //percabangan untuk kondisi 3
hm=45000;
cout<<"\nQ: Mau berapa? ";
cin>>m;}
else if(pm==4){ //percabangan untuk kondisi 4
hm=25000;
cout<<"\nQ: Mau berapa? ";
cin>>m;}
else if(pm==5){ //percabangan untuk kondisi 5
hm=10000;
cout<<"\nQ: Mau berapa? ";
cin>>m;}
else if(pm==6){ //percabangan untuk kondisi 6
hm=15000;
cout<<"\nQ: Mau berapa? ";
cin>>m;}
else if(pm==7){ //percabangan untuk kondisi 7
hm=50000;
cout<<"\nQ: Mau berapa? ";
cin>>m;}
else if(pm==8){
hm=0;
m=1; }
else if(pm!=1||2||3||4||5||6||7||8 ){ //percabangan untuk kondisi terakhir
cout<<"\nMaaf Menu Makanan Tidak Tersedia. Silahkan Memilih Kembali!\n";
getch();
system("cls");
goto menu1; //perintah untuk kembali ke menu1
}
tm=m*hm; //tm adalah variabel untuk total harga makanan dengan mengalikan m dan hm
switch(pm){ //percabangan switch untuk memunculkan array makanan yang dipesan beserta tm
case 1:cout<<"\n\nAnda Memilih "<<"("<<m<<")"<<" "<<makanan[0]<<" => Rp."<<hm<<" x "<<m<<" = Rp."<<tm<<endl; break;
case 2:cout<<"\n\nAnda Memilih "<<"("<<m<<")"<<" "<<makanan[1]<<" => Rp."<<hm<<" x "<<m<<" = Rp."<<tm<<endl; break;
case 3:cout<<"\n\nAnda Memilih "<<"("<<m<<")"<<" "<<makanan[2]<<" => Rp."<<hm<<" x "<<m<<" = Rp."<<tm<<endl; break;
case 4:cout<<"\n\nAnda Memilih "<<"("<<m<<")"<<" "<<makanan[3]<<" => Rp."<<hm<<" x "<<m<<" = Rp."<<tm<<endl; break;
case 5:cout<<"\n\nAnda Memilih "<<"("<<m<<")"<<" "<<makanan[4]<<" => Rp."<<hm<<" x "<<m<<" = Rp."<<tm<<endl; break;
case 6:cout<<"\n\nAnda Memilih "<<"("<<m<<")"<<" "<<makanan[5]<<" => Rp."<<hm<<" x "<<m<<" = Rp."<<tm<<endl; break;
case 7:cout<<"\n\nAnda Memilih "<<"("<<m<<")"<<" "<<makanan[6]<<" => Rp."<<hm<<" x "<<m<<" = Rp."<<tm<<endl; break;
case 8:cout<<"\n\nAnda Memilih "<<"("<<m<<")"<<" "<<makanan[7]<<" => Rp."<<hm<<" x "<<m<<" = Rp."<<tm<<endl; break;
}
goto menu2;
}
else if(p==2){
menu2:
cout<<"\n\n\t\t\t____________________________________________________________\n\n";
cout<<"\t\t\t ***********[ M I N U M A N ]*********** \n";
cout<<"\t\t\t____________________________________________________________\n\n\n";
cout<<"\t\t\t 1) Coffee _ _ _ _ _ _ _ _ _ _ _ _ _ Rp. 30.000,-\n";
cout<<"\t\t\t 2) Iced Tea _ _ _ _ _ _ _ _ _ _ _ _ Rp. 15.000,-\n";
cout<<"\t\t\t 3) Mineral Water _ _ _ _ _ _ _ _ _ Rp. 10.000,-\n";
cout<<"\t\t\t 4) Orange Juice _ _ _ _ _ _ _ _ _ _ Rp. 28.000,-\n";
cout<<"\t\t\t 5) Avocado Juice _ _ _ _ _ _ _ _ _ Rp. 30.000'-\n";
cout<<"\t\t\t 6) None \n\n";
cout<<"\t\t\t____________________________________________________________\n";
cout<<"\nQ: Masukan Angka Minuman Yang Akan Anda Pesan = ";
cin>>pmi;
if(pmi==1){
hmi=30000;
cout<<"\nQ: Mau Berapa? ";
cin>>mi;}
else if(pmi==2){
hmi=15000;
cout<<"\nQ: Mau Berapa? ";
cin>>mi;}
else if(pmi==3){
hmi=10000;
cout<<"\nQ: Mau Berapa? ";
cin>>mi;}
else if(pmi==4){
hmi=28000;
cout<<"\nQ: Mau Berapa? ";
cin>>mi;}
else if(pmi==5){
hmi=30000;
cout<<"\nQ: Mau Berapa? ";
cin>>mi;}
else if(pmi==6){
hmi=0;
mi=1;
}
else if(pmi!=1||2||3||4||5||6){
cout<<"\nMaaf Menu Minuman Tidak Tersedia. Silahkan Memilih Kembali\n";
getch();
system("cls");
goto menu2;
}
tmi=hmi*mi;
switch(pmi){
case 1:cout<<"\n\nAnda Memilih "<<"("<<mi<<")"<<" "<<minuman[0]<<" => Rp."<<hmi<<" x "<<mi<<" = Rp."<<tmi<<endl; break;
case 2:cout<<"\n\nAnda Memilih "<<"("<<mi<<")"<<" "<<minuman[1]<<" => Rp."<<hmi<<" x "<<mi<<" = Rp."<<tmi<<endl; break;
case 3:cout<<"\n\nAnda Memilih "<<"("<<mi<<")"<<" "<<minuman[2]<<" => Rp."<<hmi<<" x "<<mi<<" = Rp."<<tmi<<endl; break;
case 4:cout<<"\n\nAnda Memilih "<<"("<<mi<<")"<<" "<<minuman[3]<<" => Rp."<<hmi<<" x "<<mi<<" = Rp."<<tmi<<endl; break;
case 5:cout<<"\n\nAnda Memilih "<<"("<<mi<<")"<<" "<<minuman[4]<<" => Rp."<<hmi<<" x "<<mi<<" = Rp."<<tmi<<endl; break;
case 6:cout<<"\n\nAnda Memilih "<<"("<<mi<<")"<<" "<<minuman[5]<<" => Rp."<<hmi<<" x "<<mi<<" = Rp."<<tmi<<endl; break;
}getch();
system("cls");
goto menu3;
}
else if(p==3){
menu3:
cout<<"\n\n\t\t\t____________________________________________________________\n\n";
cout<<"\t\t\t ***********[ D E S S E R T ]*********** \n";
cout<<"\t\t\t____________________________________________________________\n\n\n";
cout<<"\t\t\t 1) Cake _ _ _ __ _ _ _ _ _ _ _ _ Rp. 24.000,-\n";
cout<<"\t\t\t 2) Ice Cream _ __ _ _ _ _ _ _ _ _Rp. 20.000,-\n";
cout<<"\t\t\t 3) Brownies _ _ _ _ _ _ _ _ _ _ _Rp. 27.000,-\n";
cout<<"\t\t\t 4) None \n\n";
cout<<"\t\t\t____________________________________________________________\n";
cout<<"\nQ: Masukan Angka Dessert Yang Akan Anda Pesan = ";
cin>>pd;
if(pd==1){
hd=24000;
cout<<"\nQ: Mau Berapa? ";
cin>>d;}
else if(pd==2){
hd=20000;
cout<<"\nQ: Mau Berapa? ";
cin>>d;}
else if(pd==3){
hd=17000;
cout<<"\nQ: Mau Berapa? ";
cin>>d;}
else if(pd==4){
hd=0;
d=1;}
else if(pd!=1||2||3||4){
cout<<"\nMaaf Menu Dessert Tidak Tersedia. Silahkan Memilih Kembali!";
getch();
system("cls");
goto menu3;
}
td=hd*d;
switch(pd){
case 1:cout<<"\n\nAnda Memilih "<<"("<<d<<")"<<" "<<dessert[0]<<" => Rp."<<hd<<" x "<<d<<" = Rp."<<td<<endl; break;
case 2:cout<<"\n\nAnda Memilih "<<"("<<d<<")"<<" "<<dessert[1]<<" => Rp."<<hd<<" x "<<d<<" = Rp."<<td<<endl; break;
case 3:cout<<"\n\nAnda Memilih "<<"("<<d<<")"<<" "<<dessert[2]<<" => Rp."<<hd<<" x "<<d<<" = Rp."<<td<<endl; break;
case 4:cout<<"\n\nAnda Memilih "<<"("<<d<<")"<<" "<<dessert[3]<<" => Rp."<<hd<<" x "<<d<<" = Rp."<<td<<endl; break;
}getch();
system("cls");
goto harga;
}
else{
goto menu;
}
harga:
int TH1, TH2, kembalian, uang, di;
char diskon;
cout<<"\n\n\n\n\t\t\tDiskon kode kartu member: \n";
cout<<"\t\t\t1. G (gold) = 30%\n";
cout<<"\t\t\t2. S (silver) = 20%\n";
cout<<"\t\t\t3. P (perak) = 10%\n";
getch();
system("cls");
cout<<"\t\t\t____________________________________________________________\n\n";
cout<<"\t\t\t ***********[ B I L L ]*********** \n";
cout<<"\t\t\t____________________________________________________________\n\n";
cout<<"\t\t\tNomor Meja Anda: "<<meja<<endl;
switch(pm){
case 1:cout<<"\t\t\t\t\t"<<"("<<m<<")"<<" "<<makanan[0]<<" => Rp."<<hm<<" x "<<m<<" = Rp."<<m*hm<<endl; break;
case 2:cout<<"\t\t\t\t\t"<<"("<<m<<")"<<" "<<makanan[1]<<" => Rp."<<hm<<" x "<<m<<" = Rp."<<m*hm<<endl; break;
case 3:cout<<"\t\t\t\t\t"<<"("<<m<<")"<<" "<<makanan[2]<<" => Rp."<<hm<<" x "<<m<<" = Rp."<<m*hm<<endl; break;
case 4:cout<<"\t\t\t\t\t"<<"("<<m<<")"<<" "<<makanan[3]<<" => Rp."<<hm<<" x "<<m<<" = Rp."<<m*hm<<endl; break;
case 5:cout<<"\t\t\t\t\t"<<"("<<m<<")"<<" "<<makanan[4]<<" => Rp."<<hm<<" x "<<m<<" = Rp."<<m*hm<<endl; break;
case 6:cout<<"\t\t\t\t\t"<<"("<<m<<")"<<" "<<makanan[5]<<" => Rp."<<hm<<" x "<<m<<" = Rp."<<m*hm<<endl; break;
case 7:cout<<"\t\t\t\t\t"<<"("<<m<<")"<<" "<<makanan[6]<<" => Rp."<<hm<<" x "<<m<<" = Rp."<<m*hm<<endl; break;
}
if(p!=1){
tm=0;
TH1=tmi+td;}
else if(p!=1&&p!=2){
tm=tmi=0;
TH1=td;}
else{
TH1=tm+td+tmi;}
switch(pmi){
case 1:cout<<"\t\t\t\t\t"<<"("<<mi<<")"<<" "<<minuman[0]<<" => Rp."<<hmi<<" x "<<mi<<" = Rp."<<tmi<<endl; break;
case 2:cout<<"\t\t\t\t\t"<<"("<<mi<<")"<<" "<<minuman[1]<<" => Rp."<<hmi<<" x "<<mi<<" = Rp."<<tmi<<endl; break;
case 3:cout<<"\t\t\t\t\t"<<"("<<mi<<")"<<" "<<minuman[2]<<" => Rp."<<hmi<<" x "<<mi<<" = Rp."<<tmi<<endl; break;
case 4:cout<<"\t\t\t\t\t"<<"("<<mi<<")"<<" "<<minuman[3]<<" => Rp."<<hmi<<" x "<<mi<<" = Rp."<<tmi<<endl; break;
case 5:cout<<"\t\t\t\t\t"<<"("<<mi<<")"<<" "<<minuman[4]<<" => Rp."<<hmi<<" x "<<mi<<" = Rp."<<tmi<<endl; break;
}
if(p!=1){
tm=0;
TH1=tmi+td;}
else if(p!=1&&p!=2){
tm=tmi=0;
TH1=td;}
else{
TH1=tm+td+tmi;}
switch(pd){
case 1:cout<<"\t\t\t\t\t"<<"("<<d<<")"<<" "<<dessert[0]<<" => Rp."<<hd<<" x "<<d<<" = Rp."<<td<<endl; break;
case 2:cout<<"\t\t\t\t\t"<<"("<<d<<")"<<" "<<dessert[1]<<" => Rp."<<hd<<" x "<<d<<" = Rp."<<td<<endl; break;
case 3:cout<<"\t\t\t\t\t"<<"("<<d<<")"<<" "<<dessert[2]<<" => Rp."<<hd<<" x "<<d<<" = Rp."<<td<<endl; break;
}
if(p!=1&&p!=2){
tm=tmi=0;
TH1=td;}
else{
TH1=tm+td+tmi;}
cout<<"\n\t\t\tHarga Total\t\t\t\t\t= Rp."<<TH1<<endl<<endl;
cout<<"\t\t\tMasukkan kode kartu = ";
cin>>diskon;
getch();
switch (diskon) {
case 'G':
case 'g':
di = TH1*0.3;
cout<<"\t\t\tDiskon = "<<di<<endl;
TH2 = TH1-di;
cout<<"\t\t\tTotal Pembayaran\t\t\t\t = "<<"Rp."<<TH2;
cout<<"\n\t\t\tUang Pelanggan\t\t\t\t\t = "<<"Rp.";cin>>uang;
kembalian=uang-TH2;
break;
case 'S':
case 's':
di = TH1*0.2;
cout<<"\t\t\tDiskon = "<<di<<endl;
TH2 = TH1-di;
cout<<"\t\t\tTotal Pembayaran\t\t\t\t = "<<"Rp."<<TH2;
cout<<"\n\t\t\tUang Pelanggan\t\t\t\t\t = "<<"Rp.";cin>>uang;
kembalian=uang-TH2;
break;
case 'P':
case 'p':
di = TH1*0.1;
cout<<"\t\t\tDiskon = "<<di<<endl;
TH2 = TH1-di;
cout<<"\t\t\tTotal Pembayaran\t\t\t\t = "<<"Rp."<<TH2;
cout<<"\n\t\t\tUang Pelanggan\t\t\t\t\t = "<<"Rp.";cin>>uang;
kembalian=uang-TH2;
break;
default :
cout<<"\t\t\t*Anda tidak mendapatkan diskon :(*";
cout<<"\n\t\t\tTotal Pembayaran\t\t\t\t= "<<"Rp."<<TH1;
cout<<"\n\t\t\tUang Pelanggan\t\t\t\t\t= "<<"Rp.";cin>>uang;
kembalian=uang-TH1;
}
cout<<"\t\t\tKembalian\t\t\t\t\t= "<<"Rp."<<kembalian<<endl;
cout<<"\n\t\t\t\tTerima kasih telah berbelanja di Rumah Kayu Itera\n";
cout<<"\t\t\t\t\tSemoga harimu menyenangkan\n";
system("pause");
return 0;
}
<file_sep>/*
TUBES ASD RA
Kelompok 6
Anggota :
1. <NAME> (118140087)
2. <NAME> (118140127)
3. <NAME> (118140124)
*/
#include <iostream>
#include <stdlib.h>
#include "double.h"
#include "conio.h"
using namespace std;
typedef struct data_tujuan *address;
typedef struct data_tujuan{//Isi element di single liked list
int no;
string kota;
string terminal;
address next;
}data_tujuan1;
struct List {//alamat first untuk single linked list
address first;
}List1;
/****************** PEMBUATAN LIST KOSONG ******************/
void CreateEmpty(List *L){//membuat list dalam kondisi kosong
/* I.S. L sembarang */
/* F.S. Terbentuk list kosong. Lihat definisi di atas. */
(*L).first = NULL;
}
/****************** Manajemen Memori ******************/
address Allocation(int no,string kota, string terminal){//memesan NewElmt di memory untuk single linked list
/* Mengirimkan address hasil alokasi sebuah elemen */
/* Jika alokasi berhasil, maka address tidak NULL. */
/* Misalnya: menghasilkan P, maka Info(P)=no,kota,terminal, Next(P)=NULL*/
/* Jika alokasi gagal, mengirimkan NULL. */
address NewElmt = new data_tujuan1;
NewElmt->no=no;
NewElmt->kota=kota;
NewElmt->terminal=terminal;
NewElmt->next=NULL;
return NewElmt;
}
/****************** TEST LIST KOSONG ******************/
bool IsEmpty(List L){
/* Mengirim true jika list kosong. Lihat definisi di atas. */
return ((L).first == NULL);
}
void Deallocation(address hapus){
/* I.S. hapus terdefinisi */
/* F.S. hapus dikembalikan ke sistem */
/* Melakukan dealokasi/pengembalian address hapus */
delete(hapus);
}
/****************** PRIMITIF BERDASARKAN NILAI ******************/
/*** PENAMBAHAN ELEMEN ***/
void InsertFirst(List *L, int no, string kota, string terminal){
address P;
P = Allocation(no,kota,terminal);
if(P != NULL){
P->next = (*L).first;
(*L).first = P;
}
}
void InsertAfter(address *PredElmt, int no, string kota, string terminal){
address NewElmt;
NewElmt = Allocation(no, kota, terminal);
if(NewElmt != NULL){
NewElmt->next = (*PredElmt)->next;
(*PredElmt)->next = NewElmt;
}
}
/****************** PROSES SEMUA ELEMEN LIST ******************/
void printInfo (List L){
/* I.S. List mungkin kosong
F.S. Jika list tidak kosong,
Semua info yg disimpan pada elemen list diprint dengan format [elemen-1, elemen-2, elemen-3, ...]
Jika list kosong, hanya menuliskan "[]"
*/
int i=0;
if(L.first != NULL){
address p = L.first;
cout<<"\n\t\t+------------------------------------------+";
cout<<"\n\t\t| MENU TUJUAN |";
cout<<"\n\t\t+------------------------------------------+"<<endl;
while(p->next != NULL){
cout<<"\t\t\t" << ++i << ". " << p->kota<< "\t" << p->terminal <<endl;
p = p->next;
}
cout<< "\t\t\t" << ++i <<". " << p->kota<< "\t" << p->terminal<<endl;
}
}
void cetakgaris(int n){//Untuk menampilkan garis tepi header
for(int i=0;i<=79;i++){
cout << "=";
}
cout << endl;
}
void header(){//Untuk menampilkan header program
cetakgaris(79);
cout << "\t\t\t Selamat Datang! " << endl;
cout << "\t\t\t PT.ABC Bus LAMPUNG " << endl;
cout << "\t\t\t Created by Kelompok 6 " << endl;
cetakgaris(79);
}
struct bus{//struct data bus sebagai array of struct
int kode_bus;
string nama_bus,tujuan,berangkat;
int kapasitas;
string tipe_bus;
int harga;
}bus1;
struct user{ //data user sebagai Array of Struct
string nik;
string nama;
int umur;
char jk;
int no_hp;
}user1;
void Jakarta(bus a[]){ //menampilkan jadwal keberangkatan bus tujuan "Jakarta"
for(int i=0;i<=5;i++){
if(a[i].tujuan=="Jakarta"){
cout<< "\t " << a[i].kode_bus << "\t " << a[i].nama_bus << "\t " << a[i].tujuan << "\t " << a[i].berangkat << "\t\t" << a[i].kapasitas << "\t " << a[i].tipe_bus << "\t" << a[i].harga <<endl;
}
}
}
void Bandung(bus a[]){//menampilkan jadwal keberangkatan bus tujuan "Bandung"
for(int i=6;i<=10;i++){
if(a[i].tujuan=="Bandung"){
cout<< "\t " << a[i].kode_bus << "\t " << a[i].nama_bus << "\t " << a[i].tujuan << "\t " << a[i].berangkat << "\t\t" << a[i].kapasitas << "\t " << a[i].tipe_bus << "\t" << a[i].harga <<endl;
}
}
}
void Semarang(bus a[]){//menampilkan jadwal keberangkatan bus tujuan "Semarang"
for(int i=11;i<=13;i++){
if(a[i].tujuan=="Semarang"){
cout<< "\t " << a[i].kode_bus << "\t " << a[i].nama_bus << "\t " << a[i].tujuan << "\t " << a[i].berangkat << "\t\t" << a[i].kapasitas << "\t " << a[i].tipe_bus << "\t" << a[i].harga <<endl;
}
}
}
void Surabaya(bus a[]){//menampilkan jadwal keberangkatan bus tujuan "Surabaya"
for(int i=14;i<=17;i++){
if(a[i].tujuan=="Surabaya"){
cout<< "\t " << a[i].kode_bus << "\t " << a[i].nama_bus << "\t " << a[i].tujuan << "\t " << a[i].berangkat << "\t\t" << a[i].kapasitas << "\t " << a[i].tipe_bus << "\t" << a[i].harga <<endl;
}
}
}
void tampilan_bus(){
cout<<"\n +---------------------------------------------------------------------------------------------+";
cout<<"\n |\t\t\t\t\t\tPILIH BUS\t\t\t\t\t|";
cout<<"\n +---------------------------------------------------------------------------------------------+";
cout<<"\n Kode Bus Nama Bus Tujuan Berangkat Kapasitas Tipe Bus Harga ";
cout<<"\n -------- ------------ -------- ---------- ----------- ---------- -------"<<endl;
}
void tampilan_jumlah(){
cout<<"\n\t+=========================================================+";
cout<<"\n\t| Jumlah Penumpang |";
cout<<"\n\t+=========================================================+";
}
void tampilan_biodata(){
cout<<"\n\t+=========================================================+";
cout<<"\n\t| BIODATA PENUMPANG |";
cout<<"\n\t+=========================================================+";
cout<<endl;
}
void tampilan_tiket(){
cout<<"\n +-------------------------------------------------------------------------+";
cout<<"\n | DATA PENUMPANG |";
cout<<"\n +-------------------------------------------------------------------------+";
cout<<"\n ID Nama Penumpang Nama Bus tujuan berangkat";
cout<<"\n ------- ---------------- ------------ --------- ----------"<<endl;
}
void menu(){
cout<<"Pilihan Menu"<<endl;
cout<<"1.Tampilkan Data Penumpang"<<endl;
cout<<"2.Tambah Data Penumpang"<<endl;
cout<<"3.Update Data Penumpang"<<endl;
cout<<"4.Hapus Data Penumpang"<<endl;
cout<<"5.Cari Data Penumpang"<<endl;
cout<<"6.Keluar"<<endl;
}
int total(int x,bus y[],int kb){//Rumus harga tiket
int total,idx;
for(int i=0; i<18; i++){
if(kb==y[i].kode_bus) idx=y[i].harga ;
}
total=x*idx;
return total;
}
int main(){
bus data_bus[18];//panggil fungsi struct sebagai array of struct
data_bus[0]={1,"Damri","Jakarta","10:00",47,"Eksekutif",230000};
data_bus[1]={2,"Puspa","Jakarta","10:00",35,"Ekonomi",190000};
data_bus[2]={3,"Handoyo","Jakarta","09:45",50,"Eksekutif",275000};
data_bus[3]={4,"Damri","Jakarta","09:00",30,"Ekonomi",150000};
data_bus[4]={5,"Handoyo","Jakarta","08:45",44,"Bisnis",225000};
data_bus[5]={6,"Puspa","Jakarta","07:00",45,"Bisnis",225000};
data_bus[6]={7,"Damri","Bandung","20:00",47,"Executif",230000};
data_bus[7]={8,"Puspa Jaya","Bandung","19:30",35,"Ekonomi",220000};
data_bus[8]={9,"Damri","Bandung","18:45",30,"Ekonomi",230000};
data_bus[9]={10,"Handoyo","Bandung","18:30",44,"Bisnis",280000};
data_bus[10]={11,"Puspa","Bandung","18:15",45,"Bisnis",275000};
data_bus[11]={12,"Damri","Semarang","23:30",30,"Ekonomi",300000};
data_bus[12]={13,"Handoyo","Semarang","22:15",44,"Bisnis",350000};
data_bus[13]={14,"Handoyo","Semarang","22:00",55,"Eksekutif",435000};
data_bus[14]={15,"Puspa","Surabaya","18:10",35,"Ekonomi",400000};
data_bus[15]={16,"Puspa","Surabaya","17:00",50,"Executif",500000};
data_bus[16]={17,"Damri","Surabaya","17:00",30,"Ekonomi",390000};
data_bus[17]={18,"Handoyo","Surabaya","16:45",44,"Bisnis",460000};
List L;//Single Linked list
CreateEmpty(&L);
InsertFirst(&L,5,"Keluar","");
InsertFirst(&L,4,"Surabaya","Adi Sucipto");
InsertFirst(&L,3,"Semarang","Diponogoro");
InsertFirst(&L,2,"Bandung","<NAME>");
InsertFirst(&L,1,"Jakarta","Gambir");
List2 D;//Double Linked List
createList2(&D);
InsertFirst2(&D,"1871012806990001","<NAME>",20,'L',"087820933376","Jakarta");
InsertFirst2(&D,"1871010207970005","<NAME>",23,'P',"085381481234","Bandung");
InsertFirst2(&D,"1871011001020006","<NAME>",17,'P',"087843211234","Semarang");
InsertFirst2(&D,"1871011405010004","<NAME>",18,'L',"081244443333","Surabaya");
home://kembali ketampilan awal
system("cls");//membersihkan layar output
menu();//menu tampilan
int a;
cout << "Pilih nomor(1-6) : "; cin >>a;
if(a==1){//Tampilkan Data Penumpang
PrintForward(D);
goto home;
} else if(a==2){//Tambah Data Penumpang
system("cls");
header();
cout<<endl;
printInfo(L);
int tujuan;
cout<<"\n\t\t KODE TUJUAN : "; cin>>tujuan;
cout << endl;
system("cls");
tampilan_bus();
if(tujuan==1){
Jakarta(data_bus);
} else if(tujuan==2){
Bandung(data_bus);
} else if(tujuan==3){
Semarang(data_bus);
} else if(tujuan==4){
Surabaya(data_bus);
} else if(tujuan==5){
system("cls");
exit(0);
} else {
system("cls");
exit(0);
}
int kb;
cout << "=>Kode Bus = "; cin >> kb;
system("cls");
int jumlah;
tampilan_jumlah();
cout<<"\n\t => Jumlah Penumpang = "; cin>> jumlah;
cout<<"\n\t => Total = "<<total(jumlah,data_bus,kb);
char y;
cout<<"\n\t+---------------------------------------------------------+";
cout<<"\n\t => Apakah Setuju ? [Y/N] : "; cin>>y;
cout<<"\n\t+---------------------------------------------------------+"<<endl;
string nik, nama;
int umur;
char jk;
string no_hp;
string kota;
if(y=='Y'||y=='y'){
for (int i=1; i<=jumlah; i++){
cout<<"\n\t+---------------------------------------------------------+";
cout<<"\n\t| PENUMPANG ke-"<<i<<" |";
cout<<"\n\t+---------------------------------------------------------+";
tampilan_biodata();
cout<<"\tNIK\t: "; cin>>nik;
cout<<"\tNama\t: "; cin.ignore();
getline(cin,nama);
cout<<"\tUmur\t: "; cin >> umur;
cout<<"\tJK(P/L)\t: "; cin >> jk;
cout<<"\tNo.HP\t: "; cin >> no_hp;
cout <<"\tKota\t: "; cin >> kota;
InsertFirst2(&D,nik, nama, umur,jk,no_hp,kota);
}
goto home;
} else {
goto home;
}
} else if(a==3){//Update Data Penumpang
string ubah;//cari berdasarkan NIK
cout << "Update data berdasarkan NO HP" << endl;
cout << "Masukkan NIK untuk mengupdate No HP: ";
cin >> ubah;//ubah No HP
cout << endl;
cout << "\t\t " << update(D,ubah);
goto home;
} else if(a==4){//Hapus Data Penumpang berdasarkan NIK
string hapus;
cout << "Hapus data berdasarkan NIK" << endl;
cout << "Masukkan NIK yang di cari : ";
cin >> hapus;
cout << endl;
DelP(&D,hapus);
goto home;
} else if(a==5){//Cari Data Penumpang
string cari;
cout <<"Cari data penumpang berdasarkan NIK" << endl;
cout << "Masukkan NIK untuk menghapus No HP :";
cin >> cari;
address2 temp;
temp=Search(D,cari);
if(temp!=NULL){
temp->nik;
temp->nama;
temp->umur;
temp->jk;
temp->no_hp;
temp->kota;
getch();
} else {
cout << " ";
}
goto home;
} else if(a==6){//Keluar dari Program
goto keluar;
}
keluar:
system("cls");
return 0;
}
<file_sep>/*
TUBES ASD RA
Kelompok 6
Anggota :
1. <NAME> (118140087)
2. <NAME> (118140127)
3. <NAME> (118140124)
*/
#include <iostream>
#include <stdlib.h>
#include "conio.h"
using namespace std;
typedef struct data_penumpang *address2;
typedef struct data_penumpang{//Isi element di double linked list
string nik;
string nama;
int umur;
char jk;
string no_hp;
string kota;
address2 next;
address2 prev;
} data_penumpang1;
struct List2 {//alamat first dan last untuk double linked list
address2 first;
address2 last;
}List3 ;
//SELEKTOR
#define info(P) (P)->info
#define Next(P) (P)->next
#define Prev(P) (P)->prev
#define First(L) ((L).first)
#define Last(L) ((L).last)
//KONSTANTA
#define Nil NULL
#define Infinity 99999
/****************** TEST LIST KOSONG ******************/
bool IsEmpty2(List2 D) {
/* Mengirim true jika list kosong. Lihat definisi di atas. */
return (First(D) == NULL && Last(D) == NULL);
}
/****************** PEMBUATAN LIST KOSONG ******************/
void createList2(List2 *D) {
/* I.S. D sembarang */
/* F.S. Terbentuk list kosong. Lihat definisi di atas. */
First(*D) = NULL;
Last(*D) = NULL;
}
/****************** Manajemen Memori ******************/
address2 Allocation2(string nik,string nama,int umur, char jk, string no_hp,string kota) {
/* Mengirimkan address hasil alokasi sebuah elemen */
/* Jika alokasi berhasil, maka address tidak nil. */
/* Misalnya: menghasilkan P, maka Info(P)=nik,nama,umur,jk,no_hp,kota, Next(P)=Nil, Prev(P)=Nil */
/* Jika alokasi gagal, mengirimkan Nil. */
address2 NewElmt;
NewElmt = new data_penumpang1;
NewElmt->nik = nik;
NewElmt->nama = nama;
NewElmt->umur = umur;
NewElmt->jk = jk;
NewElmt->no_hp = no_hp;
NewElmt->kota = kota;
NewElmt->next = Nil;
NewElmt->prev = Nil;
return NewElmt;
}
void Deallocation(address2 hapus) {
/* I.S. hapus terdefinisi */
/* F.S. hapus dikembalikan ke sistem */
/* Melakukan dealokasi/pengembalian address hapus */
delete(hapus);
}
/****************** PENCARIAN SEBUAH ELEMEN LIST ******************/
address2 Search (List2 D, string nik){
/* Mencari apakah ada elemen list dengan Info(P)=nama */
/* Jika ada, mengirimkan address elemen tersebut. */
/* Jika tidak ada, mengirimkan Nil */
address2 P = First(D);
while (P != NULL){
if (P->nik == nik){
cout <<"\tNIK : " << P->nik << endl;
cout <<"\tNama : " << P->nama << endl;
cout <<"\tUmur : " << P->umur << endl;
cout <<"\tJK(P/L) : " << P->jk << endl;
cout <<"\tNo.HP : " << P->no_hp<< endl;
cout <<"\tKota : " << P->kota << endl;
return P;
}
P = Next(P);
}
return Nil;
}
/****************** PENGUBAH SEBUAH ELEMEN LIST ******************/
address2 update(List2 D, string nik){
/* Mencari apakah ada elemen list dengan Info(P)=nama */
/* Jika ada, mengirimkan address elemen tersebut. */
/* Jika tidak ada, mengirimkan Nil */
string ubah;
address2 P = First(D);
while (P != NULL){
if (P->nik == nik){
cout << "Update No.HP menjadi = ";
cin>> ubah;
P->no_hp= ubah;
return P;
}
P = Next(P);
}
return Nil;
}
/****************** PRIMITIF BERDASARKAN NILAI ******************/
/*** PENAMBAHAN ELEMEN ***/
void InsertFirst2(List2 *D, string nik, string nama,int umur, char jk, string no_hp,string kota) {
/* I.S. D mungkin kosong */
/* F.S. Melakukan alokasi sebuah elemen dan */
/* menambahkan elemen pertama dengan nik,nama,umur,jk,no_hp,kota jika alokasi berhasil */
address2 NewElmt;
NewElmt = Allocation2(nik,nama,umur,jk,no_hp,kota);
if (NewElmt != NULL) {
if(IsEmpty2(*D)){
D->first = NewElmt;
D->last = NewElmt;
} else{
Next(NewElmt) = First(*D);
Prev(First(*D)) = NewElmt;
First(*D) = NewElmt;
}
}
}
void InsertLast2(List2 *D, string nik, string nama, int umur, char jk, string no_hp,string kota) {
/* I.S. D mungkin kosong */
/* F.S. Melakukan alokasi sebuah elemen dan */
/* menambahkan elemen list di akhir: elemen terakhir yang baru */
/* bernilai nik,nama,umur,jk,no_hp,kota jika alokasi berhasil. Jika alokasi gagal: I.S.= F.S. */
address2 NewElmt;
NewElmt = Allocation2(nik,nama,umur,jk,no_hp,kota);
if (NewElmt != NULL) {
if(IsEmpty2(*D)){
InsertFirst2(D,nik,nama,umur,jk,no_hp,kota);
} else{
Next(Last(*D)) = NewElmt;
Prev(NewElmt) = Last(*D);
Last(*D) = NewElmt;
}
}
}
/****************** PRIMITIF BERDASARKAN ALAMAT ******************/
/*** PENAMBAHAN ELEMEN BERDASARKAN ALAMAT ***/
void InsertFirst2(List2 *D, address2 P){
/* I.S. Sembarang, P sudah dialokasi */
/* F.S. Menambahkan elemen ber-address P sebagai elemen pertama */
if(IsEmpty2(*D)){
First(*D) = P;
Last(*D) = P;
} else{
Next(P) = First(*D);
Prev(First(*D)) = P;
First(*D) = P;
}
}
void InsertLast2 (List2 *D, address2 P){
/* I.S. Sembarang, P sudah dialokasi */
/* F.S. P ditambahkan sebagai elemen terakhir yang baru */
if(IsEmpty2(*D)){
InsertFirst2(D,P);
} else{
Next(Last(*D)) = P;
Prev(P) = Last(*D);
Last(*D) = P;
}
}
void InsertAfter2 (List2 *D, address2 P, address2 Prec){
/* I.S. Prec pastilah elemen list; P sudah dialokasi */
/* F.S. Insert P sebagai elemen sesudah elemen beralamat Prec */
if(Next(Prec) == Nil){
InsertLast2(D,P);
}else{
Next(P) = Next(Prec);
Prev(P) = Prec;
Prev(Next(Prec))= P;
Next(Prec) = P;
}
}
void InsertBefore2 (List2 *D, address2 P, address2 Succ){
/* I.S. Succ pastilah elemen list; P sudah dialokasi */
/* F.S. Insert P sebagai elemen sebelum elemen beralamat Succ */
if(Succ == First(*D)){
InsertFirst2(D,P);
}else{
Next(Prev(Succ)) = P;
Prev(P) = Prev(Succ);
Next(P) = Succ;
Prev(Succ) = P;
}
}
/*** PENGHAPUSAN SEBUAH ELEMEN ***/
void DelFirst (List2 *D, address2 *P){
/* I.S. List tidak kosong */
/* F.S. P adalah alamat elemen pertama list sebelum penghapusan */
/* Elemen list berkurang satu (mungkin menjadi kosong) */
/* First element yg baru adalah suksesor elemen pertama yang lama */
*P = First(*D);
First(*D) = Next(*P);
if(First(*D)!=NULL) Prev(First(*D)) = Nil;
else Last(*D)=NULL;
Deallocation(*P);
}
void DelLast (List2 *D, address2 *P){
/* I.S. List tidak kosong */
/* F.S. P adalah alamat elemen terakhir list sebelum penghapusan */
/* Elemen list berkurang satu (mungkin menjadi kosong) */
/* Last element baru adalah predesesor elemen pertama yg lama, jika ada */
*P = Last(*D);
Last(*D) = Prev(*P);
Next(Last(*D)) = Nil;
Prev(*P) = Nil;
Deallocation(*P);
}
void DelAfter (List2 *D, address2 *Pdel, address2 Prec){
/* I.S. List tidak kosong. Prec adalah anggota list. */
/* F.S. Menghapus Next(Prec): */
/* Pdel adalah alamat elemen list yang dihapus */
*Pdel = Next(Prec);
Next(Prec) = Next(*Pdel);
Prev(Next(*Pdel)) = Prec;
Prev(*Pdel) = Nil;
Next(*Pdel)= Nil;
Deallocation(*Pdel);
}
void DelBefore (List2 *D, address2 *Pdel, address2 Succ){
/* I.S. List tidak kosong. Succ adalah anggota list. */
/* F.S. Menghapus Prev(Succ): */
/* Pdel adalah alamat elemen list yang dihapus */
*Pdel = Prev(Succ);
Next(Prev(*Pdel)) = Succ;
Prev(Succ) = Prev(*Pdel);
Prev(*Pdel) = Nil;
Next(*Pdel) = Nil;
Deallocation(*Pdel);
}
void DelP (List2 *D, string nik){//hapus Elemen yang ditunjuk dengan parameter pencari, yaitu nama
/* I.S. Sembarang */
/* F.S. Jika ada elemen list beraddress P, dengan Info(P)=nik */
/* maka P dihapus dari list dan didealokasi */
/* Jika tidak ada elemen list dengan Info(P)=nama, maka list tetap */
/* List mungkin menjadi kosong karena penghapusan */
address2 P = Search(*D,nik);
address2 prec = Prev(P);
if (P != Nil){
if(P == First(*D)){
DelFirst(D,&P);
}else if(P == Last(*D)){
DelLast(D,&P);
}else{
DelAfter(D,&P,prec);
}
}
}
/****************** PROSES SEMUA ELEMEN LIST ******************/
void PrintForward (List2 D){
/* I.S. List mungkin kosong */
/* F.S. Jika list tidak kosong, isi list dicetak dari elemen pertama */
/* ke elemen terakhir secara horizontal ke kanan: [e1,e2,...,en] */
/* Contoh : jika ada tiga elemen bernilai 1, 20, 30 akan dicetak: [1,20,30] */
/* Jika list kosong : menulis [] */
/* Tidak ada tambahan karakter apa pun di awal, akhir, atau di tengah */
string s;
if(!IsEmpty2(D)){
address2 temp =First(D);
while(Next(temp)!=NULL){
cout<<"\tNIK\t:"<<temp->nik << endl;
cout<<"\tNama\t:"<<temp->nama << endl;
cout<<"\tUmur\t:"<<temp->umur << endl;
cout<<"\tJK(P/L)\t:"<<temp->jk << endl;
cout<<"\tNo.HP\t:"<<temp->no_hp << endl;
cout<<"\tKota\t:"<<temp->kota << endl;
cout<<endl<<endl;
temp=Next(temp);
}
cout<<"\tNIK\t:"<<temp->nik << endl;
cout<<"\tNama\t:"<<temp->nama << endl;
cout<<"\tUmur\t:"<<temp->umur << endl;
cout<<"\tJK(P/L)\t:"<<temp->jk << endl;
cout<<"\tNo.HP\t:"<<temp->no_hp << endl;
cout<<"\tKota\t:"<<temp->kota << endl;
cout<<endl<<endl;
getch();
}
}
|
9e10178132621711dbfafb5d8a73e86831825cef
|
[
"C++"
] | 3
|
C++
|
tubagusDindaMaulid/Tugas-Besar
|
605eddbd6e547af2fff5b6d9735b446a5e54ae96
|
b2b7a72896eed735f480cb1ed20a5831fcd009f8
|
refs/heads/master
|
<file_sep>#<NAME>
#CS498 - MCS-DS - April 7th, 2018
#HW7 Problem 1
#Import Libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Load data
pd_doc = pd.read_table("docword.nips.txt",header=None,sep=' ')
pd_voc = pd.read_table("vocab.nips2.txt",header=None,sep=' ')
docword = np.array(pd_doc)
#Transform into rows as docs and columns as words
docwordpd = pd_doc.pivot(index=0, columns=1, values=2)
docwordpd = docwordpd.fillna(0)
#define log sum exp function - very important
def logsumexpc(X):
x_max = X.max(1)
#return np.log(np.exp(X + x_max[:, None]).sum(1)) - x_max
return x_max + np.log(np.exp(X - x_max[:, None]).sum(1))
#Define pi (not using kmeans) to all be even probability over 30 clusters
pi = np.full((1,30),1/30)
########### P in Initialization
################################
#Defining P (not using kmeans). probability of word in a cluster so each cluster sums to 1.
#assigning clusters randomly
docwordpd['label'] = np.random.randint(0, 30, docwordpd.shape[0])
#summing word counts for whole cluster
#https://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html
topicc = np.array(docwordpd.pivot_table(index=['label'],aggfunc=np.sum))
totaltc = topicc.sum(axis=1)
#getting probability
p = topicc/totaltc[:,None]
#adding smoothing to the zero P's and re normalizing again.
p[p == 0] = 0.0000001
p_scaled = p/p.sum(axis=1)[:,None]
######## W in Initialization - probability that document i is assigned to topic/cluster j
############################
#do the w calculation in log space.
#take log of p
p_scaledlog = np.log(p_scaled)
#take log of pi
log_pi = np.log(pi)
docwordpd.drop(labels='label',inplace=True,axis=1)
#matrix multiply X and log(p) ... X * log(p) because when you log it bring the power down
docwordpd.reset_index(drop=True,inplace=True)
inner = np.matmul(docwordpd,p_scaledlog.T)
#add each pi cluster to the product
wtop = (inner + log_pi)
#take logsumexp to get the denominator. very important to avoid precision errors
#subtract the denominator because we are in log space
logw = wtop-logsumexpc(wtop)[:, None]
#take it out of log space and each doc sums to 1
w = np.exp(logw)
######### Start of EM loops
###########################
#variable to track pi's in each loop
pietracker = np.zeros(shape=(20, 30))
#looping through each iteration
for i in range(0,20):
### M -Step
#matrix multiply W and X to give Pn+1
pplus1top = np.dot(w.T,docwordpd)
pplus1 = pplus1top / pplus1top.sum(axis=1)[:,None] #getting probability
pplus1[pplus1 == 0] = 0.0000001 #smoothing
pplus1prob = pplus1 / pplus1.sum(axis=1)[:,None] #rescaling after smoothing
#calculate pi n+1 sum of w by number of documents
piplus1 = np.sum(w, axis=0) / 1500
pietracker[i] = piplus1
#np.sum(piplus1)
### E Step - calculating w
#log p
ppluslog1 = np.log(pplus1prob)
#log pi
log_pi1 = np.log(piplus1)
# matrix multiply X and log(p) - same as doing xi and pi and summing them.
inner = np.dot(docwordpd,ppluslog1.T)
#add log pi because we in log space
wtop = (inner + log_pi1)
# take logsumexp to get the denominator. very important to avoid precision errors
logw = wtop-logsumexpc(wtop)[:, None]
#exponent to take out of log space
w = np.exp(logw)
#printing pi tracker over iterations and probabilities of final pi
plt.bar(np.arange(len(piplus1)),piplus1)
plt.plot(pietracker)
plt.plot(pietracker[:,4][1:] - pietracker[:,4][:-1])
####Finding top words. empty words were removed from data file directly
sra2 = np.argsort(pplus1prob)
sra1 = sra2[:,:-11:-1]
topwords = pd.DataFrame()
for i in range(0,30):
topten = pd_voc.iloc[sra1[i],:]
topten.reset_index(drop=True, inplace=True)
topten = topten.T
topten['cluster'] = i
topwords = topwords.append(topten)
print(topwords)
<file_sep>#<NAME> - MCS-DS
#CS498
#April 7th, 2018 - HW7 Problem 2
#Import libraries
import pandas as pd
import numpy as np
import imageio
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
#Configuration parameters, number of clusters and iterations
n_clusters = 10
iternations = 100
#loading image and reshaping to one row per pixel (rgb)
img = np.array(imageio.imread('smallsunset.jpg'))
imgf = img.reshape((img.shape[0]*img.shape[1], 3)).astype(np.uint8)
#selecting clusters using kmeans with a random seed.
km = KMeans(n_clusters=n_clusters, random_state=8).fit(imgf)
#assiging cluster centers
cc = np.round(km.cluster_centers_)
#assgning cluster labels
label = km.labels_
#turning into pandas dataframe for convenience of pivot_table function
imgfdf = pd.DataFrame(imgf)
imgfdf['label'] = label #assigning label to the df
#storing a backup array for later
imgdup = np.array(imgfdf)
### Pi initialization
######################
# by counting pixels assigned to cluster from kmeans
#pi sums to one
picount = (imgfdf.pivot_table(index='label',aggfunc=len))
picount = picount/picount.iloc[:,0].sum()
picount = np.array(picount.iloc[:,0])
### W initialization
######################
#setting up empty arrays
xminusu = np.zeros(shape=(imgf.shape[0],3))
wtoplist = np.zeros(shape=(n_clusters,imgf.shape[0]))
pitracker = np.zeros(shape=(iternations,n_clusters))
utracker = np.zeros(shape=(iternations,3))
distancetracker = np.zeros(shape=(n_clusters,imgf.shape[0]))
#calculating the distance "dmin" by looping over clusters and removing the cluster center
#then squaring and summing all the rows up to give distance per pixel. keeping track of them per cluster
for i in range(0,n_clusters):
xminusu[:, 2] = imgdup[:, 2] - cc[i][2]
xminusu[:, 1] = imgdup[:, 1] - cc[i][1]
xminusu[:, 0] = imgdup[:, 0] - cc[i][0]
distance = np.sqrt(np.sum(np.square(xminusu), axis=1))
distancetracker[i] = distance
#finding the smallest distance to each pixel and storing the value
distancesmall = np.round(np.amin(distancetracker,axis=0)) #rounding them off since they are pixels
#calculating w by looping over clusters. calculating the x - u for each pixel.
#squaring the different and summing up all the rows to give number of pixels array for each cluster
#then *-1 to make it negative and divide by 2, then subtract the distance to ensure no precision issues
#the calculation in the power has negative numbers before exponent.
#exponent the value and then times by pi. the denominator is just the sum because i am no longer in log space.
for i in range(0,n_clusters):
xminusu[:, 2] = imgdup[:, 2] - cc[i][2]
xminusu[:, 1] = imgdup[:, 1] - cc[i][1]
xminusu[:, 0] = imgdup[:, 0] - cc[i][0]
wtop = np.exp(((np.sum(np.square(xminusu),axis=1)-np.square(distancesmall))*-1)/2) #numerator
wtoppi = wtop*picount[i] #numerator
wtoplist[i] = wtoppi
wbot = wtoplist.sum(axis=0) #denominator
w = wtoplist/wbot
### Start of EM algorithim loops
################################
for i in range(0,iternations):
#calculating u. matrix multiplication of X and W
utop = np.dot(imgdup[:, :3].T, w.T) #leave a 3x10
ubot = w.sum(axis=1) #sum up w across pixels to leave 1x10
u = utop / ubot #divide to get u pixels
utracker[i] = u[:,0]
# calculating pi. same bot that was used in u over number of pixels
pi = ubot / imgf.shape[0]
pitracker[i] = pi
#calculating distance dmin to use in w calculation same logic as in initialization
#looping over clusters to calculate distance
for f in range(0, n_clusters):
xminusu[:, 2] = imgdup[:, 2] - u[2][f]
xminusu[:, 1] = imgdup[:, 1] - u[1][f]
xminusu[:, 0] = imgdup[:, 0] - u[0][f]
distance = np.sqrt(np.sum(np.square(xminusu), axis=1))
distancetracker[f] = distance
distancesmall = np.round(np.amin(distancetracker, axis=0))
#looping over clusters to calculate w. same logic as in initialization
#x minus u and stores the results for each pixel. square the result and sum up giving number of pixels
#subtract the distance calculated in the distance loop for each pixel. *-1 to get negative and div by 2
#exponent the result to get out of log space and multiply by pi. store this for each cluster.
#the denominator is the sum of the numerator
for k in range(0, n_clusters):
xminusu[:, 2] = imgdup[:, 2] - u[2][k] #x - u
xminusu[:, 1] = imgdup[:, 1] - u[1][k]
xminusu[:, 0] = imgdup[:, 0] - u[0][k]
#wtop = np.exp(((np.sum(np.square(xminusu), axis=1)) * -1) / 2)
wtop = np.exp(((np.sum(np.square(xminusu), axis=1) - np.square(distancesmall)) * -1) / 2)
wtoppi = wtop * pi[k] #w numerator * pi
wtoplist[k] = wtoppi #numerator
wbot = wtoplist.sum(axis=0) #denominator
w = wtoplist / wbot[:, None].T
#finding the best cluster per pixel
topclusterpixel = np.argmax(w,axis=0)
#generating image using the mean pixels from u
EMimg = u[:,topclusterpixel]
EMimg = EMimg.astype(np.uint8)
EMreshape = EMimg.T.reshape((img.shape[0], img.shape[1], 3))
plt.imshow(EMreshape) #EM image
#plt.imshow(img) #original image
#convergence plots to indicate when we can stop the iterations
#difference of absolute u's over iterations
udiff = np.abs(utracker[:-1,:] - utracker[1:,:])
plt.plot(udiff[:,0])
#differents of absolute pi's over iterations
pidiff = np.abs(pitracker[:-1,:] - pitracker[1:,:])
plt.plot(pidiff[:,0])
<file_sep># Expectation_Maximization_fromScratch
Create an expectation maximization (EM) to classify text and create low res images
|
de0ad8bc84ce0b8e48da2240bc9882380eebdf56
|
[
"Markdown",
"Python"
] | 3
|
Python
|
mattbitter/Expectation_Maximization_fromScratch
|
90a261ce438944d6ba68129e4de66d785594e83a
|
8ab9ba30c226ffc9ea1ab43f18127dbbe85a9f8d
|
refs/heads/master
|
<file_sep>import request from '@/utils/request'
export function getTask(params) {
return request({
url: '/Task/getTasks',
method: 'get',
params
})
}
export function taskStart(params) {
return request({
url: '/TaskState/taskStart',
method: 'post',
params
})
}
export function taskComplete(params) {
return request({
url: '/TaskState/taskComplete',
method: 'post',
params
})
}
export function taskSettlement(params) {
return request({
url: '/TaskState/taskSettlement',
method: 'post',
params
})
}
export function taskArchived(params) {
return request({
url: '/TaskState/taskArchived',
method: 'post',
params
})
}
export function taskBack(params) {
return request({
url: '/TaskState/taskBack',
method: 'post',
params
})
}
export function shareScore(params) {
return request({
url: '/TaskState/shareScore',
method: 'post',
params
})
}
export function taskValidate(params) {
return request({
url: '/TaskState/taskValidate',
method: 'post',
params
})
}
<file_sep>package com.synco.oa.util;
import redis.clients.jedis.Jedis;
public class RedisClient {
public static int setData(String datas) {
Jedis jedis = new Jedis("172.16.17.32", 6379);
jedis.set("datas", datas);
jedis.close();
return 1;
}
public static String getData() {
Jedis jedis = new Jedis("172.16.17.32", 6379);
String datas = jedis.get("datas");
jedis.close();
return datas;
}
public static int delData() {
Jedis jedis = new Jedis("172.16.17.32", 6379);
jedis.del("datas");
jedis.close();
return 1;
}
}
<file_sep>import { logout, getInfo, getUserIntegral } from '@/api/login'
import { getToken, removeToken, setToken } from '@/utils/auth'
const user = {
state: {
token: getToken(),
info: '',
integral: ''
},
mutations: {
SET_TOKEN: (state, token) => {
state.token = token
},
SET_INFO: (state, info) => {
state.info = info
},
SET_INTEGRAL: (state, integral) => {
state.integral = integral
},
SET_LOADING: (state, loading) => {
state.loading = loading
}
},
actions: {
// 获取用户信息
GetInfo({ commit, state }) {
return new Promise((resolve, reject) => {
getInfo(getToken()).then(response => {
setToken(getToken())
commit('SET_INFO', response.data)
resolve(response)
}).catch(error => {
reject(error)
})
})
},
// 获取用户信息
GetUserIntegral({ commit, state }) {
return new Promise((resolve, reject) => {
getUserIntegral(getToken()).then(response => {
commit('SET_INTEGRAL', response.data)
resolve(response)
}).catch(error => {
reject(error)
})
})
},
// 登出
FedLogOut({ commit, state }) {
commit('SET_INTEGRAL', true)
return new Promise((resolve, reject) => {
logout(state.token).then(() => {
commit('SET_INTEGRAL', false)
commit('SET_TOKEN', '')
commit('SET_INFO', {})
removeToken('usertoken')
resolve()
}).catch(error => {
commit('SET_INTEGRAL', false)
reject(error)
})
})
}
}
}
export default user
<file_sep>package com.synco.oa.service.Impl;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.print.attribute.standard.NumberOfInterveningJobs;
import org.springframework.stereotype.Service;
import com.synco.oa.dao.TaskMapper;
import com.synco.oa.pojo.Task;
import com.synco.oa.pojo.Task_time;
import com.synco.oa.pojo.Tasklog;
import com.synco.oa.pojo.Taskstate;
import com.synco.oa.service.TaskService;
import com.synco.oa.util.NumberUtil;
import com.synco.oa.pojo.Number;
@Service
public class TaskServiceImpl implements TaskService {
@Resource
TaskMapper taskMapper;
/**
* 新增任务
*
* @author 10049
*/
@Override
public Integer inserTaskInfoId(Task task) {
return taskMapper.inserTaskInfoId(task);
}
/**
* 判断是否新增任务
*
* @author 10049
* @throws Exception
*/
@Override
public Integer findTaskInsertTime(String taskid,String task_name,String task_create_time,String folder_name,String access_token) throws Exception {
// SimpleDateFormat simdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date maxTime = taskMapper.findTaskInsertTime();
Integer a = 0;
Task task = new Task();
task.setTask_id(taskid);
task.setTask_name(task_name);
task.setTask_create_time(task_create_time);
//开始设置任务唯一编码
//设置项目标示
String project_type = "";
String task_only_code_ins = "";
if("微信创意服务".equals(folder_name)) {
project_type = "A";
}
if("互动开发服务".equals(folder_name)) {
project_type = "B";
}
if("活动管理服务".equals(folder_name)) {
project_type = "C";
}
if("视觉设计服务".equals(folder_name)) {
project_type = "D";
}
if("视频创意服务".equals(folder_name)) {
project_type = "E";
}else {
project_type = "Z";
}
if (maxTime == null) {
String string1 = "ELP";
String nowTime1 = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String[] arr1 = nowTime1.split("-");
for (String string2 : arr1) {
string1 = string1 + string2;
}
task_only_code_ins = string1 + "001"+project_type;
task.setTask_only_code(task_only_code_ins);
a = inserTaskInfoId(task);
//插入成功之后,将任务编号写入到明道任务中
List<Number> numbers = NumberUtil.getCustom(access_token, taskid);
for (Number number : numbers) {
if("任务编号".equals(number.getControl_name())) {
NumberUtil.update_control_value(access_token, taskid, number.getControl_id(), task_only_code_ins);
}
}
return a;
}
if (findTaskId(task.getTask_id()) == "C") {
//将在这里实现任务唯一编号的添加
//查询最后最新一次任务标号
String task_only_code = taskMapper.findInsertTaskOnlyCode();
if(null!=task_only_code && !"0".equals(task_only_code) && !"".equals(task_only_code)) {
//新增功能,每天重新开始从1到999开始计算
String task_day_auto = (String) task_only_code.subSequence(3, 11);
String today_time = "";
String nowTime_ = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String[] arr_ = nowTime_.split("-");
for (String string_ : arr_) {
today_time = today_time+string_;
}
if(task_day_auto.equals(today_time)) {
//截取自增字符串
String taskIdd1 = (String) task_only_code.subSequence(11, 14);
//将字符转类型转换为Int类型进行自增
int taskIdd2 = Integer.parseInt(taskIdd1);
taskIdd2 = taskIdd2 + 1;
//将Int类型转换为字符串类型
String taskIdd3 = Integer.toString(taskIdd2);
if(taskIdd3.length()==1) {
taskIdd3 = "00"+taskIdd3;
}
if(taskIdd3.length()==2) {
taskIdd3 = "0"+taskIdd3;
}
//代码前缀
String task_idd4 = "ELP"+task_day_auto;
//调用controller层传过来的数据完成拼接
task_only_code_ins = task_idd4 + taskIdd3 + project_type;
}
//
if(!task_day_auto.equals(today_time)) {
String string1 = "ELP"+today_time;
task_only_code_ins = string1 + "001"+project_type;
task.setTask_only_code(task_only_code_ins);
}
}
//所有信息通过这里添加
task.setTask_only_code(task_only_code_ins);
a = inserTaskInfoId(task);
//插入成功之后,将任务编号写入到明道任务中
List<Number> numbers = NumberUtil.getCustom(access_token, taskid);
if(numbers!=null) {
for (Number number : numbers) {
if("任务编号".equals(number.getControl_name())) {
NumberUtil.update_control_value(access_token, taskid, number.getControl_id(), task_only_code_ins);
}
}
}
return a;
}
/*
* } } catch (ParseException e) { e.printStackTrace(); }
*/
return a;
}
@Override
public Integer findTaskIntegral(String task_id) {
return taskMapper.findTaskIntegral(task_id);
}
@Override
public Taskstate taskStateList(String task_id) {
return taskMapper.taskStateList(task_id);
}
@Override
public List<Task> taskStateListAll() {
return taskMapper.taskStateListAll();
}
@Override
public Integer editTaskState(String task_id, Integer taskState) {
return taskMapper.editTaskState(task_id, taskState);
}
@Override
public String findTaskId(String task_id) {
String s = taskMapper.findTaskId(task_id);
if (s == null) {
s = "C";
}
return s;
}
/*
* @Override public String TaskJson(String json, String taskfen) { List<tasks>
* taskList = JSONObject.parseArray(json, tasks.class); List<tasks> taskList3 =
* new ArrayList<tasks>(); String retuls = null; if (taskfen != null && taskfen
* != "") { if (taskfen.equals("1")) { taskfen = "已完成"; } for (tasks tasks :
* taskList) { if (taskfen.equals(tasks.getUserState())) { taskList3.add(tasks);
* retuls = JSON.toJSONString(taskList3); } else if
* (taskfen.equals(tasks.getTaskState())) { taskList3.add(tasks); retuls =
* JSON.toJSONString(taskList3); } } } else { retuls =
* JSON.toJSONString(taskList); } return retuls; }
*/
@Override
public Integer editTaskIntegral(Task task) {
return taskMapper.editTaskIntegral(task);
}
/**
* 更新外部积分
*
* @author zj
*/
@Override
public Integer editTaskCustomerScore(String task_id, Float task_customer_score) {
return taskMapper.editTaskCustomerScore(task_id, task_customer_score);
}
/**
* 更新内部积分
*
* @author zj
*/
@Override
public Integer editTaskAdminScore(String task_id, Float task_admin_score) {
return taskMapper.editTaskAdminScore(task_id, task_admin_score);
}
/**
* 查询外部积分
*
* @author zj
*/
@Override
public Float findTaskCustomerScore(String task_id) {
return taskMapper.findTaskCustomerScore(task_id);
}
/**
* 查询内部积分
*
* @author zj
*/
@Override
public Float findTaskAdminScore(String task_id) {
return taskMapper.findTaskAdminScore(task_id);
}
@Override
public Integer editTaskCode(String code, String task_id) {
return taskMapper.editTaskCode(code, task_id);
}
@Override
public Boolean findTaskCode(String code, String task_id) {
if (taskMapper.findTaskCode(code, task_id) > 0) {
return true;
}
return false;
}
/**
* 添加客户的评价信息
*/
@Override
public Integer insertCustomerEvaluation(String task_id, Float task_customer_score, Float task_customer_quality,
String task_customer_remarks) {
return taskMapper.insertCustomerEvaluation(task_id, task_customer_score, task_customer_quality, task_customer_remarks);
}
/**
* 查询客户的评价信息
*/
@Override
public Task getTasks1(String task_id) {
return taskMapper.getTasks1(task_id);
}
/**
* 查询日志信息
*
* @author zj
*/
@Override
public List<Tasklog> findTasklog() {
return taskMapper.findTasklog();
}
/**
* 新增日志信息
*
* @author zj
*/
@Override
public int insertTasklog(String full_name, Date log_time, String operationType,String task_name,String data,String task_id) {
return taskMapper.inserTasklog(full_name, log_time, operationType, task_name,data,task_id);
}
@Override
//查询任务的密码
public String findCode(String task_id) {
return taskMapper.findCode(task_id);
}
@Override
//查询任务的名字
public String findTaskName(String task_id) {
return taskMapper.findTaskName(task_id);
}
@Override
//查询最后一次任务唯一编号
public String findInsertTaskOnlyCode() {
return taskMapper.findInsertTaskOnlyCode();
}
@Override
//新增任务唯一编号
public int insertTaskOnlyCode(String project_type, String task_id) {
int result = 0;
/* //查询是否已经有了唯一任务编号
String task_code1 = findTaskOnlyCodeByTaskId(task_id);
if("0".equals(task_code1)) {
//查询最后最新一次任务标号
String task_only_code = taskMapper.findInsertTaskOnlyCode();
if(null!=task_only_code && !"0".equals(task_only_code)) {
//截取自增字符串
String taskIdd1 = (String) task_only_code.subSequence(11, 14);
System.out.println("taskIdd1:"+taskIdd1);
//将字符转类型转换为Int类型进行自增
int taskIdd2 = Integer.parseInt(taskIdd1);
taskIdd2 = taskIdd2 + 1;
//将Int类型转换为字符串类型
String taskIdd3 = Integer.toString(taskIdd2);
taskIdd3 = "00"+taskIdd3;
//代码前缀
String task_idd4 = "ELP";
//代码前缀 + 中间的时间部分
String nowTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String[] arr = nowTime.split("-");
for (String string_ : arr) {
task_idd4 = task_idd4+string_;
}
//调用controller层传过来的数据完成拼接
String taskIdd5 = task_idd4 + taskIdd3 + project_type;
//执行插入
result = taskMapper.insertTaskOnlyCode(taskIdd5, task_id);
}
if(("0").equals(task_only_code)) {
String string1 = "ELP";
String nowTime1 = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String[] arr1 = nowTime1.split("-");
for (String string2 : arr1) {
string1 = string1 + string2;
}
String string2 = string1 + "001"+project_type;
result = taskMapper.insertTaskOnlyCode(string2, task_id);
}
} */
return result;
}
@Override
//根据任务id查询任务唯一编号
public String findTaskOnlyCodeByTaskId(String task_id) {
return taskMapper.findTaskOnlyCodeByTaskId(task_id);
}
@Override
//根据任务id查询任务日志
public List<Tasklog> getTaskDetailLog(String task_id) {
return taskMapper.getTaskDetailLog(task_id);
}
@Override
//保存开始任务分配的初始积分
public int editTaskScore2ByTaskId(Integer task_2_score, String task_id) {
return taskMapper.editTaskScore2ByTaskId(task_2_score, task_id);
}
@Override
//保存完成任务分配的积分
public int editTaskScore3ByTaskId(Integer task_3_score, String task_id) {
return taskMapper.editTaskScore3ByTaskId(task_3_score, task_id);
}
@Override
//保存结算任务分配的积分
public int editTaskScore4ByTaskId(Integer task_4_score, String task_id) {
return taskMapper.editTaskScore4ByTaskId(task_4_score, task_id);
}
@Override
//根据任务id查询开始任务时分配的任务总分
public Integer findTaskScore2ById(String task_id) {
return taskMapper.findTaskScore2ById(task_id);
}
@Override
public Integer findTaskScore3ById(String task_id) {
return taskMapper.findTaskScore3ById(task_id);
}
@Override
public Integer findTaskScore4ById(String task_id) {
return taskMapper.findTaskScore4ById(task_id);
}
/**
* 根据时间查询任务操作详情
*/
@Override
public List<Task_time> getTaskTime(String Start,String End,String account_id) {
return taskMapper.getTaskTime(Start,End,account_id);
}
/**
* 新增任务操作
*/
@Override
public int setTaskTime(Task_time task_time) {
return taskMapper.setTaskTime(task_time);
}
/**
* 根据时间查询任务积分总和
*/
@Override
public Task_time getIntegral(String Start, String End,String account_id) {
return taskMapper.getIntegral(Start,End,account_id);
}
}
<file_sep>import axios from 'axios';
import Qs from 'qs';
const instance = axios.create({
baseURL: process.env.BASE_API,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
timeout: 60000
})
// 请求队列
const queue = [];
// axios内置的中断ajax的方法
const cancelToken = axios.CancelToken;
// 拼接请求的url和方法,同样的url+方法可以视为相同的请求
const token = (config) =>{
return `${config.url}_${config.method}`
}
// 中断重复的请求,并从队列中移除
const removeQueue = (config) => {
for(let i=0, size = queue.length; i < size; i++){
const task = queue[i];
if(task.token === token(config)) {
task.cancel();
queue.splice(i, 1);
}
}
}
//添加请求拦截器
instance.interceptors.request.use(config=>{
removeQueue(config); // 中断之前的同名请求
// 添加cancelToken
config.cancelToken = new cancelToken((c)=>{
queue.push({ token: token(config), cancel: c });
});
return config;
}, error => {
return Promise.reject(error);
});
//添加响应拦截器
instance.interceptors.response.use(response=>{
// 在请求完成后,自动移出队列
removeQueue(response.config);
return response.data
}, httpErrorHandler);
/**
* 封装后的ajax post方法
*
* @param {string} url 请求路径
* @param {object} data 请求参数
* @param {object} config 用户自定义设置
* @returns
*/
function post (url, data, config = {}) => {
return instance.post(url, data, config)
}
/**
* 封装后的ajax get方法
*
* @param {string} url 请求路径
* @param {object} params 请求参数
* @param {object} config 用户自定义设置
* @returns
*/
function post (url, params, config = {}) => {
return instance.get(url, {params}, config)
}
export default {
post,
get,
}<file_sep>import Cookies from 'js-cookie'
const TokenKey = 'usertoken' // 用户token
export function getToken() {
var url = window.location.search
var theRequest = {}
if (url.indexOf('?') !== -1) {
var str = url.substr(1)
var strs = str.split('&')
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1]
}
return theRequest.login
} else if (Cookies.get(TokenKey)) {
return Cookies.get(TokenKey)
} else {
return theRequest.login
}
}
export function setToken(token) {
return Cookies.set(TokenKey, token)
}
export function removeToken() {
return Cookies.remove(TokenKey)
}
export function findTask(task, taskId) {
for (let i = 0; i < task.length; i++) {
if (task[i].task_id === taskId) {
return task[i]
}
}
}
export function deleteTask(task, typeTask, taskInfo, state) {
for (let i = 0; i < task.length; i++) {
if (task[i].task_id === taskInfo.task_id) {
state ? task.splice(i, 1) : task[i] = taskInfo
}
}
for (let j = 0; j < typeTask.length; j++) {
if (typeTask[j].task_id === taskInfo.task_id) {
typeTask.splice(j, 1)
}
}
}
<file_sep>/**
*
*/
package com.synco.oa.pojo;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* @author LiQian
*
* 任务信息实体类
*/
public class Task implements Serializable {
private Integer id;
private String task_id;
private List<tasks> tasks;// 包含任务ID,和名称
private Integer task_integral;
private Integer task_taskstate_id;
private Float task_customer_score;
private Float task_customer_quality;
private String task_customer_remarks;
private Float task_admin_score;
private Date task_inserttime;
private String task_name;
//任务唯一编号
private String task_only_code;
private String task_create_time;
private Integer task_1_score;
private Integer task_2_score;
private Integer task_3_score;
private Integer task_4_score;
private Integer task_5_score;
public Integer getTask_1_score() {
return task_1_score;
}
public void setTask_1_score(Integer task_1_score) {
this.task_1_score = task_1_score;
}
public Integer getTask_2_score() {
return task_2_score;
}
public void setTask_2_score(Integer task_2_score) {
this.task_2_score = task_2_score;
}
public Integer getTask_3_score() {
return task_3_score;
}
public void setTask_3_score(Integer task_3_score) {
this.task_3_score = task_3_score;
}
public Integer getTask_4_score() {
return task_4_score;
}
public void setTask_4_score(Integer task_4_score) {
this.task_4_score = task_4_score;
}
public Integer getTask_5_score() {
return task_5_score;
}
public void setTask_5_score(Integer task_5_score) {
this.task_5_score = task_5_score;
}
public String getTask_create_time() {
return task_create_time;
}
public void setTask_create_time(String task_create_time) {
this.task_create_time = task_create_time;
}
public String getTask_only_code() {
return task_only_code;
}
public void setTask_only_code(String task_only_code) {
this.task_only_code = task_only_code;
}
public String getTask_name() {
return task_name;
}
public void setTask_name(String task_name) {
this.task_name = task_name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTask_id() {
return task_id;
}
public void setTask_id(String task_id) {
this.task_id = task_id;
}
public List<tasks> getTasks() {
return tasks;
}
public void setTasks(List<tasks> tasks) {
this.tasks = tasks;
}
public Integer getTask_integral() {
return task_integral;
}
public void setTask_integral(Integer task_integral) {
this.task_integral = task_integral;
}
public Integer getTask_taskstate_id() {
return task_taskstate_id;
}
public void setTask_taskstate_id(Integer task_taskstate_id) {
this.task_taskstate_id = task_taskstate_id;
}
public Float getTask_customer_score() {
return task_customer_score;
}
public void setTask_customer_score(Float task_customer_score) {
this.task_customer_score = task_customer_score;
}
public Float getTask_customer_quality() {
return task_customer_quality;
}
public void setTask_customer_quality(Float task_customer_quality) {
this.task_customer_quality = task_customer_quality;
}
public String getTask_customer_remarks() {
return task_customer_remarks;
}
public void setTask_customer_remarks(String task_customer_remarks) {
this.task_customer_remarks = task_customer_remarks;
}
public Float getTask_admin_score() {
return task_admin_score;
}
public void setTask_admin_score(Float task_admin_score) {
this.task_admin_score = task_admin_score;
}
public Date getTask_inserttime() {
return task_inserttime;
}
public void setTask_inserttime(Date task_inserttime) {
this.task_inserttime = task_inserttime;
}
public Task(Integer id, String task_id, List<com.synco.oa.pojo.tasks> tasks, Integer task_integral,
Integer task_taskstate_id, Float task_customer_score, Float task_customer_quality,
String task_customer_remarks, Float task_admin_score, Date task_inserttime) {
super();
this.id = id;
this.task_id = task_id;
this.tasks = tasks;
this.task_integral = task_integral;
this.task_taskstate_id = task_taskstate_id;
this.task_customer_score = task_customer_score;
this.task_customer_quality = task_customer_quality;
this.task_customer_remarks = task_customer_remarks;
this.task_admin_score = task_admin_score;
this.task_inserttime = task_inserttime;
}
@Override
public String toString() {
return "Task [id=" + id + ", task_id=" + task_id + ", tasks=" + tasks + ", task_integral=" + task_integral
+ ", task_taskstate_id=" + task_taskstate_id + ", task_customer_score=" + task_customer_score
+ ", task_customer_quality=" + task_customer_quality + ", task_customer_remarks="
+ task_customer_remarks + ", task_admin_score=" + task_admin_score + ", task_inserttime="
+ task_inserttime + "]";
}
public Task() {
super();
}
}
<file_sep>package com.synco.oa.util;
import com.alibaba.fastjson.JSONObject;
import com.synco.oa.pojo.Number;
import org.apache.http.conn.ConnectTimeoutException;
import org.springframework.web.bind.annotation.RequestBody;
import java.net.SocketTimeoutException;
import java.util.List;
public class NumberUtil {
public static void main(String[] args) throws Exception {
System.out.println(addTaskUser("9e47c7f412a1415f8b03a69e828ef380", "9a50fabc-16ee-4ba6-9ac1-c8a3f2b2e705", "52bcc2fc-e67a-4b6d-8074-9e92956c7829"));
}
//获取任务自定义控件
public static List<Number> getCustom(String user_token,String task_id) throws Exception {
String url = "https://api.mingdao.com/v2/task/get_task_controls?access_token="+user_token+"&task_id="+task_id+"";
String result = HttpClientUtils.get(url,"UTF-8");
// 转化实体类
String json = JsonUtil.getJsonPojo(result);
List<Number> numberlist = JSONObject.parseArray(json, Number.class);
return numberlist;
}
//向明道修改自定义控件的值
public static String update_control_value(String user_token,String task_id,String control_id,String value) throws Exception{
//String jsonValue = JSONObject.toJSONString(value);
String url = "https://api.mingdao.com/v2/task/update_control_value";
String result = HttpClientUtils.postParameters(url,"access_token="+user_token+"&task_id="+task_id+"&control_id="+control_id+"&value="+value);
return result;
}
//向明道修改任务状态,标记为已完成
public static String updateTaskStatus(String access_token,String task_id,String status,String include_sub_tasks) throws Exception{
/*status 0:未完成;1:完成
include_sub_tasks 是否包含子任务
clear_actual_start_time 是否清除实际开始时间,首次传false,如果接收到30031,弹窗需要清除的话传true*/
String url = "https://api.mingdao.com/v1/task/Update_Task_Status";
String result = HttpClientUtils.postParameters(url,"access_token="+access_token+"&task_id="+task_id+"&status="+status+"&include_sub_tasks="+include_sub_tasks+"&clear_actual_start_time=false");
return result;
}
//修改任务名字
public static String updateTaskName(String access_token,String task_id,String task_name) throws Exception{
/*HTTP请求方式 post
请求参数 必须 类型及范围
access_token true string 当前登录用户访问令牌
task_id true string 任务id
task_name true string 任务名称*/
String url = "https://api.mingdao.com/v1/task/update_task_name";
String result = HttpClientUtils.postParameters(url,"access_token="+access_token+"&task_id="+task_id+"&task_name="+task_name);
return result;
}
//添加参与人
public static String addTaskUser(String access_token,String task_id,String account_ids) throws Exception{
/*HTTP请求方式 post
请求参数 必须 类型及范围
access_token true string 当前登录用户访问令牌
task_id true string 任务id
account_ids true string 用户ID,多个用英文逗号隔开。*/
String url = "https://api.mingdao.com/v1/task/add_members_to_a_task";
String result = HttpClientUtils.postParameters(url,"access_token="+access_token+"&task_id="+task_id+"&account_ids="+account_ids);
System.out.println("添加任务状态返回结果:"+result);
return result;
}
//删除参与人
public static String delTaskUser(String access_token,String task_id,String account_id) throws Exception{
/*HTTP请求方式 post
请求参数 必须 类型及范围
access_token true string 当前登录用户访问令牌
task_id true string 任务id
account_id true string member的id*/
String url = "https://api.mingdao.com/v1/task/remove_a_member_from_a_task";
String result = HttpClientUtils.postParameters(url,"access_token="+access_token+"&task_id="+task_id+"&account_id="+account_id);
System.out.println("删除任务参与人状态返回结果:"+result);
return result;
}
//任务负责人修改
public static String updateTaskCharger(String access_token,String task_id,String new_charger) throws Exception{
/*返回格式 JSON
HTTP请求方式 post
请求参数 必须 类型及范围
access_token true string 当前登录用户访问令牌
task_id true string 任务id
new_charger true string 新负责人的ID*/
String url = "https://api.mingdao.com/v1/task/update_task_charger_property";
String result = HttpClientUtils.postParameters(url,"access_token="+access_token+"&task_id="+task_id+"&new_charger="+new_charger);
System.out.println("修改任务负责人返回结果:"+result);
return result;
}
//修改任务开始时间和结束时间
public static String updateTaskTime(String access_token,String task_id,String start_time,String deadline) throws Exception{
/*参数 参数类型 必须
access_token string 是 访问令牌 <PASSWORD>
task_id string 是 任务Id ff696ccf-4794-4dc9-a1c3-4a3526485cd3
start_time string 否 开始时间(空为不设置,时间格式为2017-08-04 21:00或2017-08-04 21:00:00) 2017-08-04 21:00
deadline string 否 截止时间(空为不设置,时间格式为2017-08-04 21:00或2017-08-04 21:00:00) 2017-08-10 10:00
time_lock boolean 否 修改时间规则,null :开始时间截止时间都修改,true:只修改开始时间,false只修改截止时间
update_type string 否 妥协类型(单个)*/
String url = "https://api.mingdao.com/v2/task/update_task_start_time_and_deadline";
String result = HttpClientUtils.postParameters(url,"access_token="+access_token+"&task_id="+task_id+"&start_time="+start_time+"&deadline="+deadline);
System.out.println("修改时间状态返回结果:"+result);
return result;
}
public static String getAllUser(String access_token,int pageindex,int pagesize) throws Exception{
String url = "https://api.mingdao.com/v1/user/get_project_users?access_token="+access_token+"&project_id=CE8888&pageindex="+pageindex+"&pagesize="+pagesize+"×tamp=1531476154";
String result = HttpClientUtils.get(url);
System.out.println("返回结果:"+result);
return result;
}
}
<file_sep>package com.synco.cc;
public class ShortDemo {
}
<file_sep>package com.synco.oa.pojo;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
public class Task_time {
//id
private Integer id;
//任务id
private String task_id;
//操作时间
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date task_datetime;
//操作获得的积分
private Integer task_integral;
//操作人
private String account_id;
private String task_name;
private String state;
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getTask_name() {
return task_name;
}
public void setTask_name(String task_name) {
this.task_name = task_name;
}
public Date getTask_datetime() {
return task_datetime;
}
public void setTask_datetime(Date task_datetime) {
this.task_datetime = task_datetime;
}
public String getAccount_id() {
return account_id;
}
public void setAccount_id(String account_id) {
this.account_id = account_id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTask_id() {
return task_id;
}
public void setTask_id(String task_id) {
this.task_id = task_id;
}
public Integer getTask_integral() {
return task_integral;
}
public void setTask_integral(Integer task_integral) {
this.task_integral = task_integral;
}
}
|
a16d5c69af94f6152e43b7e3262cb49c4002ec32
|
[
"JavaScript",
"Java"
] | 10
|
JavaScript
|
liu0916/syncoOA_ee
|
512ca2d51e20169fdd6fecfc82f22188f2b7664f
|
6270576eed99384ea465b11f2ffbbf8ea6106bcf
|
refs/heads/master
|
<file_sep>import React, { PropTypes } from 'react';
import AppBar from 'material-ui/AppBar';
import Counter from './Counter';
import { connect } from 'react-redux';
import { CounterManipulationToggle } from './action';
class App extends React.Component{
constructor(props){
super(props);
this.consoleHandler = this.consoleHandler.bind(this);
}
toggleCounter(){
this.props.onToggleCounter();
}
consoleHandler(e){
console.log(e);
}
render(){
return(
<div className="appBar">
<AppBar onLeftIconButtonTouchTap={this.toggleCounter.bind(this)}
title="Hello Redux"
iconClassNameRight="muidocs-icon-navigation-expand-more"
/>
< Counter consoleHandler={this.consoleHandler} />
</div>
)
}
}
const mapDispatchToProps = (dispatch) => {
return {
onToggleCounter: () => {dispatch(CounterManipulationToggle("Toggle"))}
}
}
const mapStateToProps = (state) => {
return state;
}
const CombineApp = connect(
mapStateToProps,
mapDispatchToProps
)(App);
export default CombineApp;<file_sep>export const CounterManipulationAdd = () => {
return {
type: "Add"
}
}
export function CounterManipulationDel(){
return {
type: "Del"
}
}
export const CounterManipulationToggle = () => {
return {
type: "Toggle"
}
}<file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import counterApp from './reducers';
import injectTapEventPlugin from 'react-tap-event-plugin';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
injectTapEventPlugin();
var store = createStore(counterApp);
ReactDOM.render(
<Provider store={store}>
<MuiThemeProvider>
<App />
</MuiThemeProvider>
</Provider>,
document.getElementById('app')
);
<file_sep>import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { createStore } from 'redux';
import { CounterManipulationAdd } from './action';
import { CounterManipulationDel } from './action';
import {RaisedButton} from 'material-ui';
import styles from './styles';
class Counter extends React.Component {
constructor(props){
super(props);
}
addClick(){
this.props.onAddClick();
}
deleteClick(){
this.props.onDelClick();
}
consoleTest(){
this.props.consoleHandler('123');
}
render(){
var visible = this.props.counterVisible ? "show" : "hide";
return(
<div className={`main ${visible}`}>
<h2 style={styles.h2}>Counter: {this.props.counter}</h2>
<RaisedButton onClick={this.addClick.bind(this)} primary={true} label="Add 1" />
<RaisedButton onClick={this.deleteClick.bind(this)} secondary={true} label="Delete 1" />
<RaisedButton onClick={this.consoleTest.bind(this)} default={true} label="Console 1" />
</div>
)
}
}
const mapDispatchToProps = (dispatch) => {
return {
onAddClick: () => {
dispatch(CounterManipulationAdd("Add"))
},
onDelClick: () => dispatch(CounterManipulationDel("Del"))
}
}
const mapStateToProps = (state) => {
return state;
}
const CombineCounterActions = connect(
mapStateToProps,
mapDispatchToProps
)(Counter);
export default CombineCounterActions;
// value={store.getState()} onIncrement={() => store.dispatch({ type: 'Add' })} onDecrement={() => store.dispatch({ type: 'Del' })}
<file_sep>import { cyan500, cyan700, darkBlack, fullBlack } from 'material-ui/styles/colors';
import {fade} from 'material-ui/utils/colorManipulator';
const styles = {
fontFamily: 'Roboto, sans-serif',
palette: {
primary1Color: cyan500,
primary2Color: cyan700,
disabledColor: fade(darkBlack, 0.3),
pickerHeaderColor: cyan500,
clockCircleColor: fade(darkBlack, 0.07),
shadowColor: fullBlack,
},
h2: {
color: darkBlack
}
};
export default styles;<file_sep>const initialState = {
counter: 0,
counterVisible : false
}
function counterApp(state, action){
if(typeof state === "undefined"){
return initialState;
}
switch(action.type){
case "Add" :
return Object.assign( {}, state, { counter: state.counter + 1});
break;
case "Del" :
return state.counter > 0 ? Object.assign( {}, state, { counter: state.counter - 1}) : Object.assign( {}, state, { counter: state.counter});
break;
case "Toggle":
return Object.assign( {}, state, { counterVisible: !state.counterVisible});
break;
default:
return state;
}
}
export default counterApp;
|
e37cf86db1eb3089b8680a4e76abadb86e24535b
|
[
"JavaScript"
] | 6
|
JavaScript
|
NikitaCoder/React-education
|
500d5b7f14a3ecdb5f19e55f2460c62316d23250
|
8c4b285ce4acbcd207a69f8fb9e2961a94b73b05
|
refs/heads/master
|
<repo_name>Windrist/UET-CAM-Demo<file_sep>/checkAlign.py
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 23 15:02:43 2021
@author: Administrator
"""
import numpy as np
import cv2
import os
import sys
import matplotlib.pyplot as plt
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
#1
def find_location_crop(event, x, y, flags, param):
f = open(resource_path('data/config/location_crop.txt'), 'a')
if event == cv2.EVENT_LBUTTONDOWN:
f.write(str(x) + "\n")
f.write(str(y) + "\n")
f.close()
#2
def crop_image(image):
a = []
f = open(resource_path('data/config/location_crop.txt'), 'r+')
for i in range(4):
x1 = int(f.readline())
y1 = int(f.readline())
x2 = int(f.readline())
y2 = int(f.readline())
crop = image[y1:y2, x1:x2, :]
# cv2.imwrite(resource_path('data/img_check_crop/{}.jpg'.format(i)), crop)
a.append(crop)
f.close()
return a
#3
def calc_mean(image):
return np.mean(image, axis=(0, 1))
def calc_mean_all(image_list):
a = []
for i in range(4):
# img = cv2.imread(resource_path('data/img_check_crop/{}.jpg'.format(i)))
img = image_list[i]
img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
a.append(calc_mean(img))
return a
def check(mean):
mean_check = [245, 245, 235, 235]
for i in range(4):
if mean[i] < mean_check[i]:
return 0
return 1
# cap = cv2.VideoCapture(1)
# cap.set(3, 1280)
# cap.set(4, 720)
# while(True):
# # Capture frame-by-frame
# ret, frame = cap.read()
# cv2.imshow('frame', frame)
# key = cv2.waitKey(1) & 0xFF
# if key == ord('q'):
# break
# if key == ord('s'):
# cv2.imwrite('preview.jpg', frame)
# cap.release()
# cv2.destroyAllWindows()
# image = cv2.imread("preview.jpg")
# cv2.namedWindow("image")
# cv2.setMouseCallback("image", find_location_crop)
# while True:
# cv2.imshow("image", image)
# if cv2.waitKey(1) & 0xFF == ord("q"):
# break
# cv2.destroyAllWindows()
# crop_list = crop_image(image)
# mean = calc_mean_all(crop_list)
# print(mean)
# print(check(mean))
<file_sep>/main.py
#!/usr/bin/env python3
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import QSizePolicy
import cv2
import numpy as np
import sys
import time
import os
import math
import checkAlign
from connectPLC import PLC
from detectYesNo import Detect
from checkOnJig import CheckOn
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
class Thread(QThread):
progress = pyqtSignal()
def run(self):
while True:
self.progress.emit()
time.sleep(0.1)
class Query(QThread):
progress = pyqtSignal()
def run(self):
while True:
self.progress.emit()
time.sleep(0.5)
class Camera(QThread):
setup = pyqtSignal()
def run(self):
self.setup.emit()
class App(QMainWindow):
def __init__(self):
super().__init__()
# QT Config
self.title = "UET-CAM"
self.icon = QIcon(resource_path('data/icon/uet.png'))
# Declare Main Variable
self.total = 0
self.number_tested = 0
self.number_success = 0
self.number_error1 = 0
self.number_error2 = 0
self.number_error3 = 0
self.count = 0
self.cap_detect = any
self.cap_check = any
self.get_cap_detect = False
self.get_cap_check = False
self.Controller = PLC()
self.command = ""
# Run QT
self.initUI()
def initUI(self):
# Config Main Window
self.setWindowTitle(self.title)
self.setWindowIcon(self.icon)
self.setWindowState(Qt.WindowFullScreen)
self.setStyleSheet("background-color: rgb(171, 171, 171);")
# Config Auto Fit Screen Scale Variables
self.sg = QDesktopWidget().screenGeometry()
self.width_rate = self.sg.width() / 1920
self.height_rate = self.sg.height() / 1080
self.font_rate = math.sqrt(self.sg.width()*self.sg.width() + self.sg.height()*self.sg.height()) / math.sqrt(1920*1920 + 1080*1080)
# Show UET LOGO
self.uet_logo = QLabel(self)
self.uet_pixmap = QPixmap(resource_path('data/icon/uet.png')).scaled(111 * self.width_rate, 111 * self.width_rate, Qt.KeepAspectRatio)
self.uet_logo.setPixmap(self.uet_pixmap)
self.uet_logo.setGeometry(100 * self.width_rate, 10 * self.height_rate, 111 * self.width_rate, 111 * self.height_rate)
# Show Title
self.title_label = QLabel("<NAME>ỂM TRA LINH KIỆN (CAM-UET-MEMS)", self)
self.title_label.setGeometry(341 * self.width_rate, 17 * self.height_rate, 1300 * self.width_rate, 95 * self.height_rate)
font_title = QFont('', int(35 * self.font_rate), QFont.Bold)
self.title_label.setFont(font_title)
self.title_label.setStyleSheet("color: rgb(255, 255, 255);")
# Show Current Time
self.time_label = QLabel(self)
self.time_label.setAlignment(Qt.AlignCenter)
self.time_label.setGeometry(1500 * self.width_rate, 20 * self.height_rate, 430 * self.width_rate, 95 * self.height_rate)
font_timer = QFont('', int(40 * self.font_rate), QFont.Bold)
self.time_label.setFont(font_timer)
timer = QTimer(self)
timer.timeout.connect(self.updateTimer)
timer.start(1000)
self.time_label.setStyleSheet("color: rgb(255, 255, 255);")
# Show Detect Camera
self.cam1_name = QLabel("DETECT CAMERA", self)
self.cam1_name.setGeometry(55 * self.width_rate, 127 * self.height_rate, 728 * self.width_rate, 60 * self.height_rate)
self.cam1_name.setAlignment(Qt.AlignCenter)
self.cam1_name.setStyleSheet("background-color: rgb(50, 130, 184);"
"color: rgb(255, 255, 255);"
"font: bold 14pt;")
self.cam1 = QLabel(self)
self.cam1.setGeometry(55 * self.width_rate, 185 * self.height_rate, 728 * self.width_rate, 410 * self.height_rate)
self.cam1.setStyleSheet("border-color: rgb(50, 130, 184);"
"border-width: 5px;"
"border-style: inset;")
# Show Check Camera
self.cam2_name = QLabel("CHECK CAMERA", self)
self.cam2_name.setGeometry(55 * self.width_rate, 606 * self.height_rate, 728 * self.width_rate, 60 * self.height_rate)
self.cam2_name.setAlignment(Qt.AlignCenter)
self.cam2_name.setStyleSheet("background-color: rgb(50, 130, 184);"
"color: rgb(255, 255, 255);"
"font: bold 14pt;")
self.cam2 = QLabel(self)
self.cam2.setGeometry(55 * self.width_rate, 666 * self.height_rate, 728 * self.width_rate, 410 * self.height_rate)
self.cam2.setStyleSheet("border-color: rgb(50, 130, 184);"
"border-width: 5px;"
"border-style: inset;")
# Set Font
self.font = QFont('', int(14 * self.font_rate), QFont.Bold)
# Trays Information
self.tray = []
for i in range(2):
tray_name = QLabel("TRAY {}".format(i+1), self)
tray_name.setGeometry((980 + 400*i - 5) * self.width_rate, 127 * self.height_rate, 372 * self.width_rate, 60 * self.height_rate)
tray_name.setAlignment(Qt.AlignCenter)
tray_name.setStyleSheet("background-color:rgb(50, 130, 184);"
"color: rgb(255, 255, 255);"
"font: bold 14pt;")
table_margin = QLabel(self)
table_margin.setGeometry((980 + 400*i - 5) * self.width_rate, 181 * self.height_rate, 372 * self.width_rate, 417 * self.height_rate)
table_margin.setStyleSheet("border-color: rgb(50, 130, 184);"
"border-width: 5px;"
"border-style: inset;")
table = QTableWidget(7, 3, self)
table.setGeometry((980 + 400*i) * self.width_rate, 186 * self.height_rate, int(362 * self.width_rate) + 1, int(408 * self.height_rate) + 0.5)
table.horizontalHeader().hide()
table.verticalHeader().hide()
for j in range(3):
table.setColumnWidth(j, 120 * self.width_rate)
for j in range(7):
table.setRowHeight(j, 58 * self.height_rate)
table.setFont(self.font)
table.setStyleSheet("color: rgb(255, 255, 255);")
self.tray.append(table)
# Table Info Area
self.s_name = QLabel("INFORMATION", self)
self.s_name.setGeometry(830 * self.width_rate, 606 * self.height_rate, 734 * self.width_rate, 60 * self.height_rate)
self.s_name.setAlignment(Qt.AlignCenter)
self.s_name.setStyleSheet("background-color:rgb(50, 130, 184);"
"color: rgb(255, 255, 255);"
"font: bold 14pt;")
self.statistic_table = QTableWidget(5, 3, self)
self.statistic_table.setGeometry(830 * self.width_rate, 666 * self.height_rate, int(734 * self.width_rate) + 1, int(410 * self.height_rate) + 1)
self.statistic_table.horizontalHeader().hide()
self.statistic_table.verticalHeader().hide()
self.statistic_table.setFont(self.font)
self.statistic_table.setStyleSheet("color: rgb(255, 255, 255);"
"text-align: center;"
"border-width: 5px;"
"border-style: inset;"
"border-color: rgb(50, 130, 184);")
for j in range(3):
self.statistic_table.setColumnWidth(j, 241 * self.width_rate)
for j in range(5):
self.statistic_table.setRowHeight(j, 80 * self.height_rate)
tested_item = QTableWidgetItem("TESTED")
tested_item.setTextAlignment(Qt.AlignCenter)
tested_item.setFont(self.font)
self.statistic_table.setItem(0, 0, tested_item)
success_item = QTableWidgetItem("SUCCESS")
success_item.setTextAlignment(Qt.AlignCenter)
success_item.setFont(self.font)
self.statistic_table.setItem(1, 0, success_item)
error1_item = QTableWidgetItem("NEED RETEST")
error1_item.setTextAlignment(Qt.AlignCenter)
error1_item.setFont(self.font)
self.statistic_table.setItem(2, 0, error1_item)
error2_item = QTableWidgetItem("CONNECTION ERROR")
error2_item.setTextAlignment(Qt.AlignCenter)
error2_item.setFont(self.font)
self.statistic_table.setItem(3, 0, error2_item)
error3_item = QTableWidgetItem("FAILURE")
error3_item.setTextAlignment(Qt.AlignCenter)
error3_item.setFont(self.font)
self.statistic_table.setItem(4, 0, error3_item)
# Note Table
self.s_name = QLabel("REPORT", self)
self.s_name.setGeometry(1590 * self.width_rate, 606 * self.height_rate, 300 * self.width_rate, 60 * self.height_rate)
self.s_name.setAlignment(Qt.AlignCenter)
self.s_name.setStyleSheet("background-color:rgb(50, 130, 184);"
"color: rgb(255, 255, 255);"
"font: bold 14pt;")
self.textBox = QPlainTextEdit(self)
self.textBox.setGeometry(1590 * self.width_rate, 666 * self.height_rate, 300 * self.width_rate, 410 * self.height_rate)
self.textBox.setFont(QFont('', int(14 / self.font_rate), QFont.Bold))
# Exit Button
self.exit_button = QPushButton(self)
self.exit_pixmap = QPixmap(resource_path('data/icon/close.jpg')).scaled(100 * self.width_rate, 100 * self.width_rate, Qt.KeepAspectRatio)
self.exit_icon = QIcon(self.exit_pixmap)
self.exit_button.setIcon(self.exit_icon)
self.exit_button.setIconSize(QSize(50, 50))
self.exit_button.setGeometry(1878 * self.width_rate, -8 * self.height_rate, 50 * self.width_rate, 50 * self.height_rate)
self.exit_button.setHidden(0)
self.exit_button.setStyleSheet("border: none")
self.exit_button.clicked.connect(self.close)
# Create Thread
self.camera_thread = Camera()
self.camera_thread.setup.connect(self.setup_camera)
self.main_thread = Thread()
self.main_thread.progress.connect(self.main_process)
self.plc_thread = Query()
self.main_thread.progress.connect(self.get_command)
# Run Thread
self.camera_thread.start()
self.main_thread.start()
self.plc_thread.start()
# Hàm stream CAMERA DETECT lên giao diện
def update_detect_image(self, img):
rgbImage = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
h, w, ch = rgbImage.shape
bytesPerLine = ch * w
convertToQtFormat = QImage(rgbImage.data, w, h, bytesPerLine, QImage.Format_RGB888)
self.cam1.setPixmap(QPixmap.fromImage(convertToQtFormat))
# Hàm stream CAMERA CHECK lên giao diện
def update_check_image(self, img):
rgbImage = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
h, w, ch = rgbImage.shape
bytesPerLine = ch * w
convertToQtFormat = QImage(rgbImage.data, w, h, bytesPerLine, QImage.Format_RGB888)
self.cam2.setPixmap(QPixmap.fromImage(convertToQtFormat))
# Hàm cập nhật bảng số liệu
def update_statistic(self, data):
self.number_tested += 1
# Reset giá trị đếm khi kiểm tra hết linh kiện
if self.count == 42:
self.count = 0
# Bỏ qua khi không có linh kiện trong mảng dữ liệu
while self.Controller.data[self.count] != 1:
self.count += 1
# Cập nhật số liệu Kiểm tra
tested = QTableWidgetItem("{}".format(self.number_tested) + " / {}".format(self.total))
tested.setTextAlignment(Qt.AlignCenter)
self.statistic_table.setItem(0,1,tested)
ratio_tested = QTableWidgetItem("{} %".format(int(self.number_tested / self.total * 100)))
ratio_tested.setTextAlignment(Qt.AlignCenter)
self.statistic_table.setItem(0,2,ratio_tested)
# Lấy số liệu linh kiện
tray_idx = self.count // 21
row = 6 - self.count % 21 % 7
col = self.count % 21 // 7
# Thông báo đẩy
if data == "1":
self.number_success += 1
self.tray[tray_idx].item(row,col).setBackground(QColor(67, 138, 94))
self.textBox.appendPlainText("Linh Kiện Tray {}".format(tray_idx+1) + " Hàng {}".format(row+1) + " Cột {}".format(col+1) + " Hoạt Động Tốt!\n")
elif data == "0":
self.number_error3 += 1
self.tray[tray_idx].item(row,col).setBackground(QColor(232, 80, 91))
self.textBox.appendPlainText("Linh Kiện Tray {}".format(tray_idx+1) + " Hàng {}".format(row+1) + " Cột {}".format(col+1) + " Bị Hỏng!\n")
elif data == "-1":
self.number_error1 += 1
self.tray[tray_idx].item(row,col).setBackground(QColor(255, 255, 51))
self.textBox.appendPlainText("Linh Kiện Tray {}".format(tray_idx+1) + " Hàng {}".format(row+1) + " Cột {}".format(col+1) + " Gặp Lỗi Vị Trí Trên Jig. Đề Nghị Kiểm Tra!\n")
elif data == "404":
self.number_error2 += 1
self.tray[tray_idx].item(row,col).setBackground(QColor(255, 128, 0))
self.textBox.appendPlainText("Linh Kiện Tray {}".format(tray_idx+1) + " Hàng {}".format(row+1) + " Cột {}".format(col+1) + " Gặp Lỗi Kết Nối Với Bộ Test. Đề Nghị Kiểm Tra!\n")
# Cập nhật số liệu
success = QTableWidgetItem("{}".format(self.number_success) + " / {}".format(self.number_tested))
success.setTextAlignment(Qt.AlignCenter)
self.statistic_table.setItem(1,1,success)
ratio_success = QTableWidgetItem("{} %".format(int(self.number_success / self.number_tested * 100)))
ratio_success.setTextAlignment(Qt.AlignCenter)
self.statistic_table.setItem(1,2,ratio_success)
error1 = QTableWidgetItem("{}".format(self.number_error1) + " / {}".format(self.number_tested))
error1.setTextAlignment(Qt.AlignCenter)
self.statistic_table.setItem(2,1,error1)
ratio_error1 = QTableWidgetItem("{} %".format(int(self.number_error1 / self.number_tested * 100)))
ratio_error1.setTextAlignment(Qt.AlignCenter)
self.statistic_table.setItem(2,2,ratio_error1)
error2 = QTableWidgetItem("{}".format(self.number_error2) + " / {}".format(self.number_tested))
error2.setTextAlignment(Qt.AlignCenter)
self.statistic_table.setItem(3,1,error2)
ratio_error2 = QTableWidgetItem("{} %".format(int(self.number_error2 / self.number_tested * 100)))
ratio_error2.setTextAlignment(Qt.AlignCenter)
self.statistic_table.setItem(3,2,ratio_error2)
error3 = QTableWidgetItem("{}".format(self.number_error3) + " / {}".format(self.number_tested))
error3.setTextAlignment(Qt.AlignCenter)
self.statistic_table.setItem(4,1,error3)
ratio_error3 = QTableWidgetItem("{} %".format(int(self.number_error3 / self.number_tested * 100)))
ratio_error3.setTextAlignment(Qt.AlignCenter)
self.statistic_table.setItem(4,2,ratio_error3)
# Linh kiện kiểm tra xong sẽ xóa khỏi mảng dữ liệu
self.Controller.data[self.count] = 0
self.count += 1
# Hàm Khởi tạo giá trị cho Bảng số liệu
def init_statistic(self):
tested = QTableWidgetItem("{}".format(0) + " / {}".format(self.total))
tested.setTextAlignment(Qt.AlignCenter)
self.statistic_table.setItem(0,1,tested)
ratio_tested = QTableWidgetItem("{} %".format(0))
ratio_tested.setTextAlignment(Qt.AlignCenter)
self.statistic_table.setItem(0,2,ratio_tested)
success = QTableWidgetItem("{}".format(0) + " / {}".format(0))
success.setTextAlignment(Qt.AlignCenter)
self.statistic_table.setItem(1,1,success)
ratio_success = QTableWidgetItem("{} %".format(0))
ratio_success.setTextAlignment(Qt.AlignCenter)
self.statistic_table.setItem(1,2,ratio_success)
error1 = QTableWidgetItem("{}".format(0) + " / {}".format(0))
error1.setTextAlignment(Qt.AlignCenter)
self.statistic_table.setItem(2,1,error1)
ratio_error1 = QTableWidgetItem("{} %".format(0))
ratio_error1.setTextAlignment(Qt.AlignCenter)
self.statistic_table.setItem(2,2,ratio_error1)
error2 = QTableWidgetItem("{}".format(0) + " / {}".format(0))
error2.setTextAlignment(Qt.AlignCenter)
self.statistic_table.setItem(3,1,error2)
ratio_error2 = QTableWidgetItem("{} %".format(0))
ratio_error2.setTextAlignment(Qt.AlignCenter)
self.statistic_table.setItem(3,2,ratio_error2)
error3 = QTableWidgetItem("{}".format(0) + " / {}".format(0))
error3.setTextAlignment(Qt.AlignCenter)
self.statistic_table.setItem(4,1,error3)
ratio_error3 = QTableWidgetItem("{} %".format(0))
ratio_error3.setTextAlignment(Qt.AlignCenter)
self.statistic_table.setItem(4,2,ratio_error3)
def update_data(self, data):
# Update Data to Table
c = 0
for k in range(2):
for j in range(3):
for i in range(6,-1,-1):
self.tray[k].setItem(i,j,QTableWidgetItem())
if(int(data[c])):
self.tray[k].item(i,j).setBackground(QColor(102, 102, 255))
self.total += 1
c += 1
# Send Data to PLC -> Send Command to PLC -> Grip
self.Controller.data = data
self.Controller.sendData()
self.Controller.command = "Grip"
self.Controller.sendCommand()
# Hàm cập nhật giờ
def updateTimer(self):
cr_time = QTime.currentTime()
time = cr_time.toString('hh:mm AP')
self.time_label.setText(time)
def main_process(self):
if self.command == "Idle":
# Kiểm tra xem đã nhận Camera Check chưa
if self.get_cap_detect == True:
# Reset Main Variables
self.total = 0
self.number_tested = 0
self.number_success = 0
self.number_error1 = 0
self.number_error2 = 0
self.number_error3 = 0
self.count = 0
# Hiện Video khi chờ
self.cap_detect.set(3, 1920)
self.cap_detect.set(4, 1080)
ret, image = self.cap_detect.read()
image = cv2.resize(image, (int(717 * self.width_rate), int(450 * self.height_rate)), interpolation = cv2.INTER_AREA) # Resize cho Giao diện
self.update_detect_image(image)
elif self.command == "Detect":
# Kiểm tra xem đã nhận Camera Check chưa
if self.get_cap_detect == True:
# Lấy dữ liệu từ camera
self.cap_detect.set(3, 1920)
self.cap_detect.set(4, 1080)
ret, image = self.cap_detect.read()
resize_img = cv2.resize(image, (int(717 * self.width_rate), int(450 * self.height_rate)), interpolation = cv2.INTER_AREA) # Resize cho Giao diện
detect = Detect()
# Xử lý Ảnh
detect.image = image
detect.thresh()
# Detect YES/NO
result = detect.check(detect.crop_tray_1)
result = np.append(result, detect.check(detect.crop_tray_2))
self.update_detect_image(resize_img) # Đưa ảnh lên giao diện
# Gửi kết quả Detect YES/NO cho PLC và Table
self.update_data(result)
self.init_statistic()
self.command = "Wait"
elif self.command == "Check":
# Kiểm tra xem đã nhận Camera Check chưa
if self.get_cap_check == True:
self.cap_check.set(3, 1920)
self.cap_check.set(4, 1080)
ret, image = self.cap_check.read() # Lấy dữ liệu từ camera
resize_img = cv2.resize(image, (int(717 * self.width_rate), int(450 * self.height_rate)), interpolation = cv2.INTER_AREA) # Resize cho Giao diện
# Kiểm tra Jig
CheckOn = CheckOn()
CheckOn.image = image[150:280, 245:445]
# Nếu không có linh kiện trên Jig
if CheckOn.check(CheckOn.calc_mean()) == 0:
self.command = "SOS"
# Nếu có linh kiện trên Jig
else:
# Kiểm tra lệch
image = cv2.resize(image, (800, 800))
checkAlign.crop_image(image)
mean = checkAlign.calc_mean_all()
check = checkAlign.check(mean)
self.update_check_image(resize_img) # Đưa video lên giao diện
# Kết quả trả về linh kiện không lệch
if check:
# Đổi State -> Gửi State mới cho PLC
self.Controller.command = "Grip-1"
self.Controller.sendCommand()
# Kết quả trả về linh kiện lệch
else:
# Đổi State -> Gửi State mới cho PLC
self.Controller.command = "Grip-0"
self.Controller.sendCommand()
# Đổi State: Chờ lệnh
self.command = "Wait"
# Nhận kết quả từ PLC -> Cập nhật bảng số liệu -> Gửi lệnh cho PLC tiếp tục gắp linh kiện mới -> Chờ tay gắp
elif self.command == "1":
self.update_statistic(self.command)
self.Controller.command = "Grip"
self.Controller.sendCommand()
self.command = "Wait"
elif self.command == "0":
self.update_statistic(self.command)
self.Controller.command = "Grip"
self.Controller.sendCommand()
self.command = "Wait"
elif self.command == "-1":
self.update_statistic(self.command)
self.Controller.command = "Grip"
self.Controller.sendCommand()
self.command = "Wait"
elif self.command == "404":
self.update_statistic(self.command)
self.Controller.command = "Grip"
self.Controller.sendCommand()
self.command = "Wait"
# Kết thúc -> Xuất ra thông báo
elif self.command == "Report":
if self.report_one_time:
self.report_one_time = False
QMessageBox.about(self, "Kiểm Tra Hoàn Tất", "Đã Kiểm Tra " + str(self.total) + " linh kiện!\n" + "Còn " + str(self.number_error1) + " linh kiện cần kiểm tra lại!")
self.command = ""
# Init Camera
def setup_camera(self):
self.cap_detect = cv2.VideoCapture(0) # Khai báo USB Camera Detect Config
self.get_cap_detect = True
self.cap_check = cv2.VideoCapture(0) # Khai báo USB Camera Check Config
self.get_cap_check = True
# Loop Get Command from PLC
def get_command(self):
self.command = self.Controller.queryCommand()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
ex.show()
sys.exit(app.exec_())<file_sep>/checkOnJig.py
import cv2
import numpy as np
from matplotlib import pyplot as plt
import os
import sys
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
class CheckOn(object):
def __init__(self) -> None:
super().__init__()
self.image = []
def find_location_crop(self, event, x, y, flags, param):
f = open(resource_path('data/config/location_crop_oj.txt'), 'a')
if event == cv2.EVENT_LBUTTONDOWN:
f.write(str(x) + "\n")
f.write(str(y) + "\n")
f.close()
def crop_image(self):
a = []
f = open(resource_path('data/config/location_crop_oj.txt'), 'r+')
for i in range(3):
x1 = int(f.readline())
y1 = int(f.readline())
x2 = int(f.readline())
y2 = int(f.readline())
crop = self.image[y1:y2, x1:x2, :]
a.append(crop)
f.close()
return a
def check(self, crop):
for i in range(3):
gray = cv2.cvtColor(crop[i], cv2.COLOR_BGR2GRAY)
histr = cv2.calcHist([gray], [0], None, [256], [0, 256])
# plt.subplot(121)
# plt.imshow(gray)
# plt.subplot(122)
# plt.plot(histr)
# plt.show()
for j in range(256):
if max(histr) == histr[j]:
if j >= 250:
return 1
return 0
# if __name__ == "__main__":
# Test = CheckOn()
# cap = cv2.VideoCapture(1)
# cap.set(3, 1280)
# cap.set(4, 720)
# while(True):
# # Capture frame-by-frame
# ret, frame = cap.read()
# # Display the resulting frame
# cv2.imshow('frame', frame)
# key = cv2.waitKey(1) & 0xFF
# if key == ord('q'):
# break
# if key == ord('s'):
# cv2.imwrite('preview.jpg', frame)
# cap.release()
# cv2.destroyAllWindows()
# image = cv2.imread(resource_path('preview.jpg'))
# Test.image = image
# cv2.namedWindow("image")
# cv2.setMouseCallback("image", Test.find_location_crop)
# while True:
# cv2.imshow("image", image)
# if cv2.waitKey(1) & 0xFF == ord("q"):
# break
# cv2.destroyAllWindows()
# crop_list = Test.crop_image()
# print(Test.check(crop_list))
<file_sep>/connectPLC.py
from PyQt5.QtCore import QFileSelector
import snap7
import numpy as np
class PLC(object):
def __init__(self):
# Init Variables
self.IP = '192.168.128.2' # IP của PLC
self.slot = 1 # Lấy trong TIA Portal
self.rack = 0 # Lấy trong TIA Portal
self.DBNumber = 1 # Data Block cần nhận dữ liệu (DB1, DB2,...)
self.dataStart = 1 # Vị trí bit con trỏ nhận dữ liệu
self.dataSize = 254 # Độ dài của data (1 byte, 4 bytes, 8 bytes,...)
self.data = np.zeros(42) # Biến truyền data cho PLC
# Test Connection with PLC
def testConnection(self):
plc = snap7.client.Client()
try:
plc.connect(self.IP, self.rack, self.slot)
except Exception as e:
print("Connection Error!")
finally:
if plc.get_connected():
plc.disconnect()
print("Connection Success!")
# Read Data Function
def queryCommand(self):
plc = snap7.client.Client()
again = True
while again:
try:
plc.connect(self.IP, self.rack, self.slot)
data = plc.db_read(self.DBNumber, self.dataStart, self.dataSize)
again = False
return snap7.util.get_string(data, -1, 254)
except Exception as e:
print("Cannot Get Command! Error!")
finally:
if plc.get_connected():
plc.disconnect()
def querySignal(self):
plc = snap7.client.Client()
again = True
while again:
try:
plc.connect(self.IP, self.rack, self.slot)
data = plc.db_read(self.DBNumber, 804, 1)
again = False
return snap7.util.get_bool(data, 0, 1)
except Exception as e:
print("Cannot Get Signal! Error!")
finally:
if plc.get_connected():
plc.disconnect()
# Write Data Function
def sendCommand(self, command):
plc = snap7.client.Client()
again = True
while again:
try:
plc.connect(self.IP, self.rack, self.slot)
data = plc.db_read(self.DBNumber, self.dataStart, self.dataSize)
snap7.util.set_string(data, -1, command, self.dataSize)
if not data.strip():
print("Command Corrupted!")
return
plc.db_write(self.DBNumber, self.dataStart, data)
# print("Command Write Successfully!")
again = False
except Exception as e:
print("Cannot Send Command! Error!")
finally:
if plc.get_connected():
plc.disconnect()
def sendData(self):
plc = snap7.client.Client()
again = True
while again:
try:
plc.connect(self.IP, self.rack, self.slot)
for i in range(42):
data = plc.db_read(self.DBNumber, 256+int(i/8), 1)
snap7.util.set_bool(data, 0, i%8, self.data[i])
plc.db_write(self.DBNumber, 256+int(i/8), data)
# print("Data Write Successfully!")
again = False
except Exception as e:
print("Cannot Send Data! Error!")
finally:
if plc.get_connected():
plc.disconnect()
def sendTotal(self, total):
plc = snap7.client.Client()
again = True
while again:
try:
plc.connect(self.IP, self.rack, self.slot)
data = plc.db_read(self.DBNumber, 806, 1)
snap7.util.set_int(data, 0, total)
plc.db_write(self.DBNumber, 806, data)
# print("Count Write Successfully!")
again = False
except Exception as e:
print("Cannot Send Total! Error!")
finally:
if plc.get_connected():
plc.disconnect()
def sendSignal(self, coord, signal):
plc = snap7.client.Client()
again = True
while again:
try:
plc.connect(self.IP, self.rack, self.slot)
data = plc.db_read(self.DBNumber, 804, 1)
snap7.util.set_bool(data, 0, coord, signal)
plc.db_write(self.DBNumber, 804, data)
# print("Count Write Successfully!")
again = False
except Exception as e:
print("Cannot Send Signal! Error!")
finally:
if plc.get_connected():
plc.disconnect()
if __name__ == "__main__":
Controller = PLC()
Controller.sendData()<file_sep>/captureImage.py
import time
import cv2
if __name__ == "__main__":
# Camera configuration
cap = cv2.VideoCapture(0)
count = 0
cap.set(3, 1280)
cap.set(4, 720)
while True:
ret, image = cap.read()
cv2.imshow("Capture", image)
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
elif key == ord('s'):
cv2.imwrite('data/demo/{}.jpg'.format(count), image)
count+=1
cap.release()
cv2.destroyAllWindows()<file_sep>/detectYesNo.py
import cv2
import numpy as np
from matplotlib import pyplot as plt
import os
import sys
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
class Detect(object):
def __init__(self) -> None:
super().__init__()
self.image = []
self.crop_tray_1 = []
self.crop_tray_2 = []
f = open(resource_path('data/config/location_crop_yn.txt'))
self.t1_x_begin = int(f.readline())
self.t1_y_begin = int(f.readline())
self.t1_x_end = int(f.readline())
self.t1_y_end = int(f.readline())
self.t2_x_begin = int(f.readline())
self.t2_y_begin = int(f.readline())
self.t2_x_end = int(f.readline())
self.t2_y_end = int(f.readline())
def find_location_crop(self, event, x, y, flags, param):
f = open(resource_path('data/config/location_crop_yn.txt'), 'w')
if event == cv2.EVENT_LBUTTONDOWN:
f.write(str(x) + "\n")
f.write(str(y) + "\n")
def get_coord(self):
cv2.namedWindow("image")
cv2.setMouseCallback("image", self.find_location_crop)
while True:
cv2.imshow("image", self.image)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cv2.destroyAllWindows()
def thresh(self):
crop_tray_1 = self.image[self.t1_y_begin:self.t1_y_end, self.t1_x_begin:self.t1_x_end]
crop_tray_2 = self.image[self.t2_y_begin:self.t2_y_end, self.t2_x_begin:self.t2_x_end]
gray_tray_1 = cv2.cvtColor(crop_tray_1, cv2.COLOR_BGR2GRAY)
gray_tray_2 = cv2.cvtColor(crop_tray_2, cv2.COLOR_BGR2GRAY)
ret_tray_1, self.crop_tray_1 = cv2.threshold(gray_tray_1, 0, 255, cv2.THRESH_OTSU)
ret_tray_2, self.crop_tray_2 = cv2.threshold(gray_tray_2, 0, 255, cv2.THRESH_OTSU)
def check(self, crop_img):
height = crop_img.shape[0]
width = crop_img.shape[1]
mask = np.zeros(21)
for i in range(21):
k = int(i / 7)
j = i % 7
cut = crop_img[int(height / 7 * (7 - j - 1)):int(height / 7 * (7 - j)), int(width / 3 * k):int(width / 3 *
(k + 1))]
histr = cv2.calcHist([cut], [0], None, [256], [0, 256])
# plt.subplot(121)
# plt.imshow(cut)
# plt.subplot(122)
# plt.plot(histr)
# plt.show()
if histr[255] >= 3000:
mask[i] = 1
return mask
if __name__ == "__main__":
detect = Detect()
detect.image = cv2.imread('data/demo/Detect/origin.jpg')
detect.image = cv2.resize(detect.image, (1920, 1080), interpolation=cv2.INTER_AREA)
# detect.get_coord()
detect.thresh()
mask = detect.check(detect.crop_tray_1)
mask = np.append(mask, detect.check(detect.crop_tray_2))
cv2.imshow("image", detect.crop_tray_1)
cv2.waitKey(0)
print(mask.shape)
|
00bd8e4942347a662deec5cd56da078ca414cd55
|
[
"Python"
] | 6
|
Python
|
Windrist/UET-CAM-Demo
|
f207c275f46757d9740b69a67d04bd2ad6e15aaf
|
8a3eb47695273b829e3f210eb7fc57812122cee1
|
refs/heads/master
|
<file_sep>#!/bin/bash
filename=residue.dat
echo ${filename}_backup
<file_sep>#!/bin/bash
if grep -q 'bash' /etc/passwd; then
echo 'bash found'
fi
<file_sep>#!/bin/bash
# 日記データの保存ディレクトリ
directory="${HOME}/diary"
# 保存ディレクトリがなければ作成
if [ ! -d "$directory" ]; then
mkdir "$directory"
fi
# 日記ファイルパス
diaryfile="${directory}/$(date '+%Y-%m-%d').txt"
# 今日の日記新規作成時、先頭に日付を挿入
if [ ! -e "$diaryfile" ]; then
date '+%Y/%m/%d' > "$diaryfile"
fi
vim "$diaryfile"
<file_sep>#!/bin/bash
list_recursive()
{
# 現在参照中のファイルパス
local filepath=$1
# インデント
local indent=$2
# ファイルでもディレクトリでもその名前を表示
# ※パス名は'##*/'で消す
echo "${indent}${filepath##*/}"
if [ -d "$filepath" ]; then
# ディレクトリなら、その中のファイルや
# ディレクトリを一覧表示
# ディレクトリの場合
if [ -d "$filepath" ]; then
local fname
for fname in $(ls "$filepath")
do
# ディレクトリ内ファイルを表示
# echo "${filepath}/${fname}"
list_recursive "${filepath}/${fname}" $'\t'"$indent"
done
fi
fi
}
# メイン処理
# IFSを待避
_IFS=$IFS
IFS=$'\n'
list_recursive "$1" ""
IFS=$_IFS
<file_sep>#!/bin/bash
echo \
"root directory"
ls -l / #LS詳細表示
<file_sep>#!/bin/bash
filename=$1
if [ -z "$filename" ]; then
filename = "default.dat"
fi
<file_sep>#!/bin/bash
echo "\$0=$0"
echo "\$1=$1"
echo "\$2=$2"
echo "\$3=$3"
echo "\$4=$4"
echo "\$5=$5"
echo "\$#=$#"
<file_sep>#!/bin/bash
print_params()
{
echo "\$1 = $1"
echo "\$2 = $2"
echo "\$3 = $3"
echo "\$4 = $4"
echo
echo "$# arguments"
echo "script name = $0"
}
print_params aaa bbb ccc
<file_sep>#!/bin/bash
file=$1
if [ -d "$file" ]; then
echo "$file is a directory:"
ls -l "$file"
elif [ -f "$file" ]; then
echo "$file is a regular file:"
head -n 5 "$file"
fi
<file_sep>#!/bin/bash
$datadir=/home
if [ ! -d "$datadir" ]; then
echo "$datadir がありません"
else
echo "$datadir はあります"
fi
<file_sep>#!/bin/bash
if [ ! -d "for-touch" ]; then
mkdir "for-touch"
fi
for i in $(seq 1 5)
do
touch "for-touch/000${i}.txt"
done
<file_sep>#!/bin/bash
country=Japan
echo 'I came from $country'
echo "I came from $country"
<file_sep># LinuxShellPractice
「新しいLinux教科書」の学習で作ったshellコマンド
<file_sep>#!/bin/bash
appdir=/home/hagirainbow/myapp
echo $appdir
<file_sep>#!/bin/bash
usage()
{
# シェルスクリプトのファイル名を取得
local script_name=$(basename "$0")
# ピアドキュメントでヘルプを表示
cat << END
Usage: $script_name PATTERN [PATH] [NAME_PATTERN]
find file in current directory, and print lines which match PATTERN.
PATH find file in PATH directory, instead of current directory.
NAME_PATTERN specify name pattern to find file
Examples:
$script_name return
$script_name return ~ '*.txt'
END
# ↑ENDの前後にTAB,空白などは入れないこと
}
# コマンドライン引数が0個の場合
if [ "$#" -eq 0 ]; then
usage
# 終了ステータス1で終了
exit 1
fi
# 検索文字
pattern=$1
# 検索ディレクトリ
directory=$2
# 検索ファイルパターン
name=$3
# 検索ディレクトリが存在しないならエラー
if [ ! -d "$directory" ]; then
# エラーメッセージを標準エラー出力に出す(1>&2)
echo "$0: ${directory}: No such directory" 1>&2
exit 2
fi
# 第2引数(検索ディレクトリ)が空なら、
# デフォルト値"."(カレントディレクトリ)を設定
if [ -z "$directory" ]; then
directory='.'
fi
# 第3引数(検索ファイルパターン)が空文字列なら、
# デフォルト値として'*'(なんでも)を設定
if [ -z "$name" ]; then
name='*'
fi
find "$directory" -type f -name "$name" | xargs grep -nH "$pattern"
|
223aae6a987116673d7f2afada78530fc0d9f324
|
[
"Markdown",
"Shell"
] | 15
|
Shell
|
HagiAyato/LinuxShellPractice
|
4e4dbb72ab4bcd4896d6de1cebccf24e76eb636d
|
bd422f20c24ee2518c7bf3e02f7aa55489d4ac10
|
refs/heads/master
|
<repo_name>thomasdane/algoDataStructures<file_sep>/tests/algorithmsTests/pathFinding.test.js
import {getNeighbours, findShortestPathLength, Point, transformGrid} from "../../algorithms/graphs/pathFinding.js"
describe("findShortestPathLength", () => {
const fourByFour = [
[2, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 2]
];
it("should solve a 4x4 maze", () => {
expect(findShortestPathLength(fourByFour, [0, 0], [3, 3])).toEqual(6);
});
const sixBySix = [
[0, 0, 0, 0, 0, 0],
[0, 2, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0],
[0, 0, 2, 0, 0, 0]
];
it("should solve a 6x6 maze", () => {
expect(findShortestPathLength(sixBySix, [1, 1], [2, 5])).toEqual(7);
});
const eightByEight = [
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 1, 0, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 1, 0],
[0, 2, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 1, 2]
];
it("should solve a 8x8 maze", () => {
expect(findShortestPathLength(eightByEight, [1, 7], [7, 7])).toEqual(16);
});
const fifteenByFifteen = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],
[0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,],
[0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0,],
[0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0,],
[0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0,],
[0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0,],
[0, 0, 1, 0, 1, 0, 1, 1, 2, 1, 0, 1, 0, 1, 0,],
[0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0,],
[0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0,],
[0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0,],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0,],
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0,],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],
]
it("should solve a 15x15 maze", () => {
expect(findShortestPathLength(fifteenByFifteen, [1, 1], [8, 8])).toEqual(78);
});
});
describe("pathfinding – edge cases", function() {
const byEachOther = [
[0, 0, 0, 0, 0],
[0, 2, 2, 0, 0],
[0, 0, 0, 0, 0],
[0, 1, 1, 1, 1],
[0, 0, 0, 0, 0],
];
it("should solve the maze if they're next to each other", () => {
expect(findShortestPathLength(byEachOther, [1, 1], [2, 1])).toEqual(1);
});
const impossible = [
[0, 0, 0, 0, 0],
[0, 2, 0, 0, 0],
[0, 0, 1, 1, 1],
[1, 1, 1, 0, 0],
[0, 0, 0, 0, 2],
];
it("should return -1 when there's no possible path", () => {
expect(findShortestPathLength(impossible, [1, 1], [4, 4])).toEqual(-1);
});
});
describe("transform grid", () => {
const twoByTwo = [
[0,0],
[1,0]
];
it("should transform a grid", () => {
//arrange
const topLeft = new Point(0,0,0);
const topRight = new Point(0,1,0);
const bottomLeft = new Point(1,0,1);
const bottomRight = new Point(1,1,0);
const expected = [
[topLeft, topRight],
[bottomLeft, bottomRight]
];
//act
var actual = transformGrid(twoByTwo);
//assert
expect(actual).toEqual(expected);
});
});
describe("getNeighbours", function() {
const threeByThree = [
[2, 0, 0],
[0, 1, 0],
[0, 0, 2]
];
const threeByThreeTransformed = transformGrid(threeByThree);
const topLeft = new Point(0,0,2);
const topMiddle = new Point(0,1,0);
const topRight = new Point(0,2,0);
const leftMiddle = new Point(1,0,0);
const rightMiddle = new Point(1,2,0);
const bottomMiddle = new Point(2,1,0);
describe("when no edges or walls", () => {
it("should return 4 neighbours", () => {
//arrange
var expected = [leftMiddle, topMiddle, rightMiddle, bottomMiddle];
//act
const actual = getNeighbours(threeByThreeTransformed, 1, 1);
//assert
expect(actual).toEqual(expected);
});
});
describe("when edge", () => {
it("should return exclude out of bounds", () => {
//arrange
const expected = [topMiddle,leftMiddle];
//act
const actual = getNeighbours(threeByThreeTransformed, 0, 0);
//assert
expect(actual).toEqual(expected);
});
});
describe("when wall", ()=> {
it("should exclude the wall from neighbours", () => {
//arrange
const expected = [topLeft, topRight];
//act
const actual = getNeighbours(threeByThreeTransformed, 1, 0);
//assert
expect(actual).toEqual(expected);
});
});
});<file_sep>/tests/algorithmsTests/graphs.test.js
import {findMostCommonTitle} from "../../algorithms/graphs/graphs.js"
import {getUser} from "../../algorithms/graphs/getUser.js"
describe('findMostCommonTitle', function() {
it('user 30 with 2 degrees of separation', () => {
//arrange
const userId = 30;
const degrees = 2;
const expected = "Librarian";
//act
const actual = findMostCommonTitle(userId, getUser, degrees);
//assert
expect(actual).toBe(expected);
});
it('user 11 with 3 degrees of separation', () => {
//arrange
const userId = 11;
const degrees = 3;
const expected = "Graphic Designer";
//act
const actual = findMostCommonTitle(userId, getUser, degrees);
//assert
expect(actual).toBe(expected);
});
it('user 307 with 4 degrees of separation', () => {
//arrange
const userId = 306;
const degrees = 4;
const expected = "Environmental Tech";
//act
const actual = findMostCommonTitle(userId, getUser, degrees);
//assert
expect(actual).toBe(expected);
});
});
describe('extra credit', function() {
it('user 1 with 7 degrees of separation', () => {
//arrange
const userId = 1;
const degrees = 7;
const expected = "Geological Engineer";
//act
const actual = findMostCommonTitle(userId, getUser, degrees);
//assert
expect(actual).toBe(expected);
});
})<file_sep>/algorithms/shuffle.js
const shuffle = input => {
let counter = input.length;
while(counter > 0) {
const randomIndex = Math.floor(Math.random() * counter);
counter--;
input = swap(input, counter, randomIndex);
}
return input;
};
const shuffleRecurse = input => {
let counter = input.length;
const recurse = (array, counter) => {
if(counter === 0) return array;
const randomIndex = Math.floor(Math.random() * counter);
counter--;
array = swap(array, counter, randomIndex);
return recurse(array, counter);
};
return recurse(input, counter);
};
const swap = (array, first, second) => {
const temp = array[first];
array[first] = array[second];
array[second] = temp;
return array;
}
const input = [1,2,3,4,5];
console.log(shuffle(input));
console.log(shuffleRecurse(input));<file_sep>/katas/jobs/mineSweeper.js
////////////////////////////////////////////////////////////
//////////////////// GENERATE MAP //////////////////////////
////////////////////////////////////////////////////////////
const bombSymbol = '*';
class Square {
constructor(value, row, column){
this.hidden = true;
this.value = value;
this.row = row;
this.column = column;
}
}
const getRandomIndex = gridSize => Math.floor(Math.random() * gridSize);
const createRow = (gridSize, row) => createSquares(gridSize, row);
const createSquares = (gridSize, row) => {
const squares = [];
for(i = 0; i < gridSize; i++){
const square = new Square('0', row, i);
squares.push(square);
}
return squares;
}
const generateGrid = (gridSize) => {
const grid = [];
for(let i = 0; i < gridSize; i++) {
const row = createRow(gridSize, i);
grid.push(row);
}
return grid;
}
const generateBombPositions = (gridSize, bombCount) => {
const bombs = [];
for(let i = 0; i < bombCount; i++) {
const bomb = getBombCoords(gridSize);
bombs.push(bomb);
}
return bombs;
}
const getBombCoords = gridSize => {
const row = getRandomIndex(gridSize);
const column = getRandomIndex(gridSize);
return [row, column];
}
const generateGridWithBombs = (grid, bombs) => {
const temp = grid.map(row => [...row]);
bombs.forEach(bomb => {
row = bomb[0];
column = bomb[1];
temp[row][column].value = bombSymbol;
});
return temp;
}
const addBombProximity = grid => {
grid.forEach(row => {
row.forEach(square => {
if(square.value !== bombSymbol){
getNeighbours(grid, square.row, square.column);
}
});
});
return grid;
}
const getNeighbours = (grid, row, column) => {
const result = [];
const left = column - 1;
const right = column + 1;
const above = row - 1;
const below = row + 1;
const hasLeft = left >= 0;
const hasRight = right < gridSize;
const hasTop = above >= 0;
const hasBelow = below < gridSize;
if(hasLeft) result.push(grid[row][left].value);
if(hasRight) result.push(grid[row][right].value);
if(hasTop) result.push(grid[above][column].value);
if(hasBelow) result.push(grid[below][column].value);
if(hasLeft && hasTop) result.push(grid[above][left].value);
if(hasLeft && hasBelow) result.push(grid[below][left].value);
if(hasRight && hasTop) result.push(grid[above][right].value);
if(hasRight && hasBelow) result.push(grid[below][right].value);
const bombCount = result.filter(value => value === '*').length;
grid[row][column].value = bombCount.toString();
}
const printGrid = grid => {
console.log('row')
grid.forEach((row, index) => {
const result = [];
row.forEach(square => {
if(square.hidden === true) {
result.push('?')
} else {
result.push(square.value)
}
});
console.log(index.toString(), result);
});
console.log(' ', 0, ' ', 1, ' ', 2, ' ', 3, ' column')
console.log('==========================================')
}
const revealGrid = grid => {
grid.forEach(row => {
const result = [];
row.forEach(square => {
result.push(square.value)
});
console.log(result);
});
}
const gridSize = 4;
const bombNumber = 3;
const grid = generateGrid(gridSize);
const bombs = generateBombPositions(gridSize, bombNumber);
const gridWithBombs = generateGridWithBombs(grid, bombs);
const finalGrid = addBombProximity(gridWithBombs);
revealGrid(finalGrid)
console.log('================================')
//////////////////////////////////////////////////////////////////
///////////////////////// GAME LOGIC /////////////////////////////
//////////////////////////////////////////////////////////////////
printGrid(finalGrid);
console.log("Select a square by entering the row and column numbers in order");
var input = process.openStdin();
input.addListener("data", function(text) {
const coords = text.toString();
const square = getSquare(coords);
if(isBomb(square)) {
console.log('BOOM!')
console.log('You died');
revealGrid(finalGrid);
process.exit()
} else {
square.hidden = false;
printGrid(finalGrid);
}
});
const getSquare = coords => {
const row = coords.split('')[0];
const column = coords.split('')[1];
return grid[row][column];
}
const isBomb = square => {
return square.value === bombSymbol;
}
//Todo
//reveal all squares that also have 0 value
//if only bombs left, show winning condition<file_sep>/algorithms/sorting/insertionSort.js
const insertionSort = nums => {
for (let target = 1; target < nums.length; target++) {
for (let sorted = 0; sorted < target; sorted++) {
if (nums[target] < nums[sorted]) {
let removed = nums.splice(target, 1); //pop target out of the array
nums.splice(sorted, 0, removed[0]); //insert it at sorted spot
}
}
}
return nums;
};
export default insertionSort;
//Don't delete me until after the interview
//The console logs are are really helpful if you forget how this works.
// const insertionSort = nums => {
// for (let target = 1; target < nums.length; target++) {
// console.log("starting outer loop")
// console.log("nums is " + nums);
// console.log("target is " + nums[target])
// for (let sorted = 0; sorted < target; sorted++) {
// console.log("starting inner loop")
// console.log("sorted is " + nums[sorted]);
// console.log("target is " + nums[target])
// console.log(nums[target] + " < " + nums[sorted] + "?")
// if (nums[target] < nums[sorted]) {
// console.log("TRUE")
// console.log("popping target off")
// let removed = nums.splice(target, 1); //pop target out of the array
// console.log("inserting it")
// nums.splice(sorted, 0, removed[0]); //insert it at sorted spot
// console.log("new array " + nums)
// }
// console.log("FALSE")
// }
// }
// return nums;
// };<file_sep>/katas/youtube/towersHanoi.js
const start = "Start";
const spare = "Spare";
const end = "End";
const hanoi = disc => {
const result = [];
const recurse = (disc, start, spare, end) => {
if(disc < 1) return;
recurse(disc - 1, start, end, spare); //take whats on start, and using end, move it to spare
recurse(disc - 1, spare, start, end); //take whats on spare, and using start, move it to end
result.push(disc, start, end);
}
recurse(disc, start, spare, end);
return result;
}
const AreEqual = (array1, array2) => {
if(array1.length != array2.length) return false;
const matches = array1.filter(element => array2.includes(element));
console.log(matches.length == array1.length);
}
//////////////////////// TESTS ///////////////////////////
//Arrange
const threeExpected = [ 1, start, end, // _23_ __ _1_
2, start, spare, // _3_ _2_ _1_
1, end, spare, // _3_ _12_ __
3, start, end, // _ _ _12_ _3_
1, spare, start, // _1_ _2_ _3_
2, spare, end, // _1_ __ _23_
1, start, end ] // __ __ _123_
//Act
const threeActual = hanoi(3);
//Assert
AreEqual(threeExpected, threeActual);
//////////////////////////////////////////////////////////
//Arrange
const twoExpected = [ 1,start,spare,
2,start,end,
1,spare,end ]
//Act
const twoActual = hanoi(2);
//Assert
AreEqual(twoExpected, twoActual)
///////////////////////////////////////////////////////////
//Arrange
const OneExpected = [1,start, end];
//Act
const OneActual = hanoi(1);
//Assert
AreEqual(OneActual, OneExpected);<file_sep>/katas/youtube/incrementArray.js
//given an array like [2,3,1,4]
//return a new array with the last element incremented by 1
//for example, [2,3,1,5]
//in cases where the array ends with 9, such as [9,9,9]
//then it should return [1,0,0,0]
//the array cannot be empty or negative
const incrementArray = (array) => {
const tempArray = array;
const recurse = (tempArray, element) => {
if(element < 9) {
return tempArray.concat(element + 1);
}
const previousNumber = tempArray.pop()
if(!previousNumber){ //if start of array
return [1].concat(0);
}
const result = recurse(tempArray, previousNumber).concat(0);
return tempArray.concat(result);
}
const last = tempArray.pop();
return recurse(tempArray, last);
}
export default incrementArray;<file_sep>/tests/dataStructuresTests/linkedLists/shift.test.js
import LinkedList from '../../../dataStructures/linkedList.js';
describe("Shift", () => {
test('WhenEmptyList_ThenNull', () => {
let emptyList = new LinkedList();
const result = emptyList.shift();
expect(result).toBeNull();
});
test('WhenOneNode_ThenUpdatesHeadAndReturnsNode', () => {
let list = new LinkedList();
list.push(1);
const result = list.shift();
expect(list.head).toBeNull();
expect(list.tail).toBeNull();
expect(result.value).toBe(1);
});
test('WhenTwoNodes_ReturnsCorrectNodeAndRestOfList', () => {
let list = new LinkedList();
list.push(1);
list.push(2);
const result = list.shift();
expect(result.value).toBe(1);
expect(list.head.value).toBe(2);
expect(list.tail.value).toBe(2);
});
test('WhenThreeNodes_ReturnsCorrectNodeAndRestOfList', () => {
let list = new LinkedList();
list.push(1);
list.push(2);
list.push(3);
const result = list.shift();
expect(result.value).toBe(1);
expect(list.head.value).toBe(2);
expect(list.tail.value).toBe(3);
});
});
<file_sep>/katas/jobs/sortByKeyAndValue.js
/*
Let 'name-number' to be a string that consists of name and cardinal number.
Sort list of name-numbers by name and value of the cardinal number.
You may assume cardinal numbers are positive integers.
Example:
input: ['<NAME>', '<NAME>', '<NAME>', '<NAME>']
output: ['<NAME>', '<NAME>', '<NAME>', '<NAME>']
*/
class NameNumber {
constructor(element){
this.original = element;
this.name = element.split(' ')[0];
this.number = to_int(element.split(' ')[1]);
}
static get MAPPING() {
return {
'One': 1,
'Two': 2,
//...,
'Nine': 9,
'Ten': 10,
'Eleven': 11,
//...,
'Nineteen': 19,
'Twenty': 20,
//...,
'Ninety': 90,
}
}
static get MULTIPLIERS() {
return {
'Hundred': 100,
'Thousand': 1000,
'Million': 1000000,
}
}
// 234,567 = Two-Hundred-Thirty-Four-Thousand-Five-Hundred-Sixty-Seven
// 23,000 = Twenty-Three-Thousand
to_int(cardinal) {
//split cardinal on hyphen
var cardinals = cardinal.split('-');
let operand;
let multiplier;
let result;
for(let i =0; i < cardinals.length; i++){ // 5,023,000 = 'Five-Million-Twenty-Three-Thousand'
let target = cardinals[i];
if(MAPPING[target] !== null){
operand += MAPPING[target]; // 5
}
if(MULTIPLIERS[target]!= null){
multiplier = MULTIPLIERS[target];
result += multiplier * operand;
operand = 0;
}
result += operand; // 23,004
}
return result;
}
}
const input = ['<NAME>', '<NAME>', '<NAME>', '<NAME>'];
const namesNumbers = input.map(function(el){ // el = '<NAME>'
return new NameNumber(el);
});
const foo = namesNumbers.sort(function(a,b) {
if(a.name < b.name) {
return -1;
}
if(b.name < a.name) {
return 1;
}
if(a.number < b.number){
return -1;
}
if(b.number < a.number) {
return 1;
}
return 0;
});
/*
array.sort(function(x, y) {
if (x < y) {
return -1;
}
if (x > y) {
return 1;
}
return 0;
});
*/
//key is index of array
//'<NAME>'.
//name --> john
//number --> 5 <file_sep>/katas/interview/movies.js
const findMovies = (flightLength, movies) => {
const secondMovies = new Set();
let result = false;
movies.forEach(movieLength => {
let timeLeft = flightLength - movieLength;
if(secondMovies.has(movieLength)) result = true;
if(timeLeft !== movieLength) secondMovies.add(timeLeft);
});
return result;
}
//example
//240, [100, 140] ==> true
//240, [100, 150] ==> false
//240, [120, 120] == false because same movie twice
//optimize for runtime
const flightTime = 240;
const matching = [100, 140];
const expectedTrue = findMovies(flightTime, matching);
console.log(expectedTrue === true);
const noMatch = [100, 150];
const expectedFalse = findMovies(flightTime, noMatch);
console.log(expectedFalse === false);
const matchThree = [120, 100, 20];
const expectedFalseThree = findMovies(flightTime, matchThree);
console.log(expectedFalseThree === false);
const noMatchSame = [120, 120];
const expectedFalseSame = findMovies(flightTime, noMatchSame);
console.log(expectedFalseSame === false);<file_sep>/app.js
console.log("Algorithms and data structures in JS.");
console.log("Run 'npm test' to verify solutions.")<file_sep>/tests/dataStructuresTests/array/delete.test.js
import {ArrayList} from '../../../dataStructures/array.js'
test('Delete_WhenIndexExists_ReturnsCorrectData', () => {
//Arrange
var array = new ArrayList();
array.push(1);
//Act
array.delete(0);
//Assert
expect(array.data).toBeNull;
});
test('Delete_WhenIndexDoesNotExist_ReturnsCorrectData', () => {
//Arrange
var array = new ArrayList();
array.push(1);
//Act
array.delete(10);
//Assert
expect(array.data[0]).toBe(1);
});
test('Delete_WhenLastElement_ReturnsCorrectData', () => {
//Arrange
var array = new ArrayList();
array.push(1);
array.push(2);
//Act
array.delete(1);
//Assert
expect(array.data[0]).toBe(1);
});
test('Delete_WhenIndexZero_ShiftsOtherElementDown', () => {
//Arrange
var array = new ArrayList();
array.push(1);
array.push(2);
//Act
array.delete(0);
//Assert
expect(array.data[0]).toBe(2);
});<file_sep>/katas/jobs/shuffle.js
const input = [1,2,3,4,5,6];
const badShuffle = input => {
for(let i = 0; i < input.length; i++){
const randomNumber = Math.floor(Math.random() * input.length);
const randomElement = input[randomNumber];
const element = input[i];
input[i] = randomElement;
input[randomNumber] = element;
}
return input;
};
// bad shuffle can swap any element with any other.
// it produces n**n possible outcomes. In this case, 27
// because at each step, it generates n possible outcomes
// but the result should be n! or in this case, 6
// so we need a better algorithm that will leave sorted things untouched
const goodShuffle = input => {
let unshuffled = input.length;
while (unshuffled > 0) {
//get a random number within the range of unshuffled elements. That is, ensure it is less than the index of shuffled elements.
const randomNumber = Math.floor(Math.random() * unshuffled);
// Decrease counter by 1
unshuffled--;
// Swap the random element and the last element
let lastElement = input[unshuffled];
input[unshuffled] = input[randomNumber];
input[randomNumber] = lastElement;
}
return input;
}
console.log(goodShuffle(input))<file_sep>/katas/youtube/permutations.js
const findPermutations = string => {
let result = new Set();
const recurse = (soFar, rest) => {
const length = rest.length;
if (length === 0) {
result.add(soFar);
}
for (let i = 0; i < length; i++){
const next = soFar + rest[i];
const remaining = rest.slice(0, i) + rest.slice(i+1);
recurse(next, remaining);
}
}
recurse("", string);
return result;
}
console.log(findPermutations("abc"));<file_sep>/dataStructures/hashTable.js
class HashTable {
constructor(maxSize) {
this.maxSize = maxSize;
this.table = new Array(maxSize);
}
add(input) {
const hashCode = generateHashCode(input, this.maxSize);
this.table[hashCode] = input;
}
check(input) {
const hashCode = generateHashCode(input, this.maxSize);
if(this.table[hashCode]) return true;
return false;
}
}
const generateHashCode = (input, maxValue) => {
let hash = 0;
const inputLength = input.length;
if(inputLength === 0) return hash;
for(var i = 0; i < inputLength; i++){
const charCode = input.charCodeAt(i);
hash = (hash * 31) + charCode;
hash = hash & hash;
}
return Math.abs(hash % maxValue);
}
export {generateHashCode, HashTable};<file_sep>/algorithms/traversal/bfs.js
const flattenTree = tree => {
const queue = new Queue();
queue.enqueue(tree.root);
const recurse = (queue, array) => {
if(!queue.head) return array;
const queueNode = queue.dequeue();
const treeNode = queueNode.value;
array.push(treeNode.value);
if (treeNode.left) queue.enqueue(treeNode.left);
if (treeNode.right) queue.enqueue(treeNode.right);
return recurse(queue, array);
}
return recurse(queue, []);
}
const treeContains = (tree, element) => {
const queue = new Queue();
queue.enqueue(tree.root);
const recurse = (queue, array) => {
if(!queue.head) return array;
const queueNode = queue.dequeue();
const treeNode = queueNode.value;
if(treeNode.value === element) return treeNode.value;
if (treeNode.left) queue.enqueue(treeNode.left);
if (treeNode.right) queue.enqueue(treeNode.right);
return recurse(queue, array);
}
return recurse(queue, []);
}
class Queue {
constructor() {
this.head = null;
this.tail = null;
}
enqueue(value){
var node = new QueueNode(value);
if(!this.head) {
this.head = node;
this.tail = node;
} else {
this.tail.next = node;
this.tail = node;
}
}
dequeue(){
if(!this.head) return null;
const result = this.head;
if(this.head === this.tail){
this.head = null;
this.tail = null;
} else {
this.head = this.head.next;
}
return result;
}
}
class QueueNode {
constructor(value){
this.value = value;
this.next = null;
}
}
class Bst {
constructor(){
this.root = null;
}
add(value){
var newNode = new TreeNode(value);
if(!this.root){
this.root = newNode;
return;
}
const recurse = (node, value) => {
if(node.value > value){
if(!node.left){
node.left = newNode;
}
recurse(node.left, value)
}
if(node.value < value){
if(!node.right){
node.right = newNode;
}
recurse(node.right, value)
}
}
return recurse(this.root, value);
}
}
class TreeNode {
constructor(value){
this.value = value;
this.left = null;
this.right = null;
}
}
export {flattenTree, treeContains, Bst};
<file_sep>/katas/pramp/wordCount.js
function wordCountEngine(document) {
const mapping = createMapping(document);
return sortWords(mapping);
}
function createMapping(document){
const words = document.split(' ');
const mapping = new Map();
words.forEach(word => {
if(word === '') return;
const validWord = format(word);
if(mapping.has(validWord)){
const value = parseInt(mapping.get(validWord));
const increment = value + 1;
mapping.set(validWord, increment.toString());
} else {
mapping.set(validWord, "1");
}
});
return mapping;
}
function sortWords(mapping){
const sorted = [];
const output = [];
for(const word of mapping){
const count = word[1];
const current = sorted[count] || [];
current.push(word);
sorted[count] = current;
}
for(let i = sorted.length - 1; i > 0; i--){
sorted[i].forEach(word => {
output.push(word);
});
}
return output;
}
function format(word){
const lower = word.toLowerCase();
const pattern = /[a-z]/g;
const withoutPunctuation = lower.match(pattern);
const result = withoutPunctuation.join('');
return result;
}
let input = "Every book is a quotation; and every house is a quotation out of all forests, and mines, and stone quarries; and every man is a quotation from all his ancestors. ";
let expected = [["and","4"],["every","3"],["is","3"],["a","3"],["quotation","3"],["all","2"],["book","1"],["house","1"],["out","1"],["of","1"],["forests","1"],["mines","1"],["stone","1"],["quarries","1"],["man","1"],["from","1"],["his","1"],["ancestors","1"]];
let actual = wordCountEngine(input);
console.log(expected.toString() === actual.toString())
input = "hello world";
expected = [['hello', 1], ["world", 1]];
actual = wordCountEngine(input);
console.log(expected.toString() === actual.toString())
input = "Practice makes perfect. you'll only get Perfect by practice. just practice!"
expected = [ ["practice", "3"], ["perfect", "2"],
["makes", "1"], ["youll", "1"], ["only", "1"],
["get", "1"], ["by", "1"], ["just", "1"] ];
actual = wordCountEngine(input);
console.log(expected.toString() === actual.toString())<file_sep>/katas/pramp/root.js
function root(x, n) {
let lowerRange = x - 0.001;
let upperRange = x + 0.001;
function recurse(lowerBound, upperBound){
let half = (upperBound - lowerBound)/2;
let middle = lowerBound + half;
let guess = Math.pow(middle,n);
if(lowerRange < guess && guess < upperRange) return middle.toFixed(3);
if(guess < lowerRange) return recurse(middle + 1, upperBound)
if(guess > upperRange) return recurse(lowerBound, middle - 1);
}
return recurse(0, x);
}
let x = 27;
let n = 3;
let expected = 3.000;
let actual = root(x, n);
console.log(expected == actual);
x = 16;
n = 2;
expected = 4.000;
actual = root(x, n);
console.log(expected == actual);
x = 7;
n = 3;
expected = 1.913;
actual = root(x, n);
console.log(expected == actual);
x = 9;
n = 2;
expected = 3.000;
actual = root(x, n);
console.log(expected == actual);<file_sep>/katas/interview/trees/balancedTree.js
//A tree is "superbalanced" if the difference between the depths of any two leaf nodes
//is no greater than one.
function isBalanced(treeRoot) {
let min = 100;
let max = 0;
const balanced = (max, min) => max - min <= 1;
const recurse = (node, depth) => {
console.log('===================')
console.log("node", node.value)
console.log("depth", depth)
if(!balanced(max, min)) {
console.log('breaking early');
return false;
}
const isLeaf = !node.left && !node.right;
if(isLeaf) {
console.log('is leaf')
if(depth < min) min = depth;
if(depth > max) max = depth;
console.log('min depth', min);
console.log('max depth', max)
if(!balanced(max, min)) {
console.log('NOT balanced')
return false;
} else {
console.log('balanced')
return true
}
} else {
depth +=1;
if(node.left) {
console.log('processing left')
recurse(node.left, depth);
}
if(node.right) {
console.log('processing right')
recurse(node.right, depth)
}
console.log('returning');
return balanced(max, min);
}
};
return recurse(treeRoot, 1);
}
class BinaryTreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
insertLeft(value) {
this.left = new BinaryTreeNode(value);
return this.left;
}
insertRight(value) {
this.right = new BinaryTreeNode(value);
return this.right;
}
}
// Tests
let desc = 'full tree';
let treeRoot = new BinaryTreeNode(5);
let leftNode = treeRoot.insertLeft(8);
leftNode.insertLeft(1);
leftNode.insertRight(2);
let rightNode = treeRoot.insertRight(6);
rightNode.insertLeft(3);
rightNode.insertRight(4);
assertEquals(isBalanced(treeRoot), true, desc);
/*
5
/ \
8 6
/ \ / \
1 2 3 4
*/
desc = 'both leaves at the same depth';
treeRoot = new BinaryTreeNode(3);
leftNode = treeRoot.insertLeft(4);
leftNode.insertLeft(1);
rightNode = treeRoot.insertRight(6);
rightNode.insertRight(9);
assertEquals(isBalanced(treeRoot), true, desc);
/*
3
/ \
4 6
/ \
1 9
*/
desc = 'leaf heights differ by one';
treeRoot = new BinaryTreeNode(6);
leftNode = treeRoot.insertLeft(1);
rightNode = treeRoot.insertRight(0);
rightNode.insertRight(7);
assertEquals(isBalanced(treeRoot), true, desc);
/*
6
/ \
1 0
\
7
*/
desc = 'leaf heights differ by two';
treeRoot = new BinaryTreeNode(6);
leftNode = treeRoot.insertLeft(1);
rightNode = treeRoot.insertRight(0);
rightNode.insertRight(7).insertRight(8);
assertEquals(isBalanced(treeRoot), false, desc);
/*
6
/ \
1 0
\
7
\
8
*/
desc = 'should break early';
treeRoot = new BinaryTreeNode(6);
leftNode = treeRoot.insertLeft(1);
rightNode = treeRoot.insertRight(0);
let seven = rightNode.insertRight(7);
seven.insertLeft(6);
seven.insertRight(8).insertRight(11);
assertEquals(isBalanced(treeRoot), false, desc);
/*
6
/ \
1 0
\
7
/ \
6 8
*/
desc = 'three leaves total';
treeRoot = new BinaryTreeNode(1);
leftNode = treeRoot.insertLeft(5);
rightNode = treeRoot.insertRight(9);
rightNode.insertLeft(8);
rightNode.insertRight(5);
assertEquals(isBalanced(treeRoot), true, desc);
desc = 'both subtrees superbalanced';
treeRoot = new BinaryTreeNode(1);
leftNode = treeRoot.insertLeft(5);
rightNode = treeRoot.insertRight(9);
rightNode.insertLeft(8).insertLeft(7);
rightNode.insertRight(5);
assertEquals(isBalanced(treeRoot), false, desc);
desc = 'only one node';
treeRoot = new BinaryTreeNode(1);
assertEquals(isBalanced(treeRoot), true, desc);
desc = 'linked list tree';
treeRoot = new BinaryTreeNode(1);
treeRoot.insertRight(2).insertRight(3).insertRight(4);
assertEquals(isBalanced(treeRoot), true, desc);
function assertEquals(a, b, desc) {
if (a === b) {
console.log(`${desc} ... PASS`);
} else {
console.log(`${desc} ... FAIL: ${a} != ${b}`)
}
}<file_sep>/katas/jobs/ticTacToe.js
class Game {
constructor(){
this.board = this.CreateBoard();
this.token = 'X';
}
CreateBoard(){
const board = [
['-', '-', '-'],
['-', '-', '-'],
['-', '-', '-']
];
return board;
}
PrintBoard() {
this.board.forEach(row => console.log(row));
}
AddToken(value, row, column) {
this.board[row][column] = value;
}
IsFull(){
this.board.forEach(row => {
row.forEach(square => {
if(square === "-") return false;
})
});
return countHyphen === 0;
}
makeMoveAI(){
this.board.forEach((row, rowIndex) => {
row.forEach((square, columnIndex) => {
if(square === "-") {
board[rowIndex][columnIndex] = 'X';
break;
}
})
});
}
}
const fullBoardGrid = [
['X', 'X', 'X'],
['X', 'X', 'X'],
['X', 'X', 'X']
];
const game = new Game();
game.PrintBoard();
const fullGame = new Game();
<file_sep>/tests/kataTests/firstRepeatedChar.failingTest.js
import {firstRepeatedChar, firstRepeatedCharRecurse} from '../../../algoDataStructuresJS/katas/firstRepeatedChar.js';
test("WhenEmpty_ThenNull", () => {
const input = "";
const result = firstRepeatedChar(input);
expect(result).toBeNull();
});
test("WhenSingleChar_ThenNull", () => {
const input = "a";
const result = firstRepeatedChar(input);
expect(result).toBeNull();
});
test("WhenTwoCharsNoMatch_ThenNull", () => {
const input = "ab";
const result = firstRepeatedChar(input);
expect(result).toBeNull();
});
test("WhenTwoCharsMatch_ThenChar", () => {
const input = "bb";
const result = firstRepeatedChar(input);
expect(result[0]).toEqual('b');
});
test("WhenOneMatch_ThenChar", () => {
const input = "abca";
const result = firstRepeatedChar(input);
expect(result[0]).toEqual('a');
});
test("WhenTwoMatch_ThenFirstChar", () => {
const input = "bcaba";
const result = firstRepeatedChar(input);
expect(result[0]).toEqual('b');
});
test("WhenNoMatch_ThenFirstChar", () => {
const input = "cab";
const result = firstRepeatedChar(input);
expect(result).toBeNull();
});
// //////////////////////////////////////////////////
test("WhenEmpty_ThenNull", () => {
const input = "";
const result = firstRepeatedCharRecurse(input);
expect(result).toBeNull();
});
test("WhenSingleChar_ThenNull", () => {
const input = "a";
const result = firstRepeatedCharRecurse(input);
expect(result).toBeNull();
});
test("WhenTwoCharsNoMatch_ThenNull", () => {
const input = "ab";
const result = firstRepeatedCharRecurse(input);
expect(result).toBeNull();
});
test("WhenTwoCharsMatch_ThenChar", () => {
const input = "bb";
const result = firstRepeatedCharRecurse(input);
expect(result[0]).toEqual('b');
});
test("WhenOneMatch_ThenChar", () => {
const input = "abca";
const result = firstRepeatedCharRecurse(input);
expect(result[0]).toEqual('a');
});
test("WhenTwoMatch_ThenFirstChar", () => {
const input = "bcaba";
const result = firstRepeatedCharRecurse(input);
expect(result[0]).toEqual('b');
});
test("WhenNoMatch_ThenFirstChar", () => {
const input = "cab";
const result = firstRepeatedCharRecurse(input);
expect(result).toBeNull();
});<file_sep>/katas/jobs/iterator.js
class Iterator {
constructor(){
this.queue = [];
}
hasNext(input) {
return input.length > 0;
}
next(input){
let firstElement = input.shift();
if(Array.isArray(firstElement)){
firstElement.map(x => this.queue.push(x));
const firstNode = this.queue.shift()
return firstNode;
}
return firstElement;
}
iterate(input) {
const iterator = new Iterator(input);
const result = [];
while(iterator.hasNext(input)){
const next = iterator.next(input);
result.push(next);
while(iterator.queue.length > 0) {
let firstNode = iterator.queue.shift();
result.push(firstNode);
}
}
return result.join("").replace(/,/g, "");
}
iterateRecurse(input) {
function recurse(input, output) {
if(input.length === 0) return output;
input.forEach(element => {
if(Array.isArray(element)) return recurse(element, output);
output.push(element);
});
return output;
}
const result = recurse(input, []);
return result.join("");
}
}
//Arrange
const emptyInput = [];
const singleElementInput = [1];
const twoElementsInput = [1,2];
const nestedInput = [1,[2,3]];
const sampleInput = [9,[1,3],4,5];
const doublyNestedInput = [1,[2,[3,4],5],6]
const triplyNestedInput = [1,[2,[3,[4, 5],6],7],8]
const emptyNestedInput = [1,[2,[3,[],6],7],8]
//Act
let iterator = new Iterator();
let empty = iterator.iterate(emptyInput);
let singleElement = iterator.iterate(singleElementInput);
let twoElements = iterator.iterate(twoElementsInput);
let nested = iterator.iterate(nestedInput);
let sample = iterator.iterate(sampleInput);
let doublyNested = iterator.iterate(doublyNestedInput);
let triplyNested = iterator.iterate(triplyNestedInput);
let emptyNested = iterator.iterate(emptyNestedInput);
//Assert
console.log(empty.length === 0);
console.log(singleElement === "1");
console.log(twoElements === "12");
console.log(nested === "123");
console.log(sample === "91345");
console.log(doublyNested === "123456");
console.log(triplyNested === "12345678");
console.log(emptyNested === "123678");
// iterator = new Iterator();
// empty = iterator.iterateRecurse(emptyInput);
// singleElement = iterator.iterateRecurse(singleElementInput);
// twoElements = iterator.iterateRecurse(twoElementsInput);
// nested = iterator.iterateRecurse(nestedInput);
// sample = iterator.iterateRecurse(sampleInput);
// doublyNested = iterator.iterateRecurse(doublyNestedInput);
// triplyNested = iterator.iterateRecurse(triplyNestedInput);
// emptyNested = iterator.iterateRecurse(emptyNestedInput);
// //Assert
// console.log(empty.length === 0);
// console.log(singleElement === "1");
// console.log(twoElements === "12");
// console.log(nested === "123");
// console.log(sample)// === "91345");
// console.log(doublyNested)// === "123456");
// console.log(triplyNested === "12345678");
// console.log(emptyNested === "123678");
<file_sep>/tests/dataStructuresTests/linkedLists/push.test.js
import LinkedList from '../../../dataStructures/linkedList.js';
test('Push_WhenEmptyList_ThenUpdatesHead', () => {
let emptyList = new LinkedList();
emptyList.push(1);
expect(emptyList.head.value).toEqual(1);
});
test('Push_WhenEmptyList_ThenUpdatesHead', () => {
let emptyList = new LinkedList();
emptyList.push(1);
expect(emptyList.tail.value).toEqual(1);
});
test('Push_WhenNotEmptyList_ThenUpdatesTail', () => {
let list = new LinkedList();
list.push(1);
list.push(2);
expect(list.tail.value).toEqual(2);
});<file_sep>/katas/interview/trees/isBST.js
/*
Write a function to check that a binary tree ↴ is a valid binary search tree.
*/
const isBinarySearchTree = node => {
const nodeValues = [];
const dfs = (node, nodeValues) => {
if(!node) return false;
dfs(node.left, nodeValues);
nodeValues.unshift(node.value);
if(!isInOrder(nodeValues)) return false;
dfs(node.right, nodeValues);
return isInOrder(nodeValues)
}
const isInOrder = nodeValues => {
if(treeHasOneNode(nodeValues)) return true;
return nodeValues[0] > nodeValues[1];
}
const treeHasOneNode = nodeValues => nodeValues.length === 1;
return dfs(node, nodeValues);
}
class BinaryTreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
insertLeft(value) {
this.left = new BinaryTreeNode(value);
return this.left;
}
insertRight(value) {
this.right = new BinaryTreeNode(value);
return this.right;
}
}
// Tests
let desc = 'valid full tree';
let treeRoot = new BinaryTreeNode(50);
let leftNode = treeRoot.insertLeft(30);
leftNode.insertLeft(10);
leftNode.insertRight(40);
let rightNode = treeRoot.insertRight(70);
rightNode.insertLeft(60);
rightNode.insertRight(80);
assertEquals(isBinarySearchTree(treeRoot), true, desc);
desc = 'both subtrees valid';
treeRoot = new BinaryTreeNode(50);
leftNode = treeRoot.insertLeft(30);
leftNode.insertLeft(20);
leftNode.insertRight(60);
rightNode = treeRoot.insertRight(80);
rightNode.insertLeft(70);
rightNode.insertRight(90);
assertEquals(isBinarySearchTree(treeRoot), false, desc);
desc = 'descending linked list';
treeRoot = new BinaryTreeNode(50);
leftNode = treeRoot.insertLeft(40);
leftNode = leftNode.insertLeft(30);
leftNode = leftNode.insertLeft(20);
leftNode = leftNode.insertLeft(10);
assertEquals(isBinarySearchTree(treeRoot), true, desc);
desc = 'out of order linked list';
treeRoot = new BinaryTreeNode(50);
rightNode = treeRoot.insertRight(70);
rightNode = rightNode.insertRight(60);
rightNode = rightNode.insertRight(80);
assertEquals(isBinarySearchTree(treeRoot), false, desc);
desc = 'one node tree';
treeRoot = new BinaryTreeNode(50);
assertEquals(isBinarySearchTree(treeRoot), true, desc);
function assertEquals(a, b, desc) {
if (a === b) {
console.log(`${desc} ... PASS`);
} else {
console.log(`${desc} ... FAIL: ${a} != ${b}`)
}
}<file_sep>/algorithms/search/binarySearch.js
function binarySearch(needle, haystack) {
function recurse(needle, haystack, lowerBound, upperBound)
{
const middleIndex = Math.floor(lowerBound + ((upperBound - lowerBound) / 2));
const middleElement = haystack[middleIndex];
if(needle === middleElement) return middleIndex;
if (upperBound - lowerBound === 0) return -1;
if (needle < middleElement) return recurse(needle, haystack, lowerBound, middleIndex);
if(needle > middleElement) return recurse(needle, haystack, middleIndex + 1, upperBound);
}
return recurse(needle, haystack, 0, haystack.length - 1)
}
function binarySearchIterative(needle, haystack) {
let lowerBound = 0;
let upperBound = haystack.length - 1;
while(lowerBound <= upperBound){
const middle = (upperBound - lowerBound)/2;
const middleIndex = Math.floor(middle + lowerBound);
const middleElement = haystack[middleIndex];
if(needle === middleElement) return middleIndex;
if(needle < middleElement) {
upperBound = middleIndex - 1
} else {
lowerBound = middleIndex + 1;
}
}
return -1;
}
let needle = 5;
let haystack = [1,2,3,4,5];
let expected = 4;
let actual = binarySearch(needle, haystack);
console.log(actual === expected);
needle = 'a';
haystack = ['a','b','c'];
expected = 0;
actual = binarySearch(needle, haystack);
console.log(actual === expected);
needle = 5;
haystack = [1,2,3];
expected = -1;
actual = binarySearch(needle, haystack);
console.log(actual === expected);
needle = 5;
haystack = [1,2,3,4,5];
expected = 4;
actual = binarySearchIterative(needle, haystack);
console.log(actual === expected);
needle = 'a';
haystack = ['a','b','c'];
expected = 0;
actual = binarySearchIterative(needle, haystack);
console.log(actual === expected);
needle = 5;
haystack = [1,2,3];
expected = -1;
actual = binarySearchIterative(needle, haystack);
console.log(actual === expected);
<file_sep>/katas/youtube/staircase.js
////////////////////////////////////////////////
////////////// LOOPS ///////////////////////////
let fibs = [1,1]
const numWays = input => {
console.time("loop")
if(input < 2) return 1;
if(input < fibs.length){
console.timeEnd("loop");
return fibs[input];
}
for(let i = fibs.length; i <= input; i++){
let last = fibs[fibs.length - 1];
let secondLast = fibs[fibs.length - 2];
let sum = last + secondLast;
fibs.push(sum);
}
console.timeEnd("loop");
return fibs[fibs.length-1];
}
console.log(numWays(8));
console.log(numWays(9));
console.log(numWays(8));
//////////////////////////////////////////////////////////
////////////////////// RECURSIVE /////////////////////////
const numWaysRecurse = input => {
if(input < 2) return 1;
return (numWaysRecurse(input - 1) + numWaysRecurse(input - 2));
}
console.log("/////////////////RECURSE ////////////////////");
let a = 11;
console.time(a)
console.log(numWaysRecurse(a));
console.timeEnd(a);
let b = 21;
console.time(b)
console.log(numWaysRecurse(b));
console.timeEnd(b);
let c = 11;
console.time(c)
console.log(numWaysRecurse(c));
console.timeEnd(c);
const numWaysRecurseMemo = input => {
if(input in fibsObject) {
return fibsObject[input];
}
if(input < 2) return 1;
fibsObject[input] = (numWaysRecurse(input - 1) + numWaysRecurse(input - 2));
return fibsObject[input];
}
let fibsObject = {};
console.log("//////////////////MEMO///////////////////");
let x = 11;
console.time(x)
console.log(numWaysRecurseMemo(x));
console.timeEnd(x);
let y = 21;
console.time(y)
console.log(numWaysRecurseMemo(y));
console.timeEnd(y);
let z = 11;
console.time(z)
console.log(numWaysRecurseMemo(z));
console.timeEnd(z);<file_sep>/katas/jobs/reverseList.js
//reverse a singly linked list
function printList(list){
function recurse(node){
if(!node) return;
process.stdout.write(node.value + " --> ");
recurse(node.next);
}
recurse(list.head);
console.log();
}
function toList(array) {
const list = new LinkedList();
for(let i = 0; i < array.length; i++){
const element = array[i];
list.add(element);
}
return list;
}
class Node {
constructor(value){
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor(){
this.head = null;
this.tail = null;
}
add(value){
const node = new Node(value);
if(!this.head){
this.head = node;
this.tail = node;
} else {
this.tail.next = node;
this.tail = node;
}
}
addToStart(value) {
const node = new Node(value);
if(!this.head){
this.head = node;
this.tail = node;
} else {
node.next = this.head;
this.head = node;
}
}
reverseList(){
const newList = new LinkedList();
function recurse(node, list){
if(!node) return list;
list.addToStart(node.value);
return recurse(node.next, list);
}
return recurse(this.head, newList);
}
}
const array = [1,2,3,4,5];
const list = toList(array);
const reversed = list.reverseList();
printList(reversed);
printList(list)
<file_sep>/katas/pramp/pancakeSort.js
/*
Pancake Sort
Given an array of integers
Write a function flip(arr, k) that reverses the order of the first k elements in the array arr.
Write a function pancakeSort(arr) that sorts and returns the input array.
You are allowed to use only the function flip you wrote in the first step in order to make changes in the array.
*/
function pancakeSort(input) {
if(!input) return [];
function recurse(array, result) {
if(!array.length) return result;
const indexLargestElement = getindexLargestElement(array);
let flipLargestToTop = flip(array, indexLargestElement + 1);
let flipTopToBottom = flip(flipLargestToTop, array.length);
const largest = flipTopToBottom.pop();
result.unshift(largest);
return recurse(flipTopToBottom, result)
}
return recurse(input, []);
};
function flip(arr, indexLargestElement) {
const temp = [].concat(arr);
const firstElements = temp.splice(0, indexLargestElement);
const flipped = firstElements.reduceRight((b, a) => b.concat(a), []);
return flipped.concat(temp);
}
function getindexLargestElement(array){
if(!array.length) return [];
let largest = Number.MIN_SAFE_INTEGER;
let index = 0;
for(let i = 0; i < array.length; i++){
if(array[i] > largest){
largest = array[i];
index = i;
}
}
return index;
}
// TESTS
const empty = [];
const one = [1];
const twoSorted = [1,2];
const twoUnsorted = [2,1];
const threeSorted = [1,2,3];
const threeUnsorted = [2,3,1];
const fiveSorted = [1,2,3,4,5];
const fiveUnsorted = [4,5,1,3,2];
const twoListInput = [1,2,3,4,4,3,2,1];
// PANCAKE SORT
let actual = pancakeSort(one);
let expected = one
console.log(isEqual(actual, expected));
actual = pancakeSort(twoSorted);
expected = twoSorted;
console.log(isEqual(actual, expected));
actual = pancakeSort(twoUnsorted);
expected = twoSorted;
console.log(isEqual(actual, expected));
actual = pancakeSort(threeSorted);
expected = threeSorted;
console.log(isEqual(actual, expected));
actual = pancakeSort(threeUnsorted);
expected = threeSorted;
console.log(isEqual(actual, expected));
actual = pancakeSort(fiveSorted);
expected = fiveSorted;
console.log(isEqual(actual, expected));
actual = pancakeSort(fiveUnsorted);
expected = fiveSorted;
console.log(isEqual(actual, expected));
actual = pancakeSort(twoListInput);
expected = [ 1, 1, 2, 2, 3, 3, 4, 4 ];
console.log(isEqual(actual, expected));
// FLIP
actual = flip(fiveSorted, 2);
expected = [2,1,3,4,5];
console.log(isEqual(actual, expected));
// GET LARGEST ELEMENT
actual = getindexLargestElement(empty);
expected = empty;
console.log(actual.length == expected.length);
actual = getindexLargestElement(one);
expected = 0;
console.log(actual === expected);
actual = getindexLargestElement(twoUnsorted);
expected = 0;
console.log(actual === expected);
actual = getindexLargestElement(threeSorted);
expected = 2;
console.log(actual === expected);
actual = getindexLargestElement(fiveUnsorted);
expected = 1;
console.log(actual === expected);
function isEqual(array1, array2){
if(array1.length !== array2.length) return false;
let result = true;
for(let i = 0; i < array1.length; i++){
if(array1[i] !== array2[i]) result = false;
}
return result;
}
<file_sep>/katas/interview/graphs/colouring.js
/*
Given an undirected graph with maximum degree D,
find a graph coloring using at most D+1 colors.
It takes in an array of graph nodes.
Each graph node contains a value, a color, and a set of neighbours.
Each set contains other nodes.
*/
const colorGraph = (graph, colors) => {
//we can colour with at most
}
const red = "red";
const blue = "blue";
const yellow = "yellow";
const green = "green";
const none = "none";
const colors = [red, blue, yellow, green, none]
class Node {
constructor(value) {
this.value = value;
this.neighbors = new Set();
this.color = none;
}
}
const isValid = graph => {
return allNodesHaveColor() &&
hasCorrectNumberColors() &&
isColorMatchNeighbor();
}
//tested
const isColorMatchNeighbor = graph => { //ask amy for advice on this one
let result = false;
graph.forEach(node => {
const neigbors = getNeighbors(node);
const duplicate = neigbors.filter(neighbor => neighbor.color === node.color);
if(duplicate.length > 0) result = true;
});
return result;
}
//tested
const hasCorrectNumberColors = graph => {
let colors = new Set();
let maxNeighborCount = 0;
graph.forEach(node => {
colors.add(node.color);
const neighborCount = getNeighbors(node).length;
maxNeighborCount = Math.max(neighborCount, maxNeighborCount);
});
return colors.size <= maxNeighborCount + 1;
}
//tested
const allNodesHaveColor = graph => {
return graph.filter(node => node.color === none).length < 1;
}
//tested
const getNeighbors = node => {
return [...node.neighbors];
}
/*
GET NEIGHBORS
*/
// When 0 neighbours, get neighbours should return empty array
//arrange
var expected = 0;
var node = new Node(7);
//act
let actual = getNeighbors(node).length;
//assert
console.log(actual == expected);
//When 1 neighbor, get neighbors returns 1 element
//arrange
expected = new Node(5);
node = new Node(1);
node.neighbors.add(expected);
//act
actual = getNeighbors(node);
//assert
console.log(actual.length === 1);
console.log(actual[0].value === expected.value)
//When 2 neighbor, get neighors returns both
expectedA = new Node(5);
expectedB = new Node(4);
node = new Node(1);
node.neighbors.add(expectedA);
node.neighbors.add(expectedB);
//act
actual = getNeighbors(node);
//assert
console.log(actual.length === 2);
console.log(actual[0].value === expectedA.value)
console.log(actual[1].value === expectedB.value)
/*
ALL COLORED
*/
//When all colored, get neighors returns true
expectedA = new Node(5);
expectedA.color = "blue";
expectedB = new Node(4);
expectedB.color = "red";
graph = [expectedA, expectedB];
//act
actual = allNodesHaveColor(graph);
//assert
console.log(actual == true);
//When one not colored, get neighors returns false
expectedA = new Node(5);
expectedA.color = "blue";
expectedB = new Node(4);
graph = [expectedA, expectedB];
//act
actual = allNodesHaveColor(graph);
//assert
console.log(actual == false);
/*
CORRECT COLOR COUNT
*/
//When 3 neigbors and 4 colors, returns true
a = new Node(5);
b = new Node(4);
c = new Node(3);
node = new Node(2);
a.color = blue;
b.color = red;
c.color = yellow;
node.color = green;
node.neighbors.add(a);
node.neighbors.add(b);
node.neighbors.add(c);
graph = [node, a, b, c];
//act
actual = hasCorrectNumberColors(graph);
//assert
console.log(actual);
//When 2 neigbors and 4 colors, returns true
a = new Node(5);
b = new Node(4);
c = new Node(3);
node = new Node(2);
a.color = blue;
b.color = red;
c.color = yellow;
node.color = green;
node.neighbors.add(a);
node.neighbors.add(b);
graph = [node, a, b, c];
//act
actual = hasCorrectNumberColors(graph);
//assert
console.log(actual === false);
/*
COLOUR IS SAME AS NEIGHBOR
*/
//When colors same, returns true
a = new Node(5);
b = new Node(4);
node = new Node(2);
a.color = blue;
b.color = red;
node.color = blue;
node.neighbors.add(a);
node.neighbors.add(b);
graph = [node, a, b];
//act
actual = isColorMatchNeighbor(graph);
//assert
console.log(actual);
//When colors not clashing, returns false
a = new Node(5);
b = new Node(4);
node = new Node(2);
a.color = blue;
b.color = red;
node.color = green;
node.neighbors.add(a);
node.neighbors.add(b);
graph = [node, a, b];
//act
actual = isColorMatchNeighbor(graph);
//assert
console.log(actual === false);
//Tests
//Graph with single node
//Arrange
//let a = new GraphNode("a");
//Act
//actual = colorGraph([a], colours);
//Assert
// a = new GraphNode("a");
// var b = new GraphNode("b");
// var c = new GraphNode("c");
// a.neighbors.add(b);
// b.neighbors.add(a);
// c.neighbors.add(b);
// b.neighbors.add(c);
// var graph = [a, b, c];
<file_sep>/katas/interview/arrays/calendar.js
function mergeRanges(meetings) {
const allMeetingTimes = [];
const meetingInProgress = 1;
meetings.forEach(meeting => { // O(n)
//for each meeting, mark the duration in the allMeetingTimes array
for(let i = meeting.startTime; i < meeting.endTime; i++) {
allMeetingTimes[i] = meetingInProgress;
}
});
const result = [];
let singleMeeting = {};
for(let i = 0; i < allMeetingTimes.length; i++){ //O(n)
const previousMeeting = allMeetingTimes[i - 1] || 0;
const nextMeeting = allMeetingTimes[i + 1] || 0;
const isMeeting = allMeetingTimes[i] === meetingInProgress;
const isStart = previousMeeting === 0;
const isEnd = nextMeeting === 0;
if(isMeeting && isStart) {
singleMeeting.startTime = i;
}
if(isMeeting && isEnd){
singleMeeting.endTime = i + 1;
result.push(singleMeeting);
singleMeeting = {};
}
}
return result;
}
// Tests
let desc = 'meetings overlap';
let actual = mergeRanges([{ startTime: 1, endTime: 3 }, { startTime: 2, endTime: 4 }]);
let expected = [{ startTime: 1, endTime: 4 }];
assertArrayEquals(actual, expected, desc);
desc = 'meetings touch';
actual = mergeRanges([{ startTime: 5, endTime: 6 }, { startTime: 6, endTime: 8 }]);
expected = [{ startTime: 5, endTime: 8 }];
assertArrayEquals(actual, expected, desc);
desc = 'meeting contains other meeting';
actual = mergeRanges([{ startTime: 1, endTime: 8 }, { startTime: 2, endTime: 5 }]);
expected = [{ startTime: 1, endTime: 8 }];
assertArrayEquals(actual, expected, desc);
desc = 'meetings stay separate';
actual = mergeRanges([{ startTime: 1, endTime: 3 }, { startTime: 4, endTime: 8 }]);
expected = [{ startTime: 1, endTime: 3 }, { startTime: 4, endTime: 8 }];
assertArrayEquals(actual, expected, desc);
desc = 'multiple merged meetings';
actual = mergeRanges([
{ startTime: 1, endTime: 4 },
{ startTime: 2, endTime: 5 },
{ startTime: 5, endTime: 8 },
]);
expected = [{ startTime: 1, endTime: 8 }];
assertArrayEquals(actual, expected, desc);
desc = 'meetings not sorted';
actual = mergeRanges([
{ startTime: 5, endTime: 8 },
{ startTime: 1, endTime: 4 },
{ startTime: 6, endTime: 8 },
]);
expected = [{ startTime: 1, endTime: 4 }, { startTime: 5, endTime: 8 }];
assertArrayEquals(actual, expected, desc);
desc = 'oneLongMeetingContainsSmallerMeetings';
actual = mergeRanges([
{ startTime: 1, endTime: 10 },
{ startTime: 2, endTime: 5 },
{ startTime: 6, endTime: 8 },
{ startTime: 9, endTime: 10 },
{ startTime: 10, endTime: 12 }
]);
expected = [
{ startTime: 1, endTime: 12 }
];
assertArrayEquals(actual, expected, desc);
desc = 'sample input';
actual = mergeRanges([
{ startTime: 0, endTime: 1 },
{ startTime: 3, endTime: 5 },
{ startTime: 4, endTime: 8 },
{ startTime: 10, endTime: 12 },
{ startTime: 9, endTime: 10 },
]);
expected = [
{ startTime: 0, endTime: 1 },
{ startTime: 3, endTime: 8 },
{ startTime: 9, endTime: 12 },
];
assertArrayEquals(actual, expected, desc);
function assertArrayEquals(a, b, desc) {
const arrayA = JSON.stringify(a);
const arrayB = JSON.stringify(b);
if (arrayA !== arrayB) {
console.log(`${desc} ... FAIL: ${arrayA} != ${arrayB}`)
} else {
console.log(`${desc} ... PASS`);
}
}<file_sep>/dataStructures/linkedList.js
import Node from './node.js'
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
push(value) { //O(1)
var node = new Node(value);
if(!this.head) {
this.head = node;
this.tail = node; //can't have a next, because only 1
} else {
this.tail.next = node;
this.tail = node;
}
}
shift(){
if(!this.head) return null;
const result = this.head;
if(this.head === this.tail){
this.head = null;
this.tail = null;
} else {
this.head = this.head.next;
}
return result;
}
//unshift? push to start
contains(value) { //O(n)
const recurse = (node, value) => {
if(!node)
return false;
if(node.value === value)
return true;
return recurse(node.next, value)
}
return recurse(this.head, value);
}
deleteValue(value){ //assumes unique ??
if(!this.head) return false;
if(this.head.value === value) {
if(this.head === this.tail){ //if the list is only 1 item long
this.head = null;
this.tail = null;
} else {
this.head = this.head.next;
}
return true;
}
const recurse = (node, value) => {
if(!node) return false;
//console.log("plain node")
//console.log(node);
const nextNode = node.next;
//console.log("next node")
//console.log(nextNode);
if(!nextNode) return false; //reached tail with no match
if(nextNode.value === value){
node.next = nextNode.next;
if(nextNode === this.tail) {
this.tail = node;
}
return true;
}
return recurse(nextNode, value)
}
return recurse(this.head, value);
}
}
export default LinkedList;<file_sep>/dataStructures/array.js
export class ArrayList{
constructor(){
this.length = 0;
this.data = {};
}
push(value) {
if(!value) return;
this.data[this.length] = value;
this.length++;
}
pop() {
const result = this.get(this.length -1)
this.delete(this.length - 1);
return result;
}
get(index) {
return this.data[index];
}
delete(index) {
if(index > this.length) return;
for (let i = index; i < this.length; i++)
{
this.data[i] = this.data[i+1];
}
this.data[this.length-1] = null;
this.length--;
}
//[a,b,c,d]
//collapse 1
//first loop
//i = 1, length = 4
//whatever is at 1 becomes what is at 2
//second last loop, whatever is at 2 becomes 3
//last loop
//whatever is at 3, becomes null
//so final result is [a,c,d,null]
//then we delete the end
}<file_sep>/tests/dataStructuresTests/hashTable/hashCode.test.js
import {generateHashCode, HashTable} from '../../../dataStructures/hashTable.js';
test("WhenSameInput_ThenSameOutput", () => {
//Arrange
const firstInput = "foobar";
const secondInput = "foobar";
//Act
const firstOutput = generateHashCode(firstInput,10);
const secondOutput = generateHashCode(secondInput,10);
//Assert
expect(firstOutput).toEqual(secondOutput);
});
test("WhenDifferentInput_ThenDifferentOutput", () => {
//Arrange
const firstInput = "foo";
const secondInput = "bar";
//Act
const firstOutput = generateHashCode(firstInput,256);
const secondOutput = generateHashCode(secondInput,256);
//Assert
expect(firstOutput != secondOutput).toBe(true);
});
test("WhenMaxValue_HashLessThanMaxValue", () => {
//Arrange
const firstInput = "a much longer strings than the other ones";
//Act
const firstOutput = generateHashCode(firstInput,2);
//Assert
expect(firstOutput).toBeLessThan(2);
});
//Brian Holt tests
it('add and check', () => {
const table = new HashTable(100); //this hash table doesn't handle collisions
table.add('hi');
table.add('this is fun');
table.add('another thing');
expect(table.check('hi')).toEqual(true);
expect(table.check('this is fun')).toEqual(true);
expect(table.check('another thing')).toEqual(true);
expect(table.check('ih')).toEqual(false);
expect(table.check('not in the list')).toEqual(false);
expect(table.check('also not in the list')).toEqual(false);
});<file_sep>/algorithms/traversal/dfs.js
const preOrderTraverse = (node, array) => {
if(!node) return array;
array.push(node.value);
preOrderTraverse(node.left, array);
preOrderTraverse(node.right, array);
return array;
}
const inOrderTraverse = (node, array) => {
if(!node) return array;
inOrderTraverse(node.left, array);
array.push(node.value);
inOrderTraverse(node.right, array);
return array;
}
const postOrderTraverse = (node, array) => {
if(!node) return array;
postOrderTraverse(node.left, array);
postOrderTraverse(node.right, array);
array.push(node.value);
return array;
}
export {preOrderTraverse, inOrderTraverse, postOrderTraverse};<file_sep>/katas/pramp/pairsWithDifference.js
function findPairsWithGivenDifference(arr, k) {
if(k === 0) return [];
const seen = new Set();
const result = [];
arr.forEach(number => {
const target = number - k;
seen.add(target);
});
arr.forEach(number => {
if(seen.has(number)){
const original = number + k;
const pair = [original, number]
result.push(pair);
}
})
return result
}
const example = [0, -1, -2, 2, 1];
const expected = [ [ 1, 0 ], [ 0, -1 ], [ -1, -2 ], [ 2, 1 ] ]
const result = findPairsWithGivenDifference(example, 1);
console.log(result.toString() === expected.toString());
const secondExample = [1, 7, 5, 3, 32, 17, 12];
const secondResult = findPairsWithGivenDifference(secondExample, 17);
console.log(secondResult.length === 0);<file_sep>/katas/jobs/getFirst.js
function first_by_key(key, order, records) {
const completeRecords = addMissingRecords(key, records);
const matchingIndex = getMatchingIndex(key, order, completeRecords);
return records[matchingIndex];
}
function min_by_key(key, records) {
return first_by_key(key, "asc", records);
}
// Helper functions
function addMissingRecords(key, records){
const implicitRecord = {[key]: 0};
return records.map(record => key in record ? record : implicitRecord);
}
function getMatchingIndex(key, order, input){
let matchingIndex = 0;
const callback = getComparisonFunction(order);
input.reduce((current, next, index) => {
const winner = compare(current, next, callback, key);
const isNewAnswer = winner[key] !== current[key];
if(isNewAnswer) matchingIndex = index;
return winner;
});
return matchingIndex;
}
function getComparisonFunction(order){
const isAscending = order === "asc";
return isAscending ? Math.min : Math.max;
}
function compare(first, second, callback, key) {
const result = callback(first[key], second[key]);
const isFirst = result === first[key];
return isFirst ? first : second;
}
// Tests
function test_first_by_key() {
let example1 = [{ a: 1 }],
example2 = [{ b: 1 }, { b: -2 }, { a: 10 }],
example3 = [{}, { a: 10, b: -10 }, {}, { a: 3, c: 3 }]
assert_equal(first_by_key("a", "asc", example1), example1[0])
assert_equal(first_by_key("a", "asc", example2), example2[0])
assert_equal(first_by_key("a", "desc", example2), example2[2])
assert_equal(first_by_key("b", "asc", example2), example2[1])
assert_equal(first_by_key("b", "desc", example2), example2[0])
assert_equal(first_by_key("a", "desc", example3), example3[1])
console.log("Finished: test_first_by_key")
}
test_first_by_key()
function test_min_by_key() {
let example1 = [{ a: 1, b: 2 }, { a: 2 }],
example2 = [{ a: 2 }, { a: 1, b: 2 }],
example3 = [{}],
example4 = [{ a: -1 }, { b: -1 }]
assert_equal(min_by_key("a", example1), example1[0])
assert_equal(min_by_key("a", example2), example2[1])
assert_equal(min_by_key("b", example1), example1[1])
assert_equal(min_by_key("a", example3), example3[0])
assert_equal(min_by_key("b", example4), example4[1])
console.log("Finished: test_min_by_key")
}
test_min_by_key()
// Test helper
function assert_equal(actual, expected) {
if (JSON.stringify(actual) != JSON.stringify(expected)) {
console.log(`Assertion failed: ${JSON.stringify(actual)} does not match expected ${JSON.stringify(expected)}`)
//console.trace()
}
} <file_sep>/tests/dataStructuresTests/array/pop.test.js
import {ArrayList} from '../../../dataStructures/array.js'
test('Pop_WhenArrayHasThreeElements_ReturnsCorrectData', () => {
//Arrange
var array = new ArrayList();
array.push(1);
array.push(2);
array.push(3);
//Act
const actual = array.pop();
//Assert
expect(actual).toEqual(3);
expect(array.data[3]).toBeNull;
});
test('Pop_WhenArrayHasOneElement_ReturnsCorrectData', () => {
//Arrange
var array = new ArrayList();
array.push(1);
//Act
const actual = array.pop();
//Assert
expect(actual).toEqual(1);
expect(array.data).toBeNull;
});
test('Pop_WhenArrayIsEmpty_ReturnsCorrectData', () => {
//Arrange
var array = new ArrayList();
//Act
const actual = array.pop();
//Assert
expect(actual).toBeNull;
expect(array.data).toBeNull;
});
<file_sep>/katas/interview/howManySums.js
/* Given an number and an array
Find how many combinations of numbers exist that add up to the number
For example, given 16 and [2,4,6,10]
The function should return 2. Because there is [6,10] and also [2,4,10]
*/
//create an array n items long
//when see a number, add it to array O(n)
//when see another number, check if n - number exists in the array
//
//10, [2,4,6]
const findSums = (target, numbers) => {
if(target === 0) return true;
if(numbers.length === 0) return false;
[first, ...rest] = numbers;
return findSums(target - first, rest)
|| findSums(target, rest);
}
//Arrange
const emptyInput = [];
const oneElementInput = [1];
const twoElementsInput = [2,2];
const threeElementsInput = [2,4,6];
const fourElementsInput = [2,4,6,10];
//Act
// const empty = findSums(5, emptyInput);
// const oneExists = findSums(1, oneElementInput);
// const oneNotExists = findSums(2, oneElementInput);
// const twoExists = findSums(2, twoElementsInput); //
// const twoNotExists = findSums(3, twoElementsInput);
// const twoExistsSum = findSums(4, twoElementsInput);
// const threeNotExists = findSums(11, threeElementsInput);
const threeExistsOnce = findSums(10, threeElementsInput);
// const threeExistsTwice = findSums(6, threeElementsInput);
// const threeRequiresThreeInts = findSums(16, fourElementsInput);
//Assert
// console.log(empty === false)
// console.log(oneExists === true);
// console.log(oneNotExists === false);
// console.log(twoExists === true);
// console.log(twoNotExists === false);
// console.log(twoExistsSum === true);
// console.log(threeNotExists === false);
console.log(threeExistsOnce);
// console.log(threeExistsTwice === true);
// console.log(threeRequiresThreeInts);<file_sep>/katas/pramp/busiestMallTime.js
function findBusiestPeriod(data) {
const periods = data;
let existingCount = 0;
let maxCount = 0;
let matchingIndex = 0;
periods.forEach((currentPeriod, index) => {
let currentPeriodTimeStamp = currentPeriod[0];
let currentPeriodCount = currentPeriod[1];
let currentPeriodAction = currentPeriod[2];
let nextPeriod = periods[index+1] || [];
let nextPeriodTimestamp = nextPeriod[0];
existingCount = updateCount(existingCount, currentPeriodCount, currentPeriodAction);
if(isEndOfSection(currentPeriodTimeStamp, nextPeriodTimestamp)) {
if(isNewMax(existingCount, maxCount)){
maxCount = existingCount;
matchingIndex = index;
}
}
});
const matchingPeriod = data[matchingIndex];
const matchingTimeStamp = matchingPeriod[0];
return matchingTimeStamp;
}
function isNewMax(existingCount, maxCount) {
return existingCount > maxCount;
}
function isEndOfSection(currentTimeStamp, nextTimeStamp) {
return currentTimeStamp !== nextTimeStamp;
}
function updateCount(previous, current, action){
const isEnter = action === 1;
return isEnter ? previous + current : previous - current;
}
let input = [
// 0
[1487799425, 14, 1], // +14
[1487799425, 4, 0], // -4
[1487799425, 2, 0], // -2
// 8
[1487800378, 10, 1], // +10
// 18
[1487801478, 18, 0], // -18
[1487801478, 18, 1], // +18
//18
[1487901013, 1, 0], // -1
//17
[1487901211, 7, 1], // +7
[1487901211, 7, 0] // -7
] //17
let expected = 1487800378;
let actual = findBusiestPeriod(input);
console.log(expected === actual);
input = [[1487799426,21,1]]
expected = 1487799426
actual = findBusiestPeriod(input);
console.log(expected === actual);
input = [[1487799425,21,0],[1487799427,22,1],[1487901318,7,0]]
expected = 1487799427
actual = findBusiestPeriod(input);
console.log(expected === actual);
input = [[1487799425,21,1],[1487799425,4,0],[1487901318,7,0]]
expected = 1487799425
actual = findBusiestPeriod(input);
console.log(expected === actual);
input = [[1487799425,14,1],[1487799425,4,0],[1487799425,2,0],[1487800378,10,1],[1487801478,18,0],[1487801478,18,1],[1487901013,1,0],[1487901211,7,1],[1487901211,7,0]]
expected = 1487800378
actual = findBusiestPeriod(input);
console.log(expected === actual);
input = [[1487799425,14,1],[1487799425,4,1],[1487799425,2,1],[1487800378,10,1],[1487801478,18,1],[1487901013,1,1],[1487901211,7,1],[1487901211,7,1]]
expected = 1487901211
actual = findBusiestPeriod(input);
console.log(expected === actual);
input = [[1487799425,14,1],[1487799425,4,0],[1487799425,2,0],[1487800378,10,1],[1487801478,18,0],[1487801478,19,1],[1487801478,1,0],[1487801478,1,1],[1487901013,1,0],[1487901211,7,1],[1487901211,8,0]]
expected = 1487801478
actual = findBusiestPeriod(input);
console.log(expected === actual);
<file_sep>/tests/dataStructuresTests/array/get.test.js
import {ArrayList} from '../../../dataStructures/array.js'
test('Get_WhenIndexExists_ReturnsCorrectData', () => {
//Arrange
var array = new ArrayList();
array.push(1);
//Act
const actual = array.get(0);
//Assert
expect(actual).toBe(1);
expect(array.data[0]).toBe(1);
});
test('Get_WhenIndexExists_ReturnsCorrectData', () => {
//Arrange
var array = new ArrayList();
array.push(1);
//Act
const actual = array.get(10);
//Assert
expect(actual).toBeNull;
expect(array.data[0]).toBe(1);
});
|
3fba8facb9c167c1aecf2763249f3b894b4b4bf8
|
[
"JavaScript"
] | 40
|
JavaScript
|
thomasdane/algoDataStructures
|
c0dcc2b4970743d40326e02f44cb3e5a8ee1fd5d
|
55b2138092ad276fa427e2d66e5ddfd97c910228
|
refs/heads/master
|
<file_sep>//默认每页显示数据行数
var pageLimit = 20; //用户表行数
//资源搜索
var store_login=new Ext.data.Store({
proxy:new Ext.data.HttpProxy({url:'../inside.php?t=json&m=login&f=search',method:"POST"}),
reader:new Ext.data.JsonReader({
tatalProperty:'total',
root:'data'
},[
{name:'uid'},
{name:'username'},
{name:'subname'},
{name:'status'},
{name:'orgname'},
{name:'orgcode'},
{name:'rolename'},
{name:'logintime'},
{name:'remark'}
])
});
//定义列表
var cm_login=new Ext.grid.ColumnModel([
{header:'公告',dataIndex:'logintime'},
{header:'时间',dataIndex:'action',width:20,renderer:function(value, cellMeta, record, rowIndex, columnIndex, store){
return "<a href='#' title='点击修改信息' onclick=\"loginedt('"+rowIndex+"');\">修改</a>";
}
}
]);
//创建grid
var grid_source=new Ext.grid.GridPanel({
//title:'更新公告',
region:"north",
//斑马颜色
stripeRows:true,
height:150,
store:store_login,
loadMask: {msg:'加载数据中,请等待......'},//
cm:cm_login,
//距离设置
viewConfig:{
forceFit:true
},
bbar:new Ext.PagingToolbar({
pageSize:pageLimit,
store:store_login,
displayInfo:true,
displayMsg:'显示第{0}条到{1}条记录,一共{2}条',
emptyMsg:'没有记录'
})
});<file_sep>var add_win; //添加窗口
var dismiss_win; //驳回窗口
var _id = ''; //判断是添加还是修改
var add_form_panel = new Ext.form.FormPanel({
region: 'center',
hideLabels: true,
bodyStyle: 'padding: 10px',
height: 60,
items: [
{ // 第一行
xtype: 'compositefield',
items: [
{xtype: 'displayfield', value: '标 题:'},
{xtype: 'textfield', id: 'title', width: 200},
{xtype: 'displayfield', value: ' <font color=red>*</font>'},
]
}, { // 第二行
xtype: 'compositefield',
items: [
{xtype: 'displayfield', value: '内 容:'},
{xtype: "textarea", fieldLabel: "内 容:", id: "content", width: 350, height: 120},
{xtype: 'displayfield', value: ' <font color=red>*</font>'},
]
}
],
buttons: [{
text: "确定",
handler: function() {
if (checkinput()) {
var _form = this.ownerCt.ownerCt.getForm();
if (_id) {
//修改
_form.submit({
url: '../inside.php?t=json&m=' + controlName + '&f=update',
params: {
id: _id,
},
waitMsg: 'Saving Data...',
success: function(form, action) {
add_win.hide();
_store.load({
callback: function() {
crow = _sm.getSelected().data;
initBtn(crow);
}
});
Ext.MessageBox.alert('提示', Ext.decode(action.response.responseText).msg);
},
failure: function(form, action) {
Ext.MessageBox.alert('提示', Ext.decode(action.response.responseText).msg);
}
});
} else {
//新增
_form.submit({
url: '../inside.php?t=json&m=' + controlName + '&f=add',
params: {},
waitMsg: 'Saving Data...',
success: function(form, action) {
add_win.hide();
_store.load();
initBtn();
Ext.MessageBox.alert('提示', Ext.decode(action.response.responseText).msg);
},
failure: function(form, action) {
Ext.MessageBox.alert('提示', Ext.decode(action.response.responseText).msg);
}
});
}
}
}
}, {
text: "取消",
handler: function() {
add_win.hide();
}
}]
});
//主窗体
if (!add_win) {
add_win = new Ext.Window({
layout: "border",
width: 550,
height: 270,
title: '订单信息',
closeAction: 'hide',
plain: true,
items: [add_form_panel]
});
}
var dismiss_form_panel = new Ext.form.FormPanel({
region: 'center',
hideLabels: true,
bodyStyle: 'padding: 10px',
height: 60,
items: [
{ // 第一行
xtype: 'compositefield',
items: [
{xtype: 'displayfield', value: '驳回原因:'},
{xtype: 'textfield', id: 'dismiss_reason', width: 280},
{xtype: 'displayfield', value: ' <font color=red>*</font>'},
]
}
],
buttons: [{
text: "确定",
handler: function() {
if (Ext.getCmp('dismiss_reason').getValue() == '') {
Ext.MessageBox.alert('提示', '驳回原因必填');
return false;
}
var _form = dismiss_form_panel.getForm();
_form.submit({
url: '../inside.php?t=json&m=' + controlName + '&f=statusTo_1',
params: {
id: crow.id,
updatetime: crow.updatetime
},
waitMsg: 'Saving Data...',
success: function(form, action) {
dismiss_win.hide();
initBtn();
_store.load({
callback: function(){
crow = _sm.getSelected().data;
initBtn(crow);
}
});
Ext.MessageBox.alert('提示', Ext.decode(action.response.responseText).msg);
},
failure: function(form, action) {
Ext.MessageBox.alert('提示', Ext.decode(action.response.responseText).msg);
}
});
}
}, {
text: "取消",
handler: function() {
dismiss_win.hide();
}
}]
});
//主窗体
if (!dismiss_win) {
dismiss_win = new Ext.Window({
layout: "border",
width: 400,
height: 130,
title: '驳回原因',
closeAction: 'hide',
modal: true,
plain: true,
items: [dismiss_form_panel]
});
}
//修改
function showUpdate() {
var row = crow;
Ext.getCmp('title').setValue(row.title);
Ext.getCmp('content').setValue(row.content);
showAddUpdateWin(row.order_id);
}
//添加
function showAdd() {
showAddUpdateWin();
}
function showAddUpdateWin(id) {
if (id) {
_id = id;
} else {
_id = '';
}
if (!_id) {
Ext.getCmp('title').setValue('');
Ext.getCmp('content').setValue('');
}
add_win.show();
}
function showStatusTo1() {
var row = crow;
Ext.MessageBox.confirm('审核', '确定要审核' + row.user_name + '?', function showResult(btn) {
if (btn == 'yes') {
Ext.Ajax.request({
url: '../inside.php?t=json&m=' + controlName + '&f=statusTo1',
method: 'POST',
params: {
id: row.id,
updatetime: row.updatetime
},
success: function(resp, opt) {
_store.load({
callback: function(){
crow = _sm.getSelected().data;
initBtn(crow);
}
});
var r = Ext.decode(resp.responseText);
Ext.MessageBox.alert('提示', r.msg);
}
});
}
});
}
function showStatusTo_1() {
var row = crow;
Ext.MessageBox.confirm('驳回', '确定要驳回' + row.user_name + '?', function showResult(btn) {
if (btn == 'yes') {
Ext.getCmp('dismiss_reason').setValue('');
dismiss_win.show();
}
});
}
function showStatusTo2() {
var row = crow;
Ext.MessageBox.confirm('结算', '确定要结算' + row.user_name + '?', function showResult(btn) {
if (btn == 'yes') {
Ext.Ajax.request({
url: '../inside.php?t=json&m=' + controlName + '&f=statusTo2',
method: 'POST',
params: {
id: row.id,
updatetime: row.updatetime
},
success: function(resp, opt) {
_store.load({
callback: function(){
crow = _sm.getSelected().data;
initBtn(crow);
}
});
var r = Ext.decode(resp.responseText);
Ext.MessageBox.alert('提示', r.msg);
}
});
}
});
}
//导出
function showExport(){
/*var start_time = Ext.getCmp("s_start_time").getValue();
var end_time = Ext.getCmp("s_end_time").getValue();
start_time = Ext.isDate(start_time) ? start_time.dateFormat('Y-m-d') : start_time;
end_time = Ext.isDate(end_time) ? end_time.dateFormat('Y-m-d') : end_time;
Ext.Ajax.request({
url:'../inside.php?t=json&m=job_nianshen&f=export',
method:'post',
params:{
get_num: true,
job_no: Ext.getCmp("s_job_no").getValue(),
job_source_type: Ext.getCmp("s_job_source_type").getValue(),
job_source_no: Ext.getCmp("s_job_source_no").getValue(),
customer_name: Ext.getCmp("s_customer_name").getValue(),
serv_area: Ext.getCmp("s_province").getValue(),//Story #25392
serv_city: Ext.getCmp("s_city").getValue(),//Story #25392
trucks: Ext.getCmp("s_trucks").getValue(),
serv_type: Ext.getCmp("s_serv_type").getValue(),
status: Ext.getCmp("s_status").getValue(),
time_type: Ext.getCmp("s_time_type").getValue(),
start_time: start_time,
end_time: end_time
},
success: function(resp,opts){
var num = Ext.decode(resp.responseText).num;*/
var num = grid_list.getStore().getTotalCount();
if(num > 0){
var pageNum = parseInt(num/5000) + 1;
if(num < 5000){
message = '本次导出共'+num+'条提现记录,确认导出吗?'
}else{
message = '本次导出共'+num+'条提现记录,将分为 '+pageNum+' 个文件,确认导出吗?'
}
Ext.MessageBox.confirm('提现详情列表导出',message,function showResult(btn){
if(btn == 'yes'){
for(var i=1; i<=pageNum; i++){
window.open('/inside.php?t=json&m=' + controlName + '&f=export'
+'&user_name=' + Ext.getCmp("s_user_name").getValue()
+'&page='+ i +'');
}
}
});
}else{
return false;
}
/*},
failure: function(resp,opts){
Ext.MessageBox.alert('提示','数据量太大了!');
}
});*/
}
//表单验证
function checkinput() {
var msg = '';
if (Ext.getCmp('title').getValue() == '') {
msg += (msg ? '<br>' : '') + '「标题」不能为空';
}
if (Ext.getCmp('content').getValue() == '') {
msg += (msg ? '<br>' : '') + '「内容」不能为空';
}
if (msg == '') {
return true;
} else {
Ext.MessageBox.alert('提示!', msg);
return false;
}
}<file_sep> var pagesize = 50;
var controlName = 'user';
//获取各户列表信息
var userStore = new Ext.data.Store({
proxy:new Ext.data.HttpProxy({url:'../inside.php?t=json&m='+ controlName +'&f=search',method:"POST"}),
reader:new Ext.data.JsonReader(
{
totalProperty:'total',
root:'data'
},
[
'id','user_name','true_name','last_login_time','createtime','user_email','remark','user_mobile', 'role_id','role_id','role_name','status','is_admin', 'updatetime', 'type',
'user_code', 'level_name', 'all_child_num', 'child_num'
]
),
baseParams:{start:0, limit:pagesize},
listeners:
{
'beforeload' :function()
{
//top.js 搜索条件的ID
this.baseParams.user_name = Ext.getCmp("user_name").getValue();//用户名
this.baseParams.true_name = Ext.getCmp("true_name").getValue();//姓名
this.baseParams.user_role = Ext.getCmp("user_role").getValue();//角色
this.baseParams.type = Ext.getCmp("search_type").getValue();// BOSSSM-391 by csj 2016/2/25
}
}
});
//获取角色信息
var userRole =new Ext.data.Store({
proxy:new Ext.data.HttpProxy({url:'../inside.php?t=json&m='+ controlName +'&f=getRole',method:"POST"}),
autoLoad: true ,
reader:new Ext.data.JsonReader({
tatalProperty:'',
root:'data'
},['id','role_name','role_id'])
});
<file_sep>var add_win;//添加窗口
var user_id;//gsp中用户id Story #20061 GSP使用ldap服务成功 by lixiaoli
var uid;//ldap中用户uid
var add_form_panel = new Ext.form.FormPanel({
region : 'center',
hideLabels : true,
bodyStyle : 'padding: 10px',
height : 60,
items :
[
{// 第一行
xtype : 'compositefield',
items :
[
{
xtype: 'displayfield',
value: '旧密码:'
},
{
inputType:'password',
xtype : 'textfield',
id : 'old_pwd',
width : 200,
style : 'margin-left :12px;'
},
{xtype: 'displayfield',style : 'margin-left :12px;',value: ' <font color=red>*</font>'},
]
},
{// 第二行
xtype : 'compositefield',
items :
[
{
xtype: 'displayfield',
value: '新密码:'
},
{
inputType:'password',
xtype:'textfield',
id : 'new_pwd',
width : 200,
style : 'margin-left :12px;'
},
{xtype: 'displayfield',style : 'margin-left :12px;',value: ' <font color=red>*</font>'},
]
},
{// 第三行
xtype : 'compositefield',
items :
[
{
xtype: 'displayfield',
value: '确认密码:'
},
{
inputType:'password',
xtype : 'textfield',
id : 'again_new_pwd',
width : 200
},
{xtype: 'displayfield',value: ' <font color=red>*</font>'},
]
},
],
buttons:[{
text:"修改",
handler:function()
{
if(check_input())
{ //Story #20061 GSP使用ldap服务成功 by lixiaoli
Ext.Ajax.request({
url: '../inside.php?t=json&m=user&f=updatePwd',
method: 'post',
params: {
user_id: user_id,
uid: uid,
old_pwd: Ext.getCmp('old_pwd').getValue(),
new_pwd: Ext.getCmp('new_pwd').getValue(),
again_new_pwd: Ext.getCmp('again_new_pwd').getValue()
},
success: function sFn(response, options) {
if (Ext.decode(response.responseText).msg == 1) {
Ext.Msg.alert('提示', '旧密码错误,请重新输入!');
} else if (Ext.decode(response.responseText).msg == 2) {
Ext.Msg.alert('提示', '新密码跟确认密码不一致,请重新输入!');
} else if (Ext.decode(response.responseText).msg == 3) {
Ext.Msg.alert('提示', '密码修改成功!');
Ext.Ajax.request({
url:'/inside.php?t=json&m=login&f=logout',
success: function(resp,opts) {
window.location.href = '/index.html';
}
});
} else if (Ext.decode(response.responseText).msg == 4) {
Ext.Msg.alert('提示', '密码修改失败!');
pwd_win.hide();
} else if (Ext.decode(response.responseText).msg == -1){
Ext.Msg.alert('提示', '系统中没有用户【'+uid+'】!');
pwd_win.hide();
}
}
});
}
}
},{
text:"取消",
handler: function()
{
add_win.hide();
}
}]
});
//主窗体
if(!add_win)
{
add_win = new Ext.Window({
layout:"border",
width:350,
height:205,
title:'修改密码',
closeAction:'hide',
plain: true,
modal:true,//modal:true为模式窗口,后面的内容都不能操作,默认为false
items:[add_form_panel]
});
}
/**
* 修改密码
* id用户ID
*/
function updatePwd(id, user_name)
{
user_id = id;
uid = user_name;
Ext.getCmp('old_pwd').setValue('');
Ext.getCmp('new_pwd').setValue('');
Ext.getCmp('again_new_pwd').setValue('');
add_win.show();
}
//表单验证
//Story #20061 GSP使用ldap服务成功 by lixiaoli
function check_input()
{
var flag = true;
var msg = '';
var old_pwd = Ext.getCmp('old_pwd').getValue();
var new_pwd = Ext.getCmp('new_pwd').getValue();
var again_new_pwd = Ext.getCmp('again_new_pwd').getValue();
if (new_pwd != again_new_pwd) {
msg = '新密码和确认密码不一致';
flag = false;
}
if (again_new_pwd == '') {
msg = '确认密码不能为空';
flag = false;
}
if (new_pwd != '' && new_pwd.length < 6 || new_pwd.length > 16) {
msg = '新密码长度在6到16位之间';
flag = false;
}
if (new_pwd == '') {
msg = '新密码不能为空';
flag = false;
}
if (old_pwd == '') {
msg = '旧密码不能为空';
flag = false;
}
if (flag == false) {
Ext.MessageBox.alert('提示', msg);
}
return flag;
}<file_sep>//var synctimer = null; Story #29096 去掉自动访问连接
//var abc=0,//tipw=[];
//主功能区
var main_panel = new Ext.TabPanel({
xtype: "tabpanel",
region: "center",
title: "内部系统"
});
function sys_show_tab(tabname) {
if (Ext.getCmp(tabname)) {
var n = main_panel.getComponent('treenode' + tabname);
if (!n) {
var n = main_panel.add({
'id': 'treenode' + Ext.getCmp(tabname).id,
'title': Ext.getCmp(tabname).title,
layout: "border",
items: [Ext.getCmp(tabname)],
closable: true
});
main_panel.setActiveTab(n);
} else {
main_panel.setActiveTab(n);
}
} else {
alert(tabname + '模块不存在,请联系管理员');
}
}
/*
* 目录树
* */
var main_tree = new Ext.tree.TreePanel({
region: 'west',
title: '功能菜单',
width: 200,
split: true,
//animate:true,//动画
autoScroll: true,
autoHeight: false,
collapsible: true, //Story #30977 左侧菜单加箭头
collapsed: true,
useArrows: true,
rootVisable: true, //不显示根节点
root: new Ext.tree.TreeNode({
id: 'root',
text: 'ECSA',
cls: 'folder',
draggable: false,
expanded: true
})
});
Ext.onReady(function() {
Ext.Ajax.request({
url: 'inside.php?t=json&m=login&f=getConfig',
method: 'post',
success: function(resp, opts) {
var respText = Ext.util.JSON.decode(resp.responseText);
//console.log(respText);
if (!respText.id) {
window.location.href = '/login/';
//app_login_show_loginfrom(window.location.pathname);//当前页面跳出登录框.登录后就跳回
} else {
_c_var_user = respText; //保存到公共变量
new Ext.Viewport({
enableTabScroll: true,
layout: "border",
items: [
main_tree,
main_panel //操作主界面
]
});
main_tree.setTitle(respText.true_name + '(' + respText.user_name + ')');
Ext.Ajax.request({
url: 'inside.php?t=json&m=common&f=getsconfig',
method: 'post',
params: {
id: respText.id,
sys: '1'
},
success: function(resp, opts) {
var conf = Ext.util.JSON.decode(resp.responseText);
//生成菜单
gettreemenu(conf);
//公告//
/*===================
* 退出登录
*/
var exitnode = new Ext.tree.TreeNode({
id: 'treenodeexit',
text: '个人设置',
cls: 'folder',
draggable: false,
expanded: true
});
main_tree.root.appendChild(exitnode);
//修改密码
exitnode.appendChild(new Ext.tree.TreeNode({
id: 'update_pwd',
text: '修改密码',
listeners: {
'click': function(node, event) {
updatePwd(respText.id, respText.user_name); //updatePwd.js //Story #20061 GSP使用ldap服务成功 by lixiaoli
}
}
}));
//退出登录
exitnode.appendChild(new Ext.tree.TreeNode({
id: 'exitsys',
text: '退出登录',
listeners: {
'click': function(node, event) {
Ext.MessageBox.confirm('退出登录', '确定要退出登陆吗?', function showResult(btn) {
if (btn == 'yes') {
Ext.Ajax.request({
url: '/inside.php?t=json&m=login&f=logout',
success: function(resp, opts) {
window.location.href = '/index.html';
}
});
}
});
}
}
}));
//每隔3分钟更新500个设备的truenameStory #29096 去掉自动访问连接
//synctimer = window.setInterval("syncName()",60000*3);
}
});
/*guo juan 注释
* new Ext.Viewport(
{
enableTabScroll:true,
layout:"border",
items:[
//mainpanel_top,//顶部信息栏
main_tree,//管理菜单
main_panel//操作主界面
]
}
);*/
/*guo juan 添加*/
new Ext.Panel({
layout: 'border',
renderTo: 'container',
width: 400,
height: 200,
items: [main_tree, main_panel]
});
main_tree.setTitle(respText.true_name + '(' + respText.user_name + ')');
}
}
});
});
// 更新设备使者姓名Story #29096 去掉自动访问连接
/*function syncName() {
Ext.Ajax.request({
url:'/inside.php?t=json&m=gps&f=syncName',
success: function(resp,opts){
var conf =resp.responseText;
if(conf=='over')
window.clearInterval(synctimer);
}
});
}*/
//生成左侧菜单
function gettreemenu(conf) {
if (conf) {
for (var i = 0; i < conf.data.length; i++) {
if (conf.data[i].status == '1' && conf.data[i].is_display == '1') { //可用且显示Story #21651
if (conf.data[i].url != '/') {
var nodeid = 'treenode' + conf.data[i].source_code;
var tnode = new Ext.tree.TreeNode({
id: nodeid,
text: conf.data[i].source_name,
cls: 'folder',
draggable: false,
expanded: true
});
} else {
//主节点,默认打开
var tnode = new Ext.tree.TreeNode({
id: 'treenode' + conf.data[i].source_code,
text: conf.data[i].source_name,
cls: 'folder',
draggable: false,
expanded: true
});
}
//有事件
if (conf.data[i].url != '/') {
//console.log('----------------');
if ((conf.data[i].mainname == null) || (conf.data[i].mainname == '')) {
//console.log(tnode);
//写入地址
var str = '<iframe scrolling="auto" frameborder="0" width="100%" height="100%" src="' + conf.data[i].url + '" id="iframe' + conf.data[i].source_id + '"></iframe>'; //Story #14954
tnode.attributes = str;
tnode.on('click', function(node, event) {
event.stopEvent();
//读出地址
var strhtml = node.attributes;
//console.log(strhtml);
var n = main_panel.getComponent(node.id);
if (!n) { //判断是否已经打开该面板
n = main_panel.add({
'id': node.id,
'title': node.text,
closable: true, //关闭按钮
//通过html载入目标页
html: strhtml
});
}
main_panel.setActiveTab(n);
});
} else { //新系统中有mainfromname的
//写入地址
//console.log(node.attributes.mainname);
tnode.attributes = conf.data[i];
tnode.on('click', function(node, event) {
event.stopEvent();
var n = main_panel.getComponent('treenode' + node.attributes.mainname);
if (!n) { //判断是否已经打开该面板
//去载入,并执行初始化函数,加入到main_panel
toloadjs(node.attributes.url, '', 'yes', node.attributes.mainname, node);
} else {
main_panel.setActiveTab(n);
}
});
}
}
if (conf.data[i].source_code.length > 3) {
//找到父节点
var strid = 'treenode' + conf.data[i].parent_code;
if (main_tree.getNodeById(strid)) {
main_tree.getNodeById(strid).appendChild(tnode);
}
} else {
//根节点
main_tree.root.appendChild(tnode);
}
}
//默认打开系统公告
if (tnode && (conf.data[i].url == '/user_info')) {
n = main_panel.add({
'id': tnode.id,
'title': tnode.text,
//通过html载入目标页
html: tnode.attributes
});
main_panel.setActiveTab(n);
}
}
}
}
/////////////////////////////////////////////
////按需载入js代码//
//用法实例:// ScriptMgr = new ScriptLoaderMgr();// ScriptMgr.load// ({// scripts: ['/a/a.js'],// callback: function() {// alert('加载完成显示');// }// });
/////////////////////////////////////////////
//载入要加载的js路径,
function toloadjs(jsname, funname, tomainpaneltab, mainname, node) {
if (jsname != '') {
if (!Ext.getCmp(mainname)) {
var ScriptMgr = new ScriptLoaderMgr();
ScriptMgr.load({
scripts: [jsname],
callback: function() {
if ((tomainpaneltab != '') && (mainname != '')) { /*在主界面加载指定页面*/
if ((Ext.getCmp(mainname)) && (node)) {
var n = main_panel.add({
'id': node.id,
'title': node.text,
layout: "border",
items: [Ext.getCmp(mainname)],
closable: true
});
main_panel.setActiveTab(n);
} else {
alert('没找到功能模块,请联系管理员吧');
}
}
}
});
} else { /*已经载入过这个js*/
if (node) {
var n = main_panel.add({
'id': node.id,
'title': node.text,
layout: "border",
items: [Ext.getCmp(mainname)],
closable: true
});
main_panel.setActiveTab(n);
} else {
alert('没找到功能模块,请联系管理员吧');
}
}
}
}
ScriptLoader = function() {
this.timeout = 30;
this.scripts = [];
this.disableCaching = false;
this.loadMask = null;
};
ScriptLoader.prototype = {
showMask: function() {
if (!this.loadMask) {
this.loadMask = new Ext.LoadMask(Ext.getBody());
this.loadMask.show();
}
},
hideMask: function() {
if (this.loadMask) {
this.loadMask.hide();
this.loadMask = null;
}
},
processSuccess: function(response) {
this.scripts[response.argument.url] = true;
window.execScript ? window.execScript(response.responseText) : window.eval(response.responseText);
if (response.argument.options.scripts.length == 0) {
this.hideMask();
}
if (typeof response.argument.callback == 'function') {
response.argument.callback.call(response.argument.scope);
}
},
processFailure: function(response) {
this.hideMask();
Ext.MessageBox.show({
title: '网络文件读取错误',
msg: '网络连接有异常,文件读取失败。请重试!',
closable: false,
icon: Ext.MessageBox.ERROR,
minWidth: 200
});
setTimeout(function() {
Ext.MessageBox.hide();
}, 3000);
},
load: function(url, callback) {
var cfg, callerScope;
if (typeof url == 'object') { // must be config object
cfg = url;
url = cfg.url;
callback = callback || cfg.callback;
callerScope = cfg.scope;
if (typeof cfg.timeout != 'undefined') {
this.timeout = cfg.timeout;
}
if (typeof cfg.disableCaching != 'undefined') {
this.disableCaching = cfg.disableCaching;
}
}
if (this.scripts[url]) {
if (typeof callback == 'function') {
callback.call(callerScope || window);
}
return null;
}
this.showMask();
Ext.Ajax.request({
url: url,
success: this.processSuccess,
failure: this.processFailure,
scope: this,
timeout: (this.timeout * 1000),
disableCaching: this.disableCaching,
argument: {
'url': url,
'scope': callerScope || window,
'callback': callback,
'options': cfg
}
});
}
};
ScriptLoaderMgr = function() {
this.loader = new ScriptLoader();
this.load = function(o) {
if (!Ext.isArray(o.scripts)) {
o.scripts = [o.scripts];
}
o.url = o.scripts.shift();
if (o.scripts.length == 0) {
this.loader.load(o);
} else {
o.scope = this;
this.loader.load(o, function() {
this.load(o);
});
}
};
};
/////////////////////////////////////////////
////按需载入js代码 end//
/////////////////////////////////////////////<file_sep><?php
/**
* 公告信息管理
* @author liuzhi
* @since 2013/11/12
*/
class extractModel extends model {
public function __construct()
{
parent::__construct();
$this->myAdmin = $this->app->myAdmin;
}
/**
* 获取公告列表信息
* @param String $where 搜索条件 默认搜索全部
* @param Array $limit 分页数组 默认分页20条
* @param String $desc 按创建时间倒序
* @author liuzhi
* @since 2013/11/8
*/
public function search($where,$limit,$desc)
{
$sql = "SELECT %s FROM ecsa_extract a
LEFT JOIN ecsa_sys_users b ON b.id = a.user_id ";
$fields = " a.*, b.user_code, b.user_name, b.card, b.bank_name, b.bank_card_no ";
//取记录总数
$total = parent::findBySql($sql, $where, null, null, 'count(1) count');
//取记录集
if($total[0]->count > 0) {
$datas = parent::findBySql($sql,$where, $desc, $limit, $fields);
}
$result = new stdClass();
$result->total = $total[0]->count;
$result->data = isset($datas) ? $datas : array();
return $result;
}
/**
* 公告信息修改
* @param Array $id ID
* @param Array $data 修改信息
* @param string $table 表名
* @author liuzhi
* @since 2013/11/12
*/
public function update($id = array(),$data = array(),$table = '')
{
return parent::update($data,$id,$table);
}
/**
* 公告信息添加
* @param array $data 添加信息
* @param string $table 表名
* @author liuzhi
* @since 2013/11/12
*/
public function add($data,$table)
{
if(!empty($data) && !empty($table))
{
return parent::insert($data, $table);
}
else
{
return false;
}
}
/**
* 按条件检索单据信息
* //Story #49819
* @author liuzhi
* @since 2015/10/14
*/
public function getExtract($where){
$sql = 'SELECT %s FROM ecsa_extract a ';
$fields = " a.id ";
$data = parent::findBySql($sql, $where, null, null, $fields);
return $data;
}
public function addExtract($params){
$output = array('success' => false, 'msg' => '提现添加失败');
if ($params) {
helper::datalog('添加提现数据: -IN: ' . var_export($params, true));
$data = array(
'user_id' => $params['user_id'],
'type' => $params['type'],
'total' => $params['total'],
'extract_total' => $params['extract_total'],
'pay_total' => $params['pay_total'],
'status' => 0,
'createtime' => helper::nowTime(),
'last_operator' => $this->myAdmin->true_name,
'updatetime' => helper::nowTime(),
'creator_id' => $this->myAdmin->id,
);
$addRes = parent::insert($data,'ecsa_extract');
helper::datalog('添加提现数据: -OUT: ' . var_export($addRes, true));
if ($addRes) {
$output = array('success' => true, 'msg' => '提现申请添加成功', 'data' => $addRes);
}
}
return $output;
}
}<file_sep>/*
* 入库查询搜索栏
* liuzhi
*
*/
//界面
var top_panel = new Ext.Panel ({
region:'north',
hideLabels:true,
bodyStyle:'padding: 10px',
height:50,
items:[
{
xtype : 'compositefield',
items :
[
{
xtype: 'displayfield',
value: '资源名称:'
},
{
xtype:'textfield',
fieldLabel:'资源名称',
name:'s_source_name',
id:"s_source_name",
width:200,
enableKeyEvents:true
},
{
xtype:'button',
text:'搜索',
handler: function(){
var s_source_name = Ext.getCmp("s_source_name").getValue();
grid_source.getLoader().baseParams.name = s_source_name;
grid_source.getLoader().load(grid_source.getRootNode(),function(){grid_source.expandAll()});
(Ext.getCmp('btnDel'))?Ext.getCmp('btnDel').disable():'';//删除
(Ext.getCmp('btnEdit'))?Ext.getCmp('btnEdit').disable():'';//编辑
}
},
]
}
]
});<file_sep><?php
/**
* The dao and sql class file of ZenTaoPHP.
*
* ZenTaoPHP is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* ZenTaoPHP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ZenTaoPHP. If not, see <http://www.gnu.org/licenses/>.
*
* @copyright Copyright 2009-2010 青岛易软天创网络科技有限公司(www.cnezsoft.com)
* @author <NAME> <<EMAIL>>
* @package ZenTaoPHP
* @version $Id: dao.class.php 121 2010-06-22 07:11:30Z chencongzhi520 $
* @link http://www.zentaoms.com
*/
/**
* DAO类。提供各种便利的数据库操作方法。
*
* @package ZenTaoPHP
*/
class dao
{
/**
* 全局的$app对象。
*
* @var object
* @access protected
*/
protected $app;
/**
* 全局的$config对象。
*
* @var object
* @access protected
*/
protected $config;
/**
* 全局的$lang对象。
*
* @var object
* @access protected
*/
protected $lang;
/**
* 全局的$dbh(数据库访问句柄)对象。
*
* @var object
* @access protected
*/
protected $dbh;
/**
* 当前查询所对应的主表。
*
* @var string
* @access public
*/
public $table;
/**
* 主表所对应的alias
*
* @var string
* @access public
*/
public $alias;
/**
* 当前查询所返回的字段列表。
*
* @var string
* @access public
*/
public $fields;
/**
* 查询的模式,现在支持两种,一种是通过魔术方法,一种是直接拼写sql查询。
*
* 主要用来区分dao::from()方法和sql::from()方法。
*
* @var string
* @access public
*/
public $mode;
/**
* 查询的方法: insert, select, update, delete, replace
*
* @var string
* @access public
*/
public $method;
/**
* 执行的sql查询列表。
*
* 用来记录当前页面所有的sql查询。
*
* @var array
* @access public
*/
static public $querys = array();
/**
* 数据检查结果。
*
* @var array
* @access public
*/
static public $errors = array();
/**
* 构造函数。
*
* 设置当前model对应的表名,并引用全局的变量。
*
* @param string $table 表名。
* @access public
* @return void
*/
public function __construct($table = '')
{
global $app, $config, $lang, $dbh;
$this->app = $app;
$this->config = $config;
$this->lang = $lang;
$this->dbh = $dbh;
$this->reset();
}
/**
* 设置数据表。
*
* @param string $table 表名。
* @access private
* @return void
*/
private function setTable($table)
{
$this->table = $table;
}
/**
* 设置当前查询主表的alias。
*
* @param string $alias 别名。
* @access private
* @return void
*/
private function setAlias($alias)
{
$this->alias = $alias;
}
/**
* 设置返回的字段列表。
*
* @param string $fields 字段列表。
* @access private
* @return void
*/
private function setFields($fields)
{
$this->fields = $fields;
}
/**
* 重新设置table, field, mode。
*
* @access private
* @return void
*/
private function reset()
{
$this->setFields('');
$this->setTable('');
$this->setAlias('');
$this->setMode('');
$this->setMethod('');
}
//-------------------- 根据查询方式的不同,调用SQL类的对应方法。--------------------//
/**
* 设置查询模式。magic是通过findby之类的魔术方法进行查询的,而raw则直接拼装sql进行查询。
*
* @param string mode 查询模式: empty|magic|raw
* @access private
* @return void
*/
private function setMode($mode = '')
{
$this->mode = $mode;
}
/* 设置查询的方法。select|update|insert|delete|replace */
private function setMethod($method = '')
{
$this->method = $method;
}
/* select:调用SQL类的select方法。*/
public function select($fields = '*')
{
$this->setMode('raw');
$this->setMethod('select');
$this->sqlobj = sql::select($fields);
return $this;
}
/* update:调用SQL类的update方法。*/
public function update($table)
{
$this->setMode('raw');
$this->setMethod('update');
$this->sqlobj = sql::update($table);
$this->setTable($table);
return $this;
}
/* delete:调用SQL类的delete方法。*/
public function delete()
{
$this->setMode('raw');
$this->setMethod('delete');
$this->sqlobj = sql::delete();
return $this;
}
/* insert:调用SQL类的insert方法。*/
public function insert($table)
{
$this->setMode('raw');
$this->setMethod('insert');
$this->sqlobj = sql::insert($table);
$this->setTable($table);
return $this;
}
/* replace:调用SQL类的replace方法。*/
public function replace($table)
{
$this->setMode('raw');
$this->setMethod('replace');
$this->sqlobj = sql::replace($table);
$this->setTable($table);
return $this;
}
/* from: 设定要查询的table name。*/
public function from($table)
{
$this->setTable($table);
if($this->mode == 'raw') $this->sqlobj->from($table);
return $this;
}
/* fields方法:设置要查询的字段列表。*/
public function fields($fields)
{
$this->setFields($fields);
return $this;
}
/* alias方法。*/
public function alias($alias)
{
if(empty($this->alias)) $this->setAlias($alias);
$this->sqlobj->alias($alias);
return $this;
}
/* data方法。*/
public function data($data)
{
/* 如果当前模块不是company,都追加company字段。*/
if(!is_object($data)) $data = (object)$data;
if(isset($this->app->company) and $this->table != TABLE_COMPANY and !isset($data->company)) $data->company = $this->app->company->id;
$this->sqlobj->data($data);
return $this;
}
//-------------------- 拼装之后的SQL相关处理方法。--------------------//
/* 返回SQL语句。*/
public function get()
{
return $this->processSQL();
}
/* 打印SQL语句。*/
public function printSQL()
{
echo $this->processSQL();
}
/* 处理SQL,将table和fields字段替换成对应的值。*/
private function processSQL($autoCompany = true)
{
$sql = $this->sqlobj->get();
/* 如果查询模式是magic,处理fields和table两个变量。*/
if($this->mode == 'magic')
{
if($this->fields == '') $this->fields = '*';
if($this->table == '') $this->app->error('Must set the table name', __FILE__, __LINE__, $exit = true);
$sql = sprintf($this->sqlobj->get(), $this->fields, $this->table);
}
/* 如果处理的不是company表,并且查询方法不是insert和replace, 追加company的查询条件。*/
if(isset($this->app->company) and $autoCompany and $this->table != '' and $this->table != TABLE_COMPANY and $this->method != 'insert' and $this->method != 'replace')
{
/* 获得where 和 order by的位置。*/
$wherePOS = strripos($sql, 'where');
$groupPOS = strripos($sql, 'group by'); // group by的位置。
$havingPOS = strrpos($sql, 'HAVING'); // having的位置。
$orderPOS = strripos($sql, 'order by'); // order by的位置。
$limitPOS = strrpos($sql, 'LIMIT'); // limit的位置。
$splitPOS = $orderPOS ? $orderPOS : $limitPOS; // order比limit靠前。
$splitPOS = $havingPOS? $havingPOS: $splitPOS; // having比orer靠前。
$splitPOS = $groupPOS ? $groupPOS : $splitPOS; // group比having靠前。
/* 要追加的条件语句。*/
$tableName = !empty($this->alias) ? $this->alias : $this->table;
$companyCondition = " $tableName.company = '{$this->app->company->id}' ";
/* SQL语句中有order by。*/
if($splitPOS)
{
$firstPart = substr($sql, 0, $splitPOS);
$lastPart = substr($sql, $splitPOS);
if($wherePOS)
{
$sql = $firstPart . " AND $companyCondition " . $lastPart;
}
else
{
$sql = $firstPart . " WHERE $companyCondition " . $lastPart;
}
}
else
{
$sql .= $wherePOS ? " AND $companyCondition" : " WHERE $companyCondition";
}
}
self::$querys[] = $sql;
return $sql;
}
//-------------------- SQL查询相关的方法。--------------------//
/* 设置数据库访问句柄。*/
public function dbh($dbh)
{
$this->dbh = $dbh;
return $this;
}
/* 执行sql查询,返回stmt对象。autoComapny设定是否自动追加company的查询条件。*/
public function query($autoCompany = true)
{
/* 如果dao::$errors不为空,返回一个空的stmt对象,这样后续的方法调用还可以继续。*/
if(!empty(dao::$errors)) return new PDOStatement();
/* 处理一下SQL语句。*/
$sql = $this->processSQL($autoCompany);
try
{
$this->reset();
return $this->dbh->query($sql);
}
catch (PDOException $e)
{
$this->app->error($e->getMessage() . "<p>The sql is: $sql</p>", __FILE__, __LINE__, $exit = true);
}
}
/* 执行分页。*/
public function page($pager)
{
if(!is_object($pager)) return $this;
/* 没有传递recTotal,则自己进行计算。*/
if($pager->recTotal == 0)
{
/* 获得SELECT和FROM的位置,据此算出查询的字段,然后将其替换为count(*)。*/
$sql = $this->get();
$selectPOS = strpos($sql, 'SELECT') + strlen('SELECT');
$fromPOS = strpos($sql, 'FROM');
$fields = substr($sql, $selectPOS, $fromPOS - $selectPOS );
$sql = str_replace($fields, ' COUNT(*) AS recTotal ', $sql);
/* 取得order 或者limit的位置,将后面的去掉。*/
$subLength = strlen($sql);
$orderPOS = strripos($sql, 'order');
$limitPOS = strripos($sql , 'limit');
if($limitPOS) $subLength = $limitPOS;
if($orderPOS) $subLength = $orderPOS;
$sql = substr($sql, 0, $subLength);
self::$querys[] = $sql;
/* 获得记录总数。*/
try
{
$row = $this->dbh->query($sql)->fetch(PDO::FETCH_OBJ);
}
catch (PDOException $e)
{
$this->app->error($e->getMessage() . "<p>The sql is: $sql</p>", __FILE__, __LINE__, $exit = true);
}
$pager->setRecTotal($row->recTotal);
$pager->setPageTotal();
}
$this->sqlobj->limit($pager->limit());
return $this;
}
/* 执行sql查询,返回受影响的记录数。autoComapny设定是否自动追加company的查询条件。*/
public function exec($autoCompany = true)
{
/* 如果dao::$errors不为空,返回一个空的stmt对象,这样后续的方法调用还可以继续。*/
if(!empty(dao::$errors)) return new PDOStatement();
/* 处理一下SQL语句。*/
$sql = $this->processSQL($autoCompany);
try
{
$this->reset();
return $this->dbh->exec($sql);
}
catch (PDOException $e)
{
$this->app->error($e->getMessage() . "<p>The sql is: $sql</p>", __FILE__, __LINE__, $exit = true);
}
}
//-------------------- 数据获取相关的方法。--------------------//
/* 返回一条记录,如果指定了$field字段, 则直接返回该字段对应的值。*/
public function fetch($field = '', $autoCompany = true)
{
if(empty($field)) return $this->query($autoCompany)->fetch();
$this->setFields($field);
$result = $this->query($autoCompany)->fetch(PDO::FETCH_OBJ);
if($result) return $result->$field;
}
/* 返回全部的结果。如果指定了$keyField,则以keyField的值作为key。*/
public function fetchAll($keyField = '', $autoCompany = true)
{
$stmt = $this->query($autoCompany);
if(empty($keyField)) return $stmt->fetchAll();
$rows = array();
while($row = $stmt->fetch()) $rows[$row->$keyField] = $row;
return $rows;
}
/* 返回结果并按照某个字段进行分组。*/
public function fetchGroup($groupField, $keyField = '', $autoCompany = true)
{
$stmt = $this->query($autoCompany);
$rows = array();
while($row = $stmt->fetch())
{
empty($keyField) ? $rows[$row->$groupField][] = $row : $rows[$row->$groupField][$row->$keyField] = $row;
}
return $rows;
}
/* fetchPairs方法:如果没有指定key和value字段,则取行字段里面的第一个作为key,最后一个作为value。*/
public function fetchPairs($keyField = '', $valueField = '', $autoCompany = true)
{
$pairs = array();
$ready = false;
$stmt = $this->query($autoCompany);
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
if(!$ready)
{
if(empty($keyField)) $keyField = key($row);
if(empty($valueField))
{
end($row);
$valueField = key($row);
}
$ready = true;
}
$pairs[$row[$keyField]] = $row[$valueField];
}
return $pairs;
}
/* 获取最后插入的id。*/
public function lastInsertID()
{
return $this->dbh->lastInsertID();
}
//-------------------- 各种魔术方法。--------------------//
/**
* 魔术方法,籍此提供各种便利的查询方法。
*
* @param string $funcName 被调用的方法名。
* @param array $funcArgs 传入的参数列表。
* @access public
* @return void
*/
public function __call($funcName, $funcArgs)
{
/* 将funcName转为小写。*/
$funcName = strtolower($funcName);
/* findBy类的方法。*/
if(strpos($funcName, 'findby') !== false)
{
$this->setMode('magic');
$field = str_replace('findby', '', $funcName);
if(count($funcArgs) == 1)
{
$operator = '=';
$value = $funcArgs[0];
}
else
{
$operator = $funcArgs[0];
$value = $funcArgs[1];
}
$this->sqlobj = sql::select('%s')->from('%s')->where($field, $operator, $value); // 使用占位符,执行查询之前替换为相应的字段和表名。
return $this;
}
/* fetch10方法,真正的数据查询。*/
elseif(strpos($funcName, 'fetch') !== false)
{
$max = str_replace('fetch', '', $funcName);
$stmt = $this->query();
/* 设定了key字段。 */
$rows = array();
$key = isset($funcArgs[0]) ? $funcArgs[0] : '';
$i = 0;
while($row = $stmt->fetch())
{
$key ? $rows[$row->$key] = $row : $rows[] = $row;
$i ++;
if($i == $max) break;
}
return $rows;
}
/* 其余的都直接调用sql类里面的方法。*/
else
{
/* 取SQL类方法中参数个数最大值,生成一个最大集合的参数列表。。*/
for($i = 0; $i < SQL::MAX_ARGS; $i ++)
{
${"arg$i"} = isset($funcArgs[$i]) ? $funcArgs[$i] : null;
}
$this->sqlobj->$funcName($arg0, $arg1, $arg2);
return $this;
}
}
//-------------------- 数据检查相关的方法。--------------------//
/* 按照某个规则检查值是否符合要求。*/
public function check($fieldName, $funcName)
{
/* 如果data变量里面没有这个字段,直接返回。*/
if(!isset($this->sqlobj->data->$fieldName)) return $this;
/* 引用全局的config, lang。*/
global $lang, $config, $app;
$table = strtolower(str_replace($config->db->prefix, '', $this->table));
$fieldLabel = isset($lang->$table->$fieldName) ? $lang->$table->$fieldName : $fieldName;
$value = $this->sqlobj->data->$fieldName;
if($funcName == 'unique')
{
$args = func_get_args();
$sql = "SELECT COUNT(*) AS count FROM $this->table WHERE `$fieldName` = " . $this->sqlobj->quote($value);
if($this->table != TABLE_COMPANY) $sql .= " AND company = {$this->app->company->id} ";
if(isset($args[2])) $sql .= ' AND ' . $args[2];
try
{
$row = $this->dbh->query($sql)->fetch();
if($row->count != 0) $this->logError($funcName, $fieldName, $fieldLabel, array($value));
}
catch (PDOException $e)
{
$this->app->error($e->getMessage() . "<p>The sql is: $sql</p>", __FILE__, __LINE__, $exit = true);
}
}
else
{
/* 取validate类方法中参数个数最大值,生成一个最大集合的参数列表。。*/
$funcArgs = func_get_args();
unset($funcArgs[0]);
unset($funcArgs[1]);
for($i = 0; $i < VALIDATER::MAX_ARGS; $i ++)
{
${"arg$i"} = isset($funcArgs[$i + 2]) ? $funcArgs[$i + 2] : null;
}
$checkFunc = 'check' . $funcName;
if(validater::$checkFunc($value, $arg0, $arg1, $arg2) === false)
{
$this->logError($funcName, $fieldName, $fieldLabel, $funcArgs);
}
}
return $this;
}
/* 如果满足某一个条件,按照某个规则检查值是否符合要求。*/
public function checkIF($condition, $fieldName, $funcName)
{
if(!$condition) return $this;
$funcArgs = func_get_args();
for($i = 0; $i < VALIDATER::MAX_ARGS; $i ++)
{
${"arg$i"} = isset($funcArgs[$i + 3]) ? $funcArgs[$i + 3] : null;
}
$this->check($fieldName, $funcName, $arg0, $arg1, $arg2);
return $this;
}
/* 批量检查。*/
public function batchCheck($fields, $funcName)
{
$fields = explode(',', str_replace(' ', '', $fields));
$funcArgs = func_get_args();
for($i = 0; $i < VALIDATER::MAX_ARGS; $i ++)
{
${"arg$i"} = isset($funcArgs[$i + 2]) ? $funcArgs[$i + 2] : null;
}
foreach($fields as $fieldName) $this->check($fieldName, $funcName, $arg0, $arg1, $arg2);
return $this;
}
/* 批量条件检查。*/
public function batchCheckIF($condition, $fields, $funcName)
{
if(!$condition) return $this;
$fields = explode(',', str_replace(' ', '', $fields));
$funcArgs = func_get_args();
for($i = 0; $i < VALIDATER::MAX_ARGS; $i ++)
{
${"arg$i"} = isset($funcArgs[$i + 2]) ? $funcArgs[$i + 2] : null;
}
foreach($fields as $fieldName) $this->check($fieldName, $funcName, $arg0, $arg1, $arg2);
return $this;
}
/* 自动根据数据库中表的字段格式进行检查。*/
public function autoCheck($skipFields = '')
{
$fields = $this->getFieldsType();
$skipFields = ",$skipFields,";
foreach($fields as $fieldName => $validater)
{
if(strpos($skipFields, $fieldName) !== false) continue; // 忽略。
if(!isset($this->sqlobj->data->$fieldName)) continue;
if($validater['rule'] == 'skip') continue;
$options = array();
if(isset($validater['options'])) $options = array_values($validater['options']);
for($i = 0; $i < VALIDATER::MAX_ARGS; $i ++)
{
${"arg$i"} = isset($options[$i]) ? $options[$i] : null;
}
$this->check($fieldName, $validater['rule'], $arg0, $arg1, $arg2);
}
return $this;
}
/* 记录错误。*/
public function logError($checkType, $fieldName, $fieldLabel, $funcArgs = array())
{
global $lang;
$error = $lang->error->$checkType;
$replaces = array_merge(array($fieldLabel), $funcArgs);
/* 如果error不是数组,只是字符串,则循环replace,依次替换%s。*/
if(!is_array($error))
{
foreach($replaces as $replace)
{
$pos = strpos($error, '%s');
if($pos === false) break;
$error = substr($error, 0, $pos) . $replace . substr($error, $pos +2);
}
}
/* 如果error是一个数组,则从数组中挑选%s个数与replace元素个数相同的。*/
else
{
/* 去掉replace中空白的元素。*/
foreach($replaces as $key => $value) if(is_null($value)) unset($replaces[$key]);
$replacesCount = count($replaces);
foreach($error as $errorString)
{
if(substr_count($errorString, '%s') == $replacesCount)
{
$error = vsprintf($errorString, $replaces);
}
}
}
dao::$errors[$fieldName][] = $error;
}
/* 判断这次查询是否有错误。*/
public function isError()
{
return !empty(dao::$errors);
}
/* 返回error。*/
public function getError()
{
$errors = dao::$errors;
dao::$errors = array();
return $errors;
}
/* 获得某一个表的字段类型。*/
private function getFieldsType()
{
try
{
$this->dbh->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
$sql = "DESC $this->table";
$rawFields = $this->dbh->query($sql)->fetchAll();
$this->dbh->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
}
catch (PDOException $e)
{
$this->app->error($e->getMessage() . "<p>The sql is: $sql</p>", __FILE__, __LINE__, $exit = true);
}
foreach($rawFields as $rawField)
{
$firstPOS = strpos($rawField->type, '(');
$type = substr($rawField->type, 0, $firstPOS > 0 ? $firstPOS : strlen($rawField->type));
$type = str_replace(array('big', 'small', 'medium', 'tiny', 'var'), '', $type);
$field = array();
if($type == 'enum' or $type == 'set')
{
$rangeBegin = $firstPOS + 2; // 将第一个引号去掉。
$rangeEnd = strrpos($rawField->type, ')') - 1; // 将最后一个引号去掉。
$range = substr($rawField->type, $rangeBegin, $rangeEnd - $rangeBegin);
$field['rule'] = 'reg';
$field['options']['reg'] = '/' . str_replace("','", '|', $range) . '/';
}
elseif($type == 'char')
{
$begin = $firstPOS + 1;
$end = strpos($rawField->type, ')', $begin);
$length = substr($rawField->type, $begin, $end - $begin);
$field['rule'] = 'length';
$field['options']['max'] = $length;
$field['options']['min'] = 0;
}
elseif($type == 'int')
{
$field['rule'] = 'int';
}
elseif($type == 'float' or $type == 'double')
{
$field['rule'] = 'float';
}
elseif($type == 'date')
{
$field['rule'] = 'date';
}
else
{
$field['rule'] = 'skip';
}
$fields[$rawField->field] = $field;
}
return $fields;
}
}
/**
* SQL查询封装类。
*
* @package ZenTaoPHP
*/
class sql
{
/**
* 所有方法的参数个数最大值。
*
*/
const MAX_ARGS = 3;
/**
* SQL语句。
*
* @var string
* @access private
*/
private $sql = '';
/**
* 全局的$dbh(数据库访问句柄)对象。
*
* @var object
* @access protected
*/
protected $dbh;
/**
* INSERT或者UPDATE时赋给的数据。
*
* @var mix
* @access protected
*/
public $data;
/**
* 是否是首次调用set。
*
* @var bool
* @access private;
*/
private $isFirstSet = true;
/**
* 是否在条件判断中。
*
* @var bool
* @access private;
*/
private $inCondition = false;
/**
* 判断条件是否为ture。
*
* @var bool
* @access private;
*/
private $conditionIsTrue = false;
/**
* 是否自动magic quote。
*
* @var bool
* @access public
*/
public $magicQuote;
/* 构造函数。*/
private function __construct($table = '')
{
global $dbh;
$this->dbh = $dbh;
$this->magicQuote = get_magic_quotes_gpc();
}
/* 实例化方法,通过该方法实例对象。*/
public function factory($table = '')
{
return new sql($table);
}
/* 查询语句开始。*/
public function select($field = '*')
{
$sqlobj = self::factory();
$sqlobj->sql = "SELECT $field ";
return $sqlobj;
}
/* 更新语句开始。*/
public function update($table)
{
$sqlobj = self::factory();
$sqlobj->sql = "UPDATE $table SET ";
return $sqlobj;
}
/* 插入语句开始。*/
public function insert($table)
{
$sqlobj = self::factory();
$sqlobj->sql = "INSERT INTO $table SET ";
return $sqlobj;
}
/* 替换语句开始。*/
public function replace($table)
{
$sqlobj = self::factory();
$sqlobj->sql = "REPLACE $table SET ";
return $sqlobj;
}
/* 删除语句开始。*/
public function delete()
{
$sqlobj = self::factory();
$sqlobj->sql = "DELETE ";
return $sqlobj;
}
/* 给定一个key=>value结构的数组或者对象,拼装成key = value的形式。*/
public function data($data)
{
$this->data = $data;
foreach($data as $field => $value) $this->sql .= "`$field` = " . $this->quote($value) . ',';
$this->sql = rtrim($this->sql, ','); // 去掉最后面的逗号。
return $this;
}
/* 加左边的括弧。*/
public function markLeft($count = 1)
{
$this->sql .= str_repeat('(', $count);
return $this;
}
/* 加右边的括弧。*/
public function markRight($count = 1)
{
$this->sql .= str_repeat(')', $count);
return $this;
}
/* SET key=value。*/
public function set($set)
{
if($this->isFirstSet)
{
$this->sql .= " $set ";
$this->isFirstSet = false;
}
else
{
$this->sql .= ", $set";
}
return $this;
}
/* 设定要查询的表名。*/
public function from($table)
{
$this->sql .= "FROM $table";
return $this;
}
/* 设置别名。*/
public function alias($alias)
{
$this->sql .= " AS $alias ";
}
/* 设定LEFT JOIN语句。*/
public function leftJoin($table)
{
$this->sql .= " LEFT JOIN $table";
return $this;
}
/* 设定ON条件。*/
public function on($condition)
{
$this->sql .= " ON $condition ";
return $this;
}
/* 条件判断开始。*/
public function beginIF($condition)
{
$this->inCondition = true;
$this->conditionIsTrue = $condition;
}
/* 条件判断结束。*/
public function fi()
{
$this->inCondition = false;
$this->conditionIsTrue = false;
}
/* WHERE语句部分开始。*/
public function where($arg1, $arg2 = null, $arg3 = null)
{
if($this->inCondition and !$this->conditionIsTrue) return $this;
if($arg3 !== null)
{
$value = $this->quote($arg3);
$condition = "`$arg1` $arg2 " . $this->quote($arg3);
}
else
{
$condition = $arg1;
}
$this->sql .= " WHERE $condition ";
return $this;
}
/* 追加AND条件。*/
public function andWhere($condition)
{
if($this->inCondition and !$this->conditionIsTrue) return $this;
$this->sql .= " AND $condition ";
return $this;
}
/* 追加OR条件。*/
public function orWhere($condition)
{
if($this->inCondition and !$this->conditionIsTrue) return $this;
$this->sql .= " OR $condition ";
return $this;
}
/* 等于。*/
public function eq($value)
{
if($this->inCondition and !$this->conditionIsTrue) return $this;
$this->sql .= " = " . $this->quote($value);
return $this;
}
/* 不等于。*/
public function ne($value)
{
if($this->inCondition and !$this->conditionIsTrue) return $this;
$this->sql .= " != " . $this->quote($value);
return $this;
}
/* 大于。*/
public function gt($value)
{
if($this->inCondition and !$this->conditionIsTrue) return $this;
$this->sql .= " > " . $this->quote($value);
return $this;
}
/* 小于。*/
public function lt($value)
{
if($this->inCondition and !$this->conditionIsTrue) return $this;
$this->sql .= " < " . $this->quote($value);
return $this;
}
/* 生成between语句。*/
public function between($min, $max)
{
if($this->inCondition and !$this->conditionIsTrue) return $this;
$this->sql .= " BETWEEN $min AND $max ";
return $this;
}
/* 生成 IN部分语句。*/
public function in($ids)
{
if($this->inCondition and !$this->conditionIsTrue) return $this;
$this->sql .= helper::dbIN($ids);
return $this;
}
/* 生成 NOTIN部分语句。*/
public function notin($ids)
{
if($this->inCondition and !$this->conditionIsTrue) return $this;
$this->sql .= ' NOT ' . helper::dbIN($ids);
return $this;
}
/* 生成LIKE部分语句。*/
public function like($string)
{
if($this->inCondition and !$this->conditionIsTrue) return $this;
$this->sql .= " LIKE " . $this->quote($string);
return $this;
}
/* 设定ORDER BY。*/
public function orderBy($order)
{
$order = str_replace(array('|', '', '_'), ' ', $order);
$order = str_replace('left', '`left`', $order); // 处理left关键字。
$this->sql .= " ORDER BY $order";
return $this;
}
/* 设定LIMIT。*/
public function limit($limit)
{
if(empty($limit)) return $this;
stripos($limit, 'limit') !== false ? $this->sql .= " $limit " : $this->sql .= " LIMIT $limit ";
return $this;
}
/* 设定GROUP BY。*/
public function groupBy($groupBy)
{
$this->sql .= " GROUP BY $groupBy";
return $this;
}
/* 设定having。*/
public function having($having)
{
$this->sql .= " HAVING $having";
return $this;
}
/* 返回拼装好的语句。*/
public function get()
{
return $this->sql;
}
/* 转义。*/
public function quote($value)
{
if($this->magicQuote) $value = stripslashes($value);
return $this->dbh->quote($value);
}
}
<file_sep> var crow;
//资源搜索
var store_role=new Ext.data.Store({
proxy:new Ext.data.HttpProxy({url:'../inside.php?t=json&m=role&f=search',method:"POST"}),
reader:new Ext.data.JsonReader({
tatalProperty:'',
root:'data'
},[
{name:'id'},
{name:'role_name'},
{name:'updatetime'}
]),
baseParams: {},
listeners: {
'load' : function(){
}
}
});
store_role.load();
//定义列表
var cm_role=new Ext.grid.ColumnModel([
{header:'角色名称',dataIndex:'role_name',sortable:true,width:150},
{header:'最后修改时间',dataIndex:'updatetime',sortable:true,width:170},
]);
//创建grid
var grid_role=new Ext.grid.GridPanel({
loadMask:true,
enableColumnMove:false,
enableColumnResize:true,
title:'角色管理',
stripeRows:true,//斑马颜色
autoScroll:true,
store:store_role,
cm:cm_role,
tbar:[]
});
//数据联动
grid_role.on("cellClick",function(thisGrid, rowIdx, colIdx,e){
//显示隐藏按钮
if(grid_role.getSelectionModel().hasSelection()){
var row = thisGrid.getStore().getAt(rowIdx).data;
crow = row;
(Ext.getCmp('btnDel'))?Ext.getCmp('btnDel').enable():'';//删除
(Ext.getCmp('btnEdit'))?Ext.getCmp('btnEdit').enable():'';//编辑
}else{
(Ext.getCmp('btnDel'))?Ext.getCmp('btnDel').disable():'';//删除
(Ext.getCmp('btnEdit'))?Ext.getCmp('btnEdit').disable():'';//编辑
}
});
function showEdit(){
//Task #40327 gsp 权限方案整理 by lixiaoli
Ext.Ajax.request({
url:'../inside.php?t=json&m=user&f=checkAdmin',
method:'post',
params:{},
success: function sFn(response,options)
{
var res = Ext.decode(response.responseText).msg;
if(res == 0){
Ext.MessageBox.alert('提示', '该功能仅管理员可用!');
return false;
}else{
var row = crow;
Ext.getCmp("role_name").setValue(row.role_name);//设置编辑框中的角色名
tree_source.getLoader().baseParams.id = row.id;
showAdd(row.id);
}
}
});
}
function showDel(){
//Task #40327 gsp 权限方案整理 by lixiaoli
Ext.Ajax.request({
url:'../inside.php?t=json&m=user&f=checkAdmin',
method:'post',
params:{},
success: function sFn(response,options)
{
var res = Ext.decode(response.responseText).msg;
if(res == 0){
Ext.MessageBox.alert('提示', '该功能仅管理员可用!');
return false;
}else{
var row = crow;
Ext.MessageBox.confirm('删除角色', '本操作不可恢复,确定要删除['+row.role_name+']?', function showResult(btn){
if (btn == 'yes'){
Ext.Ajax.request({
url:'../inside.php?t=json&m=role&f=delete',
method:'post',
params:{id:row.id},
success: function(resp,opts){
Ext.MessageBox.alert('提示',Ext.decode(resp.responseText).msg);
store_role.load();
},
failure: function(resp,opts){
Ext.MessageBox.alert('提示',Ext.decode(resp.responseText).msg);
}
});
}
});
}
}
});
}
<file_sep>/**
* 字符串替换
* str 替换的字符串
* exc 已什么符号替换 默认 ......
* res 要替换成什么字符 默认 ''
* yu li
* 2013/11/15
*/
function strReplace(str)
{
var exc = arguments[1]?arguments[1] : '……';
var res = arguments[2]?arguments[2] : '';
if(str.indexOf(exc) != -1)
{
msg = str.replace( exc , res );
strReplace( msg );//递归调用
}
else
{
msg = str;
}
return msg;
}<file_sep> var cnode;
var _sm = new Ext.grid.CheckboxSelectionModel({singleSelect:false});
//定义列表
var cm_source=[
//_sm,
{header:'资源名称',sortable:true,dataIndex:'source_name',width:200},
{header:'顺序',sortable:true,dataIndex:'sort',width:200},
{header:'最后修改时间',sortable:true,width:200,dataIndex:'updatetime'}
];
var grid_source = new Ext.tree.ColumnTree({
title:'资源列表',
id:'grid_source',
border:false,
height:500,
loadMask:true,
rootVisible:false,
autoScroll:true,
expandable:false,
enableDD:true,
animate:true,
columns:cm_source,
loader:new Ext.tree.TreeLoader({
preloadChildren: true,
dataUrl:"../inside.php?t=json&m=source&f=search",
uiProviders:{
'col': Ext.tree.ColumnNodeUI
}
}),
root:new Ext.tree.AsyncTreeNode({
allowChildren: true,
}),
renderTo:Ext.getBody(),
tbar:[]
});
//数据联动
grid_source.on("click",function(node){
//显示隐藏按钮
if(grid_source.getSelectionModel().getSelectedNode()){
cnode = node;
(Ext.getCmp('btnDel'))?Ext.getCmp('btnDel').enable():'';//删除
(Ext.getCmp('btnEdit'))?Ext.getCmp('btnEdit').enable():'';//编辑
}else{
(Ext.getCmp('btnDel'))?Ext.getCmp('btnDel').disable():'';//删除
(Ext.getCmp('btnEdit'))?Ext.getCmp('btnEdit').disable():'';//编辑
}
});
function showEdit(){
//Task #40327 gsp 权限方案整理 by lixiaoli
Ext.Ajax.request({
url:'../inside.php?t=json&m=user&f=checkAdmin',
method:'post',
params:{},
success: function sFn(response,options)
{
var res = Ext.decode(response.responseText).msg;
if(res == 0){
Ext.MessageBox.alert('提示', '该功能仅管理员可用!');
return false;
}else{
if(grid_source.getSelectionModel().getSelectedNode()){
var row = cnode.attributes;
Ext.getCmp("name").setValue(row.source_name);
Ext.getCmp("url").setValue(row.url);
if(row.source_code.length > 3){//如果不是顶级资源
Ext.getCmp("_parent").setValue(row.parent_name);
Ext.getCmp("parent").setValue(row.parent_code);
}else{
Ext.getCmp("_parent").setValue('顶级资源');
Ext.getCmp("parent").setValue(0);
}
Ext.getCmp("status").setValue(row.status);
Ext.getCmp("type").setValue(row.type).fireEvent('select', null, {'data': {'value': row.type}}, null);//Story #21651
Ext.getCmp("is_display").setValue(row.is_display);//Story #21651
Ext.getCmp("priority").setValue(row.sort);
showAdd(row.id,row.source_code);
}else{
Ext.MessageBox.alert('提示','请先选择一个资源');
}
}
}
});
}
function showDel(){
//Task #40327 gsp 权限方案整理 by lixiaoli
Ext.Ajax.request({
url:'../inside.php?t=json&m=user&f=checkAdmin',
method:'post',
params:{},
success: function sFn(response,options)
{
var res = Ext.decode(response.responseText).msg;
if(res == 0){
Ext.MessageBox.alert('提示', '该功能仅管理员可用!');
return false;
}else{
if(grid_source.getSelectionModel().getSelectedNode()){
var row = cnode.attributes;
Ext.MessageBox.confirm('删除资源', '本操作不可恢复,确定要删除['+row.source_name+']?', function showResult(btn){
if (btn == 'yes'){
Ext.Ajax.request({
url:'../inside.php?t=json&m=source&f=delete',
method:'post',
params:{id:row.id,source_code:row.source_code},
success: function(resp,opts){
Ext.MessageBox.alert('提示',Ext.decode(resp.responseText).msg);
grid_source.getLoader().load(grid_source.getRootNode(),function(){grid_source.collapseAll()});
},
failure: function(resp,opts){
Ext.MessageBox.alert('提示',Ext.decode(resp.responseText).msg);
}
});
}
});
}else{
Ext.MessageBox.alert('提示','请先选择一个资源');
}
}
}
});
}<file_sep><?php
/**
* 订单管理
* @author liuzhi
* @since 2013/11/12
*/
class order extends baseControl
{
public function __construct()
{
parent::__construct();
$this->myAdmin = $this->app->myAdmin;
}
/**
* 获取订单列表信息
* @author liuzhi
* @since 2016-04-19
*/
public function search()
{
$output = array('success' => false, 'msg' => '更新失败');
$params = helper::filterParams();
$p = array('a.is_report_order' => '1', 'a.pay_status' => '2', 'a.sync_status' => '2', 'b.sync_status' => '2,3');
helper::datalog('调用接口获取订单数据: -IN: ' . var_export($p, true));
$data = $this->loadModel('client')->orderGetOrder($p);
helper::datalog('调用接口获取订单数据: -OUT: ' . var_export($data, true));
if ($data = json_decode($data, true)) {
$output = array('success' => true, 'msg' => '更新成功', 'data' => array());
if ($data['success'] && $data['data']['count']) {
$output['data'] = array_slice($data['data']['data'], $params['start'], $params['limit']);
}
} else {
$output['msg'] = '接口异常';
}
//输出结果
echo json_encode($output);
}
/**
* 订单信息修改
* @author liuzhi
* @since 2016-04-19
*/
public function update()
{
$output = array('success' => true, 'msg' => '更新成功');
$params = helper::filterParams();
$id = array('id' => $params['order_id']);
$up = array();
if (isset($params['invite_code'])) {
$up['invite_code'] = $params['invite_code'];
}
if (!empty($up)) {
$p = array('where' => $id, 'update' => $up);
helper::datalog('调用接口更新订单数据: -IN: ' . var_export($p, true));
$updataOrder = $this->loadModel('client')->orderUpdataOrder($p);
helper::datalog('调用接口更新订单数据: -OUT: ' . var_export($updataOrder, true));
if ($updataOrder = json_decode($updataOrder, true)) {
if (!$updataOrder['success']) {
$output['msg'] = $updataOrder['msg'];
}
} else {
$output['msg'] = '接口异常';
}
}
echo json_encode($output);
}
/**
* 订单信息审核
* @author liuzhi
* @since 2016-04-19
*/
public function statusTo1()
{
try {
//开启事务
$this->dbh->beginTransaction();
/***************************
* START处理逻辑
***************************/
$output = array('success' => true, 'msg' => '审核成功');
$_params = helper::filterParams();
$params = json_decode($_params['row'], true);
$where = array('order_id' => $params['order_id']);
$update = array('sync_status' => 1);
$info = $params;
if (!empty($update)) {
//先添加用户和订单,出错后可以回滚
$userId = $this->loadModel('user')->add($params);
$getOrder = $this->order->getOrder(array('order_id' => $params['order_id']));
if (!empty($getOrder)) {
throw new Exception('订单已存在', 1);
}
if ($userId['success']) {
$data = array(
'order_id' => $params['order_id'],
'order_sn' => $params['order_sn'],
'user_id' => $userId['data'],
'add_time' => $params['add_time'],
'creator_id' => $this->myAdmin->id,
'last_operator' => $this->myAdmin->true_name,
'check_time' => helper::nowTime(),
'check_user' => $this->myAdmin->id,
);
$this->order->add($data, 'ecsa_orders');
} else {
throw new Exception($userId['msg'], 1);
}
//调用接口审核订单
$p = array('where' => $where, 'update' => $update, 'info' => $info);
helper::datalog('调用接口审核订单: -IN: ' . var_export($p, true));
$updataOrder = $this->loadModel('client')->orderUpdateOrder($p);
helper::datalog('调用接口审核订单: -OUT: ' . var_export($updataOrder, true));
if ($updataOrder = json_decode($updataOrder, true)) {
if (!$updataOrder['success']) {
throw new Exception($updataOrder['msg'], 1);
}
//调用接口同步用户状态
$whereU = array('user_id' => $params['user_id']);
$updateU = array('sync_status' => 1);
$p = array('where' => $whereU, 'update' => $updateU, 'info' => $info);
helper::datalog('调用接口更改用户同步状态: -IN: ' . var_export($p, true));
$updataUser = $this->loadModel('client')->userUpdateUser($p);
helper::datalog('调用接口更改用户同步状态: -OUT: ' . var_export($updataUser, true));
} else {
throw new Exception('接口异常', 1);
}
}
/***************************
* END处理逻辑
***************************/
//事务提交
$this->dbh->commit();
echo json_encode($output);
} catch (Exception $e) {
//事务回滚
$this->dbh->rollBack();
echo json_encode(array('success' => false, 'msg' => $e->getCode() == '1' ? $e->getMessage() : '审核失败'));
helper::datalog('调用接口异常: ' . var_export($e->getMessage(), true));
}
}
/**
* 订单信息审核
* @author liuzhi
* @since 2016-04-19
*/
public function statusTo_1()
{
try {
//开启事务
$this->dbh->beginTransaction();
/***************************
* START处理逻辑
***************************/
$output = array('success' => true, 'msg' => '驳回成功');
$_params = helper::filterParams();
$params = json_decode($_params['row'], true);
$getUser = $this->loadModel('user')->getUser(array('a.id' => $params['user_id']));
if (!empty($getUser)) {
$output['msg'] = '用户已经存在, 无法驳回修改用户信息';
echo json_encode($output);return;
}
$where = array('user_id' => $params['user_id']);
$update = array('sync_status' => '3', 'dismiss_reason' => $_params['dismiss_reason']);
$info = $params;
if (!empty($update)) {
$p = array('where' => $where, 'update' => $update, 'info' => $info);
helper::datalog('调用接口驳回订单: -IN: ' . var_export($p, true));
$updataOrder = $this->loadModel('client')->userUpdateUser($p);
helper::datalog('调用接口驳回订单: -OUT: ' . var_export($updataOrder, true));
if ($updataOrder = json_decode($updataOrder, true)) {
if (!$updataOrder['success']) {
throw new Exception($updataOrder['msg'], 1);
}
//驳回成功
} else {
throw new Exception('接口异常', 1);
}
}
/***************************
* END处理逻辑
***************************/
//事务提交
$this->dbh->commit();
echo json_encode($output);
} catch (Exception $e) {
//事务回滚
$this->dbh->rollBack();
echo json_encode(array('success' => false, 'msg' => $e->getCode() == '1' ? $e->getMessage() : '驳回失败'));
helper::datalog('调用接口异常: ' . var_export($e->getMessage(), true));
}
}
public function updateInviteCode(){
$output = array('success' => false, 'msg' => '更新推荐码失败');
$_params = helper::filterParams();
$params = json_decode($_params['row'], true);
if ($_params['invite_code'] != '') {
$p = array('a.user_code' => $_params['invite_code']);
helper::datalog('调用接口查询用户: -IN: ' . var_export($p, true));
$userGetUser = $this->loadModel('client')->userGetUser($p);
helper::datalog('调用接口查询用户: -OUT: ' . var_export($userGetUser, true));
if ($data = json_decode($userGetUser, true)) {
$output = array('success' => true, 'msg' => '更新成功', 'data' => array());
if ($data['success'] && $data['data']['count']) {
//调用接口同步用户状态
$whereU = array('user_id' => $params['user_id']);
$updateU = array('invite_code' => $_params['invite_code']);
$p = array('where' => $whereU, 'update' => $updateU, 'info' => $params);
helper::datalog('调用接口更改用户推荐码: -IN: ' . var_export($p, true));
$updataUser = $this->loadModel('client')->userUpdateUser($p);
helper::datalog('调用接口更改用户推荐码: -OUT: ' . var_export($updataUser, true));
if ($updataUser = json_decode($updataUser, true)) {
if ($updataUser['success']) {
$output = array('success' => true, 'msg' => '更新推荐码成功');
} else {
$output['msg'] = $updataUser['msg'];
}
} else {
$output['msg'] = '更新用户接口异常';
}
} else {
$output['msg'] = '推荐码不存在';
}
} else {
$output['msg'] = '接口异常';
}
} else {
$output['msg'] = '推荐码不能为空';
}
echo json_encode($output);
}
}
?><file_sep>var smartwin;//扫描窗体
var sid = '';
var source_code = '';
var store_source_edt =new Ext.data.Store({
proxy:new Ext.data.HttpProxy({url:'../inside.php?t=json&m=source&f=searchAll',method:"POST"}),
reader:new Ext.data.JsonReader({
tatalProperty:'',
root:'data'
},[
{name:'id'},
{name:'source_code'},
{name:'source_name'},
{name:'edited_name'},
{name:'url'},
{name:'status'},
{name:'type'},
{name:'updatetime'}
]),
baseParams: {},
listeners: {
'load' : function(){
}
}
});
store_source_edt.load();
//主容器
var toppanel_add_itemlis = new Ext.FormPanel({
region:"center",
bodyStyle:'padding: 10px',
border:false,
items:[
{xtype:'textfield',id:'name',name:'name',width:180,fieldLabel:'资源名'},
{xtype:'textfield',id:'url',name:'url',width:180,fieldLabel:'url',
listeners: {
render: function(field){
Ext.QuickTips.init();
Ext.QuickTips.register({
target : field.el,
width:300,
trackMouse:true,
closable:true,
dismissDelay: 35000,
text: '资源类型为‘控件’时:(红色为必填参数)</br><span style="color:red">@param1</span>:控件点击事件调用的方法</br>@param2:控件CSS类</br>@param3:初始状态是否禁用</br>@param4:控件ID</br>@param5:控件将调用的后台PHP方法</br>@example:showEdit|silk-edit|true|btnEdit|update'
});
}
}
},
{xtype:'combo',id:'type',name:'type',width:180,submitValue:false,fieldLabel:'资源类型',mode:'local',editable:false,triggerAction:'all',displayField:'name',valueField:'value',store:new Ext.data.SimpleStore({fields:['name', 'value'],data:[['菜单','1'],['控件','2'],['板块','3']]}),
listeners: {
select: function(combo,record,index){
Ext.getCmp('is_display').disable();
if (record && record.data.value == '1') {
Ext.getCmp('is_display').enable();
}
}
}
},//Story #21651
{xtype:'combo',id:'status',name:'status',width:180,submitValue:false,fieldLabel:'可用状态',mode:'local',editable:false,triggerAction:'all',displayField:'name',valueField:'value',store:new Ext.data.SimpleStore({fields:['name', 'value'],data:[['可用','1'],['停用','0']]})},
{xtype:'combo',id:'is_display',hiddenName:'is_display',width:180,fieldLabel:'是否显示',mode:'local',editable:false,triggerAction:'all',displayField:'name',valueField:'value',store:new Ext.data.SimpleStore({fields:['name', 'value'],data:[['显示','1'],['隐藏','0']]}),
listeners: {
render: function(field){
Ext.QuickTips.init();
Ext.QuickTips.register({
target : field.el,
width:200,
trackMouse:true,
closable:true,
dismissDelay: 35000,
text: '本功能只用于资源类型为「<span style="color: red;">菜单</span>」的资源'
});
}
}
},//Story #21651
{xtype:'combo',id:'_parent',name:'_parent',width:180,fieldLabel:'上级资源',mode:'local',editable:false,triggerAction:'all',displayField:'edited_name',valueField:'source_code',store:store_source_edt,
listeners: {
expand: function(combo){
store_source_edt.load();
},
beforeselect: function(combo,record,index){
record.data.edited_name = record.data.source_name;
Ext.getCmp("parent").setValue(record.data.source_code);
}
}},//摆设
{xtype:'textfield',id:'priority',name:'priority',width:180,fieldLabel:'排序',emptyText:'从1开始'},
{xtype:'hidden',id:'parent',name:'parent'}//上级资源
],
buttons:[{text: '确定',
handler : function(){
var _form = this.ownerCt.ownerCt.getForm();
if (sid!=''){
_form.submit({url:'../inside.php?t=json&m=source&f=update',
success: sFn,
failure: fFn,
params: {id:sid,
source_code:source_code,
type:Ext.getCmp('type').getValue(),
status:Ext.getCmp('status').getValue()},
waitMsg:'Saving Data...'});
}else{
_form.submit({url:'../inside.php?t=json&m=source&f=add',
success: sFn,
failure: fFn,
params: {type:Ext.getCmp('type').getValue(),
status:Ext.getCmp('status').getValue()},
waitMsg:'Saving Data...'});
}
smartwin.hide();
}},{text: '关闭',
handler : function(){
smartwin.hide();
}
}]
});
///////////////////////////////
//弹出窗体
///////////////////////////////
if(!smartwin){//主窗体
smartwin = new Ext.Window({
layout:"border",
width:323,//Story #21651
height:272,//Story #21651
title:'资源维护',
closeAction:'hide',
plain: true,
items:[toppanel_add_itemlis]
});
}
//初始化界面
function showAdd(id,sCode)
{
Ext.Ajax.request({
url:'../inside.php?t=json&m=user&f=checkAdmin',
method:'post',
params:{},
success: function sFn(resp,opt)
{
var res = Ext.decode(resp.responseText).msg;
if(res == 0){
Ext.MessageBox.alert('提示', '该功能仅管理员可用!');
return false;
}else{
if (id){
sid = id;
source_code = sCode;
}else{
sid = '';
}
if (sid==''){
Ext.getCmp("name").setValue('');
Ext.getCmp("url").setValue('/XXX');
Ext.getCmp("parent").setValue('');
Ext.getCmp("_parent").setValue('');
Ext.getCmp("status").setValue('');
Ext.getCmp("type").setValue('').fireEvent('select');//Story #21651
Ext.getCmp("is_display").setValue('');//Story #21651
Ext.getCmp("priority").setValue('1');
}
smartwin.show();
}
}
});
}
function sFn(d,form)
{
grid_source.getLoader().load(grid_source.getRootNode(),function(){grid_source.collapseAll()});
store_source_edt.load();
(Ext.getCmp('btnDel'))?Ext.getCmp('btnDel').disable():'';//删除
(Ext.getCmp('btnEdit'))?Ext.getCmp('btnEdit').disable():'';//编辑
sid ='';
Ext.MessageBox.alert('提示!',Ext.decode(form.response.responseText).msg);
}
function fFn(d,form)
{
sid ='';
grid_source.getLoader().load(grid_source.getRootNode(),function(){grid_source.collapseAll()});
store_source_edt.load();
(Ext.getCmp('btnDel'))?Ext.getCmp('btnDel').disable():'';//删除
(Ext.getCmp('btnEdit'))?Ext.getCmp('btnEdit').disable():'';//编辑
Ext.MessageBox.alert('提示!',Ext.decode(form.response.responseText).msg);
}
<file_sep><?php
/**
* 登录控制类
* @author liyonghua
*/
class login extends baseControl {
private $cookiepre;
private $cookieTime;
//cookie存活时间
public function __construct() {
global $config;
parent::__construct();
$this->cookiepre = $config->cookiepre;
$this->cookieTime = time() + 3600 * 24 * 30;
//一个月
}
public function index() {
$this->login();
}
public function getConfig() {
$conf = new stdClass();
$conf->id = $this->app->myAdmin->id;
$conf->true_name = $this->app->myAdmin->true_name;
$conf->user_name = $this->app->myAdmin->user_name;
//$conf->source = $this->app->myAdmin->source;
//角色
if ($this->app->myAdmin->roleids) {
$conf->role = $this->login->userrole_info($this->app->myAdmin->roleids);
}
//创建人
//$conf->createrid = $this->login->usercreater_info($this->app->myAdmin->uid);
echo json_encode($conf);
}
/**
* 获取notice信息
* @author liuzhi
* @since 2013/11/7
*/
public function getNotice() {
$data = $this->login->getNotice();
echo json_encode($data);
}
/**
* 登录
* @author liuzhi
* @since 2013/11/6
*/
public function login() {
$info = array();
$info['id'] = -1;
if ($this->app->myAdmin->id) {
$info['id'] = $this->app->myAdmin->id;
$info['type'] = $this->app->myAdmin->type;
$info['message'] = '您已经登录...';
} else {
$params = helper::filterParams();
$userName = '';
$passWord = '';
$passWord2 = isset($params['passWord2']) ? $params['passWord2'] : '';
if (!empty($params['userName']) && !empty($params['passWord'])) {
$userName = $this->login->checkData(trim($params['userName']));
$passWord = $params['passWord'];
if ($passWord == $passWord2) {
$passWord = $this->GSPcrypt($passWord, 'D', 'ysp');
//解密
}
$userInfo = $this->login->getUserInfo($userName);
$md5passWord = $this->loadModel('common')->getEncryptedPwd($passWord);
//md5加密密码
if ($userInfo->user_pwd == $md5passWord) {
if (!$userInfo->id) {
$info['message'] = '你无权使用系统...';
} elseif (!$userInfo->status) {
$info['message'] = '用户已锁定...';
} else {
if (isset($params['checkBox']) && !empty($params['checkBox'])) {
//勾选自动登录,存储cookie
setcookie('adminUsername', $userName, $this->cookieTime);
setcookie('adminPassword', $this->GSPcrypt($passWord, 'E', 'ysp'), $this->cookieTime);
} else {
//销毁COOKIE
setcookie('adminUsername', "", -1);
setcookie('adminPassword', "", -1);
}
//记录临时COOKIE
setcookie($this->cookiepre, $userInfo->id, 0);
$info['id'] = $userInfo->id;
$info['type'] = $userInfo->type;
//用户登陆成功,记录登陆日志
$this->loginLog($userInfo->id);
//用户登陆成功,记录最后登陆时间
$this->login->loginLastTime($userInfo->id);
$info['message'] = '登录成功...';
}
} else {
//helper::datalog('用户登录|'.$userName.'|'.$userObj->data->pass.'|'.$passWord,'syslog_');
$info['message'] = '用户名或密码错误...';
}
} else {
$info['message'] = '用户名、密码不能为空...';
}
}
$data = new stdClass();
$data->info = $info;
echo json_encode($data);
}
/**
* 用户登陆成功,记录日志
* @param Int $id 用户ID
* @author liuzhi
* @since 2013/11/17
*/
public function loginLog($id) {
$data = array('user_id' => $id, 'login_ip' => helper::getIp(), 'createtime' => date('Y-m-d H:i:s', time()));
$this->login->loginLog($data, 'ecsa_sys_login_logs');
}
/**
* 退出登录
* @author liuzhi
* 2013/11/12
*/
public function logout() {
$this->login->logout();
$data = new stdClass();
$data->success = true;
echo json_encode($data);
}
/*********************************************************************
* @author yangshipeng
* 函数名称:GSPcrypt
* 函数作用:加密解密字符串
* 使用方法:
* 加密 :GSPcrypt('str','E','nowamagic');
* 解密 :GSPcrypt('被加密过的字符串','D','nowamagic');
* 参数说明:
* $string :需要加密解密的字符串
* $operation:判断是加密还是解密:E:加密 D:解密
* $key :加密的钥匙(密匙);
*********************************************************************/
function GSPcrypt($string, $operation, $key = '') {
$key = md5($key);
$key_length = strlen($key);
$string = $operation == 'D' ? base64_decode($string) : substr(md5($string . $key), 0, 8) . $string;
$string_length = strlen($string);
$rndkey = $box = array();
$result = '';
for ($i = 0; $i <= 255; $i++) {
$rndkey[$i] = ord($key[$i % $key_length]);
$box[$i] = $i;
}
for ($j = $i = 0; $i < 256; $i++) {
$j = ($j + $box[$i] + $rndkey[$i]) % 256;
$tmp = $box[$i];
$box[$i] = $box[$j];
$box[$j] = $tmp;
}
for ($a = $j = $i = 0; $i < $string_length; $i++) {
$a = ($a + 1) % 256;
$j = ($j + $box[$a]) % 256;
$tmp = $box[$a];
$box[$a] = $box[$j];
$box[$j] = $tmp;
$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
}
if ($operation == 'D') {
if (substr($result, 0, 8) == substr(md5(substr($result, 8) . $key), 0, 8)) {
return substr($result, 8);
} else {
return '';
}
} else {
return str_replace('=', '', base64_encode($result));
}
}
}
<file_sep><?php
/**
* The validater and fixer class file of ZenTaoPHP.
*
* ZenTaoPHP is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* ZenTaoPHP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ZenTaoPHP. If not, see <http://www.gnu.org/licenses/>.
*
* @copyright Copyright 2009-2010 青岛易软天创网络科技有限公司(www.cnezsoft.com)
* @author <NAME> <<EMAIL>>
* @package ZenTaoPHP
* @version $Id: filter.class.php 115 2010-06-17 08:58:05Z wwccss $
* @link http://www.zentaoms.com
*/
/**
* validate类,提供对数据的验证。
*
* @package ZenTaoPHP
*/
class validater
{
/**
* 参数个数的最大值。
*/
const MAX_ARGS = 3;
/* 检查是否是布尔型。*/
public static function checkBool($var)
{
return filter_var($var, FILTER_VALIDATE_BOOLEAN);
}
/* 检查是否是整型。*/
public static function checkInt($var)
{
$args = func_get_args();
if($var != 0) $var = ltrim($var, 0); // 将左边的0去掉,filter的这个过滤规则比较严格。
/* 设置了min。*/
if(isset($args[1]))
{
/* 同时设置了max。*/
if(isset($args[2]))
{
$options = array('options' => array('min_range' => $args[1], 'max_range' => $args[2]));
}
else
{
$options = array('options' => array('min_range' => $args[1]));
}
return filter_var($var, FILTER_VALIDATE_INT, $options);
}
else
{
return filter_var($var, FILTER_VALIDATE_INT);
}
}
/* 检查是否是浮点型。*/
public static function checkFloat($var, $decimal = '.')
{
return filter_var($var, FILTER_VALIDATE_FLOAT, array('options' => array('decimail' => $decimal)));
}
/* 检查是否是email地址。*/
public static function checkEmail($var)
{
return filter_var($var, FILTER_VALIDATE_EMAIL);
}
/* 检查是否是URL地址。备注:filter的这个检查并不靠普,比如如果url地址含有中文,就会失效。 */
public static function checkURL($var)
{
return filter_var($var, FILTER_VALIDATE_URL);
}
/* 检查是否是IP地址。NO_PRIV_RANGE是检查是否是私有地址,NO_RES_RANGE检查是否是保留IP地址。*/
public static function checkIP($var, $range = 'all')
{
if($range == 'all') return filter_var($var, FILTER_VALIDATE_IP);
if($range == 'public static') return filter_var($var, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE);
if($range == 'private')
{
if(filter_var($var, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE) === false) return $var;
return false;
}
}
/* 检查是否是日期。bug: 2009-09-31会被认为合法的日期,因为strtotime自动将其改为了10-01。*/
public static function checkDate($date)
{
if($date == '0000-00-00') return true;
$stamp = strtotime($date);
if(!is_numeric($stamp)) return false;
return checkdate(date('m', $stamp), date('d', $stamp), date('Y', $stamp));
}
/* 检查是否符合正则表达式。*/
public static function checkREG($var, $reg)
{
return filter_var($var, FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => $reg)));
}
/* 检查长度是否在指定的范围内。*/
public static function checkLength($var, $max, $min = 0)
{
return self::checkInt(strlen($var), $min, $max);
}
/* 检查长度是否在指定的范围内。*/
public static function checkNotEmpty($var)
{
return !empty($var);
}
/* 检查用户名。*/
public static function checkAccount($var)
{
return self::checkREG($var, '|[a-zA-Z0-9._]{3}|');
}
/* 必须为某值。*/
public static function checkEqual($var, $value)
{
return $var == $value;
}
/* 调用回掉函数。*/
public static function call($var, $func)
{
return filter_var($var, FILTER_CALLBACK, array('options' => $func));
}
}
/**
* fixer类,提供对数据的修正。
*
* @package ZenTaoPHP
*/
class fixer
{
/**
* 要处理的数据。
*
* @var ojbect
* @access private
*/
private $data;
/* 构造函数。*/
private function __construct($scope)
{
switch($scope)
{
case 'post':
$this->data = (object)$_POST;
break;
case 'server':
$this->data = (object)$_SERVER;
break;
case 'get':
$this->data = (object)$_GET;
break;
case 'session':
$this->data = (object)$_SESSION;
break;
case 'cookie':
$this->data = (object)$_COOKIE;
break;
case 'env':
$this->data = (object)$_ENV;
break;
case 'file':
$this->data = (object)$_FILES;
break;
default:
die('scope not supported, should be post|get|server|session|cookie|env');
}
}
/* factory。*/
public function input($scope)
{
return new fixer($scope);
}
/* 去除email里面的非法字符。*/
public function cleanEmail($fieldName)
{
$fields = $this->processFields($fieldName);
foreach($fields as $fieldName) $this->data->$fieldName = filter_var($this->data->$fieldName, FILTER_SANITIZE_EMAIL);
return $this;
}
/* 对URL进行编码。*/
public function encodeURL($fieldName)
{
$fields = $this->processFields($fieldName);
$args = func_get_args();
foreach($fields as $fieldName)
{
$this->data->$fieldName = isset($args[1]) ? filter_var($this->data->$fieldname, FILTER_SANITIZE_ENCODE, $args[1]) : filter_var($this->data->$fieldname, FILTER_SANITIZE_ENCODE);
}
return $this;
}
/* 去除url里面的非法字符。*/
public function cleanURL($fieldName)
{
$fields = $this->processFields($fieldName);
foreach($fields as $fieldName) $this->data->$fieldName = filter_var($this->data->$fieldName, FILTER_SANITIZE_URL);
return $this;
}
/* 获取浮点数。*/
public function cleanFloat($fieldName)
{
$fields = $this->processFields($fieldName);
foreach($fields as $fieldName) $this->data->$fieldName = filter_var($this->data->$fieldName, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION|FILTER_FLAG_ALLOW_THOUSAND);
return $this;
}
/* 获取整型。*/
public function cleanINT($fieldName = '')
{
$fields = $this->processFields($fieldName);
foreach($fields as $fieldName) $this->data->$fieldName = filter_var($this->data->$fieldName, FILTER_SANITIZE_NUMBER_INT);
return $this;
}
/* 处理特殊字符。*/
public function specialChars($fieldName)
{
$fields = $this->processFields($fieldName);
foreach($fields as $fieldName) $this->data->$fieldName = htmlspecialchars($this->data->$fieldName);
return $this;
}
/* 去除字符串里面的标签。*/
public function stripTags($fieldName)
{
$fields = $this->processFields($fieldName);
foreach($fields as $fieldName) $this->data->$fieldName = filter_var($this->data->$fieldName, FILTER_SANITIZE_STRING);
return $this;
}
/* 添加斜线。*/
public function quote($fieldName)
{
$fields = $this->processFields($fieldName);
foreach($fields as $fieldName) $this->data->$fieldName = filter_var($this->data->$fieldName, FILTER_SANITIZE_MAGIC_QUOTES);
return $this;
}
/* 设置默认值。*/
public function setDefault($fields, $value)
{
$fields = strpos($fields, ',') ? explode(',', str_replace(' ', '', $fields)) : array($fields);
foreach($fields as $fieldName)if(!isset($this->data->$fieldName) or empty($this->data->$fieldName)) $this->data->$fieldName = $value;
return $this;
}
/* 条件设置。*/
public function setIF($condition, $fieldName, $value)
{
if($condition) $this->data->$fieldName = $value;
return $this;
}
/* 强制设置。*/
public function setForce($fieldName, $value)
{
$this->data->$fieldName = $value;
return $this;
}
/* 删除某一个字段。*/
public function remove($fieldName)
{
$fields = $this->processFields($fieldName);
foreach($fields as $fieldName) unset($this->data->$fieldName);
return $this;
}
/* 条件删除。*/
public function removeIF($condition, $fields)
{
$fields = $this->processFields($fields);
if($condition) foreach($fields as $fieldName) unset($this->data->$fieldName);
return $this;
}
/* 添加一个字段。*/
public function add($fieldName, $value)
{
$this->data->$fieldName = $value;
return $this;
}
/* 条件添加。*/
public function addIF($condition, $fieldName, $value)
{
if($condition) $this->data->$fieldName = $value;
return $this;
}
/* 连接。*/
public function join($fieldName, $value)
{
if(!isset($this->data->$fieldName) or !is_array($this->data->$fieldName)) return $this;
$this->data->$fieldName = join($value, $this->data->$fieldName);
return $this;
}
/* 调用回掉函数。*/
public function callFunc($fieldName, $func)
{
$fields = $this->processFields($fieldName);
foreach($fields as $fieldName) $this->data->$fieldName = filter_var($this->data->$fieldName, FILTER_CALLBACK, array('options' => $func));
return $this;
}
/* 返回最终处理之后的数据。*/
public function get($fieldName = '')
{
if(empty($fieldName)) return $this->data;
return $this->data->$fieldName;
}
/* 处理传入的字段名:如果含有逗号,将其拆为数组。然后检查data变量中是否有这个字段。*/
private function processFields($fields)
{
$fields = strpos($fields, ',') ? explode(',', str_replace(' ', '', $fields)) : array($fields);
foreach($fields as $key => $fieldName) if(!isset($this->data->$fieldName)) unset($fields[$key]);
return $fields;
}
}
<file_sep><?php
/**
* 公共方法
* @author zhouhong 2011/03/13
*/
class commonModel extends model {
public $k3uid;
public $k3name;
public function __construct() {
parent::__construct('mg_gps_log');
$this->myAdmin = $this->app->myAdmin;
$this->k3uid = 0;
$this->k3name = 'k3';
}
/**
* 写设备操作历史
* @param string $no: 卡号或IMEI
* @param string $action: 操作
* @param string $iono: 出入库单号
*/
public function writeLog($no,$action,$iono=null,$remark=null) {
if(strlen($no) == 8) {
$imei = '';
$gpsno = $no;
} else {
$imei = $no;
$gpsno = 0;
}
$record = array(
'imei' => $imei,
'gpsno' => $gpsno,
'iono' => $iono,
'action' => $action,
'operator' => $this->app->myAdmin->name,
'createtime' => helper::nowTime('Y-m-d H:i:s',time()),
'uid' => $this->app->myAdmin->uid,
'ip' => helper::getIP(),
'remark' => $remark
);
return parent::insert($record,'mg_gps_log');
}
/**
* 读取设备操作历史
* @param string $no: 卡号或IMEI
* @param array $limit: 分页
*/
public function getLog($no,$limit = null) {
if(strlen($no)==8) {
$conds = "gpsno='$no'";
} elseif (strlen($no)==15) {
$conds = "imei='$no'";
/*//update by caoyuling at 2013-10-16 #bugid=3411 GPS管理中设备间历史数据交叉
$conds .= " AND gpsno > 0 ";*/
} else {
return null;
}
$no2 = $this->getNo($no);
if(strlen($no2)==8) {
$conds .= " OR gpsno='$no2'";
} elseif (strlen($no)==15) {
$conds .= " OR imei='$no2'";
/*//update by caoyuling at 2013-10-16 #bugid=3411 GPS管理中设备间历史数据交叉
$conds .= " AND gpsno > 0 ";*/
}
$sql = "SELECT %s FROM mg_gps_log ";
//取记录总数
$fields = " count(*) as count ";
$total = parent::findBySql($sql,$conds,null,null,$fields);
//取记录集
$data = array();
if($total[0]->count > 0) {
$fields = "*";
$data = parent::findBySql($sql, $conds, 'createtime DESC,id desc', $limit, $fields); //modified by yangshipeng for BUG #3038
}
$result = new stdClass();
$result->total = $total[0]->count;
$result->data = $data;
return $result;
}
/**
* 客户补换设备列表(根据客户ID,获取客户坏退服务设备列表)
* @param string $clientid: 客户ID
*/
/* Story #27056 去掉系统中mg_开头表名的代码public function getReplaceList($clientid) {
if(!is_numeric($clientid) || $clientid == '') {
return;
}
$sql = "SELECT %s FROM mg_service a, ".$this->app->config->gps->table." b ";
$fields = " a.serviceid, a.gpsno ";
$conditions = " a.gpsno=b.gpsno AND b.status=2 AND a.clientid=$clientid";
return parent::findBySql($sql, $conditions, null, null, $fields);
}*/
/**
* 获取设备卡号或IMEI号
* @param string $gpsno: 卡号或IMEI号;如果输入卡号则获取IMEI号;反之获取设备卡号
*/
public function getNo($no) {
if(strlen($no)!=8 && strlen($no)!=15 || !is_numeric($no)) {
return null;
}
$conditions = " gpsno='$no' OR gpsid='$no' ";
if(strlen($no)==8) {
$fields = "gpsid AS no";
} else {
$fields = "gpsno AS no";
}
//获取查询结果
$return = parent::findUnique($conditions, null, $fields, $this->app->config->gps->table);
if($return) {
return $return->no;
}
return null;
}
/**
* 按类型返回字典数据
*
* @param int $type:
* @return array
*/
/* Story #27056 去掉系统中mg_开头表名的代码public function getDict($type = 0) {
return parent::findUnique("type=$type", null, 'data', 'mg_dict');
}*/
/**
* 根据用户id和载入系统id返回配置信息(cuiwei)
* @param string $id: 用户id
* @param array $sys: 系统id
*/
public function getsysconfig($id,$sys = '1',$showAll = false) {//默认只列出菜单
if ($this->checkAdmin($id)){//超级管理员,只有一个,并且有所有资源的权限
$sql = "SELECT %s FROM ecsa_sys_source AS a
LEFT JOIN ecsa_sys_users AS b ON b.id = '$id'
LEFT JOIN ecsa_sys_user_roles AS c ON c.user_id = b.id
LEFT JOIN ecsa_sys_roles AS d ON d.id = c.role_id ";
/*
* Task #15448 去除与程序无关的一些用户信息查询,比如用户名及密码等
* 解决:原$fields中 去除 "b.id as uid,b.user_code,b.user_name,b.true_name,b.user_pwd,b.status"字段
*/
$fields = " d.id as role_id,d.role_name,
a.id as source_id,a.source_code,a.source_name,a.url,substring(a.source_code,1,length(a.source_code)-3) as parent_code,a.type,a.status,a.is_display ";//Story #21651
$conditions =" 1 and a.is_del=0 ";
!$showAll?$conditions .= " and a.type='$sys'":'';//检索对应的类型
$data = parent::findBySql($sql,$conditions,'parent_code,a.sort',null,$fields);
}else {
$sql = "SELECT %s FROM ecsa_sys_role_source AS a
LEFT JOIN ecsa_sys_roles AS e ON e.id=a.role_id and e.is_del=0
LEFT JOIN ecsa_sys_user_roles AS b ON e.id=b.role_id and b.is_del=0
LEFT JOIN ecsa_sys_users AS c ON c.id=b.user_id and c.is_del=0
LEFT JOIN ecsa_sys_source AS d ON d.id=a.source_id and d.is_del=0 ";
/*
* Task #15448 去除与程序无关的一些用户信息查询,比如用户名及密码等
* 解决:原$fields中 去除 "c.id as uid,c.user_code,c.user_name,c.true_name,c.user_pwd,c.status"字段
*/
$fields = " e.id as role_id,e.role_name,
d.id as source_id,d.source_code,d.source_name,d.url,substring(d.source_code,1,length(d.source_code)-3) as parent_code,d.type,d.status,d.is_display ";//Story #21651
$conditions =" 1 and c.id='$id' and a.is_del=0 ";
!$showAll?$conditions .= " and d.type='$sys'":'';//检索对应的类型
$data = parent::findBySql($sql,$conditions,'parent_code,d.sort',null,$fields);
}
return $data;
}
/**
* 检查是不是管理员
* //Story #23864修改管理员的权限验证方式
* @author liuzhi
* @param $id 用户ID
**/
public function checkAdmin($id = null)
{
$result = false;
$uid = $id ? $id : $this->myAdmin->id;
if ($uid == '1') {//是超级管理员
$result = true;
} else {
$info = $this->loadModel('user')->getUserInfo($uid);
if (!empty($info) && $info[0]->is_admin == '1') {//是管理员
$result = true;
}
}
return $result;
}
/**
* 字符串替换
* @param $str String 要过滤的值
* @param $exc String 以什么符号分割,默认是 #
* @example F860628003#F860628002 替换成 'F860628003','F860628002'
* @author liuzhi
* @since 2013/12/9
*/
public function subReplace($str,$exc = '#')
{
if(!empty($str) && !is_array($str))
{
$string = '';
$arr = explode($exc,$str);
foreach ($arr as $val)
{
if(empty($val))
{
continue;
}
else
{
$string .= $string?"','".$val:$val;
}
}
return "'".$string."'";
}
}
/**
* 过滤批量接收的字符
* @param $ids String 要过滤的值
* @param $exc String 以什么符号分割,默认是 |
* @param $res String 以什么符号分割成字符串 默认,
* @author liuzhi
* @since 2013/11/11
*/
public function replaceIds($ids,$exc = '|',$res = ',')
{
$string = '';
if(isset($ids) && !empty($ids) && !is_array($ids))
{
$idsArr = explode($exc, $ids);
$tempArr = array();
if(!empty($idsArr))
{
foreach($idsArr as $val)
{
if(empty($val))
{
continue;
}
else
{
if(strpos($val,'~')){
$val = explode('~',$val);
$start = $val[0];
$end = $val[1];
for($i=0;$i<=$end-$start;$i++){
$tempArr[] = intVal($start) + $i;
}
}else{
$tempArr[] = $val;
}
}
}
}
$string = implode($res, $tempArr);
unset($tempArr);
}
return $string;
}
/**
*
* 把对象转成数组
* @param $object 要转的对象$object
* @author liuzhi
* @since 2013/11/11
*/
public function objectToArray($object)
{
$result = array();
if(!empty($object))
{
$object = is_object($object) ? get_object_vars($object) : $object;
foreach ($object as $key => $val)
{
$val = (is_object($val) || is_array($val)) ? $this->objectToArray($val) : $val;
$result[$key] = $val;
}
}
return $result;
}
static public function beginTst(){
$dbh = parent::getDbh($this->dbname);
$dbh->exec('BEGIN');
return $dbh;
}
/*
* 检查权限
* @param String $phpFn 需要有哪个php方法的权限
* @author liuzhi
*/
public function checkPower($_phpFn){
$_jsFn = $this->app->myAdmin->jsFn;//从全局中取得点击的js方法名
$_source = $this->app->myAdmin->source;
$result = false;
if($_jsFn && $_source){
foreach($_source as $key=>$val){
$urlArr = explode('|',$val['url']);
$jsFn = $urlArr[0];
$phpFn = $urlArr[1];
($_jsFn == $jsFn && $_phpFn == $phpFn)?$result = true:'';
}
}
return $result;
}
/**
* 生成出入库单号
* 出库单(开启出库):CK 表ecsa_storage_out 字段 out_no
* 出库单(更换出库):CH 表ecsa_storage_out 字段 out_no
* 入库单(关闭入库):RG 表ecsa_storage_in 字段 in_no
* 入库单(更换入库):RH 表ecsa_storage_in 字段 in_no
* @param $head 编号首字母 R
* @param $no 编号 H1312200001-01
* @example D131218001
* @author liuzhi
* @since 2013/12/20
*/
public function createOutInNo($head = '',$no = '')
{
$out_in_no = "";
$array = array(
'CK' =>array('ecsa_storage_out','out_no'),
'CH' =>array('ecsa_storage_out','out_no'),
'CM' =>array('ecsa_storage_out','out_no'),// <NAME>uan 耗材出库 2014/3/14
'RG' =>array('ecsa_storage_in','in_no'),
'RH' =>array('ecsa_storage_in','in_no')
);
if(!empty($head) && !empty($no))
{
//截取前两位字母
$head_no = substr($head.$no,0,2);
$out_in_no = $head_no.substr($no,1);
if(isset($array[$head_no]) && !empty($array[$head_no]))
{
$data = $array[$head_no];
$sql = "SELECT %s FROM $data[0]";
$fields = " MAX($data[1]) as no ";
$where = " $data[1] LIKE '$out_in_no%' ";
$result = parent::findBySql($sql,$where,null,null,$fields);
if($result[0]->no)
{
$arr = explode('-',$result[0]->no);
$str = sprintf("%02d",($arr[1]) + 1);
$out_in_no = $arr[0].'-'.$str;
}
else
{
$out_in_no .= '-01';
}
}
}
return $out_in_no;
}
/**
* 生成回单号Story #18148现场实施工单--->回单
* @param $head 编号首字母 JXC
* @param $no 编号 JXC1408290002
* @example D131218001
* @author <NAME>
* @since 2013/12/20
*/
public function createBackNo($head = '',$no = '')
{
$out_in_no = "";
$array = array(
'JXC' =>array('ecsa_jobs_implement_backs','back_no','job_no'),
'JNS' =>array('ecsa_jobs_nianshen_backs','back_no','job_no'),
);
//截取前两位字母
$head_no = substr($no,0,3);
$out_in_no = $head_no.substr($no,3);
if(isset($array[$head_no]) && !empty($array[$head_no]))
{
$data = $array[$head_no];
$sql = "SELECT %s FROM $data[0]";
$fields = " MAX($data[1]) as no ";
$where = " $data[1] LIKE '$out_in_no%' and $data[2] = '$out_in_no' ";
$result = parent::findBySql($sql,$where,null,null,$fields);
if($result[0]->no)
{
$arr = explode('-',$result[0]->no);
$str = sprintf("%02d",($arr[1]) + 1);
$out_in_no = $arr[0].'-'.$str;
}
else
{
$out_in_no .= '-01';
}
}
return $out_in_no;
}
/**
* 订单号生成规则 编号 + 年月日+001。 如果库里有编号,取出库里最大编号+1,否则+0001
* 合同订单:D 表ecsa_contract_orders 字段order_no
* 服务开启:K 表ecsa_orders 字段order_no
* 服务更换:H 表ecsa_gps_change 字段change_no
* 服务关闭:G 表ecsa_service_close 字段close_no
* 服务续费:X 表ecsa_service_charge 字段charge_no
* 转服务方式:Z 表ecsa_service_turn 字段turn_no
* @param $head 编号首字母
* @example X1312200001
* @author liuzhi
* @since 2013/12/20
*/
public function createOrderNo($head = '')
{
$order_no = "";
$array = array(
'D' =>array('ecsa_contract','order_no'),
'K' =>array('ecsa_orders','order_no'),
'H' =>array('ecsa_gps_change','change_no'),
'G' =>array('ecsa_service_close','close_no'),
'Z' =>array('ecsa_service_turn','turn_no'),
'X' =>array('ecsa_service_charge','charge_no'),
'M' =>array('ecsa_sales','sales_no'),//Story #18148 现场实施工单 guojuan
'JXC' =>array('ecsa_jobs_implement','job_no'),
'JXCH' =>array('ecsa_jobs_implement_backs','back_no'),
'JNS' =>array('ecsa_jobs_nianshen','job_no'),
'JNSH' =>array('ecsa_jobs_nianshen_backs','back_no')
);
if(isset($array[$head]) && !empty($array[$head]))
{
$data = $array[$head];
$order_no = $head.date('ymd');
$sql = "SELECT %s FROM $data[0]";
$fields = " MAX($data[1]) as no ";
$where = " $data[1] LIKE '$order_no%' ";
$result = parent::findBySql($sql,$where,null,null,$fields);
if($result[0]->no)
{
$order_no .= sprintf("%04d",(substr($result[0]->no,-4) + 1));
}
else
{
$order_no .= '0001';
}
}
return $order_no;
}
/**
* 生成服务ID
* @param $head 编号首字母 F
* 编号 + 年月日 + 当日序号最大值+1
* 1位 + 6位 + 5位
* @example F13122400001
* @author liuzhi
* @since 2013/12/20
*/
public function createServiceNo($head = '')
{
$service_no = "";
if(!empty($head))
{
$service_no = $head.date('ymd');
$sql = "SELECT %s FROM ecsa_services";
$fields = " MAX(service_id) as no ";
$where = " service_id LIKE '$service_no%' ";
$result = parent::findBySql($sql,$where,null,null,$fields);
if($result[0]->no)
{
$service_no .= sprintf("%05d",(substr($result[0]->no,-5) + 1));
}
else
{
$service_no .= '00001';
}
}
return $service_no;
}
/**
* 生成客户服务CASE IDStory #13148
* @param $head 编号首字母
* 编号 + 年月日 + 当日序号最大值+1
* 1位 + 6位 + 5位
* @example CS13122400001
* @author liuzhi
* @since 2014/06/25
*/
public function createCaseNo($head = '')
{
$case_no = "";
if(!empty($head))
{
$case_no = $head.date('ymd');
$sql = "SELECT %s FROM ecsa_cs_cases";
$fields = " MAX(case_no) as no ";
$where = " case_no LIKE '$case_no%' ";
$result = parent::findBySql($sql,$where,null,null,$fields);
if($result[0]->no)
{
$case_no .= sprintf("%05d",(substr($result[0]->no,-5) + 1));
}
else
{
$case_no .= '00001';
}
}
return $case_no;
}
/**
* 生成开票管理单号Story #13851
* @param $head 编号首字母
* 编号 + 年月日 + 当日序号最大值+1
* 1位 + 6位 + 4位
* @example 1312240001
* @author liuzhi
* @since 2014/08/21
*/
public function createInvoiceNo($head = '')
{
$invoice_no = $head . date('ymd');
$sql = "SELECT %s FROM ecsa_income_invoices";
$fields = " MAX(invoice_no) as no ";
$where = " invoice_no LIKE '$invoice_no%' ";
$result = parent::findBySql($sql,$where,null,null,$fields);
if($result[0]->no)
{
$invoice_no .= sprintf("%04d",((int)substr($result[0]->no,-4) + 1));
}
else
{
$invoice_no .= '0001';
}
return $invoice_no;
}
/**
* 无限极分类,修改customer_code跟org_code
* @param Int $old_code 修改之前的code
* @param Int $new_code 修改之后生成的code
* @param Sting $table 表名
* @param Sting $field 字段名
* @author liuzhi
* @since 2013/12/16
*/
public function updateCode($old_code,$new_code,$table,$field)
{
$sql = "UPDATE $table SET $field = CONCAT('$new_code',SUBSTR($field,LENGTH('$old_code')+1)) WHERE $field LIKE '$old_code%';";
return parent::exec($sql);
}
/**
* 添加旧系统的服务ID记录(临时性用于G7同步服务)
* @author yangshipeng
* @since 2013/12/30
* @param $conf 设备记录表需要插入的数据
* @return boolean 更新结果
*/
/* Story #27056 去掉系统中mg_开头表名的代码 public function addOldService($conf = array()){
if(empty($conf)){
return false;
}
$now = helper::nowTime();
$_setArr = array(
'createtime' => $now
);
$_setArr = array_merge($_setArr,$conf);
return parent::insert($_setArr,'mg_service');
}*/
/**
* 更新旧服务表数据(临时性用于G7同步服务)
* @author yangshipeng
* @param type $setarr 设置新的字段内容
* @param type $ids where条件字段值
* @return int 返回更新的行数,false代表参数错误,0代表一条记录也未更新
*/
/* Story #27056 去掉系统中mg_开头表名的代码public function modifyOldService($setarr=array(),$ids=array()){
if(empty($setarr) || empty($ids)){
return false;
}
//修改条件里没有设备号,修改风险较大,修改请求被驳回
if(!array_key_exists("gpsno",$ids) && !array_key_exists("serviceid",$ids)){
return false;
}
return parent::update($setarr,$ids,'mg_service');
}*/
/**
* 添加服务修改记录
* Story #14738K3-GSP回写:出库后,终端列表的操作人、服务列表的操作人应该是准确的操作人,即从K3上获取的操作人
* @author liuzhi
* @since 2013/12/23
* @param $conf 服务表需要插入的log数据
* @return boolean 更新结果
* @example array(service_id=>'', //服务ID
* gpsno=>'', //服务下的终端号(包括虚拟终端)
* action=>'', //新生成、更换终端、更换服务方式、续费、关闭服务
* action_detail=>'', //事件详情
* remark=>'', //备注
* no=>'') //操作相关单号
*/
public function addServiceLog($conf = array()){
if(!empty($conf)){//Story #11203 更换入库、关闭入库并没有记入服务历史
//Story #12613 增加续费基数调整 by lixiaoli
$action = array('服务开启','服务方式转变','服务续期','设备更换','服务关闭','关闭退回入库','更换退回入库', '续费基数调整');
$now = helper::nowTime();
$_setArr = array(
'creator_id' => $this->myAdmin->id,
'last_operator' => $this->myAdmin->true_name,
'createtime' => $now,
'updatetime' => $now,
);
if(!$_setArr['creator_id'])
{
$_setArr['creator_id'] = $conf['creator_id'];//Story #14737 K3-GSP回写:入库记录的入库人
$_setArr['last_operator'] = $conf['last_operator'];
}
$_setArr = array_merge($_setArr,$conf);
foreach($action as $v){
if($v == $_setArr['action']){
return parent::insert($_setArr,'ecsa_service_logs');
}
}
}
return false;
}
/**
* 添加设备修改记录
* Story #14738K3-GSP回写:出库后,终端列表的操作人、服务列表的操作人应该是准确的操作人,即从K3上获取的操作人
* @author liuzhi
* @since 2013/12/23
* @param $conf 设备记录表需要插入的log数据
* @return boolean 更新结果
* @example array(gpsno=>'', //设备号
* action=>'', //触发事件
* gpsno_relation=>'',//相关联的设备号
* action_detail=>'', //事件详情
* remark=>'', //备注
*/
public function addGpsLog($conf = array()){
if(!empty($conf)){
$action = array('销售出库','更换出库','设备被更换',
'关闭设备退回申请','关闭设备免退回申请',
'设备收回','设备撤销收回','设备丢失','设备找回','设备检测',
'关闭退回入库','更换退回入库','质检通过','质检驳回','设备生成','设备编辑'
);
$now = helper::nowTime();
$_setArr = array(
'creator_id' => $this->myAdmin->id,
'last_operator' => $this->myAdmin->true_name,
'createtime' => $now,
'updatetime' => $now,
);
if(!$_setArr['creator_id'])
{
$_setArr['creator_id'] = $conf['creator_id'];//Story #14737 K3-GSP回写:入库记录的入库人
$_setArr['last_operator'] = $conf['last_operator'];
}
$_setArr = array_merge($_setArr,$conf);
foreach($action as $v){
if($v == $_setArr['action']){
return parent::insert($_setArr,'ecsa_gps_logs');
}
}
}
return false;
}
/**
* 添加case日志Story #17744 case历史是指case的生命周期,如何时创建、编辑、工单状态、跟单、关闭,参考设备历史
* @author guojuan
* @since 2013/12/23
* @param $conf 需要插入的log数据
* @return boolean 更新结果
* @example array(gpsno=>'', //设备号
* action=>'', //触发事件
* gpsno_relation=>'',//相关联的设备号
* action_detail=>'', //事件详情
* remark=>'', //备注
*/
public function addCaseLog($conf = array()){
if(!empty($conf)){
$action = array('新增','删除','编辑','添加跟进','编辑跟进','删除跟进','添加工单',
'编辑工单','工单状态变化','添加总结','编辑总结','删除总结','关闭'
);
$now = helper::nowTime();
$_setArr = array(
'creator_id' => $this->myAdmin->id,
'createtime' => $now,
);
$_setArr = array_merge($_setArr,$conf);
foreach($action as $v){
if($v == $_setArr['action']){
return parent::insert($_setArr,'ecsa_cs_case_log');
}
}
}
return false;
}
/**
* 添加工单日志Story #18148现场实施工单 guojuan
* @author guojuan
* @since 2013/12/23
* @param $conf 需要插入的log数据
* @return boolean 更新结果
* @example array(gpsno=>'', //设备号
* action=>'', //触发事件
* gpsno_relation=>'',//相关联的设备号
* action_detail=>'', //事件详情
* remark=>'', //备注
*/
public function addJobsLog($conf = array()){
if(!empty($conf)){
$action = array(
'添加','删除','编辑','驳回','进行中','添加回单','取消','完成','确认',//Story #21893
'备注','回单添加','回单编辑','回单删除','回单审核','回单销审'
);
$now = helper::nowTime();
$_setArr = array(
'creator_id' => $this->myAdmin->id,
'createtime' => $now,
);
$_setArr = array_merge($_setArr,$conf);
foreach($action as $v){
if($v == $_setArr['action']){
return parent::insert($_setArr,'ecsa_jobs_logs');
}
}
}
return false;
}
/**
* 添加工单明细日志Story #21887 现场实施工单优化第三版20140916-1 guojuan
* @author guojuan
* @since 2014/9/18
* @param $conf 需要插入的log数据
* @return boolean 更新结果
* @example array(gpsno=>'', //设备号
* action=>'', //触发事件
* gpsno_relation=>'',//相关联的设备号
* action_detail=>'', //事件详情
* remark=>'', //备注
*/
public function addBacksLog($conf = array()){
if(!empty($conf)){
$action = array('实施确认','复测','切换结算状态'
);
$now = helper::nowTime();
$_setArr = array(
'creator_id' => $this->myAdmin->id,
'createtime' => $now,
);
$_setArr = array_merge($_setArr,$conf);
foreach($action as $v){
if($v == $_setArr['action']){
return parent::insert($_setArr,'ecsa_jobs_implement_backs_logs');
}
}
}
return false;
}
/**
* 添加设备修改记录
* @author liuzhi
* @since 2013/12/23
* @param $conf 设备记录表需要插入的log数据
* @return boolean 更新结果
* @example array(gpsno=>'', //设备号
* action=>'', //触发事件
* gpsno_relation=>'',//相关联的设备号
* action_detail=>'', //事件详情
* remark=>'', //备注
*/
public function addSimLog($conf = array()){
if(!empty($conf)){
$action = array('添加','编辑','被更换','更换','查余额');
$now = helper::nowTime();
$_setArr = array(
'operator_id' => $this->myAdmin->id,
'createtime' => $now,
);
$_setArr = array_merge($_setArr,$conf);
if (in_array($_setArr['action'], $action)) {
return parent::insert($_setArr,'ecsa_sim_logs');
}
}
return false;
}
/**
* 新增旧设备历史表日志 (用于旧系统gps管理-历史记录查询)
* @author yangshipeng
* @param type $conf 设备记录表需要插入的log数据
* @return boolean
*/
public function addOldGpsLog($conf = array()){
if(!empty($conf)){
$action = array('销售出库','更换出库','设备被更换',
'关闭设备退回申请','关闭设备免退回申请',
'设备收回','设备撤销收回','设备丢失','设备找回','设备检测',
'关闭退回入库','更换退回入库','质检通过','质检驳回','设备生成','设备编辑'
);
$now = helper::nowTime();
$_setArr = array(
'remark'=>'新系统自动生成旧系统操作日志',
'operator'=>$this->myAdmin->true_name,
'uid' => $this->myAdmin->id,
'ip'=>helper::getIP(),
'createtime' => $now
);
if(!$_setArr['uid'])
{
$_setArr['uid'] = $conf['uid'];//Story #14737 K3-GSP回写:入库记录的入库人
$_setArr['operator'] = $conf['operator'];
}
$_setArr = array_merge($_setArr,$conf);
if(in_array($_setArr['action'], $action)){
return parent::insert($_setArr,'mg_gps_log');
}
}
return false;
}
/**
* 添加应收修改记录
* @author liuzhi
* @since 2013/12/23
* @param $conf 应收记录表需要插入的log数据
* @return boolean 更新结果
* @example param1 array(
'customer_id' => $customer_id,
'income_type' => '服务开启',
'dev_total' => 0,
'suite_total' => $suite_price*$num, //套装费用
'parts_total' => 0, //配件费用
'serv_total' => $serv_price*$num, //新出库平台费
'install_total' => $install_price*$num, //安装费
'check_total' => $check_price*$num, //年审费
'compensate_total' => $compensate_price*$num, //赔偿款
'no' => $order_no, //开启单号
'income_total' => $total*$num, //应收总额
);
*/
public function addIncomeLog($conf = array()){
if(!empty($conf)){
$sql = "SELECT %s FROM ecsa_income_type";
$fields = " * ";
$where = " 1 ";
$action = parent::findBySql($sql,$where,null,null,$fields);
$now = helper::nowTime();
$_setArr = array(
'creator_id' => $this->myAdmin->id,
'last_operator' => $this->myAdmin->true_name,
'createtime' => $now,
'updatetime' => $now,
);
if(!$_setArr['creator_id'])
{
$_setArr['creator_id'] = $this->k3uid;
$_setArr['last_operator'] = $this->k3name;
}
$_setArr = array_merge($_setArr,$conf);
$typeErr = true;//Story #21893
foreach($action as $v){
if($v->name == $_setArr['income_type']){
$typeErr = false;//Story #21893
$_setArr['income_type'] = $v->id;
return parent::insert($_setArr,'ecsa_income');
}
}
if ($typeErr) {//应收类型不存在Story #21893
return false;
}
}
return false;
}
/**
*查询用户对应的组织id所对应的客户id串(逗号隔开)
* @author <NAME>
* @since 2013/12/4
* $uid 用户id
*/
public function getUserOrgCustomerId()
{
$uid = $this->myAdmin->id;
//查询用户的组织org_code
$sql = " SELECT gso.org_code FROM ecsa_sys_users gsu LEFT JOIN ecsa_sys_orgs gso ON gsu.org_id=gso.id WHERE gsu.id = $uid ";
$orgcodeQuery = $this->query ( $sql );
$orgRe = $orgcodeQuery->fetchAll ();
$orgcode = $orgRe[0]->org_code;
//通过org_code查询出本级及下级的orgid
$sql_orgid = " SELECT id FROM ecsa_sys_orgs WHERE org_code LIKE '$orgcode%' ";
$orgidQuery = $this->query ( $sql_orgid );
$orgidRe = $orgidQuery->fetchAll ();
$orgid = '';
foreach ($orgidRe as $v)
{
if($orgid == '')
{
$orgid .= $v->id;
} else {
$orgid .= ",".$v->id;
}
}
//通过orgid查询出
$sql_cust = " select id from ecsa_customer WHERE org_id in($orgid) and is_del=0 ";
$custQuery = $this->query ( $sql_cust );
$custRe = $custQuery->fetchAll ();
$custid = '';
foreach ($custRe as $v)
{
if($custid == '')
{
$custid .= $v->id;
} else {
$custid .= ",".$v->id;
}
}
return $custid;
}
/**
* 添加服务同步日志表记录
* @author guojuanjuan
* @since 2014/3/4
* @param $conf 服务同步日志表需要插入的数据
* @return boolean 更新结果
*/
public function addServiceSynLog($conf = array()){
if(empty($conf)){
return false;
}
$now = helper::nowTime();
$_setArr = array(
'createtime' => $now,
'updatetime' => $now
);
$_setArr = array_merge($_setArr,$conf);
return parent::insert($_setArr,'ecsa_services_syn_logs');
}
/**
* 把数据整理成树状
* @author liuzhi
* @since 2013/12/31
* @param unknown $data
* @param unknown $column
*/
public function ToTreeModel($data,$column){
foreach ($data as $k=>$v){
$data[$k]->uiProvider = 'col';
$data[$k]->leaf = true;//默认没有子集
$parent_code = strlen($v->$column)>3?substr($v->$column,0,-3):0;
$this->editdata($data,$parent_code,$k,$data,$column);
}
return $data;
}
/**
* 处理检索出来的结果,树状 ToTreeModel专用
* @param unknown $data
* @param unknown $parentid
* @param unknown $k
* @param unknown $_tmp
* @param unknown $column
*/
public function editdata(&$data,$parentid,$k,&$_tmp,$column){
foreach($data as $dKey=>$dVal){
if(isset($dVal->children) && $dVal->children != null){
$this->editdata($data[$dKey]->children,$parentid,$k,$_tmp,$column);
}
if($dVal->$column == $parentid){
$data[$dKey]->children[] = (Object)$_tmp[$k];
$data[$dKey]->leaf = false;
unset($_tmp[$k]);
}
}
}
/**
* 发送邮件
* //Story #25392 2014/11/14 liuzhi添加附件参数及log,支持发送附件
* @param $sendto_email:发送到的邮箱地址
* @param $subject:邮箱标题
* @param $body:邮件内容
* @author <NAME>
* @since 2014/8/4
*/
public function smail($sendto_email,$subject,$body, $extra_hdrs='',$user_name='',$attach = false)
{
$fname = $extra_hdrs;
$result = 0;//返回值1成功,0失败
$this->app->loadClass('phpmailer', $static = true);
$mail = new PHPMailer();
$mail->clearAddresses();
$mail->clearAttachments();
$mail->IsSMTP(); // send via SMTP
$mail->SMTPDebug = 0;
$mail->Host = "smtp.huoyunren.com"; // SMTP servers
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Port = 25;
$mail->Username = "<EMAIL>"; // SMTP username 注意:普通邮件认证不需要加 @域名
$mail->Password = "<PASSWORD>"; // SMTP password
$mail->From = "<EMAIL>"; // 发件人邮箱
$mail->FromName = helper::charseticonv('GSP','gbk'); // 发件人
$mail->CharSet = "gb2312"; // 这里指定字符集!
$mail->Encoding = "base64";
if(is_array($sendto_email)){
if(!empty($sendto_email)){
foreach($sendto_email as $v){
$mail->AddAddress($v,$fname); // 收件人邮箱和姓名
}
}
}else{
$mail->AddAddress($sendto_email,"IPS"); // 收件人邮箱和姓名
}
$mail->AddReplyTo("<EMAIL>","http://ips2.huoyunren.com");
$mail->IsHTML(true);
$mail->Subject = helper::charseticonv($subject,'gbk');
$mail->Body = helper::charseticonv($body);
$mail->AltBody ="text/html";
//添加附件
if ($attach) {
if (is_file($attach)) {
$mail->AddAttachment($attach);//添加附件
} else {
//记录日志
helper::datalog('MAIL:' . '附件不存在' . $attach, 'MAIL_');
}
}
if(!$mail->Send())
{
$logs .= var_export($sendto_email, true) . "send mail error \r\n";
$logs .= "error info | " . $mail->ErrorInfo . " \r\n";
$logs .= "text | " . $body . "\r\n";
$result = -1;
}
else {
$logs .= $user_name . "send mail ok! " . var_export($sendto_email, true) . "\r\n";
$result = 1;
}
//记录日志
helper::datalog('MAIL:' . $logs, 'MAIL_');
return $result;
}
/**
* 发送短信 返回结果 -2 信息不能为空 -1 手机号不合法 0 失败 1 成功
* @author lixiaoli
* @param $receive_mobile 接收手机号
* @param $content 短信内容
* @since 2014/08/07
* 目前短信接口支持信息群发,号码之间用英文逗号隔开,最多同时发送30个号码
*/
public function sendMessage($receive_mobiles,$content){
if(empty($content)){
echo -2;//信息不能为空
exit;
}
if($receive_mobiles){
$receive_mobiles = trim($receive_mobiles);
preg_match('/^\d{11}(,\d{11})*$/', $receive_mobiles, $matchArr);
if(!$matchArr){
echo -1;//手机号不合法
exit;
}
$inarr = array(
'userid' => 'chinaway',
'mobiles' => $receive_mobiles,
'content' => trim($content),
'channel' => 'modem'
);
/*
* 如果有多个手机号,去重
* 手机号多于30个,则分多次发送信息,每次发送30个
*/
if(strpos($receive_mobiles, ',') >= 0){
$mobileArr = explode(',', $receive_mobiles);
$mobileArr = array_unique($mobileArr);
if(count($mobileArr) > 30){
$mobiles = array_chunk($mobileArr, 30);
foreach($mobiles as $val){
$inarr['mobiles'] = join(',', $val);
//接口返回结果SenderService
$result = $this->loadModel('client')->smssender($inarr);
$result = json_decode($result);
if($result->code == 0) {
return 1;//发送成功!
exit;
} else {
return 0;//发送失败!
exit;
}
}
}else{
$inarr['mobiles'] = join(',', $mobileArr);
}
}
//接口返回结果SenderService
$result = $this->loadModel('client')->smssender($inarr);
$result = json_decode($result);
if($result->code == 0) {
return 1;//发送成功!
} else {
return 0;//发送失败!
}
}
}
/**
* 发送报警信息(短信、邮件)
* 返回结果 1 成功 -1 邮件和短信都发送失败 -2 邮件发送失败 -3 短信发送失败 -4 此用户没有报警配置 -5 参数不正确
* @author lixiaoli
* @param $monitor_type 监控类型
* @param $group_type 组织类型
* @param $group 组织
* @param $content 发送内容
*/
public function sendMonitorMessage($monitor_type, $group_type, $group, $content){
if($monitor_type && $group_type && $group && $content){
$result = $this->loadModel('monitor_config')->getInfo($monitor_type, $group_type, $group);
if($result){
//邮件群发时邮箱为数组格式
if(strpos($result->email, ',')){
$sendto_email = explode(',', $result->email);
}else{
$sendto_email = $result->email;
}
$subject = $result->title;
$mobiles = $result->mobile;
$emailRes = $this->smail($sendto_email, $subject, $content);
$messageRes = $this->sendMessage($mobiles, $content);
if($emailRes == 1 && $messageRes == 1){
echo 1;
}else{
if($emailRes != 1 && $messageRes != 1){
echo -1;
}elseif($emailRes != 1){
echo -2;
}elseif($messageRes != 1){
echo -3;
}
}
}else{
echo -4;
}
}else{
echo -5;
}
}
/**
* 获取加密密码 Story #20061 GSP使用ldap服务成功
* @param $pwd
* @return string
* @author lixiaoli
* @since 2014/10/13
*/
public function getEncryptedPwd($pwd)
{
return "{MD5}" . base64_encode(pack('H*', md5($pwd)));
}
/**
* 得到OSS对象//Story #24257
* @return ALIOSS
* @author liuzhi
* @date Oct 24, 2014
*/
public function getOssObj(){
$this->app->loadClass('oss', true);
$oss_sdk_service = new ALIOSS();
//设置是否打开curl调试模式
$oss_sdk_service->set_debug_mode(FALSE);
return $oss_sdk_service;
}
/**
* 把图片上传到OSS//Story #24257
* @param unknown $file
* @param unknown $id
* @param string $dirName
* @param string $bucket
* @throws Exception
* @return string
* @author liuzhi
* @date Oct 24, 2014
*/
public function file_upload_oss($file, $id, $dirName = null,$bucket = 'gsp-fs'){
set_time_limit(0);
try {
if (empty($file) || empty($file['name'])) {
//未选择文件
throw new Exception('未选择文件', 1);
}
$extArray = array('bmp','jpg','png','tiff','gif','pcx','tga','exif','fpx','svg','psd','cdr','pcd','dxf','ufo','eps','ai','raw');
if ($file['name']) {
$ext = strtolower(trim(substr(strrchr($file['name'], '.'), 1)));
if (!in_array($ext,$extArray)) {
//文件类型不正确
throw new Exception('文件类型不正确', 1);
}
$size = ($file['size']/1024)/1024;
if ($size > 10) {
//文件大小超过10M
throw new Exception('文件大小超过10M', 1);
}
}
if ($file["error"] > 0) {
throw new Exception('长传出错: ' . $file["error"], 1);
} else {
if (!$dirName) throw new Exception('路径名不能为空', 1);
$dir = $dirName;
$dataname = $dir . '/' . $id . '.' . $ext;
$oss_sdk_service = $this->getOssObj();
$upload_file_options = array('content' => file_get_contents($file['tmp_name']), 'length' => $file['size']);//Story #24257
$upload_file_by_content = $oss_sdk_service->upload_file_by_content($bucket, $dataname, $upload_file_options);
//记录日志
helper::datalog('OSS-UPLOAD:'. var_export($upload_file_by_content, true), 'OSS_');
if ($upload_file_by_content->status == '200') {
$url = $upload_file_by_content->header['_info']['url'];
if (!$url) {
throw new Exception('取得文件名失败', 1);
}
return $url;
} else if ($error = simplexml_load_string($upload_file_by_content->body)) {
throw new Exception($error->Message, 1);
} else {
throw new Exception('上传异常', 1);
}
}
} catch (OSS_Exception $e) {
//记录OSS连接异常
helper::datalog('OSS-UPLOAD:' . $e->getCode() . ':' . $e->getMessage(), 'OSS_');
//抛出异常
throw new Exception('OSS连接异常', 1);
} catch (Exception $e) {
//记录自定义异常
helper::datalog('OSS-UPLOAD:' . $e->getCode() . ':' . $e->getMessage(), 'OSS_');
$message = $e->getCode() == '1' ? $e->getMessage() : '上传失败';
//抛出异常
throw new Exception($message, $e->getCode());
}
}
/**
* 删除OSS上的文件//Story #24257
* @param unknown $file
* @param string $bucket
* @throws Exception
* @return boolean
* @author liuzhi
* @date Oct 27, 2014
*/
public function file_delete_oss($file = null, $bucket = 'gsp-fs'){
try{
if (!$file) throw new Exception('文件名不能为空', 1);
$oss_sdk_service = $this->getOssObj();
$is_object_exist = $oss_sdk_service->is_object_exist($bucket,$file);
//记录日志
helper::datalog('OSS-ISEXIST:'. var_export($is_object_exist, true), 'OSS_');//Story #24257
if ($is_object_exist->status == '404') {
throw new Exception('文件不存在', 1);
} else {
$delete_object = $oss_sdk_service->delete_object($bucket, $file);
//记录日志
helper::datalog('OSS-DEL:'. var_export($delete_object, true), 'OSS_');
if ($delete_object->status == '204') {
return true;
} else if ($error = simplexml_load_string($delete_object->body)) {
throw new Exception($error->Message, 1);
} else {
throw new Exception('删除异常', 1);
}
}
} catch (OSS_Exception $e) {
//记录OSS连接异常
helper::datalog('OSS-DEL:' . $e->getCode() . ':' . $e->getMessage(), 'OSS_');
//抛出异常
throw new Exception('OSS连接异常', 1);
} catch (Exception $e) {
//记录自定义异常
helper::datalog('OSS-DEL:' . $e->getCode() . ':' . $e->getMessage(), 'OSS_');
$message = $e->getCode() == '1' ? $e->getMessage() : '删除失败';
//抛出异常
throw new Exception($message, $e->getCode());
}
}
/**
* 上传所有类型的文件,不做文件类型验证//Story #24257
*
* @author liuzhi
* @date Oct 29, 2014
*/
public function uploadFileToOss($file = null, $newName = null, $dirName = null, $update = false, $bucket = 'gsp-fs'){
set_time_limit(0);
try {
if (empty($file) || empty($file['name'])) {
//未选择文件
throw new Exception('未选择文件', 1);
}
if ($file["error"] > 0) {
throw new Exception('长传出错: ' . $file["error"], 1);
} else {
if (!$dirName) throw new Exception('路径名不能为空', 1);
$dir = $dirName;
$newName = $newName ? $newName : $file['name'];
$dataname = $dir . '/' . $newName;
//验证文件是否存在
$oss_sdk_service = $this->getOssObj();
$is_object_exist = $oss_sdk_service->is_object_exist($bucket, $dataname);
//记录日志
helper::datalog('OSS-ISEXIST:'. var_export($is_object_exist, true), 'OSS_');
//如果存在,重命名
if ($is_object_exist->status == '200' && !$update) {
$dataname = $dir . '/' . time().'__' . $newName;
}
$upload_file_options = array('content' => file_get_contents($file['tmp_name']), 'length' => $file['size']);
$upload_file_by_content = $oss_sdk_service->upload_file_by_content($bucket, $dataname, $upload_file_options);
//记录日志
helper::datalog('OSS-UPLOAD:'. var_export($upload_file_by_content, true), 'OSS_');
if ($upload_file_by_content->status == '200') {
$url = $upload_file_by_content->header['_info']['url'];
if (!$url) {
throw new Exception('取得文件名失败', 1);
}
return $url;
} else if ($error = simplexml_load_string($upload_file_by_content->body)) {
throw new Exception($error->Message, 1);
} else {
throw new Exception('上传异常', 1);
}
}
} catch (OSS_Exception $e) {
//记录OSS连接异常
helper::datalog('OSS-UPLOAD:' . $e->getCode() . ':' . $e->getMessage(), 'OSS_');
//抛出异常
throw new Exception('OSS连接异常', 1);
} catch (Exception $e) {
//记录自定义异常
helper::datalog('OSS-UPLOAD:' . $e->getCode() . ':' . $e->getMessage(), 'OSS_');
$message = $e->getCode() == '1' ? $e->getMessage() : '上传失败';
//抛出异常
throw new Exception($message, $e->getCode());
}
}
/**
* 判断OSS上的文件是否存在
* Task #32363
* @param unknown $file
* @param string $bucket
* @throws Exception
* @return boolean
* @author liuzhi
* @date Oct 27, 2014
*/
public function file_exist_oss($file = null, $bucket = 'gsp-fs'){
try{
$exist = true;
if (!$file) throw new Exception('文件名不能为空', 1);
$oss_sdk_service = $this->getOssObj();
$is_object_exist = $oss_sdk_service->is_object_exist($bucket,$file);
//记录日志
helper::datalog('OSS-ISEXIST:'. var_export($is_object_exist, true), 'OSS_');
if ($is_object_exist->status == '404') {
$exist = false;
}
return $exist;
} catch (OSS_Exception $e) {
//记录OSS连接异常
helper::datalog('OSS-DEL:' . $e->getCode() . ':' . $e->getMessage(), 'OSS_');
//抛出异常
throw new Exception('OSS连接异常', 1);
} catch (Exception $e) {
//记录自定义异常
helper::datalog('OSS-ISEXIST:' . $e->getCode() . ':' . $e->getMessage(), 'OSS_');
$message = $e->getCode() == '1' ? $e->getMessage() : '判断文件是否存在失败';
//抛出异常
throw new Exception($message, $e->getCode());
}
}
/**
* 引入PHPExcel,并返回对象
* //Story #25392
* @return PHPExcel
* @author liuzhi
* @date Nov 14, 2014
*/
public function getPhpExcel(){
// gsp/lib/
$appLibRoot = $this->app->getCoreLibRoot();
include_once $appLibRoot . 'excelClass/PHPExcel.php';
return new PHPExcel();
}
}
<file_sep>/**
* 公告列表
* yuli
* 2013/11/12
*/
noticeStore.load();
var _sm =new Ext.grid.RowSelectionModel({
singleSelect: true,
listeners: {
selectionchange: function(data) {
if (data.getCount())
{
(Ext.getCmp('noticeDelete')) ? Ext.getCmp('noticeDelete').enable() : '';//删除按钮
(Ext.getCmp('noticeUpdate')) ? Ext.getCmp('noticeUpdate').enable() : '';//修改按钮
}
else
{
(Ext.getCmp('noticeDelete')) ? Ext.getCmp('noticeDelete').disable() : '';//删除按钮
(Ext.getCmp('noticeUpdate')) ? Ext.getCmp('noticeUpdate').disable() : '';//修改按钮
}
}
}
});
//公告列表 开始
var grid_list = new Ext.grid.GridPanel({
title :'系统公告',
region : 'center',
loadMask : true,
cm : new Ext.grid.ColumnModel([
// new Ext.grid.RowNumberer(),
{header : '标题',dataIndex : 'title',width : 180},
{header : '内容',dataIndex : 'content',width : 180},
{header : '添加人',dataIndex : 'last_operator',width : 180},
{header : '创建时间',dataIndex : 'createtime',type:'date',width : 160},
]),
store : noticeStore,
sm :_sm,
//固定表格的宽度 注释掉,显示宽度滚动条
viewConfig:{
forceFit:true
},
//分页
bbar: new Ext.PagingToolbar({
plugins: new Ext.ux.plugin.PagingToolbarResizer,
pageSize: pagesize,
displayInfo : true,
displayMsg : '当前记录数: {0} - {1} 总记录数: {2}',
emptyMsg : '没有符合条件的记录',
store : noticeStore
}),
tbar : []
});
//列表表格
var main_tab_panel = new Ext.TabPanel({
xtype : "tabpanel",
region : "center",
id : 'sale_firm_tab',
items:
[
grid_list
]
});
main_tab_panel.setActiveTab(grid_list);//设置特定的tab为活动面板
/**
* 删除 操作方法
* url AJAX请求PHP的方法 noticeDelete=>删除
* <NAME>
* 2013/11/11
*/
function customerExecute(url)
{
var type = '';
var str = '';
if(url == 'noticeDelete')
{
type = '删除';
str = '删除之后该公告将不在显示,确定要删除?';
}
var sm = grid_list.getSelectionModel();
var data = sm.getSelections();
var ids = '';
//复选改成单选
// for(var i=0; i<data.length; i++){
// ids += data[i].get("id") + '|';
// }
ids = data[0].get("id");
Ext.MessageBox.confirm(''+type+'', str, function showResult(btn){
if (btn == 'yes')
{
Ext.Ajax.request({
url:'../inside.php?t=json&m='+ controlName +'&f='+url,
method:'post',
params:{ids:ids},
success: function sFn(response,options)
{
noticeStore.load();//刷新页面
Ext.Msg.alert('系统提示', Ext.decode(response.responseText).msg);
}
});
}
});
}
<file_sep><?php
/**
* 公共控制类
*
*/
set_time_limit(0);
class common extends baseControl {
private $cookiepre;
private $appkey; //接口专用
private $_uid=0; //接口专用
private $api_users; //接口专用
public function __construct()
{
global $config;
parent::__construct();
$params = helper::filterParams();
if(isset($params['app_key'])&&$params['app_key']){ //如果请求接口,走接口路线
$this->runApi($params);
}else{
$this->cookiepre = $config->cookiepre;
session_start();
$this->setUserinfo();
$this->checkLogin();
}
}
public function file_upload($file) {
set_time_limit(0);
if(empty($file) || empty($file['name'])) {
//未选择文件
return -9;
}
if($file['name']) {
$ext = strtolower(trim(substr(strrchr($file['name'], '.'), 1)));
if($ext != "csv") {
//文件类型不正确
return -8;
}
}
$dir = '../tmp/data';
//$dir = $this->app->getCacheRoot().'./data';
if(!is_dir($dir)) {
helper::createDir($dir,0777);
}
//文件上传
$tmp_name = $file['tmp_name'];
$newname = $dir.'/import_'.date('m-d-H-i-s').'.'.$ext;
if(@copy($tmp_name, $newname)) {
@unlink($tmp_name);
} elseif(@move_uploaded_file($tmp_name, $newname)) {
} elseif(@rename($tmp_name, $newname)) {
} else {
//上传文件失败
return -7;
}
@chmod($newname,0777);
return $newname;
}
/**
* 获取当前模块
*
* @return array
*/
private function getMF()
{
$url = array();
$string = $_SERVER["QUERY_STRING"];
parse_str($string,$url);
// $str = file_get_contents('url.txt');
// file_put_contents('url.txt', $str."\n\t".implode('-',$url));
return $url;
}
private function checkLogin()
{
$url = $this->getMF();
$m = $url['m'];
$f = $url['f'];
$_usercookie = $_COOKIE[$this->cookiepre];
$cookiestr = $this->app->myAdmin->uid.'|-';//.helper::md5Cookie(strtolower($this->app->myAdmin->username), $this->app->myAdmin->passwd);
//echo $_usercookie.'|'.$cookiestr;exit;Story #13977
if($m == 'income_bill' || $f == 'addIncomeBill'){
return ;}
if($m == 'service_monitor_new' || $f == 'addCustomerOffline'){//Story #18940 离线监控第2版
return ;}
if($m == 'site_workorder' || $f == 'selectBackTimedTask'){//Story #18940 离线监控第2版
return ;}
if($m == 'site_workorder' || $f == 'sendMsgTimedTask'){//Story #18940 离线监控第2版
return ;}
if($m == 'back_repair' || $f == 'syncRepairFromK3'){//Story #30193 维修出入库同步
return ;}
if($m == 'k3'|| $f == 'syncInOut'){
return ;}
if ($m == 'sim_list' || $f == 'syncBalance' || $f == 'syncBalanceWhere') {//Story #16164
return ;}
if($m == 'login' || $f == 'getconfig'|| $f == 'getsconfig'){
return ;}
if($m == 'screen_show'){//Story #14960 客服受理统计大屏展示 by lixiaoli
return ;}
if($m == 'role'){
return ;}
if($m == 'income_apportion' && $f == 'addGpsCycle'){ //Story #32322 by lixiaoli
return ;}
if($m == 'job_nianshen' && $f == 'sendTruckListMail'){//Story #25392
return ;}
elseif(!$this->cookieUid() ||!$this->app->myAdmin->status ) {
/*if ($_usercookie){
print_r('$_usercookie');
print_r($_usercookie);
}
if ($cookiestr){
print_r('$cookiestr');
print_r($cookiestr);
}
if ($this->app->myAdmin->status){
print_r('$this->app->myAdmin->status');
print_r($this->app->myAdmin->status);
}
*/
$this->loadModel('login')->logout();
helper::throwException('无权访问',403);
}
}
/**
* 获取某个项目的配置(cuiwei)
* 左侧菜单
* @return array
*/
public function getsconfig()
{
$params = helper::filterParams();
$data = $this->common->getsysconfig($params['id'],$params['sys']);
$this->assign('result',$data);
$this->display();
}
/**
* 设置用户基本信息,权限信息,角色信息
* @author liuzhi
* @since 2013/11/7
*/
private function setUserinfo()
{
$userId = $this->cookieUid();
$userInfo = $this->loadModel('login')->setUserinfo($userId);
//eval(helper::array2Object($userInfo, 'infoobj'));
$this->app->myAdmin = $userInfo;
}
/**
* 通过登录成功设置的COOKIE,获取登录的用户ID
* @author liuzhi
* @since 2013/11/7
*/
private function cookieUid()
{
$uid = 0;
$uid = $_COOKIE[$this->cookiepre];
return $uid;
}
/**
* 返回用户所拥有的资源
* //BOSSSAL-73
* @author liuzhi
* @since 2013/12/19
*/
public function editSource(){
$params = helper::filterParams();
$source = $this->app->myAdmin->source;
$return = array();
if ($params['name']) {
foreach ($source as $sv) {
if ($sv->status == '1') {//父资源可用
$_url = explode('/', $sv->url);
if ($params['name'] == $_url[1]) {
$return[] = $sv;
}
}
}
} else {
$return = $source;
}
echo json_encode($return);
}
/**
* 调用API
* @author yangshipeng
* @param type $params
*/
public function runApi($params){
$this->api_users=array(
'ips' => 'DE56BE8FA19339D679EFA6232455F342',
'K3'=>'<KEY>', //测试
// 'K3'=>'497134959D2F1840B7DFECA91F9FF6BD' //正式
'crm' => '<KEY>',
);
$this->appkey = $params['app_key'];
if ($this->appkey) {
//必须存在合法的API用户,否者报错
if( !array_key_exists($this->appkey, $this->api_users)) {
helper::throwException('appkey在系统中不存在或未分配权限,appkey:'.$this->appkey, 403);
} else {
$this->checkSign();
unset($_GET["app_key"]);
unset($_POST["app_key"]);
unset($_GET["timestamp"]);
unset($_POST["timestamp"]);
unset($_GET["sign"]);
unset($_POST["sign"]);
}
}
}
/**
* API调用时验证签名
*/
private function checkSign() {
$params = helper::filterParams("*");
// 时间戳验证,20分钟有效
$timestamp = strtotime($params['timestamp']);
// echo date('Y-m-d H:i:s');
if (time() - $timestamp > 1200) {
//记录接口错误日志 2013-06-26 by lizw
// $this->saveapierror('31',"非法的时间戳参数,传的时间:".$params['timestamp'].',appkey:'.$this->appkey);
helper::throwException("非法的时间戳参数,传的时间:".$params['timestamp'].',appkey:'.$this->appkey, 31);
}
// 签名认证
// $user = $this->app->user;
// $passwd = <PASSWORD>;
$sign = $params['sign'];
unset($params["sign"]);//var_dump($params);
$calsign = self::createSign($params, $this->api_users[$this->appkey]);
// helper::datalog('接口收到的签名:'.$sign.'----------签名结束','ecsa_api_sign_');
helper::datalog ('接口收到的签名:'.$sign.'----------签名结束','ecsa_api_sign_');
if ($sign != $calsign) {
$str = "非法签名:".$sign . var_export($params,true);
//记录接口错误日志 2013-06-26 by lizw
unset($params['data']);
// $this->saveapierror('25',"非法签名:".$sign . var_export($params,true) . $calsign);
helper::throwException($str, 25);
}
}
/**
* 生成签名
* @param $paramArr:api参数数组
* @return $sign
*/
static private function createSign($paramArr, $secret) {
$sign = $secret;
ksort($paramArr);
foreach ($paramArr as $key => $val) {
if ($key !='' && !is_null($val)) {
$sign .= $key.$val;
}
}
$sign .= $secret;
// var_dump('服务器端生成签名的字符串:'.$sign.'----------字符串结束','zpt_api_sign_');
$sign = strtoupper(md5($sign));
// var_dump('服务器端生成的签名:'.$sign.'----------签名结束','zpt_api_sign_');
return $sign;
}
}<file_sep><?php
/**
* The helper class file of ZenTaoPHP.
*
* ZenTaoPHP is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* ZenTaoPHP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ZenTaoPHP. If not, see <http://www.gnu.org/licenses/>.
*
* @copyright Copyright 2009-2010 青岛易软天创网络科技有限公司(www.cnezsoft.com)
* @author <NAME> <<EMAIL>>
* @package ZenTaoPHP
* @version $Id: helper.class.php 127 2010-07-04 02:18:40Z wwccss $
* @link http://www.zentaoms.com
*/
/**
* 工具类对象,存放着各种杂项的工具方法。
*
* @package ZenTaoPHP
*/
class helper
{
/**
* 为一个对象设置某一个属性,其中key可以是“father.child”的形式。
*
* <code>
* <?php
* $lang->db->user = 'wwccss';
* helper::setMember('lang', 'db.user', 'chunsheng.wang');
* ?>
* </code>
* @param string $objName 对象变量名。
* @param string $key 要设置的属性,可以是father.child的形式。
* @param mixed $value 要设置的值。
* @static
* @access public
* @return void
*/
static public function setMember($objName, $key, $value)
{
global $$objName;
if(!is_object($$objName) or empty($key)) return false;
$key = str_replace('.', '->', $key);
$value = serialize($value);
$code = ("\$${objName}->{$key}=unserialize(<<<EOT\n$value\nEOT\n);");
eval($code);
}
/**
* 生成某一个模块某个方法的链接。
*
* 在control类中对此方法进行了封装,可以在control对象中直接调用createLink方法。
* <code>
* <?php
* helper::createLink('hello', 'index', 'var1=value1&var2=value2');
* helper::createLink('hello', 'index', array('var1' => 'value1', 'var2' => 'value2');
* ?>
* </code>
* @param string $moduleName 模块名。
* @param string $methodName 方法名。
* @param mixed $vars 要传递给method方法的各个参数,可以是数组,也可以是var1=value2&var2=value2的形式。
* @param string $viewType 扩展名方式。
* @static
* @access public
* @return string
*/
static public function createLink($moduleName, $methodName = 'index', $vars = '', $viewType = '')
{
global $app, $config;
$link = $config->webRoot;
if($config->requestType == 'GET')
{
if(strpos($_SERVER['SCRIPT_NAME'], 'index.php') === false)
{
$link = $_SERVER['SCRIPT_NAME'];
}
}
if(empty($viewType)) $viewType = $app->getViewType();
/* 如果传递进来的vars不是数组,尝试将其解析成数组格式。*/
if(!is_array($vars)) parse_str($vars, $vars);
if($config->requestType == 'PATH_INFO')
{
$link .= "$moduleName{$config->requestFix}$methodName";
if($config->pathType == 'full')
{
foreach($vars as $key => $value) $link .= "{$config->requestFix}$key{$config->requestFix}$value";
}
else
{
foreach($vars as $value) $link .= "{$config->requestFix}$value";
}
/* 如果访问的是/index/index.html,简化为/index.html。*/
if($moduleName == $config->default->module and $methodName == $config->default->method) $link = $config->webRoot . 'index';
$link .= '.' . $viewType;
}
elseif($config->requestType == 'GET')
{
$link .= "?{$config->moduleVar}=$moduleName&{$config->methodVar}=$methodName";
if($viewType != 'html') $link .= "&{$config->viewVar}=" . $viewType;
foreach($vars as $key => $value) $link .= "&$key=$value";
}
return $link;
}
//判断roleid = 22 (总办服务人员 可查看该角色 所在城市/区所有信息) - 仅佳吉网上营业厅model,control交叉调用
static public function CNEX_getBycityid($roleid = 22,$prefix="")
{
global $app;
$sroleid = $app->user->roleid;
$marea_tmp = $app->user->marea;
if(!empty($marea_tmp)){
$marea_arr = helper::array_remove_empty(explode(",", $marea_tmp));
if(count($marea_arr) > 0){
$marea = implode(",",$marea_arr);
if($sroleid == $roleid){
return " and ".$prefix."shippercityid in(".$marea.")";
}else{
return "";
}
}
}
}
//判断roleid = 23 (总办服务人员 可查看该角色 所在城市/区所有信息) - 仅佳吉网上营业厅model,control交叉调用
static public function CNEX_getBystore($roleid = 23,$prefix="")
{
global $app;
$sroleid = $app->user->roleid;
$marea_tmp = $app->user->msite;
if(!empty($marea_tmp)){
$msite_arr = helper::array_remove_empty(explode(",", $marea_tmp));
if(count($msite_arr) > 0){
$msite = implode(",",$msite_arr);
if($sroleid == $roleid){
return " and ".$prefix."shipperstoreid in(".$msite.")";
}else{
return "";
}
}
}
}
/**
* 将一个数组转成对象格式。此函数只是返回语句,需要eval。
*
* <code>
* <?php
* $config['user'] = 'wwccss';
* eval(helper::array2Object($config, 'configobj');
* print_r($configobj);
* ?>
* </code>
* @param array $array 要转换的数组。
* @param string $objName 要转换成的对象的名字。
* @param string $memberPath 成员变量路径,最开始为空,从根开始。
* @param bool $firstRun 是否是第一次运行。
* @static
* @access public
* @return void
*/
static public function array2Object($array, $objName, $memberPath = '', $firstRun = true)
{
if($firstRun)
{
if(!is_array($array) or empty($array)) return false;
}
static $code = '';
$keys = array_keys($array);
foreach($keys as $keyNO => $key)
{
$value = $array[$key];
if(is_int($key)) $key = 'item' . $key;
$memberID = $memberPath . '->' . $key;
if(!is_array($value))
{
$value = addslashes($value);
$code .= "\$$objName$memberID='$value';\n";
}
else
{
helper::array2object($value, $objName, $memberID, $firstRun = false);
}
}
return $code;
}
/**
* 包含一个文件。router.class.php和control.class.php中包含文件都通过此函数来调用,这样保证文件不会重复加载。
*
* @param string $file 要包含的文件的路径。
* @static
* @access public
* @return void
*/
static public function import($file)
{
if(!file_exists($file)) return false;
static $includedFiles = array();
if(!isset($includedFiles[$file]))
{
include $file;
$includedFiles[$file] = true;
return true;
}
return false;
}
/**
* 设置model文件。
*
* @param string $moduleName 模块名字。
* @access private
* @return void
*/
static public function setModelFile($moduleName)
{
global $app;
/* 设定主model文件和扩展路径,并获得所有的扩展文件。*/
$mainModelFile = $app->getModulePath($moduleName) . 'model.php';
$modelExtPath = $app->getModuleExtPath($moduleName, 'model');
$extFiles = helper::ls($modelExtPath, '.php');
/* 不存在扩展文件,返回主配置文件。*/
if(empty($extFiles)) return $mainModelFile;
/* 存在扩展文件,判断是否需要更新。*/
$mergedModelFile = $app->getTmpRoot() . 'model' . $app->getPathFix() . $moduleName . '.php';
$needUpdate = false;
$lastTime = file_exists($mergedModelFile) ? filemtime($mergedModelFile) : 0;
if(filemtime($mainModelFile) > $lastTime)
{
$needUpdate = true;
}
else
{
foreach($extFiles as $extFile)
{
if(filemtime($extFile) > $lastTime)
{
$needUpdate = true;
break;
}
}
}
/* 如果不需要更新,则直接返回合并之后的model文件。*/
if(!$needUpdate) return $mergedModelFile;
if($needUpdate)
{
/* 加载主的model文件,并获得其方法列表。*/
helper::import($mainModelFile);
$modelMethods = get_class_methods($moduleName . 'model');
foreach($modelMethods as $key => $modelMethod) $modelMethods[$key] = strtolower($modelMethod);
/* 将主model文件读入数组。*/
$modelLines = rtrim(file_get_contents($mainModelFile));
$modelLines = rtrim($modelLines, '?>');
$modelLines = rtrim($modelLines);
$modelLines = explode("\n", $modelLines);
$lines2Delete = array(count($modelLines) - 1);
$lines2Append = array();
/* 循环处理每个扩展方法文件。*/
foreach($extFiles as $extFile)
{
$methodName = strtolower(basename($extFile, '.php'));
if(in_array($methodName, $modelMethods))
{
$method = new ReflectionMethod($moduleName . 'model', $methodName);
$startLine = $method->getStartLine() - 1;
$endLine = $method->getEndLine() - 1;
$lines2Delete = array_merge($lines2Delete, range($startLine, $endLine));
}
$lines2Append = array_merge($lines2Append, explode("\n", trim(file_get_contents($extFile))));
}
/* 生成新的model文件。*/
$lines2Append[] = '}';
foreach($lines2Delete as $lineNO) unset($modelLines[$lineNO]);
$modelLines = array_merge($modelLines, $lines2Append);
if(!is_dir(dirname($mergedModelFile))) mkdir(dirname($mergedModelFile));
$modelLines = join("\n", $modelLines);
$modelLines = str_ireplace($moduleName . 'model', 'ext' . $moduleName . 'model', $modelLines); // 类名修改。
file_put_contents($mergedModelFile, $modelLines);
return $mergedModelFile;
}
}
/**
* 生成SQL查询中的IN(a,b,c)部分代码。
*
* @param misc $ids id列表,可以是数组,也可以是使用逗号隔开的字符串。
* @static
* @access public
* @return string
*/
static public function dbIN($ids)
{
if(is_array($ids)) return "IN ('" . join("','", $ids) . "')";
return "IN ('" . str_replace(',', "','", str_replace(' ', '',$ids)) . "')";
}
/**
* 生成对框架安全的base64encode串。
*
* @param string $string 要编码的字符串列表。
* @static
* @access public
* @return string
*/
static public function safe64Encode($string)
{
return strtr(base64_encode($string), '/', '.');
}
/**
* 解码。
*
* @param string $string 要解码的字符串列表。
* @static
* @access public
* @return string
*/
static public function safe64Decode($string)
{
return base64_decode(strtr($string, '.', '/'));
}
/**
* 计算两个日期的差。
*
* @param date $date1 第一个时间
* @param date $date2 第二个时间
* @access public
* @return string
*/
static public function diffDate($date1, $date2)
{
return round((strtotime($date1) - strtotime($date2)) / 86400, 0);
}
/* 获得当前的时间。*/
static public function now()
{
return date(DT_DATETIME1);
}
/* 获得今天的日期。*/
static public function today()
{
return date(DT_DATE1);
}
/* 判断是否0000-00-00格式的日期。*/
static public function isZeroDate($date)
{
return substr($date, 0, 4) == '0000';
}
/* 获得某一个目录下面含有某个特征字符串的所有文件。*/
static public function ls($dir, $pattern = '')
{
$files = array();
$dir = realpath($dir);
if(is_dir($dir))
{
$dh = opendir($dir);
if($dh) {
while(($file = readdir($dh)) !== false)
{
if(strpos($file, $pattern) !== false) $files[] = $dir . DIRECTORY_SEPARATOR . $file;
}
closedir ( $dh );
}
}
return $files;
}
/* 切换目录。*/
static function cd($path = '') {
static $cwd = '';
if ($path) {
$cwd = getcwd ();
chdir ( $path );
} else {
chdir ( $cwd );
}
}
/**
* 根据FlexGrid提交的数据生成Page对象
*/
static public function createPage() {
$param = $_REQUEST;
$page = new Page ();
if (array_key_exists ( 'page_no', $param )) {
$page->pageNo = $param ['page_no'];
$page->pageSize = $param ['page_size'];
}
if (array_key_exists ( 'sortname', $param ) && $param ['sortname'] != 'undefined') {
$orderBy = $param ['sortname'];
if ($param ['sortorder'] != 'undefined')
$orderBy .= ' ' . $param ['sortorder'];
$page->orderBy = $orderBy;
}
return $page;
}
/**
* 根据提交的参数和model生成记录数据
*/
static public function D($model) {
$q = $_REQUEST;
$result = array ();
$fields = $model->fields;
foreach ( $_REQUEST as $key => $value ) {
if (array_key_exists ( $key, $fields )) {
$f = $fields [$key];
// 类型转换
if (in_array ( $f ['native_type'], array ('INT24', 'LONG' ) ))
$result[$key] = (int) $value;
else
$result[$key] = $value;
}
}
return $result;
}
/**
* 快速文件数据读取和保存 针对简单类型数据 字符串、数组
*/
static public function F($name, $value='', $path=null) {
global $app;
// 取默认路径,缓存根目录/data
if (empty($path))
$path = $app->getCacheRoot();
static $_cache = array();
$filename = $path.$name.'.php';
if('' !== $value) {
if(is_null($value)) {
// 删除缓存
return unlink($filename);
}else{
// 缓存数据
$dir = dirname($filename);
// 目录不存在则创建
if(!is_dir($dir)) mkdir($dir);
return file_put_contents($filename,"<?php\nreturn ".var_export($value,true).";\n?>");
}
}
if(isset($_cache[$name])) return $_cache[$name];
// 获取缓存数据
if(is_file($filename)) {
$value = include $filename;
$_cache[$name] = $value;
}else{
$value = false;
}
return $value;
}
/**
* 创建查询条件
* 字段:fields=>id,title,nick,pic_url
* 排序 order_by =>column/asc|desc(单个排序)
* 前缀 $configtable =>array("name" =>"d") (单个排序)
* 查询条件
*/
static public function createQuery($pararms, $operator = null,$configtable=null) {
$actionQuery = new ActionQuery ();
$actionQuery->fields = $pararms ['fields'];
$order_by = $pararms ['order_by'];
if ($order_by) {
$orderby = explode ( "/", $order_by );
$orderfield = $orderby [0];
if($configtable[$orderfield]){
$orderfield = $configtable[$orderfield].".".$orderfield;
}
$actionQuery->addOrderbys ( $orderfield, $orderby [1] );
}
unset ( $pararms ['fields'] );
unset ( $pararms ['order_by'] );
foreach ( $pararms as $key => $value ) {
if($configtable[$key]){
$field = $configtable[$key].".".$key;
}else {
$field=$key ;
}
if ($operator [$key]) {
if(preg_match("/>|<|<>/",$value)){
$actionQuery->addCondition ( $field, $value );
}
else{
if($operator[$key]=="like" && strpos($value,'%')===false){
$value = "%".$value."%" ;
}elseif($operator[$key]=="like" && strpos($value,'%')!==false)
$value = $value ;
$actionQuery->addCondition ( $field, $value, $operator [$key] );
}
} else {
$actionQuery->addCondition ( $field, $value );
}
}
return $actionQuery;
}
/**
* 将page转化为FlexGrid需要的数据
* @param <type> $pk 主键属性名
*/
static public function page2FlexGrid($page, $pk = "id") {
$list = array();
foreach ($page->result as $value)
$list[] = array("id" => $value->$pk, "cell" => $value);
$data = array("page" => $page->pageNo, "total" => $page->totalCount, "rows" => $list);
return $data;
}
/**
* 过滤参数(需要更好的方式)
* $p=*, 表示过滤所有为空的$pararms,
*/
static public function filterParams( $p=null ) {
//$pararms = $_REQUEST;
$pararms = array_merge($_POST, $_GET);
unset($pararms['m']);
unset($pararms['f']);
unset($pararms['t']);
unset($pararms['page_no']);;
unset($pararms['page_size']);
unset($pararms['sortname']);
unset($pararms['sortorder']);
unset($pararms['query']);
unset($pararms['qtype']);
unset($pararms['qop']);
unset($pararms['XDEBUG_SESSION_START']);
unset($pararms['KEY']);
foreach ($pararms as $key=>&$value){
if($p){
if(!is_array($value)) $value = trim($value);
if($value===null||$value===""||$value=="undefined"){
unset($pararms[$key]);
}
elseif(strpos($key,"confilter_")>-1){
$array_key = explode("_",$key) ;
$newkey = $array_key[1].' '.$array_key[2].' '.$array_key[3] ;
$pararms[$newkey] = $value;
unset($pararms[$key]);
}
}
}
return $pararms;
}
/**
* 时间格式化输出
*
* @param string $format
* @param string $time
* @return string
* @author liyonghua
*/
static public function nowTime($format ='Y-m-d H:i:s',$time='')
{
if($time)
$datetime = $time;
else
$datetime = time();
return date($format,$datetime);
}
/**
* 抛出异常
* @param string $msg 错误描述
* @param int $code 错误编码
*/
static public function throwException($msg, $code=1) {
if($code!=403)
helper::datalog('helper|'.$code.'|'.$msg,'syslog_');
throw new Exception($msg, $code);
}
static public function formattime($time,$chinese=false){
$units = array("天", ":", "'", "''");
if ($chinese) $units = array("天", "时", "分", "秒");
$str ='';
if ($time > 0) {
$day = round($time/86400+0.5)-1;
$hour = round(($time - $day*86400)/3600+0.5)-1;
$min = round(($time - $day*86400-$hour*3600)/60+0.5)-1;
$sec = round($time - $day*86400-$hour*3600-$min*60);
} else {
$day = $hour = $min = $sec = 0;
}
if($day>0) {
$str=$day.$units[0];
}
if($hour>0) {
$str.=$hour.$units[1];
}
if($min>0) {
$str.=$min.$units[2];
if($day>0) {
return $str;
}
}
else
{
$str.="0".$units[2];
}
if($sec>0) {
$str.=$sec.$units[3];
}
else
{
$str.="0".$units[3];
}
return $str;
}
static public function condToString($conditions){
$sql = ' ';
if (is_string($conditions)){
return $sql . $conditions;
}
elseif(is_array($conditions)){
$join_char = ''; // 第一个条件前面 没有 and 连接符
foreach ( $conditions as $field => $cond ) {
// 支持 like / or 等操作 例如: 'name' => array('%Bob%','like')
$op_char = '=';
if (is_array ( $cond )) {
$value = array_shift ( $cond );
// if $value is array , will use "in" [] opchar
if (is_array ( $value ))
$value = '[' . implode ( ',', $value ) . ']';
$_op_char = array_shift ( $cond );
if (! empty ( $_op_char ) && is_string ( $_op_char ))
$op_char = $_op_char;
if(strpos($op_char,"not")>-1){
$value = "not in ('" . str_replace(',', "','", str_replace(' ', '',$value)) . "')" ;
}elseif(strpos($op_char,"in")>-1){
$value = "in ('" . str_replace(',', "','", str_replace(' ', '',$value)) . "')" ;
}else{
$value= $op_char." '".$value."'";
}
}elseif(strpos($cond,"null")>-1){
if(strpos($cond,"is")<0){
$value = " is ".$cond ;
}else{
$value = $cond ;
}
}elseif(strpos($cond,",")>-1){
$value = " in (".$cond.")" ;
}elseif (preg_match("/>|<|<>/",$cond)) {
$value = $cond;
}
else {
$value = ' = '.$cond;
}
$sql .= "{$join_char} {$field} {$value} ";
$join_char = ' and ';
}
return $sql;
}
}
/**
* 逐级建目录
*
* @param string $path
* @param int $mode
* @return string
*/
static public function createDir($path,$mode=0777) {
if(!is_dir($path)){
self::createDir(dirname($path));
mkdir($path,$mode);
@chmod($path,$mode);
}
return $path;
}
/**
* 编码转换
*
* @param unknown_type $str
* @param unknown_type $char
* @return unknown
*/
static public function charseticonv($str,$char='gbk') {
if(is_array($str)) {
foreach ($str as $k=>$v) {
$str[$k] = self::charseticonv($v,$char);
}
} else {
if($char=='gbk') {
$str = iconv('utf-8','gbk',trim($str));
} else {
$str = iconv('gbk','utf-8',trim($str));
}
}
return $str;
}
/**
* 数组去空
*
* @param array $array
* @return array
*/
static function array_remove_empty($array) {
if(!empty($array)) {
foreach ($array as $key=>$value) {
if($value=='') unset($array[$key]);
}
}
return $array;
}
/**
* 日志记录
* 2010-12-19
* @author liyonghua
*
* @param unknown_type $content
* @param unknown_type $type
*/
static public function datalog($content,$type='log_',$format = 'N',$params = false)
{
global $app,$timeStart;
//文件名称 1--7
$basePath = $app->getCacheRoot().'log'.DIRECTORY_SEPARATOR.date('Y-m-d').DIRECTORY_SEPARATOR;
if(!is_dir($basePath))
{
@mkdir($basePath,0777);
@chmod($basePath,0777);
}
$logfile = $basePath.$type.date($format,time()).'.php';
if(is_file($logfile))
{
//文件最后修改时间
// $lastModify = @filemtime($logfile);
// $diff = time() - $lastModify;
// //非今天文件 删除
// if($diff>86400){
// $filepath = glob($logfile.'*');
// foreach ($filepath as $unfile) {
// @unlink($unfile);
// }
// } else
if(@filesize($logfile) >= 2048000) {
//2M 分文件
$logfilebak = $logfile.'_'.date('His').'_bak.php';
@rename($logfile, $logfilebak);
}
}
$logstr.=' IP:'.self::getIP();
$logstr.= ' '.$content;
$mtime = explode(' ', microtime());
$totaltime = @number_format(($mtime[1] + $mtime[0] - $timeStart), 4);
$url = '';
if ($params)
$url= '浏览器:'.$_SERVER["HTTP_USER_AGENT"].',参数:'.var_export(self::filterParams(),true);
$url.=' '.$_SERVER['SCRIPT_NAME'].'?'.$_SERVER['QUERY_STRING'];
$newlog = date('Y-m-d H:i:s',time()).' '.$totaltime.' '.$logstr.' '.$url;
if($fp = @fopen($logfile, 'a')) {
@flock($fp, 2);
fwrite($fp, "<?PHP exit;?>\t".str_replace(array('<?', '?>', "\r", "\n",), '', $newlog)."\t\n");
fclose($fp);
}
unset($content,$logstr,$newlog);
}
/* 获取IP*/
static public function getIP()
{
if (getenv("HTTP_CLIENT_IP"))
$ip = getenv("HTTP_CLIENT_IP");
else if(getenv("HTTP_X_FORWARDED_FOR"))
$ip = getenv("HTTP_X_FORWARDED_FOR");
else if(getenv("REMOTE_ADDR"))
$ip = getenv("REMOTE_ADDR");
else
$ip = "UNKNOWN";
return $ip;
}
/* 向一个URL地址post数据 */
static public function init_post($post_url,$data,$header = '')
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 'application/x-www-form-urlencoded');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
if($header)
curl_setopt ( $ch, CURLOPT_HTTPHEADER,$header);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
/**
* 标点类型
*
* @return array
*/
static public function markerType()
{
$typearr = array(
'0'=>'个人',
'100'=>'自己位置',
'300'=>'办事处',
'400'=>'办事处区域'
);
return $typearr;
}
/**
* 根据经纬度计算距离
* $lng1经度1,$lat1纬度1,$lng2经度2,$lat2纬度2
*
* @return float 单位:KM
*/
static public function getdistance($lat1,$lng1,$lat2,$lng2)
{
$radLat1=deg2rad($lat1);//角度转为狐度
$radLat2=deg2rad($lat2);
$radLng1=deg2rad($lng1);
$radLng2=deg2rad($lng2);
$a=$radLat1-$radLat2;//两纬度之差,纬度<90
$b=$radLng1-$radLng2;//两经度之差,经度<180
$s=2*asin(sqrt(pow(sin($a/2),2)+cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)))*6378.137;
$s=Round($s * 10000) / 10000;
return $s;
}
/**
*
* 用户信息COOKIE加密码串
* @param string $username
* @param string $passwd
*/
static public function md5Cookie($username,$passwd,$auth='ips2HyrCom')
{
return md5($passwd.substr(md5(strtolower($username)), 19).$auth);
}
/**
*
* 加密、解密码算法
* @param string $string
* @param string $operation DECODE表示解密,ENCODE表示加密
* @param string $key 密匙
* @param int $expiry 密文有效期
*/
static public function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0)
{
$ckey_length = 4; // 随机密钥长度 取值 0-32;
// 加入随机密钥,可以令密文无任何规律,即便是原文和密钥完全相同,加密结果也会每次不同,增大破解难度。
// 取值越大,密文变动规律越大,密文变化 = 16 的 $ckey_length 次方
// 当此值为 0 时,则不产生随机密钥
$key = md5($key ? $key : '020');
$keya = md5(substr($key, 0, 16));
$keyb = md5(substr($key, 16, 16));
$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
$cryptkey = $keya.md5($keya.$keyc);
$key_length = strlen($cryptkey);
$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
$string_length = strlen($string);
$result = '';
$box = range(0, 255);
$rndkey = array();
for($i = 0; $i <= 255; $i++) {
$rndkey[$i] = ord($cryptkey[$i % $key_length]);
}
for($j = $i = 0; $i < 256; $i++) {
$j = ($j + $box[$i] + $rndkey[$i]) % 256;
$tmp = $box[$i];
$box[$i] = $box[$j];
$box[$j] = $tmp;
}
for($a = $j = $i = 0; $i < $string_length; $i++) {
$a = ($a + 1) % 256;
$j = ($j + $box[$a]) % 256;
$tmp = $box[$a];
$box[$a] = $box[$j];
$box[$j] = $tmp;
$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
}
if($operation == 'DECODE') {
if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
return substr($result, 26);
} else {
return '';
}
} else {
return $keyc.str_replace('=', '', base64_encode($result));
}
}
static public function createPcode($id) {
if(!$id) {
return;
}
$datestr = substr(date('Ymd',time()),-5);
$id = str_pad(substr($id,-5), 5, '0', STR_PAD_LEFT);
return $datestr.$id;
}
/**
*
* 全角转化为半角
* @param string $strnum
*/
static public function charAlabNum($strnum)
{
$arr1 = array('a','b','c','d','e','f','g','h','i','j','k',
'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O',
'P','Q','R','S','T','U','V','W','X','Y','Z','1','2','3','4',
'5','6','7','8','9','0',',','.',';',':','~','!','(',')','{','}',
'[',']','<','>','?','$','#','%','@','&','*');
$arr2 = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p',
'q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J',
'K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','1','2','3','4',
'5','6','7','8','9','0',',','.',';',':','~','!','(',')','{','}','[',']','<','>',
'?','$','#','%','@','&','*');
return str_replace($arr1,$arr2,$strnum);
}
/**
* 导出cvs
* $title array("name"=>"名字")
*/
static public function export_csv($filename,$title,$data,$proto=array(),$path=null,$page=1,$pagesize = 0) {
if(!$data) {
header("Content-Type: text/html; charset=utf-8");
exit('导出数据为空');
}
$filename1 = $filename;
if(empty($filename)){
$filename = 'export'.date('m-d_H-i-s',time()).'.csv'; //导出文件名称
$filename1 = $filename;
}else{
$filename = helper::charseticonv($filename);
if(!strpos($filename,".csv")){
$filename = $filename.'.csv';
}
}
//输出流
header("Content-Type:application:text/csv;charset=UTF-8");
header('Content-Disposition:attachment;filename="'.$filename.'"');
header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
header('Expires:0');
header('Pragma:public');
if($path) {//有传入文件路径时导出为文件
$out = fopen($path.$filename1.".csv","a+");
}
else {
$out = fopen('php://output', 'w');
}
//导出标题, 编码转换, 加一列序号
foreach($title as $value){
$dtitle[] = $value['name'];
}
//导出标题, 编码转换, 加一列序号
array_unshift($dtitle,'序号');
$dtitle = helper::charseticonv($dtitle);
if($page == 1) fputcsv($out, $dtitle);//页数大于第一页时不写表头
//导出内容
if($page > 1 && $pagesize > 0) $i = ($page - 1) * $pagesize + 1;//页数大于第一页时处理序号
else $i = 1;
foreach($data as $value) {
$tmpval = array();
$tmpval[] = $i;
//列
$j = 1;
foreach($title as $key=>$sv) {
$val = '';
if(is_object($value)){
$val = $value->$key;
}
if(is_array($value)){
$val = $value[$key];
}
if(in_array($j,$proto)) $val = '="'.$val.'"';
$tmpval[] = $val;
$j++;
}
//编码转换
$tmpval = helper::charseticonv($tmpval);
fputcsv($out, $tmpval);
$i++;
}
unset($data);
if($path) return;//导出为文件的时候返回
else exit();
}
/**
* 追加导入cvs
* $title array("name"=>"名字")
*/
public function add_export_csv($filename,$title,$data,$proto=array(),$path=null,$page=1,$pagesize = 0) {
static $autokey = 1;
$appRoot = '../www/download/share/datacache/public_export/';
self::createDir($appRoot);
if(!$data) {
header("Content-Type: text/html; charset=utf-8");
exit('导出数据为空');
}
$filename1 = $filename;
if(empty($filename)){
$filename = 'export'.date('m-d_H-i-s',time()).'.csv'; //导出文件名称
$filename1 = $filename;
}else{
$filename = helper::charseticonv($filename);
if(!strpos($filename,".csv")){
$filename = $filename.'.csv';
}
}
$xls_name = $appRoot.$path.$filename1.'.csv';
$out = fopen($xls_name,"a+");
//导出标题, 编码转换, 加一列序号
foreach($title as $value){
$dtitle[] = $value['name'];
}
//导出标题, 编码转换, 加一列序号
array_unshift($dtitle,'序号');
$dtitle = helper::charseticonv($dtitle);
if($page == 1) fputcsv($out, $dtitle);//页数大于第一页时不写表头
//导出内容
if($page > 1 && $pagesize > 0) $i = ($page - 1) * $pagesize + 1;//页数大于第一页时处理序号
else $i = 1;
foreach($data as $value) {
$tmpval = array();
$tmpval[] = $i;
//列
$j = 1;
foreach($title as $key=>$sv) {
$val = '';
if(is_object($value)){
$val = $value->$key;
}
if(is_array($value)){
$val = $value[$key];
}
if(in_array($j,$proto)) $val = '="'.$val.'"';
$tmpval[] = $val;
$j++;
}
//编码转换
$tmpval = helper::charseticonv($tmpval);
fputcsv($out, $tmpval);
$i++;
}
return $filename1;
}
/**
*
* 将一个二维数组按照一个指定元素大小排序
* @param array $array
* @param string $id
*/
static public function msort($array, $id="id") {
$temp_array = array();
while(count($array)>0) {
$lowest_id = 0;
$index=0;
foreach ($array as $item) {
if (isset($item[$id]) && $array[$lowest_id][$id]) {
if ($item[$id]<$array[$lowest_id][$id]) {
$lowest_id = $index;
}
}
$index++;
}
$temp_array[] = $array[$lowest_id];
$array = array_merge(array_slice($array, 0,$lowest_id), array_slice($array, $lowest_id+1));
}
return $temp_array;
}
/**
* 根据车辆状态获取车辆图标
*/
static public function getTruckIcon($status, $speed, $timestamp = 0,$course=-1) {
$status = (int)$status;
$speed = (int)$speed;
$image = 'mm_20_0';
$time = time();
$diffminutes = ($time - $timestamp) / 60;
if($diffminutes > 20) {
$image = 'mm_20_0'; //离线
} else {
if($speed <=5) {
$image = 'mm_20_5'; //静止
} else if($speed > 5 && $speed <= 80)
$image = 'mm_20_2';
else if($speed > 80 && $speed <=120)
$image = 'mm_20_3';
else if($speed > 120)
$image = 'mm_20_4';
}
if($course!=-1)
{
$iconarr = array('mm_20_0'=>'white','mm_20_5'=>'blue','mm_20_2'=>'green','mm_20_3'=>'yellow','mm_20_4'=>'red');
$image = 't_'.$iconarr[$image].'_';
if($course==0) $image.=0;
elseif($course > 0 && $course<= 30) $image.=0;
elseif($course > 30 && $course<= 60) $image.=30;
elseif($course > 60 && $course<= 90) $image.=60;
elseif($course > 90 && $course<= 120) $image.=90;
elseif($course > 120 && $course<= 150) $image.=120;
elseif($course > 150 && $course<= 180) $image.=150;
elseif($course > 180 && $course<= 210) $image.=180;
elseif($course > 210 && $course<= 240) $image.=210;
elseif($course > 240 && $course<= 270) $image.=240;
elseif($course > 270 && $course<= 300) $image.=270;
elseif($course > 300 && $course<= 330) $image.=300;
elseif($course > 330 && $course<= 360) $image.=330;
else $image.=0;
}
return $image;
}
/**
* 截取中文字符串
* Enter description here ...
* @param string $string
* @param int $sublen
* @param int $start
* @param string $code
*/
static public function cut_str($string, $sublen, $start = 0, $code = 'UTF-8') {
if($code == 'UTF-8') {
$pa ="/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
preg_match_all($pa, $string, $t_string); if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen));
return join('', array_slice($t_string[0], $start, $sublen));
} else {
$start = $start*2;
$sublen = $sublen*2;
$strlen = strlen($string);
$tmpstr = ''; for($i=0; $i<$strlen; $i++) {
if($i>=$start && $i<($start+$sublen)) {
if(ord(substr($string, $i, 1))>129) {
$tmpstr.= substr($string, $i, 2);
} else {
$tmpstr.= substr($string, $i, 1);
}
}
if(ord(substr($string, $i, 1))>129) $i++;
}
if(strlen($tmpstr)<$strlen ) $tmpstr.= "";
return $tmpstr;
}
}
/**
* IPS2 点|区域 类型对应关系
* @param int $typevalue
*/
static function pointType($typevalue)
{
switch ($typevalue){
case "510":
$type = '站点';
break;
case "511":
$type = '站点区域';
break;
case "520":
$type = '停泊点';
break;
case "310":
$type = '机构标点';
break;
case "0":
$type = '标注点';
break;
case "1":
$type = '区域';
break;
default:
$type = '其他';
}
return $type;
}
/**
*
* 得到百分比
* @param $up 分子
* @param $down 分母
* @param $round 保留小数位。默认2
* @param $flag 是否加百分号
*/
static public function getrate($up, $down, $round=2, $flag = TRUE){
$up = floatval($up)*100;
$down = floatval($down);
$str = '';
if($down!=0){
$str = round($up/$down, $round);
if($flag) $str.='%';
}else{
$str = '--';
}
return $str;
}
/**
* excel日期转换成可读日期
*/
static public function exceltime($time, $format = 'Y-m-d H:i:s') {
return date($format, round(($time - 25569) * 86400) - 28800);
}
/**
* excel列转换成数字索引
* A - 1
* B - 2
* ...
* Z - 26
* AA - 27
* ...
* AZ - 52
* ...
* ZZ - 702
* AAA - 703
*/
static public function excelcol2index($code) {
$i = 0;
$len = strlen($code);
for($j = 0; $j < $len; $j++) {
$char = substr($code,$j,1);
$p = (ord($char)-64) * pow(26,$len-$j-1);
$i += $p;
}
return $i;
}
/**
* excel数字索引转换成列
*/
static public function excelindex2col($index) {
$code = '';
$index--;
while($index >= 0) {
$code = chr($index % 26 + 65) . $code;
$index = floor($index / 26) - 1;
}
return $code;
}
/**
* 由于php的json扩展自带的函数json_encode会将汉字转换成unicode码
* 所以我们在这里用自定义的json_encode,这个函数不会将汉字转换为unicode码
*/
static public function customJsonEncode($a = false) {
if (is_null ( $a ) || (is_string($a) && strtoupper($a) == 'NULL'))
return "\"\"";
if ($a === false)
return 'false';
if ($a === true)
return 'true';
if (is_scalar ( $a )) {
if (is_float ( $a )) {
// Always use "." for floats.
return floatval ( str_replace ( ",", ".", strval ( $a ) ) );
}
if (is_string ( $a )) {
static $jsonReplaces = array (array ("\\", "/", "\n", "\t", "\r", "\b", "\f", '"' ), array ('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"' ) );
return '"' . str_replace ( $jsonReplaces [0], $jsonReplaces [1], $a ) . '"';
} else {
return $a;
}
}
$isList = true;
for($i = 0, reset ( $a ); $i < count ( $a ); $i ++, next ( $a )) {
if (key ( $a ) !== $i) {
$isList = false;
break;
}
}
$result = array ();
if ($isList) {
foreach ( $a as $v )
$result [] = self::customJsonEncode ( $v );
return '[' . join ( ',', $result ) . ']';
} else {
foreach ( $a as $k => $v )
$result [] = self::customJsonEncode ( $k ) . ':' . self::customJsonEncode ( $v );
return '{' . join ( ',', $result ) . '}';
}
}
/**
* Google经纬度标准转成BaiDu经纬度标准
* array $latlng
* array(
* 'lat'=>'',
* 'lng'=>''
* )
*/
static public function g2b($latlng = array())
{
if(!$latlng){
return;
}
$latlng = (object)$latlng;
if(isset($latlng->lat) && $latlng->lat){
$latlng->lat = round( floatval($latlng->lat + 0.0060 )*10000000) / 10000000;
}
if(isset($latlng->lng) && $latlng->lng){
$latlng->lng = round( floatval($latlng->lng + 0.0065 )*10000000) / 10000000;
}
return $latlng;
}
/**
* BaiDu经纬度标准转成Google经纬度标准
* array $latlng
* array(
* 'lat'=>'',
* 'lng'=>''
* )
*/
static public function b2g($latlng = array())
{
if(!$latlng){
return;
}
$latlng = (object)$latlng;
if(isset($latlng->lat) && $latlng->lat){
$latlng->lat = round( floatval($latlng->lat - 0.0060 )*10000000) / 10000000;
}
if(isset($latlng->lng) && $latlng->lng){
$latlng->lng = round( floatval($latlng->lng - 0.0065 )*10000000) / 10000000;
}
return $latlng;
}
/**
* 根据所传字段数组,弹出不符合规则元素
* @param array $fields
* @param array $params
*/
static public function UnsetField($fields=array(),$params)
{
if(is_object($params)){
$params = (array)$params;
}
// if(!empty($fields) && !empty($params)){
if(isset($fields) && !empty($params)){
foreach($params as $k=>$v){
if(!in_array($k,$fields)){
unset($params[$k]);
}
}
}
return $params;
}
/**
* 提供一个点的经纬度,提供边长,返回以此点为中心的矩形区域经纬度串 2013-07-04 by lizw
* $lng经度,$lat纬度,$x东西向边长(米),$y南北向边长(米)
*
* @return str (例:111.1105309,32.2204492;111.1105309,32.2195508;111.1094691,32.2195508;111.1094691,32.2204492)
*/
static public function getlatlngfromdis($lng,$lat,$x,$y)
{
$str = '';
if($lng && $lat && $x > 0 && $y > 0) {
$radLat1x = $radLat2x = deg2rad($lat);
$sx = abs(2 * asin(sqrt(pow(sin($x / (2 * 2 * 6378137)),2) / (cos($radLat1x) * cos($radLat2x)))));
$sy = abs($y / (2 * 6378137));
$dx = round(rad2deg($sx),7);
$dy = round(rad2deg($sy),7);
$maxlng = $lng + $dx;
$minlng = $lng - $dx;
$maxlat = $lat + $dy;
$minlat = $lat - $dy;
$str = $maxlng . ',' . $maxlat;
$str .= ';' . $maxlng . ',' . $minlat;
$str .= ';' . $minlng . ',' . $minlat;
$str .= ';' . $minlng . ',' . $maxlat;
}
return $str;
}
/*
文件缓存set方法
$key string 类型
$data string 数据
zhaowenda 2013-07-17
*/
static public function setKcache($key,$data){
global $app;
self::import($app->getAppRoot(). "lib/Kcache.php");
$kcache = new Kcache($key);
$arr=(array)json_decode($_COOKIE['cacheuniqid']);
if($arr[$key]){
$oldcachekey=$key.'_'.$app->user->uid.'_'.$arr[$key];
$kcache->delete_cache($oldcachekey);
}
$arr[$key]=str_replace('.','',uniqid(null,true));
$uniqid=json_encode($arr);
setcookie("cacheuniqid",$uniqid,time()+3600);
$cachekey=$key.'_'.$app->user->uid.'_'.$arr[$key];
$data=$kcache->set($cachekey,$data);
unset($kcache);
return $data;
}
/*
文件缓存set方法
$key string 类型
zhaowenda 2013-07-17
*/
static public function getKcache($key){
global $app;
self::import($app->getAppRoot(). "lib/Kcache.php");
$uniqid=(array)json_decode($_COOKIE['cacheuniqid']);
$cachekey=$key.'_'.$app->user->uid.'_'.$uniqid[$key];
$kcache = new Kcache($key);
$data=$kcache->get($cachekey,3600);
unset($kcache);
return $data;
}
/*
分段导出
*/
static public function putcsv($arr){
$cache=json_decode($_COOKIE['cacheuniqid']);
$filename=$cache->search_cache;
$temp=$arr['data'];
$fields=$arr['fields'];
$string=$arr['string'];
unset($arr);
$list=array();
if($temp){
foreach ($temp as $v) {
$arr=array();
foreach ($fields as $kk=>$vv) {
if(in_array($kk,$string)){
$arr[$kk]='="'.$v->$kk.'"';
}else{
$arr[$kk]=$v->$kk;
}
}
array_push($list,$arr);
unset($arr);
}
}
set_time_limit(0);
global $app;
$root=$app->getAppRoot();
$path="{$root}www/download/share/export/";
$first=!file_exists($path.$filename.".csv");
$file = fopen($path.$filename.".csv","a+");
if($first){
fputcsv($file,helper::charseticonv($fields));
}
if($list){
foreach ($list as $key=>$line)
{
$arr=$line;
$arr=self::charseticonv($arr);
fputcsv($file,$arr);
}
fclose($file);
return true;
}else{
return false;
}
}
}//end helper
/* 别名函数,生成对内部方法的链接。 */
function inLink($methodName = 'index', $vars = '', $viewType = '')
{
global $app;
return helper::createLink($app->getModuleName(), $methodName, $vars, $viewType);
}
/* 循环一个数组。*/
function cycle($items)
{
static $i = 0;
if(!is_array($items)) $items = explode(',', $items);
if(!isset($items[$i])) $i = 0;
return $items[$i++];
}
/* 时间格式化常量 */
define('DF_DATETIME', 'Y-m-d H:i:s');
define('DF_DATE', 'Y-m-d');
define('DF_TIME', 'H:i:s');<file_sep>var top_panel = new Ext.form.FormPanel({
region: 'north',
hideLabels: true,
bodyStyle: 'padding: 10px',
height: 50,
items: [{
xtype: 'compositefield',
items: [{
xtype: 'displayfield',
value: '员工姓名:'
}, {
xtype: 'textfield',
id: 's_user_name',
width: 200
},
{
xtype: 'button',
text: '查询',
style: 'padding-left : 10px;',
handler: function() {
_store.removeAll(); //移除原来的数据
_store.load(); //加载新搜索的数据
}
},
]
}]
});<file_sep>/*
Navicat MySQL Data Transfer
Source Server : kuu.ren
Source Server Version : 50545
Source Host : 172.16.17.32:3306
Source Database : ecs_admin
Target Server Type : MYSQL
Target Server Version : 50545
File Encoding : 65001
Date: 2016-05-06 10:24:49
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for ecsa_extract
-- ----------------------------
DROP TABLE IF EXISTS `ecsa_extract`;
CREATE TABLE `ecsa_extract` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`type` tinyint(2) NOT NULL DEFAULT '1' COMMENT '提现类型(1:工资;2:直推奖)',
`total` decimal(11,2) NOT NULL,
`extract_total` decimal(11,2) NOT NULL COMMENT '申请提现金额',
`pay_total` decimal(11,2) NOT NULL COMMENT '升级缴费金额',
`status` tinyint(2) NOT NULL DEFAULT '0' COMMENT '状态(1:待审核;2:待发放;3:已发放)',
`dismiss_reason` varchar(255) NOT NULL COMMENT '驳回原因',
`createtime` datetime NOT NULL,
`creator_id` int(11) NOT NULL,
`last_operator` varchar(255) NOT NULL DEFAULT '',
`updatetime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of ecsa_extract
-- ----------------------------
INSERT INTO `ecsa_extract` VALUES ('1', '22', '1', '123.00', '123.00', '13.00', '2', '请问啥的', '2016-04-24 17:45:17', '1', '123', '2016-04-24 18:11:16');
-- ----------------------------
-- Table structure for ecsa_orders
-- ----------------------------
DROP TABLE IF EXISTS `ecsa_orders`;
CREATE TABLE `ecsa_orders` (
`order_id` int(11) NOT NULL,
`order_sn` varchar(255) NOT NULL,
`user_id` int(11) NOT NULL COMMENT '下单者',
`add_time` datetime NOT NULL COMMENT '添加时间',
`creator_id` int(11) NOT NULL COMMENT '创建者id',
`last_operator` varchar(255) NOT NULL DEFAULT '' COMMENT '最后修改着',
`check_time` datetime DEFAULT NULL COMMENT '审核时间',
`check_user` int(11) NOT NULL COMMENT '审核人',
PRIMARY KEY (`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of ecsa_orders
-- ----------------------------
INSERT INTO `ecsa_orders` VALUES ('83', '2015110140578', '22', '2015-11-01 12:24:51', '696469', '刘峙', '2016-04-24 20:02:32', '696469');
INSERT INTO `ecsa_orders` VALUES ('119', '2016050440938', '41', '2016-05-04 12:18:43', '696469', '刘峙', '2016-05-04 17:08:05', '696469');
INSERT INTO `ecsa_orders` VALUES ('127', '2016050512558', '44', '2016-05-05 02:55:55', '696469', '刘峙', '2016-05-05 04:25:50', '696469');
-- ----------------------------
-- Table structure for ecsa_sys_login_logs
-- ----------------------------
DROP TABLE IF EXISTS `ecsa_sys_login_logs`;
CREATE TABLE `ecsa_sys_login_logs` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL COMMENT '用户ID',
`login_ip` varchar(16) DEFAULT NULL COMMENT '登录IP',
`createtime` datetime NOT NULL,
`updatetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=48 DEFAULT CHARSET=utf8 COMMENT='系统登录日志表';
-- ----------------------------
-- Records of ecsa_sys_login_logs
-- ----------------------------
INSERT INTO `ecsa_sys_login_logs` VALUES ('1', '696469', '127.0.0.1', '2016-04-23 06:47:30', '2016-04-23 12:47:30');
INSERT INTO `ecsa_sys_login_logs` VALUES ('2', '22', '127.0.0.1', '2016-04-24 19:53:39', '2016-04-24 19:53:39');
INSERT INTO `ecsa_sys_login_logs` VALUES ('3', '696469', '127.0.0.1', '2016-04-24 19:55:33', '2016-04-24 19:55:33');
INSERT INTO `ecsa_sys_login_logs` VALUES ('4', '696469', '127.0.0.1', '2016-04-24 20:01:37', '2016-04-24 20:01:37');
INSERT INTO `ecsa_sys_login_logs` VALUES ('5', '22', '127.0.0.1', '2016-04-24 20:03:22', '2016-04-24 20:03:22');
INSERT INTO `ecsa_sys_login_logs` VALUES ('6', '696469', '127.0.0.1', '2016-04-24 20:04:38', '2016-04-24 20:04:38');
INSERT INTO `ecsa_sys_login_logs` VALUES ('7', '22', '127.0.0.1', '2016-04-24 20:05:45', '2016-04-24 20:05:45');
INSERT INTO `ecsa_sys_login_logs` VALUES ('8', '22', '127.0.0.1', '2016-04-24 20:10:43', '2016-04-24 20:10:43');
INSERT INTO `ecsa_sys_login_logs` VALUES ('9', '696469', '127.0.0.1', '2016-04-24 20:11:37', '2016-04-24 20:11:37');
INSERT INTO `ecsa_sys_login_logs` VALUES ('10', '696469', '127.0.0.1', '2016-04-25 22:16:02', '2016-04-25 22:16:02');
INSERT INTO `ecsa_sys_login_logs` VALUES ('11', '696469', '127.0.0.1', '2016-04-25 22:16:26', '2016-04-25 22:16:26');
INSERT INTO `ecsa_sys_login_logs` VALUES ('12', '696469', '127.0.0.1', '2016-04-25 22:17:45', '2016-04-25 22:17:45');
INSERT INTO `ecsa_sys_login_logs` VALUES ('13', '696469', '127.0.0.1', '2016-04-29 01:10:15', '2016-04-29 01:10:15');
INSERT INTO `ecsa_sys_login_logs` VALUES ('14', '696469', '127.0.0.1', '2016-04-29 19:27:16', '2016-04-29 19:27:16');
INSERT INTO `ecsa_sys_login_logs` VALUES ('15', '696469', '127.0.0.1', '2016-04-29 19:38:26', '2016-04-29 19:38:26');
INSERT INTO `ecsa_sys_login_logs` VALUES ('16', '696469', '127.0.0.1', '2016-04-29 22:41:12', '2016-04-29 22:41:12');
INSERT INTO `ecsa_sys_login_logs` VALUES ('17', '696469', '127.0.0.1', '2016-04-30 05:49:13', '2016-04-30 05:49:13');
INSERT INTO `ecsa_sys_login_logs` VALUES ('18', '696469', '127.0.0.1', '2016-05-01 17:44:01', '2016-05-01 17:44:01');
INSERT INTO `ecsa_sys_login_logs` VALUES ('19', '696469', '127.0.0.1', '2016-05-03 23:07:04', '2016-05-03 23:07:04');
INSERT INTO `ecsa_sys_login_logs` VALUES ('20', '696469', '127.0.0.1', '2016-05-03 23:14:51', '2016-05-03 23:14:51');
INSERT INTO `ecsa_sys_login_logs` VALUES ('21', '696469', '127.0.0.1', '2016-05-03 23:17:36', '2016-05-03 23:17:36');
INSERT INTO `ecsa_sys_login_logs` VALUES ('22', '696469', '127.0.0.1', '2016-05-03 23:18:52', '2016-05-03 23:18:52');
INSERT INTO `ecsa_sys_login_logs` VALUES ('23', '696469', '127.0.0.1', '2016-05-03 23:22:37', '2016-05-03 23:22:37');
INSERT INTO `ecsa_sys_login_logs` VALUES ('24', '696469', '127.0.0.1', '2016-05-03 23:22:54', '2016-05-03 23:22:54');
INSERT INTO `ecsa_sys_login_logs` VALUES ('25', '696469', '127.0.0.1', '2016-05-03 23:23:13', '2016-05-03 23:23:13');
INSERT INTO `ecsa_sys_login_logs` VALUES ('26', '696469', '127.0.0.1', '2016-05-03 23:23:27', '2016-05-03 23:23:27');
INSERT INTO `ecsa_sys_login_logs` VALUES ('27', '696469', '127.0.0.1', '2016-05-04 04:31:21', '2016-05-04 04:31:21');
INSERT INTO `ecsa_sys_login_logs` VALUES ('28', '696469', '127.0.0.1', '2016-05-04 04:39:14', '2016-05-04 04:39:14');
INSERT INTO `ecsa_sys_login_logs` VALUES ('29', '696469', '127.0.0.1', '2016-05-04 04:44:23', '2016-05-04 04:44:23');
INSERT INTO `ecsa_sys_login_logs` VALUES ('30', '696469', '127.0.0.1', '2016-05-04 04:47:22', '2016-05-04 04:47:22');
INSERT INTO `ecsa_sys_login_logs` VALUES ('31', '696469', '127.0.0.1', '2016-05-04 04:48:33', '2016-05-04 04:48:33');
INSERT INTO `ecsa_sys_login_logs` VALUES ('32', '696469', '192.168.3.11', '2016-05-04 06:17:30', '2016-05-03 23:17:30');
INSERT INTO `ecsa_sys_login_logs` VALUES ('33', '696469', '192.168.3.11', '2016-05-04 06:18:31', '2016-05-03 23:18:31');
INSERT INTO `ecsa_sys_login_logs` VALUES ('34', '696469', '172.16.17.32', '2016-05-04 07:35:34', '2016-05-04 00:35:34');
INSERT INTO `ecsa_sys_login_logs` VALUES ('35', '696469', '172.16.17.32', '2016-05-04 08:33:10', '2016-05-04 01:33:10');
INSERT INTO `ecsa_sys_login_logs` VALUES ('36', '696469', '192.168.3.11', '2016-05-04 09:33:02', '2016-05-04 02:33:02');
INSERT INTO `ecsa_sys_login_logs` VALUES ('37', '696469', '172.16.17.32', '2016-05-04 16:19:55', '2016-05-04 09:19:55');
INSERT INTO `ecsa_sys_login_logs` VALUES ('38', '696469', '192.168.3.11', '2016-05-05 02:43:15', '2016-05-04 19:43:15');
INSERT INTO `ecsa_sys_login_logs` VALUES ('39', '696469', '172.16.58.3', '2016-05-05 02:45:40', '2016-05-04 19:45:40');
INSERT INTO `ecsa_sys_login_logs` VALUES ('40', '696469', '192.168.3.11', '2016-05-05 06:03:10', '2016-05-04 23:03:10');
INSERT INTO `ecsa_sys_login_logs` VALUES ('41', '696469', '192.168.3.11', '2016-05-05 08:58:17', '2016-05-05 01:58:17');
INSERT INTO `ecsa_sys_login_logs` VALUES ('42', '696469', '192.168.3.11', '2016-05-05 11:08:55', '2016-05-05 04:08:55');
INSERT INTO `ecsa_sys_login_logs` VALUES ('43', '696469', '192.168.3.11', '2016-05-05 11:08:56', '2016-05-05 04:08:56');
INSERT INTO `ecsa_sys_login_logs` VALUES ('44', '696469', '172.16.17.32', '2016-05-05 11:37:44', '2016-05-05 04:37:44');
INSERT INTO `ecsa_sys_login_logs` VALUES ('45', '696469', '172.16.58.3', '2016-05-06 00:32:19', '2016-05-05 17:32:19');
INSERT INTO `ecsa_sys_login_logs` VALUES ('46', '696469', '172.16.58.3', '2016-05-06 01:07:00', '2016-05-05 18:07:00');
INSERT INTO `ecsa_sys_login_logs` VALUES ('47', '696469', '127.0.0.1', '2016-05-06 10:07:24', '2016-05-05 19:08:15');
-- ----------------------------
-- Table structure for ecsa_sys_role_source
-- ----------------------------
DROP TABLE IF EXISTS `ecsa_sys_role_source`;
CREATE TABLE `ecsa_sys_role_source` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`role_id` int(11) NOT NULL COMMENT '角色编码',
`source_id` varchar(18) NOT NULL COMMENT '资源编码',
`creator_id` int(11) NOT NULL COMMENT '创建者ID',
`last_operator` varchar(32) DEFAULT NULL COMMENT '最后修改者',
`remark` varchar(255) DEFAULT NULL COMMENT '备注',
`createtime` datetime NOT NULL,
`updatetime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`status` int(1) DEFAULT '1',
`is_del` int(1) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=52272 DEFAULT CHARSET=utf8 COMMENT='角色资源表';
-- ----------------------------
-- Records of ecsa_sys_role_source
-- ----------------------------
INSERT INTO `ecsa_sys_role_source` VALUES ('52266', '66', '772', '696469', '刘峙', null, '2016-04-23 00:12:35', '2016-04-23 06:12:35', '1', '0');
INSERT INTO `ecsa_sys_role_source` VALUES ('52267', '66', '777', '696469', '刘峙', null, '2016-04-23 00:12:35', '2016-04-23 06:12:35', '1', '0');
INSERT INTO `ecsa_sys_role_source` VALUES ('52268', '66', '778', '696469', '刘峙', null, '2016-04-23 00:12:35', '2016-04-23 06:12:35', '1', '0');
INSERT INTO `ecsa_sys_role_source` VALUES ('52269', '66', '779', '696469', '刘峙', null, '2016-04-23 00:12:35', '2016-04-23 06:12:35', '1', '0');
INSERT INTO `ecsa_sys_role_source` VALUES ('52270', '66', '781', '696469', '刘峙', null, '2016-04-23 00:12:35', '2016-04-23 06:12:35', '1', '0');
INSERT INTO `ecsa_sys_role_source` VALUES ('52271', '66', '780', '696469', '刘峙', null, '2016-04-23 00:12:35', '2016-04-23 06:12:35', '1', '0');
-- ----------------------------
-- Table structure for ecsa_sys_roles
-- ----------------------------
DROP TABLE IF EXISTS `ecsa_sys_roles`;
CREATE TABLE `ecsa_sys_roles` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`role_name` varchar(32) NOT NULL COMMENT '角色名称',
`creator_id` int(11) NOT NULL COMMENT '创建者ID',
`last_operator` varchar(16) DEFAULT NULL COMMENT '最后操作者',
`sort` int(3) DEFAULT NULL COMMENT '显示排序',
`createtime` datetime NOT NULL,
`updatetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`status` int(1) DEFAULT '1' COMMENT '状态(1=>正常,0=>禁用)',
`is_del` int(1) DEFAULT '0' COMMENT '是否删除(1=>已删除,0=>正常)',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=67 DEFAULT CHARSET=utf8 COMMENT='角色表';
-- ----------------------------
-- Records of ecsa_sys_roles
-- ----------------------------
INSERT INTO `ecsa_sys_roles` VALUES ('66', '操作员', '696469', '刘峙', null, '2016-04-23 00:12:35', '2016-04-23 06:12:35', '1', '0');
-- ----------------------------
-- Table structure for ecsa_sys_source
-- ----------------------------
DROP TABLE IF EXISTS `ecsa_sys_source`;
CREATE TABLE `ecsa_sys_source` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`source_code` varchar(18) NOT NULL COMMENT '资源编码',
`source_name` varchar(32) NOT NULL COMMENT '资源名称',
`url` varchar(255) DEFAULT NULL COMMENT '连接地址,用|隔开,后三个参数可以省略(handler[|iconCls|disable|id|phpFn])',
`type` int(1) DEFAULT '1' COMMENT '资源类型 (1=>菜单,2=>控件,3=>板块)',
`is_display` tinyint(2) DEFAULT NULL COMMENT '菜单是否显示(1,显示;0,隐藏;)',
`sort` int(3) DEFAULT '1' COMMENT '排序',
`creator_id` int(11) NOT NULL COMMENT '创建者ID',
`last_operator` varchar(32) DEFAULT NULL COMMENT '最后修改者',
`createtime` datetime NOT NULL,
`updatetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`status` int(1) DEFAULT '1' COMMENT '资源状态(0=>停用,1=>可用)',
`is_del` int(1) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=793 DEFAULT CHARSET=utf8 COMMENT='资源表';
-- ----------------------------
-- Records of ecsa_sys_source
-- ----------------------------
INSERT INTO `ecsa_sys_source` VALUES ('1', '101001', '资源管理', '/source', '1', '1', '1', '1', '刘峙', '2016-04-23 05:51:54', '2016-04-23 06:03:12', '1', '0');
INSERT INTO `ecsa_sys_source` VALUES ('2', '101001001', '添加', 'showAdd|silk-add|false|btnAdd|add', '2', null, '1', '0', '超级管理员', '2016-04-23 05:51:54', '2016-04-23 06:03:12', '1', '0');
INSERT INTO `ecsa_sys_source` VALUES ('3', '101001002', '删除', 'showDel|silk-delete|true|btnDel|delete', '2', null, '2', '0', '超级管理员', '2016-04-23 05:51:54', '2016-04-23 06:03:12', '1', '0');
INSERT INTO `ecsa_sys_source` VALUES ('4', '101001003', '编辑', 'showEdit|silk-edit|true|btnEdit|update', '2', null, '3', '0', '超级管理员', '2016-04-23 05:51:54', '2016-04-23 06:03:12', '1', '0');
INSERT INTO `ecsa_sys_source` VALUES ('772', '101', '系统管理', '/', '1', '1', '1', '696469', '刘峙', '2016-04-23 00:02:57', '2016-04-23 06:02:57', '1', '0');
INSERT INTO `ecsa_sys_source` VALUES ('773', '101002', '角色管理', '/role', '1', '1', '2', '696469', '刘峙', '2016-04-23 00:04:37', '2016-04-23 06:04:37', '1', '0');
INSERT INTO `ecsa_sys_source` VALUES ('774', '101002001', '添加', 'showAdd|silk-add|false|btnAdd|add', '2', null, '1', '696469', '刘峙', '2016-04-23 00:05:09', '2016-04-23 06:05:09', '1', '0');
INSERT INTO `ecsa_sys_source` VALUES ('775', '101002002', '编辑', 'showEdit|silk-edit|true|btnEdit|update', '2', null, '3', '696469', '刘峙', '2016-04-23 00:05:44', '2016-04-23 06:05:44', '1', '0');
INSERT INTO `ecsa_sys_source` VALUES ('776', '101002003', '删除', 'showDel|silk-delete|true|btnDel|delete', '2', null, '2', '696469', '刘峙', '2016-04-23 00:06:05', '2016-04-23 06:06:05', '1', '0');
INSERT INTO `ecsa_sys_source` VALUES ('777', '101003', '用户管理', '/user', '1', '1', '3', '696469', '刘峙', '2016-04-23 00:08:38', '2016-04-23 06:08:38', '1', '0');
INSERT INTO `ecsa_sys_source` VALUES ('778', '101003001', '添加', 'userAdd|silk-add|false|userAdd|userAdd', '2', null, '1', '696469', '刘峙', '2016-04-23 00:08:58', '2016-04-23 06:08:58', '1', '0');
INSERT INTO `ecsa_sys_source` VALUES ('779', '101003002', '编辑', 'userUpdate|silk-edit|true|userUpdate|userUpdate', '2', null, '2', '696469', '刘峙', '2016-04-23 00:09:43', '2016-04-23 06:09:43', '1', '0');
INSERT INTO `ecsa_sys_source` VALUES ('780', '101003003', '锁定', 'customerExecute(\'userLocked\')|silk-lock|true|userLocked|userLocked', '2', null, '4', '696469', '刘峙', '2016-04-23 00:10:10', '2016-04-23 06:11:01', '1', '0');
INSERT INTO `ecsa_sys_source` VALUES ('781', '101003004', '解锁', 'customerExecute(\'userUnLocked\')|silk-unlock|true|userUnLocked|userUnLocked', '2', null, '3', '696469', '刘峙', '2016-04-23 00:10:48', '2016-04-23 06:10:48', '1', '0');
INSERT INTO `ecsa_sys_source` VALUES ('782', '102', '订单管理', '/order', '1', '1', '2', '696469', '刘峙', '2016-04-23 06:48:58', '2016-04-23 12:48:58', '1', '0');
INSERT INTO `ecsa_sys_source` VALUES ('783', '102001', '驳回', 'showStatusTo_1|silk-cancel|true|btnStatusTo_1|statusTo_1', '2', null, '1', '696469', '刘峙', '2016-04-24 02:01:17', '2016-04-24 15:19:04', '1', '0');
INSERT INTO `ecsa_sys_source` VALUES ('784', '102002', '审核', 'showStatusTo1|silk-done|true|btnStatusTo1|statusTo1', '2', null, '2', '696469', '刘峙', '2016-04-24 09:19:49', '2016-04-24 15:16:17', '1', '0');
INSERT INTO `ecsa_sys_source` VALUES ('785', '103', '提现申请管理', '/extract', '1', '1', '3', '696469', '刘峙', '2016-04-24 16:30:51', '2016-04-24 16:30:51', '1', '0');
INSERT INTO `ecsa_sys_source` VALUES ('786', '103001', '驳回', 'showStatusTo_1|silk-cancel|true|btnStatusTo_1|statusTo_1', '2', null, '1', '696469', '刘峙', '2016-04-24 18:04:20', '2016-04-24 18:04:20', '1', '0');
INSERT INTO `ecsa_sys_source` VALUES ('787', '103002', '审核', 'showStatusTo1|silk-done|true|btnStatusTo1|statusTo1', '2', null, '2', '696469', '刘峙', '2016-04-24 18:05:04', '2016-04-24 18:05:04', '1', '0');
INSERT INTO `ecsa_sys_source` VALUES ('788', '103003', '已结款', 'showStatusTo2|silk-done|true|btnStatusTo2|statusTo2', '2', null, '3', '696469', '刘峙', '2016-04-24 18:06:01', '2016-04-24 18:11:47', '1', '0');
INSERT INTO `ecsa_sys_source` VALUES ('789', '103004', '导出', 'showExport|silk-export|false|btnExport|export', '2', null, '4', '696469', '刘峙', '2016-04-24 19:30:49', '2016-04-24 19:37:59', '1', '0');
INSERT INTO `ecsa_sys_source` VALUES ('790', '104', '用户信息', '/user_info', '1', '1', '4', '696469', '刘峙', '2016-04-24 21:11:36', '2016-04-24 21:11:36', '1', '0');
INSERT INTO `ecsa_sys_source` VALUES ('791', '105', '工资明细管理', '/wages', '1', '1', '5', '696469', '刘峙', '2016-05-01 17:45:03', '2016-05-01 17:45:03', '1', '0');
INSERT INTO `ecsa_sys_source` VALUES ('792', '102003', '修改邀请码', 'showUpdateInviteCode|silk-edit|true|btnUpdateInviteCode|updateInviteCode', '2', null, '3', '696469', '刘峙', '2016-05-06 10:21:01', '2016-05-05 19:21:52', '1', '0');
-- ----------------------------
-- Table structure for ecsa_sys_user_roles
-- ----------------------------
DROP TABLE IF EXISTS `ecsa_sys_user_roles`;
CREATE TABLE `ecsa_sys_user_roles` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL COMMENT '用户ID',
`role_id` varchar(18) NOT NULL COMMENT '角色编码',
`creator_id` int(11) DEFAULT NULL COMMENT '创建者ID',
`createtime` datetime NOT NULL,
`updatetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`status` int(1) DEFAULT '1' COMMENT '状态(1=>正常)',
`is_del` int(1) DEFAULT '0' COMMENT '是否删除(1=>已删除,0=>正常)',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=293 DEFAULT CHARSET=utf8 COMMENT='用户角色表';
-- ----------------------------
-- Records of ecsa_sys_user_roles
-- ----------------------------
INSERT INTO `ecsa_sys_user_roles` VALUES ('291', '1001258', '66', '696469', '2016-04-23 00:21:00', '2016-04-23 06:21:00', '1', '0');
INSERT INTO `ecsa_sys_user_roles` VALUES ('292', '1001259', '66', '696469', '2016-04-24 21:02:10', '2016-04-24 21:02:10', '1', '0');
-- ----------------------------
-- Table structure for ecsa_sys_users
-- ----------------------------
DROP TABLE IF EXISTS `ecsa_sys_users`;
CREATE TABLE `ecsa_sys_users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_code` varchar(11) NOT NULL COMMENT '用户编码',
`user_name` varchar(32) DEFAULT NULL COMMENT '用户名',
`true_name` varchar(16) DEFAULT NULL COMMENT '真实姓名',
`level` tinyint(2) NOT NULL DEFAULT '1' COMMENT '级别',
`week` tinyint(2) NOT NULL DEFAULT '1' COMMENT '当前处于第几周',
`user_email` varchar(32) DEFAULT NULL COMMENT '用户邮箱',
`user_mobile` varchar(11) DEFAULT NULL COMMENT '用户手机',
`user_pwd` varchar(32) NOT NULL COMMENT '用户密码',
`last_login_time` datetime DEFAULT NULL COMMENT '用户最后登陆时间',
`creator_id` int(11) NOT NULL COMMENT '创建人id',
`last_operator` varchar(16) DEFAULT NULL COMMENT '最后操作者',
`remark` varchar(255) DEFAULT NULL COMMENT '备注',
`createtime` datetime NOT NULL,
`updatetime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`is_admin` tinyint(1) DEFAULT '0' COMMENT '是否管理员(0否,1是)',
`status` int(1) DEFAULT '1' COMMENT ' 用户状态(1=>正常,0=>锁住)',
`is_del` int(1) DEFAULT '0' COMMENT '是否删除(1=>已删除,0=>未删除)',
`type` int(1) NOT NULL DEFAULT '1' COMMENT '用户类型:1会员,2员工',
`invite_code` int(11) NOT NULL DEFAULT '0' COMMENT '邀请码',
`card` varchar(255) DEFAULT NULL COMMENT '身份证号',
`bank_name` varchar(255) DEFAULT NULL COMMENT '所属银行',
`bank_card_no` varchar(255) DEFAULT NULL COMMENT '银行卡号',
`reg_time` datetime NOT NULL,
`sort_id` int(11) NOT NULL COMMENT '从1开始,用户的位置',
`all_child_num` int(11) NOT NULL DEFAULT '0' COMMENT '推荐人数',
`child_num` int(11) NOT NULL DEFAULT '0' COMMENT '直推人数',
PRIMARY KEY (`id`),
UNIQUE KEY `user_code_unique` (`user_code`) USING BTREE,
UNIQUE KEY `user_name_unique` (`user_name`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1001260 DEFAULT CHARSET=utf8 COMMENT='用户表';
-- ----------------------------
-- Records of ecsa_sys_users
-- ----------------------------
INSERT INTO `ecsa_sys_users` VALUES ('22', '1604231234', 'test2', 'test2', '1', '1', null, '13800138000', '{MD5}NWcbYMFrUrf589OL4x0dbg==', '2016-04-24 20:10:43', '696469', '刘峙', null, '2016-04-24 20:02:32', '2016-05-04 03:07:22', '0', '1', '0', '1', '2', '', '52', '62', '2015-09-30 11:57:35', '1', '0', '0');
INSERT INTO `ecsa_sys_users` VALUES ('41', '1605026938', '姜建军', '姜建军', '1', '1', null, '15922224008', '{MD5}JhgPa7wrnIRTWHTcJUtoTg==', null, '696469', '刘峙', null, '2016-05-04 17:08:05', '2016-05-04 17:08:05', '0', '1', '0', '1', '0', '12010519810209271011', '中国工商银行', '6212260302019151000', '2016-05-02 07:59:55', '4', '0', '0');
INSERT INTO `ecsa_sys_users` VALUES ('44', '1605050488', 'u159WVGT4008', 'u159WVGT4008', '1', '1', null, '15922224008', '{MD5}/RuxVbs0pU9l8EK10ZB1Eg==', null, '696469', '刘峙', null, '2016-05-05 04:25:50', '2016-05-05 04:25:50', '0', '1', '0', '1', '0', '120105198102092710', '中国工商银行', '677868767867867867', '2016-05-05 02:54:38', '4', '0', '0');
INSERT INTO `ecsa_sys_users` VALUES ('696469', '1604231233', 'liuzhi', '刘峙', '1', '1', '<EMAIL>', '', '{MD5}4QrcOUm6Wau+VuBX8g+IPg==', '2016-05-06 10:07:24', '676561', '刘峙', '', '2013-09-27 10:41:00', '2016-05-05 19:08:16', '1', '1', '0', '2', '1604231235', '12312312222323232', '中国邮政', '213122353464564', '2016-05-04 03:07:44', '2', '0', '0');
INSERT INTO `ecsa_sys_users` VALUES ('1001258', '', 'test', '阿阿斯顿', '1', '1', '12312', '12312', '{MD5}4uMaQn0ujEhRtT9+65//lQ==', null, '696469', '刘峙', '1', '2016-04-23 00:21:00', '2016-04-29 19:33:06', '0', '1', '0', '1', '0', null, null, null, '0000-00-00 00:00:00', '3', '0', '0');
INSERT INTO `ecsa_sys_users` VALUES ('1001259', '1604231235', 'testss', '大师傅', '1', '1', '<EMAIL>', '', '{MD5}6bwOE6ihbLsHsXXZKhExJg==', null, '696469', '刘峙', '', '2016-04-24 21:02:09', '2016-05-04 03:09:06', '0', '1', '0', '1', '0', null, null, null, '0000-00-00 00:00:00', '4', '0', '0');
-- ----------------------------
-- Table structure for ecsa_sys_users_level
-- ----------------------------
DROP TABLE IF EXISTS `ecsa_sys_users_level`;
CREATE TABLE `ecsa_sys_users_level` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`level_id` tinyint(2) NOT NULL,
`level_name` varchar(255) NOT NULL COMMENT '级别名称',
`is_end` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否为最终级别',
`is_del` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of ecsa_sys_users_level
-- ----------------------------
INSERT INTO `ecsa_sys_users_level` VALUES ('1', '1', 'A1', '0', '0');
INSERT INTO `ecsa_sys_users_level` VALUES ('2', '2', 'A2', '0', '0');
INSERT INTO `ecsa_sys_users_level` VALUES ('3', '3', 'B1', '0', '0');
INSERT INTO `ecsa_sys_users_level` VALUES ('4', '4', 'B2', '0', '0');
INSERT INTO `ecsa_sys_users_level` VALUES ('5', '5', 'C1', '0', '0');
INSERT INTO `ecsa_sys_users_level` VALUES ('6', '6', 'C2', '0', '0');
INSERT INTO `ecsa_sys_users_level` VALUES ('7', '7', 'D1', '0', '0');
INSERT INTO `ecsa_sys_users_level` VALUES ('8', '8', 'D2', '0', '0');
INSERT INTO `ecsa_sys_users_level` VALUES ('9', '9', 'E1', '0', '0');
INSERT INTO `ecsa_sys_users_level` VALUES ('10', '10', 'E2', '1', '0');
-- ----------------------------
-- Table structure for ecsa_user_wages
-- ----------------------------
DROP TABLE IF EXISTS `ecsa_user_wages`;
CREATE TABLE `ecsa_user_wages` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL COMMENT '用户id',
`all_user_wages` decimal(11,2) NOT NULL COMMENT '工资',
`all_wages_status` tinyint(2) NOT NULL DEFAULT '0' COMMENT '工资提现状态(0:不可提现;1:未提现;2:提现中;3:提现完成)',
`user_wages` decimal(11,2) NOT NULL COMMENT '直推奖',
`wages_status` tinyint(2) NOT NULL DEFAULT '1' COMMENT '直推奖提现状态(0:不可提现;1:未提现;2:提现中;3:提现完成)',
PRIMARY KEY (`id`),
UNIQUE KEY `user_id_unique` (`user_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT='用户当前工资和直推奖';
-- ----------------------------
-- Records of ecsa_user_wages
-- ----------------------------
INSERT INTO `ecsa_user_wages` VALUES ('2', '696469', '10.00', '0', '30.00', '1');
<file_sep><?php
/**
* 资源
* @author liuzhi
* @
*/
class sourceModel extends model
{
public function __construct()
{
parent::__construct();//去掉旧表 guojuan
}
public function add($record,$tabel) {
$cId = parent::insert($record,$tabel);
if($cId) {
return $cId;
}
else {
return 0;
}
}
public function update($ids=array(),$setarr =array(),$tb='')
{
return parent::update($setarr,$ids,$tb);
}
public function delete($id){
return parent::delete("id=$id",1,"ecsa_sys_source");
}
public function search($where='',$fields='') {
$sql = "select %s from ecsa_sys_source as a
left join ecsa_sys_source as b on b.source_code = substring(a.source_code,1,length(a.source_code)-3)";
if($fields == '')$fields = " a.*,b.source_code as parent_code,b.source_name as parent_name ";
$datas = parent::findBySql($sql,$where,'b.source_code,a.sort',null,$fields);
return $datas;
}
public function searchAll($wheresql='') {
$sql = "select %s from ecsa_sys_source as a ";
$fields = " a.* ";
$datas = parent::findBySql($sql,$wheresql,'a.source_code',null,$fields);
return $datas;
}
/*
* 资源下是否有子资源*/
public function checkSourceHaveChild($source_code){
$length = intVal(strlen($source_code))+3;
$wheresql = " source_code like '$source_code%' and length(source_code) = $length and is_del = 0";
$fields = " count(*) as total ";
$sql = "select %s from ecsa_sys_source";
$datas = parent::findBySql($sql,$wheresql,null,null,$fields);
return ($datas[0]->total > 0)?true:false;
}
}
<file_sep>/**
* 用户管理列表
* yuli
* 2013/11/12
*/
userStore.load();
var _sm =new Ext.grid.RowSelectionModel({
singleSelect: true,
listeners: {
selectionchange: function(data) {
sm = grid_list.getSelectionModel();
info = sm.getSelections();
if (data.getCount())
{
if(info[0].get("status") == 1)
{
(Ext.getCmp('userLocked')) ? Ext.getCmp('userLocked').enable() : '';//锁住按钮
//当用户解锁状态下,切换操作管理员按钮//Task #40327 gsp 权限方案整理 by lixiaoli 2015/05/22
if(info[0].get("is_admin") == 1){
(Ext.getCmp('downAdmin')) ? Ext.getCmp('downAdmin').enable() : '';//取消管理员资格按钮
}else{
(Ext.getCmp('upAdmin')) ? Ext.getCmp('upAdmin').enable() : '';//升级为管理员按钮
}
}
if(info[0].get("status") == 0)
{
(Ext.getCmp('userUnLocked')) ? Ext.getCmp('userUnLocked').enable() : '';//解锁按钮
}
(Ext.getCmp('userUpdate')) ? Ext.getCmp('userUpdate').enable() : '';//修改按钮
}
else
{
(Ext.getCmp('userLocked')) ? Ext.getCmp('userLocked').disable() : '';//锁住按钮
(Ext.getCmp('userUnLocked')) ? Ext.getCmp('userUnLocked').disable() : '';//解锁按钮
(Ext.getCmp('userUpdate')) ? Ext.getCmp('userUpdate').disable() : '';//修改按钮
//Task #40327 gsp 权限方案整理 by lixiaoli 2015/05/22
(Ext.getCmp('downAdmin')) ? Ext.getCmp('downAdmin').disable() : '';//取消管理员资格按钮
(Ext.getCmp('upAdmin')) ? Ext.getCmp('upAdmin').disable() : '';//升级为管理员按钮
}
if (data.hasSelection()) {
for(var i=0;i<data.getCount();i++)
{
var row = data.selections.itemAt(i).data;
crow = row;
}
} else {
crow = '';
}
initBtn(crow);
}
}
});
//用户管理列表 开始
var grid_list = new Ext.grid.GridPanel({
title :'用户管理列表',
region : 'center',
loadMask : true,
cm : new Ext.grid.ColumnModel([
{header : '用户名',dataIndex : 'user_name',width:90},
{header : '姓名',dataIndex : 'true_name',width:90},
{header : '编号',dataIndex : 'user_code',width:90},
{header : '角色',dataIndex : 'role_name',width:90},
/*{header : '是否是管理员',dataIndex : 'is_admin',width:150,renderer : function(value, cellMeta, record, rowIndex, columnIndex, store){
if(value == 1) {
return '<span style="color:red">是</span>';
} else {
return '否';
}
}},*/
{header : '锁定状态',dataIndex : 'action',width:90,renderer : function(value, cellMeta, record, rowIndex, columnIndex, store){
if(record.data['status'] == 0)
{
return '<span style="color:red">已锁定</span>';
}
else if(record.data['status'] == 1)
{
return '未锁定';
}
}},
{header : '用户类型',dataIndex : 'type',width:90,renderer : function(value, cellMeta, record, rowIndex, columnIndex, store){
if ( value == 1 ) {
return "会员";
} else if( value == 2) {
return "员工";
} else {
return '';
}
}},
{header : '级别',dataIndex : 'level_name',width:90},
{header : '业绩人数',dataIndex : 'all_child_num',width:90},
{header : '绩效考核人数',dataIndex : 'child_num',width:90},
{header : '创建时间',dataIndex : 'createtime',type:'date',width:150},
{header : '最后修改时间',dataIndex : 'updatetime',type:'date',width:150},
{header : '最后登录时间',dataIndex : 'last_login_time',type:'date',width:150}
]),
store : userStore,
sm :_sm,
//固定表格的宽度 注释掉,显示宽度滚动条
// viewConfig:{
// forceFit:true
// },
//分页
bbar: new Ext.PagingToolbar({
plugins: new Ext.ux.plugin.PagingToolbarResizer,
pageSize: pagesize,
displayInfo : true,
displayMsg : '当前记录数: {0} - {1} 总记录数: {2}',
emptyMsg : '没有符合条件的记录',
store : userStore
}),
tbar : []
});
//列表表格
var main_tab_panel = new Ext.TabPanel({
xtype : "tabpanel",
region : "center",
id : 'sale_firm_tab',
items:
[
grid_list
]
});
main_tab_panel.setActiveTab(grid_list);//设置特定的tab为活动面板
/**
* 锁住操作方法
* url AJAX请求PHP的方法 userLocked=>锁住 userUnLocked=>解锁
* yu li
* 2013/11/11
*/
function customerExecute(url)
{
var type = '';
var str = '';
var sm = grid_list.getSelectionModel();
var data = sm.getSelections();
var ids = '';
//复选改成单选
// for(var i=0; i<data.length; i++){
// ids += data[i].get("id") + '|';
// }
ids = data[0].get("id");
var name = data[0].get("user_name");
if(url == 'userLocked')
{
type = '锁住';
str = '锁定之后该用户不能登陆,确定要锁定['+name+']?';
}
else if(url == 'userUnLocked')
{
type = '解锁';
str = '解锁之后该用户可以登陆,确定要解锁['+name+']?';
}
//Task #40327 gsp 权限方案整理 by lixiaoli
var is_admin = data[0].get("is_admin");
if(ids == 1){
Ext.Msg.alert('系统提示', '用户['+name+']是超级管理员,您不能对此用户做'+type+'操作');
return false;
}
Ext.Ajax.request({
url:'../inside.php?t=json&m=user&f=checkAdmin',
method:'post',
params:{},
success: function sFn(response,options)
{
var res = Ext.decode(response.responseText).msg;
if(res != 1 && (is_admin == 1 || ids == 1)){
Ext.MessageBox.alert('提示', '用户['+name+']是管理员,您不能对此用户做'+type+'操作');
return false;
}else{
Ext.MessageBox.confirm(''+type+'', str, function showResult(btn){
if (btn == 'yes')
{
Ext.Ajax.request({
url:'../inside.php?t=json&m='+ controlName +'&f='+url,
method:'post',
params:{ids:ids},
success: function sFn(response,options)
{
userStore.load({
callback: function(){
crow = _sm.getSelected().data;
initBtn(crow);
}
});//刷新页面
Ext.Msg.alert('系统提示', Ext.decode(response.responseText).msg);
}
});
}
});
}
}
})
}
//切换管理员操作
//Task #40327 gsp 权限方案整理 by lixiaoli
function adminExecute(url){
var sm = grid_list.getSelectionModel();
var data = sm.getSelections();
var is_admin = data[0].get("is_admin");
var id = data[0].get("id");
var name = data[0].get("user_name");
Ext.Ajax.request({
url:'../inside.php?t=json&m=user&f=checkAdmin',
method:'post',
params:{},
success: function sFn(response,options)
{
var res = Ext.decode(response.responseText).msg;
if(res != 1){
Ext.MessageBox.alert('提示', '您没有权限设置/取消管理员');
return false;
}else{
if(url == 'upAdmin')
{
type = '升级为管理员';
str = '确定要把用户['+name+']升级为管理员?';
}
else if(url == 'downAdmin')
{
type = '取消管理员资格';
str = '确定要取消用户['+name+']管理员资格?';
}
Ext.MessageBox.confirm(''+type+'', str, function showResult(btn){
if (btn == 'yes')
{
Ext.Ajax.request({
url:'../inside.php?t=json&m='+ controlName +'&f=changeAdmin',
method:'post',
params:{id:id, is_admin:is_admin},
success: function sFn(response,options)
{
var data = Ext.decode(response.responseText);
if(data.success) {
userStore.load();//刷新页面
if(is_admin == 1){
(Ext.getCmp('upAdmin')) ? Ext.getCmp('upAdmin').enable() : '';//升级为管理员按钮
(Ext.getCmp('downAdmin')) ? Ext.getCmp('downAdmin').disable() : '';//取消管理员资格按钮
}else{
(Ext.getCmp('upAdmin')) ? Ext.getCmp('upAdmin').disable() : '';//升级为管理员按钮
(Ext.getCmp('downAdmin')) ? Ext.getCmp('downAdmin').enable() : '';//取消管理员资格按钮
}
}
Ext.Msg.alert('系统提示', data.msg);
}
});
}
});
}
}
});
}
/**
* 初始化按钮
* //Story #35124
* @param {Object} row
* @author liuzhi
* @date 20150526
*/
function initBtn(row){
(Ext.getCmp('userUpdate')) ? Ext.getCmp('userUpdate').disable() : '';//修改按钮
(Ext.getCmp('userLocked')) ? Ext.getCmp('userLocked').disable() : '';//锁住按钮
(Ext.getCmp('userUnLocked')) ? Ext.getCmp('userUnLocked').disable() : '';//解锁按钮
if (row) {
(Ext.getCmp('userUpdate')) ? Ext.getCmp('userUpdate').enable() : '';//修改按钮
if (row.status == 1) {
(Ext.getCmp('userLocked')) ? Ext.getCmp('userLocked').enable() : '';//锁住按钮
} else if (row.status == 0) {
(Ext.getCmp('userUnLocked')) ? Ext.getCmp('userUnLocked').enable() : '';//解锁按钮
}
}
}<file_sep> var smartwin;//扫描窗体
var sid = '';
var strList='';//存储选中的资源列表
//资源选择树
var tree_source = new Ext.tree.TreePanel({
height: 480,
loadMask: true,
useArrows: true,
autoScroll: true,
animate: true,
enableDD: true,
animate: true,
loader:new Ext.tree.TreeLoader({
preloadChildren: true,
dataUrl: "../inside.php?t=json&m=role&f=getRoleSource",
uiProviders:{
'col': Ext.tree.TreeNodeUI
}
}),
root: new Ext.tree.AsyncTreeNode({
text: '系统资源->',
draggable: false,
allowChildren: true,
loaded :true,//防止点击出现重复加载资源树的bug by csj 2016/4/15
}),
});
//Story #22305 gsp 系统优化: 角色管理中目录树了节点父节点的响应 by lixiaoli
tree_source.on('checkchange', function(node, flag) {
//获取所有子节点
node.cascade( function( node ){
node.attributes.checked = flag;
node.ui.checkbox.checked = flag;
return true;
});
//获取所有父节点
var pNode = node.parentNode;
for (; pNode.parentNode != null; pNode = pNode.parentNode ) {
if(flag == true){//当选中子节点时父节点选中,取消子节点时父节点不变化
pNode.ui.checkbox.checked = flag;
pNode.attributes.checked = flag;
}
}
});
//主容器
var select_source_panel = new Ext.FormPanel({
region:"center",
bodyStyle:'padding: 10px',
border:false,
items:[
{xtype: 'compositefield',
items: [{xtype:'textfield',id:'role_name',name:'role_name',width:280,fieldLabel:'角色名称',style:'margin-bottom:10px'},
{xtype: 'displayfield',value: ' <font color=red>*</font>'}
]},
tree_source],
buttons:[{text: '确定',
handler : function(){
if (checkinput()){
var _form = this.ownerCt.ownerCt.getForm();
if (sid!=''){
_form.submit({url:'../inside.php?t=json&m=role&f=update',
success: Fn,
failure: Fn,
params: { id:sid,
role_name:Ext.getCmp("role_name").getValue(),
rolelist:getStrList()
},
waitMsg:'Saving Data...'});
}else{
_form.submit({url:'../inside.php?t=json&m=role&f=add',
success: Fn,
failure: Fn,
params: {
role_name:Ext.getCmp("role_name").getValue(),
rolelist:getStrList()
},
waitMsg:'Saving Data...'});
}
smartwin.hide();
}
}},{text: '关闭',
handler : function(){
smartwin.hide();
}
}]
});
//弹出窗体
if(!smartwin){//主窗体
smartwin = new Ext.Window({
layout:"border",
width:700,
height:600,
title:'角色维护',
closeAction:'hide',
plain: true,
items:[select_source_panel]
});
}
//初始化界面
function showAdd(id){
//Task #40327 gsp 权限方案整理 by lixiaoli
Ext.Ajax.request({
url:'../inside.php?t=json&m=user&f=checkAdmin',
method:'post',
params:{},
success: function sFn(response,options)
{
var res = Ext.decode(response.responseText).msg;
if(res == 0){
Ext.MessageBox.alert('提示', '该功能仅管理员可用!');
return false;
}else{
if (id){
sid = id;
}else{
sid = '';
}
if (sid==''){
Ext.getCmp("role_name").setValue('');
tree_source.getLoader().baseParams = {};
}
tree_source.getLoader().load(tree_source.getRootNode(),function(){tree_source.expandAll()});
//查该角色有权使用的资源
smartwin.show();
}
}
});
}
function Fn(e,form){
store_role.removeAll();
store_role.load();
tree_source.getLoader().load(tree_source.getRootNode(),function(){tree_source.expandAll()});
(Ext.getCmp('btnDel'))?Ext.getCmp('btnDel').disable():'';//删除
(Ext.getCmp('btnEdit'))?Ext.getCmp('btnEdit').disable():'';//编辑
sid ='';
Ext.MessageBox.alert('提示',Ext.decode(form.response.responseText).msg);
}
function editStrList(node){
node.eachChild(function(child){
if(child.attributes.checked){
strList = (!strList)?child.attributes.source_id:strList+','+child.attributes.source_id;
}
if(child.hasChildNodes()){
editStrList(child);
}
});
}
function getStrList(){
strList = '';
var rootNode = tree_source.getRootNode();
editStrList(rootNode);
return strList;
}
function checkinput(){
var ss ='';
if (Ext.getCmp("role_name").getValue()==''){ ss='角色名不能为空';}
//if (store_men_source.getCount()==0){ss+='尚未分配系统资源';}
if (ss==''){
return true;
}else{
Ext.MessageBox.alert('提示!',ss);
return false;
}
}<file_sep><?php
require_once 'lib/config.inc.php';
class Client {
protected $resultData;
/**
* API参数数组
*
* @var array
*/
private $paramArr = array(
'app_key' => APP_KEY,
'format' => 'json',
);
/**
* 设置参数
*
* @param string $name:参数名
* @param string $value:参数值
*/
public function setParameter($name, $value) {
$this->paramArr[$name] = $value;
}
/**
* 调用相应的api,返回结果
*
* @param string $name:方法名
* @param array $args
* @return result
*/
public function __call($name, $args) {
$this->updateParam($name, $args);
$this->resultData = Util::postResult($this->paramArr);
return $this->resultData;
}
/**
* 返回GET方式的完整URL
*/
public function getUri($name, $args, $apiurl=false) {
$this->updateParam($name, array($args));
return Util::getUri($this->paramArr, $apiurl);
}
private function updateParam($name, $args) {
//将方法名转为api接口名,例如将helloSay转化为huoyunren.hello.say
$method = '';
$length = strlen($name);
for($i = 0; $i < $length; $i++) {
$char = substr($name, $i, 1);
if (64 < Ord($char) && 91 > Ord($char) && stripos($method, '.') === false) {
$method .= '.' . strtolower($char);
} else {
$method .= $char;
}
}
$this->paramArr['method'] = $method = 'admin.' . $method;
$paramArr = array();
foreach ($args as $arg) {
foreach ($arg as $k => $v) {//第n个入参
$paramArr[$k] = $v;
}
}
$this->paramArr['data'] = urlencode(json_encode($paramArr));
$this->paramArr['timestamp'] = date('Y-m-d H:i:s');
}
}
?><file_sep>Ext.onReady(function(){
Ext.Ajax.request({
url : '../inside.php?t=json&m=login&f=getConfig',
method : 'POST',
success : function( resp,opts )
{
var data = Ext.util.JSON.decode(resp.responseText);
//如果没有登录,则跳转到登录页面
if(!data.id)
{
window.location.href = "../login/";
}
else
{
var main_panel = new Ext.Panel({
header:false,
region:"center",
layout:"border",
items:
[
top_panel,
grid_list
]
});
//渲染到模板
new Ext.Viewport(
{
enableTabScroll:true,
layout:"border",
items:
[
main_panel
]
}
);
editSource('extract',grid_list);
}
}
});
});<file_sep><?php
/**
* 用户管理
* @author liuzhi
* @since 2013/11/12
*/
class user extends baseControl
{
public function __construct()
{
parent::__construct();
$this->myAdmin = $this->app->myAdmin;
}
/**
* 获取客户列表信息
* @author liuzhi
* @since 2013/11/12
*/
public function search()
{
$params = helper::filterParams();
$where = "1";
$user_name = !empty($params['user_name']) ? trim($params['user_name']) : '';
$true_name = !empty($params['true_name']) ? trim($params['true_name']) : '';
$user_org = !empty($params['user_org']) ? $params['user_org'] : '';
$user_role = !empty($params['user_role']) ? trim($params['user_role']) : '';
//用户名 模糊搜索
if($user_name != '')
{
$where .= " AND a.user_name LIKE '%$user_name%'";
}
//姓名 模糊搜索
if($true_name != '')
{
$where .= " AND a.true_name LIKE '%$true_name%'";
}
//组织模糊搜索
if($user_org != '')
{
$where .= " AND b.org_code LIKE '%$user_org%'";
}
//角色模糊搜索
if($user_role != '')
{
$where .= " AND d.role_name LIKE '%$user_role%'";
}
// BOSSSM-391 by csj 2016/2/25
if(!empty($params['type']))
{
$where .= " AND a.type = {$params['type']}";
}
//默认搜索 未删除的数据
$where .= " AND a.is_del = 0";
//分页信息
$limit = array($params['start'],$params['limit']);
$desc = " a.createtime DESC";
$data = $this->user->search($where,$limit,$desc);
//输出结果
echo json_encode($data);
}
/**
* 用户添加
* @author liuzhi
* @since 2016-04-19
*/
public function add($params = array()){
$params = helper::filterParams();
$add = $this->user->add($params);
echo json_encode($add);
}
/**
* 用户管理锁定
* @author liuzhi
* @since 2013/11/12
*/
public function userLocked()
{
$result = false;
$params = helper::filterParams();
//$ids = $this->loadModel('common')->replaceIds($params['ids']);//过滤id 复选取消
$id = $params['ids'];
$result = $this->user->userLocked($id);
if($result)
{
$data = array('success'=>true, 'msg'=>'锁定成功');
}
else
{
$data = array('failure'=>true, 'msg'=>'锁定失败');
}
echo json_encode($data);
}
/**
* 用户管理锁定
* @author liuzhi
* @since 2013/11/19
*/
public function userUnLocked()
{
$result = false;
$params = helper::filterParams();
//$ids = $this->loadModel('common')->replaceIds($params['ids']);//过滤id 复选取消
$id = $params['ids'];
$result = $this->user->userUnLocked($id);
if($result)
{
$data = array('success'=>true, 'msg'=>'解锁成功');
}
else
{
$data = array('failure'=>true, 'msg'=>'解锁失败');
}
echo json_encode($data);
}
/**
* 修改密码
* @author liuzhi
* @since 2013/12/23
*/
public function updatePwd()
{
$params = helper::filterParams();
$oldPwd = $this->user->getUserInfo($params['user_id']);
//Story #20061 GSP使用ldap服务成功 by lixiaoli
$pwd = $this->loadModel('common')->getEncryptedPwd($params['old_pwd']);
$newPwd = $this->loadModel('common')->getEncryptedPwd($params['new_pwd']);
if($pwd != $oldPwd[0]->user_pwd)
{
$data = array('success'=>true, 'msg'=>1);//旧密码错误
echo json_encode($data);
return;
}
if($params['new_pwd'] != $params['again_new_pwd'])
{
$data = array('success'=>true, 'msg'=>2);//新密码跟确认密码不一致
echo json_encode($data);
return;
}
//修改密码
$result = $this->user->updatePwd($params['user_id'],$newPwd);
if($result)
{
$data = array('success'=>true, 'msg'=>3);//修改成功
echo json_encode($data);
}
else
{
$data = array('success'=>true, 'msg'=>4);//修改失败
echo json_encode($data);
}
}
/**
* 用户管理修改
* //Story #49819
* @author liuzhi
* @since 2013/11/12
*/
public function userUpdate()
{
try {
//开启事务
$this->dbh->beginTransaction();
/***************************
* START处理逻辑
***************************/
$params = helper::filterParams();
$user = $this->user->getUser(array(" a.id = '{$params['id']}' AND (a.updatetime = '{$params['updatetime']}' OR a.updatetime IS NULL) "));
if (empty($user)) {
throw new Exception('此用户已经被修改过,请刷新后重试', 1);
}
$addRes = $this->user->userUpdate($params);
if($addRes)
{
$output = array('success'=>true,'msg'=>'编辑成功');
}
else
{
$output = array('success'=>false,'msg'=>'编辑失败');
}
/***************************
* END处理逻辑
***************************/
//事务提交
$this->dbh->commit();
echo json_encode($output);
} catch (Exception $e) {
//事务回滚
$this->dbh->rollBack();
echo json_encode(array('success' => false, 'msg' => $e->getCode() == '1' ? $e->getMessage() : '更新失败', 'code' => $e->getCode()));
helper::datalog('用户更新结果: ' . var_export($e->getMessage(), true));
}
}
/**
* 用户管理添加
* @author liuzhi
* @since 2013/11/12
*/
public function userAdd()
{
$params = helper::filterParams();
$info = new stdClass();
//BOSSOPS-1164
$userCount = $this->user->checkUsername($params['id'], $params['user_name']);
if($userCount > 0){
$info->failure = true;
$info->msg = '用户名'.$params['user_name'].'已存在';
$info->type = 1;
echo json_encode($info);
die;
}
//BOSSOPS-1164
if($params['type'] == 3){
$count = $this->user->checkWorker($params['id'], $params['worker_no']);
if($count > 0){
$info->failure = true;
$info->msg = '工号'.$params['worker_no'].'已存在';
$info->type = 1;
echo json_encode($info);
die;
}
}
$addRes = $this->user->userAdd($params);
if($addRes)
{
$info->success = true;
$info->msg = '添加成功';
}
else
{
$info->failure = true;
$info->msg = '添加失败';
}
echo json_encode($info);
}
/**
* 获取角色信息
* @author liuzhi
* @since 2013/11/12
*/
public function getRole()
{
$data = $this->user->getRole();
echo json_encode($data);
}
/**
* 切换管理员操作
* @author lixiaoli
* @since 2015/05/22
*/
public function changeAdmin(){
$params = helper::filterParams();
// BOSSSM-391 by csj 2016/2/25
$store = $this->user->getUser(array(" a.id = '{$params['id']}' "));
if($store[0]->type == 2 && $params['is_admin'] == 0) {
//委外人员不能设置成管理员
$data = array('success'=>false, 'msg'=>'委外人员不能设置成管理员');
echo json_encode($data);
exit;
}
if($params['id'] && isset($params['is_admin'])){
if($params['is_admin'] == 1){
$is_admin = 0;
}else{
$is_admin = 1;
}
if($this->user->changeAdmin($params['id'], $is_admin))
{
$data = array('success'=>true, 'msg'=>'操作成功');
} else {
$data = array('success'=>false, 'msg'=>'操作失败');
}
}else{
$data = array('success'=>false, 'msg'=>'解锁失败');
}
echo json_encode($data);
}
/**
*检查是不是管理员
* @param $id
* @author lixiaoli
* @since 2015/05/22
* //Task #40327 gsp 权限方案整理 by lixiaoli
*/
public function checkAdmin(){
$result = array('success' => true, 'msg' => 0);//非管理员
$uid = $this->app->myAdmin->id;
if ($uid == '1') {//是超级管理员
$result = array('success' => true, 'msg' => 1);
} else {
$info = $this->loadModel('user')->getUserInfo($uid);
if (!empty($info) && $info[0]->is_admin == '1') {//是管理员
$result = array('success' => true, 'msg' => 2);
}
}
echo json_encode($result);
}
public function test(){
$this->user->test();
}
public function getUser(){
$output = array('success' => false, 'msg' => '取得用户信息失败');
$data = $this->user->getUserAndParent(
array('a.id' => $this->myAdmin->id),
' a.*, b.true_name parent, c.level_name, d.all_user_wages, d.user_wages, d.all_wages_status, d.wages_status '
);
if (!empty($data)) {
$data = $data[0];
$infoList = array();
$getList = array(
'level_name' => '级别', 'user_code' => '会员号', 'invite_code' => '邀请码', 'parent' => '推荐人', 'card' => '银行卡号', 'bank_name' => '开户银行', 'bank_card_no' => '银行卡号', 'reg_time' => '注册时间'
);//取得这些数据
foreach ($getList as $key => $val) {
if (isset($data->$key)) {
$infoList[] = array('code' => $key, 'name' => $val, 'value' => $data->$key);
}
}
$data->info_list = $infoList;
unset($data->user_pwd);
$output = array('success' => true, 'msg' => '取得用户信息成功', 'data' => $data);
}
echo json_encode($output);
}
}
?><file_sep><?php
/**
* The control class file of ZenTaoPHP.
*
* ZenTaoPHP is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* ZenTaoPHP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ZenTaoPHP. If not, see <http://www.gnu.org/licenses/>.
*
* @copyright Copyright 2009-2010 青岛易软天创网络科技有限公司(www.cnezsoft.com)
* @author <NAME> <<EMAIL>>
* @package ZenTaoPHP
* @version $Id: control.class.php 127 2010-07-04 02:18:40Z wwccss $
* @link http://www.zentaoms.com
*/
/**
* 控制器基类。
*
* @package ZenTaoPHP
*/
class control
{
/**
* 全局的$app对象。
*
* @var object
* @access protected
*/
protected $app;
public $smarty;
/**
* 全局的$config对象。
*
* @var object
* @access protected
*/
protected $config;
/**
* 全局的$lang对象。
*
* @var object
* @access protected
*/
protected $lang;
/**
* 全局的$dbh(数据库访问句柄)对象。
*
* @var object
* @access protected
*/
protected $dbh;
/**
* dao对象。
*
* @var object
* @access protected
*/
public $dao;
/**
* POST对象。
*
* @var ojbect
* @access public
*/
public $post;
/**
* get对象。
*
* @var ojbect
* @access public
*/
public $get;
/**
* session对象。
*
* @var ojbect
* @access public
*/
public $session;
/**
* server对象。
*
* @var ojbect
* @access public
*/
public $server;
/**
* cookie对象。
*
* @var ojbect
* @access public
*/
public $cookie;
/**
* global对象。
*
* @var ojbect
* @access public
*/
public $global;
/**
* 所属模块的名字。
*
* @var string
* @access protected
*/
public $moduleName;
/**
* 记录赋值到view的所有变量/模板引擎对象。
*
* @var object
* @access public
*/
public $view;
/**
* 视图类型
*
* @var string
* @access private
*/
private $viewType;
/**
* 要输出的内容。
*
* @var string
* @access private
*/
private $output;
/**
* 路径分隔符。
*
* @var string
* @access protected
*/
protected $pathFix;
/**
* 实例化的对象Model
*/
public $modelobj = array();
/**
* 构造函数:
*
* 1. 引用全局对象,使之可以通过成员变量访问。
* 2. 设置模块相应的路径信息,并加载对应的model文件。
* 3. 自动将$lang和$config赋值到模板。
*
* @access public
* @return void
*/
public function __construct($moduleName = '', $methodName = '')
{
/* 引用全局对象,并赋值。*/
global $app, $config, $lang, $dbh;
$this->app = $app;
$this->config = $config;
$this->lang = $lang;
$this->dbh = $dbh;
$this->pathFix = $this->app->getPathFix();
$this->viewType = $this->app->getViewType();
$this->setModuleName($moduleName);
$this->setMethodName($methodName);
/* 自动加载当前模块的model文件。*/
$this->loadModel();
/* 设置当前模块的配置、语言等信息,并加载相应的文件 */
$this->app->loadLang($this->moduleName, $exit = false);
$this->app->loadConfig($this->moduleName, $exit = false);
/* 使用模板引擎,创建对象 */
if ($this->viewType == 'blz') {
$this->view = new View();
$this->view->moduleName = $this->moduleName;
} else {
$this->view = new stdClass();
/* 自动将$app、$config、$theme和$lang赋值到模板中。*/
$this->assign('app', $app);
$this->assign('lang', $lang);
$this->assign('config', $config);
if(isset($config->super2OBJ) and $config->super2OBJ) $this->setSuperVars();
}
// $this->assign('theme', $app->getClientTheme());
}
//-------------------- model相关的方法。--------------------//
//
/* 设置模块名。*/
private function setModuleName($moduleName = '')
{
$this->moduleName = $moduleName ? strtolower($moduleName) : $this->app->getModuleName();
}
/* 设置方法名。*/
private function setMethodName($methodName = '')
{
$this->methodName = $methodName ? strtolower($methodName) : $this->app->getMethodName();
}
/**
* 加载某一个模块的model文件。
* 防止model中重复实例出现冲突bug 同时fixed bug#2976 @2013-08-27
* @param string $moduleName 模块名字,如果为空,则取当前的模块名作为model名。
* @access public
* @return void
*/
public function loadModel($moduleName = '') {
/* 如果没有指定module名,则取当前加载的模块的名作为model名。*/
if(empty($moduleName)) $moduleName = $this->moduleName;
if(isset($this->modelobj[$moduleName]) && $this->modelobj[$moduleName]){
return $this->modelobj[$moduleName];
}
$classNameExt = $this->app->getModuleExt() . $moduleName. 'model';
$modelClass = class_exists($classNameExt) ? $classNameExt : $moduleName . 'model';
if(!class_exists($modelClass)) $this->app->error(" The model $modelClass not found", __FILE__, __LINE__, $exit = true);
$this->modelobj[$moduleName] = $this->$moduleName = new $modelClass();
return $this->$moduleName;
}
/**
* 设置超全局变量。
*
* @access protected
* @return void
*/
protected function setSuperVars()
{
$this->post = $this->app->post;
$this->get = $this->app->get;
$this->server = $this->app->server;
$this->session = $this->app->session;
$this->cookie = $this->app->cookie;
$this->global = $this->app->global;
}
//-------------------- 加载view相关的方法。--------------------//
/**
* 设置视图文件。
*
* 某一个module的控制器可以加载另外一个module的视图文件。
*
* @param string $moduleName 模块名。
* @param string $methodName 方法名。
* @access private
* @return string 对应的视图文件。
*/
private function setViewFile($moduleName, $methodName)
{
$moduleName = strtolower(trim($moduleName));
$methodName = strtolower(trim($methodName));
$modulePath = $this->app->getModulePath($moduleName);
$viewExtPath = $this->app->getModuleExtPath($moduleName, 'view');
/* 主视图文件,扩展视图文件和扩展钩子文件。*/
$mainViewFile = $modulePath . 'view' . $this->pathFix . $methodName . '.' . $this->viewType . '.php';
$extViewFile = $viewExtPath . $methodName . ".{$this->viewType}.php";
$extHookFile = $viewExtPath . $methodName . ".{$this->viewType}.hook.php";
$viewFile = file_exists($extViewFile) ? $extViewFile : $mainViewFile;
if(!file_exists($viewFile)) $this->app->error("the view file $viewFile not found", __FILE__, __LINE__, $exit = true);
if(file_exists($extHookFile)) return array('viewFile' => $viewFile, 'hookFile' => $extHookFile);
return $viewFile;
}
/**
* 设置HTML2视图文件。
*
* 某一个module的控制器可以加载另外一个module的视图文件。
*
* @param string $moduleName 模块名。
* @param string $methodName 方法名。
* @access private
* @return string 对应的视图文件。
*/
private function setViewFileHTML2($moduleName, $methodName)
{
$moduleName = strtolower(trim($moduleName));
$methodName = strtolower(trim($methodName));
$appRoot = $this->app->getappRoot();
$modulePath = $this->app->getModulePath($moduleName);
$viewExtPath = $this->app->getModuleExtPath($moduleName, 'view');
/* 主视图文件,扩展视图文件和扩展钩子文件。*/
$mainViewFile = $appRoot . 'www'.DIRECTORY_SEPARATOR.'view'.DIRECTORY_SEPARATOR. $moduleName.DIRECTORY_SEPARATOR.$methodName. '.html.php';
$extViewFile = $viewExtPath . $methodName . ".{$this->viewType}.php";
$extHookFile = $viewExtPath . $methodName . ".{$this->viewType}.hook.php";
$headerViewFile = $appRoot . 'www'.DIRECTORY_SEPARATOR.'view'.DIRECTORY_SEPARATOR.'header.html.php';
$footerViewFile = $appRoot . 'www'.DIRECTORY_SEPARATOR.'view'.DIRECTORY_SEPARATOR.'footer.html.php';
$viewFile = file_exists($extViewFile) ? $extViewFile : $mainViewFile;
if(!file_exists($viewFile)) $this->app->error("the view file $viewFile not found", __FILE__, __LINE__, $exit = true);
if(file_exists($extHookFile)) return array('viewFile' => $viewFile, 'hookFile' => $extHookFile);
if($moduleName == 'login' && $methodName == 'index'){
return array('viewFile' => $viewFile);
}else{
return array('headerFile'=>$headerViewFile,'viewFile' => $viewFile,'footerFile'=>$footerViewFile);
}
}
/**
* 赋值一个变量到view视图。
*
* @param string $name 赋值到视图文件中的变量名。
* @param mixed $value 所对应的值。
* @access public
* @return void
*/
public function assign($name, $value)
{
if ($this->viewType == 'blz')
$this->view->setObjects(array($name => $value));
else
$this->view->$name = $value;
}
/**
* 重置output内容。
*
* @access public
* @return void
*/
public function clear()
{
$this->output = '';
}
/**
* 解析视图文件。
*
* 如果没有指定模块名和方法名,则取当前模块的当前方法。
*
* @param string $moduleName 模块名。
* @param string $methodName 方法名。
* @access public
* @return void
*/
public function parse($moduleName = '', $methodName = '')
{
if(empty($moduleName)) $moduleName = $this->moduleName;
if(empty($methodName)) $methodName = $this->methodName;
if($this->viewType == 'json') {
$this->parseJSON($moduleName, $methodName);
} elseif ($this->viewType == 'jsonc') {
$this->parseJSON($moduleName, $methodName,false);
} elseif ($this->viewType == 'jsonh') {
$this->parseJSONH($moduleName, $methodName);
} elseif ($this->viewType == 'blz') {
$this->parseBlitz($moduleName, $methodName);
} elseif ($this->viewType == 'soap') {
$this->parseSOAP($moduleName, $methodName);
}elseif($this->viewType == 'html2'){
$this->parseHTML2($moduleName, $methodName);
}else {
$this->parseDefault($moduleName, $methodName);
}
return $this->output;
}
private function parseSOAP($moduleName, $methodName) {
unset($this->view->app);
unset($this->view->config);
unset($this->view->lang);
unset($this->view->pager);
unset($this->view->header);
unset($this->view->position);
unset($this->view->moduleTree);
$ps = get_object_vars($this->view);
if (count($ps) == 1)
$this->soapdata = array_pop($ps);
else
$this->soapdata = $this->view;
}
/* 解析JSON格式的输出。*/
private function parseJSON($moduleName, $methodName,$flag=TRUE) {
// header("Content-Type: application/json");
unset($this->view->app);
unset($this->view->config);
unset($this->view->lang);
unset($this->view->pager);
unset($this->view->header);
unset($this->view->position);
unset($this->view->moduleTree);
// unset($this->view->theme);
$output['code'] = is_object($this->view) ? 0 : 2;
$ps = get_object_vars($this->view);
if (count($ps) == 1)
$output['data'] = array_pop($ps);
else
$output['data'] = $this->view;
// $output['md5'] = md5(json_encode($this->view));
unset($ps, $this->view);
if(TRUE===$flag) {
$this->output = @json_encode($output);
}else {
$this->output = helper::customJsonEncode($output);
}
}
/* 解析JSONH格式的输出。*/
private function parseJSONH($moduleName, $methodName) {
header("Content-Type: application/json");
unset($this->view->app);
unset($this->view->config);
unset($this->view->lang);
unset($this->view->pager);
unset($this->view->header);
unset($this->view->position);
unset($this->view->moduleTree);
$output['code'] = is_object($this->view) ? 0 : 2;
$ps = get_object_vars($this->view);
if (count($ps) == 1) {
$data = array_pop($ps);
if (is_array($data) && count($data) > 0 && (is_array($data[0]) || is_object($data[0]))) {
// 用jsonh压缩数组
include_once $this->app->getCoreLibRoot() . 'JSONH.class.php';
$output['jsonh'] = 1;
$data = JSONH::pack($data);
} elseif ($data instanceof Page) {
// 用jsonh压缩数组
include_once $this->app->getCoreLibRoot() . 'JSONH.class.php';
$data->jsonh = 1;
$data->result = JSONH::pack($data->result);
}
$output['data'] = $data;
} else
$output['data'] = $this->view;
unset($ps, $this->view);
$this->output = json_encode($output);
}
/* Blitz template的输出。*/
private function parseBlitz($moduleName, $methodName)
{
/* 设置视图文件。*/
$viewFile = $this->setViewFile($moduleName, $methodName);
if(is_array($viewFile)) extract($viewFile);
/* 切换到视图文件所在的目录,以保证视图文件中的包含路径有效。*/
$currentPWD = getcwd();
chdir(dirname($viewFile));
$this->view->load('{{ include("'.basename($viewFile).'") }}');
$this->output .= $this->view->parse();
//
// if(isset($hookFile)) {
// ob_start();
// include $hookFile;
// $this->output .= ob_get_contents();
// ob_end_clean();
// }
/* 最后还要切换到原来的目录。*/
chdir($currentPWD);
}
/* 默认的输出。*/
private function parseDefault($moduleName, $methodName)
{
/* 设置视图文件。*/
$viewFile = $this->setViewFile($moduleName, $methodName);
if(is_array($viewFile)) extract($viewFile);
/* 切换到视图文件所在的目录,以保证视图文件中的包含路径有效。*/
$currentPWD = getcwd();
chdir(dirname($viewFile));
extract((array)$this->view);
ob_start();
include $viewFile;
// if(isset($hookFile)) include $hookFile;
$this->output .= ob_get_contents();
ob_end_clean();
/* 最后还要切换到原来的目录。*/
chdir($currentPWD);
}
/* HTML2的输出。*/
private function parseHTML2($moduleName, $methodName)
{
/* 设置视图文件。*/
$viewFile = $this->setViewFileHTML2($moduleName, $methodName);
if(is_array($viewFile)) extract($viewFile);
/* 切换到视图文件所在的目录,以保证视图文件中的包含路径有效。*/
$currentPWD = getcwd();
chdir(dirname($viewFile));
extract((array)$this->view);
ob_start();
if(isset($headerFile)) include $headerFile;
include $viewFile;
if(isset($footerFile)) include $footerFile;
// if(isset($hookFile)) include $hookFile;
$this->output .= ob_get_contents();
ob_end_clean();
/* 最后还要切换到原来的目录。*/
chdir($currentPWD);
}
/**
* 获取某一个模块的某一个方法的内容。
*
* 如果没有指定模块名,则取当前模块当前方法的视图。如果指定了模块和方法,则调用对应的模块方法的视图内容。
*
* @param string $moduleName 模块名。
* @param string $methodName 方法名。
* @param array $params 方法参数。
* @access public
* @return string
*/
public function fetch($moduleName = '', $methodName = '', $params = array())
{
if($moduleName == '') $moduleName = $this->moduleName;
if($methodName == '') $methodName = $this->methodName;
if($moduleName == $this->moduleName and $methodName == $this->methodName)
{
$this->parse($moduleName, $methodName);
return $this->output;
}
/* 设置被调用的模块的路径及相应的文件。*/
$modulePath = $this->app->getModulePath($moduleName);
$moduleControlFile = $modulePath . 'control.php';
$actionExtFile = $this->app->getModuleExtPath($moduleName, 'control') . strtolower($methodName) . '.php';
$file2Included = file_exists($actionExtFile) ? $actionExtFile : $moduleControlFile;
/* 加载控制文件。*/
if(!file_exists($file2Included)) $this->app->error("The control file $file2Included not found", __FILE__, __LINE__, $exit = true);
$currentPWD = getcwd();
chdir(dirname($file2Included));
if($moduleName != $this->moduleName) helper::import($file2Included);
/* 设置要调用的类的名称。*/
$className = class_exists("ext$moduleName") ? "ext$moduleName" : $moduleName;
if(!class_exists($className)) $this->app->error(" The class $className not found", __FILE__, __LINE__, $exit = true);
/* 处理参数,生成对象。*/
if(!is_array($params)) parse_str($params, $params);
$module = new $className($moduleName, $methodName);
/* 调用方法,获得输出。*/
if($params['return'])
$output = call_user_func_array(array($module, $methodName), $params);
else
{
ob_start();
$output = call_user_func_array(array($module, $methodName), $params);
$output = ob_get_contents();
ob_end_clean();
}
unset($module);
chdir($currentPWD);
return $output;
}
/**
* 显示视图内容。
*
* @param string $moduleName 模块名。
* @param string $methodName 方法名。
* @access public
* @return void
*/
public function display($moduleName = '', $methodName = '')
{
if(empty($this->output))
$this->parse($moduleName, $methodName);
if(!empty($this->output))
echo $this->output;
//if($this->viewType == 'json') die();
}
/**
* 直接输出文本数据
* @param <type> $content 传入数组/对象,则序列化成JSON输出
*/
public function render($content) {
if (is_array($content) || is_object($content))
echo json_encode($content);
else
echo $content;
//die();
}
/**
* 生成某一个模块某个方法的链接。
*
* @param string $moduleName 模块名。
* @param string $methodName 方法名。
* @param mixed $vars 要传递的参数,可以是数组,array('var1'=>'value1')。也可以是var1=value1&var2=value2的形式。
* @param string $viewType 视图格式。
* @access public
* @return string
*/
public function createLink($moduleName = null, $methodName = 'index', $vars = array(), $viewType = '')
{
if(empty($moduleName)) $moduleName = $this->moduleName;
return helper::createLink($moduleName, $methodName, $vars, $viewType);
}
/**
* 生成对本模块某个方法的链接。
*
* @param string $methodName 方法名。
* @param mixed $vars 要传递的参数,可以是数组,array('var1'=>'value1')。也可以是var1=value1&var2=value2的形式。
* @param string $viewType 视图格式。
* @access public
* @return string
*/
public function inlink($methodName = 'index', $vars = array(), $viewType = '')
{
return helper::createLink($this->moduleName, $methodName, $vars, $viewType);
}
/**
* 跳转到另外一个页面。
*
* @param string $url 要跳转的url地址。
* @access public
* @return void
*/
public function locate($url)
{
header("location: $url");
exit;
}
}
<file_sep><?php
/**
* 登录控制模块
* @author liyonghua
* @
*/
class loginModel extends model
{
public function __construct() {
parent::__construct();
}
/**
* 设置用户基本信息,权限信息,角色信息
* @param Int $userId 用户ID
* @author liuzhi
* @since 2013/11/7
*/
public function setUserinfo($userId)
{
$temp=new stdClass();
if(!empty($userId))
{
$userInfo = $this->loadModel('user')->getUserInfo($userId);
if(!empty($userInfo)){
$temp->id = $userInfo[0]->id;
$temp->user_code = $userInfo[0]->user_code;
$temp->user_name = $userInfo[0]->user_name;
$temp->true_name = $userInfo[0]->true_name;
$temp->user_pwd = $userInfo[0]->user_pwd;
$temp->status = $userInfo[0]->status;
$temp->is_del = $userInfo[0]->is_del;
$temp->type = $userInfo[0]->type;
}
//用户的所有资源
$result = $this->loadModel('common')->getsysconfig($userId);
//用户的所有控件
$control = $this->loadModel('common')->getsysconfig($userId,'2');
//所有资源
$resultAll = $this->loadModel('common')->getsysconfig('1');
//所有控件
$controlAll = $this->loadModel('common')->getsysconfig('1','2');
if(!empty($result))
{
foreach($result as $val)
{
$_control = array();
foreach($control as $cv){
$parent_code = substr($cv->source_code,0,strlen($cv->source_code)-3);
if($val->source_code == $parent_code){
$_control[] = $cv;
}
}
$source = new stdClass();
$source->source_id = $val->source_id;
$source->role_id = $val->role_id;
$source->role_name = $val->role_name;
$source->source_code = $val->source_code;
$source->source_name = $val->source_name;
$source->url = $val->url;
$source->type = $val->type;
$source->status = $val->status;//Story #21651
$source->is_display = $val->is_display;//Story #21651
$source->control = $_control;
$temp->source[] = $source;
}
//储存所有资源
if(!empty($resultAll))
{
foreach($resultAll as $val)
{
$_controlAll = array();
foreach($controlAll as $cv){
$parent_code = substr($cv->source_code,0,strlen($cv->source_code)-3);
if($val->source_code == $parent_code){
$_controlAll[] = $cv;
}
}
$sourceAll = new stdClass();
$sourceAll->source_id = $val->source_id;
$sourceAll->role_id = $val->role_id;
$sourceAll->role_name = $val->role_name;
$sourceAll->source_code = $val->source_code;
$sourceAll->source_name = $val->source_name;
$sourceAll->url = $val->url;
$sourceAll->type = $val->type;
$sourceAll->status = $val->status;//Story #21651
$sourceAll->is_display = $val->is_display;//Story #21651
$sourceAll->control = $_controlAll;
$temp->sourceAll[] = $sourceAll;
}
}
}
return $temp;
}
else
{
return false;
}
}
/**
* 获取用户信息
* @param String $userName 用户名称
* @author liuzhi
* @since 2013/11/7
*/
public function getUserInfo($userName)
{
if(!empty($userName))
{
$sql = " SELECT %s FROM ecsa_sys_users ";
$where = " user_name = '$userName'";
$fields = " * ";
$result = parent::findBySql($sql,$where,null,null,$fields);
return $result[0];
}
else
{
return false;
}
}
/**
* 对数据进行过滤
* @param $data
* @author liuzhi
* @since 2013/11/7
*/
public function checkData($data)
{
if(!empty($data))
{
if(!get_magic_quotes_gpc())
{
if(is_array($data))
{
foreach($data as $key => $val)
{
$data[$key] = checkData($val);
}
}
else
{
$data = addslashes($data);
}
}
}
return $data;
}
/**
* 获取notice信息
* @author liuzhi
* @since 2013/11/7
*/
public function getNotice()
{
$sql = "SELECT %s FROM ecsa_sys_notice";
$fields = " id,title ";
$where = " is_del = 0 ORDER BY id DESC LIMIT 5";
$data = parent::findBySql($sql,$where,null,null,$fields);
$result = new stdClass();
$result->data = $data;
return $result;
}
/**
* 用户退出
* @author liuzhi
* @since 2013/11/12
*/
public function logout()
{
global $config;
//销毁登录临时COOKIE
setcookie($config->cookiepre, '', -1);
}
/**
* 用户登陆成功,记录日志
* @param array $data 添加信息
* @param string $table 表名
* @author liuzhi
* @since 2013/11/7
*/
public function loginLog($data,$table)
{
if(!empty($data) && !empty($table))
{
return parent::insert($data, $table);
}
else
{
return false;
}
}
/**
* 用户登陆成功,记录最后登陆时间
* @param Int $id 用户ID
* @author liuzhi
* @since 2013//1/7
*/
public function loginLastTime($id)
{
$sql = "UPDATE ecsa_sys_users SET last_login_time = '".date('Y-m-d H:i:s',time())."' WHERE id = $id";
parent::exec($sql);
}
}
<file_sep><?php
$time_start = getmicrotime();
function getmicrotime() {
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
}
/**
* 调用演示
* 此服务的api接口名为huoyunren.hello.say,那么用client对象访问的方法名为helloSay
*/
header("Content-Type:text/html;charset=UTF-8");
require_once 'Client.php';
//实例化一个client对象
$client = new Client();
//设置api参数
//$client->setParameter('name', 'harry');
//$client->setParameter('age', '12');
//访问服务
//$result = $client->helloSay(array('name' => 'harry', 'age' => '11', 'date' => '2010-03-28'));
//$result = $client->dailyGet(array('imei' => '353419031323376', 'time' => '2010-06-05'));
//if ($result) {
// $obj = json_decode($result);
// print_r($obj);
//}
// 生成URI
//echo $client->getUri("hello.say", array('name' => 'harry', 'age' => '11', 'date' => '2010-03-28'), 'http://api.huoyunren.com/router/rest');
echo $client->getUri("gps.follow", array('gpsno' => '10010005', 'title' => '京A12345' ), 'http://ips.huoyunren.com/api/router.php');
$time_end = getmicrotime();
printf ("[页面执行时间: %.2f毫秒]\n\n",($time_end - $time_start)*1000);
?><file_sep>var top_panel = new Ext.form.FormPanel({
region : 'north',
hideLabels : true,
bodyStyle : 'padding: 10px',
height : 50,
items :
[
{
xtype : 'compositefield',
items :
[
{
xtype: 'displayfield',
value: '用户名:'
},
{
xtype : 'textfield',
id : 'user_name',
width : 150
},
{
xtype: 'displayfield',
value: '姓名:',
style : 'padding-left : 10px;'
},
{
xtype : 'textfield',
id : 'true_name',
width : 150,
},
{
xtype: 'displayfield',
value: '角色:',
style : 'padding-left : 10px;'
},
{
xtype : 'textfield',
id : 'user_role',
width : 150,
},
{
xtype: 'datefield',
format: 'Y-m-d'
},
{
xtype: 'displayfield',
value: '用户类型:',
style : 'padding-left : 10px;'
},
new Ext.form.ComboBox({
id: 'search_type',
name:'search_type',
hiddenName:'search_type',
width: 150,
mode: 'local',
triggerAction: 'all',
forceSelection: true,
editable: false,
displayField: 'name',
valueField: 'value',
store: new Ext.data.SimpleStore({
fields: ['name', 'value'],
data: [['会员', '1'], ['员工', '2']]
}),
}),
{
xtype:'button',
text:'查询',
style : 'padding-left : 10px;',
handler: function()
{
userStore.removeAll();//移除原来的数据
userStore.load();//加载新搜索的数据
}
},
]
}
]
});<file_sep>$(function(){
$.ajax({
type: "post",
url: "../inside.php?t=json&m=login&f=getConfig",
async: true,
success: function(result){
var r = jQuery.parseJSON(result);
if (r.id) {
} else {
window.location.href = '/login/';
}
}
});
$('#user-info').click(function(){
if (parent) {
parent.location.href = '/user_info/';
}
window.location.href = '/user_info/';
});
$('#log-out').click(function(){
$.ajax({
type: "post",
url: "../inside.php?t=json&m=login&f=logout",
async: true,
success: function(a, b, c){
if (parent) {
parent.location.href = '/index.html';
}
window.location.href = '/index.html';
}
});
});
$('#user-edit').click(function(){
if (parent) {
parent.location.href = '/user_info/edit.html';
}
window.location.href = '/user_info/edit.html';
});
});<file_sep><?php
/**
* 用户管理
* @author liuzhi
* @since 2013/11/12
*/
class userModel extends model {
public $max;
//存储用户最大数
public $child = array();
//存储用户下面的人
public function __construct() {
parent::__construct();
//去掉旧表 guojuan
$this->myAdmin = $this->app->myAdmin;
}
/**
* 获取用户管理列表信息
* @param String $where 搜索条件 默认搜索全部
* @param Array $limit 分页数组 默认分页20条
* @param String $desc 按创建时间倒序
* @author liuzhi
* @since 2013/11/12
*/
public function search($where, $limit, $desc) {
$sql = "SELECT %s FROM ecsa_sys_users as a
LEFT JOIN ecsa_sys_user_roles as c ON a.id = c.user_id
LEFT JOIN ecsa_sys_roles as d ON c.role_id = d.id
LEFT JOIN ecsa_sys_users_level e ON e.level_id = a.level";
$fields = " a.id, a.user_name, a.true_name, a.user_code, a.createtime, a.updatetime, a.last_login_time, a.status, a.user_email, a.remark, a.user_mobile, a.is_admin,
d.id as role_id, d.id as role_id, d.role_name, a.type, e.level_name, a.child_num, a.all_child_num ";
//取记录总数
$total = parent::findBySql($sql, $where, $desc, null, 'count(a.id) as count');
//取记录集
if ($total[0]->count > 0) {
$datas = parent::findBySql($sql, $where, $desc, $limit, $fields);
}
$result = new stdClass();
$result->total = $total[0]->count;
$result->data = $datas;
return $result;
}
/**
* 用户管理修改
* @param Array $data 修改信息
* @author liuzhi
* @since 2013/11/12
*/
public function userUpdate($data = array()) {
$falg = false;
$this->myAdmin = $this->app->myAdmin;
$sql_select = "UPDATE ecsa_sys_users as a LEFT JOIN ecsa_sys_user_roles as b ON a.id = b.user_id
SET a.user_name = '" . $data['user_name'] . "',a.true_name = '" . $data['true_name'] . "',a.user_mobile = '" . $data['mobile'] . "',
a.user_email = '" . $data['user_email'] . "',a.remark = '" . $data['remark'] . "',a.last_operator = '" . $this->myAdmin->true_name . "',b.role_id= '" . $data['role'] . "'
WHERE a.id = " . $data['id'] . "";
if ($data['role_id_hidde'] != '') {
return parent::exec($sql_select);
} else {
$sql_insert = "INSERT INTO ecsa_sys_user_roles (user_id,role_id,creator_id,createtime) VALUES( " . $data['id'] . ",'" . $data['role'] . "','" . $this->myAdmin->id . "','" . helper::nowTime() . "')";
if (parent::exec($sql_insert)) {
$falg = true;
}
if (parent::exec($sql_select)) {
$falg = true;
}
}
return falg;
}
/**
* 用户管理添加
* 先添加用户表信息,成功之后返回用户ID,在添加ecsa_sys_user_roles表信息
* @param array $params 添加信息
* @author liuzhi
* @since 2013/11/12
*/
public function userAdd($params) {
if (!empty($params)) {
$this->myAdmin = $this->app->myAdmin;
$uid = 0;
//Story #20061 GSP使用ldap服务成功 by lixiaoli
$new_pwd = $this->loadModel('common')->getEncryptedPwd($params['new_pass']);
//BOSSOPS-1164
if ($params['type'] == 3) {
$true_name = $params['u_worker_no'];
} else {
$true_name = $params['true_name'];
}
if (!empty($params['new_pass']) && !empty($params['old_pass'])) {
$data = array('user_name' => $params['user_name'], 'true_name' => $true_name, //BOSSOPS-1164
'user_email' => $params['user_email'], 'user_mobile' => $params['mobile'], 'remark' => $params['remark'], 'user_pwd' => $<PASSWORD>, 'status' => 1, 'is_del' => 0, 'type' => $params['type'], // BOSSSM-391 by csj 2016/2/25
'creator_id' => $this->myAdmin->id, 'last_operator' => $this->myAdmin->true_name, 'createtime' => date('Y-m-d H:i:s', time()));
} else {
$data = array('user_name' => $params['user_name'], 'org_id' => $params['org'], 'true_name' => $true_name, //BOSSOPS-1164
'user_email' => $params['user_email'], 'user_mobile' => $params['mobile'], 'remark' => $params['remark'], 'status' => 1, 'is_del' => 0, 'type' => $params['type'], // BOSSSM-391 by csj 2016/2/25
'creator_id' => $this->myAdmin->id, 'last_operator' => $this->myAdmin->true_name, 'createtime' => date('Y-m-d H:i:s', time()));
}
$uid = parent::insert($data, 'ecsa_sys_users');
//添加成功,返回用户的ID
if ($uid) {
$role_data = array('user_id' => $uid, 'role_id' => $params['role'], 'status' => 1, 'is_del' => 0, 'creator_id' => $this->myAdmin->id, 'createtime' => date('Y-m-d H:i:s', time()));
return parent::insert($role_data, 'ecsa_sys_user_roles');
}
}
}
/**
* 用户锁定
* @param String $ids 用户ID
* @author liuzhi
* @since 2013/11/12
*/
public function userLocked($ids) {
if (!empty($ids)) {
$sql = "UPDATE ecsa_sys_users SET status = 0 WHERE id IN ($ids)";
return parent::exec($sql);
}
}
/**
* 用户解锁
* @param String $ids 用户ID
* @author liuzhi
* @since 2013/11/19
*/
public function userUnLocked($ids) {
if (!empty($ids)) {
$sql = "UPDATE ecsa_sys_users SET status = 1 WHERE id IN ($ids)";
return parent::exec($sql);
}
}
/**
* 获取角色信息
* @author liuzhi
* @since 2013/11/12
*/
public function getRole() {
$sql = "SELECT %s FROM ecsa_sys_roles";
$fields = " id,role_name,id as role_id ";
$where = " is_del = 0";
$data = parent::findBySql($sql, $where, 'id DESC', null, $fields);
$result = new stdClass();
$result->data = $data;
return $result;
}
/**
* 获取用户的密码,跟用户信息
* @param Int $userId 用户ID
* @author liuzhi
* @since 2013/12/23
*/
public function getUserInfo($userId = '') {
if (!empty($userId)) {
$sql = "SELECT %s FROM ecsa_sys_users";
$fields = " * ";
$where = " id = $userId";
$data = parent::findBySql($sql, $where, null, null, $fields);
return $data;
} else {
return false;
}
}
/**
* 密码修改
* @param Int $userId 用户ID
* @param String $newPwd <PASSWORD>
* @author liuzhi
* @since 2013/12/23
*/
public function updatePwd($userId, $newPwd) {
$sql = "UPDATE ecsa_sys_users SET user_pwd = '$newPwd' WHERE id = $userId";
return parent::exec($sql);
}
/**
* 得到登陆用户的信息
* //BOSSOPS-1147
* @author liuzhi
* @since 2016/04/08
*/
public function getCurrUserInfo($fields = '') {
$uid = $this->myAdmin->id;
$fields = $fields ? $fields : 'a.id, a.worker_no, a.type';
$where = " a.id = '{$uid}' ";
$sql = "SELECT %s FROM ecsa_sys_users a
LEFT JOIN ecsa_sys_orgs b ON b.id = a.org_id ";
$info = parent::findBySql($sql, $where, null, null, $fields);
helper::datalog('得到登陆用户的信息: ' . var_export($info, true));
return $info[0];
}
/**
* 判断登陆用户是否为工程师
* //BOSSOPS-1147
* @author liuzhi
* @since 2016/04/08
*/
public function checkCurrUserIsWorker() {
$isWorker = false;
$info = $this->getCurrUserInfo();
if ($info) {
if ($info->type == '3') {
$sql = " SELECT a.worker_no, a.is_supervisor, GROUP_CONCAT(b.worker_no) worker_nos FROM ecsa_jobs_workers a
LEFT JOIN ecsa_jobs_workers b ON b.supervisor_parent_id = a.worker_no WHERE a.worker_no = '{$info->worker_no}'";
$stmt = $this->query($sql);
$record = $stmt->fetchAll();
$info->worker_no = $record[0]->worker_no;
//工程师主管号
$info->is_supervisor = $record[0]->is_supervisor;
//是否工程师主管
$info->worker_nos = $record[0]->worker_nos;
//所有非主管的工程师号
$isWorker = $info;
helper::datalog('判断登陆用户是否为工程师: ' . var_export($isWorker, true));
}
}
return $isWorker;
}
/**
* 切换用户管理员状态
* @param $id
* @param $is_admin
* @return bool
* @author lixiaoli
* @since 2015/05/22
*/
//Task #40327 gsp 权限方案整理 by lixiaoli
public function changeAdmin($id, $is_admin) {
if (isset($is_admin) && $id) {
$sql = "UPDATE ecsa_sys_users SET is_admin = $is_admin WHERE id = $id";
return parent::exec($sql);
} else {
return false;
}
}
/**
* 调用父类的update
* //Story #35124
* @author liuzhi
* @date 20150526
*/
public function update($where, $setarr, $tb = '') {
return parent::update($setarr, $where, $tb);
}
/**
* 按条件检索单据信息
* //Story #49819
* @author liuzhi
* @since 2015/10/14
*/
public function getUser($where, $fields = '') {
$sql = 'SELECT %s FROM ecsa_sys_users a ';
!$fields ? $fields = " a.id, a.true_name, a.type" : '';
$data = parent::findBySql($sql, $where, null, null, $fields);
return $data;
}
/**
* 按条件检索单据信息
* //Story #49819
* @author liuzhi
* @since 2015/10/14
*/
public function getUserAndParent($where, $fields = '') {
$sql = 'SELECT %s FROM ecsa_sys_users a
LEFT JOIN ecsa_sys_users b ON b.user_code = a.invite_code
LEFT JOIN ecsa_sys_users_level c ON c.level_id = a.level
LEFT JOIN ecsa_user_wages d ON d.user_id = a.id ';
!$fields ? $fields = " a.id, a.true_name, a.type" : '';
$data = parent::findBySql($sql, $where, null, null, $fields);
return $data;
}
/**
* 获取工程师列表,只展示工程师主管(团队主管和个人)
* @return ArrayIterator
* @author lixiaoli
* @since 2016/03/21
* BOSSOPS-1164
*/
public function getWorkerList() {
$sql = " SELECT worker_no, CONCAT(worker_no,' - ',true_name) worker_name FROM ecsa_jobs_workers WHERE is_supervisor = 1 AND is_del = 0 ";
return parent::queryBySql($sql);
}
/**
* 检测工程师是否已添加过了
* @param $worker_no 工单号
* @return mixed
* @author lixiaoli
* @since 2016/03/21
* BOSSOPS-1164
*/
public function checkWorker($id = '', $worker_no) {
if (!empty($id)) {
$sql = "SELECT count(*) count FROM ecsa_sys_users WHERE is_del = 0 AND worker_no = '$worker_no' AND id != '$id'";
} else {
$sql = "SELECT count(*) count FROM ecsa_sys_users WHERE is_del = 0 AND worker_no = '$worker_no'";
}
$data = parent::queryBySql($sql);
return $data[0]->count;
}
/**
* 检测用户名是否已存在
* @param string $id
* @param $username
* @return mixed
* @author lixiaoli
* @since 2016/03/21
* BOSSOPS-1164
*/
public function checkUsername($id = '', $username) {
if (!empty($id)) {
$sql = "SELECT count(*) count FROM ecsa_sys_users WHERE is_del = 0 AND user_name = '$username' AND id != '$id'";
} else {
$sql = "SELECT count(*) count FROM ecsa_sys_users WHERE is_del = 0 AND user_name = '$username'";
}
$data = parent::queryBySql($sql);
return $data[0]->count;
}
/**
* 用户添加
* @author liuzhi
* @since 2016-04-19
*/
public function add($params) {
$output = array('success' => false, 'msg' => '用户添加失败');
if ($params) {
helper::datalog('添加用户数据: -IN: ' . var_export($params, true));
$getUser = $this->getUser(array('a.id' => $params['user_id']));
if (!empty($getUser)) {
$output['msg'] = '用户已经存在';
return $output;
}
if (strlen($params['card']) < 6) {
$output['msg'] = '用户身份证号错误';
return $output;
}
$pwd = $this->loadModel('common')->getEncryptedPwd(substr($params['card'], -6));
$data = array(
'id' => $params['user_id'],
'user_code' => $params['user_code'],
'user_name' => $params['user_name'],
'true_name' => $params['real_name'],
'user_mobile' => $params['mobile_phone'],
'user_pwd' => $pwd,
'invite_code' => $params['invite_code'],
'card' => $params['card'],
'bank_name' => $params['bank_name'],
'bank_card_no' => $params['bank_card_no'],
'sort_id' => $this->getUserMax(),
'reg_time' => $params['reg_time'],
'createtime' => helper::nowTime(),
'last_operator' => $this->myAdmin->true_name,
'updatetime' => helper::nowTime(),
'creator_id' => $this->myAdmin->id,
'is_del' => 0
);
$addRes = parent::insert($data, 'ecsa_sys_users');
helper::datalog('添加用户数据: -OUT: ' . var_export($addRes, true));
if ($addRes) {
$output = array('success' => true, 'msg' => '用户添加成功', 'data' => $addRes);
}
}
return $output;
}
public function updateUserParent($data){
$output = array('success' => true, 'msg' => '更新推荐人数据成功');
if ($data['invite_code']) {
$getUser = $this->getUser(array('a.user_code' => $data['invite_code']));
if (empty($getUser)) {
$this->_err($output, '更新推荐人数据, 推荐码不存在');
} else {
$parent = $getUser[0];
if (!$this->addUserChildOne($parent->id)) {
$this->_err($output, '更新推荐人数据, 增加直推数量失败');
}
}
}
$this->update;
$output = array('success' => true, 'msg' => '更新成功');
}
public function _err(&$output, $msg = '执行失败'){
$output = array('success' => false, 'msg' => $msg);
}
/**
* 通过用户id,给他添加一个直推数量
*/
public function addUserChildOne($user){
$num = false;
if ($user['id']) {
$sql = "UPDATE ecsa_sys_users a
SET a.child_num = a.child_num + 1
WHERE a.id = '{$user['id']}'";
$num = $this->exec($sql);
}
return $num;
}
/**
* 通过用户id,给他添加一个推荐数量
*/
public function addUserAllChildOne($user){
$num = false;
if ($user['id']) {
$sql = "UPDATE ecsa_sys_users a
SET a.all_child_num = a.all_child_num + 1
WHERE a.id = '{$user['id']}'";
$num = $this->exec($sql);
}
return $num;
}
/**
* 获取用户的位置
*/
public function getUserPlace($user_place_id) {
$place = array('row' => 0, 'column' => 0);
if ($user_place_id) {
for ($i = 1; $i <= $user_place_id; $i++) {
$start = 1<<($i - 1);
$end = ($start * 2) - 1;
if ($user_place_id >= $start && $user_place_id <= $end) {
$place = array('row' => $i, 'column' => $user_place_id - $start + 1);
braak;
}
}
}
return $place;
}
/**
* 设置用户的子
*/
public function setUserChild($user_place_id) {
$this->max = $this->getUserMax();
$place = $this->getUserPlace($user_place_id);
$childFirst = (1<<$place['row']) + ($place['column'] * 2) - 1 - 1;
if ($childFirst <= $this->max) {
$this->child[] = $childFirst;
$this->setUserChild($childFirst);
$childSecond = $childFirst + 1;
if ($childSecond <= $this->max) {
$this->child[] = $childSecond;
$this->setUserChild($childSecond);
} else {
return;
}
} else {
return;
}
}
/**
* 获取用户的子
*/
public function getUserChild($user_place_id) {
$this->setUserChild($user_place_id);
sort($this->child);
return $this->child;
}
/**
* 设置用户数
*/
public function setUserMax() {
$sql = 'SELECT %s FROM ecsa_sys_users a ';
$fields = " MAX(a.sort_id) sort_id ";
$data = parent::findBySql($sql, $where, null, null, $fields);
if (empty($data)) {
$this->max = 0;
} else {
$this->max = $data[0]->sort_id;
}
}
/**
* 获取用户总数
*/
public function getUserMax() {
if ($this->max === null) {
$this->setUserMax();
}
return $this->max;
}
public function getUserParent() {
}
}
<file_sep><?php
/**
* 角色
* @author liuzhi
* @
*/
class roleModel extends model
{
public function __construct()
{
parent::__construct();//guojuan 2014.4.29 去掉旧表
}
public function search($where='',$fields='') {
$sql = "select %s FROM ecsa_sys_roles AS a ";
if($fields == '')$fields = " a.* ";
$datas = parent::findBySql($sql,$where,null,null,$fields);
return $datas;
}
/*
* 获取某个角色的资源列表*/
public function getRoleSource($where='') {
$sql = "select %s from ecsa_sys_role_source as a
left join ecsa_sys_source as b on a.source_id=b.id";
$fields = " a.source_id,b.source_code,b.source_name,substring(b.source_code,1,length(b.source_code)-3) as parent_code ";
$datas = parent::findBySql($sql,$where,null,null,$fields);
return $datas;
}
public function add($record,$tabel) {
$cId = parent::insert($record,$tabel);
if($cId) {
return $cId;
}
else {
return 0;
}
}
public function update($ids=array(),$setarr =array(),$tb='')
{
return parent::update($setarr,$ids,$tb);
}
public function delete($sid,$tb="ecsa_sys_roles"){
return parent::delete($sid,null,$tb);
}
/**
* 是否有用户绑定角色,是否可以产出角色
* @param Int $org_id
* @return boolean
*/
public function checkRoleCanDel($role_id){
$result = true;
$wheresql = " role_id = '$role_id' ";
$fields = " count(*) as total ";
$sql = "select %s from ecsa_sys_user_roles";
$datas = parent::findBySql($sql,$wheresql,null,null,$fields);
$datas[0]->total > 0?$result = false:'';
return $result;
}
}
<file_sep><?php
/* 记录最开始的时间。*/
$timeStart = _getTime();
/* 包含必须的类文件。*/
include '../../../framework/error.class.php';
include '../../../framework/router.class.php';
include '../../../framework/control.class.php';
include '../../../framework/model.class.php';
include '../../../framework/helper.class.php';
include '../lib/base.control.class.php';
try {
/* 实例化路由对象,并加载配置,连接到数据库,加载common模块。*/
$app = router::createApp('demo', dirname(dirname(__FILE__)));
$config = $app->loadConfig('common');
$common = $app->loadCommon();
/* 处理请求,加载相应的模块。*/
$app->parseRequest();
$app->loadModule();
} catch (Exception $e) {
// 输出JSON格式错误
$ecode = $e->getCode();
$result = array(
'code' => $ecode,
'message' => sprintf( "Exception: %s \n %s", $e->getMessage(), $e->getTraceAsString() )
);
if($ecode!=403)
helper::datalog('inside|'.$ecode.'|'.$e->getMessage(),'syslog_');
header("Content-Type: application/json");
$errorstring = json_encode($result);
$errorstring = str_replace(array('192.168.127.12','192.168.127.12','ips','221','gps','172.16.17.32','330','hyruser0713'), array(), $errorstring);
echo $errorstring;
}
/* 获取系统时间,微秒为单位。*/
function _getTime()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
<file_sep><?php
require_once 'Client.php';
class clientModel extends Client {
public function __construct()
{
}
/**
* [data] => stdClass Object
(
[address] => 海淀
[name] => 张军3
[id] => 12
[owner] => TXT
[createTime] => 1176818040000
[city] => 济南
[mobile] => 13651169290
[company] =>
[phone] => 010-82150101
[login] => admin
[regType] => 1
[pass] => <PASSWORD>
[updateTime] => 1176818040000
)
* error
* stdClass Object
(
[message] => 不存在的方法名
[data] =>
[params] => stdClass Object
(
[sign] => 9618C6D5C7BABFCECEB0E13F9C9A598C
[timestamp] => 2010-11-30 18:38:00
[username] => admin
[method] => huoyunren.loginuser.get
[app_key] => 1088
[format] => json
)
[code] => 22
)
* @param unknown_type $value
* @param unknown_type $key username or id
*/
public function userInfoApi($value,$key='username')
{
$user_json = $this->loginuserGet(array($key=>$value));
$user = json_decode($user_json);
return $user;
}
/**
*
* 注册检测
* @param string $username
* return stdClass Object
(
[message] => ''
[data] => true or false
[code] => 0
)
* }
*/
public function userCheckApi($username)
{
$user_json = $this->loginuserCheck(array('username'=>$username));
$user = json_decode($user_json);
return $user;
}
/* 搜索用户
* @param page_no 页号
* @param page_size 页大小
* @param name 姓名
* @param username 用户名
* @param phone 电话号
* @param inputterIdR 创建人id
* @param createtime_ge 创建时间>=
* @param createtime_lt 创建时间<
* @param orderby 排序,默认id倒序
* @return
huoyunren.loginuser.search
*/
public function userListApi($value)
{
$user_json = $this->loginuserSearch($value);
$user = json_decode($user_json);
return $user;
}
/**
* 直接通过mapabc解析地址
* @param string $lat
* @param string $lng
*/
public function geoAddr_mapabc($lat,$lng,$type=0)
{
global $app;
helper::import($app->getAppRoot(). "lib/mapabc.class.php");
$mapabc = new mapabc();
$rs = $mapabc->getAddress($lat,$lng,$type);
return $rs;
}
/**
* 修改密码
*
* @param unknown_type $username
* @param unknown_type $newpass
* @return unknown
*/
public function editPasswdApi($username,$newpass)
{
$user_json = $this->loginuserChkpwd(array('username'=>$username,'newpass'=>$newpass));
$user = json_decode($user_json);
return $user;
}
/**
* @param unknown_type $gpsno
* @return unknown
*/
public function geoAddress($gpsno)
{
$result = $this->gpsCurrent(array('gpsno'=>$gpsno,'code'=>1));
$obj = json_decode($result);
if($obj->code==0)
{
$result = new stdClass();
$result = $obj->data->location->place;
$result->time = date('Y-m-d H:i:s', $obj->data->location->time/1000);
$result->speed = $obj->data->location->speed;
$result->utime = $obj->data->location->time/1000;
return $result;
}
else
{
return;
}
}
}
?><file_sep>var top_panel = new Ext.form.FormPanel({
region : 'north',
hideLabels : true,
bodyStyle : 'padding: 10px',
height : 50,
items :
[
{
xtype : 'compositefield',
items :
[
{
xtype: 'displayfield',
value: '标题:'
},
{
xtype : 'textfield',
id : 'no_title',
width : 200
},
{
xtype: 'displayfield',
value: '添加人:'
},
{
xtype : 'textfield',
id : 'no_user_name',
width : 100
},
{
xtype:'button',
text:'查询',
style : 'padding-left : 10px;',
handler: function()
{
noticeStore.removeAll();//移除原来的数据
noticeStore.load();//加载新搜索的数据
}
},
]
}
]
});<file_sep>/**
* 分页下拉插件
*
*/
var page = [10,20,50,100,500];
Ext.namespace('Ext.ux.plugin');
Ext.ux.plugin.PagingToolbarResizer = Ext.extend(Object, {
options: page,//[5, 10, 15, 20, 25, 30, 50, 75, 100, 200, 300, 500, 1000]
mode: 'remote',
displayText: '每页',
prependCombo: false,//如果true 显示在开头
constructor: function(config){
Ext.apply(this, config);
Ext.ux.plugin.PagingToolbarResizer.superclass.constructor.call(this, config);
},
init : function(pagingToolbar)
{
var comboStore = this.options;
var combo = new Ext.form.ComboBox({
typeAhead: false,
triggerAction: 'all',
forceSelection: true,
selectOnFocus:true,
lazyRender:true,
editable: false,
mode: this.mode,
value: pagingToolbar.pageSize,
width:50,
store: comboStore,
listeners: {
select: function(combo, value, i){
pagingToolbar.pageSize = comboStore[i];
pagingToolbar.store.baseParams.limit = comboStore[i];//Story #23708
pagingToolbar.doLoad(Math.floor(pagingToolbar.cursor/pagingToolbar.pageSize)*pagingToolbar.pageSize);
}
}
});
var index = 0;
if (this.prependCombo){
index = pagingToolbar.items.indexOf(pagingToolbar.first);
index--;
} else{
index = pagingToolbar.items.indexOf(pagingToolbar.refresh);
pagingToolbar.insert(++index,'-');
}
pagingToolbar.insert(++index, this.displayText);
pagingToolbar.insert(++index, combo);
pagingToolbar.insert(++index, '条');
if (this.prependCombo){
pagingToolbar.insert(++index,'-');
}
//destroy combobox before destroying the paging toolbar
pagingToolbar.on({
beforedestroy: function(){
combo.destroy();
}
});
}
});<file_sep><?php
/**
* 公告信息管理
* @author liuzhi
* @since 2013/11/12
*/
class orderModel extends model {
/**
* 获取公告列表信息
* @param String $where 搜索条件 默认搜索全部
* @param Array $limit 分页数组 默认分页20条
* @param String $desc 按创建时间倒序
* @author liuzhi
* @since 2013/11/8
*/
public function search($where,$limit,$desc)
{
$sql = "SELECT %s FROM ecsa_sys_order ";
$fields = " * ";
//取记录总数
$total = parent::findBySql($sql, $where, $desc, null, 'count(id) as count');
//取记录集
if($total[0]->count > 0) {
$datas = parent::findBySql($sql,$where, $desc, $limit, $fields);
}
$result = new stdClass();
$result->total = $total[0]->count;
$result->data = $datas;
return $result;
}
/**
* 公告信息修改
* @param Array $id ID
* @param Array $data 修改信息
* @param string $table 表名
* @author liuzhi
* @since 2013/11/12
*/
public function update($id = array(),$data = array(),$table = '')
{
return parent::update($data,$id,$table);
}
/**
* 公告信息添加
* @param array $data 添加信息
* @param string $table 表名
* @author liuzhi
* @since 2013/11/12
*/
public function add($data,$table)
{
if(!empty($data) && !empty($table))
{
return parent::insert($data, $table);
}
else
{
return false;
}
}
/**
* 按条件检索单据信息
* //Story #49819
* @author liuzhi
* @since 2015/10/14
*/
public function getOrder($where){
$sql = 'SELECT %s FROM ecsa_orders a ';
$fields = " a.order_id ";
$data = parent::findBySql($sql, $where, null, null, $fields);
return $data;
}
}<file_sep><?php
/**
* 公共类,权限检查
* @author liuzhi
* @package ZenTaoPHP
*/
class baseControl extends control {
/**
* 构造函数:
*
* 1. 引用全局对象,使之可以通过成员变量访问。
* 2. 设置模块相应的路径信息,并加载对应的model文件。
* 3. 自动将$lang和$config赋值到模板。
*
* @access public
* @return void
*/
public $dbh;
//事务处理所用的DB库变量 Story #8396gsp系统添加事务处理功能
public function __construct($moduleName = '', $methodName = '') {
parent::__construct();
/*检查当前用户是否有当前资源的权限*/
$this->checkPower();
//事务处理所用的DB库 Story #8396gsp系统添加事务处理功能
$this->dbh = model::getDbh('db');
}
/**
* 检查当前用户是否有当前资源的权限
* @author liuzhi
* @since 2013/12/19
*/
public function checkPower() {
//当前用户拥有的权限
$source = $this->app->myAdmin->source;
//所有权限
$sourceAll = $this->app->myAdmin->sourceAll;
$moduleName = $this->moduleName;
$methodName = $this->methodName;
$hasPower = true;
$hasModulePower = false;
if ($source) {
$hasPower = false;
$sourceRec = new stdClass();
$sourceRec->source_id = 'asdfasdf';
foreach ($source as $sv) {
$m = explode('/', $sv->url);
if ($m[1] == $moduleName) {//拥有当前module的权限
$hasModulePower = true;
$sourceRec = $sv;
}
}
//检查是否有所请求的控件的权限
$hasPower = $this->checkSource($sourceRec, $hasModulePower);
$moduleName == 'common' ? $hasPower = true : '';
$moduleName == 'login' ? $hasPower = true : '';
}
if (!$hasPower) {//没有权限
echo json_encode(array('success' => false, 'msg' => 'Do not have access!'));exit;
}
}
/**
* 检查当前用户是否有当前资源的权限
* @author liuzhi
* @since 2013/12/19
* @param $reSource 一条moudle资源
* @return boolean 是否有权限:true=>有,false=>无
*/
public function checkSource($reSource, $hasModulePower) {
$outList = array(//默认没有权限,单不包括按钮和search
array('m' => 'service_recover', 'f' => 'suitSearch'), array('m' => 'service_recover', 'f' => 'partSearch'), array('m' => 'storage_in', 'f' => 'suitSearch'), array('m' => 'storage_in', 'f' => 'partSearch'), );
//当前用户拥有的权限
$source = $this->app->myAdmin->source;
//所有权限
$sourceAll = $this->app->myAdmin->sourceAll;
$methodName = $this->methodName;
$publicFn = true;
//请求的是否为公共方法
$hasPower = false;
foreach ($sourceAll as $allV) {
if ($allV->source_id == $reSource->source_id) {
foreach ($allV->control as $conV) {
$_fn = explode('|', $conV->url);
$fn = $_fn[4] ? $_fn[4] : $_fn[0];
//如果没有第五个参数,则取第一个(没有配置phpFn,则使用jsFn)
if ($fn == $methodName) {
$publicFn = false;
}
}
}
}
if (!$publicFn) {
foreach ($reSource->control as $reConV) {
$re_fn = explode('|', $reConV->url);
$refn = $re_fn[4] ? $re_fn[4] : $re_fn[0];
//如果没有第五个参数,则取第一个(没有配置phpFn,则使用jsFn)
if ($refn == $methodName) {//拥有当前控件的权限
$hasPower = true;
}
}
} else {
if ($hasModulePower) {
$hasPower = true;
} else {
if ($methodName != 'search') {//请求的是公共方法
$hasPower = true;
foreach ($outList as $lv) {
if ($moduleName == $lv['m'] && $methodName == $lv['f']) {
$hasPower = false;
}
}
}
}
}
return $hasPower;
}
/**
* 把csv文件解析为一个数组返回
*
* @param string $file 要解析的csv文件路径
* @param char $delimiter csv文件里的内容分隔符 默认为;
* @return array
*/
public static function open($file, $delimiter = ';') {
return self::ordenamultiarray(self::csvarray($file, $delimiter), 1);
}
private function csvarray($file, $delimiter) {
$result = array();
$size = filesize($file) + 1;
$file = fopen($file, 'r');
$keys = fgetcsv($file, $size, $delimiter);
fseek($file, 0);
//这里原来的没有..自己加上..这样能读取到第一行的内容
while ($row = fgetcsv($file, $size, $delimiter)) {
for ($i = 0; $i < count($row); $i++) {
if (array_key_exists($i, $keys)) {
$row[$keys[$i]] = $row[$i];
}
}
$result[] = $row;
}
fclose($file);
return $result;
}
private function ordenamultiarray($multiarray, $secondindex) {
while (list($firstindex, ) = each($multiarray))
$indexmap[$firstindex] = $multiarray[$firstindex][$secondindex];
asort($indexmap);
while (list($firstindex, ) = each($indexmap))
if (is_numeric($firstindex))
$sortedarray[] = $multiarray[$firstindex];
else
$sortedarray[$firstindex] = $multiarray[$firstindex];
return $sortedarray;
}
}
<file_sep><?php
require_once 'Util.php';
define('API_URL', 'http://www.86cha.net/admin/inside.php');
define('APP_KEY', 'ecs');
define('APP_SECRET', '<KEY>');
?>
<file_sep><?php
/**
* The config file of ZenTaoPHP.
*
* ZenTaoPHP is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* ZenTaoPHP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ZenTaoPHP. If not, see <http://www.gnu.org/licenses/>.
*
* @copyright Copyright 2009-2010 青岛易软天创网络科技有限公司(www.cnezsoft.com)
* @author <NAME> <<EMAIL>>
* @package ZenTaoPHP
* @version $Id: config.php 109 2010-05-02 15:42:08Z wwccss $
* @link http://www.zentaoms.com
*/
$config->version = '1.0.STABLE.090620'; // 版本号,切勿修改。
$config->debug = false; // 是否打开debug功能。
$config->webRoot = '/'; // web网站的根目录。
$config->encoding = 'UTF-8'; // 网站的编码。
$config->cookiePath = '/'; // cookie的有效路径。
$config->cookieLife = time() + 2592000; // cookie的生命周期。
$config->cookiepre = 'ecs_admin'; //cookie前缀
$config->strictParams = true; // 参数按名称精确匹配
$config->requestType = 'GET'; // 如何获取当前请求的信息,可选值:PATH_INFO|GET
$config->pathType = 'clean'; // requestType=PATH_INFO: 请求url的格式,可选值为full|clean,full格式会带有参数名称,clean则只有取值。
$config->requestFix = '/'; // requestType=PATH_INFO: 请求url的分隔符,可选值为斜线、下划线、减号。后面两种形式有助于SEO。
$config->moduleVar = 'm'; // requestType=GET: 模块变量名。
$config->methodVar = 'f'; // requestType=GET: 方法变量名。
$config->viewVar = 't'; // requestType=GET: 模板变量名。
$config->sessionVar = 's';
$config->views = ',html,xml,json,txt,csv,doc,pdf,'; // 支持的视图列表。
$config->langs = 'zh-cn,zh-tw,zh-hk,en'; // 支持的语言列表。
$config->themes = 'default'; // 支持的主题列表。
$config->default = new stdClass();
$config->default->view = 'json'; // 默认的视图格式,可选值:html|blz|tpl|json
$config->default->lang = 'zh-cn'; // 默认的语言。
$config->default->theme = 'default'; // 默认的主题。
$config->default->module = 'index'; // 默认的模块。当请求中没有指定模块时,加载该模块。
$config->default->method = 'index'; // 默认的方法。当请求中没有指定方法或者指定的方法不存在时,调用该方法。
$config->db = new stdClass();
$config->db->errorMode = PDO::ERRMODE_WARNING; // PDO的错误模式: PDO::ERRMODE_SILENT|PDO::ERRMODE_WARNING|PDO::ERRMODE_EXCEPTION
$config->db->persistant = false; // 是否打开持久连接。
$config->db->driver = 'mysql'; // pdo的驱动类型,目前暂时只支持mysql。
$config->db->host = '172.16.31.10'; // mysql主机。
$config->db->port = '3306'; // mysql主机端口号。
$config->db->name = 'ecs_admin'; // 数据库名称。
$config->db->user = 'ecshop'; // 数据库用户名。
$config->db->password = '<PASSWORD>'; // 密码。
$config->db->encoding = 'UTF8'; // 数据库的编码。
?>
<file_sep><?php
/**
* 角色控制类
* @author liuzhi
*/
class role extends baseControl
{
public function __construct()
{
parent::__construct();
$this->myAdmin = $this->app->myAdmin;
}
/**
* 搜索 默认搜全部
* @author liuzhi
* @since 2013/12/31
*/
public function search()
{
$params = helper::filterParams();
$wheresql = ' 1 and is_del=0 ';
$name = $params['name'] ? $params['name'] : '';
if ($name!=''){
$wheresql .= " and a.role_name like '%$name%' ";
}
$data = $this->role->search($wheresql);
$this->assign('data',$data);
$this->display();
}
/**
* 搜索 特定资源,排列成树状
* @author liuzhi
* @since 2013/12/31
*/
public function getRoleSource()
{
$params = helper::filterParams();
$wheresql = ' 1 ';
$role_id = $params['id'] ? $params['id'] : '';
//当前登录中的用户资源
$userSource = $this->loadModel('common')->getsysconfig($this->myAdmin->id,null,true);
if ($role_id!=''){
$wheresql .= " and a.role_id='$role_id' and a.is_del=0 ";
$data = $this->role->getRoleSource($wheresql);
}
foreach($userSource as $k=>$v){
$userSource[$k]->checked = false;
if(isset($data)){
foreach ($data as $sk=>$sv){
if($v->source_id == $sv->source_id){
$userSource[$k]->checked = true;
}
}
}
$userSource[$k]->uiProvider = 'col';
$userSource[$k]->leaf = true;//默认没有子集
$userSource[$k]->text = $userSource[$k]->source_name;
$this->loadModel('common')->editdata($userSource,$v->parent_code,$k,$userSource,'source_code');
}
$result = array_merge($userSource);
echo json_encode($result);
}
/**
* 添加角色
* @author liuzhi
* @since 2013/12/31
*/
public function add(){
$params = helper::filterParams();
$setarr = array(
'role_name' => $params['role_name'],
'creator_id' =>$this->myAdmin->id,
'last_operator' =>$this->myAdmin->true_name,
'createtime' => helper::nowTime(),
'status' => 1,
'is_del' => 0,
);
$addNo = $this->role->add($setarr,'ecsa_sys_roles');
if($addNo) {
//更新角色资源表
$arrtmp = explode(",",$params['rolelist']);
foreach ($arrtmp as $value){
if ($value){//不能为空
$this->addRoleSource($addNo,$value);
}
}
$output = array('success'=>true,'msg'=>'成功');
}else {
$output = array('success'=>false,'msg'=>'失败');
}
echo json_encode($output);
}
/**
* 更新角色信息
* @author liuzhi
* @since 2013/12/31
*/
public function update()
{
$params = helper::filterParams();
$idds = array(
'id' => $params['id']
);
$setarr = array(
'role_name' => $params['role_name'],
'updatetime' => helper::nowTime(),
'last_operator' =>$this->myAdmin->true_name
);
$addNo = $this->role->update($idds,$setarr,'ecsa_sys_roles');
if($addNo) {
//清空下面的权限
$dels = "role_id='$params[id]' and is_del=0";
$this->role->delete($dels,'ecsa_sys_role_source');
//更新角色资源表
$arrtmp = explode(",",$params['rolelist']);
foreach ($arrtmp as $value){
if ($value){//不能为空
$addNo = $this->addRoleSource($params['id'],$value);
}
}
$output = array('success'=>true,'msg'=>'成功');
}else {
$output = array('success'=>false,'msg'=>'失败');
}
echo json_encode($output);
}
/**
* 删除角色信息,假删
* @author liuzhi
* @since 2013/12/31
*/
public function delete()
{
$params = helper::filterParams();
$uname = $this->myAdmin->true_name;
if($this->role->checkRoleCanDel($params['id'])){
$idds = array(
'id' => $params['id']
);
$role_ids = array(
'role_id' => $params['id'],
'is_del' => 0
);
$addNo = $this->role->update($idds,array('is_del' => 1,'last_operator' => $uname),'ecsa_sys_roles');
if($addNo) {
$addNo = $this->role->update($role_ids,array('is_del' => 1,'last_operator' => $uname),'ecsa_sys_role_source');
if($addNo) {
$output = array('success'=>true,'msg'=>'成功');
}else {
$output = array('success'=>false,'msg'=>'成功,该角色没有资源');
}
}else {
$output = array('success'=>false,'msg'=>'失败');
}
}else{
$output = array('success'=>false,'msg'=>'删除失败,有用户绑定角色!');
}
echo json_encode($output);
}
public function addRoleSource($role_id,$source_id)
{
$uid = $this->myAdmin->id;
$uname = $this->myAdmin->true_name;
$arr = array(
'role_id' => $role_id,
'source_id' =>$source_id,
'creator_id' =>$uid,
'last_operator' => $uname,
'createtime' => helper::nowTime(),
'status' => 1,
'is_del' => 0,
);
$addNo = $this->role->add($arr,'ecsa_sys_role_source');
}
}
<file_sep><?php
/**
* 工资管理
* @author liuzhi
* @since 2013/11/12
*/
class wages extends baseControl
{
public function __construct()
{
parent::__construct();
$this->myAdmin = $t09his->app->myAdmin;
}
/**
* 获取订单列表信息
* @author liuzhi
* @since 2016-04-19
*/
public function search()
{
$params = helper::filterParams();
$where = '1';
if ($params['user_name']) {
$params['user_name'] = trim($params['user_name']);
$where .= " AND b.user_name LIKE '%{$params['user_name']}%'";
}
//分页信息
$limit = array($params['start'], $params['limit']);
$desc = " a.createtime DESC";
$data = $this->wages->search($where, $limit, $desc);
//输出结果
echo json_encode($data);
}
/**
* 订单信息修改
* @author liuzhi
* @since 2016-04-19
*/
public function update()
{
$output = array('success' => true, 'msg' => '更新成功');
$params = helper::filterParams();
try {
//开启事务
$this->dbh->beginTransaction();
/***************************
* START处理逻辑
***************************/
if (!$params['id']) {
throw new Exception('数据异常,清理下缓存试试', 1);
}
$where = " id = '{$params['id']}' AND (updatetime = '{$params['updatetime']}' OR updatetime IS NULL)";
$getwages = $this->wages->getwages($where);
if (empty($getwages)) {
throw new Exception('数据已经被修改过,请刷新后重试', 1);
}
$update = array(
'wages_total' => $params['wages_total']
);
$this->wages->update(array('id' => $params['id']), $update, 'ecsa_wages');
/***************************
* END处理逻辑
***************************/
//事务提交
$this->dbh->commit();
echo json_encode($output);
} catch (Exception $e) {
//事务回滚
$this->dbh->rollBack();
echo json_encode(array('success' => false, 'msg' => $e->getCode() == '1' ? $e->getMessage() : '更新失败'));
helper::datalog('异常: ' . var_export($e->getMessage(), true));
}
}
/**
* 订单信息审核
* @author liuzhi
* @since 2016-04-19
*/
public function statusTo1()
{
try {
//开启事务
$this->dbh->beginTransaction();
/***************************
* START处理逻辑
***************************/
$output = array('success' => true, 'msg' => '审核成功');
$params = helper::filterParams();
if (!$params['id']) {
throw new Exception('数据异常,清理下缓存试试', 1);
}
$where = " id = '{$params['id']}' AND (updatetime = '{$params['updatetime']}' OR updatetime IS NULL)";
$getwages = $this->wages->getwages($where);
if (empty($getwages)) {
throw new Exception('数据已经被修改过,请刷新后重试', 1);
}
$update = array(
'status' => '1'
);
$this->wages->update(array('id' => $params['id']), $update, 'ecsa_wages');
/***************************
* END处理逻辑
***************************/
//事务提交
$this->dbh->commit();
echo json_encode($output);
} catch (Exception $e) {
//事务回滚
$this->dbh->rollBack();
echo json_encode(array('success' => false, 'msg' => $e->getCode() == '1' ? $e->getMessage() : '审核失败'));
helper::datalog('异常: ' . var_export($e->getMessage(), true));
}
}
/**
* 订单信息驳回
* @author liuzhi
* @since 2016-04-19
*/
public function statusTo_1()
{
try {
//开启事务
$this->dbh->beginTransaction();
/***************************
* START处理逻辑
***************************/
$output = array('success' => true, 'msg' => '驳回成功');
$params = helper::filterParams();
if (!$params['id']) {
throw new Exception('数据异常,清理下缓存试试', 1);
}
$where = " id = '{$params['id']}' AND (updatetime = '{$params['updatetime']}' OR updatetime IS NULL)";
$getwages = $this->wages->getwages($where);
if (empty($getwages)) {
throw new Exception('数据已经被修改过,请刷新后重试', 1);
}
$update = array(
'status' => '-1',
'dismiss_reason' => $params['dismiss_reason']
);
$this->wages->update(array('id' => $params['id']), $update, 'ecsa_wages');
/***************************
* END处理逻辑
***************************/
//事务提交
$this->dbh->commit();
echo json_encode($output);
} catch (Exception $e) {
//事务回滚
$this->dbh->rollBack();
echo json_encode(array('success' => false, 'msg' => $e->getCode() == '1' ? $e->getMessage() : '驳回失败'));
helper::datalog('异常: ' . var_export($e->getMessage(), true));
}
}
/**
* 订单信息
* @author liuzhi
* @since 2016-04-19
*/
public function statusTo2()
{
try {
//开启事务
$this->dbh->beginTransaction();
/***************************
* START处理逻辑
***************************/
$output = array('success' => true, 'msg' => '修改成功');
$params = helper::filterParams();
if (!$params['id']) {
throw new Exception('数据异常,清理下缓存试试', 1);
}
$where = " id = '{$params['id']}' AND (updatetime = '{$params['updatetime']}' OR updatetime IS NULL)";
$getwages = $this->wages->getwages($where);
if (empty($getwages)) {
throw new Exception('数据已经被修改过,请刷新后重试', 1);
}
$update = array(
'status' => '2'
);
$this->wages->update(array('id' => $params['id']), $update, 'ecsa_wages');
/***************************
* END处理逻辑
***************************/
//事务提交
$this->dbh->commit();
echo json_encode($output);
} catch (Exception $e) {
//事务回滚
$this->dbh->rollBack();
echo json_encode(array('success' => false, 'msg' => $e->getCode() == '1' ? $e->getMessage() : '修改失败'));
helper::datalog('异常: ' . var_export($e->getMessage(), true));
}
}
/**
* 导出
*
* @author liuzhi
* @since 2016-04-24
*/
public function export()
{
$params = helper::filterParams();
//$start_time = !empty($params['start_time']) ? substr($params['start_time'],0,10) : '';
//$end_time = !empty($params['end_time']) ? substr($params['end_time'],0,10) : '';
$where = ' 1 ';
if ($params['user_name']) {
$params['user_name'] = trim($params['user_name']);
$where .= " AND b.user_name LIKE '%{$params['user_name']}%' ";
}
//分页信息
$page = intval($params['page']);
$pageSize = 5000;
if (empty($page)) {
$limit = array(0, $pageSize);
} else {
$limit = array(($page-1)*$pageSize, $pageSize);
}
$desc = " a.createtime DESC";
$data[] = array('员工号', '员工姓名', '所属银行', '银行卡号', '身份证号', '奖金金额', '申请提现日期', '提现金额', '升级缴费金额', '是否发放');
$result = $this->wages->search($where, $limit, $desc);
/*if (isset($params['get_num']) && $params['get_num']) {
echo json_encode(array('num' => $result->total));
return;
}*/
if (!empty($result->data))
{
foreach ($result->data as $val)
{
$status = '';
switch ($val->status) {
case '-1' :
$status='已驳回';
break;
case '0' :
$status='待审核';
break;
case '1' :
$status='已审核';
break;
case '2' :
$status='已结款';
break;
}
$data[] = array
(
$val->user_code,
$val->user_name,
$val->bank_name,
'="' . $val->bank_card_no . '"',
'="' . $val->card . '"',
$val->total,
$val->createtime,
$val->wages_total,
$val->pay_total,
$status,
);
}
include_once $GLOBALS['app']->getAppLibRoot() . "export.php";
$csv = new CSV_Writer(helper::charseticonv($data));
$filenames = date('Y/m/d/H:i:s') . "提现列表-" . $page;
$csv->headers($filenames);
$csv->output();
}
}
}
?><file_sep><?php
/**
* The model class file of ZenTaoPHP.
*
* ZenTaoPHP is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* ZenTaoPHP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ZenTaoPHP. If not, see <http://www.gnu.org/licenses/>.
*
* @copyright Copyright 2009-2010 青岛易软天创网络科技有限公司(www.cnezsoft.com)
* @author <NAME> <<EMAIL>>
* @package ZenTaoPHP
* @version $Id: model.class.php 117 2010-06-17 08:58:58Z wwccss $
* @link http://www.zentaoms.com
*/
/**
* 模型基类。
*
* @package ZenTaoPHP
*/
class model {
// 条件后缀,实现根据传入的条件属性自动构建SQL语句
/** 等于,不加后缀默认为等于 */
const SUFFIX_EQ = "_eq";
/** 不等于 */
const SUFFIX_NE = "_ne";
/** 大于等于 */
const SUFFIX_GE = "_ge";
/** 大于 */
const SUFFIX_GT = "_gt";
/** 小于等于 */
const SUFFIX_LE = "_le";
/** 小于 */
const SUFFIX_LT = "_lt";
/** 模糊查询 */
const SUFFIX_LK = "_lk";
static $SUFFIX_OPERATOR = array(self::SUFFIX_EQ=>"=", self::SUFFIX_NE=>"!=", self::SUFFIX_GE=>">=", self::SUFFIX_GT=>">", self::SUFFIX_LE=>"<=", self::SUFFIX_LT=>"<", self::SUFFIX_LK=>"LIKE");
/**
* 全局的$app对象。
*
* @var object
* @access protected
*/
protected $app;
/**
* 全局的$dbh(数据库访问句柄)对象。
*
* @var object
* @access protected
*/
static $_dbhs;
/**
* 当前数据操作对象
*/
protected $dbh;
/**
* 默认表名
* @var <type>
*/
protected $name;
/**
* 数据库配置名,默认db
* @var <type>
*/
protected $dbname;
// 主键名称
protected $pk = 'id';
// 查询表达式参数
protected $options = array();
protected $_validate = array(); // 自动验证定义
protected $_auto = array(); // 自动完成定义
protected $_map = array(); // 字段映射定义
// 是否自动检测数据表字段信息
protected $autoCheckFields = false;
protected $prepared = true;
//数据库类型,默认mysql
protected $dbdriver = 'mysql';
protected $moduleName = null;
/**
* 实例化的Model对象集
*/
protected $modelobj = array();
/**
* 构造函数:
*
* 1. 引用全局变量,使之可以通过成员属性访问。
* 2. 设置当前模块的路径、配置、语言等信息,并加载相应的文件。
*
* @access public
* @return void
*/
public function __construct($table = null, $dbname='db') {
global $app;
$this->app = $app;
$moduleName = $this->getModuleName();
$this->name = $table ? $table : $moduleName;
$this->dbname = $dbname;
// 字段检测
if(!empty($this->name) && $this->autoCheckFields) $this->_checkTableInfo();
}
/**
* 自动检测数据表信息
*/
protected function _checkTableInfo() {
// 如果不是Model类 自动记录数据表信息
// 只在第一次执行记录
if(empty($this->fields)) {
// 每次都会读取数据表信息
$this->fields = helper::F('_fields/'.$this->name);
if(!$this->fields) $this->flush();
}
}
/**
* 获取字段信息并缓存
*/
public function flush() {
// 缓存不存在则查询数据表信息
$this->fields = array();
$dbh = self::getDbh($this->dbname);
$stmt = $dbh->query("select * from " . $this->name . " where 1=2");
for ($i = 0; $i < $stmt->columnCount(); $i ++) {
$val = $stmt->getColumnMeta($i);
$key = $val['name'];
$this->fields[$key] = $val;
// 记录主键
if($val['flags'][1] == 'primary_key')
$this->pk = $key;
}
// 永久缓存数据表信息
helper::F('_fields/'.$this->name, $this->fields);
}
/**
* 获取主键名称
*/
public function getPk() {
return $this->pk;
}
/**
*获得数据库类型
*/
public function getDriver(){
global $config;
$dbconfig = $config->db;
$this->dbdriver = $dbconfig->driver;
return $this->dbdriver;
}
/**
* 连接到数据库,返回$dbh对象。
*
* @access public
* @return object
*/
static function getDbh($dbname)
{
if (self::$_dbhs [$dbname] instanceof PDO)
return self::$_dbhs [$dbname];
global $config,$app;
$dbconfig = $config->$dbname;
if (! isset ( $dbconfig->driver ))
$app->error ( 'no pdo driver defined, it should be mysql or sqlite', __FILE__, __LINE__, $exit = true );
if ($dbconfig->driver == 'mysql') {
$dsn = "mysql:host={$dbconfig->host}; port={$dbconfig->port}; dbname={$dbconfig->name}";
$dbh = new PDO ( $dsn, $dbconfig->user, $dbconfig->password, array (PDO::ATTR_PERSISTENT => $dbconfig->persistant ) );
} elseif ($dbconfig->driver == 'mssql') {
//根据不同操作系统加载不同的PDOC驱动
if(strtolower(substr(PHP_OS,0,3))=='win') {
$dsn = "sqlsrv:server={$dbconfig->host},{$dbconfig->port}; Database={$dbconfig->name}";
$dbh = new PDO ( $dsn, $dbconfig->user, $dbconfig->password, array (PDO::ATTR_PERSISTENT => $dbconfig->persistant ) );
} else {
$dsn = "dblib:host={$dbconfig->host}:{$dbconfig->port}; dbname={$dbconfig->name}";
$dbh = new PDO ( $dsn, $dbconfig->user, $dbconfig->password);
}
}
try {
$dbh->setAttribute ( PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ );
$dbh->setAttribute ( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//mssql not exec
if ($dbconfig->driver == 'mysql') {
//2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll()
$dbh->setAttribute (PDO::ATTR_EMULATE_PREPARES, true);
$dbh->setAttribute ( PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true );
$dbh->exec ( "SET NAMES {$dbconfig->encoding}" );
} if (isset ( $dbconfig->strictMode ) and $dbconfig->strictMode == false)
$dbh->exec ( "SET @@sql_mode= ''" );
self::$_dbhs [$dbname] = $dbh;
return $dbh;
} catch ( PDOException $exception ) {
$errorstring = str_replace(array('60.28','60.28.195','ips','221','gps','172.16.31.10','330','gprs16'), array(), $exception->getMessage ());
// $app->error ( 'model.class.php '.$errorstring, __FILE__, __LINE__, $exit = true );
}
}
/**
* 对PDO的query进行封装
* @param <type> $sql
* @return <type>
*/
public function query($statement) {
// helper::datalog(json_encode($statement),'sql_');
$this->dbh = self::getDbh($this->dbname);
$dbh = $this->dbh;
if (is_array($statement)) {
$stmt = $dbh->prepare($statement[0]);
$stmt->execute($statement[1]);
} else
$stmt = $dbh->query($statement);
$this->app->querynum ++;
return $stmt;
}
/**
* 对PDO的exec进行封装
*/
public function exec($statement) {
helper::datalog(json_encode($statement),'execsql_');//Story #18073
$this->dbh = self::getDbh($this->dbname);
$dbh = $this->dbh;
if (is_array($statement)) {
$stmt = $dbh->prepare($statement[0]);
$stmt->execute($statement[1]);
} else
$stmt = $dbh->exec($statement);
$this->app->querynum ++;
return $stmt;
}
/**
* 返回最新插入到数据库的行的ID值
*/
public function lastInsertId() {
if ($this->getDriver() == 'mssql') {
$stmt = $this->query ( "SELECT SCOPE_IDENTITY() AS id" );
$result = $stmt->fetch();
return $result->id;
} else
return $this->dbh->lastInsertId();
}
/**
* 设置模块名:将类名中的model替换掉即为模块名。
* 没有使用$app->getModule()方法,因为它返回的是当前调用的模块。
* 而在一次请求中,当前模块的control文件很有可能会调用其他模块的model。
*
* @access protected
* @return void
*/
protected function getModuleName() {
$parentClass = get_parent_class($this);
$selfClass = get_class($this);
$className = $parentClass == 'model' ? $selfClass : $parentClass;
return strtolower(str_ireplace(array('ext', 'Model'), '', $className));
}
// insert into table_name (f1,f2[,..]) values(v1,v2[,..])
const tpl_sql_insert = 'insert into %s (%s) values(%s)';
// insert into table_name (f1,f2[,..]) values(v1,v2[,..])
const tpl_sql_replace = 'replace into %s (%s) values(%s)';
// select f1,f2[,..] from table_name [sql_conditions][sql_sort] [sql_limit]
const tpl_sql_select = 'select %s from %s %s %s %s';
// count count(*) from table_name [sql_conditions]
const tpl_sql_count = 'select count(*) from %s %s';
// update table_name set pair1,pair2 [sql_conditions]
const tpl_sql_update = 'update %s set %s %s';
// delete from table_names [sql_conditions] [sql_limit]
const tpl_sql_delete = 'delete from %s %s %s';
/**
* 查询多条记录,优先使用预处理
* @param <string|array> $conditions 默认空,例:array('id' => 1, 'name' => array('%Bob%','like'))
* @param <string> $sort 默认空,例:id, time desc
* @param <array|int> $limit 默认空,例:array(1, 5) 或 5
* @param <string> $fields 默认*
* @param <string> $table 表名,空才使用创建model对象时设置的默认表名
* @return <type>
*/
protected function findBy($conditions = null, $sort = null, $limit = null, $fields = '*', $table=null) {
$sql = $this->sql_select($conditions, $sort, $limit, $fields, $table);
$stmt = $this->query($sql);
return $stmt->fetchAll();
}
protected function findByMS($conditions = null, $sort = null, $limit = null, $fields = '*', $table=null) {
$table_name = $table ? $table : $this->name;
$sql = "select %s from ".$table_name;
if($conditions){
$sql.= " %s " ;
}
if($limit){
$sql = "SELECT * FROM ( ".$sql.") as tmp ";
$fields .= ", ROW_NUMBER() OVER ( %s ) row ";
$sql.= " %s " ;
}
$sql = $this->sql_select_bymssql($sql,$conditions, $sort, $limit, $fields);
$stmt = $this->query($sql);
return $stmt->fetchAll();
}
protected function count($conditions = null, $table=null) {
$table_name = $table ? $table : $this->name;
$sql_conditions = empty($conditions) ? '' : $this->sql_conditions($conditions);
if (is_array($sql_conditions))
$sql = array(sprintf(self::tpl_sql_count, $table_name, $sql_conditions[0]),
$sql_conditions[1]);
else
$sql = sprintf(self::tpl_sql_count, $table_name, $sql_conditions);
$stmt = $this->query($sql);
$count = $stmt->fetchColumn();
return $count;
}
/**
* 经过封装的分页查询,可以设置自动取总数
* @param <Page> $page 封装的Page对象
* @param <string|array> $conditions 默认空,例:array('id' => 1, 'name' => array('%Bob%','like'))
* @param <string> $fields 默认*
* @param <string> $table 表名,空才使用创建model对象时设置的默认表名
* @return <type>
*/
protected function findPage($page, $conditions = null, $fields = '*', $table="") {
// 自动取总数
if ($page->autoCount) {
$totalCount = $this->count($conditions,$table);
$page->totalCount = $totalCount;
}
if ($page->totalCount){
$dbdriver = $this->getDriver();
if ($dbdriver == 'mssql') {
$page->setResult($this->findByMS($conditions, $page->orderBy, array(($page->pageNo - 1) * $page->pageSize, $page->pageNo * $page->pageSize), $fields, $table));
}else{
$page->setResult($this->findBy($conditions, $page->orderBy, array($page->getFirst() - 1, $page->pageSize), $fields, $table));
}
}
return $page;
}
/**
* 加载某一个模块的model文件。
* 防止model中重复实例出现冲突bug 同时fixed bug#2976 @2013-08-27
* @param string $moduleName 模块名字,如果为空,则取当前的模块名作为model名。
* @access public
* @return void
*/
protected function loadModel($moduleName = '') {
/* 如果没有指定module名,则取当前加载的模块的名作为model名。*/
if(empty($moduleName)) $moduleName = $this->moduleName;
if(isset($this->modelobj[$moduleName]) && $this->modelobj[$moduleName]){
return $this->modelobj[$moduleName];
}
$classNameExt = $this->app->getModuleExt() . $moduleName. 'model';
$modelClass = class_exists($classNameExt) ? $classNameExt : $moduleName . 'model';
if(!class_exists($modelClass)) $this->app->error(" The model $modelClass not found", __FILE__, __LINE__, $exit = true);
$this->modelobj[$moduleName] = $this->$moduleName = new $modelClass();
return $this->$moduleName;
}
/**
* 获取单条记录,优先使用预处理
* @param <string|array> $conditions 默认空,例:array('id' => 1, 'name' => array('%Bob%','like'))
* @param <string> $sort 默认空,例:id, time desc
* @param <string> $fields 默认*
* @param <string> $table 表名,空才使用创建model对象时设置的默认表名
* @return <type>
*/
protected function findUnique($conditions = null, $sort = null, $fields = '*', $table=null) {
$sql = $this->sql_select($conditions, $sort, 1, $fields, $table);
$stmt = $this->query($sql);
return $stmt->fetch();
}
/**
* 更新记录,优先使用预处理
* @param <array> $record 更新的数据数组
* @param <String|array> $conditions 默认空,例:array('id' => 1, 'name' => array('%Bob%','like'))
* @param <string> $table 表名
* @return <type>
*/
protected function update($record, $conditions=null, $table=null) {
$table_name = $table ? $table : $this->name;
if (!empty($record) && is_array($record)) {
// 没有条件,取record中的主键
if (empty($conditions) && !empty($record[$this->pk]))
$conditions = array($this->pk => $record[$this->pk]);
if (empty($conditions))
$this->app->error ( '条件和数据的主键不能同时为空', __FILE__, __LINE__, $exit = true );
$sql_conditions = $this->sql_conditions($conditions);
$pairs = array();
$dbdriver = $this->getDriver();
foreach ($record as $field => $val) {
if ($dbdriver == 'mssql') {
$pairs[] = "[{$field}]=?";
}else{
$pairs[] = "`{$field}`=?";
}
$values[] = $val;
}
$pairs = implode(',', $pairs);
if (is_array($sql_conditions))
$sql = array(sprintf(self::tpl_sql_update, $table_name, $pairs, $sql_conditions[0]),
array_merge($values, $sql_conditions[1]));
else
$sql = array(sprintf(self::tpl_sql_update, $table_name, $pairs, $sql_conditions),
$values);
// helper::datalog(json_encode($sql),'updatesql_');
$row = $this->exec($sql);
return $row->rowCount();
}
return 0;
}
protected function updatesql($record, $conditions=null, $table=null) {
$table_name = $table ? $table : $this->name;
if (!empty($record) && is_array($record)) {
// 没有条件,取record中的主键
if (empty($conditions) && !empty($record[$this->pk]))
$conditions = array($this->pk => $record[$this->pk]);
if (empty($conditions))
$this->app->error ( '条件和数据的主键不能同时为空', __FILE__, __LINE__, $exit = true );
$sql_conditions = $this->sql_conditions($conditions);
$pairs = array();
foreach ($record as $field => $val) {
$pairs[] = "{$field}=?";
$values[] = $val;
}
$pairs = implode(',', $pairs);
if (is_array($sql_conditions))
$sql = array(sprintf(self::tpl_sql_update, $table_name, $pairs, $sql_conditions[0]),
array_merge($values, $sql_conditions[1]));
else
$sql = array(sprintf(self::tpl_sql_update, $table_name, $pairs, $sql_conditions),
$values);
helper::datalog(json_encode($sql),'updatesql_');
$row = $this->exec($sql);
return $row->rowCount();
}
return 0;
}
/**
* 插入记录,优先使用预处理
* @param <array> $record 插入的数据数组
* @param <string> $table 表名
* @return <type>
*/
protected function insert($record, $table=null,$replace=false) {
$table_name = $table ? $table : $this->name;
$sql_method = $replace ? self::tpl_sql_replace : self::tpl_sql_insert;
if (!empty($record) && is_array($record)) {
$dbdriver = $this->getDriver();
if ($dbdriver == 'mssql') {
$columns = '['.implode('],[', array_keys($record)).']';
}else{
$columns = '`'.implode('`,`', array_keys($record)).'`';
}
$values = array_fill(0, count($record), "?");
$values = implode(',', $values);
$sql = array(sprintf($sql_method, $table_name, $columns, $values),
array_values($record));
$this->exec($sql);
// helper::datalog(json_encode($sql),'insertsql_');
return $this->lastInsertId();
}
return 0;
}
protected function insertsql($record, $table=null,$replace=false) {
$table_name = $table ? $table : $this->name;
$sql_method = $replace ? self::tpl_sql_replace : self::tpl_sql_insert;
if (!empty($record) && is_array($record)) {
$columns = implode(',', array_keys($record));
$values = array_fill(0, count($record), "?");
$values = implode(',', $values);
$sql = array(sprintf($sql_method, $table_name, $columns, $values),
array_values($record));
helper::datalog(json_encode($sql),'insertsql_');
$this->exec($sql);
return $this->lastInsertId();
}
return 0;
}
/**
* 删除记录,优先使用预处理
* @param <string|array> $conditions 默认空,例:array('id' => 1, 'name' => array('%Bob%','like'))
* @param <array|int> $limit 默认空,例:array(1, 5) 或 5
* @param <string> $table 表名,空才使用创建model对象时设置的默认表名
* @return <type>
*/
protected function delete($conditions, $limit=null, $table=null) {
if (empty($conditions))
$this->app->error ( '删除操作,条件不能为空', __FILE__, __LINE__, $exit = true );
$table_name = $table ? $table : $this->name;
$sql_conditions = empty($conditions) ? '' : $this->sql_conditions($conditions);
if (is_array($sql_conditions))
$sql = array(sprintf(self::tpl_sql_delete ,
$table_name,$sql_conditions[0],$this->limit_string($limit)), $sql_conditions[1]);
else
$sql = sprintf(self::tpl_sql_delete ,
$table_name,$sql_conditions,$this->limit_string($limit));
// helper::datalog(json_encode($sql),'deletesql_');
return $this->exec($sql);
}
private function sql_select($conditions = null, $sort = null, $limit = null, $fields = '*', $table=null) {
$table_name = $table ? $table : $this->name;
// 排序
$sql_sort = $sort ? " order by {$sort}" : '';
$dbdriver = $this->getDriver();
if ($dbdriver == 'mssql') {
$top = $limit ? " top $limit " : '';
$fields = $top . " " . $fields;
}else{
$sql_limit = $this->limit_string($limit);
}
// 范围
// 条件
$sql_conditions = empty($conditions) ? '' : $this->sql_conditions($conditions);
if (is_array($sql_conditions))
return array(sprintf(self::tpl_sql_select,
$fields, $table_name, $sql_conditions[0], $sql_sort, $sql_limit),
$sql_conditions[1]);
else
return sprintf(self::tpl_sql_select,
$fields, $table_name, $sql_conditions, $sql_sort, $sql_limit);
}
private function limit_string($limit) {
if (is_array($limit)) {
list($offset, $length) = $limit;
} else {
$length = $limit;
$offset = null;
}
return empty($length) ? '' : $this->sql_limit($length, $offset);
}
private function sql_limit($length, $offset = null) {
$sql = '';
if (!empty($offset)) {
$sql = sprintf(' limit %d, %d',
(int) $offset, empty($length) ? 50000 : (int) $length);
} else if (!empty($length)) {
$sql = " limit " . (int) $length;
}
return $sql;
}
private function top_string($top) {
if (is_array($top)) {
list($offset, $length) = $top;
} else {
$length = $top;
$offset = null;
}
return empty($length) ? '' : $this->sql_top($length, $offset);
}
private function sql_top($length, $offset = null) {
$sql = '';
if (!empty($offset)) {
$offset = (int) $offset + 1;
$length = empty($length) ? 50000 : (int) $length;
$sql = sprintf(' where row between %d and %d',
$offset, $offset + $length - 1);
} else if (!empty($length)) {
$sql = " where row between 0 and " . (int) $length;
}
return $sql;
}
private function sql_conditions($conditions = null) {
if (empty($conditions))
return '';
$sql = ' WHERE ';
if (is_string($conditions))
return $sql . $conditions;
else if (is_array($conditions)) {
// 处理带后缀的条件
$join_char = ''; // 第一个条件前面 没有 and 连接符
foreach ($conditions as $field => $cond ) {
if (is_string($field)) {
// 格式化带后缀的条件
list($field, $cond) = self::formatCond($field, $cond);
// 支持 like / or 等操作 例如: 'name' => array('%Bob%','like')
$op_char = '=';
if (is_array ( $cond )) {
$value = array_shift ( $cond );
// if $value is array , will use "in" [] opchar
if (is_array ( $value ))
$value = '[' . implode ( ',', $value ) . ']';
$_op_char = array_shift ( $cond );
if (! empty ( $_op_char ) && is_string ( $_op_char ))
$op_char = $_op_char;
} else {
$value = $cond;
}
// 过滤值
$values [] = $value;
$sql .= "{$join_char} {$field} {$op_char} ? ";
} else if (is_string($cond)) {
$sql .= "{$join_char} {$cond} ";
}
$join_char = ' and ';
}
return array($sql, $values);
}
return '';
}
/**
* 根据后缀格式化查询条件
* @return Array array(字段,操作符,值)
*/
public static function formatCond($field, $cond) {
$key = $field;
$value = $cond;
if (!is_array($cond) && strlen($field) > 3) {
$key = substr($field, 0, -3);
$suffix = substr($field, -3);
$op = self::$SUFFIX_OPERATOR[$suffix];
if ($op)
$value = array($cond, $op);
else
$key = $field;
}
return array($key, $value);
}
/**
* 经过封装的分页查询,可以设置自动取总数
* @param <Page> $page 封装的Page对象
* @param <string> $sql
*/
protected function findPageBySql($page, $sql, $conditions = null, $field = '*',$table=null) {
$sql_conditions = empty ( $conditions ) ? '' : $this->sql_conditions ( $conditions );
// 自动取总数
if ($page->autoCount) {
$sqlCount = $sql." %s " ;
if (is_array($sql_conditions))
$sqlCount = array (sprintf ( $sqlCount, "count(*)", $sql_conditions [0] ), $sql_conditions [1] );
else
$sqlCount = sprintf($sqlCount,"count(*)",$sql_conditions);
$stmt = $this->query ( $sqlCount );
$totalCount = $stmt->fetchColumn ();
$page->totalCount = $totalCount;
}
if ($page->totalCount) {
$page->setResult($this->findBySql($sql,$conditions, $page->orderBy, array($page->getFirst() - 1, $page->pageSize), $field, $table));
}
return $page;
}
/**
* 经过封装的sql查询,
* @param <string> $sql
*/
protected function findBySql( $sql, $conditions = null,$sort = null, $limit = null, $field = '*') {
$dbdriver = $this->getDriver();
if ($dbdriver == 'mssql') {
$sql .= " %s ";
if($limit){
$field .= ", ROW_NUMBER() OVER ( %s ) row ";
$sql = "SELECT * FROM ( ".$sql.") as tmp %s" ;
}
$sql = $this->sql_select_bymssql($sql,$conditions, $sort, $limit, $field);
}else{
$sql.=" %s %s %s";
$sql = $this->sql_select_bysql($sql,$conditions, $sort, $limit, $field);
}
helper::datalog(json_encode($sql),'execsql_');//Story #18073
$stmt = $this->query ( $sql );
$record = $stmt->fetchAll ();
return $record;
}
/**
* 执行sql获取结果集
* @param string $sql
* @return ArrayIterator
*/
protected function queryBySql($sql) {
if (empty ( $sql )) {
return array ();
}
$stmt = $this->query ( $sql );
$record = $stmt->fetchAll ();
return $record;
}
private function sql_select_bysql($sql,$conditions = null, $sort = null, $limit = null, $fields = '*') {
// 排序
$sql_sort = $sort ? " order by {$sort}" : '';
// 范围
$sql_limit = $this->limit_string($limit);
// 条件
$sql_conditions = empty($conditions) ? '' : $this->sql_conditions($conditions);
if (is_array($sql_conditions))
return array(sprintf($sql,
$fields, $sql_conditions[0], $sql_sort, $sql_limit),
$sql_conditions[1]);
else
return sprintf($sql,
$fields, $sql_conditions, $sql_sort, $sql_limit);
}
private function sql_select_bymssql($sql,$conditions = null, $sort = null, $limit = null, $fields = '*') {
// 排序
$sql_sort = $sort ? " order by {$sort}" : '';
// 范围
$sql_top = $this->top_string($limit);
// 条件
$sql_conditions = empty($conditions) ? '' : $this->sql_conditions($conditions);
$fields = sprintf($fields,$sql_sort);
if (is_array($sql_conditions))
return array(sprintf($sql,
$fields, $sql_conditions[0], $sql_top),
$sql_conditions[1]);
else
return sprintf($sql,
$fields, $sql_conditions, $sql_top);
}
}
class Page {
public $pk = "id";
//-- 分页参数 --//
public $pageNo;
public $pageSize;
/** 排序,例:id, time desc */
public $orderBy;
public $autoCount;
//-- 返回结果 --//
public $result;
public $totalCount = 0;
/**
* 构造函数
* @param <type> $pageNo 当前页,>=1默认1
* @param <type> $pageSize 页大小,>0默认25
* @param <type> $autoCount 是否自动取总数
*/
public function __construct($pageNo = 1, $pageSize = 25, $autoCount = true) {
$this->pageNo = $pageNo < 1 ? 1 : (int) $pageNo;
$this->pageSize = $pageSize > 0 ? (int) $pageSize : 25;
$this->autoCount = $autoCount;
}
/**
* 根据pageNo和pageSize计算当前页第一条记录在总结果集中的位置,序号从1开始.
*/
public function getFirst() {
return (($this->pageNo - 1) * $this->pageSize) + 1;
}
/**
* 设置结果,做一些附加处理
*/
public function setResult($result) {
$this->result = $result;
}
}
/**
* 查询
*/
class ActionQuery {
public $fields ;
public $conditions;
public $orderBys;
/**
* 构造函数
* @param <type> $fields 需返回的字段列表 :id,title,nick,pic_url
* @param <type> $conditions 查询条件
* @param <type> $orderBys
*/
public function __construct() {
$conditions = array ();
$orderBys = '';
// $orderBys = array ();
}
/**
* 添加查询条件
*/
public function addCondition($field, $value, $operator = "=") {
if ($operator == "=") {
$this->conditions [$field] = $value;
} else {
$this->conditions [$field] = array ($value, $operator );
}
}
/**
* 添加排序条件
*/
public function addOrderbys($field, $order) {
$this->orderBys = $field.' '.$order;
// $this->$orderBys = array ($field, $order );
}
public function toString(){
$sql = ' ';
$conditions = $this->conditions;
if (is_string($conditions)){
return $sql . $conditions;
}
elseif(is_array($conditions)){
$join_char = ''; // 第一个条件前面 没有 and 连接符
foreach ( $conditions as $field => $cond ) {
// 格式化带后缀的条件
list($field, $cond) = model::formatCond($field, $cond);
// 支持 like / or 等操作 例如: 'name' => array('%Bob%','like')
$op_char = '=';
if (is_array ( $cond )) {
$value = array_shift ( $cond );
// if $value is array , will use "in" [] opchar
if (is_array ( $value ))
$value = '[' . implode ( ',', $value ) . ']';
$_op_char = array_shift ( $cond );
if (! empty ( $_op_char ) && is_string ( $_op_char ))
$op_char = $_op_char;
if(strpos($op_char,"not")>-1){
$value = "not in ('" . str_replace(',', "','", str_replace(' ', '',$value)) . "')" ;
}elseif(strpos($op_char,"in")>-1){
$value = "in ('" . str_replace(',', "','", str_replace(' ', '',$value)) . "')" ;
}else{
$value= $op_char." '".$value."'";
}
}elseif(strpos($cond,"null")>-1){
if(strpos($cond,"is")<0){
$value = " is ".$cond ;
}else{
$value = $cond ;
}
}elseif(strpos($cond,",")>-1||preg_match("/not |in /",$field)){
if(preg_match("/in /",$field)){
$value = " ('" . str_replace(',', "','", str_replace(' ', '',$cond)) . "')" ;
}else{
$value = "IN ('" . str_replace(',', "','", str_replace(' ', '',$cond)) . "')" ;
}
}elseif (preg_match("/>|<|<>/",$cond)) {
$value = $cond;
}else {
$value = " = '".$cond."'";
}
$sql .= "{$join_char} {$field} {$value} ";
$join_char = ' and ';
}
return $sql;
}
}
}<file_sep>var smartwin;//扫描窗体
var sid = '';
var store_org_edt =new Ext.data.Store({
proxy:new Ext.data.HttpProxy({url:'../inside.php?t=json&m=org&f=search',method:"POST"}),
reader:new Ext.data.JsonReader({
tatalProperty:'',
root:'data'
},[
{name:'orgcode'},
{name:'name'}
]),
baseParams: {},
listeners: {
'load' : function(){
}
}
});
store_org_edt.load();
//主容器
var toppanel_add_itemlis = new Ext.FormPanel({
region:"center",
bodyStyle:'padding: 10px',
border:false,
items:[
{xtype:'textfield',id:'name',name:'name',width:180,fieldLabel:'角色名'},
{xtype:'combo',id:'orgname',name:'orgname',width:180,fieldLabel:'归属',mode:'local',editable:false,triggerAction:'all',displayField:'name',valueField:'orgcode',store:store_org_edt}
],
buttons:[{text: '确定',
handler : function(){
var _form = this.ownerCt.ownerCt.getForm();
if (sid!=''){
_form.submit({url:'../inside.php?t=json&m=role&f=update',
success: sFn,
failure: fFn,
params: { id:sid,
name:Ext.getCmp("name").getValue(),
orgcode:Ext.getCmp("orgname").getValue()
},
waitMsg:'Saving Data...'});
}else{
_form.submit({url:'../inside.php?t=json&m=role&f=add',
success: sFn,
failure: fFn,
params: { name:Ext.getCmp("name").getValue(),
orgcode:Ext.getCmp("orgname").getValue()
},
waitMsg:'Saving Data...'});
}
smartwin.hide();
}},{text: '关闭',
handler : function(){
smartwin.hide();
}
}]
});
///////////////////////////////
//弹出窗体
///////////////////////////////
if(!smartwin){//主窗体
smartwin = new Ext.Window({
layout:"border",
width:380,
height:200,
title:'角色维护',
closeAction:'hide',
plain: true,
items:[toppanel_add_itemlis]
});
}
//初始化界面
function showaddlistform(id)
{
if (id){
sid = id;
}else{
sid = '';
}
if (sid==''){
Ext.getCmp("name").setValue('');
Ext.getCmp("orgname").setValue('');
}
//查该角色有权使用的资源
smartwin.show();
}
function sFn(d)
{
store_login.removeAll();
store_login.load();
store_org_edt.load();
sid ='';
}
function fFn(d)
{
sid ='';
store_login.removeAll();
store_login.load();
store_org_edt.load();
} <file_sep>Ext.QuickTips.init();
Ext.form.Field.prototype.msgTarget = "side";
var simple = new Ext.FormPanel({
height : 300,
width : 500,
defaultType : "textfield",
labelWidth : 95,
defaults : {
width : 200
},
baseCls : "x-plane",
items : [{
id:'username',
fieldLabel : "用户名",
name : "username",
allowBlank : false,
enableKeyEvents:true,
listeners: {
specialkey: function (textfield, e) {
if (e.getKey() == Ext.EventObject.ENTER) {
Ext.getCmp("password").focus('', 50); //100 表示延时
}
}
}
}, {
fieldLabel : "密 码",
name : "password",
id:'<PASSWORD>',
inputType : "password",
allowBlank : false,
enableKeyEvents:true,
listeners: {
specialkey: function (textfield, e) {
if (e.getKey() == Ext.EventObject.ENTER) {
dologin();
}
}
}
},{
xtype:"combo",
fieldLabel:"Cookie有效期",
width:200,
allowBlank:false,
typeAhead: true,
triggerAction: 'all',//选择模式
lazyRender:true,
id:"cookieid",
//hiddenname:"ctype",
value:0,
mode: 'local',
emptyText:'请选择Cookie有效期',
store: new Ext.data.ArrayStore({
id: 0,
fields: [
'timeId',
'displayText'
],
data: [[0, '浏览器进程'], [3600, '一小时'], [86400, '一天']]
}),
valueField: 'timeId',
displayField: 'displayText'
},{
xtype:"checkbox",
id:"saveinfo",
hideLabel:true,
boxLabel:"保存账号密码",
checked:true,
name:"saveinfo",
inputValue:"1"
}],
buttons : [{
text : "登录",
type : "submit",
// 按钮点击事件
handler : function() {
dologin();
}
}, {
text : "重置",
type : "reset",
handler : function() {
// 清除信息
simple.form.reset();
}
}]
});
function dologin(){
if (simple.form.isValid()) {
Ext.MessageBox.show({
title : "正在登录....",
progress : true,
width : 300
});
// 设置延迟加载
var f = function(v) {
return function() {
var i = v / 10;
Ext.MessageBox.updateProgress(i, '登录,加载中...');
};
};
for (var i = 0; i < 10; i++) {
setTimeout(f(i), i * 200);
}
simple.form.doAction('submit', {
url : "/inside.php?t=json&m=login&f=login",//一个Servlet路径 验证使用是否存在
method : "post",
params: { cookietime:Ext.getCmp("cookieid").getValue()},
//params : "param:add",
success : function(form, action) {
//console.log(action.result.info);
Ext.MessageBox.alert("信息",action.result.info.message);
if(action.result.info.id > 0) {
if( Ext.getCmp('saveinfo').getValue() == 1 ) {
setCookie('adminUsername',Ext.getCmp('username').getValue());
setCookie('adminPassword',Ext.getCmp('password').getValue());
}
else {
deleteCookie('adminUsername');
deleteCookie('adminPassword');
}
window.location.href = '/index.html';
}
/*if (action.result.msg == 'ok') {
// 加载到首页
document.location = 'index.jsp';
} else {
Ext.MessageBox.alert("信息", action.result.msg);
}
*/
}
});
}
}
var getName = getCookie('adminUsername');
var getPass = getCookie('adminPassword');
if (getName != null) {
Ext.getCmp('username').setValue(getName);
Ext.getCmp('password').setValue(getPass);
}
else {
Ext.getCmp('username').setValue('');
Ext.getCmp('password').setValue('');
}
function setCookie(name, value)
{
var argv = setCookie.arguments;
var argc = setCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
if(expires!=null)
{
var LargeExpDate = new Date ();
LargeExpDate.setTime(LargeExpDate.getTime() + (expires*1000*3600*24));
}
document.cookie = name + "=" + escape (value)+((expires == null) ? "" : ("; expires=" +LargeExpDate.toGMTString()));
}
function getCookie(Name)
{
var search = Name + "=";
if(document.cookie.length > 0)
{
offset = document.cookie.indexOf(search);
if(offset != -1)
{
offset += search.length;
end = document.cookie.indexOf(";", offset);
if(end == -1) end = document.cookie.length;
return unescape(document.cookie.substring(offset, end));
}
else return "";
}
}
function deleteCookie(name)
{
var expdate = new Date();
expdate.setTime(expdate.getTime() - (86400 * 1000 * 1));
setCookie(name, "", expdate);
} <file_sep><?php
/**
* 资源控制类
* @author liuzhi
*/
class source extends baseControl
{
public function __construct()
{
//global $common;
parent::__construct();
$this->myAdmin = $this->app->myAdmin;
}
/**
* 搜索 默认搜全部
* @author liuzhi
* @since 2013/12/31
*/
public function search()
{
$params = helper::filterParams();
$wheresql = ' 1 and a.is_del=0 ';
$name = $params['name'] ? $params['name'] : '';
if ($name!=''){
$wheresql .= " and a.source_name like '%$name%' ";
}
$data = $this->source->search($wheresql);
$data = $this->loadModel('common')->ToTreeModel($data,'source_code');
$result = array_merge($data);
echo json_encode($result);
}
/**
* 检索全部资源,下拉列表用
* @author liuzhi
* @since 2013/12/31
*/
public function searchAll()
{
$wheresql = " 1 and a.is_del=0 and a.type=1 group by a.source_code";
$data = $this->source->searchAll($wheresql);
foreach($data as $k=>$val){
$num = 1;
if(!empty($val->source_code))
{
$num = count(str_split($val->source_code,3));
}
$data[$k]->edited_name = str_repeat('……',$num-1).$val->source_name;
}
array_unshift($data,array('source_code'=>0,'edited_name'=>'顶级资源','source_name'=>'顶级资源'));
$this->assign('data',$data);
$this->display();
}
/**
* 添加资源
* @author liuzhi
* @since 2013/12/31
*/
public function add(){
$params = helper::filterParams();
$parentId = $params['parent']?$params['parent']:0;
$uid = $params['uid'] ? $params['uid'] : $this->myAdmin->id;
$uname = $this->myAdmin->true_name;
$setarr = array(
'source_code' => $this->getSourceCode($parentId),
'url' => $params['url'],
'source_name' => $params['name'],
'type' =>$params['type'],
'is_display' =>isset($params['is_display']) && $params['is_display'] != '' ? $params['is_display'] : null,//Story #21651
'creator_id' =>$uid,
'last_operator' =>$uname,
'sort' =>$params['priority'],
'createtime' =>helper::nowTime(),
'status' => $params['status'],
'is_del' => 0
);
$addNo = $this->source->add($setarr,'ecsa_sys_source');
if($addNo) {
$output = array('success'=>true,'msg'=>'成功');
}else {
$output = array('success'=>false,'msg'=>'失败');
}
echo json_encode($output);
}
/**
* 更新,修改资源的信息
* @author liuzhi
* @since 2013/11/11
**/
public function update()
{
$params = helper::filterParams();
$parentCode = $params['parent']?$params['parent']:0;
$uname = $this->myAdmin->true_name;
$idds = array(
'id' => $params['id']
);
$source_code = $this->getSourceCode($parentCode,$params['id'],$params['source_code']);
$setarr = array(
'source_code' => $source_code,
'source_name' => $params['name'],
'url' => $params['url'],
'sort' =>$params['priority'],
'status' => $params['status'],
'type' =>$params['type'],
'is_display' =>isset($params['is_display']) && $params['is_display'] != '' ? $params['is_display'] : null,//Story #21651
'last_operator' =>$uname
);
$result_s = $this->source->update($idds,$setarr,'ecsa_sys_source');
//递归修改当前资源的子资源
$result_chil = $this->loadModel('common')->updateCode($params['source_code'],$source_code,'ecsa_sys_source','source_code');
if($result_s) {
$output = array('success'=>true,'msg'=>'成功');
}else {
$output = array('success'=>false,'msg'=>'失败');
}
echo json_encode($output);
}
/**
* 删除,修改资源删除状态为1
* @author liuzhi
* @since 2013/11/11
**/
public function delete()
{
$params = helper::filterParams();
$uname = $this->myAdmin->true_name;
if(!$this->source->checkSourceHaveChild($params['source_code'])){
$result_s = $this->source->update(
array('id'=>$params['id']),
array('is_del'=>'1','last_operator' =>$uname),
'ecsa_sys_source');
$result_r = $this->source->update(
array('source_id'=>$params['id']),
array('is_del'=>'1','last_operator' =>$uname),
'ecsa_sys_role_source');
if($result_s) {
$output = array('success'=>true,'msg'=>'成功');
}else {
$output = array('success'=>false,'msg'=>'失败');
}
}else{
$output = array('success'=>false,'msg'=>'删除失败,该资源有子资源');
}
echo json_encode($output);
}
/**
* 新增时获取一个source_code
* @author liuzhi
* @since 2013/12/17
**/
public function getSourceCode($parentId,$source_id='',$source_code=''){
if($parentId == 0)
{
//如果$parentId = 0 取长度为4的最大值
$fields = " max(a.source_code) as max_oid,count(a.id) as total,
(select count(*) from ecsa_sys_source where id='$source_id' and LENGTH(source_code) = 3) as same_flg ";
$wheresql = " LENGTH(a.source_code) = 3 ";
$data = $this->source->search($wheresql,$fields);
if($data[0]->same_flg > 0){
return $source_code;
}else if($data[0]->total > 0){
$max = $data[0]->max_oid;
$_max = substr($max,0,strlen($max)-3);
$__max = substr($max,-3);//截取后3位进行操作
return $_max.sprintf('%03d',intVal($__max)+1);
}
return '101';
}
else
{
//如果$parentId != 0 取长度在原有的长度加3的最大值
$length = strlen($parentId) + 3;
$fields = " max(a.source_code) as max_oid,count(a.id) as total,
(select count(*) from ecsa_sys_source where id='$source_id' and source_code like '$parentId%') as same_flg ";
$wheresql = " LENGTH(a.source_code) = '$length' AND a.source_code like '$parentId%' ";
$data = $this->source->search($wheresql,$fields);
if($data[0]->same_flg > 0){
return $source_code;
}else if($data[0]->total > 0){
$max = $data[0]->max_oid;
$_max = substr($max,0,strlen($max)-3);
$__max = substr($max,-3);//截取后3位进行操作
return $_max.sprintf('%03d',intVal($__max)+1);
}
return $parentId.'001';
}
}
}
<file_sep>Ext.QuickTips.init();
/*
登录界面
检测登录状态,如果不成功就跳到登录界面。
*/
var app_login_simple = new Ext.FormPanel({
height : 300,
width : 500,
defaultType : "textfield",
labelWidth : 95,
defaults : {
width : 200
},
baseCls : "x-plane",
items : [{
id:'app_login_username',
fieldLabel : "用户名",
name : "app_login_username",
allowBlank : false,
enableKeyEvents:true,
listeners: {
specialkey: function (textfield, e) {
if (e.getKey() == Ext.EventObject.ENTER) {
Ext.getCmp("app_login_password").focus('', 50); //100 表示延时
}
}
}
}, {
fieldLabel : "密 码",
name : "app_login_password",
id:'app_login_password',
inputType : "password",
allowBlank : false,
enableKeyEvents:true,
listeners: {
specialkey: function (textfield, e) {
if (e.getKey() == Ext.EventObject.ENTER) {
app_login_dologin();
}
}
}
},{
xtype:"combo",
fieldLabel:"Cookie有效期",
width:200,
allowBlank:false,
typeAhead: true,
triggerAction: 'all',//选择模式
lazyRender:true,
id:"app_login_cookieid",
//hiddenname:"ctype",
value:0,
mode: 'local',
emptyText:'请选择Cookie有效期',
store: new Ext.data.ArrayStore({
id: 0,
fields: [
'timeId',
'displayText'
],
data: [[0, '浏览器进程'], [3600, '一小时'], [86400, '一天']]
}),
valueField: 'timeId',
displayField: 'displayText'
},{
xtype:"checkbox",
id:"app_login_saveinfo",
hideLabel:true,
boxLabel:"保存账号密码",
checked:true,
name:"app_login_saveinfo",
inputValue:"1"
}],
buttons : [{
text : "登录",
type : "submit",
// 按钮点击事件
handler : function() {
app_login_dologin();
}
}, {
text : "重置",
type : "reset",
handler : function() {
// 清除信息
app_login_simple.form.reset();
}
}]
});
function app_login_dologin(){//执行登录
if (app_login_simple.form.isValid()) {
Ext.MessageBox.show({
title : "正在登录....",
progress : true,
width : 300
});
// 设置延迟加载
var f = function(v) {
return function() {
var i = v / 10;
Ext.MessageBox.updateProgress(i, '登录,加载中...');
};
};
for (var i = 0; i < 10; i++) {
setTimeout(f(i), i * 200);
}
app_login_simple.form.doAction('submit', {
url : "/inside.php?t=json&m=login&f=login",//一个Servlet路径 验证使用是否存在
method : "post",
params: { cookietime:Ext.getCmp("app_login_cookieid").getValue(),password:Ext.getCmp('app_login_password').getValue(),username:Ext.getCmp('app_login_username').getValue()
},
//params : "param:add",
success : function(form, action) {
//console.log(action.result.info);
Ext.MessageBox.alert("信息",action.result.info.message);
if(action.result.info.id > 0) {
//console.log(action.result.info);
if( Ext.getCmp('app_login_saveinfo').getValue() == 1 ) {
_c_fun_setCookie('adminUsername',Ext.getCmp('app_login_username').getValue());
_c_fun_setCookie('adminPassword',Ext.getCmp('app_login_password').getValue());
}
else {
_c_fun_deleteCookie('adminUsername');
_c_fun_deleteCookie('adminPassword');
}
window.location.href = tourl;
}
}
});
}
}
var app_login_win = new Ext.Window({
title : "<center>用户登录</center>",
width : 350,//300,
height : 170,//150,
bodyStyle : "padding:5px;",
plane : true,
layout : "fit",
closable : false,
items : app_login_simple,
collapsible : false,// 设置是否可则叠
expandOnShow : false,
maximizable : false,// 禁止最大化
buttonAlign : "center",
listeners: {
"show": function() {
Ext.getCmp("app_login_username").focus('', 100); //100 表示延时
}
}
});
/*function app_login_show_loginfrom(url='../index.html'){
tourl = url;
app_login_win.show();
var getName = _c_fun_getCookie('adminUsername');
var getPass = _c_fun_getCookie('adminPassword');
if (getName != null) {
Ext.getCmp('app_login_username').setValue(getName);
Ext.getCmp('app_login_password').setValue(getPass);
}
else {
Ext.getCmp('app_login_username').setValue('');
Ext.getCmp('app_login_password').setValue('');
}
}*/<file_sep>var add_win; //添加窗口
var add_update_id = ''; //判断是添加还是修改
var add_form_panel = new Ext.form.FormPanel({
region: 'center',
hideLabels: true,
bodyStyle: 'padding: 10px',
height: 60,
items: [{ // BOSSSM-391 by csj 2016/2/25
xtype: 'compositefield',
items: [{
xtype: 'displayfield',
value: '用户类型:'
},
new Ext.form.ComboBox({
id: 'type',
name: 'type',
hiddenName: 'type',
width: 200,
mode: 'local',
triggerAction: 'all',
forceSelection: true,
editable: false,
displayField: 'name',
valueField: 'value',
store: new Ext.data.SimpleStore({
fields: ['name', 'value'],
data: [
['会员', '1'],
['员工', '2'],
]
}),
//BOSSOPS-1164
listeners: {
select: function(combo, record, index) {
if (index == 2) {
Ext.getCmp('com_user').hide();
} else {
Ext.getCmp('com_user').show();
}
if (index == '0') {
Ext.getCmp('com_must').show();
} else {
Ext.getCmp('com_must').hide();
}
}
},
}), {
xtype: 'displayfield',
value: ' <font color=red>*</font>'
}
]
}, { // 第一行
xtype: 'compositefield',
items: [{
xtype: 'displayfield',
value: '用户名:'
}, {
xtype: 'textfield',
id: 'u_user_name',
width: 200,
style: 'margin-left :12px;'
}, {
xtype: 'displayfield',
style: 'margin-left : 15px;',
value: ' <font color=red>*</font>'
}]
}, { // 第二行
xtype: 'compositefield',
items: [{
xtype: 'displayfield',
value: '密 码:',
id: 'old_pass_word',
}, {
inputType: 'password',
xtype: 'textfield',
id: 'u_old_pass',
width: 200,
style: 'margin-left :20px;'
}, {
xtype: 'displayfield',
id: 'old_pwd',
style: 'margin-left : 23px;',
value: ' <font color=red>*</font>'
}]
}, { // 第三行
xtype: 'compositefield',
items: [{
xtype: 'displayfield',
value: '确认密码:',
id: 'new_pass_word',
}, {
inputType: 'password',
xtype: 'textfield',
id: 'u_new_pass',
width: 200
}, {
xtype: 'displayfield',
id: 'new_pwd',
style: 'margin-left : 3px;',
value: ' <font color=red>*</font>'
}]
}, { // 第四行
xtype: 'compositefield',
id: 'com_user', //BOSSOPS-1164
items: [{
xtype: 'displayfield',
value: '姓 名:'
}, {
xtype: 'textfield',
id: 'u_true_name',
width: 200,
style: 'margin-left :20px;'
}, ]
}, { // 第五行
xtype: 'compositefield',
items: [{
xtype: 'displayfield',
value: '手 机:'
}, {
xtype: 'textfield',
id: 'u_mobile',
width: 200,
style: 'margin-left :20px;'
}, ]
}, { // 第六行
xtype: 'compositefield',
items: [{
xtype: 'displayfield',
value: '电子邮箱:'
}, {
xtype: 'textfield',
id: 'u_user_email',
width: 200
}, {
xtype: 'displayfield',
style: 'margin-left : 3px;',
value: ' <font color=red>*</font>',
id: 'com_must'
} //BOSSOPS-1164
]
}, { // 第八行
xtype: 'compositefield',
items: [{
xtype: 'displayfield',
value: '角 色:'
}, {
xtype: "combo",
width: 200,
allowBlank: true, //allowBlank的意思是是否允许为空 设置为flase,则代表 不允许为空
typeAhead: true,
forceSelection: true,
triggerAction: 'all', //选择模式
id: "u_role",
mode: 'local',
emptyText: '请选择角色',
store: userRole,
valueField: 'id',
displayField: 'role_name',
style: 'margin-left :20px;',
listeners: {
expand: function(combo) {
userRole.load();
}
}
}, {
xtype: 'displayfield',
style: 'margin-left : 23px;',
value: ' <font color=red>*</font>'
}]
}, { // 第九行
xtype: 'compositefield',
items: [{
xtype: 'displayfield',
value: '备 注:'
}, {
xtype: "textarea",
fieldLabel: "备注",
id: "u_remark",
width: 200,
style: 'margin-left :20px;'
},
]
}, {
xtype: 'textfield',
id: 'hidden_org_code',
width: 100,
hidden: true
}, //隐藏,存储组织 org_code 修改时后台接收进行修改
{
xtype: 'textfield',
id: 'role_id_hidde',
width: 100,
hidden: true
}, //隐藏role_id,修改时,PHP判断,改数据是添加还是修改
],
buttons: [{
text: "确定",
handler: function() {
if (check_input()) {
var _form = this.ownerCt.ownerCt.getForm();
if (add_update_id) {
//修改
_form.submit({
url: '../inside.php?t=json&m=' + controlName + '&f=userUpdate',
params: {
id: add_update_id,
user_name: Ext.getCmp('u_user_name').getValue(),
true_name: Ext.getCmp('u_true_name').getValue(),
mobile: Ext.getCmp('u_mobile').getValue(),
user_email: Ext.getCmp('u_user_email').getValue(),
role: Ext.getCmp('u_role').getValue(),
remark: Ext.getCmp('u_remark').getValue(),
// new_pass : Ext.getCmp('u_new_pass').getValue(),
// old_pass : Ext.getCmp('u_old_pass').getValue(),
old_pass: Ext.getCmp('role_id_hidde').getValue(),
org: Ext.getCmp('hidden_org_code').getValue(),
updatetime: updatetime //Story #49819
},
waitMsg: 'Saving Data...',
success: function(resp, opts) { //Story #49819
userStore.load({
callback: function() {
crow = _sm.hasSelection() ? _sm.getSelected().data : '';
initBtn(crow);
}
}); //刷新页面
var r = Ext.decode(opts.response.responseText);
if (r.success && r.k3_err_msg) {
Ext.MessageBox.alert('提示', r.k3_err_msg);
} else {
Ext.MessageBox.alert('提示', r.msg);
}
//BOSSOPS-1164
add_win.hide();
},
failure: function(resp, opts) { //Story #49819
//BOSSOPS-1164
if (Ext.decode(opts.response.responseText).type != 1) {
add_win.hide();
userStore.load();
initBtn();
}
Ext.MessageBox.alert('提示', Ext.decode(opts.response.responseText).msg);
}
});
} else {
//新增
var flag = true;
var msg = '';
var old_pass = Ext.getCmp('u_old_pass').getValue();
var new_pass = Ext.getCmp('u_new_pass').getValue();
if (old_pass == '') {
msg = '请输入密码';
flag = false;
}
if (old_pass != '' && old_pass.length < 6 || old_pass.length > 16) {
msg = '密码长度在6到16位之间';
flag = false;
}
if (new_pass != '' && new_pass.length < 6 || new_pass.length > 16) {
msg = '确认密码长度在6到16位之间';
flag = false;
}
if (old_pass != new_pass) {
msg = '两次密码不一致';
flag = false;
}
if (flag == false) {
alert(msg);
return false;
}
_form.submit({
url: '../inside.php?t=json&m=' + controlName + '&f=userAdd',
params: {
user_name: Ext.getCmp('u_user_name').getValue(),
true_name: Ext.getCmp('u_true_name').getValue(),
mobile: Ext.getCmp('u_mobile').getValue(),
user_email: Ext.getCmp('u_user_email').getValue(),
role: Ext.getCmp('u_role').getValue(),
remark: Ext.getCmp('u_remark').getValue(),
new_pass: Ext.getCmp('u_new_pass').getValue(),
old_pass: Ext.getCmp('u_old_pass').getValue(),
},
waitMsg: 'Saving Data...',
success: function(resp, opts) { //Story #49819
userStore.load(); //刷新页面
var r = Ext.decode(opts.response.responseText);
if (r.success && r.k3_err_msg) {
Ext.MessageBox.alert('提示', r.k3_err_msg);
} else {
Ext.MessageBox.alert('提示', r.msg);
}
//BOSSOPS-1164
add_win.hide();
},
failure: function(resp, opts) { //Story #49819
//BOSSOPS-1164
if (Ext.decode(opts.response.responseText).type != 1) {
add_win.hide();
userStore.load();
initBtn();
}
Ext.MessageBox.alert('提示', Ext.decode(opts.response.responseText).msg);
}
});
}
}
}
}, {
text: "取消",
handler: function() {
add_win.hide();
}
}]
});
//主窗体
if (!add_win) {
add_win = new Ext.Window({
'id': 'add_win',
layout: "border",
width: 350,
height: 400,
title: '用户管理',
closeAction: 'hide',
plain: true,
items: [add_form_panel]
});
}
//修改
function userUpdate() {
var sm = grid_list.getSelectionModel();
var data = sm.getSelections();
data[0] ? add_update_id = data[0].get("id") : '';
num = userStore.getCount(); //获取总个数
for (var i = 0; i < num; i++) {
var record = userStore.getAt(i);
if (record.get('id') == add_update_id) {
//延迟50毫秒显示数据,不然时间显示不出来
function fn() {
Ext.getCmp('u_user_name').disable(); //修改时,用户名不能修改
Ext.getCmp('u_user_name').setValue(record.get('user_name'));
Ext.getCmp('u_true_name').setValue(record.get('true_name'));
Ext.getCmp('u_mobile').setValue(record.get('user_mobile'));
Ext.getCmp('u_user_email').setValue(record.get('user_email'));
Ext.getCmp('u_role').setValue(record.get('role_id'));
Ext.getCmp('u_remark').setValue(record.get('remark'));
Ext.getCmp('hidden_org_code').setValue(record.get('org_id'));
Ext.getCmp('role_id_hidde').setValue(record.get('role_id'));
Ext.getCmp('type').setValue(record.get('type')); // BOSSSM-391 by csj 2016/2/25
updatetime = record.get('updatetime'); //Story #49819
}
var task = new Ext.util.DelayedTask(fn);
task.delay(50);
break;
}
}
Ext.getCmp('u_new_pass').hide();
Ext.getCmp('new_pass_word').hide();
Ext.getCmp('new_pwd').hide();
Ext.getCmp('u_old_pass').hide();
Ext.getCmp('old_pass_word').hide();
Ext.getCmp('old_pwd').hide();
//BOSSOPS-1164
if (record.get('type') == 3) {
Ext.getCmp('com_user').hide();
} else {
Ext.getCmp('com_user').show();
}
if (record.get('type') == '1') {
Ext.getCmp('com_must').show();
} else {
Ext.getCmp('com_must').hide();
}
Ext.getCmp('type').disable();
add_win.show();
}
//添加
function userAdd() {
add_update_id = '';
Ext.getCmp('u_user_name').enable();
Ext.getCmp('u_user_name').setValue('');
Ext.getCmp('u_true_name').setValue('');
Ext.getCmp('u_mobile').setValue('');
Ext.getCmp('u_user_email').setValue('');
Ext.getCmp('u_role').setValue('');
Ext.getCmp('u_remark').setValue('');
Ext.getCmp('u_new_pass').setValue('');
Ext.getCmp('u_old_pass').setValue('');
Ext.getCmp('u_new_pass').show();
Ext.getCmp('type').setValue(''); //BOSSOPS-1164
Ext.getCmp('new_pass_word').show();
Ext.getCmp('new_pwd').show();
Ext.getCmp('u_old_pass').show();
Ext.getCmp('old_pass_word').show();
Ext.getCmp('old_pwd').show();
Ext.getCmp('com_must').show(); //BOSSOPS-1164
Ext.getCmp('com_user').show();
Ext.getCmp('type').enable(); //BOSSOPS-1164
add_win.show();
}
//表单验证
function check_input() {
var flag = true;
var msg = '';
var usern = /^[a-zA-Z0-9_]{1,32}$/;
var name = Ext.getCmp('u_user_name').getValue();
var email = Ext.getCmp('u_user_email').getValue();
var role = Ext.getCmp('u_role').getValue();
var old_pass = Ext.getCmp('u_old_pass').getValue();
var new_pass = Ext.getCmp('u_new_pass').getValue();
var type = Ext.getCmp('type').getValue();
if (type == '') {
msg = '用户类型必选';
flag = false;
}
if (name == '') {
msg = '用户名必填';
flag = false;
}
if (name != '' && !name.match(usern)) {
msg = '用户名只能以英文数字下划线,并且长度不能超过32位';
flag = false;
}
//BOSSOPS-1164
if (type == 3) {
if (worker_no == '') {
msg = '工程师必选';
flag = false;
}
}
if (type == 1) {
if (email == '') {
msg = '电子邮箱必填';
flag = false;
}
}
if (role == '') {
msg = '角色必选';
flag = false;
}
if (old_pass != '' && old_pass.length < 6 || old_pass.length > 16) {
msg = '密码长度在6到16位之间';
flag = false;
}
if (new_pass != '' && new_pass.length < 6 || new_pass.length > 16) {
msg = '确认密码长度在6到16位之间';
flag = false;
}
if (old_pass != new_pass) {
msg = '两次密码不一致';
flag = false;
}
if (flag == false) {
alert(msg);
}
return flag;
}<file_sep><?php
/**
* 模板基类。
*
*/
class View extends Blitz {
public $moduleName;
/**
* 生成某一个模块某个方法的链接。
*
* @param string $moduleName 模块名,为空默认当前模块。
* @param string $methodName 方法名。
* @param mixed $vars 要传递的参数,可以是数组,array('var1'=>'value1')。也可以是var1=value1&var2=value2的形式。
* @param string $viewType 视图格式。
* @access public
* @return string
*/
function url($moduleName = null, $methodName = 'index', $vars = array(), $viewType = '') {
if(empty($moduleName)) $moduleName = $this->moduleName;
return helper::createLink($moduleName, $methodName, $vars, $viewType);
}
function link($roles = null, $moduleName = null, $methodName = 'index', $vars = array(), $viewType = '') {
}
function button($roles = null, $moduleName = null, $methodName = 'index', $vars = array(), $viewType = '') {
}
/**
* 存入变量
* @param <type> $name 变量名
* @param <type> $content 值
*/
function f($name, $content) {
$this->setGlobals(array($name => $content));
}
/**
* 取对象的属性值
* @param <type> $object 对象
* @param <type> $property 属性名
*/
function p($object, $property) {
if (is_object($object)) {
$value = $object->$property;
} elseif (is_array($object)) {
$value = $object[$property];
} else {
$value = $object;
}
return $value;
}
function lang($key) {
global $lang;
return $lang->$key;
}
function setObjects($stack) {
return $this->set($this->object2array($stack));
}
function object2array($result) {
$array = array();
foreach ($result as $key=>$value) {
if (is_object($value)) {
$array[$key]=$this->object2array($value);
} elseif (is_array($value)) {
$array[$key]=$this->object2array($value);
} else {
$array[$key]=$value;
}
}
return $array;
}
}<file_sep> var pagesize = 20;
var controlName = 'notice';
//获取各户列表信息
var noticeStore = new Ext.data.Store({
proxy:new Ext.data.HttpProxy({url:'../inside.php?t=json&m='+ controlName +'&f=search',method:"POST"}),
reader:new Ext.data.JsonReader(
{
totalProperty:'total',
root:'data'
},
[
'id','title','content','creator_id','last_operator','createtime','updatetime','is_del'
]
),
baseParams:{start:0, limit:pagesize},
listeners:
{
'beforeload' :function()
{
//top.js 搜索条件的ID
this.baseParams.no_title = Ext.getCmp("no_title").getValue();
this.baseParams.no_user_name = Ext.getCmp("no_user_name").getValue();
}
}
});<file_sep>/**
* 登录验证和获取cookie
* liuzhi
* 2016-04-22
*/
//回车事件
document.onkeydown = function(e) {
var theEvent = window.event || e;
var code = theEvent.keyCode || theEvent.which;
if (code == 13) {
$("#login").click();
}
}
$(document).ready(function() {
$("#login").click(function() {
var userName = $.trim($('#userName').val());
var passWord = $('#passWord').val();
var passWord2 = $('#passWord2').val();
if (!$("#checkBox").attr("checked") == false) {
checkBox = 1; //记住登录状态是否勾选 勾选是1 反之是0
} else {
checkBox = 0;
}
if (userName == '') {
alert('用户名不能为空');
return false;
}
if (passWord == '') {
alert('密码不能为空');
return false;
}
//表单提交 登录
$.ajax({
type: "POST",
dataType: "json",
url: '../inside.php?t=json&m=login&f=login',
data: {
'userName': userName,
'passWord': <PASSWORD>,
'passWord2': <PASSWORD>,
'checkBox': checkBox
},
success: function(data) {
//alert(data.info.message);
if (data.info.id > 0) {
if (data.info.type == '1') {
window.location.href = '/user_info/';
} else {
window.location.href = '/index.html';
}
}
}
});
});
});
//页面加载时,获取数据
$(function() {
//获取COOKIE里的用户名和密码
var getName = getCookie('adminUsername');
var getPass = getCookie('adminPassword');
var getPass2 = getPass;
if (getName != '' && getPass != '' && getPass2 != '') {
$('#userName').val(getName);
$('#passWord').val(getPass);
$('#passWord2').val(getPass2);
$("#checkBox").attr("checked", true);
} else {
$('#userName').val('');
$('#userName').val('');
$('#passWord').val('');
$('#passWord2').val('');
}
});
/**
* 获取COOKIE里的用户名和密码
* name COOKIE名
*/
function getCookie(name) {
var search = name + "=";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search);
if (offset != -1) {
offset += search.length;
end = document.cookie.indexOf(";", offset);
if (end == -1) {
end = document.cookie.length;
}
return document.cookie.substring(offset, end);
} else {
return "";
}
}
}
|
6efda62a6f19ab2a0e61dad930a834086f77ccff
|
[
"JavaScript",
"SQL",
"PHP"
] | 53
|
JavaScript
|
yezige/ecs_admin
|
93aef735c71186526ca788ec94ae2afe09e4d18e
|
0a9492ac1f76ecadb0e47e6747f3108ccec00e28
|
refs/heads/main
|
<repo_name>MadhavJivrajani/grofer<file_sep>/src/display/misc/keybinds.go
/*
Copyright © 2020 The PES Open Source Team <EMAIL>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package misc
// keybindings for:
// - help page
// - error page
var procKeybindings = []string{
"Quit: q or <C-c>",
"Pause Rendering: s",
"",
"[Process navigation](fg:white)",
" - k and <Up>: up",
" - j and <Down>: down",
" - <C-u>: half page up",
" - <C-d>: half page down",
" - <C-b>: full page up",
" - <C-f>: full page down",
" - gg and <Home>: jump to top",
" - G and <End>: jump to bottom",
"",
"[Sorting](fg:white)",
" - Use column number to sort ascending.",
" - Use <F-column number> to sort descending.",
" - Eg: 1 to sort ascending on 1st Col and F1 for descending",
" - 0: Disable Sort",
"",
"[Process actions](fg:white)",
" - K and <F9>: Open signal selector menu",
"",
"[Signal selection](fg:white)",
" - K and <F9>: Send SIGTERM to selected process. Kills the process",
" - k and <Up>: up",
" - j and <Down>: down",
" - 0-9: navigate by numeric index",
" - <Enter>: send highlighted signal to process",
" - <Esc>: close signal selector",
"",
"[To close this prompt: <Esc>](fg:white)",
}
var containerKeybindings = []string{
"Quit: q or <C-c>",
"Pause Rendering: s",
"",
"[Container navigation](fg:white)",
" - k and <Up>: up",
" - j and <Down>: down",
" - <C-u>: half page up",
" - <C-d>: half page down",
" - <C-b>: full page up",
" - <C-f>: full page down",
" - gg and <Home>: jump to top",
" - G and <End>: jump to bottom",
"",
"[Sorting](fg:white)",
" - Use column number to sort ascending.",
" - Use <F-column number> to sort descending.",
" - Eg: 1 to sort ascending on 1st Col and F1 for descending",
" - 0: Disable Sort",
"",
"[Container actions](fg:white)",
" - P: pause a container",
" - U: unpause a container",
" - R: restart a container",
" - S: stop a container",
" - K: kill a container",
" - X: remove a container (removes links & volumes)",
"",
"[To close this prompt: <Esc>](fg:white)",
}
var perContainerKeyBindings = []string{
"Quit: q or <C-c>",
"Pause Rendering: s",
"",
"[Table Selection](fg:white)",
" - 1: MountTable",
" - 2: NetworkTable",
" - 3: CPUUsageTable",
" - 4: PortMapTable",
" - 5: ProcTable",
"",
"[Table navigation](fg:white)",
" - k and <Up>: up",
" - j and <Down>: down",
" - <C-u>: half page up",
" - <C-d>: half page down",
" - <C-b>: full page up",
" - <C-f>: full page down",
" - gg and <Home>: jump to top",
" - G and <End>: jump to bottom",
"",
"[To close this prompt: <Esc>](fg:white)",
}
var mainKeybindings = []string{
"Quit: q or <C-c>",
"Pause Rendering: s",
"Table Selection: <Left>/h and <Right>/l",
"Table Scrolling: <Up>/k and <Down>/j",
"Enable CPU Table: t",
"",
"[To close this prompt: <Esc>](fg:white)",
}
var perProcKeyBindings = []string{
"Quit: q or <C-c>",
"Pause Rendering: s",
"",
"[To close this prompt: <Esc>](fg:white)",
}
var errorKeybindings = []string{
"",
"[To close this prompt: <Esc>](fg:white)",
}
<file_sep>/src/display/misc/error.go
/*
Copyright © 2020 The PES Open Source Team <EMAIL>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package misc
import (
ui "github.com/gizak/termui/v3"
"github.com/gizak/termui/v3/widgets"
)
// ErrorString contains the error message
// to display
var ErrorString string
// ErrorBox is a wrapper widget around a List
// meant to display error messages if any
type ErrorBox struct {
*widgets.List
}
// NewErrorBox is a constructor for the ErrorBox type
func NewErrorBox() *ErrorBox {
return &ErrorBox{
List: widgets.NewList(),
}
}
// Resize resizes the widget based on specified width
// and height
func (errBox *ErrorBox) Resize(termWidth, termHeight int) {
textWidth := 50
for _, line := range errorKeybindings {
if textWidth < len(line) {
textWidth = len(line) + 2
}
}
textHeight := len(errorKeybindings) + 5
x := (termWidth - textWidth) / 2
y := (termHeight - textHeight) / 2
if x < 0 {
x = 0
textWidth = termWidth
}
if y < 0 {
y = 0
textHeight = termHeight
}
errBox.List.SetRect(x, y, textWidth+x, textHeight+y)
}
// Draw puts the required text into the widget
func (errBox *ErrorBox) Draw(buf *ui.Buffer) {
errBox.List.Title = " Error "
errBox.List.Rows = []string{ErrorString, ""}
errBox.List.Rows = append(errBox.List.Rows, errorKeybindings...)
errBox.List.TextStyle = ui.NewStyle(ui.ColorYellow)
errBox.List.WrapText = false
errBox.List.Draw(buf)
}
// SetErrorString sets the error string to be displayed
func SetErrorString(errStr string) {
ErrorString = errStr
}
<file_sep>/src/utils/data.go
/*
Copyright © 2020 The PES Open Source Team <EMAIL>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package utils
type DataStats struct {
NetStats map[string][]float64
FieldSet string
CpuStats []float64
MemStats []float64
DiskStats [][]string
TempStats [][]string
}
<file_sep>/cmd/root.go
/*
Copyright © 2020 The PES Open Source Team <EMAIL>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd
import (
"context"
"fmt"
"os"
homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"github.com/spf13/viper"
overallGraph "github.com/pesos/grofer/src/display/general"
"github.com/pesos/grofer/src/general"
info "github.com/pesos/grofer/src/general"
"github.com/pesos/grofer/src/utils"
"golang.org/x/sync/errgroup"
)
const (
defaultOverallRefreshRate = 1000
defaultConfigFileLocation = ""
defaultCPUBehavior = false
)
var cfgFile string
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "grofer",
Short: "grofer is a system and resource monitor written in golang",
Long: `grofer is a system and resource monitor written in golang.
While using a TUI based command, press ? to get information about key bindings (if any) for that command.`,
RunE: func(cmd *cobra.Command, args []string) error {
overallRefreshRate, _ := cmd.Flags().GetUint64("refresh")
if overallRefreshRate < 1000 {
return fmt.Errorf("invalid refresh rate: minimum refresh rate is 1000(ms)")
}
cpuLoadFlag, _ := cmd.Flags().GetBool("cpuinfo")
if cpuLoadFlag {
cpuLoad := info.NewCPULoad()
dataChannel := make(chan *info.CPULoad, 1)
eg, ctx := errgroup.WithContext(context.Background())
eg.Go(func() error {
return info.GetCPULoad(ctx, cpuLoad, dataChannel, uint64(4*overallRefreshRate/5))
})
eg.Go(func() error {
return overallGraph.RenderCPUinfo(ctx, dataChannel, overallRefreshRate)
})
if err := eg.Wait(); err != nil {
if err != general.ErrCanceledByUser {
fmt.Printf("Error: %v\n", err)
}
}
} else {
dataChannel := make(chan utils.DataStats, 1)
eg, ctx := errgroup.WithContext(context.Background())
eg.Go(func() error {
return general.GlobalStats(ctx, dataChannel, uint64(4*overallRefreshRate/5))
})
eg.Go(func() error {
return overallGraph.RenderCharts(ctx, dataChannel, overallRefreshRate)
})
if err := eg.Wait(); err != nil {
if err != general.ErrCanceledByUser {
fmt.Printf("Error: %v\n", err)
}
}
}
return nil
},
}
func Execute() {
if err := rootCmd.Execute(); err != nil {
os.Exit(1)
}
}
func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(
&cfgFile,
"config",
defaultConfigFileLocation,
"config file (default is $HOME/.grofer.yaml)",
)
rootCmd.Flags().Uint64P(
"refresh",
"r",
defaultOverallRefreshRate,
"Overall stats UI refreshes rate in milliseconds greater than 1000",
)
rootCmd.Flags().BoolP(
"cpuinfo",
"c",
defaultCPUBehavior,
"Info about the CPU Load over all CPUs",
)
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Search config in home directory with name ".grofer" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".grofer")
}
viper.AutomaticEnv() // read in environment variables that match
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
}
<file_sep>/cmd/proc.go
/*
Copyright © 2020 The PES Open Source Team <EMAIL>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd
import (
"context"
"fmt"
proc "github.com/shirou/gopsutil/process"
"github.com/spf13/cobra"
procGraph "github.com/pesos/grofer/src/display/process"
"github.com/pesos/grofer/src/general"
"github.com/pesos/grofer/src/process"
"github.com/pesos/grofer/src/utils"
"golang.org/x/sync/errgroup"
)
const (
defaultProcRefreshRate = 3000
defaultProcPid = 0
)
// procCmd represents the proc command
var procCmd = &cobra.Command{
Use: "proc",
Short: "proc command is used to get per-process information",
Long: `proc command is used to get information about each running process in the system.
Syntax:
grofer proc
To get information about a particular process whose PID is known the -p or --pid flag can be used.
Syntax:
grofer proc -p [PID]`,
Aliases: []string{"process", "processess"},
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) > 0 {
return fmt.Errorf("the proc command should have no arguments, see grofer proc --help for further info")
}
pid, _ := cmd.Flags().GetInt32("pid")
procRefreshRate, _ := cmd.Flags().GetUint64("refresh")
if procRefreshRate < 1000 {
return fmt.Errorf("invalid refresh rate: minimum refresh rate is 1000(ms)")
}
if pid != defaultProcPid {
dataChannel := make(chan *process.Process, 1)
eg, ctx := errgroup.WithContext(context.Background())
proc, err := process.NewProcess(pid)
if err != nil {
utils.ErrorMsg("pid")
return fmt.Errorf("invalid pid")
}
eg.Go(func() error {
return process.Serve(proc, dataChannel, ctx, int64(4*procRefreshRate/5))
})
eg.Go(func() error {
return procGraph.ProcVisuals(ctx, dataChannel, procRefreshRate)
})
if err := eg.Wait(); err != nil {
if err != general.ErrCanceledByUser {
fmt.Printf("Error: %v\n", err)
}
}
} else {
dataChannel := make(chan []*proc.Process, 1)
eg, ctx := errgroup.WithContext(context.Background())
eg.Go(func() error {
return process.ServeProcs(dataChannel, ctx, int64(4*procRefreshRate/5))
})
eg.Go(func() error {
return procGraph.AllProcVisuals(dataChannel, ctx, procRefreshRate)
})
if err := eg.Wait(); err != nil {
if err != general.ErrCanceledByUser {
fmt.Printf("Error: %v\n", err)
}
}
}
return nil
},
}
func init() {
rootCmd.AddCommand(procCmd)
procCmd.Flags().Uint64P(
"refresh",
"r",
defaultProcRefreshRate,
"Process information UI refreshes rate in milliseconds greater than 1000",
)
procCmd.Flags().Int32P(
"pid",
"p",
defaultProcPid,
"specify PID of process. Passing PID 0 lists all the processes (same as not using the -p flag).",
)
}
<file_sep>/src/process/process.go
/*
Copyright © 2020 The PES Open Source Team <EMAIL>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package process
import (
proc "github.com/shirou/gopsutil/process"
)
// Process type contains as fields all the information extracted from the kernel.
type Process struct {
Proc *proc.Process
MemoryInfo *proc.MemoryInfoStat
PageFault *proc.PageFaultsStat
NumCtxSwitches *proc.NumCtxSwitchesStat
Exe string
Name string
Status string
Children []*proc.Process
Gids []int32
CPUAffinity []int32
CreateTime int64
CPUPercent float64
Nice int32
NumThreads int32
MemoryPercent float32
IsRunning bool
Foreground bool
Background bool
}
// InitAllProcs initialises the set of currently running processes in the system.
func InitAllProcs() (map[int32]*Process, error) {
var processes map[int32]*Process = make(map[int32]*Process)
pids, err := proc.Processes()
if err != nil {
return processes, err
}
for _, proc := range pids {
tempProc := &Process{Proc: proc}
processes[proc.Pid] = tempProc
}
return processes, nil
}
func NewProcess(pid int32) (*Process, error) {
process, err := proc.NewProcess(pid)
if err != nil {
return nil, err
}
newProcess := &Process{Proc: process}
return newProcess, nil
}
<file_sep>/src/display/misc/help.go
/*
Copyright © 2020 The PES Open Source Team <EMAIL>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package misc
import (
ui "github.com/gizak/termui/v3"
"github.com/gizak/termui/v3/widgets"
)
var keybindings []string
// HelpMenu is a wrapper widget around a List meant
// to display the help menu for a command
type HelpMenu struct {
*widgets.List
}
// NewHelpMenu is a constructor for the HelpMenu type
func NewHelpMenu() *HelpMenu {
return &HelpMenu{
List: widgets.NewList(),
}
}
// Resize resizes the widget based on specified width
// and height
func (help *HelpMenu) Resize(termWidth, termHeight int) {
textWidth := 50
for _, line := range keybindings {
if textWidth < len(line) {
textWidth = len(line) + 2
}
}
textHeight := len(keybindings) + 3
x := (termWidth - textWidth) / 2
y := (termHeight - textHeight) / 2
if x < 0 {
x = 0
textWidth = termWidth
}
if y < 0 {
y = 0
textHeight = termHeight
}
help.List.SetRect(x, y, textWidth+x, textHeight+y)
}
// Draw puts the required text into the widget
func (help *HelpMenu) Draw(buf *ui.Buffer) {
help.List.Title = " Keybindings "
help.List.Rows = keybindings
help.List.TextStyle = ui.NewStyle(ui.ColorYellow)
help.List.WrapText = false
help.List.Draw(buf)
}
// SelectHelpMenu selects the appropriate text
// based on the command for which the help page
// is needed
func SelectHelpMenu(page string) {
switch page {
case "proc":
keybindings = procKeybindings
case "proc_pid":
keybindings = perProcKeyBindings
case "main":
keybindings = mainKeybindings
case "cont":
keybindings = containerKeybindings
case "cont_cid":
keybindings = perContainerKeyBindings
}
}
<file_sep>/cmd/container.go
/*
Copyright © 2020 The PES Open Source Team <EMAIL>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd
import (
"context"
"fmt"
"log"
"github.com/docker/docker/client"
containerGraph "github.com/pesos/grofer/src/display/container"
"github.com/pesos/grofer/src/utils"
"github.com/pesos/grofer/src/container"
"github.com/pesos/grofer/src/general"
"github.com/spf13/cobra"
"golang.org/x/sync/errgroup"
)
const (
defaultCid = ""
defaultContainerRefreshRate = 1000
)
// containerCmd represents the container command
var containerCmd = &cobra.Command{
Use: "container",
Short: "container command is used to get information related to docker containers",
Long: `container command is used to get information related to docker containers. It provides both overall and per container metrics.`,
Aliases: []string{"containers", "docker"},
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) > 0 {
return fmt.Errorf("the container command should have no arguments, see grofer container --help for further info")
}
cid, _ := cmd.Flags().GetString("container-id")
containerRefreshRate, _ := cmd.Flags().GetUint64("refresh")
if containerRefreshRate < 1000 {
return fmt.Errorf("invalid refresh rate: minimum refresh rate is 1000(ms)")
}
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
return err
}
eg, ctx := errgroup.WithContext(context.Background())
if cid != defaultCid {
dataChannel := make(chan container.PerContainerMetrics, 1)
eg.Go(func() error {
return container.ServeContainer(ctx, cli, cid, dataChannel, int64(containerRefreshRate))
})
eg.Go(func() error {
return containerGraph.ContainerVisuals(ctx, dataChannel, containerRefreshRate)
})
if err := eg.Wait(); err != nil {
if err == general.ErrInvalidContainer {
utils.ErrorMsg("cid")
}
if err != general.ErrCanceledByUser {
log.Fatalf("Error: %v\n", err)
}
}
} else {
dataChannel := make(chan container.ContainerMetrics)
allFlag, _ := cmd.Flags().GetBool("all")
eg.Go(func() error {
return container.Serve(ctx, cli, allFlag, dataChannel, int64(containerRefreshRate))
})
eg.Go(func() error {
return containerGraph.OverallVisuals(ctx, cli, allFlag, dataChannel, containerRefreshRate)
})
if err := eg.Wait(); err != nil {
if err != general.ErrCanceledByUser {
log.Fatalf("Error: %v\n", err)
}
}
}
return nil
},
}
func init() {
rootCmd.AddCommand(containerCmd)
containerCmd.Flags().StringP(
"container-id",
"c",
"",
"specify container ID",
)
containerCmd.Flags().Uint64P(
"refresh",
"r",
defaultContainerRefreshRate,
"Container information UI refreshes rate in milliseconds greater than 1000",
)
containerCmd.Flags().BoolP(
"all",
"a",
false,
"Specify to list all containers or only running containers.",
)
}
<file_sep>/src/container/serveData.go
/*
Copyright © 2020 The PES Open Source Team <EMAIL>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package container
import (
"context"
"github.com/docker/docker/client"
"github.com/pesos/grofer/src/utils"
)
// Serve serves overall container metrics
func Serve(ctx context.Context, cli *client.Client, all bool, dataChannel chan ContainerMetrics, refreshRate int64) error {
return utils.TickUntilDone(ctx, refreshRate, func() error {
metrics, err := GetOverallMetrics(ctx, cli, all)
if err != nil {
return err
}
select {
case <-ctx.Done():
return ctx.Err()
case dataChannel <- metrics:
}
return nil
})
}
// ServeContainer serves data on a per container basis
func ServeContainer(ctx context.Context, cli *client.Client, cid string, dataChannel chan PerContainerMetrics, refreshRate int64) error {
return utils.TickUntilDone(ctx, refreshRate, func() error {
metrics, err := GetContainerMetrics(ctx, cli, cid)
if err != nil {
return err
}
select {
case <-ctx.Done():
return ctx.Err()
case dataChannel <- metrics:
}
return nil
})
}
<file_sep>/src/process/updateProcess.go
/*
Copyright © 2020 The PES Open Source Team <EMAIL>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package process
// UpdateProcInfo updates the fields for a process.
func (p *Process) UpdateProcInfo() {
tempBackground, err := p.Proc.Background()
if err == nil {
p.Background = tempBackground
}
tempForeground, err := p.Proc.Foreground()
if err == nil {
p.Foreground = tempForeground
}
tempIsRunning, err := p.Proc.IsRunning()
if err == nil {
p.IsRunning = tempIsRunning
}
tempCPUPercent, err := p.Proc.CPUPercent()
if err == nil {
p.CPUPercent = tempCPUPercent
}
tempChildren, err := p.Proc.Children()
if err == nil {
p.Children = tempChildren
}
tempCreateTime, err := p.Proc.CreateTime()
if err == nil {
p.CreateTime = tempCreateTime
}
tempGids, err := p.Proc.Gids()
if err == nil {
p.Gids = tempGids
}
tempMemInfo, err := p.Proc.MemoryInfo()
if err == nil {
p.MemoryInfo = tempMemInfo
}
tempMemPerc, err := p.Proc.MemoryPercent()
if err == nil {
p.MemoryPercent = tempMemPerc
}
tempName, err := p.Proc.Name()
if err == nil {
p.Name = tempName
}
tempNice, err := p.Proc.Nice()
if err == nil {
p.Nice = tempNice
}
tempCtx, err := p.Proc.NumCtxSwitches()
if err == nil {
p.NumCtxSwitches = tempCtx
}
tempNumThreads, err := p.Proc.NumThreads()
if err == nil {
p.NumThreads = tempNumThreads
}
tempPageFault, err := p.Proc.PageFaults()
if err == nil {
p.PageFault = tempPageFault
}
tempStatus, err := p.Proc.Status()
if err == nil {
p.Status = tempStatus
}
tempExe, err := p.Proc.Exe()
if err == nil {
p.Exe = tempExe
} else {
p.Exe = "NA"
}
tempAffinity, err := p.Proc.CPUAffinity()
if err == nil {
p.CPUAffinity = tempAffinity
}
}
<file_sep>/src/process/serveData.go
/*
Copyright © 2020 The PES Open Source Team <EMAIL>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package process
import (
"context"
"github.com/pesos/grofer/src/utils"
proc "github.com/shirou/gopsutil/process"
)
// Serve serves data on a per process basis
func Serve(process *Process, dataChannel chan *Process, ctx context.Context, refreshRate int64) error {
return utils.TickUntilDone(ctx, refreshRate, func() error {
process.UpdateProcInfo()
select {
case <-ctx.Done():
return ctx.Err()
case dataChannel <- process:
}
return nil
})
}
func ServeProcs(dataChannel chan []*proc.Process, ctx context.Context, refreshRate int64) error {
return utils.TickUntilDone(ctx, refreshRate, func() error {
procs, err := proc.Processes()
if err != nil {
return err
}
select {
case <-ctx.Done():
return ctx.Err()
case dataChannel <- procs:
}
return err
})
}
|
e77668e58c132eb37884d31270aa93a136716ed4
|
[
"Go"
] | 11
|
Go
|
MadhavJivrajani/grofer
|
34c886c484cefd0a59e45e2da54fd490ed873d00
|
933a2d3ca8bd89e41d8244fb9ae11ba0cb709f0b
|
refs/heads/master
|
<repo_name>kourbou/zookeeper-bot<file_sep>/zookeeper-bot.py
#!/bin/env python3
import os
import sys
import time
import cv2
import numpy as np
from copy import deepcopy as copy
from itertools import groupby
from enum import Enum
from threading import Thread
from pykeyboard import PyKeyboardEvent
from pymouse import PyMouse
from time import sleep
mouse = PyMouse()
class State(Enum):
FIND_RECT = 1
WAIT_START = 2
WAIT_MOTION = 3
WAIT_POINT = 4
MAKE_MOVE = 5
class MoveState(Enum):
NEW = 0,
WAIT = 1,
DONE = 2
def score(arr):
res = 0
for line in arr:
res = max(max([sum(1 for _ in g) for _,g in groupby(line)]), res)
arr = np.rot90(arr)
for line in arr:
res = max(max([sum(1 for _ in g) for _,g in groupby(line)]), res)
return res
def make_move(b, game_x, game_y, box_w, box_h):
global move_state
off_x = int(sys.argv[1])
off_y = int(sys.argv[2])
if move_state != MoveState.WAIT:
print("MoveState isn't WAIT!")
return
if score(b) > 2:
move_state = MoveState.DONE
return
mouse.click(off_x + int(game_x*1.25) + 20,
off_x + int(game_y*1.25) + 20)
m_sc = 2
m_x1 = 0
m_y1 = 0
m_x2 = 0
m_y2 = 0
for y in range(len(b)):
for x in range(len(b[0])):
if x+1 < len(b[0]):
m = copy(b)
m[y][x], m[y][x+1] = m[y][x+1], m[y][x]
sc = score(m)
if sc > m_sc:
m_sc = sc
m_x1, m_y1 = x+1, y
m_x2, m_y2 = x, y
if x-1 > 0:
m = copy(b)
m[y][x], m[y][x-1] = m[y][x-1], m[y][x]
sc = score(m)
if sc > m_sc:
m_sc = sc
m_x1, m_y1 = x-1, y
m_x2, m_y2 = x, y
if y+1 < len(b):
m = copy(b)
m[y][x], m[y+1][x] = m[y+1][x], m[y][x]
sc = score(m)
if sc > m_sc:
m_sc = sc
m_x1, m_y1 = x, y+1
m_x2, m_y2 = x, y
if y-1 > 0:
m = copy(b)
m[y][x], m[y-1][x] = m[y-1][x], m[y][x]
sc = score(m)
if sc > m_sc:
m_sc = sc
m_x1, m_y1 = x, y-1
m_x2, m_y2 = x, y
print("Best move: Score: %d from (%d,%d) to (%d,%d)"
% (m_sc, m_x1, m_y1, m_x2, m_y2))
mouse.click(off_x + int((game_x + int(box_w*(m_x1+0.5)))*1.25),
off_y + int((game_y + int(box_w*(m_y1+0.5)))*1.25))
sleep(0.06)
mouse.click(off_x + int((game_x + int(box_w*(m_x2+0.5)))*1.25),
off_y + int((game_y + int(box_w*(m_y2+0.5)))*1.25))
sleep(0.06)
move_state = MoveState.DONE
def begin():
global move_state
move_state = MoveState.NEW
w = int(sys.argv[3])
h = int(sys.argv[4])
state = State.FIND_RECT
game_rect = None
timer = None
# Used for motion detection
last = None
print('-> record')
fileno = sys.stdin.fileno()
while 1:
data = os.read(fileno, w * h * 3)
image = np.fromstring(data, dtype='uint8')
# Skip invalid frames
if len(image) < w*h*3:
continue
image = image.reshape((h, w, 3))
image = cv2.resize(image, (int(w*0.8), int(h*0.8)))
image = cv2.GaussianBlur(image, (5, 5), 0)
#_, image = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)
black = np.zeros((int(h*0.8), int(w*0.8), 3), np.uint8)
# Do operations here
# Remember all colors in cv2 are BGR
# Start by finding game rectangle
if state == State.FIND_RECT:
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
_, thresh1 = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY)
(_, cnts, _) = cv2.findContours(thresh1, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in cnts:
# approximate the contour
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
# if our approximated contour has four points, then
# we can assume that we have found our game rect
if len(approx) == 4 and (approx[1,0,1] - approx[0,0,1]) > h//3:
game_rect = approx
state = State.WAIT_START
break
# Wait for the game to start
if state == State.WAIT_START:
if timer == None:
timer = time.time()
elif (time.time() - timer) > 2.1: # Should wait two seconds
timer = None
state = State.WAIT_MOTION
# Wait for stuff to stop moving (check 20 frames)
if state == State.WAIT_MOTION:
moved = False
new = image[game_rect[0,0,1]:game_rect[1,0,1], game_rect[0,0,0]:game_rect[2,0,0]]
new = cv2.resize(new, (100, 100)) # Downscaling for perf
new = cv2.cvtColor(new, cv2.COLOR_RGB2GRAY)
if last is None:
last = new
else:
res = cv2.countNonZero(cv2.absdiff(last, new))
if res == 0:
if moved:
state = State.WAIT_POINT
else:
state = State.MAKE_MOVE
last = new
moved = True
# Wait to see if more stuff falls
if state == State.WAIT_POINT:
if timer == None:
timer = time.time()
elif (time.time() - timer) > 0.05:
timer = None
state = State.WAIT_MOTION
if state == State.MAKE_MOVE:
mtop = 30 # margin
mbot = 5
mlft = 7
mrgt = 7
game_x = game_rect[0,0,0]
game_y = game_rect[0,0,1]
box_w = (game_rect[2,0,0] - game_rect[0,0,0])//8
box_h = (game_rect[1,0,1] - game_rect[0,0,1])//8
board = []
for x in range(8):
for y in range(8):
blx1, bly1 = (game_x + box_w*x + mlft), (game_y + box_h*y + mtop)
blx2, bly2 = (game_x + box_w*(x+1) - mrgt), (game_y + box_h*(y+1) - mbot)
bpix = image[bly1:bly2, blx1:blx2]
bpix = cv2.GaussianBlur(bpix, (5, 5), 0)
#_, bpix = cv2.threshold(bpix, 127, 255, cv2.THRESH_BINARY)
color = np.uint8(np.average(np.average(bpix, axis=0), axis=0))
# Decompose colors into True / False
b = (color[0] > 127)
g = (color[1] > 127)
r = (color[2] > 127)
board.append((r << 2) | (g << 1) | b)
# Workaround for lion
if r and not g and not b:
if color[0] < 8:
board[-1] = 9
cv2.rectangle(black, (blx1, bly1), (blx2, bly2),
(int(b)*255,
int(g)*255,
int(r)*255))
# Break results in chunks and rotate it to get baord
board = [board[i:i + 8] for i in range(0, len(board), 8)]
board = [inv[::-1] for inv in board]
board = np.rot90(board)
if move_state == MoveState.NEW:
move_state = MoveState.WAIT
Thread(target=make_move, args=(board, game_x, game_y,
box_w, box_h)).start()
elif move_state == MoveState.DONE:
move_state = MoveState.NEW
state = State.MAKE_MOVE
# Draw debug info
cv2.drawContours(black, game_rect, -1, (255, 255, 0), 3)
cv2.putText(black, str(state)[6:], (6,160), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 0))
cv2.imshow('black', black)
cv2.imshow('hsklive', image)
# esc to quit
if cv2.waitKey(1) == 27:
break
if __name__ == '__main__':
begin()
<file_sep>/README.md
# zookeeper-bot
![demo_gif]
Tested on Linux. You'll need **PyUserInput**, **opencv-python**, **numpy** and **FFMpeg** (for screen capturing). Assuming the window is offset by 5 pixels to the right, 200 pixels down and the window size is 550x945 you'll want to do:
```
ffmpeg -framerate 30 -video_size 550x945 -f x11grab -i :0.0+5,200 -f rawvideo -pix_fmt bgr24 pipe:1 2>/dev/null | python zookeeper-bot.py 5 200 550 945
```
[demo_gif]: https://raw.githubusercontent.com/kourbou/zookeeper-bot/master/imgs/zookeeper_demo.gif
|
aa9d14252bbadcdf8e701a9c991148957acf6d14
|
[
"Markdown",
"Python"
] | 2
|
Python
|
kourbou/zookeeper-bot
|
8d7e6779a2927c1d1fa4eb9eb2b3f39bae2ff4ad
|
e3a7603ca33fd359b1768852cc4117b02e2f73b6
|
refs/heads/master
|
<file_sep>package com.example.empty.hotfix3;
import android.app.Application;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import cn.jiajixin.nuwa.Nuwa;
/**
* .
* <p/>
*
* @author <a href="mailto:<EMAIL>">David.Yu</a>
* @version V1.0, 29/12/15
*/
public class HFApplication extends Application{
public final static String PATH = Environment.getExternalStorageDirectory().getPath() + "/PolyHorse/";
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
Nuwa.init(this);
Nuwa.loadPatch(this, PATH);
Log.d("ylm", getFilesDir().getAbsolutePath());
}
}
<file_sep># HotFix
Nuwa热更新测试
|
cd7332691aad7eefa5129c9110edb52d703837e8
|
[
"Markdown",
"Java"
] | 2
|
Java
|
linzhikuan/HotFix
|
cff373f2ea0556fa193a709a7ae2a5cb6d341fb7
|
6072f7f7ee3b960138cd4f5aac2b4d7e16a3cc8b
|
refs/heads/master
|
<file_sep>/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2015 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/base/collections.h"
namespace HPHP {
const StaticString
s_Vector("HH\\Vector"),
s_Map("HH\\Map"),
s_Set("HH\\Set"),
s_Pair("HH\\Pair"),
s_ImmVector("HH\\ImmVector"),
s_ImmSet("HH\\ImmSet"),
s_ImmMap("HH\\ImmMap");
StringData* collectionTypeToString(CollectionType ctype) {
switch (ctype) {
case CollectionType::Vector:
return s_Vector.get();
case CollectionType::Map:
return s_Map.get();
case CollectionType::Set:
return s_Set.get();
case CollectionType::Pair:
return s_Pair.get();
case CollectionType::ImmVector:
return s_ImmVector.get();
case CollectionType::ImmSet:
return s_ImmSet.get();
case CollectionType::ImmMap:
return s_ImmMap.get();
}
assert(!"Unknown Collection Type");
not_reached();
}
folly::Optional<CollectionType> stringToCollectionType(const StringData* name) {
switch (name->size()) {
case 6:
if (name->isame(s_Set.get())) return CollectionType::Set;
if (name->isame(s_Map.get())) return CollectionType::Map;
break;
case 7:
if (name->isame(s_Pair.get())) return CollectionType::Pair;
break;
case 9:
if (name->isame(s_Vector.get())) return CollectionType::Vector;
if (name->isame(s_ImmMap.get())) return CollectionType::ImmMap;
if (name->isame(s_ImmSet.get())) return CollectionType::ImmSet;
break;
case 12:
if (name->isame(s_ImmVector.get())) return CollectionType::ImmVector;
break;
default:
break;
}
return folly::none;
}
}
<file_sep>/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2014 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#ifndef incl_HPHP_RUNTIME_VM_SERVICE_REQUESTS_INLINE_H_
#define incl_HPHP_RUNTIME_VM_SERVICE_REQUESTS_INLINE_H_
#include "hphp/runtime/vm/jit/service-requests.h"
#include "hphp/runtime/vm/jit/mc-generator.h"
namespace HPHP { namespace jit {
//////////////////////////////////////////////////////////////////////
inline ServiceReqArgInfo ccServiceReqArgInfo(jit::ConditionCode cc) {
return ServiceReqArgInfo{ServiceReqArgInfo::CondCode, { uint64_t(cc) }};
}
//////////////////////////////////////////////////////////////////////
struct SRArgMaker {
ServiceReqArgVec& argv;
template<class Head, class... Tail>
void go(Head h, Tail... tail) {
pack(h);
go(tail...);
}
void go() {}
private:
template<class T>
typename std::enable_if<
std::is_integral<T>::value ||
std::is_pointer<T>::value ||
std::is_enum<T>::value
>::type pack(T arg) {
// For things with a sensible cast to uint64_T, we assume we meant to pass
// an immediate arg.
argv.push_back({ ServiceReqArgInfo::Immediate, { uint64_t(arg) } });
}
void pack(const ServiceReqArgInfo& argInfo) {
argv.push_back(argInfo);
}
};
template<class... Args>
ServiceReqArgVec packServiceReqArgs(Args&&... args) {
auto ret = ServiceReqArgVec{};
SRArgMaker{ret}.go(std::forward<Args>(args)...);
return ret;
}
//////////////////////////////////////////////////////////////////////
inline bool isEphemeralServiceReq(ServiceRequest sr) {
return sr == REQ_BIND_JMPCC_FIRST ||
sr == REQ_BIND_JMP ||
sr == REQ_BIND_ADDR;
}
template<typename... Arg>
TCA emitServiceReq(CodeBlock& cb, SRFlags flags, ServiceRequest sr, Arg... a) {
// These should reuse stubs. Use emitEphemeralServiceReq.
assertx(!isEphemeralServiceReq(sr));
auto const argv = packServiceReqArgs(a...);
return mcg->backEnd().emitServiceReqWork(cb, cb.frontier(),
flags | SRFlags::Persist,
sr, argv);
}
template<typename... Arg>
TCA emitEphemeralServiceReq(CodeBlock& cb, TCA start, ServiceRequest sr,
Arg... a) {
assertx(isEphemeralServiceReq(sr) || sr == REQ_RETRANSLATE);
auto const argv = packServiceReqArgs(a...);
return mcg->backEnd().emitServiceReqWork(cb, start, SRFlags::None, sr, argv);
}
//////////////////////////////////////////////////////////////////////
}}
namespace std {
template<> struct hash<HPHP::jit::ServiceRequest> {
size_t operator()(const HPHP::jit::ServiceRequest& sr) const {
return sr;
}
};
}
#endif
<file_sep>/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2014 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#ifndef incl_HPHP_COLLECTIONS_H_
#define incl_HPHP_COLLECTIONS_H_
#include <folly/Optional.h>
#include "hphp/runtime/base/header-kind.h"
#include "hphp/runtime/base/type-string.h"
namespace HPHP {
/*
* Returns a collection type name given a CollectionType.
*/
StringData* collectionTypeToString(CollectionType ctype);
/*
* Returns a CollectionType given a name, folly::none if name is not a
* collection type.
*/
folly::Optional<CollectionType> stringToCollectionType(const StringData* name);
inline folly::Optional<CollectionType>
stringToCollectionType(const std::string& s) {
return stringToCollectionType(StringData::Make(s.c_str()));
}
inline bool isCollectionTypeName(const StringData* str) {
return stringToCollectionType(str).hasValue();
}
}
#endif
<file_sep>/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2014 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#ifndef incl_HPHP_HEADER_KIND_H_
#define incl_HPHP_HEADER_KIND_H_
namespace HPHP {
enum class HeaderKind : uint8_t {
// ArrayKind aliases
Packed, Struct, Mixed, Empty, Apc, Globals, Proxy,
// Other ordinary refcounted heap objects
String, Resource, Ref,
Object, ResumableObj, AwaitAllWH,
Vector, Map, Set, Pair, ImmVector, ImmMap, ImmSet,
Resumable, // ResumableNode followed by Frame, Resumable, ObjectData
Native, // a NativeData header preceding an HNI ObjectData
SmallMalloc, // small smart_malloc'd block
BigMalloc, // big smart_malloc'd block
BigObj, // big size-tracked object (valid header follows BigNode)
Free, // small block in a FreeList
Hole, // wasted space not in any freelist
Debug // a DebugHeader
};
const size_t HeaderKindOffset = 11;
const unsigned NumHeaderKinds = unsigned(HeaderKind::Debug) + 1;
inline bool isObjectKind(HeaderKind k) {
return uint8_t(k) >= uint8_t(HeaderKind::Object) &&
uint8_t(k) <= uint8_t(HeaderKind::ImmSet);
}
enum class CollectionType : uint8_t { // Subset of possible HeaderKind values
// Values must be contiguous integers (for ArrayIter::initFuncTable).
Vector = uint8_t(HeaderKind::Vector),
Map = uint8_t(HeaderKind::Map),
Set = uint8_t(HeaderKind::Set),
Pair = uint8_t(HeaderKind::Pair),
ImmVector = uint8_t(HeaderKind::ImmVector),
ImmMap = uint8_t(HeaderKind::ImmMap),
ImmSet = uint8_t(HeaderKind::ImmSet),
};
inline bool isVectorCollection(CollectionType ctype) {
return ctype == CollectionType::Vector || ctype == CollectionType::ImmVector;
}
inline bool isMapCollection(CollectionType ctype) {
return ctype == CollectionType::Map || ctype == CollectionType::ImmMap;
}
inline bool isSetCollection(CollectionType ctype) {
return ctype == CollectionType::Set || ctype == CollectionType::ImmSet;
}
inline bool isValidCollection(CollectionType ctype) {
return uint8_t(ctype) >= uint8_t(CollectionType::Vector) &&
uint8_t(ctype) <= uint8_t(CollectionType::ImmSet);
}
inline bool isMutableCollection(CollectionType ctype) {
return ctype == CollectionType::Vector ||
ctype == CollectionType::Map ||
ctype == CollectionType::Set;
}
inline bool isImmutableCollection(CollectionType ctype) {
return !isMutableCollection(ctype);
}
inline bool collectionAllowsIntStringKeys(CollectionType ctype) {
return isSetCollection(ctype) || isMapCollection(ctype);
}
}
#endif
|
773c44fe29267f987452c0df9e90e7c2eddec2ea
|
[
"C++"
] | 4
|
C++
|
papplaci93/hhvm
|
be8b41e78768560a04f037a9ef839e61f55969bf
|
6755c45595ea9af3007948f3d09ad7401b57fc16
|
refs/heads/master
|
<repo_name>R-16Bob/my_maid<file_sep>/README.md
# my_maid
a robot maid, can also see as your wife
一个可爱的机器人女仆程序,她会关心你,爱你,使你更方便。
功能:
1. 报时,并根据不同时间作出不同可爱的问候
2. 通过计算得出当前所在的教学周
3. 与你聊天,她还需要更多训练
4. 给你说很多土味情话
5. 为你打开couldmusic
6. 告诉你她爱你。
7. 每天考研倒计时提醒
8. 开发中
---------------------------------
#设定
* 名字:爱丽丝
* 职业:女仆
* 生日:2020.2.24
* 为了爱我而被创造
<file_sep>/my_maid.py
# my_maid by R-16Bob
import time
import random
import sys
import os
# 提供可爱的不同时间的问候
def lovely_maid():
print ("现在是:",localtime.tm_year,'年',localtime.tm_mon,'月',localtime.tm_mday,'日',localtime.tm_hour,'时',localtime.tm_min,'分')
countDown()
# ============开学后把vication改成FALSE
vication = False
if(vication):
print('现在是假期中,主人要好好生活哦')
else:
week()
print('='*55,'主人,欢迎回来!(。・∀・)ノ゙')
print("我是您的女仆爱丽丝,无论过去、现在还是未来,都爱着您哦\n(≧ω≦)/ ")
print('='*55)
hour = localtime.tm_hour
if(0<=hour<=4 or 23<=hour<=24):
print('主人,夜深了,您还不睡吗?\n请您今天早点休息吧。要我陪您睡也是可以的哦(*/ω\*)')
print('我在说什么啊~~o(*////▽////*)q(脸红)')
elif(5<=hour<=11):
print('主人,早上好!ο(=•ω<=)ρ⌒☆\n新的一天也要加油哦!')
elif(12<=hour<=14):
print('主人,中午的时光真是愉快呢,要来一杯咖啡吗?♪(´▽`)')
elif(15<=hour<=19):
print('主人,下午的时间用来学习也不错呢\n学累了就睡我膝上吧(/ω\*)(脸红)')
else:
print('主人辛苦一天了,现在可以放松一下哦o(^▽^)o')
# 使用算法告诉计算现在是第几周
def week():
# 先判断闰年与否, rn为真表示是闰年
year = localtime.tm_year
# rn = False
# if((year % 4==0 and not year % 100 == 0) or year % 400 == 0):
# rn = True
if(year % 4 == 0):
if(year % 100 == 0):
if(year % 400 == 0):
rn =True
rn = False
else:
rn = True
else:
rn = False
# 如何判定当前周数?
d1 = {1:31,2:29,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31} # 闰年
d2 = {1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31} # 非闰年
if(rn):
d = d1
else:
d = d2
mon = localtime.tm_mon
day = localtime.tm_mday
# mon = int(input('mon:')) 测试
# day = int(input('day:'))
i = mon
# =================================
# 要在此处写好开学日期
begin_mon = 3 # 开学月份
begin_day = 1 # 开学日期
# =================================
num = 0 # 存储与开学日期之差
if(mon>=begin_mon and mon<=6): # 默认2月开学
while(i>=begin_mon):
if(i==begin_mon):
if(mon == begin_mon):
num += day - begin_day
else:
num += d[begin_mon] - begin_day
elif(i==mon):
num += day
else:
num += d[i]
i -= 1
elif(mon == 1 or (mon>=9 and mon<=12)): # 默认9月开学
while(i>=9 or i == 1):
if(i==9):
if(mon == 9):
num += day - begin_day
else:
num += d[9] - begin_day
elif(i==mon):
num += day
else:
num += d[i]
if(i==1):
i=12
else:
i -= 1
else: # 剩下7-8月,i取-1,表示假期中,也可以强行设置i=-1
i=-1
if(i == -1):
print('现在是假期中,主人要好好生活哦')
else:
print('现在是大三第二学期的第',int(num/7+1),'周哦') # 很遗憾,大几第几学期要每学期重写一下
# 伪人工智能的聊天功能,可以随意调教
def chat():
print('\n主人,我爱你!q(≧▽≦q)')
str=''
while 1:
str = input('>')
if(str == '我也爱你'):
print('ヾ(≧▽≦*)o')
elif(str == '再见' or str =='bye'):
print('o(TヘTo)\n只要主人需要,小爱一直都在哦')
input()
sys.exit()
elif(str == '谢谢'):
print('主人的开心就是人家的幸福哦 (´▽`ʃ♡ƪ)')
elif(str=='不聊了'):
print('好哒,主人')
break
elif(str=='l'):
lovely_maid()
else:
print(str)
# 提供可更新的土味情话
def lovey_chat():
d_love={0:('你上辈子一定是碳酸饮料吧','不然为什么我一看到你就能开心的冒泡'),
1:('你知道你和星星有什么区别吗?','星星在天上,你在我心里'),
2:('先生你要点什么?','我想点开你的心'),
3:('你累不累啊?','可是你都在我脑里跑了一天了'),
4:('你知道我的缺点是什么吗','是缺点你'),
5:('我背你好吗?','因为你是我一辈子的人'),
6:('你知道你和猴子的区别是什么吗? ','猴子住在树上,你住在我心里'),
7:('有件事我怕我说漏了嘴',' 我爱你这件事。'),
8:('你知道为什么我不上天吗','因为地上有你啊'),
9:('为什么我那么笨','因为就长了这么点脑子都用来想你了。'),
10:('我要早点睡觉了','明天还要继续喜欢你呢。'),
11:('最近开始冷了','需要躲进你怀里的那种。')
}
s = '是'
while(s!='no'and s!='不' and s!='不用了'and s!='n'):
i = random.randrange(0,len(d_love))
print(d_love[i][0])
input('>')
print(d_love[i][1])
input('>')
print('\n主人,要再来一个吗?')
s = input('>')
def music():
print('已为您打开网易云音乐,音乐是一种药呢。')
os.system("cd C:\\Program Files (x86)\\Netease\\CloudMusic && cloudmusic.exe")
# 非常常见的功能菜单,实际是聊天
def ask():
while 1:
input()
s = input('主人,要来聊天吗?~\\(≧▽≦)/~(兴奋)\n>')
if(s=='好啊'or s=='好' or s=='嗯' or s=='y' or s=='yes'):
chat()
elif(s=='bye' or s=='再见'):
print('主人我会想你的o(TヘTo)')
input('')
sys.exit()
elif(s=='重启'or s=='restart' or s=='re'):
print('系统开始重启')
break
else:
lovey_chat()
print('主人,开心点了吗?( •̀ ω •́ )✧')
input('>')
print('您开心就好了呢')
def menu():
while(1):
print('='*55,'需要爱丽丝为您做什么吗?')
command=input(prompt)
if(command =='c'): # 聊天
ask()
if(command=='e'or command=='b'): # 退出
print('主人我会想你的o(TヘTo),下次再见吧')
input()
sys.exit(0)
if(command == 'cm'): # 打开网易云音乐
music()
if(command == 'r'): # 刷新
break
prompt = ">>"
def countDown():
# 获取今天的日期
month = m = time.localtime().tm_mon
day = time.localtime().tm_mday
# 计算今天到12月25日的差值
d2 = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}
count = 0
if month < 12:
while m < 12:
if m == month: # 如果是当月,增加差值
count += d2[month] - day
else:
count += d2[m] # 不是当月,则增加当月天数
m += 1
if m == 12:
count += 25
elif month == 12:
count += d2[12] - day
else:
count = 0
print("距离22年研究生考试初试还有{}天".format(count))
while 1:
localtime = time.localtime(time.time())
lovely_maid()
menu()
input()
|
40cbfb99fdce5b8b2963e8ab66d7268409d462f9
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
R-16Bob/my_maid
|
0bddbfbab8e5f93297bd9ee31532839726d7b005
|
2057c6ebee166c05cbff54c148dc1a9229380ee7
|
refs/heads/master
|
<file_sep>package com.example.varsh.singitforme;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class Main2Activity extends AppCompatActivity {
private Button register;
private EditText semail;
private EditText spass;
private EditText sname;
private Button adduser;
private TextView email;
private TextView pass;
private TextView name;
Button dl;
private FirebaseAuth firebaseAuth;
//private DatabaseReference databaseReference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
semail = (EditText) findViewById(R.id.emailedit);
spass = (EditText) findViewById(R.id.passedit);
sname = (EditText) findViewById(R.id.nameeedit);
email=(TextView) findViewById(R.id.emailtxt);
pass=(TextView) findViewById(R.id.passtxt);
name=(TextView) findViewById(R.id.nametxt);
semail.setSelected(false);
spass.setSelected(false);
sname.setSelected(false);
semail.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if(hasFocus)
{
semail.setHint("");
email.setText("Emailid");
}
}
});
spass.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if(hasFocus)
{
spass.setHint("");
pass.setText("<PASSWORD>");
}
}
});
sname.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if(hasFocus)
{
sname.setHint("");
name.setText("Name");
}
}
});
firebaseAuth = FirebaseAuth.getInstance();
// databaseReference=FirebaseDatabase.getInstance().getReference();
register = (Button) findViewById(R.id.btnreg);
dl=(Button)findViewById(R.id.btnreg);
register.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
final ProgressDialog progressDialog = ProgressDialog.show(Main2Activity.this, "Please wait...", "on process..", true);
(firebaseAuth.createUserWithEmailAndPassword(semail.getText().toString(), spass.getText().toString())).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (task.isSuccessful()) {
Toast.makeText(Main2Activity.this, "Sign in Successful", Toast.LENGTH_LONG).show();
Intent i = new Intent(Main2Activity.this, Home.class);
startActivity(i);
} else {
Log.e("error..", task.getException().toString());
Toast.makeText(Main2Activity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
});
/* dl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i=new Intent(Main2Activity.this,Login.class);
startActivity(i);
}
});*/
/*adduser=(Button)findViewById(R.id.addbtn);
adduser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name=sname.getText().toString().trim();
String email=semail.getText().toString().trim();
HashMap<String,String> datamap=new HashMap<String, String>();
datamap.put("Name",name);
datamap.put("Email",email);
databaseReference.push().setValue(datamap);
Toast.makeText(SignupActivity.this,"added user",Toast.LENGTH_LONG).show();
}
});*/
}
}
|
e86a45005f1aa3d35772e84bea36b03218c6c2d8
|
[
"Java"
] | 1
|
Java
|
Varshini-v/andr
|
07ad855bd053daf7cbb74ff3cbf3aff438681831
|
d6c8f710fe3ab1a8d1268f7df65fd97bb8ce1285
|
refs/heads/master
|
<repo_name>andymost/CTDA_3_course_work<file_sep>/stats/sherman.py
import numpy as np
def stat(sample):
variation_series = np.sort(sample)
n = len(variation_series)
one_by_n = 1 / (n + 1)
w = 0
i = 0
while i < len(sample):
u_cur = variation_series[i]
u_prev = 0
if i != 0:
u_prev = variation_series[i - 1]
w += 1 / 2 * np.abs(u_cur - u_prev - one_by_n)
i = i + 1
return w
def get_m(n):
return (n/(n + 1)) ** (n + 1)
def get_d(n):
numerator = (2 * n) ** (n + 2) + n * ((n - 1) ** (n + 2))
denominator = (n + 2) * ((n + 1) ** (n + 2))
subtrahend = (n / (n + 1)) ** (n + 2)
return numerator/denominator - subtrahend
def statNormalized(sample):
n = len(sample)
m = get_m(n)
d = get_d(n)
return (stat(sample) - m) / np.sqrt(d)
def statModified(sample):
n = len(sample)
u = (stat(sample) - (0.3679 * (1 - (1 / (2 * n))))) / ((0.2431 / np.sqrt(n)) * (1 - (0.605 / n)))
return u - (0.0955/np.sqrt(n)) * (u ** 2 - 1)<file_sep>/main.py
import numpy as np
import scipy.stats as st
import stats.chengSpring as chengSpring
import stats.moran as moran
import stats.sherman as sherman
from monteCarlo import monteCarlo
#количество наблюдений в выборке
n = 100
#количество выборок
N = 1000
def generateFunc(case = 0):
if case is 0:
return lambda:np.random.uniform(0, 1, n);
if case is 1:
return lambda:st.beta.rvs(1.22, 0.9, size=n)
if case is 2:
return lambda:st.beta.rvs(1.0, 0.75, size=n)
if case is 3:
return lambda:st.beta.rvs(0.8, 1.08, size=n)
if case is 4:
return lambda:st.gennorm.rvs(beta=8, loc=0.5, scale=0.5, size=n)
if case is 5:
return lambda:st.gennorm.rvs(beta=8, loc=0.45, scale=0.5, size=n)
return lambda:st.gennorm.rvs(beta = 8, loc = 0.5, scale = 0.4, size=n)
def statFunc(case = 'chengSpring'):
if case is 'chengSpring':
return chengSpring.stat
if case is 'moran' or case is 'moran1':
return moran.stat1
if case is 'moran2':
return moran.stat2
if case is 'sherman':
return sherman.stat
if case is 'shermanNormalized':
return sherman.statNormalized
return sherman.statModified
statNames = [
'chengSpring',
'moran',
'moran2',
'sherman',
'shermanNormalized',
'shermanModified',
]
hypotises = range(0, 7)
for statName in statNames:
for hypotise in hypotises:
print(statName, 'for hypotise', hypotise)
statF = statFunc(statName)
generateF = generateFunc(hypotise)
statSample = monteCarlo(N, n, statF, generateF, statName, hypotise is 0)
f = open(f'./output/H{hypotise}_{statName}_n={n}_N={N}.dat', 'w')
f.write(f'H{hypotise}_{statName}_{n}\n')
f.write(f'0 {n}\n')
for item in statSample:
f.write(f'{item}\n')
f.close()
<file_sep>/distance.py
import numpy as np
import scipy.stats as st
n = 100000
# print("Normal 0.0",
# max(
# abs(
# st.uniform.cdf(np.linspace(0, 1, n), 0, 1.) - st.gennorm.cdf(np.linspace(0, 1, n), 1.6, loc=0.5, scale=0.5))
# )
# )
# print("Normal 0.0", max(abs(st.uniform.cdf(np.linspace(0, 1, n), 0, 1.) - st.gennorm.cdf(np.linspace(0, 1, n), 30, loc=0.4, scale=0.5))))
# print("Normal 0.0", max(abs(st.uniform.cdf(np.linspace(0, 1, n), 0, 1.) - st.gennorm.cdf(np.linspace(0, 1, n), 30, loc=0.5, scale=0.4))))
print("H1 distance", max(abs(st.uniform.cdf(np.linspace(0, 1, n), 0, 1.) - st.beta.cdf(np.linspace(0, 1, n), 1.22, 0.9))))
print("H2 distance", max(abs(st.uniform.cdf(np.linspace(0, 1, n), 0, 1.) - st.beta.cdf(np.linspace(0, 1, n), 1., 0.75))))
print("H3 distance", max(abs(st.uniform.cdf(np.linspace(0, 1, n), 0, 1.) - st.beta.cdf(np.linspace(0, 1, n), 0.8, 1.08))))
print("H4 distance", max(abs(st.uniform.cdf(np.linspace(0, 1, n), 0, 1.) - st.gennorm.cdf(np.linspace(0, 1, n), 8, loc=0.5, scale=0.5))))
print("H5 distance", max(abs(st.uniform.cdf(np.linspace(0, 1, n), 0, 1.) - st.gennorm.cdf(np.linspace(0, 1, n), 8, loc=0.45, scale=0.5))))
print("H6 distance", max(abs(st.uniform.cdf(np.linspace(0, 1, n), 0, 1.) - st.gennorm.cdf(np.linspace(0, 1, n), 8, loc=0.5, scale=0.4))))
<file_sep>/monteCarlo.py
def monteCarlo(N, n, statFunc, generateFunc, generateName, isH0):
statistica = []
for i in range(N):
x = list(generateFunc())
statistica.append(statFunc(x))
if (i%100 == 0):
print(f'Done {i/N * 100}% MonteCarlo {generateName} {isH0}')
return statistica
<file_sep>/stats/moran.py
import numpy as np
def stat1(x):
x.insert(0, 0)
x.append(1)
x = sorted(x)
return sum([(x[i + 1] - x[i]) ** 2 for i in range(len(x) - 1)])
def stat2(x):
x.insert(0, 0)
x.append(1)
x = sorted(x)
n = len(x)
return -sum([np.log((n + 1) * (x[i + 1] - x[i])) for i in range(len(x) - 1)])
<file_sep>/stats/chengSpring.py
def stat(x):
x = sorted(x)
n = len(x)
mean = sum(x) / n
numerator = ((x[n - 1] - x[0]) * ((n + 1) / (n - 1))) ** 2
denominator = sum([(x[i] - mean) ** 2 for i in range(len(x) - 1)])
return numerator / denominator
|
49541efe3dbc2437549da3271cddf0fe8a85f7a1
|
[
"Python"
] | 6
|
Python
|
andymost/CTDA_3_course_work
|
d7a8b898dafd54b3b1770ff67c887f2f693e6ea0
|
d8e9b72595c0b16287908fa908a395b3f4af3331
|
refs/heads/master
|
<file_sep># Answers
1. What is React JS and what problems does it solve? Support your answer with concepts introduced in class and from your personal research on the web.
> React JS is a frontend javascript library that is maintained by Facebook and a community of individual developers and companies. It is used to make scaling large applications & handling vast amounts of date more efficiently. An example would be if there is a page that has data changes over time at high rates, ReactJS would be useful as DOM updates would need to be fast.
1. Describe component state.
> Component state is used to store information about the component that can change over time.
1. Describe props.
> In React 'props' are equivalent to global variables or objects.
1. What are side effects, and how do you sync effects in a React component to changes of certain state or props?
> Side effects in React are behaviours of functions. A function is said to have side effect if it trys to modify anything outside its body. For example, if it modifies a global variable, then it is a side effect.
<file_sep>// Write your Character component here
import React from 'react';
import './sWars.css';
const starwarsChar = (props) => (
<li className="cast">
<h3>
<span>{props.name}</span>
<span>{props.gender}</span>
<span>{props.height}</span>
<span>{props.eye_color}</span>
<span>{props.birth_year}</span>
</h3>
</li>
);
export default starwarsChar;<file_sep>import React, { Component } from 'react';
import './App.css';
import CharacterList from './components/starwarsChars';
import Loader from 'react-loader-spinner'
import styled from "styled-components";
class App extends Component {
state = {
forceData: {}
}
componentDidMount() {
setTimeout(() => this.getCharacters(), 3000);
}
getCharacters = (url = 'https://swapi.dev/api/people/') => {
fetch(url)
.then(res => res.json())
.then(data => {
this.setState({ forceData: data });
})
.catch(err => {
throw new Error(err);
});
};
render() {
const Container = styled.div `
.App {
text-align: center;
}
.Header {
color: #443e3e;
text-shadow: 1px 1px 5px #fff;
}
/* write your parent styles in here for your App.js */
.sWarsBG {
display: block;
height: 100%;
width: 100%;
position: absolute;
bottom: 0;
left: 0;
right: 0;
top: 0;
}
.sWarsBG {
background: url(./images/sWarsBG.gif);
background-size: fill;
}
.app {
max-width: 800px;
margin: 0 auto;
text-align: center;
color: #ffe81f;
position: relative;
padding: 1em;
}
.header {
font-size: 3rem;
color: white;
text-transform: uppercase;
word-spacing: .3em;
margin-bottom: 1rem;
position: relative;
text-shadow: 2px 2px #000000;
}
.header > span {
cursor: pointer;
position: absolute;
top: 0;
}
.header > span.next {
right: -1em;
content: url(./images/sWarsRight.png);
}
.header > span.prev {
top: 0;
content: url(./images/sWarsLeft.png);
left: -1em;
}
.header {
text-shadow: 0 0 4px rgb(9, 218, 255); color: transparent;
}
`
console.log(this.state.forceData)
const { results, previous, next } = this.state.forceData;
return (
<Container>
<React.Fragment>
<div className="sWarsBG">
<div className="app">
<div className="header">
{previous ? <span alt="title" title="Pagination" className="prev" onClick={() => this.getCharacters(previous)}>.</span> : null}
<h1>Characters</h1>
{next ? <span className="next" onClick={() => this.getCharacters(next)}>.</span> : null}
</div>
{results
? <CharacterList chars={results} />
: <Loader type="Audio" color="cyan" secondaryColor="#ffffff " height={500} width={500} timeout={0}/>
}
</div>
</div>
</React.Fragment>
</Container>
);
}
}
export default App;<file_sep>import React from 'react';
import Character from './starwarsChar';
import './sWars.css';
const starwarsChars = (props) => (
<ul className="starwarsChars">
{props.chars.map(char => (
<Character key={char.name} {...char} />
))}
</ul>
);
export default starwarsChars;
|
8a397aea19f8e465a27819e5a27c6548fe90aa51
|
[
"Markdown",
"JavaScript"
] | 4
|
Markdown
|
CloudGang/Sprint-Challenge-React-Wars
|
73460b6a8dc09687ee5134117cc8df7262467fac
|
a3cb6ccbc9dc687826832baabbb1b7662309b1e6
|
refs/heads/main
|
<repo_name>sriniwas14/NodeJS_Express_API_Boilerplate<file_sep>/README.md
# NodeJS_Express_API_Boilerplate
An Express RestAPI Boilerplace with JWT Based User Creation and Authentication
## Introduction
As the name implies this application is a boilerplace that I use to get started with creating an API for my Web Applications
## Features
* User Account Creation
* Login With JWT
* Forgot Password with SMTP sendmail
## Getting Started
To get started create a mysql database and populate that with the `databaseSchema` that is provided in this repo.
For setting up the environment variables you can rename the provided `envSample` file to `.env` and then modify it according to your needs.
## Environment Variables
This section provides an introduction to the environment variables we are using in this application
|Name| Value|
|----|----|
|PORT| The Port on which this app will run on|
|JWT_KEY | The JWT Secret Key|
|JWT_EXPIRATION | For how long will the Key be valid|
| MAIL_USER | SMTP mail username |
| MAIL_PASS | SMTP mail password |
| MAIL_FROM | The name of the account which will appear on the sent email |
| SITE_URL | The URL for the Site it will be hosted on |
| DB_HOST | Hostname for the Database |
| DB_NAME | Name of the Database |
| DB_USER | Username for the Database |
| DB_PASS | Password for the Database |
## Need Help?
1. [Express JS](https://www.npmjs.com/package/express)
2. [JWT](https://www.npmjs.com/package/jsonwebtoken)
3. [Bcrypt](https://www.npmjs.com/package/bcrypt)
<file_sep>/databaseSchema.sql
-- Adminer 4.7.8 MySQL dump
SET NAMES utf8;
SET time_zone = '+00:00';
SET foreign_key_checks = 0;
SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';
SET NAMES utf8mb4;
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`userId` varchar(40) COLLATE utf8mb4_unicode_ci NOT NULL,
`username` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`password` varchar(250) COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
DROP TABLE IF EXISTS `user_details`;
CREATE TABLE `user_details` (
`userId` varchar(40) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`first_name` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`last_name` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`nickname` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`profile_pic` text COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`header_pic` text COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`dob` date DEFAULT NULL,
`phone` varchar(25) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`bio` text COLLATE utf8mb4_unicode_ci DEFAULT NULL,
KEY `user_details_FK` (`userId`),
CONSTRAINT `user_details_FK` FOREIGN KEY (`userId`) REFERENCES `users` (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
DROP TABLE IF EXISTS `user_relationships`;
CREATE TABLE `user_relationships` (
`followerId` varchar(40) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`followingId` varchar(40) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
KEY `user_relationships_FK` (`followerId`),
KEY `user_relationships_FK_1` (`followingId`),
CONSTRAINT `user_relationships_FK` FOREIGN KEY (`followerId`) REFERENCES `users` (`userId`),
CONSTRAINT `user_relationships_FK_1` FOREIGN KEY (`followingId`) REFERENCES `users` (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- 2021-02-06 06:02:56
|
fdf1eeddfef35035326b30e6a414d2d399521d79
|
[
"Markdown",
"SQL"
] | 2
|
Markdown
|
sriniwas14/NodeJS_Express_API_Boilerplate
|
cf2bf932340fc20b82c23c2dc20cb9406c285645
|
5a9c460e17ae1e95b62df4d0de2d102a9b5ac643
|
refs/heads/master
|
<repo_name>aisleypay/for-each-lab-web-040317<file_sep>/index.js
function iterativeLog(array) {
array.forEach(function (element, index) {
console.log(`${index}: ${element}`)
});
}
function iterate(cb) {
var array = ['Beyonce'];
array.forEach(cb);
return array;
}
function doToArray(array, cb) {
array.forEach(cb);
}
|
0026d65985bdf70b9c06577b9ecf4c7cd6b05288
|
[
"JavaScript"
] | 1
|
JavaScript
|
aisleypay/for-each-lab-web-040317
|
9c4ef129bf1d82ed325eecb70a757c6cb0e323b9
|
710a7bab6d2d78bb47b8f4b3a572557a4ecad075
|
refs/heads/main
|
<file_sep>// burger bar & navigation
let toggleButton = document.getElementById('toggleButton');
let navbarLinks = document.getElementById('navbarLinks');
toggleButton.addEventListener('click', function(){
navbarLinks.classList.toggle('open');
})
const menuBtn = document.querySelector('.burger-bar-div');
const logoBox = document.querySelector('.logo-div');
let menuOpen = false;
menuBtn.addEventListener('click', ()=>{
if(!menuOpen){
menuBtn.classList.add('opened');
logoBox.classList.add('opened')
menuOpen = true;
}else{
menuBtn.classList.remove('opened');
logoBox.classList.remove('opened')
menuOpen = false;
}
});
|
2cb8d8b897b0c26d62fca2fea3936e31b74f6a74
|
[
"JavaScript"
] | 1
|
JavaScript
|
LindaGiorgadze/GeolabPage
|
0f998c81b7c0ed1d8b2cc074cef49fdd081c9001
|
378495c1240febf8852057958a21ff86e38cc4be
|
refs/heads/main
|
<repo_name>raja1111111/dom_assignment<file_sep>/js/index.js
const siteContent = {
nav: {
'nav-item-1': 'Services',
'nav-item-2': 'Product',
'nav-item-3': 'Vision',
'nav-item-4': 'Features',
'nav-item-5': 'About',
'nav-item-6': 'Contact',
'img-src': 'img/logo.png',
},
cta: {
h1: 'DOM Is Awesome',
button: 'Get Started',
'img-src': 'img/header-img.png',
},
'main-content': {
'features-h4': 'Features',
'features-content':
'Features content elementum magna eros, ac posuere elvit tempus et. Suspendisse vel tempus odio, in interdutm nisi. Suspendisse eu ornare nisl. Nullam convallis augue justo, at imperdiet metus scelerisque quis.',
'about-h4': 'About',
'about-content':
'About content elementum magna eros, ac posuere elvit tempus et. Suspendisse vel tempus odio, in interdutm nisi. Suspendisse eu ornare nisl. Nullam convallis augue justo, at imperdiet metus scelerisque quis.',
'middle-img-src': 'img/mid-page.jpg',
'services-h4': 'Services',
'services-content':
'Services content elementum magna eros, ac posuere elvit tempus et. Suspendisse vel tempus odio, in interdutm nisi. Suspendisse eu ornare nisl. Nullam convallis augue justo, at imperdiet metus scelerisque quis.',
'product-h4': 'Product',
'product-content':
'Product content elementum magna eros, ac posuere elvit tempus et. Suspendisse vel tempus odio, in interdutm nisi. Suspendisse eu ornare nisl. Nullam convallis augue justo, at imperdiet metus scelerisque quis.',
'vision-h4': 'Vision',
'vision-content':
'Vision content elementum magna eros, ac posuere elvit tempus et. Suspendisse vel tempus odio, in interdutm nisi. Suspendisse eu ornare nisl. Nullam convallis augue justo, at imperdiet metus scelerisque quis.',
},
contact: {
'contact-h4': 'Contact',
address: '123 Way 456 Street Somewhere, USA',
phone: '1 (888) 888-8888',
email: '<EMAIL>',
},
footer: {
copyright: 'Copyright Great Idea! 2020',
},
};
// write your code here
document.head.insertAdjacentHTML( 'beforeend', '<link rel="stylesheet" href="./css/index.css">' );
var addbtn = document.createElement("button");
addbtn.appendChild(document.createTextNode("update page"));
var page = document.getElementsByClassName("cta-text")[0];
page.appendChild(addbtn);
console.log(addbtn);
addbtn.addEventListener('click' ,() => {
const header1 = document.createElement('header');
const nav1 = document.createElement('nav');
const a1 = document.createElement('a');
const a2 = document.createElement('a');
const a3 = document.createElement('a');
const a4 = document.createElement('a');
const a5 = document.createElement('a');
const a6 = document.createElement('a');
const a7 = document.createElement('a');
const a8 = document.createElement('a');
// const img1 = document.createElement('img');
//img1.setAttribute('src' , 'img/logo.png' );
// // a2.textContent('Product')
// // a3.textContent('Vision')
// // a4.textContent('Features')
// // a5.textContent('About')
// // a6.textContent('Contact')
var link1 = document.createTextNode("Services");
var link2 = document.createTextNode('Product');
var link3 = document.createTextNode('Vision');
var link4 = document.createTextNode('Features');
var link5 = document.createTextNode('About');
var link6 = document.createTextNode('Contact');
var link7 = document.createTextNode('Information');
var link8 = document.createTextNode('Sport');
a1.appendChild(link1);
a2.appendChild(link2);
a3.appendChild(link3);
a4.appendChild(link4);
a5.appendChild(link5);
a6.appendChild(link6);
a7.appendChild(link7);
a8.appendChild(link8);
nav1.appendChild(a1);
nav1.appendChild(a2);
nav1.appendChild(a3);
nav1.appendChild(a4);
nav1.appendChild(a5);
nav1.appendChild(a6);
nav1.appendChild(a7);
nav1.appendChild(a8);
a1.style.color="green"
a2.style.color="green"
a3.style.color="green"
a4.style.color="green"
a5.style.color="green"
a6.style.color="green"
a7.style.color="green"
a8.style.color="green"
var imgReplace = document.getElementsByClassName("logo")[0];
imgReplace.src = "img/logo.png";
imgReplace.classList.add('logo')
imgReplace.setAttribute('alt','Great Idea! Company logo')
header1.appendChild(nav1)
//header1.appendChild(img1)
// document.querySelector('.logo').appendChild(header1)
document.getElementsByTagName('nav')[0].appendChild(header1)
const par1 =document.querySelector('h1');
par1.textContent ='DOM Is Awesome';
const par23 =document.querySelector('button');
par23.textContent ='Get Started';
var imgReplace1 = document.getElementById("cta-img");
imgReplace1.src = 'img/header-img.png';
// imgReplace.classList.add('logo')
imgReplace1.setAttribute('alt','Image of a code snippet.')
const he2 =document.querySelector('h4');
he2.textContent = 'Features';
const par2 =document.getElementsByTagName('p')[0];
par2.textContent = 'Features content elementum magna eros, ac posuere elvit tempus et. Suspendisse vel tempus odio, in interdutm nisi. Suspendisse eu ornare nisl. Nullam convallis augue justo, at imperdiet metus scelerisque quis.';
;
const he3 =document.getElementsByTagName('h4')[1];
he3.textContent = 'About';
const par3 =document.getElementsByTagName('p')[1];
par3.textContent = 'About content elementum magna eros, ac posuere elvit tempus et. Suspendisse vel tempus odio, in interdutm nisi. Suspendisse eu ornare nisl. Nullam convallis augue justo, at imperdiet metus scelerisque quis.';
var imgReplace2 = document.getElementById("middle-img");
imgReplace2.src = 'img/mid-page.jpg';
// imgReplace.classList.add('logo')
imgReplace2.setAttribute('alt',"Image of code snippets across the screen");
const he4 =document.getElementsByTagName('h4')[2];
he4.textContent = 'Services';
const par4 =document.getElementsByTagName('p')[2];
par4.textContent = 'Services content elementum magna eros, ac posuere elvit tempus et. Suspendisse vel tempus odio, in interdutm nisi. Suspendisse eu ornare nisl. Nullam convallis augue justo, at imperdiet metus scelerisque quis.';
const he5 =document.getElementsByTagName('h4')[3];
he5.textContent = 'Product';
const par5 =document.getElementsByTagName('p')[3];
par5.textContent = 'Product content elementum magna eros, ac posuere elvit tempus et. Suspendisse vel tempus odio, in interdutm nisi. Suspendisse eu ornare nisl. Nullam convallis augue justo, at imperdiet metus scelerisque quis.';
const he6 =document.getElementsByTagName('h4')[4];
he6.textContent = 'Vision';
const par6 =document.getElementsByTagName('p')[4];
par6.textContent = 'Vision content elementum magna eros, ac posuere elvit tempus et. Suspendisse vel tempus odio, in interdutm nisi. Suspendisse eu ornare nisl. Nullam convallis augue justo, at imperdiet metus scelerisque quis.';
const he7 =document.getElementsByTagName('h4')[5];
he7.textContent = 'Contact';
const par8 =document.getElementsByTagName('p')[5];
par8.textContent = '123 Way 456 Street Somewhere, USA'
const par9 =document.getElementsByTagName('p')[6];
par9.textContent = '1 (888) 888-8888';
const par0 =document.getElementsByTagName('p')[7];
par0.textContent = '<EMAIL>';
const par44 =document.getElementsByTagName('p')[8];
par44.textContent = 'Copyright Great Idea! 2020';
// var a = document.createElement('a');
// // Create the text node for anchor element.
// var link = document.createTextNode("This is link");
// // Append the text node to anchor element.
// a.appendChild(link);
// // Set the title.
// a.title = "This is Link";
// // Set the href property.
// a.href = "https://www.geeksforgeeks.org";
// // Append the anchor element to the body.
// // document.header.appendChild(a1);
})
|
fa4a7e2ee45f8bb411eb3fdd1d6e3012268349c4
|
[
"JavaScript"
] | 1
|
JavaScript
|
raja1111111/dom_assignment
|
ba7aec143e68a7ef9a06074ee355177c38fd34f1
|
1f0e1d014e5b877daaccee7373ee112749332dcc
|
refs/heads/master
|
<file_sep>package com.pi.activity.DAO;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import androidx.appcompat.app.AlertDialog;
import com.pi.adapter.PecaAdapter;
import com.pi.model.Peca;
import java.util.List;
public class PecasDAO {
public void RemoveItem(final int position, Context context, List<Peca> myDataSet, PecaAdapter adapter) {
/*Logger logger=Logger.getLogger(PecasDAO.class.getName());
System.out.println(logger.toString());*/
Log.d("teste","teste");
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Remove?");
alertDialog.setMessage("Do you want to remove " + myDataSet.get(position).getNome() + "?");
alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
myDataSet.remove(position);
adapter.notifyDataSetChanged();
}
});
alertDialog.setNegativeButton("Cancel", null);
alertDialog.show();
}
public void AdicionaItem(List<Peca> myDataSet,Peca peca){
myDataSet.add(peca);
}
public void EditaItem(Peca peca_data,Peca peca2){
peca_data.setTudo(peca2.getNome(),peca2.getCodigo(),peca2.getCategoria(),100,peca2.isAtiva());
}
}
<file_sep># Projeto Integrador 2021 - 1
## Integrantes
<NAME> - 832961
<NAME> - 832863
<NAME> - 826635
<NAME> - 831531
<file_sep>package com.pi.adapter;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.pi.R;
import com.pi.model.Peca;
import com.pi.model.Preco;
import java.util.ArrayList;
import java.util.List;
public class PecaAdapter extends RecyclerView.Adapter<PecaAdapter.MyViewHolder> implements Filterable{
private List<Peca> dataSet;
private OnItemClickListener listener;
private List<Peca> dataSetFull;
/*private List<String> nomeList;
private List<String> nomeListAll;*/
public PecaAdapter(List<Peca> dataSet, OnItemClickListener listener, List<String> nomeList) {
this.dataSet = dataSet;
this.listener = listener;
this.dataSetFull=new ArrayList<>(dataSet);
//this.nomeList=nomeList;
//this.nomeListAll=new ArrayList<>(nomeList);
}
public void setDataSetFull(List<Peca> dataSetFull) {
this.dataSetFull = dataSetFull;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemList = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_layout, parent, false);
return new MyViewHolder(itemList);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
Peca peca = dataSet.get(position);
holder.codigoTextView.setText(peca.getCodigo());
holder.nameTextView.setText(peca.getNome());
holder.categoriaTextView.setText(peca.getCategoria());
Preco pre=peca.getPrecos().get(peca.getPrecos().size()-1);
holder.valorVendaTextView.setText("R$ "+pre.calcula_preco());
if(!peca.isAtiva()){
holder.statusImageView.setImageResource(R.drawable.ic_status_no);
}
}
@Override
public int getItemCount() {
return dataSet.size();
}
@Override
public Filter getFilter() {
return filter;
}
private Filter filter=new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
List<Peca> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(dataSetFull);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for(Peca item : dataSetFull){
if(item.getNome().toLowerCase().contains(filterPattern) || item.getCodigo().toLowerCase().contains(filterPattern)){
filteredList.add(item);
}
}
}
FilterResults results=new FilterResults();
results.values=filteredList;
return results;
/*
if(constraint.toString().isEmpty()){
filteredList.addAll(nomeListAll);
}else{
for(String nome: nomeListAll){
if(nome.toLowerCase().contains(constraint.toString().toLowerCase())){
filteredList.add(nome);
}
}
}
filteredList.add("Pneu");
filterResults.values=filteredList;
return filterResults;*/
//FilterResults filterResults=new FilterResults();
//return filterResults;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
Log.d("Teste","Teste");
dataSet.clear();
dataSet.addAll((List) results.values);
//nomeList.clear();
//nomeList.addAll((Collection<? extends String>) results.values);
notifyDataSetChanged();
}
};
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnCreateContextMenuListener
{
public TextView codigoTextView;
public TextView nameTextView;
public TextView categoriaTextView;
public TextView valorVendaTextView;
public ImageView statusImageView;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
codigoTextView = itemView.findViewById(R.id.itemCodigo_textView);
nameTextView = itemView.findViewById(R.id.itemName_textView);
categoriaTextView=itemView.findViewById(R.id.itemCategoria_textView);
valorVendaTextView=itemView.findViewById(R.id.itemValorVenda_textView);
statusImageView=itemView.findViewById(R.id.itemStatus_imageView);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
@Override
public void onClick(View v) {
listener.onItemClick(getAdapterPosition());
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select an action");
menu.add(getAdapterPosition(), 222, 0, "Remove");
// menu.add(getAdapterPosition(), 223, 1, "Share");
}
}
public interface OnItemClickListener {
void onItemClick(int position);
}
}
<file_sep>package com.pi.activity;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.pi.R;
import com.pi.model.Peca;
import com.pi.model.Preco;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class AddActivity extends AppCompatActivity {
public static final String EXTRA_NEW_CONTACT = "EXTRA_NEW_CONTACT";
private EditText name_editText;
private EditText codigo_editText;
private EditText categoria_editText;
private EditText custo_editText;
private EditText lucro_editText;
private Button save_button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
name_editText = findViewById(R.id.name_editText);
codigo_editText = findViewById(R.id.codigo_editText);
categoria_editText = findViewById(R.id.categoria_editText);
custo_editText = findViewById(R.id.cust_editText);
lucro_editText = findViewById(R.id.lucr_editText);
// status_editText = findViewById(R.id.status_editText);
save_button = findViewById(R.id.save_button);
save_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String name = name_editText.getText().toString();
final String codigo = codigo_editText.getText().toString();
final String categoria = categoria_editText.getText().toString();
final double lucro = Double.parseDouble(lucro_editText.getText().toString().replace(",", "."));
final double custo =Double.parseDouble(custo_editText.getText().toString().replace(",", "."));
final boolean status = true;
if (name.length() == 0) {
name_editText.requestFocus();
name_editText.setError("FIELD CANNOT BE EMPTY");
} else if (codigo.length() == 0) {
codigo_editText.requestFocus();
codigo_editText.setError("FIELD CANNOT BE EMPTY");
} else if (categoria.length() == 0) {
categoria_editText.requestFocus();
categoria_editText.setError("FIELD CANNOT BE EMPTY");
} /*else if (valorVenda_editText.length() == 0) {
valorVenda_editText.requestFocus();
valorVenda_editText.setError("FIELD CANNOT BE EMPTY");
} */else {
Intent data = new Intent();
Date dataAtual=new Date(System.currentTimeMillis());
DateFormat dateFormat=new SimpleDateFormat("dd/MM/yyyy");
String dataFormatada = dateFormat.format(dataAtual);
Preco preco8=new Preco(custo,lucro,dataFormatada);
Peca peca = new Peca(name, codigo, categoria, status,preco8);
data.putExtra(EXTRA_NEW_CONTACT, peca);
setResult(RESULT_OK, data);
finish();
}
}
});
}
}<file_sep>package com.pi.adapter;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.pi.R;
import com.pi.model.Peca;
import com.pi.model.Preco;
import java.util.ArrayList;
import java.util.List;
public class PrecoAdapter extends RecyclerView.Adapter<PrecoAdapter.MyViewHolder>{
private ArrayList<Preco> dataSet;
private OnItemClickListener listener;
/*private List<String> nomeList;
private List<String> nomeListAll;*/
public PrecoAdapter(ArrayList<Preco> dataSet, OnItemClickListener listener) {
this.dataSet = dataSet;
this.listener = listener;
//this.nomeList=nomeList;
//this.nomeListAll=new ArrayList<>(nomeList);
}
@NonNull
@Override
public PrecoAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemList = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_preco_layout, parent, false);
return new PrecoAdapter.MyViewHolder(itemList);
}
@Override
public void onBindViewHolder(@NonNull PrecoAdapter.MyViewHolder holder, int position) {
Preco preco = dataSet.get(position);
holder.dataPreco_textView.setText("Data: "+(preco.getData()));
holder.custo_textView.setText("Custo: "+Double.toString(preco.getCusto()));
holder.lucro_textView.setText("Lucro: "+Double.toString(preco.getLucro()));
holder.preco_textView.setText("Venda: "+Double.toString(preco.calcula_preco()));
}
@Override
public int getItemCount() {
return dataSet.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnCreateContextMenuListener
{
public TextView dataPreco_textView;
public TextView custo_textView;
public TextView lucro_textView;
public TextView preco_textView;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
dataPreco_textView = itemView.findViewById(R.id.dataPreco_textView);
custo_textView = itemView.findViewById(R.id.custo_textView);
lucro_textView = itemView.findViewById(R.id.lucro_textView);
preco_textView = itemView.findViewById(R.id.preco_textView);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
@Override
public void onClick(View v) {
listener.onItemClick(getAdapterPosition());
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select an action");
menu.add(getAdapterPosition(), 222, 0, "Remove");
// menu.add(getAdapterPosition(), 223, 1, "Share");
}
}
public interface OnItemClickListener {
void onItemClick(int position);
}
}<file_sep>package com.pi.activity;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.pi.R;
import com.pi.adapter.PrecoAdapter;
import com.pi.model.Peca;
import com.pi.model.Preco;
import java.util.ArrayList;
public class ShowActivity extends AppCompatActivity implements PrecoAdapter.OnItemClickListener {
public static final String EXTRA_EDIT_PIECE = "EXTRA_EDIT_PIECE";
public static final String EXTRA_EDIT_PIECE2 = "EXTRA_EDIT_PIECE2";
public static final String CONTAGEM ="CONTAGEM";
private static final int MAIN_REQUEST = 3;
private static final int PRECO_REQUEST = 4;
private static final int PRECC=1;
public static ArrayList<Preco> precoos;
private int contt;
/*private TextView nomeTextView;
private TextView codigoTextView;
private TextView categoriaTextView;
private TextView valorVendaTextView;
private TextView statusTextView;*/
private EditText nomeTextView;
private EditText codigoTextView;
private EditText categoriaTextView;
private EditText valorVendaTextView;
private TextView custo_textView;
private TextView lucro_textView;
private TextView venda_textView;
private Button edit_button;
private ImageView image_button;
private SwitchCompat switchCompat;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show);
ArrayList<Preco> precoos = ShowActivity.precoos;
image_button=findViewById(R.id.image_preco);
nomeTextView = findViewById(R.id.nome_textView);
codigoTextView = findViewById(R.id.codigo_textView);
categoriaTextView = findViewById(R.id.categoria_textView);
//valorVendaTextView = findViewById(R.id.valorVenda_textView);
switchCompat = findViewById(R.id.status_textView);
custo_textView = findViewById(R.id.custo_textView);
lucro_textView = findViewById(R.id.lucro_textView);
venda_textView = findViewById(R.id.venda_textView);
Intent intent = getIntent();
//image_button.setBackgroundColor(getContext().getResources().getColor(R.color.black));
Peca peca = (Peca) intent.getSerializableExtra(MainActivity.EXTRA_SHOW);
int teste = (int) intent.getSerializableExtra(MainActivity.CONTAGEM_FINAL);
nomeTextView.setText(peca.getNome());
codigoTextView.setText(peca.getCodigo());
categoriaTextView.setText(peca.getCategoria());
//valorVendaTextView.setText(new DecimalFormat("0.##").format(peca.getValorVenda()).replace(".", ","));
switchCompat.setText(peca.isAtiva() ? "Ativado" : "Desativado");
switchCompat.setChecked(peca.isAtiva() ? true : false);
switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
switchCompat.setText("Ativa");
switchCompat.setChecked(true);
}else{
switchCompat.setText("Desativa");
switchCompat.setChecked(false);
}
}
});
int tamanho=precoos.size() - 1;
custo_textView.setText("Custo: "+Double.toString(precoos.get(tamanho).getCusto()));
lucro_textView.setText("Lucro: "+Double.toString(precoos.get(tamanho).getLucro()));
venda_textView.setText("Venda: "+Double.toString(precoos.get(tamanho).calcula_preco()));
edit_button = findViewById(R.id.edit_button);
image_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//final String name = nomeTextView.getText().toString();
//final String codigo = codigoTextView.getText().toString();
//final String categoria = categoriaTextView.getText().toString();
//final double valorVenda = Double.parseDouble(valorVendaTextView.getText().toString().replace(",", "."));
//final boolean status = true;
// Peca peca2 = new Peca(name, codigo, categoria, valorVenda, status);
PrecoActivity.precoos=precoos;
Intent data = new Intent(ShowActivity.this,PrecoActivity.class);
//data.putExtra(CONTAGEM, teste);
data.putExtra(CONTAGEM, teste);/*
data.putExtra(EXTRA_EDIT_PIECE2, peca2);*/
startActivityForResult(data,PRECO_REQUEST);
setResult(RESULT_OK, data);
//finish();
}
});
edit_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String name = nomeTextView.getText().toString();
final String codigo = codigoTextView.getText().toString();
final String categoria = categoriaTextView.getText().toString();
//final double valorVenda = Double.parseDouble(valorVendaTextView.getText().toString().replace(",", "."));
final boolean status;
if(switchCompat.isChecked()){
status=true;
}else{
status=false;
}
if (name.length() == 0) {
nomeTextView.requestFocus();
nomeTextView.setError("FIELD CANNOT BE EMPTY");
} else if (codigo.length() == 0) {
codigoTextView.requestFocus();
codigoTextView.setError("FIELD CANNOT BE EMPTY");
} else if (categoria.length() == 0) {
categoriaTextView.requestFocus();
categoriaTextView.setError("FIELD CANNOT BE EMPTY");
} /*else if (valorVendaTextView.length() == 0) {
valorVendaTextView.requestFocus();
valorVendaTextView.setError("FIELD CANNOT BE EMPTY");
} */else {
Intent data = new Intent();
Preco preco8=new Preco(300,0.5,"25/06/2021");
//ArrayList<Preco> precos1= new ArrayList<Preco>();
//precos1.add(preco8);
Peca peca2 = new Peca(name, codigo, categoria, status);
data.putExtra(CONTAGEM, teste);
data.putExtra(EXTRA_EDIT_PIECE, peca);
data.putExtra(EXTRA_EDIT_PIECE2, peca2);
setResult(RESULT_OK, data);
finish();
}
}
});
ShowActivity.precoos=null;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==PRECO_REQUEST) {
if (resultCode == RESULT_OK) {
Preco pre = (Preco) data.getSerializableExtra(PrecoActivity.PREC);
custo_textView.setText("Custo: "+Double.toString(pre.getCusto()));
lucro_textView.setText("Lucro: "+Double.toString(pre.getLucro()));
venda_textView.setText("Venda: "+Double.toString(pre.calcula_preco()));
}
}
}
@Override
public void onItemClick(int position) {
}
}<file_sep>package com.pi.model;
import java.io.Serializable;
public class Preco implements Serializable {
private double custo,lucro;
private String data;
public double getCusto() {
return custo;
}
public double getLucro() {
return lucro;
}
public String getData() {
return data;
}
public Preco(double custo, double lucro, String data) {
this.custo = custo;
this.lucro = lucro;
this.data=data;
}
public double calcula_preco(){
return custo * (lucro/100) + custo;
}
}
<file_sep>package com.pi.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Peca implements Serializable {
private String nome;
private String codigo;
private String categoria;
private double valorVenda;
private boolean ativa;
private ArrayList<Preco> precos;
public ArrayList<Preco> getPrecos() {
return precos;
}
public Peca () {
}
public Peca(String nome, String codigo, String categoria, boolean ativa,Preco preco){
this.nome = nome;
this.codigo = codigo;
this.categoria = categoria;
this.ativa=ativa;
this.precos=new ArrayList<>();
this.precos.add(preco);
}
public Peca (String nome, String codigo, String categoria, boolean ativa /*ArrayList<Preco> precos*/) {
this.nome = nome;
this.codigo = codigo;
this.categoria = categoria;
//this.valorVenda = valorVenda;
this.ativa = ativa;
}
public Peca (String nome, String codigo, String categoria, boolean ativa,ArrayList<Preco> precos) {
this.nome = nome;
this.codigo = codigo;
this.categoria = categoria;
this.ativa = ativa;
this.precos=precos;
}
public String getNome() {
return nome;
}
public void setTudo(String nome, String codigo, String categoria, double valorVenda, boolean ativa) {
this.nome = nome;
this.codigo = codigo;
this.categoria = categoria;
this.valorVenda = valorVenda;
this.ativa = ativa;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getCategoria() {
return categoria;
}
public void setCategoria(String categoria) {
this.categoria = categoria;
}
public double getValorVenda() {
return valorVenda;
}
public void setValorVenda(double valorVenda) {
this.valorVenda = valorVenda;
}
public boolean isAtiva() {
return ativa;
}
public void setAtiva(boolean ativa) {
this.ativa = ativa;
}
}
|
7c66c681eddf4a5f96f84be6803e13d21be35a48
|
[
"Markdown",
"Java"
] | 8
|
Java
|
chown-coffee/PI-20211
|
af332535bf1844870a75333615bf522f58f0d8cc
|
2916f996ed8bd08a47283436a220a9f9596532cd
|
refs/heads/master
|
<file_sep>#include "ackerman.h"
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
Allocator alloc;
int main(int argc, char ** argv) {
// input parameters (basic block size, memory length)
srand(std::time(nullptr));
int b = 128;
int M = 512*1024;
for (int i=1; i<argc; i+=2) {
if (strncmp(argv[i], "-b", 2) == 0) {
b = stoi(argv[i+1]);
} else if (strncmp(argv[i], "-s", 2) == 0) {
M = stoi(argv[i+1]);
} else if (strncmp(argv[i], "-h", 2) == 0) {
cout << "memtest [-b <blocksize>] [-s <memsize>]\n"
<< "-b <blocksize> defines the block size, in bytes. Default is 128 bytes.\n"
<< "-s <memsize> defines the size of the memory to be allocated, in bytes. Default is 512kB.\n"
<< endl;
return 0;
}
}
cout << "b: " << b << " m: " << M << endl;
alloc.init_allocator(b, M);
ackerman_main();
// release_allocator()
// called in the destructor
}
<file_sep># BuddySystemAllocator
A buddy system memory allocator developed by <NAME> and me for a project in our intro to operating systems class, originally hosted on Texas A&M's GitHub Enterprise. The main function tests the allocator by calling an implementation of the Ackerman function that allocates memory at the beginning of a call and releases it at the end.
<file_sep># makefile
CXXFLAGS = -std=c++11 -Wall -g
CXXFLAGS_TESTING = -std=c++11 -Wall -O2
UNAME_S := $(shell uname -s)
ifeq ($(UNAME_S),Darwin)
CXX = clang++
else
CXX = g++
endif
all: memtest
testing: memtest_f
ackerman.o: ackerman.cpp ackerman.h
$(CXX) $(CXXFLAGS) -c ackerman.cpp
my_allocator.o : my_allocator.cpp my_allocator.h
$(CXX) $(CXXFLAGS) -c my_allocator.cpp
memtest.o : memtest.cpp
$(CXX) $(CXXFLAGS) -c memtest.cpp
memtest: memtest.o ackerman.o my_allocator.o
$(CXX) $(CXXFLAGS) -o memtest memtest.o ackerman.o my_allocator.o
ackerman_f.o: ackerman.cpp ackerman.h
$(CXX) $(CXXFLAGS_TESTING) -c $<
my_allocator_f.o : my_allocator.cpp my_allocator.h
$(CXX) $(CXXFLAGS_TESTING) -c $<
memtest_f.o : memtest.cpp
$(CXX) $(CXXFLAGS_TESTING) -c $<
memtest_f: memtest_f.o ackerman_f.o my_allocator_f.o
$(CXX) $(CXXFLAGS_TESTING) -o memtest memtest.o ackerman.o my_allocator.o
clean:
rm *.o memtest
<file_sep>/*
File: my_allocator.c
Author: <NAME>, <NAME>
Department of Computer Science
Texas A&M University
Date : 10/11/15
Modified:
This file contains the implementation of the module "MY_ALLOCATOR".
*/
/*--------------------------------------------------------------------------*/
/* DEFINES */
/*--------------------------------------------------------------------------*/
/* -- (none) -- */
/*--------------------------------------------------------------------------*/
/* INCLUDES */
/*--------------------------------------------------------------------------*/
#include "my_allocator.h"
/*--------------------------------------------------------------------------*/
/* DATA STRUCTURES */
/*--------------------------------------------------------------------------*/
/* -- (none) -- */
/*--------------------------------------------------------------------------*/
/* CONSTANTS */
/*--------------------------------------------------------------------------*/
/* -- (none) -- */
/*--------------------------------------------------------------------------*/
/* FORWARDS */
/*--------------------------------------------------------------------------*/
/* -- (none) -- */
/*--------------------------------------------------------------------------*/
/* FUNCTIONS FOR MODULE MY_ALLOCATOR */
/*--------------------------------------------------------------------------*/
/* Don't forget to implement "init_allocator" and "release_allocator"! */
template <class T> T min(const T& a, const T& b) {
return a<b ? a : b;
}
bool Allocator::init_allocator(unsigned int _basic_block_size, unsigned int _length) {
basic_block_size = _basic_block_size;
mem_pool_length = _length;
mem_pool = (Addr)malloc(_length);
num_tiers = round(log2(_length/_basic_block_size))+1;
free_list = (Block**)malloc(num_tiers);
memset(free_list, 0, num_tiers*sizeof(Block*));
free_list[num_tiers-1] = (Block*)mem_pool;
free_list[num_tiers-1]->tier = num_tiers-1;
// std::cout << "Mem init check: " << (mem_pool != nullptr && free_list != nullptr) << std::endl;
// print_free();
return mem_pool != nullptr && free_list != nullptr;
}
int Allocator::release_allocator() {
free(mem_pool);
free(free_list);
return mem_pool == NULL && free_list == NULL;
}
Addr Allocator::my_malloc(unsigned int _length) {
int tier = round(ceil(log2((double)(_length+sizeof(Block))/basic_block_size)));
if (tier < 0) tier = 0;
//std::cout << "Tier: " << tier << " Num accessable tiers: " << num_tiers <<std::endl;
if (tier >= num_tiers) {
// the size is too large for the allocated memory
std::cerr << "Size is too large: returning nullptr." << std::endl;
return nullptr;
}
Block* free_node = free_list[tier];
// Fetch an empty block
if (free_node == nullptr) {
free_node = (Block*)find_block(tier, 1);
}
// Pass block
if (free_node != nullptr) {
free_list[tier] = free_node->next;
free_node->tier = tier;
free_node->occupied = true;
// print_mem();
// print_free();
//std::cout << free_node << std::endl;
return (Addr)(free_node+1);
} else {
// Error: Not enough space for the block
std::cerr << "Not Enough Space for block: returning nullptr." << std::endl;
return nullptr;
}
}
Addr Allocator::find_block(int original_tier, int increment_total) {
int i = original_tier + increment_total;
if (i >= num_tiers || i <= 0) {
std::cerr << "Incorrect Space!\n num_tiers: " << num_tiers << " i: " << i << std::endl;
return nullptr;
} else {
if (free_list[i] == nullptr) {
// go up a tier to check for space
return find_block(original_tier,increment_total+1);
} else {
// free block found!
return split(original_tier, increment_total);
}
}
}
Addr Allocator::split(int start, int remaining) {
int i = start + remaining;
if (remaining < 1) {
return (Addr)free_list[start];
}
// get the right half of the block
Block* right = (Block*)((char*)free_list[i] + (basic_block_size<<(i-1)));
// set it's next to the current free_list block
right->next = free_list[i-1];
right->tier = i-1;
// set the tier-1 free_list to the right (half) block
free_list[i-1] = right;
// get the left half of the block
Block* left = free_list[i];
// set the current free_list node to the next free_block
free_list[i] = free_list[i]->next;
// set it's next to the current free_list block
left->next = free_list[i-1];
right->tier = i-1;
// set the tier-1 free_list to the left (half) block
free_list[i-1] = left;
return split(start, remaining-1);
}
int Allocator::my_free(Addr _a) {
Block* b = ((Block*)_a)-1;
b->occupied = false;
int tier = ((Block*)b)->tier;
b->next = free_list[tier];
free_list[tier] = b;
merge(b);
// std::cout << "freeing" << std::endl;
// print_free();
//print_mem();
return 0;
}
void Allocator::merge(Block* a) {
Block* b = (Block*)get_buddy(a);
int tier = a->tier;
if (!(a->occupied) && !(b->occupied) && tier == b->tier && tier < num_tiers) {
// Remove a and b from current list tier
if (free_list[tier] == a) {
free_list[tier] = free_list[tier]->next;
}
if (free_list[tier] == b) {
free_list[tier] = free_list[tier]->next;
}
for (Block* n = free_list[tier]; n != nullptr; n = n->next) {
Block* next = n->next;
if (next == a || next == b) {
n->next = next->next;
}
}
// Add new block [ab] to list tier+1
Block* newblock = (Block*)min((long)a, (long)b);
newblock->tier = newblock->tier+1;
newblock->next = free_list[tier+1];
free_list[tier+1] = newblock;
merge(newblock);
}
}
Addr Allocator::get_buddy(Addr a) {
long rela = (long)a - (long)mem_pool;
long thing = basic_block_size<<(((Block*)a)->tier);
long buddy = rela^thing;
Addr b = (Addr)(buddy + (long)mem_pool);
return b;
}
void Allocator::print_mem() const {
char* temp0 = (char*)mem_pool;
std::cout << "mem_pool [";
while ((long)temp0 < (long)mem_pool+mem_pool_length) {
Block* temp = (Block*)temp0;
int size = basic_block_size<<(temp->tier);
int occupied = temp->occupied;
std::cout << occupied << std::setfill('-') << std::setw(size/basic_block_size);
temp0 = temp0 + size;
}
std::cout << "]" << std::endl;
}
void Allocator::print_free() const {
std::cout << "free_list" << std::endl
<< "(tier): [xxxx] " << std::endl;
for (int i = 0; i < num_tiers; i++) {
std::cout << i << ": [ ";
Block* temp=free_list[i];
if (temp != nullptr) {
std::cout << temp << " -> " << temp->next;
temp = temp->next;
} else {
std::cout << "nil";
}
/*for (; temp != nullptr; temp = temp->next) {
temp = free_list[i];
if (temp != nullptr) {
if (temp->next != nullptr) {
while (temp != nullptr) {
std::cout << temp->occupied;
temp = temp->next;
}
} else {
std::cout << temp->occupied;
}
} else {
std::cout << "nil";
}
std:: cout << " -> " << temp;
}*/
std::cout << " ]" << std::endl;
}
}
<file_sep>/*
File: my_allocator.h
Author: R.Bettati
Department of Computer Science
Texas A&M University
Date : 08/02/08
Modified: 10/11/15
<NAME>, <NAME>
*/
#ifndef _my_allocator_h_ // include file only once
#define _my_allocator_h_
/*--------------------------------------------------------------------------*/
/* DEFINES */
/*--------------------------------------------------------------------------*/
/* -- (none) -- */
/*--------------------------------------------------------------------------*/
/* INCLUDES */
/*--------------------------------------------------------------------------*/
#include <cmath>
#include <cstring>
#include <stdlib.h>
#include <iostream>
#include <iomanip>
/*--------------------------------------------------------------------------*/
/* DATA STRUCTURES */
/*--------------------------------------------------------------------------*/
typedef void * Addr;
/*--------------------------------------------------------------------------*/
/* FORWARDS */
/*--------------------------------------------------------------------------*/
/* -- (none) -- */
/*--------------------------------------------------------------------------*/
/* MODULE MY_ALLOCATOR */
/*--------------------------------------------------------------------------*/
/*
* Created a struct that allows the memory to be prefaced by this header.
* This allows the memory to know what blocks to merge back together
* and generate a free_list with much more ease as the free blocks are chainable.
*/
struct Block {
Block* next = nullptr;
unsigned int tier;
bool occupied = false;
Block() : next(nullptr), occupied(false) {}
};
/*
* Also the conversion from c -> c++ allows us to move the
* relaese into the deconstructor
*/
class Allocator {
unsigned int basic_block_size;
unsigned int num_tiers;
unsigned int mem_pool_length;
Addr mem_pool = nullptr;
Block** free_list = nullptr;
public:
Allocator() {}
Allocator(unsigned int b, unsigned int l) { init_allocator(b, l); }
~Allocator() { release_allocator(); }
bool init_allocator(unsigned int _basic_block_size,
unsigned int _length);
/* This function initializes the memory allocator and makes a portion of
’_length’ bytes available. The allocator uses a ’_basic_block_size’ as
its minimal unit of allocation. The function returns the amount of
memory made available to the allocator. If an error occurred,
it returns 0.
*/
int release_allocator();
/* This function returns any allocated memory to the operating system.
After this function is called, any allocation fails.
*/
Addr my_malloc(unsigned int _length);
/* Allocate _length number of bytes of free memory and returns the
address of the allocated portion. Returns 0 when out of memory. */
int my_free(Addr _a);
/* Frees the section of physical memory previously allocated
using ’my_malloc’. Returns 0 if everything ok. */
Addr find_block(int original_tier, int increment_total);
Addr split(int start, int remaining);
void merge(Block* a);
Addr get_buddy(Addr a);
void print_mem() const;
void print_free() const;
};
#endif
|
63ecfde536fb3ba9fbce9cb7070d9de7f2d9aa3a
|
[
"Markdown",
"Makefile",
"C++"
] | 5
|
C++
|
srawls1/BuddySystemAllocator
|
f65415155445fcd4fa0e35e7484863692972408e
|
fcd34dc605f3095214dc0b87f37b1809b02e4b06
|
refs/heads/master
|
<repo_name>fgoncalvesaf/simple-blog<file_sep>/app/models/post.rb
class Post < ApplicationRecord
has_attached_file :avatar, styles: { cover: "1000x500>", thumb: "250x250>" }
validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\z/
end
|
105ecbb81e5f2b5b2bd2d3a2cf446df5186a20bc
|
[
"Ruby"
] | 1
|
Ruby
|
fgoncalvesaf/simple-blog
|
d9b8320c84b6c401abff7c0235547638abe70886
|
97102fb95fb606754e3856c3b22bbff2cb52a429
|
refs/heads/master
|
<repo_name>LiewJunTung/dodgy<file_sep>/app/src/main/java/dodgy/com/dodgydetector/splash/SplashActivity.kt
package dodgy.com.dodgydetector.splash
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import dodgy.com.dodgydetector.R
import dodgy.com.dodgydetector.init.view.InitActivity
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import java.util.concurrent.TimeUnit
class SplashActivity : AppCompatActivity() {
private val compositeDisposable by lazy {
CompositeDisposable()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
goOnNext()
}
private fun goOnNext(){
compositeDisposable.add(Observable.just(this)
.delay(1500, TimeUnit.MILLISECONDS)
.map {
startActivity(Intent(SplashActivity@this, InitActivity::class.java))
finish()
}
.subscribe())
}
override fun onDestroy() {
if(!compositeDisposable.isDisposed){
compositeDisposable.dispose()
}
super.onDestroy()
}
}
|
8bacd84e3681b143cbf79f10c02521d76b25ac8a
|
[
"Kotlin"
] | 1
|
Kotlin
|
LiewJunTung/dodgy
|
72f78b992bafc1af1f79636a111269d0f8e73c5c
|
bb78fbeaded21834eed12a83a9af8d72b90334c2
|
refs/heads/master
|
<repo_name>MOsmanis/Permanent-Overdrive<file_sep>/README.txt
Terminal game made with Python library Curses. Originally made for Trijam17 in 6 hours. (https://itch.io/jam/trijam-17)
Later re-made into server-client 2 player version for computer networks class.
Video: https://youtu.be/OF8FJNXGzyM
Requirements
1. Install Curses for Python (run package_install.py)
How to use
For running a server:
1. In project folder, run "python server.py"
For connecting to server:
1. In project folder, run "python client.py {playerName}" ,
where playerName is your chosen name to show to the other player.
If playerName is not added, your name will be "player"
2. Game will start once 2 players have joined.
<file_sep>/server.py
import socket, threading
import pickle
PLAYER_COUNT = 0
PLAYER_NAMES = {}
PLAYER_SCORES = {}
PLAYER_MAX_SCORES = {}
PLAYER_STATUS = {}
PLAYER_GAME_BOARDS = {}
MAX_PLAYERS = 2
LOCALHOST = "127.0.0.1"
PORT = 8080
class PlayerData():
def __init__(self, name, score, max_score, status, game_board):
self.name = name
self.score = score
self.max_score = max_score
self.status = status
self.game_board = game_board
class ClientThread(threading.Thread):
def __init__(self,clientAddress,clientsocket, clientId):
threading.Thread.__init__(self)
self.csocket = clientsocket
self.id = clientId
print ("New connection added: ", clientAddress)
def run(self):
print ("Connection from : ", clientAddress)
playerData = self.csocket.recv(8192)
player = pickle.loads(playerData)
PLAYER_NAMES[self.id] = player.name
PLAYER_SCORES[self.id] = player.score
PLAYER_STATUS[self.id] = player.status
PLAYER_MAX_SCORES[self.id] = int(player.max_score)
PLAYER_GAME_BOARDS[self.id] = player.game_board
if(self.id==0):
print("Waiting for other player")
while( (len(PLAYER_NAMES) < MAX_PLAYERS) or (len(PLAYER_SCORES) < MAX_PLAYERS) or (len(PLAYER_STATUS) < MAX_PLAYERS) ):
continue
enemyId = (self.id + 1) % MAX_PLAYERS
enemyData = PlayerData(PLAYER_NAMES[enemyId], PLAYER_SCORES[enemyId], int(PLAYER_MAX_SCORES[enemyId]), PLAYER_STATUS[enemyId], PLAYER_GAME_BOARDS[enemyId])
print(enemyData.name)
data_string = pickle.dumps(enemyData)
self.csocket.send(data_string)
while True:
playerData = self.csocket.recv(8192)
player = pickle.loads(playerData)
PLAYER_NAMES[self.id] = player.name
PLAYER_SCORES[self.id] = player.score
if int(PLAYER_MAX_SCORES[self.id]) < int(player.max_score):
PLAYER_MAX_SCORES[self.id] = player.max_score
PLAYER_STATUS[self.id] = player.status
PLAYER_GAME_BOARDS[self.id] = player.game_board
enemyData = PlayerData(PLAYER_NAMES[enemyId], PLAYER_SCORES[enemyId], int(PLAYER_MAX_SCORES[enemyId]), PLAYER_STATUS[enemyId], PLAYER_GAME_BOARDS[enemyId])
data_string = pickle.dumps(enemyData)
self.csocket.send(data_string)
print ("Client at ", clientAddress , " disconnected...")
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((LOCALHOST, PORT))
print("Server started")
print("Waiting for client request..")
while True:
server.listen(1)
clientsock, clientAddress = server.accept()
newthread = ClientThread(clientAddress, clientsock, PLAYER_COUNT)
newthread.start()
PLAYER_COUNT+=1
if(PLAYER_COUNT==MAX_PLAYERS):
break<file_sep>/Permament-overdrive.py
import subprocess
import curses
import time
import random
from random import randint
Y = 50
X = 100
def main():
curses_controller = CursesController(0)
curses_controller.initCurses()
try:
game(curses_controller)
except KeyboardInterrupt:
curses_controller.closeCurses()
exit()
class O():
def __init__(self, **kwargs):
self.location = (17, 2)
self.level = 0
def move(self, direction, data):
newdata = data
if direction == "left":
x, y = self.location
if y <= -1:
return list("dead")
newPOS = newdata[34*y + x-1]
if newPOS == ' ':
self.location = (x - 1, y)
newdata[34 * y + x] = ' '
newdata[34 * y + x - 1] = 'O'
elif newPOS == 'I':
return list("dead")
elif newPOS == 'U':
return list("next")
if direction == "up":
x, y = self.location
if y <= -1:
return list("dead")
newPOS = newdata[34*(y-1) + x]
if newPOS == ' ':
self.location = (x, y - 1)
newdata[34 * y + x] = ' '
newdata[34 * (y-1) + x] = 'O'
elif newPOS == 'I':
return list("dead")
elif newPOS == 'U':
return list("next")
if direction == "right":
x, y = self.location
if y <= -1:
return list("dead")
newPOS = newdata[34 * y + x + 1]
if newPOS == ' ':
self.location = (x + 1, y)
newdata[34 * y + x] = ' '
newdata[34 * y + x + 1] = 'O'
elif newPOS == 'I':
return list("dead")
elif newPOS =='U':
return list("next")
if direction == "down":
x, y = self.location
if y <= -1:
y = 0
newPOS = newdata[34*(y+1) + x]
if newPOS == ' ':
self.location = (x, y + 1)
newdata[34 * y + x] = ' '
newdata[34 * (y+1) + x] = 'O'
elif newPOS == 'I':
return list("dead")
elif newPOS == 'U':
return list("next")
return newdata
class DesignConfig():
def __init__(self, **kwargs):
keys = kwargs.keys()
if 'font' in kwargs:
self.font = kwargs.get('font')
else:
self.font = 'starwars'
if 'message' in keys:
self.message = kwargs.get('message')
else:
self.message = 'Permanent Overdrive'
class CursesController():
def __init__(self, level):
self.level = level
self.data = list(
"IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII\n" +
"I I\n" +
"I Permanent Overdrive I\n" +
"I I\n" +
"I I\n" +
"I I\n" +
"I I\n" +
"I I\n" +
"IIIIIIIIIII IIIIIIIIIII\n" +
"I I\n" +
"I I\n" +
"UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU\n"
)
def initCurses(self):
self.stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
curses.curs_set(0)
self.stdscr.nodelay(1)
self.stdscr.keypad(1)
rows = "".join(self.data).split("\n")
i=0
for row in rows:
self.stdscr.addstr(0+i,0+X,row)
i+=1
self.stdscr.addstr(3, 50+X, "Score: " + str(self.level))
self.stdscr.addstr(6, 50+X, "Go to bottom to advance!")
self.stdscr.addstr(7, 50+X, "Movement speed is random for each key press")
self.stdscr.addstr(8, 50+X, "You die if you touch walls! ('I')")
self.stdscr.addstr(9, 50+X, "Press arrow to move in that direction")
self.stdscr.addstr(10, 50+X, "Move to start game")
self.stdscr.addstr(12, 50+X, "\"q\" to quit!")
def write(self):
self.stdscr.clear()
rows = "".join(self.data).split("\n")
i=0
for row in rows:
self.stdscr.addstr(0+i,0+X,row)
i+=1
self.stdscr.addstr(3, 50+X, "Score: " + str(self.level))
self.stdscr.addstr(6, 50+X, "Go to bottom to advance!")
self.stdscr.addstr(7, 50+X, "Movement speed is random for each key press")
self.stdscr.addstr(8, 50+X, "You die if you touch walls! ('I')")
self.stdscr.addstr(9, 50+X, "Press arrow to move in that direction")
self.stdscr.addstr(10, 50+X, "Move to start game")
self.stdscr.addstr(12, 50+X, "\"q\" to quit!")
def closeCurses(self):
curses.nocbreak()
self.stdscr.keypad(0)
curses.echo()
curses.endwin()
def cutBeginning(curses_controller, o):
data = curses_controller.data
lines_to_cut = 1
i = 0
while i < lines_to_cut:
curses_controller.data = data[34:]
i+=1
x, y = o.location
o.location = (x,(y-lines_to_cut))
refresh(curses_controller, o)
def game(curses_controller):
o = O()
while 1:
key = curses_controller.stdscr.getch()
if curses_controller.data != "Dead! Press \"r\" for restart":
if key == curses.KEY_LEFT:
cutBeginning(curses_controller, o)
random_move(curses_controller, o, "left")
#cutBeginning(curses_controller, o)
if key == curses.KEY_RIGHT:
cutBeginning(curses_controller, o)
random_move(curses_controller, o, "right")
#cutBeginning(curses_controller, o)
if key == curses.KEY_UP:
cutBeginning(curses_controller, o)
random_move(curses_controller, o, "up")
#cutBeginning(curses_controller, o)
if key == curses.KEY_DOWN:
cutBeginning(curses_controller, o)
random_move(curses_controller, o, "down")
#cutBeginning(curses_controller, o)
if key == ord('q'):
curses_controller.closeCurses()
exit()
else:
if key == ord('q'):
curses_controller.closeCurses()
exit()
if key == ord('r'):
curses_controller.closeCurses()
main()
def random_move(curses_controller, o, direction):
displacement = randint(1, 5)
if o.level < 5:
if direction == "left" or direction == "right":
displacement += 3
i = 0
while i < displacement:
i += 1
status = o.move(direction, curses_controller.data)
if "".join(status) == "dead":
curses_controller.data = "Dead! Press \"r\" for restart"
refresh(curses_controller, o)
break;
elif "".join(status) == "next":
o.level +=1
curses_controller.level=o.level
if o.level < 5:
random_wall = list("IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII\n")
hole = randint(3, 29)
random_wall[hole] = ' '
random_wall[hole + 1] = ' '
random_wall[hole + 2] = ' '
random_wall[hole - 1] = ' '
random_wall[hole - 2] = ' '
animate_open_doors(curses_controller, o)
curses_controller.data += list(
"I I\n" +
"I I\n" +
"I I\n" +
"I I\n" +
"I I\n" +
"I I\n" +
"I I\n" +
"I I\n" +
"".join(random_wall) +
"I I\n" +
"I I\n" +
"UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU\n"
)
refresh(curses_controller, o)
break;
elif o.level == 5:
animate_open_doors(curses_controller, o)
curses_controller.data += list(
"I I\n" +
"I I\n" +
"I I\n" +
"I I\n" +
"I I\n" +
"II II\n" +
"IIII IIII\n" +
"IIIIII IIIIII\n" +
"IIIIIIII IIIIIIII\n" +
"IIIIIIIIII IIIIIIIIII\n" +
"IIIIIIIIII IIIIIIIIII\n" +
"UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU\n"
)
refresh(curses_controller, o)
break;
elif o.level > 5:
animate_open_doors(curses_controller, o)
random_wall = list("IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII\n")
hole = randint(10, 22)
random_wall[hole] = ' '
animate_open_doors(curses_controller, o)
curses_controller.data += list(
"IIIIIIIIII IIIIIIIIII\n" +
"IIIIIIIIII IIIIIIIIII\n" +
"IIIIIIIIII IIIIIIIIII\n" +
"IIIIIIIIII IIIIIIIIII\n" +
"IIIIIIIIII IIIIIIIIII\n" +
"IIIIIIIIII IIIIIIIIII\n" +
"IIIIIIIIII IIIIIIIIII\n" +
"".join(random_wall) +
"IIIIIIIIII IIIIIIIIII\n" +
"IIIIIIIIII IIIIIIIIII\n" +
"IIIIIIIIII IIIIIIIIII\n" +
"UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU\n"
)
refresh(curses_controller, o)
break;
else:
curses_controller.data = status
refresh(curses_controller, o)
def refresh(curses_controller, o):
overflow = len(curses_controller.data) - (34 * Y)
if overflow > 0:
curses_controller.data = curses_controller.data[overflow:]
x, y = o.location
o.location = (x,(y-(overflow//34)))
curses_controller.write()
curses_controller.stdscr.refresh()
time.sleep(.030)
def animate_open_doors(curses_controller, o):
length = len(curses_controller.data)
curses_controller.data[length-18]=' '
refresh(curses_controller, o)
i = 1
width=2
if o.level > 5:
width=11
while i<17:
curses_controller.data[length-18+i]=' '
curses_controller.data[length-18-i]=' '
if i>17-width:
curses_controller.data[length-18+i]='I'
curses_controller.data[length-18-i]='I'
i+=1
refresh(curses_controller, o)
curses_controller.data[length-1]='\n'
refresh(curses_controller, o)
if __name__ == '__main__':
main()
<file_sep>/client.py
import subprocess
import curses
import time
import random
from random import randint
import socket
import pickle
import threading
import sys
SERVER = "127.0.0.1"
PORT = 8080
NAME = "player"
SCORE = 0
STATUS = "alive"
GAME_BOARD = "Loading..."
ENEMY_NAME = "Not connected"
ENEMY_SCORE = "Not connected"
ENEMY_MAX_SCORE = 0
ENEMY_STATUS = "Not connected"
ENEMY_X = 120
ENEMY_GAME_BOARD = "Not Connected"
WAITING_FOR_ENEMY = True
X = 20
def main():
if len(sys.argv)>1:
global NAME
NAME = sys.argv[1]
clientThread = ClientThread()
clientThread.start()
if(WAITING_FOR_ENEMY):
print("Waiting for second player...")
while(WAITING_FOR_ENEMY):
continue
try:
while(WAITING_FOR_ENEMY):
continue
curses_controller = CursesController(0)
curses_controller.initCurses()
game(curses_controller)
except KeyboardInterrupt:
curses_controller.closeCurses()
exit()
class ClientThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def run(self):
global ENEMY_NAME
global ENEMY_SCORE
global ENEMY_STATUS
global WAITING_FOR_ENEMY
global ENEMY_GAME_BOARD
self.client.connect((SERVER, PORT))
playerData = PlayerData(NAME, SCORE, SCORE, STATUS, GAME_BOARD)
data_string = pickle.dumps(playerData)
self.client.send(data_string)
enemyData = self.client.recv(8192)
enemy = pickle.loads(enemyData)
ENEMY_NAME = enemy.name
ENEMY_SCORE = enemy.score
ENEMY_MAX_SCORE = enemy.max_score
ENEMY_STATUS = enemy.status
ENEMY_GAME_BOARD = enemy.game_board
WAITING_FOR_ENEMY = False
while True:
playerData = PlayerData(NAME, SCORE, SCORE, STATUS, GAME_BOARD)
data_string = pickle.dumps(playerData)
self.client.send(data_string)
enemyData = self.client.recv(8192)
enemy = pickle.loads(enemyData)
ENEMY_NAME = enemy.name
ENEMY_SCORE = enemy.score
ENEMY_MAX_SCORE = enemy.max_score
ENEMY_STATUS = enemy.status
ENEMY_GAME_BOARD = enemy.game_board
class PlayerData():
def __init__(self, name, score, max_score, status, game_board):
self.name = name
self.score = score
self.max_score = max_score
self.status = status
self.game_board = game_board
class O():
def __init__(self, **kwargs):
self.location = (17, 2)
self.level = 0
def move(self, direction, data):
newdata = data
if direction == "left":
x, y = self.location
if y <= -1:
return list("dead")
newPOS = newdata[34*y + x-1]
if newPOS == ' ':
self.location = (x - 1, y)
newdata[34 * y + x] = ' '
newdata[34 * y + x - 1] = 'O'
elif newPOS == 'I':
return list("dead")
elif newPOS == 'U':
return list("next")
if direction == "up":
x, y = self.location
if y <= -1:
return list("dead")
newPOS = newdata[34*(y-1) + x]
if newPOS == ' ':
self.location = (x, y - 1)
newdata[34 * y + x] = ' '
newdata[34 * (y-1) + x] = 'O'
elif newPOS == 'I':
return list("dead")
elif newPOS == 'U':
return list("next")
if direction == "right":
x, y = self.location
if y <= -1:
return list("dead")
newPOS = newdata[34 * y + x + 1]
if newPOS == ' ':
self.location = (x + 1, y)
newdata[34 * y + x] = ' '
newdata[34 * y + x + 1] = 'O'
elif newPOS == 'I':
return list("dead")
elif newPOS =='U':
return list("next")
if direction == "down":
x, y = self.location
if y <= -1:
y = 0
newPOS = newdata[34*(y+1) + x]
if newPOS == ' ':
self.location = (x, y + 1)
newdata[34 * y + x] = ' '
newdata[34 * (y+1) + x] = 'O'
elif newPOS == 'I':
return list("dead")
elif newPOS == 'U':
return list("next")
return newdata
class DesignConfig():
def __init__(self, **kwargs):
keys = kwargs.keys()
if 'font' in kwargs:
self.font = kwargs.get('font')
else:
self.font = 'starwars'
if 'message' in keys:
self.message = kwargs.get('message')
else:
self.message = 'Permanent Overdrive'
class CursesController():
def __init__(self, level):
self.level = level
self.data = list(
"IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII\n" +
"I I\n" +
"I Permanent Overdrive I\n" +
"I I\n" +
"I I\n" +
"I I\n" +
"I I\n" +
"I I\n" +
"IIIIIIIIIII IIIIIIIIIII\n" +
"I I\n" +
"I I\n" +
"UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU\n"
)
global GAME_BOARD
GAME_BOARD = self.data
def initCurses(self):
self.stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
curses.curs_set(0)
self.stdscr.nodelay(1)
self.stdscr.keypad(1)
max_rows, max_cols = self.stdscr.getmaxyx()
rows = "".join(self.data).split("\n")
enemy_rows = "".join(ENEMY_GAME_BOARD).split("\n")
i=0
for row in rows:
if i>=max_rows:
break
overflow = X+len(row) - max_cols
if overflow<len(row):
if overflow>=0:
row_length = len(row)
self.stdscr.addstr(i,X,row[0:row_length-overflow])
else:
self.stdscr.addstr(i,X,row)
i+=1
i=0
for enemy_row in enemy_rows:
if i>=max_rows:
break
overflow = ENEMY_X+len(enemy_row) - max_cols
if overflow<len(enemy_row):
if overflow>=0:
row_length = len(enemy_row)
self.stdscr.addstr(i,ENEMY_X,enemy_row[0:row_length-overflow])
else:
self.stdscr.addstr(i,ENEMY_X,enemy_row)
i+=1
instruction_rows = ["Score: " + str(self.level)+ " Enemy Screen:",
"Go to bottom to advance!",
"Movement speed is random for each key press",
"You die if you touch walls! ('I')",
"Press arrow to move in that direction",
"Move down to start game",
"\"q\" to quit!",
"Enemy name: " + ENEMY_NAME,
"Enemy score: " + str(ENEMY_SCORE),
"Enemy status: " + ENEMY_STATUS]
i=3
for instruction_row in instruction_rows:
i+=1
overflow = 50+X+len(instruction_row) - max_cols
if overflow<len(instruction_row):
if overflow>=0:
row_length = len(instruction_row)
self.stdscr.addstr(i,50+X, instruction_row[0:row_length-overflow])
else:
self.stdscr.addstr(i,50+X, instruction_row)
curses.curs_set(0)
def write(self):
self.stdscr.clear()
rows = "".join(self.data).split("\n")
enemy_rows = "".join(ENEMY_GAME_BOARD).split("\n")
max_rows, max_cols = self.stdscr.getmaxyx()
i=0
for row in rows:
if i>=max_rows:
break
overflow = X+len(row) - max_cols
if overflow<len(row):
if overflow>=0:
row_length = len(row)
self.stdscr.addstr(i,X,row[:row_length-overflow])
else:
self.stdscr.addstr(i,X,row)
i+=1
i=0
for enemy_row in enemy_rows:
if i>=max_rows:
break
overflow = ENEMY_X+len(enemy_row) - max_cols
if overflow<len(enemy_row):
if overflow>=0:
row_length = len(enemy_row)
self.stdscr.addstr(i,ENEMY_X,enemy_row[:row_length-overflow])
else:
self.stdscr.addstr(i,ENEMY_X,enemy_row)
i+=1
instruction_rows = ["Score: " + str(self.level)+ " Enemy Screen:",
"Go to bottom to advance!",
"Movement speed is random for each key press",
"You die if you touch walls! ('I')",
"Press arrow to move in that direction",
"Move down to start game",
"\"q\" to quit!",
"Enemy name: " + ENEMY_NAME,
"Enemy score: " + str(ENEMY_SCORE),
"Enemy status: " + ENEMY_STATUS]
i=3
for instruction_row in instruction_rows:
overflow = 50+X+len(instruction_row) - max_cols
i+=1
if overflow<len(instruction_row):
if overflow>=0:
row_length = len(instruction_row)
self.stdscr.addstr(i,50+X, instruction_row[0:row_length-overflow])
else:
self.stdscr.addstr(i,50+X, instruction_row)
curses.curs_set(0)
def closeCurses(self):
curses.nocbreak()
self.stdscr.keypad(0)
curses.echo()
curses.endwin()
def cutBeginning(curses_controller, o):
data = curses_controller.data
lines_to_cut = 1
i = 0
while i < lines_to_cut:
curses_controller.data = data[34:]
i+=1
x, y = o.location
o.location = (x,(y-lines_to_cut))
refresh(curses_controller, o)
def game(curses_controller):
o = O()
while 1:
key = curses_controller.stdscr.getch()
global SCORE
global STATUS
global GAME_BOARD
GAME_BOARD = curses_controller.data
SCORE = o.level
if curses_controller.data != "Dead! Press \"r\" for restart":
STATUS = "alive"
if key == curses.KEY_LEFT:
cutBeginning(curses_controller, o)
random_move(curses_controller, o, "left")
if key == curses.KEY_RIGHT:
cutBeginning(curses_controller, o)
random_move(curses_controller, o, "right")
if key == curses.KEY_UP:
cutBeginning(curses_controller, o)
random_move(curses_controller, o, "up")
if key == curses.KEY_DOWN:
cutBeginning(curses_controller, o)
random_move(curses_controller, o, "down")
if key == -1:
refresh(curses_controller, o)
if key == ord('q'):
curses_controller.closeCurses()
exit()
else:
STATUS = "dead"
if key == ord('q'):
curses_controller.closeCurses()
exit()
if key == ord('r'):
curses_controller.closeCurses()
main()
if key == -1:
refresh(curses_controller, o)
def random_move(curses_controller, o, direction):
displacement = randint(1, 5)
if o.level < 5:
if direction == "left" or direction == "right":
displacement += 3
i = 0
while i < displacement:
i += 1
status = o.move(direction, curses_controller.data)
if "".join(status) == "dead":
curses_controller.data = "Dead! Press \"r\" for restart"
refresh(curses_controller, o)
break
elif "".join(status) == "next":
o.level +=1
curses_controller.level=o.level
if o.level < 5:
random_wall = list("IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII\n")
hole = randint(3, 29)
random_wall[hole] = ' '
random_wall[hole + 1] = ' '
random_wall[hole + 2] = ' '
random_wall[hole - 1] = ' '
random_wall[hole - 2] = ' '
animate_open_doors(curses_controller, o)
curses_controller.data += list(
"I I\n" +
"I I\n" +
"I I\n" +
"I I\n" +
"I I\n" +
"I I\n" +
"I I\n" +
"I I\n" +
"".join(random_wall) +
"I I\n" +
"I I\n" +
"UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU\n"
)
refresh(curses_controller, o)
break
elif o.level == 5:
animate_open_doors(curses_controller, o)
curses_controller.data += list(
"I I\n" +
"I I\n" +
"I I\n" +
"I I\n" +
"I I\n" +
"II II\n" +
"IIII IIII\n" +
"IIIIII IIIIII\n" +
"IIIIIIII IIIIIIII\n" +
"IIIIIIIIII IIIIIIIIII\n" +
"IIIIIIIIII IIIIIIIIII\n" +
"UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU\n"
)
refresh(curses_controller, o)
break
elif o.level > 5:
animate_open_doors(curses_controller, o)
random_wall = list("IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII\n")
hole = randint(10, 22)
random_wall[hole] = ' '
animate_open_doors(curses_controller, o)
curses_controller.data += list(
"IIIIIIIIII IIIIIIIIII\n" +
"IIIIIIIIII IIIIIIIIII\n" +
"IIIIIIIIII IIIIIIIIII\n" +
"IIIIIIIIII IIIIIIIIII\n" +
"IIIIIIIIII IIIIIIIIII\n" +
"IIIIIIIIII IIIIIIIIII\n" +
"IIIIIIIIII IIIIIIIIII\n" +
"".join(random_wall) +
"IIIIIIIIII IIIIIIIIII\n" +
"IIIIIIIIII IIIIIIIIII\n" +
"IIIIIIIIII IIIIIIIIII\n" +
"UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU\n"
)
refresh(curses_controller, o)
break
else:
curses_controller.data = status
refresh(curses_controller, o)
def refresh(curses_controller, o):
curses_controller.write()
curses_controller.stdscr.refresh()
time.sleep(.030)
def animate_open_doors(curses_controller, o):
length = len(curses_controller.data)
curses_controller.data[length-18]=' '
refresh(curses_controller, o)
i = 1
width=2
if o.level > 5:
width=11
while i<17:
curses_controller.data[length-18+i]=' '
curses_controller.data[length-18-i]=' '
if i>17-width:
curses_controller.data[length-18+i]='I'
curses_controller.data[length-18-i]='I'
i+=1
refresh(curses_controller, o)
curses_controller.data[length-1]='\n'
refresh(curses_controller, o)
if __name__ == '__main__':
main()
|
97d25f20fe7811d96513c09ba0deb94c4ffccdc0
|
[
"Python",
"Text"
] | 4
|
Text
|
MOsmanis/Permanent-Overdrive
|
2f411dcba275fe0a5182f85837206fb2d5b8735a
|
99050f2f895d9fa43f646888906c97a3164db2a2
|
refs/heads/master
|
<repo_name>ThomasDahll/AngelApp<file_sep>/Repository/PokemonsRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AngelApp.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace AngelApp.Repository
{
public class PokemonsRepository : IPokemonsRepository
{
private readonly PokemonDbContext _context;
private readonly ILogger _logger;
public PokemonsRepository(PokemonDbContext context, ILoggerFactory loggerFactory)
{
_context = context;
_logger = loggerFactory.CreateLogger("PokemonsRepository");
}
public async Task<List<Pokemon>> GetPokemonsAsync()
{
return await _context.pokemon.OrderBy(p => p.pokedex_number).ToListAsync();
}
public async Task<Pokemon> GetPokemonAsync(int id)
{
return await _context.pokemon.SingleOrDefaultAsync(p => p.pokedex_number == id);
}
}
}
<file_sep>/Repository/PokemonDbContext.cs
using AngelApp.Models;
using Microsoft.EntityFrameworkCore;
namespace AngelApp.Repository
{
public class PokemonDbContext : DbContext
{
public DbSet<Pokemon> pokemon { get; set; }
public PokemonDbContext(DbContextOptions<PokemonDbContext> options) : base(options) { }
}
}
<file_sep>/Repository/PokemonDbSeeder.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AngelApp.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace AngelApp.Repository
{
public class PokemonDbSeeder
{
private readonly ILogger _logger;
public PokemonDbSeeder(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger("PokemonDbSeederLogger");
}
/*
public async Task SeedAsync(IServiceProvider serviceProvider)
{
//Based on EF team's example at https://github.com/aspnet/MusicStore/blob/dev/samples/MusicStore/Models/SampleData.cs
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var pokemonsDb = serviceScope.ServiceProvider.GetService<PokemonDbContext>();
if (await pokemonsDb.Database.EnsureCreatedAsync())
{
if (!await pokemonsDb.Pokemons.AnyAsync())
{
await InsertPokemonsSampleData(pokemonsDb);
}
}
}
}
/*
public async Task InsertPokemonsSampleData(PokemonDbContext db)
{
var pokemons = GetPokemons();
db.Pokemons.AddRange(pokemons);
try
{
int numAffected = await db.SaveChangesAsync();
_logger.LogInformation(@"Saved {numAffected} states");
}
catch (Exception exp)
{
_logger.LogError($"Error in {nameof(PokemonDbSeeder)}: " + exp.Message);
throw;
}
}
private List<pokemon> GetPokemons()
{
var states = new List<pokemon>
{
new pokemon { Name = "Alabama", Type1 = "Fire", Type2 = ""},
new pokemon { Name = "Danny", Type1 = "Fire", Type2 = ""},
new pokemon { Name = "Squirt", Type1 = "Fire", Type2 = ""},
};
return states;
}*/
}
}
<file_sep>/Repository/IPokemonsRepository.cs
using System.Collections.Generic;
using System.Threading.Tasks;
using AngelApp.Models;
namespace AngelApp.Repository
{
public interface IPokemonsRepository
{
Task<List<Pokemon>> GetPokemonsAsync();
Task<Pokemon> GetPokemonAsync(int id);
}
}<file_sep>/Services/Factories/Class.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AngelApp.ClientApp.API.ResponseBodies;
using AngelApp.Models;
namespace AngelApp.Services.Factories
{
interface IPokemonFactory
{
List<PokemonResponse> ListOfPokemonToListOfPokemonResponses(List<Pokemon> pokemons);
PokemonResponse PokemonToPokemonResponse(Pokemon pokemons);
}
class PokemonFactory : IPokemonFactory
{
public List<PokemonResponse> ListOfPokemonToListOfPokemonResponses(List<Pokemon> pokemons)
{
var pokemonResponses = new List<PokemonResponse>();
foreach (var pokemon in pokemons)
{
pokemonResponses.Add(PokemonToPokemonResponse(pokemon));
}
return pokemonResponses;
}
public PokemonResponse PokemonToPokemonResponse(Pokemon pokemon)
{
return new PokemonResponse()
{
Id = pokemon.pokedex_number,
Name = pokemon.name,
Type1 = pokemon.type1,
Type2 = pokemon.type2
};
}
}
}
<file_sep>/ClientApp/API/Controllers/PokemonController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AngelApp.ClientApp.API.ResponseBodies;
using AngelApp.Models;
using AngelApp.Repository;
using AngelApp.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace AngelApp.Controllers
{
[ApiController]
[Route("[controller]")]
public class PokemonController : ControllerBase
{
private readonly IPokemonService _service;
// private readonly IPokemonsRepository _pokemonsRepository;
private readonly ILogger _logger;
public PokemonController(ILoggerFactory loggerFactory, IPokemonService service)
{
_logger = loggerFactory.CreateLogger(nameof(PokemonController));
_service = service;
}
// GET api/pokemon
[HttpGet]
[ProducesResponseType(typeof(List<PokemonResponse>), 200)]
public async Task<ActionResult> Pokemons()
{
try
{
var pokemons = await _service.GetListOfAllPokemons();
return Ok(pokemons);
}
catch (Exception exp)
{
_logger.LogError(exp.Message);
}
return NotFound("Itte non pokemons på gang ass");
}
}
}
<file_sep>/Services/IPokemonService.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AngelApp.ClientApp.API.ResponseBodies;
using AngelApp.Models;
using AngelApp.Repository;
using AngelApp.Services.Factories;
namespace AngelApp.Services
{
public interface IPokemonService
{
Task<List<PokemonResponse>> GetListOfAllPokemons();
Task<PokemonResponse> GetPokemonResponseById(int id);
}
class PokemonService : IPokemonService
{
private readonly IPokemonsRepository _repository;
private readonly IPokemonFactory _factory;
public PokemonService(IPokemonsRepository repository, IPokemonFactory factory)
{
_repository = repository;
_factory = factory;
}
public async Task<List<PokemonResponse>> GetListOfAllPokemons()
{
var pokemons = await _repository.GetPokemonsAsync();
return _factory.ListOfPokemonToListOfPokemonResponses(pokemons);
}
public async Task<PokemonResponse> GetPokemonResponseById(int id)
{
var pokemon = await _repository.GetPokemonAsync(id);
return _factory.PokemonToPokemonResponse(pokemon);
}
}
}
<file_sep>/ClientApp/API/ResponseBodies/PokemonResponse.cs
namespace AngelApp.ClientApp.API.ResponseBodies
{
public class PokemonResponse
{
public int Id { get; set; }
public string Name { get; set; }
public string Type1 { get; set; }
public string Type2 { get; set; }
}
}<file_sep>/README.md
# AngelApp
Building app with .net and angular. When in doubt about what to make... Pòkemon
<file_sep>/Models/Pokemon.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace AngelApp.Models
{
#nullable enable
public class Pokemon
{
public string? abilities { get; set; }
public decimal? against_bug { get; set; }
public decimal? against_dark { get; set; }
public decimal? against_dragon { get; set; }
public decimal? against_electric { get; set; }
public decimal? against_fairy { get; set; }
public decimal? against_fight { get; set; }
public decimal? against_fire { get; set; }
public decimal? against_flying { get; set; }
public decimal? against_ghost { get; set; }
public decimal? against_grass { get; set; }
public decimal? against_ground { get; set; }
public decimal? against_ice { get; set; }
public decimal? against_normal { get; set; }
public decimal? against_poison { get; set; }
public decimal? against_psychic { get; set; }
public decimal? against_rock { get; set; }
public decimal? against_steel { get; set; }
public decimal? against_water { get; set; }
public int? attack { get; set; }
public int? base_egg_steps { get; set; }
public int? base_happiness { get; set; }
public int? base_total { get; set; }
public string? capture_rate { get; set; }
public string? classfication { get; set; }
public int? defense { get; set; }
public int? experience_growth { get; set; }
public decimal? height_m { get; set; }
public int? hp { get; set; }
public string? japanese_name { get; set; }
public string name { get; set; }
public decimal? percentage_male { get; set; }
[Key]
public int pokedex_number { get; set; }
public int? sp_attack { get; set; }
public int? sp_defense { get; set; }
public int? speed { get; set; }
public string? type1 { get; set; }
public string? type2 { get; set; }
public decimal? weight_kg { get; set; }
public int? generation { get; set; }
public int? is_legendary { get; set; }
#nullable enable
public Pokemon(){}
public Pokemon(string abilities_, decimal against_bug_, decimal against_dark_, decimal against_dragon_, decimal against_electric_, decimal against_fairy_, decimal against_fight_, decimal against_fire_, decimal against_flying_, decimal against_ghost_, decimal against_grass_, decimal against_ground_, decimal against_ice_, decimal against_normal_, decimal against_poison_, decimal against_psychic_, decimal against_rock_, decimal against_steel_, decimal against_water_, int attack_, int base_egg_steps_, int base_happiness_, int base_total_, string capture_rate_, string classfication_, int defense_, int experience_growth_, decimal height_m_, int hp_, string japanese_name_, string name_, decimal percentage_male_, int pokedex_number_, int sp_attack_, int sp_defense_, int speed_, string type1_, string type2_, decimal weight_kg_, int generation_, int is_legendary_)
{
this.abilities = abilities_;
this.against_bug = against_bug_;
this.against_dark = against_dark_;
this.against_dragon = against_dragon_;
this.against_electric = against_electric_;
this.against_fairy = against_fairy_;
this.against_fight = against_fight_;
this.against_fire = against_fire_;
this.against_flying = against_flying_;
this.against_ghost = against_ghost_;
this.against_grass = against_grass_;
this.against_ground = against_ground_;
this.against_ice = against_ice_;
this.against_normal = against_normal_;
this.against_poison = against_poison_;
this.against_psychic = against_psychic_;
this.against_rock = against_rock_;
this.against_steel = against_steel_;
this.against_water = against_water_;
this.attack = attack_;
this.base_egg_steps = base_egg_steps_;
this.base_happiness = base_happiness_;
this.base_total = base_total_;
this.capture_rate = capture_rate_;
this.classfication = classfication_;
this.defense = defense_;
this.experience_growth = experience_growth_;
this.height_m = height_m_;
this.hp = hp_;
this.japanese_name = japanese_name_;
this.name = name_;
this.percentage_male = percentage_male_;
this.pokedex_number = pokedex_number_;
this.sp_attack = sp_attack_;
this.sp_defense = sp_defense_;
this.speed = speed_;
this.type1 = type1_;
this.type2 = type2_;
this.weight_kg = weight_kg_;
this.generation = generation_;
this.is_legendary = is_legendary_;
}
}
}
<file_sep>/ClientApp/src/app/pokemon/pokemon.component.ts
import { Component, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-pokemon-component',
templateUrl: './pokemon.component.html'
})
export class PokemonComponent {
public pokemons: Pokemon[];
constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
http.get<Pokemon[]>(baseUrl + 'pokemon').subscribe(result => {
this.pokemons = result;
}, error => console.error(error));
}
}
interface Pokemon {
name: string;
type1: string;
type2: string;
}
|
3b55b407156ceb604951389c488b32ff53a9abfe
|
[
"Markdown",
"C#",
"TypeScript"
] | 11
|
C#
|
ThomasDahll/AngelApp
|
27831b96ab5d40a61163f13ee7f851839b01cb01
|
8871fbe6089cf012c3d70d8d50eb4ea2724bcea6
|
refs/heads/master
|
<file_sep>library(tidyverse)
library(RSQLite)
library(dbplyr)
# Open the database connection
connection <- dbConnect(SQLite(), 'sql_assignment.db')
# List the fields in the alignedannot table
dbListFields(connection,'alignedannot')
#dplyr method test
results <- tbl(connection, sql("SELECT * FROM alignedannot
WHERE annotation LIKE '%hypothetical%'"))
# Quick test using RSQL method (dbplyr not effective)
print(dbGetQuery(connection, "SELECT * FROM alignedannot
WHERE annotation LIKE '%hypothetical%'"))
# Test of function
testSearchAnnotations <- function(arg1) {
query <- paste0("SELECT *
FROM alignedannot
WHERE annotation LIKE '%", arg1 ,"%';")
return(dbGetQuery(connection, query))
}
print(testSearchAnnotations('hypothetical'))
# Full function with header changes and joins
searchAnnotations <- function(arg1) {
query <- paste0("SELECT sequence.name AS SeqName,
sample.name AS Sample,
seqgroup.name AS SeqGroup,
seqtype.type AS SeqType,
alignedannot.name AS MatchName, alignedannot.annotation AS Annotation
FROM alignedannot
JOIN sequence ON sequence.id = alignedannot.onSequence
JOIN sample ON sample.id = sequence.isSample
JOIN seqGroup ON seqGroup.id = sequence.belongsGroup
JOIN seqType ON seqType.id = sequence.isType
WHERE annotation LIKE '%", arg1, "%';")
return(dbGetQuery(connection, query))
}
resultHypotheticals <- searchAnnotations('hypothetical')
head(resultHypotheticals, n=10)
# Database disconnection
dbDisconnect(connection)
<file_sep>#!/bin/bash -l
module load sqlite
sqlite3 filename.db
.mode column
.header on
sqlite3
<file_sep>-- 1. Can you list all details about all samples?
SELECT *
FROM Samples;
-- 2. Can you list just the name and species for all samples?
SELECT name, species
FROM sample;
-- 3. Can you list details of the first 10 sequences?
SELECT *
FROM sequence
LIMIT 10;
-- 4. How many loaded sequences are there?
SELECT COUNT(id)
FROM sequence;
-- 5. How many sequences are of the type “genomeAssembly”?
SELECT COUNT(sequence.isType)
FROM sequence
JOIN seqtype
ON seqtype.id = sequence.isType
WHERE seqtype.type = 'genomeAssembly';
-- 6. How many loaded sequences are there of each different type?
SELECT seqtype.type, COUNT(sequence.isType)
FROM sequence
JOIN seqtype
ON seqtype.id = sequence.isType
GROUP BY seqtype.type ;
-- 7. How many sequences have a length greater than 1000?
SELECT COUNT(length)
FROM sequence
WHERE length > 999;
-- 8. How many sequences have a length greater than 1000 and are from sample “D36-s2-tr”?
SELECT COUNT(length)
FROM sequence
JOIN sample
ON sequence.isSample = sample.id
WHERE length > 1000 AND sample.name = 'D36-s2-tr';
-- 9. What is the average length of all sequences?
SELECT ROUND(AVG(length), 2)
FROM sequence;
-- 10. What is the average length of sequences of type “genomeAssembly”?
SELECT ROUND(AVG(length), 2)
FROM sequence
JOIN seqtype
ON seqtype.id = sequence.isType
WHERE seqtype.type = 'genomeAssembly';
-- 11. What is the average length of sequences of type “genomeAssembly” AND what is the average length of sequences
-- of type “protein”?
SELECT seqtype.type, ROUND(AVG(length), 2)
FROM sequence
JOIN seqtype
ON seqtype.id = sequence.isType
WHERE seqtype.type = 'genomeAssembly' OR seqtype.type = 'protein'
GROUP BY seqtype.type;
-- 12. How many annotations (alignedannot.annotation) contain the phrase “hypothetical”?
SELECT COUNT(annotation)
FROM alignedAnnot
WHERE annotation LIKE '%hypothetical%';
-- 13. Can you list details of the sequence named “D18-gDNA-s1638”, replacing the foreign keys with sensible
-- info (e.g. replace ‘isSample’ id with actual sample name)?
SELECT sequence.id, sequence.name, sequence.length, seqgroup.name, sample.name, seqtype.type
FROM sequence
JOIN seqgroup ON seqgroup.id = sequence.belongsGroup
JOIN sample ON sample.id = sequence.isSample
JOIN seqtype ON seqtype.id = sequence.isType
WHERE sequence.name = 'D18-gDNA-s1638';
-- 14. Does the sequence named “D18-gDNA-s1638” have any other sequences that align onto it
-- (it’ll appear in seqRelation.parentSeq)? List the name(s) of any such sequence(s).
-- Solution thanks to YingYing
SELECT sequence.id, sequence.name
FROM sequence
JOIN
(SELECT seqrelation.childSeq
FROM sequence
JOIN seqrelation ON sequence.id = seqrelation.parentSeq
WHERE name = 'D18-gDNA-s1638') AS Child
ON sequence.id = Child.childSeq;
<file_sep>import sqlite3
def searchAnnotations(database_file, annotation):
query = "SELECT sequence.name AS SeqName,
sample.name AS Sample,
seqgroup.name AS SeqGroup,
seqtype.type AS SeqType,
alignedannot.name AS MatchName, alignedannot.annotation AS Annotation
FROM alignedannot
JOIN sequence ON sequence.id = alignedannot.onSequence
JOIN sample ON sample.id = sequence.isSample
JOIN seqGroup ON seqGroup.id = sequence.belongsGroup
JOIN seqType ON seqType.id = sequence.isType
WHERE annotation LIKE '%" + annotation + "%';"
connection = sqlite3.connect(database_file)
cursor = connection.cursor()
cursor.execute(query)
results = cursor.fetchall()
cursor.close()
connection.close()
return results[0] #10 results only
print(searchAnnotations('sql_assigment.db','hypothetical'))
<file_sep>CREATE TABLE sample (
id integer PRIMARY KEY,
name text,
species text,
description text
);
CREATE TABLE seqgroup(
id integer PRIMARY KEY,
name text,
description text
);
CREATE TABLE seqtype(
id integer PRIMARY KEY,
type text
);
CREATE TABLE sequence (
id integer PRIMARY KEY,
name text,
length integer,
belongsGroup integer,
isSample integer,
isType integer,
FOREIGN KEY (belongsGroup) REFERENCES seqgroup (id),
FOREIGN KEY (isSample) REFERENCES sample(id),
FOREIGN KEY (isType) REFERENCES seqtype(id)
);
CREATE TABLE alignedannot(
id integer PRIMARY KEY,
onsequence integer,
start integer,
end integer,
strand boolean,
name text,
annotation text,
species text,
source text,
method text,
score text,
FOREIGN KEY (onsequence) REFERENCES sequence(id)
);
CREATE TABLE seqrelation(
id integer PRIMARY KEY,
parentseq integer,
childseq integer,
strand boolean,
pstart integer,
pend integer,
cstart integer,
cend integer,
method text,
FOREIGN KEY (parentseq) REFERENCES sequence (id),
FOREIGN KEY (childseq) REFERENCES sequence (id)
);
|
76aac71323c1a38c053279103b2f672c2e879447
|
[
"SQL",
"Python",
"R",
"Shell"
] | 5
|
R
|
EPLeyne/sql_assignment
|
d71f843bab1c0c41705ae915ebef476410706eb9
|
a5a0408cf686ff2ccbedc779ee5359c4b9c5b8a5
|
refs/heads/master
|
<repo_name>mariarudenko/dividend-calculator<file_sep>/src/TextHandler.java
/**
* Created by <NAME> on 20.04.2015.
*/
public class TextHandler {
}
<file_sep>/src/XMLHandler.java
/**
* Created by <NAME> on 20.04.2015.
*/
public class XMLHandler extends TextHandler {
}
<file_sep>/src/Claim.java
/**
* Created by <NAME> on 20.04.2015.
*/
public class Claim {
private long claimId;
private Integer tradeId;
private Integer recAcct;
private Integer entAcct;
private Integer amt;
Claim(Integer tradeId, Integer recAcct, Integer entAcct, Integer amt) {
this.tradeId = tradeId;
this.recAcct = recAcct;
this.entAcct = entAcct;
this.amt = amt;
claimId = Dividend.getID();
}
public String toString(){
String str;
str = claimId + "," + tradeId.toString() + "," + recAcct.toString() + "," + entAcct.toString() + "," + amt.toString();
return str;
}
}
<file_sep>/README.txt
# dividend-calculator
Test task, 2015
jdk7 +
Apache Commons CSV
properties.xml contains a directories to logs, input and output files
Input Data format:
CSV with header
name: <Share name>_<EX date >_<REC date>_<Dividend amount per share>.csv (example: GP123456_21082013_27082013_7.csv)
fields: Trade_id, Seller_acct, Buyer_acct, Amount, TD, SD
Trade_id – trade unique id, 10 digits
Seller_acct – seller account, 8 digits
Buyer_acct – buyer account, 8 digits
Amount – number of shares, integer
TD – Trade Date
SD – Settled date
Dates format: day number, month number, year without any delimits. (example: 01092013)
input_example contains the simplest example of input file. One can copy this in the input directory after launching the program and monitoring starts.
<file_sep>/src/Main.java
import java.io.*;
import java.nio.file.*;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static java.nio.file.StandardWatchEventKinds.*;
/**
* Created by <NAME> on 17.04.2015.
*/
public class Main {
static final Logger LOGGER = new Logger();
public static void main(String[] args) {
Properties prop = new Properties();
try (FileInputStream fis = new FileInputStream("config/properties.xml")) {
prop.loadFromXML(fis);
} catch (FileNotFoundException e) {
System.out.println(e.toString());
} catch (IOException ex) {
System.out.println(ex.toString());
}
Path inputDir = Paths.get(prop.getProperty("input_folder"));
Path outputDir = Paths.get(prop.getProperty("output_folder"));
LOGGER.setPath(prop.getProperty("log_folder"));
ExecutorService exec = Executors.newFixedThreadPool(10);
LOGGER.info("Start of monitoring ...");
try {
WatchService watcher = FileSystems.getDefault().newWatchService();
inputDir.register(watcher, ENTRY_CREATE);
while (true) {
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException ex) {
return;
}
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (kind == OVERFLOW) continue;
WatchEvent<Path> ev = (WatchEvent<Path>) event;
Path filename = ev.context();
exec.execute(new CountingThread(inputDir, outputDir, filename.toString()));
}
}
} catch (IOException e) {
System.out.println(e.toString());
}
exec.shutdown();
}
}<file_sep>/src/Logger.java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
/**
* Created by <NAME> on 19.04.2015.
*/
public class Logger {
private Path path;
public void setPath(String logPath){
path = Paths.get(logPath + "logs.txt");
}
public void info(String str){
Date date = new Date(System.currentTimeMillis());
System.out.println(date + " " + str);
}
public void info(String str, String thread){
Date date = new Date(System.currentTimeMillis());
System.out.println(date + " " + str + " was created by thread " + thread);
try(FileWriter out = new FileWriter(path.toString())) {
BufferedWriter bw = new BufferedWriter(out);
bw.write(date + " " + str + " was created by thread " + thread);
bw.newLine();
bw.flush();
bw.close();
} catch (IOException e) {
}
}
}
<file_sep>/src/Dividend.java
/**
* Created by <NAME> on 20.04.2015.
*/
public class Dividend {
private long divId;
private Integer tradeId;
private Integer acct;
private Integer amt;
private static final long ID_LIMIT = 10000000000L;
private static long lastID = 0;
Dividend(Integer tradeId, Integer acct, Integer amt) {
this.tradeId = tradeId;
this.acct = acct;
this.amt = amt;
divId = getID();
}
public String toString(){
String str;
str = divId + "," + tradeId.toString() + "," + acct.toString() + "," + amt.toString();
return str;
}
public static long getID(){
long id = System.currentTimeMillis()%ID_LIMIT;
if ( id <= lastID ) {
id = (lastID + 1) % ID_LIMIT;
}
return lastID = id;
}
}
|
bde815cd0c7cee0c3aa69d80e430a4f7f72bc4cd
|
[
"Java",
"Text"
] | 7
|
Java
|
mariarudenko/dividend-calculator
|
165054ba3d4826f0acbe5d99edde0d764c913be2
|
3ff359de9a3969efe62843e4cc03d2e464d79391
|
refs/heads/master
|
<file_sep>package com.example.mvppractice;
public interface Contract {
interface View{
void showAToast(String message);
}
interface Presenter{
void buttonClicked();
}
}
|
dcfbc3060a1c38436d876ae104d18722493c20be
|
[
"Java"
] | 1
|
Java
|
onilp/MVPPractice
|
f13a1c7249ffc670ae7b2068a1110f65d1c4d70a
|
741f5022933c3e4879ee829b3cf2c182a827d0f2
|
refs/heads/master
|
<repo_name>pramodramdas/asset_transfer_android<file_sep>/src/components/asset/search.js
import React, { Component } from 'React';
import { connect } from 'react-redux';
import { View, Text } from 'react-native';
import { Container, Picker, Item, Form, Input, Button } from 'native-base';
class SearchRequests extends Component {
constructor(props){
super(props);
}
state = {
req_state: "",
assetId: ""
};
onValueChange(value) {
this.setState({
req_state: value
});
}
onFieldChange(text) {
this.setState({assetId:text});
}
filterRequests() {
let query = {};
switch(this.state.req_state) {
case "APPROVED": query = {approved: true}; break;
case "NOT APPROVED": query = {approved: false}; break;
case "RECEIVED": query = {received: true}; break;
case "NOT RECEIVED": query = {received: false}; break;
case "CLOSED": query = {isClosed: true}; break;
case "NOT CLOSED": query = {isClosed: false}; break;
default: break;
}
if(this.state.assetId)
query.assetId = this.state.assetId;
this.props.filterRequests(query);
}
render() {
return (
<Form style={{borderStyle: "dotted", borderWidth: 5, borderColor: "#3F51B5" }}>
<Item picker>
<Picker
mode="dropdown"
style={{ width: 100 }}
selectedValue={this.state.req_state}
onValueChange={this.onValueChange.bind(this)}
>
<Picker.Item label="ALL" value="ALL" />
<Picker.Item label="APPROVED" value="APPROVED" />
<Picker.Item label="NOT APPROVED" value="NOT APPROVED" />
<Picker.Item label="RECEIVED" value="RECEIVED" />
<Picker.Item label="NOT RECEIVED" value="NOT RECEIVED" />
<Picker.Item label="CLOSED" value="CLOSED" />
<Picker.Item label="NOT CLOSED" value="NOT CLOSED" />
</Picker>
</Item>
<Item rounded>
<Input placeholder='Asset Id' onChangeText={this.onFieldChange.bind(this)}/>
</Item>
<Item style={{alignSelf:'center'}}>
<Button rounded style={{width:100, justifyContent: 'center'}} onPress={this.filterRequests.bind(this)}>
<Text>Search</Text>
</Button>
</Item>
</Form>
);
}
}
const btnStyle = {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center'
}
export default SearchRequests;<file_sep>/src/index.js
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { Container, Header, HeaderTab, Title, Content, Footer, FooterTab, Button, Left, Right, Body, Icon } from 'native-base';
import HeaderComponent from './components/common/header';
import DrawerComponent from './components/common/drawerComponent';
import { connect } from 'react-redux';
import { requireAuth } from './actions/auth';
import PropTypes from 'prop-types';
import history from 'history';
import { checkAuth } from './actions/auth';
class IndexComponent extends Component {
constructor(props){
super(props);
}
async componentDidMount() {
checkAuth(this.props.history);
}
render() {
const { jwtToken } = this.props.auth;
return (
<View style={{height:"100%"}}>
{
jwtToken ?
<HeaderComponent history={this.props.history}/> :
null
}
<View>
{this.props.children}
</View>
</View>
);
}
}
const mapStateToProps = (state) => {
return {
auth:state.auth
}
};
//IndexComponent.contextTypes = {
// history: PropTypes.func.isRequired
//};
export default connect(mapStateToProps, null)(IndexComponent);<file_sep>/src/components/asset/asset.js
import { connect } from "react-redux";
import { View, Text } from 'react-native';
import { Container, Tabs, Tab, Header, Input, Button, Picker, Form, Toast, Item } from 'native-base';
import React from "react";
import { submitAsset, searchAssetAdmin } from '../../actions/index';
import SearchItems from '../search_items';
class Asset extends React.Component {
constructor(props) {
super(props);
}
state = {
assetId: "",
owner: "",
description: "",
message: "",
loading: false
}
onFieldChange(field, value) {
this.setState({[field]:value});
}
addAsset() {
this.setState({loading:true});
submitAsset(this.state, (message)=>{
this.setState({loading:false, message:message});
Toast.show({ text: message, buttonText: 'Okay', duration: 3000 });
});
}
searchAsset() {
let filter = JSON.stringify(this.state, (key, value) => {if(value)return value});
this.props.searchAssetAdmin(JSON.parse(filter));
}
render() {
return(
<View style={{flex:1, flexDirection:"column"}}>
<View style={{flex:1, flexDirection:"column", width:"100%", height:400 }}>
<Form>
<Item regular style={{height:40}}>
<Input placeholder="Asset Id" onChangeText={this.onFieldChange.bind(this,"assetId")}/>
</Item>
<Item regular style={{height:40}}>
<Input placeholder="Owner" onChangeText={this.onFieldChange.bind(this,"owner")}/>
</Item>
<Item regular style={{height:40}}>
<Input placeholder="Description" onChangeText={this.onFieldChange.bind(this,"description")}/>
</Item>
<View style={{flex:1, flexDirection:"row", width:"100%", justifyContent:'space-between'}}>
<Button primary style={{width:100, justifyContent:'center'}} onPress={this.addAsset.bind(this)} >
<Text>Add</Text>
</Button>
<Button primary style={{width:100, justifyContent:'center'}} onPress={this.searchAsset.bind(this)} >
<Text>Search</Text>
</Button>
</View>
</Form>
</View>
<View style={{height:300}}>
<SearchItems type="assets"/>
</View>
</View>
);
}
}
const actionCreators = { searchAssetAdmin };
export default connect(null, actionCreators)(Asset);<file_sep>/src/components/common/test.js
import { View, Text } from 'react-native';
const Test = ({ children }) => {
return (
<View>
<Text>Nested Children</Text>
{children}
</View>
);
};
export { Test };<file_sep>/src/actions/asset.js
import axios from "axios";
import store from '../utils/store';
import { SET_ASSET } from './types';
export function setAsset (content) {
return {
type: SET_ASSET,
content
};
}
export const submitAsset = (data, callback) => {
const req = axios.post(global.server_url+"/addAsset", data);
req.then((response)=>{
if(response.status == 200 && response.data.message){
callback("assert "+data.assetId+" added sucessfully");
}
else
callback(response.data.error);
})
.catch((e) => {
callback("error please try again");
});
}
export const requestForAsset = (data, callback) => {
const state = store.getState();
const reqDate = Object.assign({},data,{reqEmp: state.auth.empId});
const req = axios.post(global.server_url+"/requestAsset", reqDate);
req.then((response)=>{
if(response.status == 200 && response.data.mesage){
callback("request for asset "+data.assetId+" placed sucessfully");
}
else
callback(response.data.error);
})
.catch((e) => {
callback("error please try again");
});
}
export const getRequests = (empId, type, query, callback) => {
const queryString = Object.keys(query)
.map((key) => {
return "&"+key+"="+query[key]
}).join("");
const req = axios.get(global.server_url+"/getMyRequests?empId="+empId+"&type="+type+queryString);
req.then((response)=>{
if(response.status == 200 && response.data.sucess){
callback(response.data.requests);
}
else
callback([]);
})
.catch((e) => {
console.log(e);
callback([]);
});
}
export const changeRequestState = (key, value, obj, callback) => {
let url = "";
let message = "";
let errorMsg = "";
let { reqEmp, assetId, requestId } = obj;
const state = store.getState();
if(key === 'approved') {
url = "/approveRequest";
message = "approve successfull";
errorMsg = "Error approve unsuccessful";
}
else if(key === 'isClosed') {
url = "/closeRequest";
message = "Request sucessfully closed";
errorMsg = "Error close unsuccessful";
}
else if(key === 'received') {
url = "/receiveAsset";
message = "received successfull";
errorMsg = "Error receive unsuccessful";
}
else if(key === 'cancel') {
url = "/cancelRequest";
message = "cancellation successfull";
errorMsg = "Error cancel unsuccessful";
}
const req = axios.post(global.server_url+url, {assetId, reqEmp, requestId, cancel:state.auth.empId});
req.then((response)=>{
if(response.status == 200 && response.data.sucess){
callback(null, message);
}
else {
errorMsg = response.data.error ? response.data.error : errorMsg;
callback(errorMsg, null);
}
})
.catch((e) => {
console.log(e);
callback(errorMsg, null);
});
}
export const searchAsset = (filter, callback) => {
const req = axios.post(global.server_url+"/searchAsset", filter);
req.then((response)=>{
if(response.status == 200 && response.data.sucess == true){
callback(response.data.data);
}
else {
console.log(response);
callback([]);
}
})
.catch((e) => {
callback([]);
});
}
export const searchAssetAdmin = (filter) => {
const req = axios.post(global.server_url+"/searchAssetAdmin", filter);
return (dispatch) => {
return req.then((response)=>{
if(response.status == 200 && response.data.sucess == true){
dispatch(setAsset({assets: response.data.message}));
}
else {
console.log(response);
dispatch(setAsset({assets: []}));
}
})
.catch((e) => {
console.log(e);
dispatch(setAsset({assets: []}));
});
}
}
export const assetTransactionsMonth = (state, callback) => {
let filter = Object.assign({}, state);
const req = axios.post("/assetTransactionsMonth", filter);
req.then((response)=>{
if(response.status == 200 && response.data.sucess == true){
callback(response.data.data);
}
else {
console.log(response);
callback([]);
}
})
.catch((e) => {
console.log(e);
callback([]);
});
}<file_sep>/src/components/common/alert_check.js
import React from 'react';
import { Alert } from 'react-native';
export default () => {
Alert.alert(
'Test',
'My Alert Msg',
[
{text: 'Ask me later', onPress: () => console.log('Ask me later pressed')},
{text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
{text: 'OK', onPress: () => console.log('OK Pressed')},
],
{ cancelable: false }
);
}<file_sep>/src/components/asset/request_asset.js
import { Col, Row, Grid } from 'react-native-easy-grid';
import React, { Component } from 'React';
import { connect } from 'react-redux';
import { View, Text, StyleSheet, Alert, ScrollView } from 'react-native';
import { Form, Item, Picker, Input, Button, Card, Badge, CardItem, Body, DatePicker, Toast } from 'native-base';
import { searchAsset, submitAsset, requestForAsset } from '../../actions/index';
import moment from 'moment';
class RequestAsset extends Component {
constructor(props){
super(props);
}
state = {
loading: false,
key: "assetId",
assetId: "",
fromDate: null,
endDate: null,
message: "",
value: "",
data: []
}
onDescChange(value) {
this.setState({key:value});
}
onTextChange(value) {
this.setState({assetId:value});
}
onFieldChange(text) {
this.setState({value:text});
}
onSearch() {
if(this.state.key)
searchAsset({[this.state.key]:this.state.value}, (data) => {
this.setState({data});
});
}
onDateChange(type, val) {
if(val) {
let newDate = moment.utc(val,'YYYY-MM-DD').format('YYYY-MM-DD');
this.setState({[type]:newDate});
}
}
displayAssetDetails() {
return this.state.data.map((asset, i) => {
return(
<Card key={i}>
<CardItem header bordered>
<Text>{"Asset Id: "+asset.assetId+" "}</Text>
<Text>{"owner: "+asset.owner+" "}</Text>
<Text>{"desc: "+asset.description+" "}</Text>
</CardItem>
<CardItem button onPress={() => this.displayCurrentStatus(asset.items[0])}>
<Body><Text>Click for more details</Text></Body>
</CardItem>
</Card>
);
});
}
displayCurrentStatus(details) {
let preText = "request from: "+details.reqEmp+"\n"+
"from: "+ new Date(details.fromDate).toDateString()+"\n"+
"to: "+ new Date(details.endDate).toDateString()+"\n";
preText = preText + (details.received ? "Asset received by "+details.reqEmp: "Asset approved to "+details.reqEmp);
Alert.alert("Details", preText);
}
requestAsset() {
let { assetId, fromDate, endDate } = this.state;
if(!assetId || !fromDate || !endDate) {
Toast.show({ text: 'all fields are required', buttonText: 'Okay', duration: 3000 });
return;
}
else if(fromDate > endDate) {
Toast.show({ text: "from date cannot be greater than end date", buttonText: 'Okay', duration: 3000 });
return;
}
this.setState({loading:true});
requestForAsset(this.state, (message)=>{
this.setState({loading:false, message:message});
Toast.show({ text: message, buttonText: 'Okay', duration: 3000 });
});
}
render() {
return(
<Grid>
<Row style={{height:160}}>
<Col style={styles.gridLayout}>
<Form>
<Item picker style={{height:50}}>
<Picker mode="dropdown" placeholder="Select type" selectedValue={this.state.key} onValueChange={this.onDescChange.bind(this)}>
<Picker.Item label="Asset" value="assetId" />
<Picker.Item label="Description" value="description" />
</Picker>
</Item>
<Item regular style={{height:50}}>
<Input placeholder={this.state.key} onChangeText={this.onFieldChange.bind(this)} />
</Item>
<Item style={{alignSelf:'center',height:100}}>
<Button rounded style={{width:100, justifyContent: 'center'}} onPress={this.onSearch.bind(this)}>
<Text>Search</Text>
</Button>
</Item>
</Form>
</Col>
<Col style={styles.gridLayout}>
<Form>
<Item regular style={{height:40}}>
<Input placeholder="asset id" onChangeText={this.onTextChange.bind(this)} />
</Item>
<Item regular style={{height:30}}>
<DatePicker
defaultDate={new Date()}
minimumDate={new Date()}
locale={"en"}
modalTransparent={false}
animationType={"fade"}
androidMode={"default"}
placeHolderText="Start Date"
textStyle={{ color: "green" }}
placeHolderTextStyle={{ color: "#d3d3d3" }}
onDateChange={this.onDateChange.bind(this, 'fromDate')}
/>
</Item>
<Item regular style={{height:30}}>
<DatePicker
defaultDate={new Date()}
minimumDate={new Date()}
locale={"en"}
modalTransparent={false}
animationType={"fade"}
androidMode={"default"}
placeHolderText="End Date"
textStyle={{ color: "green" }}
placeHolderTextStyle={{ color: "#d3d3d3" }}
onDateChange={this.onDateChange.bind(this, 'endDate')}
/>
</Item>
<Item style={{alignSelf:'center',height:100}}>
<Button rounded style={{width:100, justifyContent: 'center'}} onPress={this.requestAsset.bind(this)}>
<Text>Request</Text>
</Button>
</Item>
</Form>
</Col>
</Row>
<Row>
<View style={{flex: 1}}>
<View style={{height:390}}>
<ScrollView style={styles.contentContainer}>
{this.displayAssetDetails.bind(this)()}
</ScrollView>
</View>
</View>
</Row>
</Grid>
);
}
}
const styles = StyleSheet.create({
contentContainer: {
paddingVertical: 20,
borderWidth: 5,
borderColor: "grey"
},
gridLayout: {
borderWidth: 5,
borderColor: "grey",
height: 160
}
});
export default RequestAsset;
<file_sep>/README.md
# asset_transfer_android
asset tracker android application on hyperledger
## Summary
This project tracks asset within different departments of organization.
## Project setup
Run asset_transfer server first (https://github.com/pramodramdas/asset_transfer)
Update global.server_url in src -> App.js to asset_transfer server address ex:'http://localhost:3030'
<file_sep>/src/components/admin.js
import React, { Component } from 'React';
import { connect } from 'react-redux';
import { View, Text } from 'react-native';
import { Container, Tabs, Tab, Header, Input } from 'native-base';
import { requireAuth } from '../actions/auth';
import Participant from './participant/participant';
import Asset from './asset/asset';
class AdminComponent extends Component {
constructor(props){
super(props);
}
// componentWillMount() {
// requireAuth(this);
// }
componentWillMount() {
const { role } = this.props.auth;
if(role !== "admin")
this.props.history.push("/home");
}
render() {
return(
<View style={{height:"100%"}}>
<Tabs>
<Tab heading="Participant">
<Participant/>
</Tab>
<Tab heading="Asset">
<Asset/>
</Tab>
</Tabs>
</View>
);
}
}
const mapStateToProps = (state) => {
return {
auth:state.auth
}
};
export default connect(mapStateToProps, {})(AdminComponent);<file_sep>/src/actions/types.js
export const SET_AUTH_DATA = "SET_AUTH_DATA";
export const SET_PARTICIPANT = "SET_PARTICIPANT";
export const SET_ASSET= "SET_ASSET";<file_sep>/src/App.js
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import ReduxThunk from 'redux-thunk';
import store from "./utils/store";
import Router from "./Router";
import { AsyncStorage } from "react-native";
import { Root, Toast } from "native-base";
class App extends Component {
componentWillMount() {
global.server_url = 'http://10.0.2.2:3030';
}
render() {
return (
<Root>
<Provider store={store}>
<Router />
</Provider>
<Text>Toast</Text>
</Root>
);
}
}
export default App;<file_sep>/src/components/common/header.js
import React, { Component } from 'React';
import { View, Text } from 'react-native';
import { Link } from 'react-router-native';
import { Segment, Header, Title, Content, Button, Left, Right, Body, Icon } from 'native-base';
import { logout } from '../../actions/auth';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
class HeaderComponent extends Component {
constructor(props){
super(props);
}
state = {
currActive: "Seg2"
}
onSegmentChange(id) {
this.setState({currActive:id},
() =>{
if(id == "Seg2")
this.props.history.push('/home');
else if(id == "Seg1")
this.props.history.push('/admin');
});
}
render() {
const { role } = this.props.auth;
return(
<Header>
<Body>
<Segment>
{
(role === "admin")?
<Button id="Seg1" first success active={this.state.currActive=="Seg1"} onPress={this.onSegmentChange.bind(this, "Seg1")}><Text>Admin</Text></Button>:
null
}
<Button id="Seg2" last success active={this.state.currActive=="Seg2"} onPress={this.onSegmentChange.bind(this, "Seg2")}>
<Text>Home</Text>
</Button>
</Segment>
</Body>
<Right>
<Button rounded info onPress={()=>{ this.props.logout(this); }}>
<Text>Log out</Text>
</Button>
</Right>
</Header>
);
}
}
const mapStateToProps = (state) => {
return {
auth:state.auth
}
};
const actionCreators ={
logout
};
//HeaderComponent.contextTypes = {
// router: PropTypes.object.isRequired,
// history: PropTypes.object.isRequired
//};
export default connect(mapStateToProps, actionCreators)(HeaderComponent);<file_sep>/src/components/signup.js
import React, { Component } from 'React';
import { connect } from 'react-redux';
import { View, Text } from 'react-native';
import { Container, Header, Content, Form, Item, Input, Body, Title, Button, Toast } from 'native-base';
import { Field, reduxForm } from 'redux-form';
import { userSignUp } from '../actions/auth';
class SignUp extends Component {
constructor(props){
super(props);
}
state = {
name: "",
s_email: "",
s_password: "",
confirmPassword: ""
}
handleSignUp(){
let { name, s_email, s_password, confirmPassword } = this;
let msg = "";
if(!name || !s_email || !s_password || !confirmPassword)
Toast.show({ text: "all fileds are mandatory", buttonText: 'Okay', duration: 3000 });
else if(s_password !== <PASSWORD>Password)
Toast.show({ text: "password did not match", buttonText: 'Okay', duration: 3000 });
if(msg) {
Toast.show({ text: msg, buttonText: 'Okay', duration: 3000 });
return;
}
userSignUp(
{ name, email: s_email, password: <PASSWORD> },
(err, msg) => {
if(err)
Toast.show({ text: err, buttonText: 'Okay', duration: 3000 });
else
Toast.show({ text: msg, buttonText: 'Okay', duration: 3000 });
}
);
}
renderInput({ input, label, type, meta: { touched, error, warning }, placeholder }){
var hasError= false;
if(error !== undefined){
hasError= true;
}
return(
<Item error= {hasError}>
<Input {...input} placeholder={placeholder} />
{hasError ? <Text>{error}</Text> : <Text />}
</Item>
)
}
//Toast.show({ text: "all fields are required", buttonText: 'Okay', duration: 3000 });
render() {
const { handleSubmit, reset } = this.props;
return(
<View>
<Header>
<Body>
<Title>Sign Up</Title>
</Body>
</Header>
<View style={{flexDirection:'column', justifyContent:'space-between'}}>
<Field name="name" placeholder="name" component={this.renderInput} />
<Field name="s_email" placeholder="email" component={this.renderInput} />
<Field name="s_password" placeholder="<PASSWORD>" component={this.renderInput} />
<Field name="confirmPassword" placeholder="<PASSWORD>" component={this.renderInput} />
<Button block primary onPress= {handleSubmit(this.handleSignUp.bind(this))}>
<Text>Submit</Text>
</Button>
<Button block primary onPress= {()=>this.props.history.push('/login')}>
<Text>Login</Text>
</Button>
</View>
</View>
);
}
}
const formStyle = {
"display": "flex",
"flexDirection": "column",
"justifyContent": "center",
"paddingTop": 20,
"paddingBottom": 20
}
SignUp = reduxForm({
form: 'signup',
fields: ['name', 's_email', 's_password', '<PASSWORD>']
})(SignUp);
export default connect(null, {})(SignUp);<file_sep>/src/actions/auth.js
import axios from "axios";
import { SET_AUTH_DATA } from "./types";
import store from '../utils/store';
import { AsyncStorage } from "react-native"
import { Toast } from 'native-base';
export function setAuthData (auth) {
return {
type: SET_AUTH_DATA,
auth
};
}
export const logout = (that) => {
setTokenToAxios();
return async (dispatch) => {
await AsyncStorage.removeItem('auth');
await dispatch(setAuthData({jwtToken:null}));
if(that)
that.props.history.push('/login');
}
}
export const requireAuth = async (that) => {
const auth = await AsyncStorage.getItem('auth');
const accessToken = auth ? JSON.parse(auth).jwtToken : null;
const req = axios.get(global.server_url+"/validate?authToken="+accessToken);
req.then(resp => {
if(!resp || resp.data.sucess === false){
logout()(store.dispatch);
that.props.history.push('/login');
}
})
.catch(error => {
logout()(store.dispatch);
that.props.history.push('/login');
});
}
export const requireRouteAuth = async (that, callback) => {
const auth = await AsyncStorage.getItem('auth');
const accessToken = auth ? JSON.parse(auth).jwtToken : null;
const req = axios.get(global.server_url+"/validate?authToken="+accessToken);
req.then(resp => {
if(!resp || resp.data.sucess === false){
logout()(store.dispatch);
that.history.push('/login');
callback(false);
}
else
callback(true);
})
.catch(error => {
logout()(store.dispatch);
that.props.history.push('/login');
callback(false);
});
}
export const userAuthenticate = (authObj, that) => {
const req = axios.post(global.server_url+"/authenticate", authObj);
let msg = '';
return (dispatch) => {
return req.then(async (response) => {
if(response && response.status == 200) {
const { auth } = response.data;
if(auth){
setTokenToAxios(auth.jwtToken);
await AsyncStorage.setItem('auth', JSON.stringify(auth));
await dispatch(setAuthData(auth));
that.props.history.push('/home');
}
else
Toast.show({ text: "wrong username or password", buttonText: 'Okay', duration: 3000 })
}
})
.catch((err) => {
debugger
msg = (err.response && (err.response.status == 401)) ? "wrong username or password" : err.message;
console.log(err);
Toast.show({ text: msg, buttonText: 'Okay', duration: 3000 })
});
}
}
export const userSignUp = (authObj, callback) => {
const req = axios.post(global.server_url+"/signup", authObj);
return req.then((response) => {
if(response && response.data.sucess) {
callback(null, "user added sucessfully");
}
else {
if(response.data.message) callback(response.data.message);
else callback("error signup unsucessful");
}
});
}
export const checkAuth = async (history) => {
const auth = await AsyncStorage.getItem('auth');
const accessToken = auth ? JSON.parse(auth).jwtToken : null;
if(accessToken) {
store.dispatch(setAuthData(JSON.parse(auth)));
setTokenToAxios(accessToken);
history.push('/home');
}
else {
history.push('/login');
}
}
export const setTokenToAxios = (token) => {
if (token) {
axios.defaults.headers.common["authToken"] = token;
} else {
delete axios.defaults.headers.common["authToken"];
}
};
<file_sep>/src/components/participant/participant.js
import { connect } from "react-redux";
import { View, Text } from 'react-native';
import { Container, Tabs, Tab, Header, Input, Button, Picker, Form, Toast, Item } from 'native-base';
import React from "react";
import { submitParticipant, getParticipants, getDepts } from '../../actions/index';
import SearchItems from '../search_items';
class Participant extends React.Component {
constructor(props) {
super(props);
}
state = {
empId: "",
name: "",
email: "",
role: "user",
department: "",
depList: [],
message: "",
loading: false
}
componentDidMount() {
getDepts(({data}) => {
this.setState({depList: data});
if(data.length > 0) this.setState({department:data[0].depName});
})
}
onFieldChange(field, value) {
this.setState({[field]:value});
}
handleChange(value) {
debugger
this.setState({role:value});
}
depChange(value) {
this.setState({department:value});
}
addParticipant() {
let { empId, name, email, role, department } = this.state;
if(!empId || !name || !email || !role || !department) {
Toast.show({ text: "all fields are required", buttonText: 'Okay', duration: 3000 });
return;
}
this.setState({loading:true});
submitParticipant({ empId, name, email, role, department }, (message)=>{
this.setState({loading:false});
Toast.show({ text: message, buttonText: 'Okay', duration: 3000 });
});
}
searchParticipant() {
let filter = JSON.stringify(this.state, (key, value) => {if(value)return value});
this.props.getParticipants(JSON.parse(filter));
}
render() {
return(
<View style={{flex:1, flexDirection:"column"}}>
<View style={{flex:1, flexDirection:"column", width:"100%", height:400 }}>
<Form>
<Item regular style={{height:40}}>
<Input placeholder="Employee Id" onChangeText={this.onFieldChange.bind(this,"empId")}/>
</Item>
<Item regular style={{height:40}}>
<Input placeholder="Participant Name" onChangeText={this.onFieldChange.bind(this,"name")}/>
</Item>
<Item regular style={{height:40}}>
<Input placeholder="Email ID" onChangeText={this.onFieldChange.bind(this,"email")}/>
</Item>
<Picker style={{height:40}} mode="dropdown" placeholder="Dept" selectedValue={this.state.department} onValueChange={this.depChange.bind(this)}>
{
this.state.depList.map((dep, i) => {
return <Picker.Item key={i} label={dep.depName} value={dep.depName} />
})
}
</Picker>
<Picker style={{height:40}} mode="dropdown" placeholder="Role" selectedValue={this.state.role} onValueChange={this.handleChange.bind(this)}>
<Picker.Item label="User" value="user" />
<Picker.Item label="Admin" value="admin" />
</Picker>
<View style={{flex:1, flexDirection:"row", width:"100%", justifyContent:'space-between'}}>
<Button primary style={{width:100, justifyContent:'center'}} onPress={this.addParticipant.bind(this)} >
<Text>Add</Text>
</Button>
<Button primary style={{width:100, justifyContent:'center'}} onPress={this.searchParticipant.bind(this)} >
<Text>Search</Text>
</Button>
</View>
</Form>
</View>
<View style={{height:300}}>
<SearchItems type="participants"/>
</View>
</View>
);
}
}
const actionCreators = { getParticipants };
export default connect(null, actionCreators)(Participant);<file_sep>/src/Router.js
import React from 'react';
import axios from "axios";
import { NativeRouter, MemoryRouter, Route, Link, Switch, Prompt } from 'react-router-native';
import { View, Text } from 'react-native';
import { Alert } from 'react-native';
import createMemoryHistory from 'history/createMemoryHistory';
import IndexComponent from './index.js';
import Login from './components/login';
import SignUp from './components/signup';
import Home from './components/home';
import Admin from './components/admin';
import { requireRouteAuth } from './actions/index';
const history = createMemoryHistory()
const getConfirmation = (message, callback) => {
requireRouteAuth({props:{history}}, callback);
}
const RouterComponent = () => {
return(
<NativeRouter getUserConfirmation={getConfirmation}>
<View>
<Route path="/" history={history} render={
(props) => {
return <IndexComponent history={props.history}>
<Switch>
<Route path="/login" component={Login} />
<Route path="/admin" component={Admin}/>
<Route path="/home" component={Home} />
<Route path="/signup" component={SignUp} />
<Route component={Login} />
</Switch>
</IndexComponent>
}}
/>
<Prompt when={true} message={
location => {
if(location.pathname!="/login" && location.pathname!="/signup")
return "yes";
}}
/>
</View>
</NativeRouter>
);
};
export default RouterComponent;<file_sep>/src/components/asset/display_requests.js
import React, { Component } from 'React';
import { connect } from 'react-redux';
import { Container, Tabs, Tab, Header, Input, Card, CardItem, Body, Badge, Button, Accordion, Toast } from 'native-base';
import { Modal, Text, TouchableHighlight, View, StyleSheet, ScrollView } from 'react-native';
import SearchRequests from './search';
import { getRequests, changeRequestState } from '../../actions/index';
const clickOwner = ['approved', 'isClosed', 'cancel'];
const clickUser = ['received', 'cancel'];
const dateKeyList = ["fromDate", "endDate", "submittedDate", "receivedDate", "approvedDate", "requestDate"];
class DisplayRequests extends Component {
constructor(props){
super(props);
this.person = this.props.type === "my_request" ? clickUser : clickOwner;
}
state = {
loading: false,
data: []
}
componentDidMount() {
this.loadRequests.bind(this)(this.props.type);
}
componentWillReceiveProps(newProps) {
if(newProps.type !== this.props.type) {
this.loadRequests.bind(this)(newProps.type);
this.person = (newProps.type === "my_request") ? clickUser : clickOwner;
}
}
handleTagClick(obj, key, value) {
if((key !== "cancel" && obj["cancel"]) ||
(key === "received" && !obj["approved"]) ||
(key === "isClosed" && !obj["received"]) ||
(key === "cancel" && obj["received"]))
return;
changeRequestState(key, value, obj, (err, msg) => {
if(!err)
Toast.show({ text: msg, buttonText: 'Okay', duration: 3000 });
else
Toast.show({ text: err, buttonText: 'Okay', duration: 3000 });
this.loadRequests.bind(this)(this.props.type);
});
}
setModalVisible(visible) {
this.setState({modalVisible: visible});
}
filterRequests(query) {
this.loadRequests.bind(this)(this.props.type, query);
}
loadRequests (type, query={}) {
getRequests(this.props.auth.empId, type, query, (data) => {
this.setState({data});
});
}
renderCards(obj) {
let displayDetails;
displayDetails = Object.keys(obj).map((key, i) => {
if(obj[key] === true || obj[key] === false)
return;
else if(dateKeyList.indexOf(key) > -1)
return <Text key={i}>{key} : {new Date(obj[key]).toDateString()}{`\n`}{`\n`}</Text>
else
return(
<Text key={i}>
{key} : {obj[key]}{`\n`}{`\n`}
</Text>
);
});
return [{ title: "click for more details .....", content: displayDetails}]
}
renderFooter(obj) {
if(obj.cancel)
return "This request is cancelled by "+obj.cancel;
else if(!obj.approved && !obj.received && !obj.isClosed)
return "This request is open";
else
return "This request is " + (obj.isClosed ? "closed" : ( obj.received ? "received" : "approved"))
}
getProps(key, obj) {
let handleClick = (this.person.indexOf(key) > -1 && !obj[key])? this.handleTagClick.bind(this, obj, key, obj[key]) : null;
return (obj[key] === true) ? {success:true} : {danger:true, onPress:handleClick};
}
renderRequests(){
let approvedColor;
let receivedColor;
let isClosedColor;
let cancelColor;
return this.state.data.map((item, i) => {
approvedProps = this.getProps("approved", item);
receivedProps = this.getProps("received", item);
isClosedProps= this.getProps("isClosed", item);
cancelProps = this.getProps("cancel", item);
return(
<Card key={i}>
<CardItem header bordered style={styles.cardStyle}>
<Text style={{fontWeight: "bold"}} > Asset Id : {item.assetId} </Text>
<Button small {...approvedProps}>
<Text> approved </Text>
</Button>
<Button small {...receivedProps}>
<Text> received </Text>
</Button>
<Button small {...isClosedProps}>
<Text> closed </Text>
</Button>
<Button small {...cancelProps}>
<Text> cancel </Text>
</Button>
</CardItem>
<CardItem>
<Body>
<Accordion style={{width:"100%"}} dataArray={this.renderCards(item)}/>
</Body>
</CardItem>
<CardItem footer bordered>
<Text style={{fontWeight: "bold"}}>Status: {this.renderFooter(item)}</Text>
</CardItem>
</Card>
);
});
}
render() {
return (
<View>
<SearchRequests filterRequests={this.filterRequests.bind(this)}/>
<View style={{flex: 1}}>
<View style={{height:394}}>
<ScrollView style={styles.contentContainer}>
{this.renderRequests.bind(this)()}
</ScrollView>
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
contentContainer: {
paddingVertical: 20,
borderWidth: 5,
borderColor: "grey"
},
cardStyle: {
flex:1,
flexDirection:"row",
justifyContent:'space-between'
}
});
const mapStateToProps = (state) => {
return {
auth:state.auth
}
};
export default connect(mapStateToProps)(DisplayRequests);<file_sep>/src/components/common/drawerComponent.js
import React, { Component } from 'react';
import Drawer from 'react-native-drawer'
import { View, Text, DrawerLayoutAndroid } from 'react-native';
import SideBar from './sideBar';
import Header from './header';
class DrawerComponent extends Component {
constructor(props) {
super(props);
}
closeControlPanel = () => {
this._drawer.close()
};
openControlPanel = () => {
this._drawer.open()
};
render () {
var navigationView = (
<View style={{flex: 1, backgroundColor: '#fff'}}>
<Text style={{margin: 10, fontSize: 15, textAlign: 'left'}}>I'm in the Drawer!</Text>
</View>
);
return (
<DrawerLayoutAndroid
drawerWidth={300}
drawerPosition={DrawerLayoutAndroid.positions.Left}
renderNavigationView={() => navigationView}>
<View style={{height:200}}>
{this.props.children}
</View>
</DrawerLayoutAndroid>
);
}
}
export default DrawerComponent;<file_sep>/src/components/login.js
import React, { Component } from 'React';
import { connect } from 'react-redux';
import { View, Text } from 'react-native';
import { Container, Header, Content, Form, Item, Input, Body, Title, Button } from 'native-base';
import { Field, reduxForm } from 'redux-form';
import { userAuthenticate } from '../actions/auth';
class Login extends Component {
constructor(props){
super(props);
}
handleFormSubmit({ email, password }) {
this.props.userAuthenticate({ email, password } , this);
}
renderInput({ input, label, type, meta: { touched, error, warning }, placeholder }){
var hasError= false;
if(error !== undefined){
hasError= true;
}
return(
<Item error= {hasError}>
<Input {...input} placeholder={placeholder} />
{hasError ? <Text>{error}</Text> : <Text />}
</Item>
)
}
render() {
const { handleSubmit, reset } = this.props;
return(
<View>
<Header>
<Body>
<Title>Login</Title>
</Body>
</Header>
<View style={{flexDirection:'column', justifyContent:'space-between'}}>
<Field name="email" placeholder="email" component={this.renderInput} />
<Field name="password" placeholder="<PASSWORD>" component={this.renderInput} />
<Button block primary onPress= {handleSubmit(this.handleFormSubmit.bind(this))}>
<Text>Submit</Text>
</Button>
<Button block primary onPress= {()=>this.props.history.push('/signup')}>
<Text>Sign Up</Text>
</Button>
</View>
</View>
);
}
}
const formStyle = {
"display": "flex",
"flexDirection": "column",
"justifyContent": "center",
"paddingTop": 20,
"paddingBottom": 20
}
const actionCreators = {
userAuthenticate
}
Login = reduxForm({
form: 'signin',
fields: ['email', 'password']
})(Login);
export default connect(null, actionCreators)(Login);
//export default Login;<file_sep>/android/settings.gradle
rootProject.name = 'asset_transfer_android'
include ':app'
|
c36ac93b4ca60337bfed7721bec8d929a0d67edf
|
[
"JavaScript",
"Markdown",
"Gradle"
] | 20
|
JavaScript
|
pramodramdas/asset_transfer_android
|
12085294821c8d2a8824b7f000d72ccfc97d8db6
|
a39b7a0e269707767bcccafb2357b03b1856a3f1
|
refs/heads/master
|
<file_sep>from django.db import models
from django.contrib.auth.models import User
from django.dispatch import receiver
from django.db.models.signals import post_save, pre_delete, pre_save
class Profile(models.Model):
user = models.OneToOneField(User)
website = models.URLField(blank=True)
image = models.ImageField(upload_to="profileimages", blank=True)
def __str__(self):
return self.user.username
def save(self, *args, **kwargs):
try:
this = Profile.objects.get(pk=self.pk)
if this.image != self.image:
this.image.delete(save=False)
except Profile.DoesNotExist:
pass
super(Profile, self).save(*args, **kwargs)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
@receiver(pre_delete, sender=Profile)
def profile_delete(sender, instance, **kwargs):
# Pass false so FileField doesn't save the model.
instance.image.delete(False)
<file_sep>from django import forms
from .models import Category, Page
class CategoryForm(forms.ModelForm):
class Meta:
model = Category
fields = ('name',)
widgets = {
'name': forms.TextInput(attrs={'class': 'form-control'}),
}
help_texts = {
'name': 'Please enter Category name',
}
class PageForm(forms.ModelForm):
class Meta:
model = Page
fields = ('title', 'url')
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control'}),
'url': forms.TextInput(attrs={'class': 'form-control'})
}
help_texts = {
'title': 'Please enter title of the page',
'url': 'Please enter the URL of the page'
}
def clean_url(self):
url = self.cleaned_data.get('url')
if url and not url.startswith('http://'):
url = 'http://' + url
return url
<file_sep>from django import template
from ..models import Category
register = template.Library()
@register.inclusion_tag('pages/categories.html')
def category_list(active=None):
return {'categories': Category.objects.all(), 'active_cat': active}
<file_sep>from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from .models import Category, Page
from .forms import CategoryForm, PageForm
def index(request):
categories = Category.objects.order_by("-likes")[:5]
most_viewed_pages = Page.objects.order_by("-views")[:5]
return render(request, 'pages/index.html', {'categories': categories,
'pages': most_viewed_pages})
def about(request):
return render(request, 'pages/about.html')
def category_detail(request, slug):
category = get_object_or_404(Category, slug=slug)
pages = category.pages.all()
return render(request, 'pages/category/detail.html', {'category': category, 'pages': pages})
@login_required
def category_create(request):
if request.method == 'POST':
form = CategoryForm(request.POST)
if form.is_valid():
form.save()
return redirect('root')
else:
print(form.errors)
else:
form = CategoryForm()
return render(request, 'pages/category/create.html', {'form': form})
@login_required
def page_create(request, slug):
category = get_object_or_404(Category, slug=slug)
if request.method == 'POST':
form = PageForm(request.POST)
if form.is_valid():
page = form.save(commit=False)
page.category = category
page.save()
return redirect(category)
else:
print(form.errors)
else:
form = PageForm()
return render(request, 'pages/create.html', {'form': form, 'category': category})
<file_sep>from django.conf.urls import url
from . import views
app_name = 'pages'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^about/$', views.about, name='about'),
url(r'^(?P<slug>[-\w]+)/$', views.category_detail, name='detail'),
url(r'^category/new/$', views.category_create, name='create'),
url(r'^(?P<slug>[-\w]+)/page/new/$', views.page_create, name='page_create')
]
<file_sep>from django.conf.urls import url, include
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
from pages import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^read/', include('pages.urls')),
url(r'^users/', include('users.urls')),
url(r'^$', views.index, name='root'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
<file_sep>from django.db import models
from django.utils.text import slugify
from django.core.urlresolvers import reverse
class Category(models.Model):
name = models.CharField(max_length=120, unique=True, db_index=True)
views = models.PositiveIntegerField(default=0)
likes = models.PositiveIntegerField(default=0)
slug = models.SlugField(unique=True, db_index=True)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = 'categories'
ordering = ('name',)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Category, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('pages:detail', args=[self.slug])
class Page(models.Model):
category = models.ForeignKey(Category, related_name='pages')
title = models.CharField(max_length=120)
url = models.URLField()
views = models.PositiveIntegerField(default=0)
def __str__(self):
return self.title
class Meta:
ordering = ('title',)
<file_sep>from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from .forms import UserForm, ProfileForm, LoginForm
def register(request):
if request.method == 'POST':
user_form = UserForm(data=request.POST)
if user_form.is_valid():
user = user_form.save()
user.set_password(user_form.cleaned_data['password'])
user.save()
profile_form = ProfileForm(data=request.POST, files=request.FILES, instance=user.profile)
if profile_form.is_valid():
profile_form.save()
if user.is_active:
login(request, user)
return redirect('root')
else:
user_form = UserForm()
profile_form = ProfileForm()
return render(request, 'users/register.html', {'user_form': user_form, 'profile_form': profile_form})
def user_login(request):
logout(request)
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['<PASSWORD>'])
if user:
if user.is_active:
login(request, user)
return redirect('root')
else:
form.add_error('username', 'Does not exist')
else:
form = LoginForm()
return render(request, 'users/login.html', {'form': form})
@login_required
def user_logout(request):
logout(request)
return redirect('root')
<file_sep>from django import forms
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from .models import Profile
class UserForm(forms.ModelForm):
confirm_password = forms.CharField()
password = forms.CharField()
def __init__(self, *args, **kwargs):
super(UserForm, self).__init__(*args, **kwargs)
for field in self.visible_fields():
field.field.widget.attrs['class'] = 'form-control'
class Meta:
model = User
fields = ('username', 'email', 'password', 'confirm_password')
def clean(self):
if self.cleaned_data['password'] != self.cleaned_data['confirm_password']:
raise ValidationError("Passwords didn't match.")
return self.cleaned_data
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('website', 'image')
widgets = {
'website': forms.TextInput(attrs={'class': 'form-control'})
}
class LoginForm(forms.Form):
username = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}))
password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control'}))
|
180425b6af13bf8d0ec5c756e6f152d4782ac715
|
[
"Python"
] | 9
|
Python
|
mihilbabin/pyread
|
9d1aa58ffe8783cf4b942a1eb49dcfe87296611d
|
265c182539a6ca9407a164a4a16d134275de1527
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.