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>using UnityEngine; using UnityEngine.UI; using System.Collections; public class HealthKeeper : MonoBehaviour { public static int health = 100; private Text myText; void Start () { HealthReset(); myText = GetComponent<Text>(); } public void Health(int damage) { health += damage; myText.text = health.ToString() + " :HEALTH"; } public static void HealthReset() { health = 100; } } <file_sep>using UnityEngine; using System.Collections; public class EnemyBehavior : MonoBehaviour { public GameObject enemyDeathPS; public GameObject enemyLaser; public float enemyLaserSpeed = 2f; public float enemyHealth = 1000f; public int scoreValue = 1000; public AudioClip enemyHit; public AudioClip enemyExplode; private float enemyFireRate = 1.5f; private ScoreKeeper scoreKeeper; void Start () { scoreKeeper = GameObject.Find("Score").GetComponent<ScoreKeeper>(); } void Update () { float probability = Time.deltaTime / enemyFireRate; float random = Random.value; if(random < probability) { EnemyAttack(); } } void OnTriggerEnter2D(Collider2D collider) { Laser laser = collider.gameObject.GetComponent<Laser> (); if (laser) { enemyHealth = enemyHealth - laser.laserDamage; AudioSource.PlayClipAtPoint (enemyHit, transform.position); Debug.Log (enemyHealth); } Destroy(collider.gameObject); if (enemyHealth <= 0) { EnemyDeathExplosion (); Destroy (gameObject); scoreKeeper.Score(scoreValue); } } void EnemyAttack() { Vector3 laserOffset = transform.position + new Vector3(0, -0.35f, 0); GameObject laserbeam = Instantiate (enemyLaser, laserOffset, Quaternion.identity) as GameObject; laserbeam.rigidbody2D.velocity = new Vector3(0, -enemyLaserSpeed, 0); } void EnemyDeathExplosion() { //spawns death explosion particle system on death of enemy Instantiate (enemyDeathPS, transform.position, Quaternion.identity); AudioSource.PlayClipAtPoint (enemyExplode, transform.position); } } <file_sep>using UnityEngine; using System.Collections; public class EnemySpawner : MonoBehaviour { public GameObject enemyPrefab; public float width = 6.5f; public float height = 4.3f; public float enemySpeed = 1f; private bool movingLeft = true; private float xmin; private float xmax; private float spawnDelay = 1f; void Start () { if(AllEnemiesDead()) { EnemySpawn(); } } public void OnDrawGizmos() { Gizmos.DrawWireCube(transform.position, new Vector3(width, height)); } void Update () { EnemyFormationMovementLimit(); EnemyFormationMovementControl(); if (AllEnemiesDead()) { Debug.Log("All Enemies Dead"); EnemySpawn (); } } void EnemySpawn() { Transform freePosition = NextFreePosition(); if(freePosition) { GameObject enemy = Instantiate(enemyPrefab, freePosition.position, Quaternion.identity) as GameObject; enemy.transform.parent = freePosition; } if(NextFreePosition()) { Invoke ("EnemySpawn", spawnDelay); } } void EnemyFormationMovementLimit() { float distance = transform.position.z - Camera.main.transform.position.z; Vector3 leftmost = Camera.main.ViewportToWorldPoint(new Vector3(0, 0, distance)); Vector3 rightmost = Camera.main.ViewportToWorldPoint(new Vector3(1, 0, distance)); xmin = leftmost.x; xmax = rightmost.x; } void EnemyFormationMovementControl() { if(movingLeft) { transform.position += Vector3.left * enemySpeed * Time.deltaTime; } else { transform.position += Vector3.right * enemySpeed * Time.deltaTime; } //tells the formation when to move left or right float rightEdgeOfFormation = transform.position.x; float leftEdgeOfFormation = transform.position.x; if(rightEdgeOfFormation > xmax) { movingLeft = true; } else if (leftEdgeOfFormation < xmin) { movingLeft = false; } //limits the movement of the enemy formation within camera viewport float newX = Mathf.Clamp(transform.position.x, xmin, xmax); transform.position = new Vector3(newX, transform.position.y, transform.position.z); } Transform NextFreePosition() { foreach(Transform childPositionGameObject in transform) { if (childPositionGameObject.childCount == 0) { return childPositionGameObject; } } return null; } bool AllEnemiesDead() { foreach(Transform childPositionGameObject in transform) { if (childPositionGameObject.childCount > 0) { return false; } } return true; } } <file_sep>using UnityEngine; using System.Collections; public class PlayerController : MonoBehaviour { public GameObject playerLaser; public GameObject playerDeathPS; public float laserSpeed = 2.0f; public float fireRate = 1f; public float playerHealth = 100f; public float shipSpeed = 8.0f; public float padding = 0.22f; public int shipHealth = 100; public AudioClip playerHit; public AudioClip playerExplode; private LevelManager levelManager; private HealthKeeper healthKeeper; private float xmin; private float xmax; void Start () { levelManager = GameObject.FindObjectOfType<LevelManager>(); healthKeeper = GameObject.Find("Health").GetComponent<HealthKeeper>(); } void Update () { PlayerMovementLimit (); PlayerMovementControl(); if(Input.touchCount > 0){ InvokeRepeating("ShootLaser", 0.000001f, fireRate); } else if (Input.touchCount == 0) { CancelInvoke("ShootLaser"); } } void OnTriggerEnter2D(Collider2D collider) { EnemyLaser laser = collider.gameObject.GetComponent<EnemyLaser> (); if (laser) { playerHealth = playerHealth - laser.laserDamage; Debug.Log (playerHealth); shipHealth =- 10; healthKeeper.Health(shipHealth); AudioSource.PlayClipAtPoint (playerHit, transform.position); } Destroy(collider.gameObject); if (playerHealth <= 0) { Die(); } } void Die () { PlayerDeathExplosion (); AudioSource.PlayClipAtPoint (playerExplode, transform.position); LevelManager man = GameObject.Find("LevelManager").GetComponent<LevelManager>(); man.LoadLevel("Lose"); Destroy (gameObject); } void PlayerMovementLimit () { float distance = transform.position.z - Camera.main.transform.position.z; Vector3 leftmost = Camera.main.ViewportToWorldPoint(new Vector3(0, 0, distance)); Vector3 rightmost = Camera.main.ViewportToWorldPoint(new Vector3(1, 0, distance)); xmin = leftmost.x + padding; xmax = rightmost.x - padding; } void PlayerMovementControl () { transform.Translate(Input.acceleration.x, 0, 0); //restricts player ship to camera view float newX = Mathf.Clamp(transform.position.x, xmin, xmax); transform.position = new Vector3(newX, transform.position.y, transform.position.z); } void ShootLaser() { GameObject beam = Instantiate (playerLaser, transform.position, Quaternion.identity) as GameObject; beam.rigidbody2D.velocity = new Vector3(0, laserSpeed, 0); } void PlayerDeathExplosion() { Instantiate (playerDeathPS, transform.position, Quaternion.identity); } }<file_sep>using UnityEngine; using System.Collections; public class GameOverAudio : MonoBehaviour { public AudioClip gameOver; void Start () { GameOver(); } void GameOver() { AudioSource.PlayClipAtPoint (gameOver, transform.position); } } <file_sep>using UnityEngine; using System.Collections; public class MusicController : MonoBehaviour { static MusicController instance = null; public AudioClip startMusic; public AudioClip gameMusic; public AudioClip loseMusic; private AudioSource music; void Awake () { if (instance != null) { Destroy (gameObject); print ("Duplicate Music Player Destroyed"); } else { instance = this; GameObject.DontDestroyOnLoad(gameObject); music = GetComponent<AudioSource>(); music.clip = startMusic; music.loop = true; music.Play(); } } void Start () { } void OnLevelWasLoaded(int level) { Debug.Log("Music Player: Level Loaded: " + level); music.Stop(); if(level == 0) { music.clip = startMusic; } if(level == 1) { music.clip = gameMusic; } if(level == 2) { music.clip = loseMusic; } music.loop = true; music.Play(); } } <file_sep>using UnityEngine; using System.Collections; public class EnemyLaser : MonoBehaviour { public float laserDamage = 10f; } <file_sep>using UnityEngine; using System.Collections; public class CameraGizmo : MonoBehaviour { public float width = 5.64f; public float height = 10f; public void OnDrawGizmos() { Gizmos.DrawWireCube(transform.position, new Vector3(width, height)); } } <file_sep>using UnityEngine; using System.Collections; public class Laser : MonoBehaviour { public float laserDamage = 100f; }
e9b44ce9e4e3aa86715763126cc63668e0b17173
[ "C#" ]
9
C#
drtomtron/Kill-All-Aliens-iOS
5d5027e6f209f18584bba5015ccc1b15c577d403
e19cfacdc8355691c87dc3945a95bc479fa2ac5a
refs/heads/master
<file_sep><?php namespace App\Http\Controllers\User; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Http\Repositories\Eloquents\User\RoleUserEloquent; use App\Model\User\Role; use App\Model\User\User; use App\Model\User\RoleUser; class RoleUserController extends Controller { private $role_user; private $user; private $role; public function __construct(User $user, Role $role,RoleUser $role_user) { $this->role_user = new RoleUserEloquent($role_user); $this->role = new RoleUserEloquent($role); $this->user = new RoleUserEloquent($user); } public function index(Request $request) { if($request->option === 'user') return $this->user->all(); else if($request->option === 'role') return $this->role->all(); else return response()->json([ 'empty' => true ],200); } public function store(Request $request) { $role_user = $this->role_user->add($request->only($this->role_user->getModel()->fillable)); return response()->json([ 'success' => true, 'data' => $this->show($role_user->user_id) ],201); } public function show($id) { return $this->role_user->single($id); } public function update(Request $request, $id) { $role_user = $this->role_user->change($request->only($this->role_user->getModel()->fillable), $id); return response()->json([ 'success' => true, 'data' => $this->show($role_user->user_id) ],200); } public function destroy($id) { $this->role_user->delete($id); return response()->json([ 'success' => true ],200); } } <file_sep><?php namespace App\Http\Controllers\Product; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Http\Repositories\Eloquents\Product\CategoriesEloquent; use App\Model\Product\Category; class CategoriesController extends Controller { private $category; public function __construct(Category $category) { $this->category = new CategoriesEloquent($category); } public function index() { return $this->category->all(); } public function store(Request $request) { $category = $this->category->add($request->only($this->category->getModel()->fillable)); return response()->json([ 'success' => true, 'data' => $category ],201); } public function show($id) { return $this->category->single($id); } public function update(Request $request, $id) { $category = $this->category->change($request->only($this->category->getModel()->fillable), $id); return response()->json([ 'success' => true, 'data' => $category ],200); } public function destroy($id) { $this->category->delete($id); return response()->json([ 'success' => true ],200); } } <file_sep># janrey-eCommerce <file_sep><?php namespace App\Http\Controllers\Product; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Http\Repositories\Eloquents\Product\ProductTagsEloquent; use App\Model\Product\ProductTag; use App\Model\Product\Product; class ProductTagsController extends Controller { private $tag_product; public function __construct(ProductTag $tag_product,Product $product) { $this->tag_product = new ProductTagsEloquent($tag_product); $this->product = new ProductTagsEloquent($product); } public function index() { $products = $this->product->all(); foreach($products as $product) { return response()->json([ 'data' => $product->tag ],200); } } public function store(Request $request) { $tag_product = $this->tag_product->add($request->only($this->tag_product->getModel()->fillable)); return response()->json([ 'success' => true, 'data' => $tag_product ],201); } public function show($id) { return $this->tag_product->single($id); } public function update(Request $request, $id) { $tag_product = $this->tag_product->change($request->only($this->tag_product->getModel()->fillable), $id); return response()->json([ 'success' => true, 'data' => $tag_product ],200); } public function destroy($id) { $this->tag_product->delete($id); return response()->json([ 'success' => true ],200); } } <file_sep><?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use App\Model\User\Role; class RolesServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { $role = Role::all(); if(count($role) <= 0) { $arr = ['admin','sales staff','sales manager','customer']; foreach($arr as $a) { $roles = new Role; $roles->name = $a; $roles->save(); } } } /** * Register the application services. * * @return void */ public function register() { // } } <file_sep><?php namespace App\Http\Controllers\Product; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Http\Repositories\Eloquents\Product\ProductsEloquent; use App\Model\Product\Product; class ProductsController extends Controller { private $product; public function __construct(Product $product) { $this->product = new ProductsEloquent($product); } public function index() { return $this->product->all(); } public function store(Request $request) { $product = $this->product->add($request->only($this->product->getModel()->fillable)); return response()->json([ 'success' => true, 'data' => $product ],201); } public function show($id) { return $this->product->single($id); } public function update(Request $request, $id) { $product = $this->product->change($request->only($this->product->getModel()->fillable), $id); return response()->json([ 'success' => true, 'data' => $product ],200); } public function destroy($id) { $this->product->delete($id); return response()->json([ 'success' => true ],200); } } <file_sep><?php namespace App\Http\Controllers\Sale; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Http\Repositories\Eloquents\Sale\SessionsEloquent; use App\Model\Sale\Session; class SessionsController extends Controller { private $session; public function __construct(Session $session) { $this->session = new SessionsEloquent($session); } public function index() { return $this->session->all(); } public function store(Request $request) { $session = $this->session->add($request->only($this->session->getModel()->fillable)); return response()->json([ 'success' => true, 'data' => $session ],201); } public function show($id) { return $this->session->single($id); } public function update(Request $request, $id) { $session = $this->session->change($request->only($this->session->getModel()->fillable), $id); return response()->json([ 'success' => true, 'data' => $session ],200); } public function destroy($id) { $this->session->delete($id); return response()->json([ 'success' => true ],200); } } <file_sep><?php namespace App\Http\Repositories\Eloquents\Product; use App\Http\Repositories\Interfaces\Product\CategoryProductsInterface; use Illuminate\Database\Eloquent\Model; class CategoryProductsEloquent implements CategoryProductsInterface { // model property on class instances protected $model; // Constructor to bind model to repo public function __construct(Model $model) { $this->model = $model; } public function all() { $category_products = $this->model->all(); return $category_products; } public function single($id) { $category_product = $this->model->find($id); return $category_product; } public function add(array $data) { $category_product = $this->model->create($data); return $category_product; } public function change(array $data,$id) { $category_product = $this->model->find($id); $category_product->update($data); return $category_product; } public function delete($id) { $category_product = $this->model->find($id); $category_product->delete(); } public function getModel() { return $this->model; } public function setModel($model) { $this->model = $model; return $this; } public function with($relations) { return $this->model->with($relations); } }<file_sep><?php namespace App\Model\Sale; use Illuminate\Database\Eloquent\Model; class Session extends Model { protected $table = 'sessions'; protected $fillable = [ 'data' ]; public function sale_order() { return $this->belongsTo(SaleOrder::class); } } <file_sep><?php namespace App\Http\Repositories\Eloquents\Sale; use App\Http\Repositories\Interfaces\Sale\CouponsInterface; use Illuminate\Database\Eloquent\Model; class CouponsEloquent implements CouponsInterface { // model property on class instances protected $model; // Constructor to bind model to repo public function __construct(Model $model) { $this->model = $model; } public function all() { $coupons = $this->model->all(); return $coupons; } public function single($id) { $coupon = $this->model->find($id); return $coupon; } public function add(array $data) { $coupon = $this->model->create($data); return $coupon; } public function change(array $data,$id) { $coupon = $this->model->find($id); $coupon->update($data); return $coupon; } public function delete($id) { $coupon = $this->model->find($id); $coupon->delete(); } public function getModel() { return $this->model; } public function setModel($model) { $this->model = $model; return $this; } public function with($relations) { return $this->model->with($relations); } }<file_sep><?php namespace App\Http\Repositories\Eloquents\User; use App\Http\Repositories\Interfaces\User\RoleUserInterface; use Illuminate\Database\Eloquent\Model; class RoleUserEloquent implements RoleUserInterface { // model property on class instances protected $model; // Constructor to bind model to repo public function __construct(Model $model) { $this->model = $model; } public function all() { $role_users = $this->model->all(); return $role_users; } public function single($id) { $role_user = $this->model->where('user_id',$id)->get(); return $role_user; } public function add(array $data) { $role_user = $this->model->create($data); return $role_user; } public function change(array $data,$id) { $role_user = $this->model->where('user_id',$id)->get(); $role_user->update($data); return $role_user; } public function delete($id) { $role_user = $this->model->where('user_id',$id)->get(); $role_user->delete(); } public function getModel() { return $this->model; } public function setModel($model) { $this->model = $model; return $this; } public function with($relations) { return $this->model->with($relations); } }<file_sep><?php namespace App\Http\Controllers\Sale; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Http\Repositories\Eloquents\Sale\CcTransactionsEloquent; use App\Model\Sale\CcTransaction; class CcTransactionsController extends Controller { private $cc_transaction; public function __construct(CcTransaction $cc_transaction) { $this->cc_transaction = new CcTransactionsEloquent($cc_transaction); } public function index() { return $this->cc_transaction->all(); } public function store(Request $request) { $cc_transaction = $this->cc_transaction->add($request->only($this->cc_transaction->getModel()->fillable)); return response()->json([ 'success' => true, 'data' => $cc_transaction ],201); } public function show($id) { return $this->cc_transaction->single($id); } public function update(Request $request, $id) { $cc_transaction = $this->cc_transaction->change($request->only($this->cc_transaction->getModel()->fillable), $id); return response()->json([ 'success' => true, 'data' => $cc_transaction ],200); } public function destroy($id) { $this->cc_transaction->delete($id); return response()->json([ 'success' => true ],200); } } <file_sep><?php namespace App\Http\Resources\User; use Illuminate\Http\Resources\Json\Resource; class User extends Resource { /** * Transform the resource into an array. * * @param \Illuminate\Http\Request $request * @return array */ public function toArray($request) { // return parent::toArray($request); return [ 'id' => $this->id, 'user' => [ 'id' => $this->user_id, 'email' => $this->user->email, 'first_name' => $this->user->first_name, 'last_name' => $this->user->last_name, 'created_at' => $this->user->created_at->diffForHumans(), 'updated_at' => $this->user->updated_at->diffForHumans() ], 'role' => $this->roles->name, 'permission' => boolval($this->permission->status) ? true : false ]; } } <file_sep><?php namespace App\Model\Sale; use Illuminate\Database\Eloquent\Model; class Coupon extends Model { protected $table = 'coupons'; protected $fillable = [ 'code', 'description', 'value' , 'start_date' , 'end_date' ]; public function sale_order() { return $this->belongsTo(SaleOrder::class); } } <file_sep><?php namespace App\Http\Controllers\User; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Http\Repositories\Eloquents\User\UsersEloquent; use App\Model\User\User; class UsersController extends Controller { private $user; public function __construct(User $user) { $this->user = new UsersEloquent($user); } public function index() { return $this->user->all(); } public function store(Request $request) { $user = $this->user->add($request->only($this->user->getModel()->fillable)); return response()->json([ 'success' => true, 'data' => $user ],201); } public function show($id) { return $this->user->single($id); } public function update(Request $request, $id) { $user = $this->user->change($request->only($this->user->getModel()->fillable), $id); return response()->json([ 'success' => true, 'data' => $user ],200); } public function destroy($id) { $this->user->delete($id); return response()->json([ 'success' => true ],200); } } <file_sep><?php namespace App\Http\Controllers\Sale; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Http\Repositories\Eloquents\Sale\CouponsEloquent; use App\Model\Sale\Coupon; class CouponsController extends Controller { private $coupon; public function __construct(Coupon $coupon) { $this->coupon = new CouponsEloquent($coupon); } public function index() { return $this->coupon->all(); } public function store(Request $request) { $coupon = $this->coupon->add($request->only($this->coupon->getModel()->fillable)); return response()->json([ 'success' => true, 'data' => $coupon ],201); } public function show($id) { return $this->coupon->single($id); } public function update(Request $request, $id) { $coupon = $this->coupon->change($request->only($this->coupon->getModel()->fillable), $id); return response()->json([ 'success' => true, 'data' => $coupon ],200); } public function destroy($id) { $this->coupon->delete($id); return response()->json([ 'success' => true ],200); } } <file_sep><?php namespace App\Http\Controllers\Sale; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Http\Repositories\Eloquents\Sale\SalesOrdersEloquent; use App\Model\Sale\SaleOrder; class SalesOrdersController extends Controller { private $sale_order; public function __construct(SaleOrder $sale_order) { $this->sale_order = new SalesOrdersEloquent($sale_order); } public function index() { return $this->sale_order->all(); } public function store(Request $request) { $sale_order = $this->sale_order->add($request->only($this->sale_order->getModel()->fillable)); return response()->json([ 'success' => true, 'data' => $sale_order ],201); } public function show($id) { return $this->sale_order->single($id); } public function update(Request $request, $id) { $sale_order = $this->sale_order->change($request->only($this->sale_order->getModel()->fillable), $id); return response()->json([ 'success' => true, 'data' => $sale_order ],200); } public function destroy($id) { $this->sale_order->delete($id); return response()->json([ 'success' => true ],200); } } <file_sep><?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use App\Http\Repositories\Eloquents\User\UsersEloquent; use App\Http\Repositories\Interfaces\User\UsersInterface; use App\Http\Repositories\Eloquents\User\RoleUserEloquent; use App\Http\Repositories\Interfaces\User\RoleUserInterface; use App\Http\Repositories\Eloquents\Product\CategoriesEloquent; use App\Http\Repositories\Interfaces\Product\CategoriesInterface; use App\Http\Repositories\Eloquents\Product\TagsEloquent; use App\Http\Repositories\Interfaces\Product\TagsInterface; use App\Http\Repositories\Eloquents\Product\ProductStatusesEloquent; use App\Http\Repositories\Interfaces\Product\ProductStatusesInterface; use App\Http\Repositories\Eloquents\Product\ProductsEloquent; use App\Http\Repositories\Interfaces\Product\ProductsInterface; use App\Http\Repositories\Eloquents\Product\CategoryProductsEloquent; use App\Http\Repositories\Interfaces\Product\CategoryProductsInterface; use App\Http\Repositories\Eloquents\Product\ProductTagsEloquent; use App\Http\Repositories\Interfaces\Product\ProductTagsInterface; use App\Http\Repositories\Eloquents\Sale\SessionsEloquent; use App\Http\Repositories\Interfaces\Sale\SessionsInterface; use App\Http\Repositories\Eloquents\Sale\CouponsEloquent; use App\Http\Repositories\Interfaces\Sale\CouponsInterface; use App\Http\Repositories\Eloquents\Sale\SalesOrdersEloquent; use App\Http\Repositories\Interfaces\Sale\SalesOrdersInterface; use App\Http\Repositories\Eloquents\Sale\OrderProductsEloquent; use App\Http\Repositories\Interfaces\Sale\OrderProductsInterface; use App\Http\Repositories\Eloquents\Sale\CcTransactionsEloquent; use App\Http\Repositories\Interfaces\Sale\CcTransactionsInterface; class RepoServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { $this->app->singleton(UsersInterface::class,UsersEloquent::class); $this->app->singleton(RoleUserInterface::class,RoleUserEloquent::class); $this->app->singleton(CategoriesInterface::class,CategoriesEloquent::class); $this->app->singleton(TagsInterface::class,TagsEloquent::class); $this->app->singleton(ProductStatusesInterface::class,ProductStatusesEloquent::class); $this->app->singleton(ProductsInterface::class,ProductsEloquent::class); $this->app->singleton(CategoryProductsInterface::class,CategoryProductsEloquent::class); $this->app->singleton(ProductTagsInterface::class,ProductTagsEloquent::class); $this->app->singleton(SessionsInterface::class,SessionsEloquent::class); $this->app->singleton(CouponsInterface::class,CouponsEloquent::class); $this->app->singleton(SalesOrdersInterface::class,SalesOrdersEloquent::class); $this->app->singleton(OrderProductsInterface::class,OrderProductsEloquent::class); $this->app->singleton(CcTransactionsInterface::class,CcTransactionsEloquent::class); } } <file_sep><?php namespace App\Http\Controllers\Sale; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Http\Repositories\Eloquents\Sale\OrderProductsEloquent; use App\Model\Sale\OrderProduct; class OrderProductsController extends Controller { private $order_product; public function __construct(OrderProduct $order_product) { $this->order_product = new OrderProductsEloquent($order_product); } public function index() { return $this->order_product->all(); } public function store(Request $request) { $order_product = $this->order_product->add($request->only($this->order_product->getModel()->fillable)); return response()->json([ 'success' => true, 'data' => $order_product ],201); } public function show($id) { return $this->order_product->single($id); } public function update(Request $request, $id) { $order_product = $this->order_product->change($request->only($this->order_product->getModel()->fillable), $id); return response()->json([ 'success' => true, 'data' => $order_product ],200); } public function destroy($id) { $this->order_product->delete($id); return response()->json([ 'success' => true ],200); } } <file_sep><?php namespace App\Model\Sale; use Illuminate\Database\Eloquent\Model; class OrderProduct extends Model { protected $table = 'order_products'; protected $fillable = [ 'order_id', 'sku', 'name', 'description', 'price', 'quantity', 'subtotal' ]; } <file_sep><?php namespace App\Model\Sale; use Illuminate\Database\Eloquent\Model; class CcTransaction extends Model { protected $table = 'cc_transactions'; protected $fillable = [ 'code', 'order_id', 'transdate', 'processor', 'processor_trans_id', 'amount', 'cc_num', 'cc_type', 'response' ]; } <file_sep><?php use App\Model\User\User; /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It is a breeze. Simply tell Lumen the URIs it should respond to | and give it the Closure to call when that URI is requested. | */ $router->get('/', function () use ($router) { return User::all(); }); //User Route $router->get('users','User\UsersController@index'); $router->get('user/{id}','User\UsersController@show'); $router->post('user','User\UsersController@store'); $router->put('user/{id}','User\UsersController@update'); $router->delete('user/{id}','User\UsersController@destroy'); $router->group(['prefix'=>'role'],function () use ($router) { //User Route $router->post('users','User\RoleUserController@index'); $router->get('user/{id}','User\RoleUserController@show'); $router->post('user','User\RoleUserController@store'); $router->put('user/{id}','User\RoleUserController@update'); $router->delete('user/{id}','User\RoleUserController@destroy'); }); //Category Route $router->get('categories','Product\CategoriesController@index'); $router->get('category/{id}','Product\CategoriesController@show'); $router->post('category','Product\CategoriesController@store'); $router->put('category/{id}','Product\CategoriesController@update'); $router->delete('category/{id}','Product\CategoriesController@destroy'); //Tag Route $router->get('tags','Product\TagsController@index'); $router->get('tag/{id}','Product\TagsController@show'); $router->post('tag','Product\TagsController@store'); $router->put('tag/{id}','Product\TagsController@update'); $router->delete('tag/{id}','Product\TagsController@destroy'); //Product Route $router->group(['prefix'=>'product'],function () use ($router) { //Product Status Route $router->get('statuses','Product\ProductStatusesController@index'); $router->get('status/{id}','Product\ProductStatusesController@show'); $router->post('status','Product\ProductStatusesController@store'); $router->put('status/{id}','Product\ProductStatusesController@update'); $router->delete('status/{id}','Product\ProductStatusesController@destroy'); //Category Product Status Route $router->get('categories','Product\CategoryProductsController@index'); $router->get('category/{id}','Product\CategoryProductsController@show'); $router->post('category','Product\CategoryProductsController@store'); $router->put('category/{id}','Product\CategoryProductsController@update'); $router->delete('category/{id}','Product\CategoryProductsController@destroy'); //Tag Product Status Route $router->get('tags','Product\ProductTagsController@index'); $router->get('tag/{id}','Product\ProductTagsController@show'); $router->post('tag','Product\ProductTagsController@store'); $router->put('tag/{id}','Product\ProductTagsController@update'); $router->delete('tag/{id}','Product\ProductTagsController@destroy'); }); //Product Status Route $router->get('products','Product\ProductsController@index'); $router->get('product/{id}','Product\ProductsController@show'); $router->post('product','Product\ProductsController@store'); $router->put('product/{id}','Product\ProductsController@update'); $router->delete('product/{id}','Product\ProductsController@destroy'); //Session Route $router->get('sessions','Sale\SessionsController@index'); $router->get('session/{id}','Sale\SessionsController@show'); $router->post('session','Sale\SessionsController@store'); $router->put('session/{id}','Sale\SessionsController@update'); $router->delete('session/{id}','Sale\SessionsController@destroy'); //Coupon Route $router->get('coupons','Sale\CouponsController@index'); $router->get('coupon/{id}','Sale\CouponsController@show'); $router->post('coupon','Sale\CouponsController@store'); $router->put('coupon/{id}','Sale\CouponsController@update'); $router->delete('coupon/{id}','Sale\CouponsController@destroy'); //Sale Route $router->group(['prefix'=>'sales'],function () use ($router) { // Sales Order $router->get('orders','Sale\SalesOrdersController@index'); $router->get('order/{id}','Sale\SalesOrdersController@show'); $router->post('order','Sale\SalesOrdersController@store'); $router->put('order/{id}','Sale\SalesOrdersController@update'); $router->delete('order/{id}','Sale\SalesOrdersController@destroy'); }); //Order Route $router->group(['prefix'=>'order'],function () use ($router) { // Product Route $router->get('products','Sale\OrderProductsController@index'); $router->get('product/{id}','Sale\OrderProductsController@show'); $router->post('product','Sale\OrderProductsController@store'); $router->put('product/{id}','Sale\OrderProductsController@update'); $router->delete('product/{id}','Sale\OrderProductsController@destroy'); }); //CC Route $router->group(['prefix'=>'cc'],function () use ($router) { // Transaction Route $router->get('transactions','Sale\CcTransactionsController@index'); $router->get('transaction/{id}','Sale\CcTransactionsController@show'); $router->post('transaction','Sale\CcTransactionsController@store'); $router->put('transaction/{id}','Sale\CcTransactionsController@update'); $router->delete('transaction/{id}','Sale\CcTransactionsController@destroy'); }); <file_sep><?php namespace App\Http\Repositories\Interfaces\User; interface RoleUserInterface { public function all(); public function single($id); public function add(array $data); public function change(array $data,$id); public function delete($id); } <file_sep><?php namespace App\Model\Sale; use Illuminate\Database\Eloquent\Model; use App\Model\User\User; class SaleOrder extends Model { protected $table = "sales_orders"; protected $fillable = [ 'order_date', 'total', 'coupon_id', 'session_id', 'user_id' ]; public function sessions() { return $this->hasMany(Session::class); } public function coupons() { return $this->hasMany(Coupon::class); } public function users() { return $this->hasMany(User::class); } } <file_sep><?php namespace App\Http\Controllers\Product; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Http\Repositories\Eloquents\Product\CategoryProductsEloquent; use App\Model\Product\CategoryProduct; use App\Model\Product\Product; class CategoryProductsController extends Controller { private $category_product; private $product; public function __construct(CategoryProduct $category_product,Product $product) { $this->category_product = new CategoryProductsEloquent($category_product); $this->product = new CategoryProductsEloquent($product); } public function index() { $products = $this->product->all(); foreach($products as $product) { return response()->json([ 'data' => $product->category ],200); } } public function store(Request $request) { $category_product = $this->category_product->add($request->only($this->category_product->getModel()->fillable)); return response()->json([ 'success' => true, 'data' => $category_product ],201); } public function show($id) { return $this->category_product->single($id); } public function update(Request $request, $id) { $category_product = $this->category_product->change($request->only($this->category_product->getModel()->fillable), $id); return response()->json([ 'success' => true, 'data' => $category_product ],200); } public function destroy($id) { $this->category_product->delete($id); return response()->json([ 'success' => true ],200); } } <file_sep><?php namespace App\Http\Controllers\Product; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Http\Repositories\Eloquents\Product\ProductStatusesEloquent; use App\Model\Product\ProductStatus; class ProductStatusesController extends Controller { private $product_status; public function __construct(ProductStatus $product_status) { $this->product_status = new ProductStatusesEloquent($product_status); } public function index() { return $this->product_status->all(); } public function store(Request $request) { $product_status = $this->product_status->add($request->only($this->product_status->getModel()->fillable)); return response()->json([ 'success' => true, 'data' => $product_status ],201); } public function show($id) { return $this->product_status->single($id); } public function update(Request $request, $id) { $product_status = $this->product_status->change($request->only($this->product_status->getModel()->fillable), $id); return response()->json([ 'success' => true, 'data' => $product_status ],200); } public function destroy($id) { $this->product_status->delete($id); return response()->json([ 'success' => true ],200); } } <file_sep><?php namespace App\Http\Controllers\Product; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Http\Repositories\Eloquents\Product\TagsEloquent; use App\Model\Product\Tag; class TagsController extends Controller { private $tag; public function __construct(Tag $tag) { $this->tag = new TagsEloquent($tag); } public function index() { return $this->tag->all(); } public function store(Request $request) { $tag = $this->tag->add($request->only($this->tag->getModel()->fillable)); return response()->json([ 'success' => true, 'data' => $tag ],201); } public function show($id) { return $this->tag->single($id); } public function update(Request $request, $id) { $tag = $this->tag->change($request->only($this->tag->getModel()->fillable), $id); return response()->json([ 'success' => true, 'data' => $tag ],200); } public function destroy($id) { $this->tag->delete($id); return response()->json([ 'success' => true ],200); } } <file_sep><?php namespace App\Model\Product; use Illuminate\Database\Eloquent\Model; class Product extends Model { protected $table = 'products'; protected $fillable = [ 'sku', 'name', 'description','product_status_id', 'regular_price', 'discount_price', 'quantity','taxable' ]; public function category() { return $this->belongsToMany(Category::class); } public function tag() { return $this->belongsToMany(Tag::class); } }
f388e2d25a12949b83892a2cb64168739ef04d43
[ "Markdown", "PHP" ]
28
PHP
janreyferil/janrey-eCommerce
e6c68cb691b3512a6124481ed386bda339997740
44394918cfc5f28b6c826b16d58e0ceb423520d7
refs/heads/master
<repo_name>mei28/resort_cancel<file_sep>/test.py # %% from utils import load_datasets, load_target import argparse import json # %% parser = argparse.ArgumentParser() parser.add_argument('--config', default='./configs/default.json') options = parser.parse_args() config = json.load(open(options.config)) # %% feats = config['features'] _, X_test = load_datasets(feats) # %% print(X_test.shape) <file_sep>/notebooks/eda.py # %% from utils import load_datasets, load_target import pandas as pd import matplotlib.pyplot as plt import pandas_profiling as pdp # %% train = pd.read_csv('../data/input/train.csv') test = pd.read_csv('../data/input/test.csv') # %% print(train.head()) print(train.info()) print(train.isnull().sum()) print(train.head(5)) # %% print(train.columns) print(train.shape) # %% print(test.head()) print(test.info()) print(test.isnull().sum()) # %% print(test.columns) print(test.shape) # %% train_profile = pdp.ProfileReport(train) # %% train_profile.to_file("../features/importances/train_profile.html") # %% print(train['previous_cancellations'].describe()) # %% print(test.shape) # %% <file_sep>/requirements.txt # local package -e . # external requirements click pandas numpy matplotlib scikit-learn seaborn jupyter flake8 autopep8 pyarrow ipykernel wheel<file_sep>/models/lgbm.py # %% import lightgbm as lgb import logging from logs.logger import log_evaluation import matplotlib.pyplot as plt def train_and_predict(X_train, X_valid, y_train, y_valid, X_test, lgbm_params): # データセットの作成 lgb_train = lgb.Dataset(X_train, y_train) lgb_eval = lgb.Dataset(X_valid, y_valid, reference=lgb_train) logging.debug(lgbm_params) # ロガーの作成 logger = logging.getLogger('main') callbacks = [log_evaluation(logger, period=30)] model = lgb.train( params=lgbm_params, train_set=lgb_train, valid_sets=lgb_eval, num_boost_round=8000, early_stopping_rounds=10, callbacks=callbacks ) y_pred = model.predict(X_test, num_iteration=model.best_iteration) lgb.plot_importance(model, importance_type="gain", max_num_features=30, figsize=(12, 6)) # plt.show() return y_pred, model <file_sep>/features/create.py import pandas as pd import numpy as np import re as re from base import Feature, get_arguments, generate_features Feature.dir = 'features' # """sample usage # """ # class Pclass(Feature): # def create_features(self): # self.train['Pclass'] = train['Pclass'] # self.test['Pclass'] = test['Pclass'] class Hotel(Feature): def create_features(self): hotels = {"City Hotel": 1, "Resort Hotel": 0} self.train['hotel'] = train['hotel'].map(hotels) self.test['hotel'] = test['hotel'].map(hotels) class Lead_time(Feature): def create_features(self): self.train['lead_time'] = train['lead_time'] self.test['lead_time'] = test['lead_time'] class Stays_in_weekend_nights(Feature): def create_features(self): self.train['stays_in_weekend_nights'] = train['stays_in_weekend_nights'] self.test['stays_in_weekend_nights'] = test['stays_in_weekend_nights'] class Stays_in_week_nights(Feature): def create_features(self): self.train['stays_in_week_nights'] = train['stays_in_week_nights'] self.test['stays_in_week_nights'] = test['stays_in_week_nights'] class Stays_in_weekend_nights(Feature): def create_features(self): self.train['stays_in_weekend_nights'] = train['stays_in_weekend_nights'] self.test['stays_in_weekend_nights'] = test['stays_in_weekend_nights'] class Adults(Feature): def create_features(self): self.train['adults'] = train['adults'] self.test['adults'] = test['adults'] class Children(Feature): def create_features(self): self.train['children'] = train['children'] self.test['children'] = test['children'] class Babies(Feature): def create_features(self): self.train['babies'] = train['babies'] self.test['babies'] = test['babies'] class Family_size(Feature): def create_features(self): self.train['family_size'] = train['adults'] + \ train['children']+train['babies'] self.test['family_size'] = test['adults'] + \ test['children']+test['babies'] class Meal(Feature): def create_features(self): Meals = {"BB": 0, "HB": 1, "SC": 2, "FB": 3} self.train['meal'] = train['meal'].map(Meals) self.test['meal'] = test['meal'].map(Meals) class Country(Feature): def create_features(self): from sklearn.preprocessing import LabelEncoder le = LabelEncoder() col = 'country' le.fit(pd.concat([train[col], test[col]])) self.train['country'] = le.transform(train[col]) self.test['country'] = le.transform(test[col]) class Market_segment(Feature): def create_features(self): from sklearn.preprocessing import LabelEncoder le = LabelEncoder() col = 'market_segment' le.fit(pd.concat([train[col], test[col]])) self.train[col] = le.transform(train[col]) self.test[col] = le.transform(test[col]) class Distribution_channel(Feature): def create_features(self): from sklearn.preprocessing import LabelEncoder le = LabelEncoder() col = 'distribution_channel' le.fit(pd.concat([train[col], test[col]])) self.train['country'] = le.transform(train[col]) self.test['country'] = le.transform(test[col]) class Is_repeated_guest(Feature): def create_features(self): self.train['is_repeated'] = train['is_repeated_guest'] self.test['is_repeated'] = test['is_repeated_guest'] class Previous_cancellations(Feature): def create_features(self): self.train['pre_cancell'] = train['previous_cancellations'] self.test['pre_cancell'] = test['previous_cancellations'] class Previous_bookings_not_canceled(Feature): def create_features(self): self.train['pre_book_not_cancell'] = train['previous_bookings_not_canceled'] self.test['pre_book_not_cancell'] = test['previous_bookings_not_canceled'] class Reserved_room_type(Feature): def create_features(self): from sklearn.preprocessing import LabelEncoder le = LabelEncoder() col = 'reserved_room_type' le.fit(pd.concat([train[col], test[col]])) self.train[col] = le.transform(train[col]) self.test[col] = le.transform(test[col]) class Assigned_room_type(Feature): def create_features(self): from sklearn.preprocessing import LabelEncoder le = LabelEncoder() col = 'assigned_room_type' le.fit(pd.concat([train[col], test[col]])) self.train[col] = le.transform(train[col]) self.test[col] = le.transform(test[col]) class Booking_changes(Feature): def create_features(self): self.train['booking_changes'] = train['booking_changes'] self.test['booking_changes'] = test['booking_changes'] class Agent(Feature): def create_features(self): self.train['agent'] = train['agent'] self.test['agent'] = test['agent'] class Company(Feature): def create_features(self): self.train['company'] = train['company'] self.test['company'] = test['company'] class Day_in_waiting_list(Feature): def create_features(self): self.train['days_in_waiting_list'] = train['days_in_waiting_list'] self.test['days_in_waiting_list'] = test['days_in_waiting_list'] class Customer_type(Feature): def create_features(self): from sklearn.preprocessing import LabelEncoder le = LabelEncoder() col = 'customer_type' le.fit(pd.concat([train[col], test[col]])) self.train[col] = le.transform(train[col]) self.test[col] = le.transform(test[col]) class Adr(Feature): def create_features(self): self.train['adr'] = train['adr'] self.test['adr'] = test['adr'] class Required_car_parking_spaces(Feature): def create_features(self): self.train['required_car_parking_spaces'] = train['required_car_parking_spaces'] self.test['required_car_parking_spaces'] = test['required_car_parking_spaces'] class Total_of_special_requests(Feature): def create_features(self): self.train['total_of_special_requests'] = train['total_of_special_requests'] self.test['total_of_special_requests'] = test['total_of_special_requests'] if __name__ == '__main__': args = get_arguments() # train = pd.read_feather('./data/input/train.feather') # test = pd.read_feather('./data/input/test.feather') train = pd.read_feather('./data/input/train.feather') test = pd.read_feather('./data/input/test.feather') generate_features(globals(), args.force)
fac8f6bba5f74146ede58e9db5aa2472c48b9415
[ "Python", "Text" ]
5
Python
mei28/resort_cancel
e0e6c3ea9e9a6278463ee4add420bc73c1e20b79
abd3a88a6ca83a011a5c3e45e97e1398b35343df
refs/heads/master
<repo_name>YuxiangQue/smart_home_app<file_sep>/main.cpp #include <QApplication> #include <QQmlApplicationEngine> int main(int argc, char *argv[]) { QApplication app(argc, argv); app.setOrganizationName("Smart Home"); app.setOrganizationDomain("localhost"); app.setApplicationName("Southeast University"); QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec(); }
9282a5b644db4dbd202448a78ecf01da55411d7d
[ "C++" ]
1
C++
YuxiangQue/smart_home_app
211b30ed3f3536af3983e58330242eb07529fcd1
8844181297b89686e56c7e4349e74c5799d62503
refs/heads/master
<repo_name>surendrakoritalanewsignature/FunctionApp-managedidentity-sample10<file_sep>/README.md # FunctionApp-managedidentity-sample10 Blob Trigger Function App <br /> Step #1: <br /> Add local.settings.json -> <br /> { "IsEncrypted": false, <br /> "Values": { "AzureWebJobsStorage": "UseDevelopmentStorage=true", <br /> "FUNCTIONS_WORKER_RUNTIME": "dotnet", <br /> "StorageConnection": "", // Enter azure storage connection string <br /> "SubscriptionID": "", // Enter subscription id of datafactory <br /> "ResourceGroup": "", // Enter resourcegroup of datafactory <br /> "DataFactoryName": "", // Enter datafactory name <br /> "PipelineName": "" // Enter pipeline, which you want to trigger <br /> } <br /> } <br /> <br /> Step #2: Start debugging using F5 <br /> <file_sep>/FunctionApp-managedidentity-sample10/BlobTriggerFunction.cs using System; using System.Configuration; using System.IO; using System.Threading.Tasks; using Microsoft.Azure.Management.DataFactory; using Microsoft.Azure.Services.AppAuthentication; using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Logging; using Microsoft.Rest; namespace FunctionApp_managedidentity_sample10 { public class BlobTriggerFunction { private string subscriptionId; private string resourceGroup; private string dataFactoryName; private string pipelineName; public BlobTriggerFunction() { subscriptionId = Environment.GetEnvironmentVariable("SubscriptionID", EnvironmentVariableTarget.Process); resourceGroup = Environment.GetEnvironmentVariable("ResourceGroup", EnvironmentVariableTarget.Process); dataFactoryName = Environment.GetEnvironmentVariable("DataFactoryName", EnvironmentVariableTarget.Process); pipelineName = Environment.GetEnvironmentVariable("PipelineName", EnvironmentVariableTarget.Process); } [FunctionName("BlobTriggerFunction")] public async Task RunAsync([BlobTrigger("files/{name}", Connection = "StorageConnection")]Stream myBlob, string name, ILogger log) { log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes"); //Specifing the application //var azureServiceTokenProvider = new AzureServiceTokenProvider($"RunAs=App;AppId=your_app_id"); //to run locally on your Vs instance // var azureServiceTokenProvider = new AzureServiceTokenProvider($"RunAs=Developer; DeveloperTool=VisualStudio"); var azureServiceTokenProvider = new AzureServiceTokenProvider(); var accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/").ConfigureAwait(false); ServiceClientCredentials cred = new TokenCredentials(accessToken); var myDataFactoryClient = new DataFactoryManagementClient(cred) { SubscriptionId = subscriptionId }; var dataFactoryRequestResult = myDataFactoryClient.Pipelines.CreateRunWithHttpMessagesAsync(resourceGroup, dataFactoryName, pipelineName).Result; } } }
955f45b73d090bd9d12b28d9ef8ce8badbee3ba9
[ "Markdown", "C#" ]
2
Markdown
surendrakoritalanewsignature/FunctionApp-managedidentity-sample10
13b6e253d5635338636792afc6664584e846b58b
8769dbbad9f8a1fdfbf376decbadd872c2c44da7
refs/heads/master
<repo_name>jakub-sieradzki/RepeatsJava<file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/ZipSet.java package com.rootekstudio.repeatsandroid; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; public class ZipSet { public static void zip(List<String> files, OutputStream outputStream) { BufferedInputStream origin = null; try { ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(outputStream)); byte data[] = new byte[1024]; for (int i = 0; i < files.size(); i++) { String file = files.get(i); FileInputStream fi = new FileInputStream(file); origin = new BufferedInputStream(fi, 1024); ZipEntry entry = new ZipEntry(file.substring(file.lastIndexOf("/")).replace("/", "")); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, 1024)) != -1) { out.write(data, 0, count); } } origin.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void UnZip(InputStream Zip, File directory) { try { ZipInputStream zis = new ZipInputStream(Zip); ZipEntry ze; while ((ze = zis.getNextEntry()) != null) { FileOutputStream fos = new FileOutputStream(directory + "/" + ze.getName()); BufferedInputStream inputStream = new BufferedInputStream(zis); BufferedOutputStream outputStream = new BufferedOutputStream(fos, 1024); byte data[] = new byte[1024]; int count; while ((count = inputStream.read(data, 0, 1024)) != -1) { outputStream.write(data, 0, count); } zis.closeEntry(); outputStream.flush(); outputStream.close(); fos.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/community/PreviewAndDownloadSetActivity.java package com.rootekstudio.repeatsandroid.community; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.button.MaterialButton; import com.google.firebase.firestore.FirebaseFirestore; import com.rootekstudio.repeatsandroid.R; import com.rootekstudio.repeatsandroid.SetsConfigHelper; import com.rootekstudio.repeatsandroid.UIHelper; import com.rootekstudio.repeatsandroid.database.RepeatsDatabase; import com.rootekstudio.repeatsandroid.mainpage.MainActivity; import java.util.ArrayList; import java.util.HashMap; import java.util.Objects; public class PreviewAndDownloadSetActivity extends AppCompatActivity { HashMap<Integer, String[]> setItems; String setName; String databaseSetID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); UIHelper.DarkTheme(this, false); setContentView(R.layout.activity_preview_and_download_set); getSupportActionBar().setDisplayHomeAsUpEnabled(true); TextView elementsCountTextView = findViewById(R.id.textViewElementsCountRC); TextView shareDateTextView = findViewById(R.id.textViewShareDateRC); RecyclerView recyclerView = findViewById(R.id.recyclerViewDownloadSet); recyclerView.setHasFixedSize(true); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL)); Intent intent = getIntent(); databaseSetID = intent.getStringExtra("databaseSetID"); if (databaseSetID != null) { FirebaseFirestore db = FirebaseFirestore.getInstance(); db.collection("sets").document(databaseSetID) .get() .addOnCompleteListener(task -> { if (task.isSuccessful()) { if (task.getResult().exists()) { ArrayList<?> questions = (ArrayList<?>) task.getResult().get("questions"); ArrayList<?> answers = (ArrayList<?>) task.getResult().get("answers"); setItems = new HashMap<>(); for (int i = 0; i < questions.size(); i++) { setItems.put(i, new String[] {questions.get(i).toString(), answers.get(i).toString()}); } setName = task.getResult().get("displayName").toString(); recyclerView.setAdapter(new PreviewAdapter(setItems)); findViewById(R.id.downloadSetButton).setEnabled(true); TextView textView = findViewById(R.id.setNamePreview); textView.setText(setName); String elementsString = setItems.size() + " " + getText(R.string.items).toString(); elementsCountTextView.setText(elementsString); String shareDateString = getText(R.string.shareDate) + " " + task.getResult().get("creationDate").toString(); shareDateTextView.setText(shareDateString); } } else { Log.d("tag", "Error getting documents: ", task.getException()); } }); } else { setItems = SetData.getSetItems(); setName = SetData.getSetName(); recyclerView.setAdapter(new PreviewAdapter(setItems)); TextView textView = findViewById(R.id.setNamePreview); textView.setText(setName); String elementsString = setItems.size() + " " + getText(R.string.items).toString(); elementsCountTextView.setText(elementsString); String shareDateString = getText(R.string.shareDate) + " " + SetData.getSetCreationDate(); shareDateTextView.setText(shareDateString); findViewById(R.id.downloadSetButton).setEnabled(true); } } public void downloadSet(View view) { MaterialButton button = (MaterialButton) view; button.setEnabled(false); String id = new SetsConfigHelper(this).createNewSet(false, setName); HashMap<Integer, String[]> set = setItems; ArrayList<String> questions = new ArrayList<>(); ArrayList<String> answers = new ArrayList<>(); for(int i = 1; i < set.size(); i++) { questions.add(Objects.requireNonNull(set.get(i))[0]); answers.add(Objects.requireNonNull(set.get(i))[1]); } RepeatsDatabase.getInstance(this).insertSetToDatabase(id, questions, answers, null); Toast.makeText(this, R.string.successDownload, Toast.LENGTH_SHORT).show(); if (databaseSetID != null) { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } else { finish(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); } return true; } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/notifications/UserReply.java package com.rootekstudio.repeatsandroid.notifications; import android.app.RemoteInput; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import com.rootekstudio.repeatsandroid.CheckAnswer; import com.rootekstudio.repeatsandroid.R; import com.rootekstudio.repeatsandroid.database.RepeatsDatabase; import com.rootekstudio.repeatsandroid.database.Values; public class UserReply extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String UserAnswer = getMessageText(intent).toString(); String setID = intent.getStringExtra("setID"); int itemID = intent.getIntExtra("itemID", -1); String setsIDs = intent.getStringExtra("setsIDs"); String Correct = intent.getStringExtra("Correct"); String ReallyCorrect = Correct; int IgnoreChars = intent.getIntExtra("IgnoreChars", 0); boolean ignoreChars = false; if(IgnoreChars == 1) { ignoreChars = true; } RepeatsDatabase DB = RepeatsDatabase.getInstance(context); boolean check = CheckAnswer.isAnswerCorrect(UserAnswer, Correct, ignoreChars); if (check) { if (ReallyCorrect.contains("\n")) { ReallyCorrect = ReallyCorrect.replace("\r\n", ", "); RepeatsNotificationTemplate.AnswerNotifi(context, context.getString(R.string.CorrectAnswer1), context.getString(R.string.CorrectAnswer2) + "\n" + context.getString(R.string.allCorrectAnswers) + " " + ReallyCorrect, setsIDs); } else { RepeatsNotificationTemplate.AnswerNotifi(context, context.getString(R.string.CorrectAnswer1), context.getString(R.string.CorrectAnswer2), setsIDs); } new Thread(() -> { DB.increaseValueInSet(setID, itemID, Values.good_answers, 1); DB.increaseValueInSetsInfo(setID, Values.good_answers, 1); }).start(); } else { if(ReallyCorrect.contains("\n")) { ReallyCorrect = ReallyCorrect.replace("\r\n", ", "); RepeatsNotificationTemplate.AnswerNotifi(context, context.getString(R.string.IncorrectAnswer1), context.getString(R.string.correct_answers) + " " + ReallyCorrect, setsIDs); } else { RepeatsNotificationTemplate.AnswerNotifi(context, context.getString(R.string.IncorrectAnswer1), context.getString(R.string.IncorrectAnswer2) + " " + ReallyCorrect, setsIDs); } new Thread(() -> { DB.increaseValueInSet(setID, itemID, Values.wrong_answers, 1); DB.increaseValueInSetsInfo(setID, Values.wrong_answers, 1); }).start(); } } private CharSequence getMessageText(Intent intent) { Bundle remoteInput = RemoteInput.getResultsFromIntent(intent); if (remoteInput != null) { return remoteInput.getCharSequence("UsersAnswer"); } return null; } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/database/SaveSharedLegacy.java package com.rootekstudio.repeatsandroid.database; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import com.rootekstudio.repeatsandroid.SetsConfigHelper; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; public class SaveSharedLegacy { private Context context; private RepeatsDatabase DB; String ID; public String setName; SaveSharedLegacy(Context context, RepeatsDatabase DB) { this.context = context; this.DB = DB; saveSharedLegacy(); } private void saveSharedLegacy() { final File dir = new File(context.getFilesDir(), "shared"); File questions = new File(dir, "Questions.txt"); File answers = new File(dir, "Answers.txt"); String name = ""; try { FileInputStream questionStream = new FileInputStream(questions); FileInputStream answerStream = new FileInputStream(answers); BufferedReader Qreader = new BufferedReader(new InputStreamReader(questionStream)); BufferedReader Areader = new BufferedReader(new InputStreamReader(answerStream)); String lineQ = Qreader.readLine(); name = lineQ; setName = name; String lineA = Areader.readLine(); lineQ = Qreader.readLine(); lineA = Areader.readLine(); int i = 0; int itemIndex = 0; ID = new SetsConfigHelper(context).createNewSet(false, name); while (lineQ != null) { final File image = new File(dir, "S" + i + ".png"); if (image.exists()) { String imageID = "I" + ID; imageID = imageID + itemIndex + ".png"; FileInputStream inputStream = new FileInputStream(image); Bitmap bitmap = BitmapFactory.decodeStream(inputStream); File control = new File(context.getFilesDir(), imageID); boolean bool = control.createNewFile(); FileOutputStream out = new FileOutputStream(control); bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); DB.addItemToSetWithValues(ID, lineQ, lineA, imageID); } else { DB.addItemToSetWithValues(ID, lineQ, lineA, ""); } lineQ = Qreader.readLine(); lineA = Areader.readLine(); i++; itemIndex++; } } catch (IOException e) { e.printStackTrace(); } } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/community/SetData.java package com.rootekstudio.repeatsandroid.community; import java.util.HashMap; class SetData { private static HashMap<Integer, String[]> setItems; private static String setName; private static String setCreationDate; static HashMap<Integer, String[]> getSetItems() { return setItems; } static String getSetName() { return setName; } static String getSetCreationDate() { return setCreationDate; } static void setSetItems(HashMap<Integer, String[]> setItems) { SetData.setItems = setItems; } static void setSetName(String setName) { SetData.setName = setName; } static void setSetCreationDate(String setCreationDate) { SetData.setCreationDate = setCreationDate; } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/notifications/RepeatsNotificationTemplate.java package com.rootekstudio.repeatsandroid.notifications; import android.app.Notification; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Build; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import androidx.core.app.RemoteInput; import com.rootekstudio.repeatsandroid.R; import com.rootekstudio.repeatsandroid.RequestCodes; import com.rootekstudio.repeatsandroid.database.GetQuestion; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; public class RepeatsNotificationTemplate { public static void questionNotification(Context context, GetQuestion getQuestion, String setsIDs, boolean isNext) { NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, "RepeatsSendQuestionChannel"); notificationBuilder.setDefaults(Notification.DEFAULT_ALL); notificationBuilder.setPriority(NotificationCompat.PRIORITY_HIGH); notificationBuilder .setSmallIcon(R.drawable.ic_notifi_icon) .setContentTitle(getQuestion.getSetName()) .setContentText(getQuestion.getQuestion()) .setStyle(new NotificationCompat.BigTextStyle() .bigText(getQuestion.getQuestion())) .setColor(context.getResources().getColor(R.color.colorAccent)) .setColorized(true) .setAutoCancel(true) .setOnlyAlertOnce(isNext); if (!getQuestion.getPictureName().equals("")) { File file = new File(context.getFilesDir(), getQuestion.getPictureName()); FileInputStream inputStream = null; try { inputStream = new FileInputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); } Bitmap bitmap = BitmapFactory.decodeStream(inputStream); notificationBuilder.setStyle(new NotificationCompat.BigPictureStyle() .bigPicture(bitmap)); } Intent answerActivity = new Intent(context, AnswerActivity.class); answerActivity.putExtra("Title", getQuestion.getSetName()); answerActivity.putExtra("Question", getQuestion.getQuestion()); answerActivity.putExtra("Correct", getQuestion.getAnswer()); answerActivity.putExtra("Image", getQuestion.getPictureName()); answerActivity.putExtra("IgnoreChars", getQuestion.getIgnoreChars()); answerActivity.putExtra("setID", getQuestion.getSetID()); answerActivity.putExtra("setsIDs", setsIDs); answerActivity.putExtra("itemID", getQuestion.getItemID()); PendingIntent notificationClickPendingIntent = PendingIntent.getActivity(context, RequestCodes.PENDING_INTENT_QUESTION_NOTIFICATION_CLICK_REQUEST_CODE, answerActivity, PendingIntent.FLAG_CANCEL_CURRENT); notificationBuilder.setContentIntent(notificationClickPendingIntent); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { String replyLabel = context.getString(R.string.ReplyText); RemoteInput remoteInput = new RemoteInput.Builder("UsersAnswer") .setLabel(replyLabel) .build(); Intent userReplyIntent = new Intent(context, UserReply.class); userReplyIntent.putExtra("Correct", getQuestion.getAnswer()); userReplyIntent.putExtra("IgnoreChars", getQuestion.getIgnoreChars()); userReplyIntent.putExtra("setID", getQuestion.getSetID()); userReplyIntent.putExtra("setsIDs", setsIDs); userReplyIntent.putExtra("itemID", getQuestion.getItemID()); PendingIntent replyPendingIntent = PendingIntent.getBroadcast(context, RequestCodes.PENDING_INTENT_USER_REPLY_REQUEST_CODE, userReplyIntent, PendingIntent.FLAG_CANCEL_CURRENT); NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.drawable.ic_notifi_icon, context.getString(R.string.Reply), replyPendingIntent) .addRemoteInput(remoteInput) .build(); notificationBuilder.addAction(action); } NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); notificationManager.notify(RequestCodes.QUESTION_NOTIFICATION_ID, notificationBuilder.build()); } public static void AnswerNotifi(Context context, String Title, String Text, String setsIDs) { Intent nextQuestionIntent = new Intent(context, NextQuestionBroadcastReceiver.class); nextQuestionIntent.putExtra("setsIDs", setsIDs); PendingIntent replyPendingIntent = PendingIntent.getBroadcast(context, RequestCodes.PENDING_INTENT_NEXT_QUESTION_REQUEST_CODE, nextQuestionIntent, PendingIntent.FLAG_CANCEL_CURRENT); NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.drawable.ic_notifi_icon, context.getString(R.string.Next), replyPendingIntent) .build(); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, "RepeatsSendQuestionChannel") .setSmallIcon(R.drawable.ic_notifi_icon) .setContentTitle(Title) .setContentText(Text) .setStyle(new NotificationCompat.BigTextStyle() .bigText(Text)) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setColor(context.getResources().getColor(R.color.colorAccent)) .setColorized(true) .setDefaults(Notification.DEFAULT_LIGHTS) .setOnlyAlertOnce(true) .addAction(action); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); notificationManager.notify(RequestCodes.QUESTION_NOTIFICATION_ID, mBuilder.build()); } } <file_sep>/app/build.gradle apply plugin: 'com.android.application' android { compileSdkVersion 30 defaultConfig { applicationId "com.rootekstudio.repeatsandroid" minSdkVersion 21 targetSdkVersion 30 versionCode 2080013 versionName "2.8.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } productFlavors { } compileOptions { targetCompatibility = 1.8 sourceCompatibility = 1.8 } } dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') implementation 'androidx.core:core:1.3.1' implementation 'androidx.appcompat:appcompat:1.2.0' implementation 'androidx.legacy:legacy-support-v4:1.0.0' implementation 'androidx.preference:preference:1.1.1' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' implementation 'com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava' implementation 'com.google.android.material:material:1.2.0' implementation 'com.google.firebase:firebase-firestore:21.5.0' implementation 'com.google.firebase:firebase-dynamic-links:19.1.0' implementation 'com.google.firebase:firebase-ml-vision:24.0.3' implementation 'com.google.android.gms:play-services-oss-licenses:17.0.0' implementation 'com.google.android.play:core:1.8.0' implementation 'com.applandeo:material-calendar-view:1.7.0' implementation "com.microsoft.appcenter:appcenter-analytics:3.3.0" implementation "com.microsoft.appcenter:appcenter-crashes:3.3.0" testImplementation 'junit:junit:4.13' androidTestImplementation 'androidx.test:runner:1.2.0' androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' implementation 'org.jetbrains:annotations-java5:15.0' } apply plugin: 'com.google.gms.google-services' apply plugin: 'com.google.android.gms.oss-licenses-plugin' <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/reminders/ReminderDayAndName.java package com.rootekstudio.repeatsandroid.reminders; public class ReminderDayAndName implements Comparable<ReminderDayAndName> { private int daysBefore; private String setID; public ReminderDayAndName(int daysBefore, String setID) { this.daysBefore = daysBefore; this.setID = setID; } public int getDaysBefore() { return daysBefore; } public void setDaysBefore(int daysBefore) { this.daysBefore = daysBefore; } public String getSetID() { return setID; } public void setSetID(String setID) { this.setID = setID; } @Override public int compareTo(ReminderDayAndName o) { return this.daysBefore - o.getDaysBefore(); } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/fastlearning/Fragment0.java package com.rootekstudio.repeatsandroid.fastlearning; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.TextView; import androidx.fragment.app.Fragment; import com.rootekstudio.repeatsandroid.R; import com.rootekstudio.repeatsandroid.database.RepeatsDatabase; import java.util.List; public class Fragment0 extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fastlearning_fragment0, container, false); if (FastLearningInfo.selectedSets.size() == 0) { getActivity().findViewById(R.id.nextConfigFL).setEnabled(false); } RepeatsDatabase DB = RepeatsDatabase.getInstance(requireContext()); LinearLayout linearLayout = view.findViewById(R.id.linearSetsListFL); List<FastLearningSetsListItem> setsList = DB.setsIdAndNameList(); for (int i = 0; i < setsList.size(); i++) { final FastLearningSetsListItem singleItem = setsList.get(i); View singleView = LayoutInflater.from(linearLayout.getContext()).inflate(R.layout.set_name_with_checkbox, null); final CheckBox checkBox = singleView.findViewById(R.id.checkBoxListViewName); for (int j = 0; j < FastLearningInfo.selectedSets.size(); j++) { if (FastLearningInfo.selectedSets.get(j).getSetID().equals(singleItem.getSetID())) { checkBox.setChecked(true); } } checkBox.setOnCheckedChangeListener((compoundButton, checked) -> { if (checked) { FastLearningInfo.selectedSets.add(singleItem); if (FastLearningInfo.selectedSets.size() == 1) { getActivity().findViewById(R.id.nextConfigFL).setEnabled(true); } } else { for (int j = 0; j < FastLearningInfo.selectedSets.size(); j++) { FastLearningSetsListItem item = FastLearningInfo.selectedSets.get(j); if (item.getSetID().equals(singleItem.getSetID())) { FastLearningInfo.selectedSets.remove(j); break; } } if (FastLearningInfo.selectedSets.size() == 0) { getActivity().findViewById(R.id.nextConfigFL).setEnabled(false); } } }); singleView.setOnClickListener(view1 -> { if (checkBox.isChecked()) { checkBox.setChecked(false); } else { checkBox.setChecked(true); } }); TextView setNameTextView = singleView.findViewById(R.id.setNameListViewItemName); setNameTextView.setText(singleItem.getSetName()); linearLayout.addView(singleView); if(FastLearningInfo.setsFromNotification != null) { if(FastLearningInfo.setsFromNotification.contains(singleItem.getSetID())) { checkBox.setChecked(true); } } } return view; } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/fastlearning/FastLearningInfo.java package com.rootekstudio.repeatsandroid.fastlearning; import com.rootekstudio.repeatsandroid.database.SetSingleItem; import java.util.ArrayList; import java.util.HashMap; import java.util.List; class FastLearningInfo { static List<FastLearningSetsListItem> selectedSets; static List<SetSingleItem> selectedQuestions; static HashMap<String, List<SetSingleItem>> setsContent; static boolean randomQuestions; static boolean ignoreChars; static int questionsCount; static int allAvailableQuestionsCount; static String setsFromNotification; static void reset() { selectedSets = new ArrayList<>(); setsContent = new HashMap<>(); selectedQuestions = new ArrayList<>(); randomQuestions = true; ignoreChars = false; questionsCount = 0; allAvailableQuestionsCount = 0; setsFromNotification = null; } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/fastlearning/FastLearningConfigActivity.java package com.rootekstudio.repeatsandroid.fastlearning; import android.content.Intent; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import com.rootekstudio.repeatsandroid.R; import com.rootekstudio.repeatsandroid.RepeatsAnalytics; import com.rootekstudio.repeatsandroid.UIHelper; import com.rootekstudio.repeatsandroid.database.MigrateDatabase; import com.rootekstudio.repeatsandroid.database.RepeatsDatabase; import com.rootekstudio.repeatsandroid.database.SetSingleItem; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; public class FastLearningConfigActivity extends AppCompatActivity { FragmentManager fragmentManager; int configStage; RepeatsDatabase DB; @Override protected void onCreate(Bundle savedInstanceState) { RepeatsAnalytics.startAnalytics(getApplication()); super.onCreate(savedInstanceState); if(MigrateDatabase.oldDBExists()) { AlertDialog dialog = UIHelper.loadingDialog(getString(R.string.dataMigrate), this); dialog.show(); new Thread(() -> { new MigrateDatabase(FastLearningConfigActivity.this).migrateToNewDatabase(); dialog.cancel(); startActivity(new Intent(FastLearningConfigActivity.this, FastLearningConfigActivity.class)); finish(); }).start(); return; } setContentView(R.layout.activity_fast_learning_config); getSupportActionBar().hide(); DB = RepeatsDatabase.getInstance(this); FastLearningInfo.reset(); configStage = 0; fragmentManager = getSupportFragmentManager(); String selectedSetID = getIntent().getStringExtra("setID"); String reminderRequest = getIntent().getStringExtra("reminderRequest"); if(reminderRequest != null) { FastLearningInfo.setsFromNotification = reminderRequest; } if (selectedSetID != null) { List<SetSingleItem> setItems = DB.allItemsInSet(selectedSetID, -1); FastLearningSetsListItem newItem = DB.singleSetIdNameAndStats(selectedSetID); FastLearningInfo.selectedSets.add(newItem); FastLearningInfo.setsContent.put(selectedSetID, setItems); FastLearningInfo.allAvailableQuestionsCount += setItems.size(); FastLearningInfo.questionsCount += setItems.size(); navigateToFragment1(); findViewById(R.id.nextConfigFL).setEnabled(true); configStage++; } else { navigateToFragment0(); } } public void nextClick(View view) { if (configStage == 0) { FastLearningInfo.setsContent = new HashMap<>(); FastLearningInfo.allAvailableQuestionsCount = 0; FastLearningInfo.questionsCount = 0; for (int i = 0; i < FastLearningInfo.selectedSets.size(); i++) { FastLearningSetsListItem singleItem = FastLearningInfo.selectedSets.get(i); List<SetSingleItem> setItems = DB.allItemsInSet(singleItem.getSetID(), -1); FastLearningInfo.setsContent.put(singleItem.getSetID(), setItems); FastLearningInfo.allAvailableQuestionsCount += setItems.size(); FastLearningInfo.questionsCount += setItems.size(); } navigateToFragment1(); configStage++; } else if (configStage == 1) { if (FastLearningInfo.randomQuestions) { if(FastLearningInfo.questionsCount == 0) { Toast.makeText(this, R.string.selectAtLeastOneQuestion, Toast.LENGTH_SHORT).show(); return; } FastLearningInfo.selectedQuestions = chooseQuestions(); navigateToFastLearning(); } else { navigateToFragment2(); } configStage++; } else if (configStage == 2) { navigateToFastLearning(); } } private void navigateToFragment0() { FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.frameLayoutFastLearning, new Fragment0()); fragmentTransaction.commit(); } private void navigateToFragment1() { FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.frameLayoutFastLearning, new Fragment1()); fragmentTransaction.commit(); } private void navigateToFragment2() { FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.frameLayoutFastLearning, new Fragment2()); fragmentTransaction.commit(); } private void navigateToFastLearning() { Intent intent = new Intent(this, FastLearningActivity.class); startActivity(intent); finish(); } private ArrayList<SetSingleItem> chooseQuestions() { ArrayList<SetSingleItem> selectedQuestions = new ArrayList<>(); //getting questions from sets with certain conditions for (List<SetSingleItem> singleItemList : FastLearningInfo.setsContent.values()) { int addedQuestionsFromSingleSet = 0; for (int i = 0; i < singleItemList.size(); i++) { if (addedQuestionsFromSingleSet >= FastLearningInfo.questionsCount / FastLearningInfo.setsContent.size()) { break; } SetSingleItem singleItem = singleItemList.get(i); float wrongAnswers = singleItem.getWrongAnswers(); float allAnswers = singleItem.getAllAnswers(); float wrongAnswersRatio = wrongAnswers / allAnswers; if (wrongAnswersRatio > 0.5 || allAnswers == 0) { selectedQuestions.add(singleItem); addedQuestionsFromSingleSet++; } } } //while user requested more questions than size of selectedQuestions while (selectedQuestions.size() < FastLearningInfo.questionsCount) { int availableSpace = FastLearningInfo.questionsCount - selectedQuestions.size(); int addedExtraQuestionsFromSingleSet = 0; //if there is more sets than available place to put questions if (availableSpace < FastLearningInfo.setsContent.size()) { //sort sets by All answers ArrayList<FastLearningSetsListItem> sortedSets = new ArrayList<>(); int lowestAllAnswers = -1; for (int i = 0; i < FastLearningInfo.setsContent.size(); i++) { FastLearningSetsListItem singleSetInfo = FastLearningInfo.selectedSets.get(i); if (i == 0) { lowestAllAnswers = singleSetInfo.getAllAnswers(); sortedSets.add(singleSetInfo); continue; } if (lowestAllAnswers > singleSetInfo.getAllAnswers()) { sortedSets.add(0, singleSetInfo); } else { sortedSets.add(singleSetInfo); } } //take one question from each set while availableSpace != 0 for (int i = 0; i < sortedSets.size(); i++) { List<SetSingleItem> singleItemList = FastLearningInfo.setsContent.get(sortedSets.get(i).getSetID()); Collections.shuffle(singleItemList); for (int j = 0; j < singleItemList.size(); j++) { SetSingleItem singleItem = singleItemList.get(j); if (!selectedQuestions.contains(singleItem)) { selectedQuestions.add(singleItem); availableSpace--; break; } } if (availableSpace == 0) { break; } } //if there is more available place for questions than sets } else { for (List<SetSingleItem> singleItemList : FastLearningInfo.setsContent.values()) { addedExtraQuestionsFromSingleSet = 0; Collections.shuffle(singleItemList); for (int i = 0; i < singleItemList.size(); i++) { if (addedExtraQuestionsFromSingleSet >= availableSpace / FastLearningInfo.setsContent.size()) { break; } else { SetSingleItem singleItem = singleItemList.get(i); if (!selectedQuestions.contains(singleItem)) { selectedQuestions.add(singleItem); addedExtraQuestionsFromSingleSet++; } } } } } } Collections.shuffle(selectedQuestions); return selectedQuestions; } public void previousClick(View view) { onBackPressed(); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); } return true; } @Override public void onBackPressed() { configStage--; if (configStage == -1) { super.onBackPressed(); } else if (configStage == 0) { navigateToFragment0(); } else if (configStage == 1) { navigateToFragment1(); findViewById(R.id.nextConfigFL).setEnabled(true); } } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/reminders/ReminderBroadcastReceiver.java package com.rootekstudio.repeatsandroid.reminders; import android.app.Notification; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import com.rootekstudio.repeatsandroid.R; import com.rootekstudio.repeatsandroid.RequestCodes; import com.rootekstudio.repeatsandroid.database.RepeatsDatabase; import com.rootekstudio.repeatsandroid.fastlearning.FastLearningConfigActivity; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class ReminderBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String setsIDs = intent.getStringExtra("setsIDs"); String daysBefore = intent.getStringExtra("daysBefore"); RepeatsDatabase.getInstance(context).updateReminderEnabled(setsIDs, false); List<String> setsNamesList = new ArrayList<>(); List<String> daysBeforeList = new ArrayList<>(); Scanner scannerIDs = new Scanner(setsIDs); while (scannerIDs.hasNextLine()) { setsNamesList.add(RepeatsDatabase.getInstance(context).setNameResolver(scannerIDs.nextLine())); } Scanner scannerDays = new Scanner(daysBefore); while (scannerDays.hasNextLine()) { daysBeforeList.add(scannerDays.nextLine()); } String title; String text = ""; if (daysBeforeList.size() > 1) { title = "\u23F0 " + context.getResources().getString(R.string.tests_coming); for (int i = 0; i < daysBeforeList.size(); i++) { text += context.getResources().getQuantityString(R.plurals.when_test, Integer.parseInt(daysBeforeList.get(i)), setsNamesList.get(i), Integer.parseInt(daysBeforeList.get(i))) + "\n"; } text += "\n" + context.getResources().getString(R.string.click_to_learn); } else { int days = Integer.parseInt(daysBeforeList.get(0)); title = "\u23F0 " + context.getResources().getQuantityString(R.plurals.when_test, days, setsNamesList.get(0), days); text = context.getResources().getString(R.string.click_to_learn); } NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, "RepeatsRemindersChannel"); mBuilder.setDefaults(Notification.DEFAULT_ALL); mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH); mBuilder .setSmallIcon(R.drawable.ic_notifi_icon) .setContentTitle(title) .setContentText(text) .setStyle(new NotificationCompat.BigTextStyle() .bigText(text)) .setColor(context.getResources().getColor(R.color.colorAccent)) .setColorized(true) .setAutoCancel(true); Intent fastLearning = new Intent(context, FastLearningConfigActivity.class); fastLearning.putExtra("reminderRequest", setsIDs); PendingIntent FL = PendingIntent.getActivity(context, RequestCodes.REMINDER_NOTIFICATION_CLICK_ID, fastLearning, PendingIntent.FLAG_CANCEL_CURRENT); mBuilder.setContentIntent(FL); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); notificationManager.notify(RequestCodes.REMINDER_NOTIFICATION_ID, mBuilder.build()); SetReminders.startReminders(context); } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/mainpage/SetsFragment.java package com.rootekstudio.repeatsandroid.mainpage; import android.content.ActivityNotFoundException; import android.content.Intent; import android.os.Bundle; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.RelativeLayout; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.rootekstudio.repeatsandroid.R; import com.rootekstudio.repeatsandroid.RequestCodes; import com.rootekstudio.repeatsandroid.activities.AddEditSetActivity; import com.rootekstudio.repeatsandroid.community.RepeatsCommunityStartActivity; import com.rootekstudio.repeatsandroid.database.RepeatsDatabase; import com.rootekstudio.repeatsandroid.database.SingleSetInfo; import com.rootekstudio.repeatsandroid.database.Values; import com.rootekstudio.repeatsandroid.textrecognition.TextRecognitionActivity; import java.util.List; public class SetsFragment extends Fragment { private PopupWindow popupWindow; private PopupWindow chooseHowTR; private RepeatsDatabase DB; int width; int height; public SetsFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { DB = RepeatsDatabase.getInstance(requireContext()); List<SingleSetInfo> repeatsList = DB.allSetsInfo(Values.ORDER_BY_ID_DESC); View view = LayoutInflater.from(getContext()).inflate(R.layout.mainfragment_sets, null); if (repeatsList.size() == 0) { RelativeLayout emptyInfo = view.findViewById(R.id.EmptyHereText); emptyInfo.setVisibility(View.VISIBLE); } RecyclerView recyclerView = view.findViewById(R.id.recycler_view_main); RecyclerView.Adapter adapter = new MainActivityAdapter(repeatsList, getContext(), (AppCompatActivity) getActivity()); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext()); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(adapter); FloatingActionButton fab = view.findViewById(R.id.fab); fab.setOnClickListener(fabClick); return view; } private View.OnClickListener fabClick = new View.OnClickListener() { @Override public void onClick(View view) { width = LinearLayout.LayoutParams.MATCH_PARENT; height = LinearLayout.LayoutParams.MATCH_PARENT; View popupView = LayoutInflater.from(getContext()).inflate(R.layout.add_set_window, null); popupView.findViewById(R.id.createNewSet).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent addEditActivityIntent = new Intent(getContext(), AddEditSetActivity.class); addEditActivityIntent.putExtra("ISEDIT", "FALSE"); addEditActivityIntent.putExtra("IGNORE_CHARS", "false"); startActivity(addEditActivityIntent); popupWindow.dismiss(); } }); popupView.findViewById(R.id.getSetFromImage).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { popupWindow.dismiss(); View chooseHowTextRecognition = LayoutInflater.from(getContext()).inflate(R.layout.choose_how_tr, null); chooseHowTextRecognition.findViewById(R.id.takePhoto).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(), TextRecognitionActivity.class); intent.putExtra("takePhoto", true); startActivity(intent); chooseHowTR.dismiss(); } }); chooseHowTextRecognition.findViewById(R.id.chooseFromGallery).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(), TextRecognitionActivity.class); intent.putExtra("takePhoto", false); startActivity(intent); chooseHowTR.dismiss(); } }); chooseHowTextRecognition.findViewById(R.id.closePopupAddSet).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { chooseHowTR.dismiss(); } }); chooseHowTR = new PopupWindow(chooseHowTextRecognition, width, height, true); chooseHowTR.setAnimationStyle(R.style.animation); chooseHowTR.showAtLocation(view, Gravity.CENTER, 0, 0); } }); popupView.findViewById(R.id.getSetFromZip).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent zipPickerIntent = new Intent(Intent.ACTION_GET_CONTENT); zipPickerIntent.setType("application/*"); try { getActivity().startActivityForResult(zipPickerIntent, RequestCodes.READ_SHARED); } catch (ActivityNotFoundException e) { Toast.makeText(getContext(), R.string.explorerNotFound, Toast.LENGTH_LONG).show(); } catch (Exception e) { e.printStackTrace(); } popupWindow.dismiss(); } }); popupView.findViewById(R.id.getSetFromCommunity).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intentRC = new Intent(getContext(), RepeatsCommunityStartActivity.class); startActivity(intentRC); popupWindow.dismiss(); } }); popupView.findViewById(R.id.closePopupAddSet).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { popupWindow.dismiss(); } }); popupWindow = new PopupWindow(popupView, width, height, true); popupWindow.setAnimationStyle(R.style.animation); popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0); } }; } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/community/PreviewAdapter.java package com.rootekstudio.repeatsandroid.community; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.rootekstudio.repeatsandroid.R; import java.util.HashMap; import java.util.Objects; public class PreviewAdapter extends RecyclerView.Adapter<PreviewAdapter.ListHolder> { HashMap<Integer, String[]> questionsAndAnswersList; public PreviewAdapter(HashMap<Integer, String[]> questionsAndAnswersList) { this.questionsAndAnswersList = questionsAndAnswersList; } static class ListHolder extends RecyclerView.ViewHolder { LinearLayout linearLayout; ListHolder(View view) { super(view); linearLayout = view.findViewById(R.id.linearQuestionAndAnswer); } } @NonNull @Override public ListHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LinearLayout linearLayout = (LinearLayout) LayoutInflater.from(parent.getContext()).inflate(R.layout.question_and_answer, parent, false); return new ListHolder(linearLayout); } @Override public void onBindViewHolder(@NonNull ListHolder holder, int position) { LinearLayout linearLayout = holder.linearLayout; TextView question = linearLayout.findViewById(R.id.questionTextView); TextView answer = linearLayout.findViewById(R.id.answerTextView); question.setText(Objects.requireNonNull(questionsAndAnswersList.get(position))[0]); answer.setText(Objects.requireNonNull(questionsAndAnswersList.get(position))[1]); } @Override public int getItemCount() { return questionsAndAnswersList.size(); } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/database/SetSingleItem.java package com.rootekstudio.repeatsandroid.database; public class SetSingleItem { private int itemID; private String setID; private String setName; private String Question; private String Answer; private String Image; private int goodAnswers; private int wrongAnswers; public SetSingleItem() { } public SetSingleItem(int itemID, String Question, String Answer, String Imag, int goodAnswers, int wrongAnswers) { this.itemID = itemID; this.Question = Question; this.Answer = Answer; this.Image = Imag; this.goodAnswers = goodAnswers; this.wrongAnswers = wrongAnswers; } public int getItemID() { return itemID; } public String getQuestion() { return Question; } public String getAnswer() { return Answer; } public String getImage() { return Image; } public int getGoodAnswers() { return goodAnswers; } public int getWrongAnswers() { return wrongAnswers; } public int getAllAnswers() { return goodAnswers + wrongAnswers; } public String getSetID() { return setID; } public String getSetName() { return setName; } public void setItemID(int itemID) { this.itemID = itemID; } public void setQuestion(String Question) { this.Question = Question; } public void setAnswer(String Answer) { this.Answer = Answer; } public void setImage(String Image) { this.Image = Image; } public void setGoodAnswers(int goodAnswers) { this.goodAnswers = goodAnswers; } public void setWrongAnswers(int wrongAnswers) { this.wrongAnswers = wrongAnswers; } public void setSetID(String setID) { this.setID = setID; } public void setSetName(String setName) { this.setName = setName; } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/database/Values.java package com.rootekstudio.repeatsandroid.database; public class Values { public static final String sets_info = "sets_info"; public static final String set_id = "set_id"; public static final String set_name = "set_name"; public static final String creation_date = "creation_date"; public static final String enabled = "enabled"; public static final String ignore_chars = "ignore_chars"; public static final String first_lang = "first_lang"; public static final String second_lang = "second_lang"; public static final String good_answers = "good_answers"; public static final String wrong_answers = "wrong_answers"; public static final String question = "question"; public static final String answer = "answer"; public static final String image = "image"; public static final String calendar = "calendar"; public static final String deadline = "deadline"; public static final String reminder_days_before = "reminder_days_before"; public static final String notifications_days = "notifications_days"; public static final String notifications_days_of_week = "notifications_days_of_week"; public static final String notifications_hours = "notifications_hours"; public static final String notifications_silent_hours = "notifications_silent_hours"; public static final String notifications_mode = "notifications_mode"; public static final String reminder_enabled = "reminder_enabled"; public static final int ORDER_BY_GOOD_ANSWERS_DESC = 0; public static final int ORDER_BY_WRONG_ANSWERS_DESC = 1; public static final int ORDER_BY_GOOD_ANSWERS_RATIO = 2; public static final int ORDER_BY_WRONG_ANSWERS_RATIO = 3; public static final int ORDER_BY_ID_ASC = 4; public static final int ORDER_BY_ID_DESC = 5; } <file_sep>/README.md # RepeatsJava Repeats is a free (and now open source!) app to learning for Android (this project) and Windows 10 (coming soon on GitHub). ### How it works? App will send a notification to you with question with specific frequency and will check if your answer is correct and if it's not, app will show the correct answer. ### Download app Google Play: https://play.google.com/store/apps/details?id=com.rootekstudio.repeatsandroid Microsoft Store: https://www.microsoft.com/store/productId/9NXLCWT9DQF2 ### It's my first time on GitHub... ...and in open source community. Also, Repeats is my first big project (I've been programming for 3 years as a hobby). I will be grateful for any comments to my code. <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/statistics/SetStats.java package com.rootekstudio.repeatsandroid.statistics; public class SetStats { private String setID; private String name; private int goodAnswers; private int wrongAnswers; private int allAnswers; public SetStats() { } public SetStats(String setID, String name, int goodAnswers, int wrongAnswers, int allAnswers) { } public void setSetID(String setID) { this.setID = setID; } public void setName(String name) { this.name = name; } public void setGoodAnswers(int goodAnswers) { this.goodAnswers = goodAnswers; } public void setWrongAnswers(int wrongAnswers) { this.wrongAnswers = wrongAnswers; } public void setAllAnswers(int allAnswers) { this.allAnswers = allAnswers; } public String getSetID() { return setID; } public String getName() { return name; } public int getGoodAnswers() { return goodAnswers; } public int getWrongAnswers() { return wrongAnswers; } public int getAllAnswers() { return goodAnswers + wrongAnswers; } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/settings/SetSettingsActivity.java package com.rootekstudio.repeatsandroid.settings; import android.content.Intent; import android.os.Bundle; import android.speech.tts.TextToSpeech; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.core.content.ContextCompat; import com.rootekstudio.repeatsandroid.R; import com.rootekstudio.repeatsandroid.database.RepeatsDatabase; import com.rootekstudio.repeatsandroid.database.SingleSetInfo; import com.rootekstudio.repeatsandroid.database.Values; import com.rootekstudio.repeatsandroid.readaloud.ReadAloudActivity; import com.rootekstudio.repeatsandroid.readaloud.ReadAloudConnector; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; public class SetSettingsActivity extends AppCompatActivity { TextToSpeech textToSpeech; AutoCompleteTextView autoCompleteTextView; AutoCompleteTextView autoCompleteTextView1; RepeatsDatabase DB; String setID; boolean fromReadAloud; SingleSetInfo singleSetInfo; CheckBox ignoreCheckBox; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_set_settings); getSupportActionBar().setDisplayHomeAsUpEnabled(true); Intent intent = getIntent(); setID = intent.getStringExtra("setID"); fromReadAloud = intent.getBooleanExtra("fromReadAloud", false); DB = RepeatsDatabase.getInstance(this); singleSetInfo = DB.singleSetInfo(setID); ignoreCheckBox = findViewById(R.id.ignoreCheckBox); if (singleSetInfo.getIgnoreChars() == 1) { ignoreCheckBox.setChecked(true); } else { ignoreCheckBox.setChecked(false); } ignoreCheckBox.setOnCheckedChangeListener(onCheckedChangeListener); initTTS(); } CompoundButton.OnCheckedChangeListener onCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean checked) { if (checked) { DB.updateIgnoreChars(setID, 1); } else { DB.updateIgnoreChars(setID, 0); } } }; private void initTTS() { new Thread(new Runnable() { @Override public void run() { textToSpeech = new TextToSpeech(SetSettingsActivity.this, new TextToSpeech.OnInitListener() { @Override public void onInit(int i) { if (i == TextToSpeech.SUCCESS) { selectLanguages(); } else { findViewById(R.id.linearSetLanguages).setVisibility(View.GONE); Toast.makeText(SetSettingsActivity.this, getString(R.string.cannotLoadLangList), Toast.LENGTH_SHORT).show(); } } }); } }).start(); } private void selectLanguages() { final HashMap<String, String> detailLocaleList = new HashMap<>(); Locale[] locales = Locale.getAvailableLocales(); List<String> displayedlocaleList = new ArrayList<>(); for (Locale locale : locales) { int res = textToSpeech.isLanguageAvailable(locale); if (res == TextToSpeech.LANG_COUNTRY_AVAILABLE) { displayedlocaleList.add(locale.getDisplayName()); detailLocaleList.put(locale.getDisplayName(), locale.toString()); } } Collections.sort(displayedlocaleList); String localeString = DB.getValueByCondition(Values.first_lang, Values.sets_info, Values.set_id, setID); String localeString1 = DB.getValueByCondition(Values.second_lang, Values.sets_info, Values.set_id, setID); final Locale locale = new Locale(localeString.substring(0, localeString.indexOf("_")), localeString.substring(localeString.indexOf("_") + 1)); final Locale locale1 = new Locale(localeString1.substring(0, localeString1.indexOf("_")), localeString1.substring(localeString1.indexOf("_") + 1)); final String defaults = getString(R.string.question_lang) + ": " + locale.getDisplayName() + "\n" + getString(R.string.answer_lang) + ": " + locale1.getDisplayName(); final ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.select_language_single_item, displayedlocaleList); runOnUiThread(new Runnable() { @Override public void run() { final TextView defaultsLanguages = findViewById(R.id.defaultsLanguageSettings); defaultsLanguages.setText(defaults); autoCompleteTextView = findViewById(R.id.firstLanguageSelect); autoCompleteTextView1 = findViewById(R.id.secondLanguageSelect); autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { TextView autoCompleteTextView = (TextView) view; String localeString = detailLocaleList.get(autoCompleteTextView.getText().toString()); if (localeString != null) { DB.updateTable(Values.sets_info, Values.first_lang + "='" + localeString + "'", Values.set_id + "='" + setID + "'"); String defaults = getString(R.string.question_lang) + ": " + autoCompleteTextView.getText().toString() + "\n" + getString(R.string.answer_lang) + ": " + locale1.getDisplayName(); defaultsLanguages.setText(defaults); ReadAloudConnector.locale0 = localeString; } } }); autoCompleteTextView1.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { TextView autoCompleteTextView = (TextView) view; String localeString = detailLocaleList.get(autoCompleteTextView.getText().toString()); if (localeString != null) { DB.updateTable(Values.sets_info, Values.second_lang + "='" + localeString + "'", Values.set_id + "='" + setID + "'"); String defaults = getString(R.string.question_lang) + ": " + locale.getDisplayName() + "\n" + getString(R.string.answer_lang) + ": " + autoCompleteTextView.getText().toString(); defaultsLanguages.setText(defaults); ReadAloudConnector.locale1 = localeString; } } }); autoCompleteTextView.setAdapter(adapter); autoCompleteTextView1.setAdapter(adapter); } }); } public void ignoreDescriptionClick(View view) { if (ignoreCheckBox.isChecked()) { ignoreCheckBox.setChecked(false); } else { ignoreCheckBox.setChecked(true); } } public void swapQuestionsWithAnswersClick(View view) { view.setEnabled(false); LinearLayout linearLayout = findViewById(R.id.operationInfo); TextView textView = linearLayout.findViewById(R.id.operationInfoTextView); ImageView imageView = linearLayout.findViewById(R.id.operationInfoImageView); try { DB.swapQuestionsWithAnswers(setID); imageView.setImageDrawable(getDrawable(R.drawable.check)); imageView.setColorFilter(ContextCompat.getColor(this, R.color.greenRepeats), android.graphics.PorterDuff.Mode.SRC_IN); textView.setText(R.string.operationSuccess); } catch (Exception e) { imageView.setImageDrawable(getDrawable(R.drawable.clear)); imageView.setColorFilter(ContextCompat.getColor(this, R.color.redRepeats), android.graphics.PorterDuff.Mode.SRC_IN); textView.setText(R.string.operationFailed); e.printStackTrace(); } linearLayout.setVisibility(View.VISIBLE); view.setEnabled(true); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); } return true; } @Override public void onBackPressed() { if (fromReadAloud && !ReadAloudConnector.isTTSStopped) { Intent intent = new Intent(this, ReadAloudActivity.class); intent.putExtra("setID", setID); intent.putExtra("loadedFromNotification", true); startActivity(intent); finish(); } else { ReadAloudConnector.returnFromSettings = true; SetSettingsActivity.super.onBackPressed(); } } @Override protected void onDestroy() { if (textToSpeech != null) { textToSpeech.stop(); textToSpeech.shutdown(); } super.onDestroy(); } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/settings/SharedPreferencesManager.java package com.rootekstudio.repeatsandroid.settings; import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import androidx.preference.PreferenceManager; import com.rootekstudio.repeatsandroid.RepeatsHelper; import java.util.UUID; public class SharedPreferencesManager { public static final String FREQUENCY_KEY = "frequency"; public static final String SILENCE_HOURS_KEY = "silenceHoursSwitch"; public static final String USER_ID_KEY = "userID"; public static final String FIRST_RUN_KEY = "firstRunTerms"; public static final String LIST_NOTIFI_KEY = "ListNotifi"; public static final String VERSION_KEY = "version"; public static final String THEME_KEY = "theme"; public static final String BATTERY_OPTIMIZATION_KEY = "batteryOptimization"; public static final String REMINDERS_ENABLED_KEY = "remindersEnabled"; public static final String REMINDERS_TIME_KEY = "remindersTime"; public static final String NOTIFICATIONS_ENABLED_KEY = "notificationsEnabled"; public static final String REQUEST_FOR_APP_REVIEW = "appReview"; public static final String TERMS_CHANGED = "termsChanged"; private SharedPreferences sharedPreferences; private static SharedPreferencesManager single_instance = null; private SharedPreferencesManager(Context context) { sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); } public static synchronized SharedPreferencesManager getInstance(Context context) { if (single_instance == null) { single_instance = new SharedPreferencesManager(context.getApplicationContext()); } return single_instance; } public SharedPreferences getSharedPreferences() { return sharedPreferences; } public void setFrequency(int frequency) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt(FREQUENCY_KEY, frequency); editor.apply(); } public int getFrequency() { if (!sharedPreferences.contains(FREQUENCY_KEY)) { setFrequency(30); } return sharedPreferences.getInt(FREQUENCY_KEY, 30); } public void setSilenceHours(boolean silenceHours) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean(SILENCE_HOURS_KEY, silenceHours); editor.apply(); } public boolean getSilenceHours() { if (!sharedPreferences.contains(SILENCE_HOURS_KEY)) { setSilenceHours(false); } return sharedPreferences.getBoolean(SILENCE_HOURS_KEY, false); } public void setUserID(String userID) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(USER_ID_KEY, userID); editor.apply(); } public String getUserID() { if (!sharedPreferences.contains(USER_ID_KEY)) { String uniqueID = UUID.randomUUID().toString(); setUserID(uniqueID); } return sharedPreferences.getString(USER_ID_KEY, ""); } public void setFirstRunTerms(int firstRunTerms) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt(FIRST_RUN_KEY, firstRunTerms); editor.apply(); } public int getFirstRunTerms() { if (!sharedPreferences.contains(FIRST_RUN_KEY)) { setFirstRunTerms(2); return 0; } return sharedPreferences.getInt(FIRST_RUN_KEY, 2); } public void setListNotifi(String listNotifi) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(LIST_NOTIFI_KEY, listNotifi); editor.apply(); } public String getListNotifi() { if (sharedPreferences.contains(LIST_NOTIFI_KEY)) { setListNotifi("0"); } return sharedPreferences.getString(LIST_NOTIFI_KEY, "0"); } public void setVersion(String version) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(VERSION_KEY, version); editor.apply(); } public String getVersion() { if (!sharedPreferences.contains(VERSION_KEY)) { setVersion(RepeatsHelper.version); } return sharedPreferences.getString(VERSION_KEY, ""); } public void setTheme(String theme) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(THEME_KEY, theme); editor.apply(); } public String getTheme() { if (!sharedPreferences.contains(THEME_KEY)) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { setTheme("2"); } else { setTheme("1"); } } return sharedPreferences.getString(THEME_KEY, "1"); } public void setBatteryOptimization(boolean batteryOptimization) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean(BATTERY_OPTIMIZATION_KEY, batteryOptimization); editor.apply(); } public boolean getBatteryOptimization() { if(!sharedPreferences.contains(BATTERY_OPTIMIZATION_KEY)) { setBatteryOptimization(false); } return sharedPreferences.getBoolean(BATTERY_OPTIMIZATION_KEY, false); } public void setRemindersEnabled(boolean remindersEnabled) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean(REMINDERS_ENABLED_KEY, remindersEnabled); editor.apply(); } public boolean getRemindersEnabled() { if(!sharedPreferences.contains(REMINDERS_ENABLED_KEY)) { setRemindersEnabled(true); } return sharedPreferences.getBoolean(REMINDERS_ENABLED_KEY, true); } public void setRemindersTime(String remindersTime) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(REMINDERS_TIME_KEY, remindersTime); editor.apply(); } public String getRemindersTime() { if(!sharedPreferences.contains(REMINDERS_TIME_KEY)) { setRemindersTime("14:00"); } return sharedPreferences.getString(REMINDERS_TIME_KEY, "14:00"); } public void setNotificationsEnabled(boolean notificationsEnabled) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean(NOTIFICATIONS_ENABLED_KEY, notificationsEnabled); editor.apply(); } public boolean getNotificationsEnabled() { if(!sharedPreferences.contains(NOTIFICATIONS_ENABLED_KEY)) { setNotificationsEnabled(true); } return sharedPreferences.getBoolean(NOTIFICATIONS_ENABLED_KEY, true); } public void setRequestForAppReview(int requestForAppReview) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt(REQUEST_FOR_APP_REVIEW, requestForAppReview); editor.apply(); } public int getRequestForAppReview() { if(!sharedPreferences.contains(REQUEST_FOR_APP_REVIEW)) { setRequestForAppReview(0); } return sharedPreferences.getInt(REQUEST_FOR_APP_REVIEW, 0); } public void setTermsChanged(int termsChanged) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt(TERMS_CHANGED, termsChanged); editor.apply(); } public int getTermsChanged() { if(!sharedPreferences.contains(TERMS_CHANGED)) { setRequestForAppReview(0); } return sharedPreferences.getInt(TERMS_CHANGED, 0); } }<file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/readaloud/ReadAloudService.java package com.rootekstudio.repeatsandroid.readaloud; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.speech.tts.TextToSpeech; import android.speech.tts.UtteranceProgressListener; import android.widget.Toast; import androidx.core.app.NotificationCompat; import com.rootekstudio.repeatsandroid.R; import com.rootekstudio.repeatsandroid.RequestCodes; import com.rootekstudio.repeatsandroid.database.SetSingleItem; import com.rootekstudio.repeatsandroid.mainpage.MainActivity; import java.util.List; import java.util.Locale; public class ReadAloudService extends Service { private final IBinder binder = new ReadAloudBinder(); private TextToSpeech textToSpeech; private TextToSpeech textToSpeech1; private List<SetSingleItem> singleSet; private String locale0; private String locale1; private NotificationCompat.Builder builder; class ReadAloudBinder extends Binder { ReadAloudService getService() { return ReadAloudService.this; } } @Override public IBinder onBind(Intent intent) { return binder; } @Override public int onStartCommand(Intent intent, int flags, int startId) { locale0 = ReadAloudConnector.locale0; locale1 = ReadAloudConnector.locale1; singleSet = ReadAloudConnector.singleSet; ReadAloudConnector.isTTSStopped = false; Intent readAloudIntent = new Intent(this, ReadAloudActivity.class); readAloudIntent.putExtra("loadedFromNotification", true); readAloudIntent.putExtra("setID", ReadAloudConnector.setID); readAloudIntent.putExtra("speedRate", ReadAloudConnector.speechRate); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, readAloudIntent, PendingIntent.FLAG_UPDATE_CURRENT); builder = new NotificationCompat.Builder(this, "RepeatsReadAloudChannel") .setContentTitle(getString(R.string.playing_set) + " " + ReadAloudConnector.setName) .setContentText(getString(R.string.click_here_read_notifi)) .setContentIntent(pendingIntent) .setSmallIcon(R.drawable.ear); startForeground(RequestCodes.READ_ALOUD_NOTIFICATION_ID, builder.build()); initTTS(); return START_NOT_STICKY; } @Override public void onDestroy() { if (textToSpeech != null) { textToSpeech.stop(); textToSpeech.shutdown(); } if (textToSpeech1 != null) { textToSpeech1.stop(); textToSpeech1.shutdown(); } stopForeground(true); super.onDestroy(); } private void initTTS() { textToSpeech = new TextToSpeech(this, i -> { if (i == TextToSpeech.SUCCESS) { textToSpeech.setLanguage(new Locale(locale0)); textToSpeech.setOnUtteranceProgressListener(utteranceProgressListener); textToSpeech.setSpeechRate(ReadAloudConnector.speechRate); textToSpeech1 = new TextToSpeech(ReadAloudService.this, i1 -> { if (i1 == TextToSpeech.SUCCESS) { textToSpeech1.setLanguage(new Locale(locale1)); textToSpeech1.setOnUtteranceProgressListener(utteranceProgressListener1); textToSpeech1.setSpeechRate(ReadAloudConnector.speechRate); textToSpeech.speak(" ", TextToSpeech.QUEUE_ADD, null, "starting"); textToSpeech1.speak(" ", TextToSpeech.QUEUE_ADD, null, "starting"); } }); } else { Toast.makeText(ReadAloudService.this, getString(R.string.cannotLoadTTS), Toast.LENGTH_LONG).show(); Intent intent = new Intent(ReadAloudService.this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); stopSelf(); } }); } UtteranceProgressListener utteranceProgressListener = new UtteranceProgressListener() { @Override public void onStart(String s) { } @Override public void onDone(String s) { if (!ReadAloudConnector.isTTSStopped) { if (ReadAloudConnector.isActivityAlive) { if (s.equals("starting")) { return; } Intent intent = new Intent(); intent.setAction("com.rootekstudio.repeatsandroid"); intent.putExtra("speakingDone0", true); sendBroadcast(intent); } else { speak1(); } } } @Override public void onError(String s) { } }; UtteranceProgressListener utteranceProgressListener1 = new UtteranceProgressListener() { @Override public void onStart(String s) { } @Override public void onDone(String s) { if (!ReadAloudConnector.isTTSStopped) { if (ReadAloudConnector.isActivityAlive) { Intent intent = new Intent(); intent.setAction("com.rootekstudio.repeatsandroid"); if (s.equals("starting")) { intent.putExtra("loadingDone", true); sendBroadcast(intent); return; } ReadAloudConnector.speakItemIndex++; ReadAloudConnector.speakItemSetIndex++; intent.putExtra("speakingDone1", true); sendBroadcast(intent); } else { if (ReadAloudConnector.speakItemSetIndex != singleSet.size() - 1) { ReadAloudConnector.speakItemSetIndex++; speak0(); } else { stopTextToSpeech(); stopForegroundServ(); } } } } @Override public void onError(String s) { } }; public void stopTextToSpeech() { ReadAloudConnector.isTTSStopped = true; textToSpeech.stop(); textToSpeech1.stop(); } public void stopForegroundServ() { stopForeground(true); } public void resumeForeground() { startForeground(RequestCodes.READ_ALOUD_NOTIFICATION_ID, builder.build()); } public TextToSpeech getTextToSpeech() { return textToSpeech; } public TextToSpeech getTextToSpeech1() { return textToSpeech1; } public void setSpeechRate() { textToSpeech.setSpeechRate(ReadAloudConnector.speechRate); textToSpeech1.setSpeechRate(ReadAloudConnector.speechRate); } public void speak0() { checkAndChangeLocale(); if (ReadAloudConnector.isTTSStopped) { ReadAloudConnector.isTTSStopped = false; } SetSingleItem singleSetDB = singleSet.get(ReadAloudConnector.speakItemSetIndex); textToSpeech.speak(singleSetDB.getQuestion(), TextToSpeech.QUEUE_ADD, null, String.valueOf(ReadAloudConnector.speakItemIndex)); ReadAloudConnector.speakItemIndex++; } public void speak1() { checkAndChangeLocale(); SetSingleItem singleSetDB = singleSet.get(ReadAloudConnector.speakItemSetIndex); textToSpeech1.speak(singleSetDB.getAnswer(), TextToSpeech.QUEUE_ADD, null, String.valueOf(ReadAloudConnector.speakItemIndex)); ReadAloudConnector.speakItemIndex++; } private void checkAndChangeLocale() { if (!locale0.equals(ReadAloudConnector.locale0)) { locale0 = ReadAloudConnector.locale0; textToSpeech.setLanguage(new Locale(locale0)); } else if (!locale1.equals(ReadAloudConnector.locale1)) { locale1 = ReadAloudConnector.locale1; textToSpeech1.setLanguage(new Locale(locale1)); } } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/UIHelper.java package com.rootekstudio.repeatsandroid; import android.app.Activity; import android.content.Context; import android.content.res.Configuration; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatDelegate; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.rootekstudio.repeatsandroid.settings.SharedPreferencesManager; public class UIHelper { public static AlertDialog loadingDialog(String text, Activity activity) { MaterialAlertDialogBuilder dialogBuilder = new MaterialAlertDialogBuilder(activity); dialogBuilder.setBackground(activity.getDrawable(R.drawable.dialog_shape)); View view = LayoutInflater.from(activity).inflate(R.layout.loading, null); TextView textView = view.findViewById(R.id.loadingText); textView.setText(text); dialogBuilder.setView(view); dialogBuilder.setCancelable(false); return dialogBuilder.show(); } public static void restartActivity(Activity activity) { activity.finish(); activity.overridePendingTransition(0, 0); activity.startActivity(activity.getIntent()); activity.overridePendingTransition(0, 0); } public static Boolean DarkTheme(Context context, Boolean onlyCheck) { String theme = SharedPreferencesManager.getInstance(context).getTheme(); if (theme.equals("0")) { if (!onlyCheck) { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); } return false; } else if (theme.equals("1")) { if (!onlyCheck) { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); } return true; } else { Configuration config = context.getApplicationContext().getResources().getConfiguration(); int currentNightMode = config.uiMode & Configuration.UI_MODE_NIGHT_MASK; if (currentNightMode == Configuration.UI_MODE_NIGHT_YES) { if (!onlyCheck) { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); } return true; } else { if (!onlyCheck) { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); } return false; } } } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/database/SingleSetInfo.java package com.rootekstudio.repeatsandroid.database; public class SingleSetInfo { private String setID; private String setName; private String CreateDate; private int IgnoreChars; private String firstLanguage; private String secondLanguage; private int goodAnswers; private int wrongAnswers; public SingleSetInfo() { } public SingleSetInfo(String setID, String setName, String CreateDate, int IgnoreChars, String firstLanguage, String secondLanguage) { this.setID = setID; this.setName = setName; this.CreateDate = CreateDate; this.IgnoreChars = IgnoreChars; this.firstLanguage = firstLanguage; this.secondLanguage = secondLanguage; this.goodAnswers = 0; this.wrongAnswers = 0; } public String getSetID() { return setID; } public String getSetName() { return setName; } public String getCreateDate() { return CreateDate; } public int getIgnoreChars() { return IgnoreChars; } public String getFirstLanguage() { return firstLanguage; } public String getSecondLanguage() { return secondLanguage; } public int getGoodAnswers() { return goodAnswers; } public int getWrongAnswers() { return wrongAnswers; } public void setSetID(String Title) { this.setID = Title; } public void setSetName(String TableName) { this.setName = TableName; } public void setCreateDate(String CreateDate) { this.CreateDate = CreateDate; } public void setIgnoreChars(int IgnoreChars) { this.IgnoreChars = IgnoreChars; } public void setFirstLanguage(String firstLanguage) { this.firstLanguage = firstLanguage; } public void setSecondLanguage(String secondLanguage) { this.secondLanguage = secondLanguage; } public void setGoodAnswers(int goodAnswers) { this.goodAnswers = goodAnswers; } public void setWrongAnswers(int wrongAnswers) { this.wrongAnswers = wrongAnswers; } }<file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/database/GetQuestion.java package com.rootekstudio.repeatsandroid.database; import android.content.Context; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Scanner; public class GetQuestion { private String question; private String answer; private String setName; private String pictureName; private int ignoreChars; private String setID; private int itemID; public GetQuestion(Context context) { RepeatsDatabase DB = RepeatsDatabase.getInstance(context); List<String> all = DB.getAllSetsIDs(); int count = all.size(); if (count == 0) { return; } Random random = new Random(); int randomint = random.nextInt(count); SingleSetInfo single = DB.singleSetInfo(all.get(randomint)); setName = single.getSetName(); setID = single.getSetID(); ignoreChars = single.getIgnoreChars(); List<SetSingleItem> set = DB.allItemsInSet(setID, -1); int setcount = set.size(); Random randomset = new Random(); int randomsetint = randomset.nextInt(setcount); SetSingleItem singleSetDB = set.get(randomsetint); question = singleSetDB.getQuestion(); answer = singleSetDB.getAnswer(); pictureName = singleSetDB.getImage(); itemID = singleSetDB.getItemID(); } //get question using rules from Advanced delivery public GetQuestion(Context context, String setsIDs) { String chosenSetID; List<String> setsIDsList = new ArrayList<>(); Scanner scanner = new Scanner(setsIDs); while(scanner.hasNextLine()) { setsIDsList.add(scanner.nextLine()); } int count = setsIDsList.size(); if (count == 1) { chosenSetID = setsIDsList.get(0); } else { Random random = new Random(); int randomint = random.nextInt(count); chosenSetID = setsIDsList.get(randomint); } setID = chosenSetID; RepeatsDatabase DB = RepeatsDatabase.getInstance(context); SingleSetInfo singleTitle = DB.singleSetInfo(chosenSetID); setName = singleTitle.getSetName(); ignoreChars = singleTitle.getIgnoreChars(); List<SetSingleItem> allQuestions = DB.allItemsInSet(chosenSetID, -1); int allQcount = allQuestions.size(); SetSingleItem single; if (allQcount == 1) { single = allQuestions.get(0); } else { Random randomset = new Random(); int randomsetint = randomset.nextInt(allQcount); single = allQuestions.get(randomsetint); } question = single.getQuestion(); answer = single.getAnswer(); pictureName = single.getImage(); itemID = single.getItemID(); } public GetQuestion() { } public void setQuestion(String question) { this.question = question; } public void setAnswer(String answer) { this.answer = answer; } public void setSetName(String setName) { this.setName = setName; } public void setPictureName(String pictureName) { this.pictureName = pictureName; } public void setIgnoreChars(int ignoreChars) { this.ignoreChars = ignoreChars; } public void setSetID(String setID) { this.setID = setID; } public void setItemID(int itemID) { this.itemID = itemID; } public String getQuestion() { return question; } public String getAnswer() { return answer; } public String getSetName() { return setName; } public String getPictureName() { return pictureName; } public int getIgnoreChars() { return ignoreChars; } public String getSetID() { return setID; } public int getItemID() { return itemID; } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/AdvancedTimeItem.java package com.rootekstudio.repeatsandroid; public class AdvancedTimeItem { public String id; public String name; private String days; private String hours; public String frequency; public String sets; public AdvancedTimeItem() { } public AdvancedTimeItem(String id, String name, String days, String hours, String frequency, String sets) { this.id = id; this.name = name; this.days = days; this.hours = hours; this.frequency = frequency; this.sets = sets; } public String getId() { return id; } public String getName() { return name; } public String getDays() { return days; } public String getHours() { return hours; } public String getFrequency() { return frequency; } public String getSets() { return sets; } public void setId(String id) { this.id = id; } public void setName(String name) { this.name = name; } public void setDays(String days) { this.days = days; } public void setHours(String hours) { this.hours = hours; } public void setFrequency(String frequency) { this.frequency = frequency; } public void setSets(String sets) { this.sets = sets; } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/community/MySetsActivity.java package com.rootekstudio.repeatsandroid.community; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.firebase.dynamiclinks.DynamicLink; import com.google.firebase.dynamiclinks.FirebaseDynamicLinks; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.rootekstudio.repeatsandroid.R; import com.rootekstudio.repeatsandroid.RepeatsHelper; import com.rootekstudio.repeatsandroid.UIHelper; import com.rootekstudio.repeatsandroid.settings.SharedPreferencesManager; import java.util.ArrayList; public class MySetsActivity extends AppCompatActivity { ArrayList<QueryDocumentSnapshot> documents; private RecyclerView.Adapter mAdapter; FirebaseFirestore db; ArrayList<String> resultNames; ProgressBar progressBar; TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); UIHelper.DarkTheme(this, false); setContentView(R.layout.activity_my_sets); progressBar = findViewById(R.id.progressBarMySets); getSupportActionBar().setDisplayHomeAsUpEnabled(true); documents = new ArrayList<>(); final RecyclerView recyclerView = findViewById(R.id.mySetsRecyclerView); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(layoutManager); db = FirebaseFirestore.getInstance(); textView = findViewById(R.id.emptyMySetsText); String userID = SharedPreferencesManager.getInstance(this).getUserID(); resultNames = new ArrayList<>(); if(RepeatsHelper.isOnline(this)) { db.collection("sets") .whereEqualTo("userID", userID) .get() .addOnCompleteListener(task -> { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { documents.add(document); resultNames.add(document.get("displayName").toString()); } mAdapter = new MySetsListAdapter(resultNames); mAdapter.notifyDataSetChanged(); recyclerView.setAdapter(mAdapter); progressBar.setVisibility(View.GONE); if (documents.size() == 0) { textView.setVisibility(View.VISIBLE); } } }); } else { progressBar.setVisibility(View.GONE); Toast.makeText(this, getString(R.string.problem_connecting_to_db), Toast.LENGTH_LONG).show(); } } public void previewSetMySets(View view) { int id = (Integer) view.findViewById(R.id.setNameMySetsList).getTag(); CommunityHelper.getSetAndStartPreviewActivity(id, this, documents); } public void createLinkMySets(final View view) { view.setEnabled(false); View vParent = (View) view.getParent(); final ProgressBar progressLink = vParent.findViewById(R.id.progressLink); progressLink.setVisibility(View.VISIBLE); int id = (Integer) vParent.findViewById(R.id.setNameMySetsList).getTag(); FirebaseDynamicLinks.getInstance().createDynamicLink() .setLink(Uri.parse("https://kubas20020.wixsite.com/repeatsc/" + "shareset/" + documents.get(id).getId())) .setDomainUriPrefix("https://repeats.page.link") .setAndroidParameters(new DynamicLink.AndroidParameters.Builder().build()) .buildShortDynamicLink() .addOnCompleteListener(this, task -> { String dynamicLink = task.getResult().getShortLink().toString(); Intent shareLink = new Intent(Intent.ACTION_SEND); shareLink.setType("text/plain"); shareLink.putExtra(Intent.EXTRA_SUBJECT, ""); shareLink.putExtra(Intent.EXTRA_TEXT, dynamicLink); startActivity(Intent.createChooser(shareLink, getString(R.string.share))); view.setEnabled(true); progressLink.setVisibility(View.GONE); }); } public void deleteSetMySets(View view) { View vParent = (View) view.getParent(); int id = (Integer) vParent.findViewById(R.id.setNameMySetsList).getTag(); db.collection("sets").document(documents.get(id).getId()).delete(); resultNames.remove(id); mAdapter.notifyDataSetChanged(); if (resultNames.size() == 0) { textView.setVisibility(View.VISIBLE); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); } return true; } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/CheckAnswer.java package com.rootekstudio.repeatsandroid; import java.text.Normalizer; import java.util.Locale; import java.util.Scanner; public class CheckAnswer { public static boolean isAnswerCorrect(String user, String correct, boolean ignore) { user = user.trim(); user = user.toLowerCase(); correct = correct.toLowerCase(); if (ignore) { user = Normalizer.normalize(user, Normalizer.Form.NFD) .replaceAll(" ", "") .replaceAll("Ł", "l") .replaceAll("ł", "l") .replaceAll("[^\\p{ASCII}]", "") .toLowerCase(Locale.getDefault()); correct = Normalizer.normalize(correct, Normalizer.Form.NFD) .replaceAll(" ", "") .replaceAll("Ł", "l") .replaceAll("ł", "l") .replaceAll("[^\\p{ASCII}]", "") .toLowerCase(Locale.getDefault()); } if (!correct.contains(RepeatsHelper.breakLine)) { if (user.equals(correct)) { return true; } else { return false; } } else { Scanner scanner = new Scanner(correct); while (scanner.hasNextLine()) { String singleCorrect = scanner.nextLine(); if (singleCorrect.equals(user)) { return true; } } } return false; } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/fastlearning/Fragment1.java package com.rootekstudio.repeatsandroid.fastlearning; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.RadioButton; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TextView; import androidx.fragment.app.Fragment; import com.rootekstudio.repeatsandroid.R; public class Fragment1 extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fastlearning_fragment1, container, false); RadioButton randomQuestions = view.findViewById(R.id.randomQuestionsButton); RadioButton manuallySelectQuestions = view.findViewById(R.id.manuallySelectQuestions); TextView maxTextView = view.findViewById(R.id.maxQuestionsTextView); final RelativeLayout relativeSeekBar = view.findViewById(R.id.relativeSeekBar); final SeekBar seekBar = view.findViewById(R.id.seekBarFastLearning); final TextView textViewSelectedAnswers = view.findViewById(R.id.seekBarSelectedAnswers); CheckBox ignoreChars = view.findViewById(R.id.checkBoxIgnoreCharsFL); ignoreChars.setChecked(FastLearningInfo.ignoreChars); randomQuestions.setChecked(FastLearningInfo.randomQuestions); manuallySelectQuestions.setChecked(!FastLearningInfo.randomQuestions); if (!FastLearningInfo.randomQuestions) { relativeSeekBar.setVisibility(View.GONE); } ignoreChars.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { FastLearningInfo.ignoreChars = b; } }); randomQuestions.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if (b) { FastLearningInfo.questionsCount = seekBar.getProgress(); FastLearningInfo.randomQuestions = true; relativeSeekBar.setVisibility(View.VISIBLE); } } }); manuallySelectQuestions.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if (b) { FastLearningInfo.randomQuestions = false; FastLearningInfo.questionsCount = 0; relativeSeekBar.setVisibility(View.GONE); } } }); maxTextView.setText(String.valueOf(FastLearningInfo.allAvailableQuestionsCount)); seekBar.setMax(FastLearningInfo.allAvailableQuestionsCount); //if user previously did not chose how many questions he want / and set default value if (FastLearningInfo.questionsCount == 0) { FastLearningInfo.questionsCount = FastLearningInfo.allAvailableQuestionsCount; seekBar.setProgress(FastLearningInfo.allAvailableQuestionsCount); } else { seekBar.setProgress(FastLearningInfo.questionsCount); } seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { FastLearningInfo.questionsCount = i; String text = FastLearningInfo.questionsCount + " " + getString(R.string.questions2); textViewSelectedAnswers.setText(text); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); String seekBarSelectedAnswersText = FastLearningInfo.questionsCount + " " + getString(R.string.questions2); textViewSelectedAnswers.setText(seekBarSelectedAnswersText); return view; } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/fastlearning/Fragment2.java package com.rootekstudio.repeatsandroid.fastlearning; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.TextView; import androidx.fragment.app.Fragment; import com.google.android.material.button.MaterialButton; import com.rootekstudio.repeatsandroid.R; import com.rootekstudio.repeatsandroid.database.RepeatsDatabase; import com.rootekstudio.repeatsandroid.database.SetSingleItem; import java.util.List; public class Fragment2 extends Fragment { private LinearLayout linearList; private MaterialButton button; private TextView textCount; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fastlearning_fragment2, container, false); linearList = view.findViewById(R.id.linearLayoutQuestionsListFL); button = requireActivity().findViewById(R.id.nextConfigFL); button.setEnabled(false); textCount = view.findViewById(R.id.questionsCountTextView); String textQuestionsCount = getString(R.string.selected) + ": " + FastLearningInfo.selectedQuestions.size() + " " + getString(R.string.questions2); textCount.setText(textQuestionsCount); generateList(); return view; } private void generateList() { new Thread(() -> { RepeatsDatabase DB = RepeatsDatabase.getInstance(requireContext()); final List<SetSingleItem> questionsList = DB.getItemsForFastLearning(FastLearningInfo.selectedSets); LayoutInflater inflater = LayoutInflater.from(requireContext()); String setID = ""; for (int i = 0; i < questionsList.size(); i++) { SetSingleItem singleItem = questionsList.get(i); //add view with set name if (!singleItem.getSetID().equals(setID)) { setID = singleItem.getSetID(); View view = inflater.inflate(R.layout.set_name_with_checkbox, linearList, false); TextView textView = view.findViewById(R.id.setNameListViewItemName); CheckBox checkBox = view.findViewById(R.id.checkBoxListViewName); checkBox.setVisibility(View.GONE); String text = getString(R.string.Set) + ": " + singleItem.getSetName(); textView.setText(text); view.setEnabled(false); requireActivity().runOnUiThread(() -> linearList.addView(view)); } //add view with question and checkbox View view = inflater.inflate(R.layout.set_name_with_checkbox, linearList, false); TextView textView = view.findViewById(R.id.setNameListViewItemName); CheckBox checkBox = view.findViewById(R.id.checkBoxListViewName); textView.setText(singleItem.getQuestion()); checkBox.setOnCheckedChangeListener((compoundButton, b) -> { if (b) { FastLearningInfo.selectedQuestions.add(singleItem); FastLearningInfo.questionsCount++; if (FastLearningInfo.questionsCount == 1) { button.setEnabled(true); } } else { FastLearningInfo.selectedQuestions.remove(singleItem); FastLearningInfo.questionsCount--; if (FastLearningInfo.questionsCount == 0) { button.setEnabled(false); } } String text = getString(R.string.selected) + ": " + FastLearningInfo.selectedQuestions.size() + " " + getString(R.string.questions2); textCount.setText(text); }); view.setOnClickListener(view1 -> { if (checkBox.isChecked()) { checkBox.setChecked(false); } else { checkBox.setChecked(true); } }); requireActivity().runOnUiThread(() -> linearList.addView(view)); } }).start(); } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/database/LegacyDatabase.java package com.rootekstudio.repeatsandroid.database; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class LegacyDatabase extends SQLiteOpenHelper { int version = 4; public LegacyDatabase(Context context) { super(context, "repeats", null, 4); } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { version = oldVersion; } public List<SingleSetInfo> allSetsInfo() { String firstLanguage; String secondLanguage; if(Locale.getDefault().toString().equals("pl_PL")) { firstLanguage = "pl_PL"; secondLanguage = "en_GB"; } else { firstLanguage = "en_US"; secondLanguage = "es_ES"; } SQLiteDatabase DB = this.getReadableDatabase(); List<SingleSetInfo> setInfo = new ArrayList<>(); SingleSetInfo singleSetInfo; if(version == 4) { String query = "SELECT TableName, title, CreateDate, IsEnabled, IgnoreChars, firstLanguage, secondLanguage, goodAnswers, wrongAnswers FROM TitleTable;"; Cursor cursor = DB.rawQuery(query, null); if(cursor.moveToFirst()) { do { singleSetInfo = new SingleSetInfo(); singleSetInfo.setSetID(cursor.getString(0)); singleSetInfo.setSetName(cursor.getString(1)); singleSetInfo.setCreateDate(cursor.getString(2)); if(cursor.getString(4).equals("true")) { singleSetInfo.setIgnoreChars(1); } else { singleSetInfo.setIgnoreChars(0); } singleSetInfo.setFirstLanguage(cursor.getString(5)); singleSetInfo.setSecondLanguage(cursor.getString(6)); singleSetInfo.setGoodAnswers(cursor.getInt(7)); singleSetInfo.setWrongAnswers(cursor.getInt(8)); setInfo.add(singleSetInfo); }while(cursor.moveToNext()); } cursor.close(); DB.close(); } else if(version == 3) { String query = "SELECT TableName, title, CreateDate, IsEnabled, IgnoreChars, firstLanguage, secondLanguage FROM TitleTable;"; Cursor cursor = DB.rawQuery(query, null); if(cursor.moveToFirst()) { do { singleSetInfo = new SingleSetInfo(); singleSetInfo.setSetID(cursor.getString(0)); singleSetInfo.setSetName(cursor.getString(1)); singleSetInfo.setCreateDate(cursor.getString(2)); if(cursor.getString(4).equals("true")) { singleSetInfo.setIgnoreChars(1); } else { singleSetInfo.setIgnoreChars(0); } singleSetInfo.setFirstLanguage(cursor.getString(5)); singleSetInfo.setSecondLanguage(cursor.getString(6)); singleSetInfo.setGoodAnswers(0); singleSetInfo.setWrongAnswers(0); setInfo.add(singleSetInfo); }while(cursor.moveToNext()); } cursor.close(); DB.close(); } else if(version == 2) { String query = "SELECT TableName, title, CreateDate, IsEnabled, IgnoreChars FROM TitleTable;"; Cursor cursor = DB.rawQuery(query, null); if(cursor.moveToFirst()) { do { singleSetInfo = new SingleSetInfo(); singleSetInfo.setSetID(cursor.getString(0)); singleSetInfo.setSetName(cursor.getString(1)); singleSetInfo.setCreateDate(cursor.getString(2)); if(cursor.getString(4).equals("true")) { singleSetInfo.setIgnoreChars(1); } else { singleSetInfo.setIgnoreChars(0); } singleSetInfo.setFirstLanguage(firstLanguage); singleSetInfo.setSecondLanguage(secondLanguage); singleSetInfo.setGoodAnswers(0); singleSetInfo.setWrongAnswers(0); setInfo.add(singleSetInfo); }while(cursor.moveToNext()); } cursor.close(); DB.close(); } else if(version == 1) { String query = "SELECT TableName, title, CreateDate, IsEnabled FROM TitleTable;"; Cursor cursor = DB.rawQuery(query, null); if(cursor.moveToFirst()) { do { singleSetInfo = new SingleSetInfo(); singleSetInfo.setSetID(cursor.getString(0)); singleSetInfo.setSetName(cursor.getString(1)); singleSetInfo.setCreateDate(cursor.getString(2)); singleSetInfo.setIgnoreChars(0); singleSetInfo.setFirstLanguage(firstLanguage); singleSetInfo.setSecondLanguage(secondLanguage); singleSetInfo.setGoodAnswers(0); singleSetInfo.setWrongAnswers(0); setInfo.add(singleSetInfo); }while(cursor.moveToNext()); } cursor.close(); DB.close(); } return setInfo; } public List<SetSingleItem> allItemsInSet(String setID) { SQLiteDatabase DB = this.getReadableDatabase(); List<SetSingleItem> itemsInSet = new ArrayList<>(); SetSingleItem singleItem; if(version == 4) { String query = "SELECT question, answer, image, goodAnswers, wrongAnswers FROM " + setID + " ;"; Cursor cursor = DB.rawQuery(query, null); if(cursor.moveToFirst()) { do { singleItem = new SetSingleItem(); singleItem.setQuestion(cursor.getString(0)); singleItem.setAnswer(cursor.getString(1)); singleItem.setImage(cursor.getString(2)); singleItem.setGoodAnswers(cursor.getInt(3)); singleItem.setWrongAnswers(cursor.getInt(4)); itemsInSet.add(singleItem); }while(cursor.moveToNext()); } cursor.close(); DB.close(); } else { String query = "SELECT question, answer, image FROM " + setID + " ;"; Cursor cursor = DB.rawQuery(query, null); if(cursor.moveToFirst()) { do { singleItem = new SetSingleItem(); singleItem.setQuestion(cursor.getString(0)); singleItem.setAnswer(cursor.getString(1)); singleItem.setImage(cursor.getString(2)); singleItem.setGoodAnswers(0); singleItem.setWrongAnswers(0); itemsInSet.add(singleItem); }while(cursor.moveToNext()); } cursor.close(); DB.close(); } return itemsInSet; } }<file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/SetsConfigHelper.java package com.rootekstudio.repeatsandroid; import android.annotation.SuppressLint; import android.content.Context; import com.rootekstudio.repeatsandroid.database.RepeatsDatabase; import com.rootekstudio.repeatsandroid.database.SingleSetInfo; import com.rootekstudio.repeatsandroid.database.Values; import com.rootekstudio.repeatsandroid.notifications.NotificationsScheduler; import com.rootekstudio.repeatsandroid.settings.SharedPreferencesManager; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Locale; public class SetsConfigHelper { private Context context; private RepeatsDatabase DB; private SimpleDateFormat idFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS"); private SimpleDateFormat creationDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public SetsConfigHelper(Context context) { this.context = context; DB = RepeatsDatabase.getInstance(context); } public RepeatsDatabase getRepeatsDatabase() { return DB; } @SuppressLint("SimpleDateFormat") public String createNewSet(boolean addEmptyItem, String setName) { String id = "R" + idFormat.format(new Date()); String creationDate = creationDateFormat.format(new Date()); SingleSetInfo list; if (Locale.getDefault().toString().equals("pl_PL")) { list = new SingleSetInfo(id, setName, creationDate, 0, "pl_PL", "en_GB"); } else { list = new SingleSetInfo(id, setName, creationDate, 0, "en_US", "es_ES"); } //Registering set in database DB.createSet(id); DB.addSetToSetsInfoAndCalendar(list); if(addEmptyItem) { //Adding first empty item to set DB.addEmptyItemToSet(id); } JsonFile.putSetToJSON(context, id); return id; } public String createTempSet() { String date = idFormat.format(new Date()); String setID = "temp" + date; DB.createSet(setID); DB.addEmptyItemToSet(setID); return setID; } public void deleteSet(String setID) { ArrayList<String> allImages = DB.getAllImages(setID); for (int i = 0; i < allImages.size(); i++) { String imgName = allImages.get(i); File file = new File(context.getFilesDir(), imgName); file.delete(); } DB.deleteSetFromDatabase(setID); DB.deleteSet(setID); JsonFile.removeSetFromJSON(context, setID); //if there is no set left in database, turn off notifications if (DB.itemsInSetCount(Values.sets_info) == 0) { NotificationsScheduler.stopNotifications(context); SharedPreferencesManager.getInstance(context).setListNotifi("0"); } } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/community/RepeatsCommunityStartActivity.java package com.rootekstudio.repeatsandroid.community; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.rootekstudio.repeatsandroid.R; import com.rootekstudio.repeatsandroid.RepeatsHelper; import com.rootekstudio.repeatsandroid.UIHelper; import java.util.ArrayList; import java.util.Objects; public class RepeatsCommunityStartActivity extends AppCompatActivity { private RecyclerView recyclerView; private RecyclerView.Adapter mAdapter; ArrayList<String> resultNames; ArrayList<QueryDocumentSnapshot> documents; FirebaseFirestore db; ProgressBar progressBar; LinearLayout linearSearchInfo; TextView searchInfoText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); UIHelper.DarkTheme(this, false); setContentView(R.layout.activity_repeats_community_start); getSupportActionBar().setDisplayHomeAsUpEnabled(true); progressBar = findViewById(R.id.progressBarSearchC); db = FirebaseFirestore.getInstance(); recyclerView = findViewById(R.id.resultsRecycler); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(layoutManager); linearSearchInfo = findViewById(R.id.linearSearchInfo); searchInfoText = findViewById(R.id.searchInfoText); final EditText search = findViewById(R.id.searchRC); search.setOnEditorActionListener((textView, id, keyEvent) -> { if (id == EditorInfo.IME_ACTION_SEARCH) { String queryText = search.getText().toString(); if (!queryText.equals("")) { progressBar.setVisibility(View.VISIBLE); linearSearchInfo.setVisibility(View.GONE); search(queryText); InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); assert imm != null; imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); Objects.requireNonNull(getCurrentFocus()).clearFocus(); return true; } } return false; }); } void search(String text) { text = text + " "; ArrayList<String> queries = new ArrayList<>(); outerloop: while (text.contains(" ")) { String tag = text.substring(0, text.indexOf(" ")); while (tag.equals("")) { text = text.replaceFirst(" ", ""); if (text.length() == 0) { break outerloop; } tag = text.substring(0, text.indexOf(" ")); } text = text.replace(tag + " ", ""); String upper = tag.substring(0, 1).toUpperCase() + tag.substring(1); queries.add(upper); String lower = tag.substring(0, 1).toLowerCase() + tag.substring(1); queries.add(lower); } if (queries.size() > 10) { Toast.makeText(this, R.string.upTo5Words, Toast.LENGTH_LONG).show(); progressBar.setVisibility(View.GONE); linearSearchInfo.setVisibility(View.VISIBLE); searchInfoText.setText(R.string.nothingFound); return; } if (queries.size() == 0) { progressBar.setVisibility(View.GONE); linearSearchInfo.setVisibility(View.VISIBLE); searchInfoText.setText(R.string.nothingFound); return; } if(RepeatsHelper.isOnline(this)) { db.collection("sets") .whereArrayContainsAny("tags", queries) .get() .addOnCompleteListener(task -> { if (task.isSuccessful()) { documents = new ArrayList<>(); resultNames = new ArrayList<>(); for (QueryDocumentSnapshot document : task.getResult()) { String a = (String) document.get("availability"); if (a.equals("PUBLIC")) { documents.add(document); resultNames.add(document.get("displayName").toString()); } } mAdapter = new RCmainListAdapter(resultNames, 0); mAdapter.notifyDataSetChanged(); recyclerView.setAdapter(mAdapter); if (documents.size() == 0) { linearSearchInfo.setVisibility(View.VISIBLE); searchInfoText.setText(R.string.nothingFound); } progressBar.setVisibility(View.GONE); } else { Objects.requireNonNull(task.getException()).printStackTrace(); } }); } else { progressBar.setVisibility(View.GONE); Toast.makeText(this, getString(R.string.problem_connecting_to_db), Toast.LENGTH_LONG).show(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.repeats_community_menu, menu); return true; } public void searchResultClick(View view) { int tag = (Integer) view.findViewById(R.id.setNameListItemRC).getTag(); CommunityHelper.getSetAndStartPreviewActivity(tag, this, documents); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); } else if (item.getItemId() == R.id.yourSetsOption) { Intent intent = new Intent(this, MySetsActivity.class); startActivity(intent); } return true; } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/notifications/AnswerActivity.java package com.rootekstudio.repeatsandroid.notifications; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.rootekstudio.repeatsandroid.CheckAnswer; import com.rootekstudio.repeatsandroid.R; import com.rootekstudio.repeatsandroid.UIHelper; import com.rootekstudio.repeatsandroid.database.GetQuestion; import com.rootekstudio.repeatsandroid.database.RepeatsDatabase; import com.rootekstudio.repeatsandroid.database.Values; import com.rootekstudio.repeatsandroid.mainpage.MainActivity; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; public class AnswerActivity extends AppCompatActivity { private GetQuestion getQuestion; private String setsIDs; @Override protected void onCreate(Bundle savedInstanceState) { UIHelper.DarkTheme(this, false); super.onCreate(savedInstanceState); getQuestion = new GetQuestion(); Intent intent = getIntent(); getQuestion.setSetName(intent.getStringExtra("Title")); getQuestion.setQuestion(intent.getStringExtra("Question")); getQuestion.setPictureName(intent.getStringExtra("Image")); getQuestion.setAnswer(intent.getStringExtra("Correct")); getQuestion.setIgnoreChars(intent.getIntExtra("IgnoreChars", 0)); getQuestion.setSetID(intent.getStringExtra("setID")); getQuestion.setItemID(intent.getIntExtra("itemID", -1)); setsIDs = intent.getStringExtra("setsIDs"); createAlertDialogWithQuestion(); } private void createAlertDialogWithQuestion() { String title = getQuestion.getSetName(); String message = getQuestion.getQuestion(); String image = getQuestion.getPictureName(); MaterialAlertDialogBuilder alertDialog = new MaterialAlertDialogBuilder(this); alertDialog.setBackground(getDrawable(R.drawable.dialog_shape)); View view = getLayoutInflater().inflate(R.layout.ask, null); final EditText answerEditText = view.findViewById(R.id.EditAsk); answerEditText.setHint(R.string.ReplyText); answerEditText.requestFocus(); if (!image.equals("")) { final ImageView imgView = view.findViewById(R.id.imageViewQuestion); imgView.setVisibility(View.VISIBLE); File file = new File(getFilesDir(), image); FileInputStream inputStream = null; try { inputStream = new FileInputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); } Bitmap bitmap = BitmapFactory.decodeStream(inputStream); imgView.setImageBitmap(bitmap); } alertDialog.setTitle(title) .setMessage(message) .setView(view) .setCancelable(false) .setNegativeButton(R.string.Cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { finish(); } }) .setPositiveButton(R.string.Check, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { String userAnswer = answerEditText.getText().toString(); String correctAnswer = getQuestion.getAnswer(); boolean ignoreChars = false; if (getQuestion.getIgnoreChars() == 1) { ignoreChars = true; } if (CheckAnswer.isAnswerCorrect(userAnswer, correctAnswer, ignoreChars)) { if (correctAnswer.contains("\n")) { correctAnswer = correctAnswer.replace("\r\n", ", "); dialogInterface.dismiss(); createAlertDialogWithAnswer(getString(R.string.CorrectAnswer1), getString(R.string.CorrectAnswer2) + "\n" + getString(R.string.otherCorrectAnswers) + " " + correctAnswer); } else { dialogInterface.dismiss(); createAlertDialogWithAnswer(getString(R.string.CorrectAnswer1), getString(R.string.CorrectAnswer2)); } new Thread(new Runnable() { @Override public void run() { String setID = getQuestion.getSetID(); int itemID = getQuestion.getItemID(); RepeatsDatabase DB = RepeatsDatabase.getInstance(AnswerActivity.this); DB.increaseValueInSet(setID, itemID, Values.good_answers, 1); DB.increaseValueInSetsInfo(setID, Values.good_answers, 1); } }).start(); } else { dialogInterface.dismiss(); createAlertDialogWithAnswer(getString(R.string.IncorrectAnswer1), getString(R.string.IncorrectAnswer2) + " " + correctAnswer); new Thread(new Runnable() { @Override public void run() { String setID = getQuestion.getSetID(); int itemID = getQuestion.getItemID(); RepeatsDatabase DB = RepeatsDatabase.getInstance(AnswerActivity.this); DB.increaseValueInSet(setID, itemID, Values.wrong_answers, 1); DB.increaseValueInSetsInfo(setID, Values.wrong_answers, 1); } }).start(); } } }); AlertDialog dialog = alertDialog.create(); dialog.show(); } private void createAlertDialogWithAnswer(String title, String message) { MaterialAlertDialogBuilder alertDialog = new MaterialAlertDialogBuilder(this); alertDialog.setBackground(getDrawable(R.drawable.dialog_shape)) .setTitle(title) .setMessage(message) .setCancelable(false) .setNegativeButton(R.string.Cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { finish(); } }) .setPositiveButton(R.string.Next, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { getQuestion = new GetQuestion(AnswerActivity.this, setsIDs); dialogInterface.dismiss(); if (getQuestion.getQuestion() == null) { createAlertDialogWithError(); } else { createAlertDialogWithQuestion(); } } }); AlertDialog dialog = alertDialog.create(); dialog.show(); } private void createAlertDialogWithError() { MaterialAlertDialogBuilder alertDialog = new MaterialAlertDialogBuilder(this); alertDialog.setBackground(getDrawable(R.drawable.dialog_shape)) .setTitle(getString(R.string.cantLoadSet)) .setMessage(getString(R.string.checkSetSettings)) .setCancelable(false) .setNegativeButton(R.string.Cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { finish(); } }) .setPositiveButton(R.string.Settings, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Intent intent = new Intent(AnswerActivity.this, MainActivity.class); startActivity(intent); finish(); } }); AlertDialog dialog = alertDialog.create(); dialog.show(); } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/RepeatsAnalytics.java package com.rootekstudio.repeatsandroid; import android.app.Application; import com.microsoft.appcenter.AppCenter; import com.microsoft.appcenter.analytics.Analytics; import com.microsoft.appcenter.crashes.Crashes; public class RepeatsAnalytics { public static void startAnalytics(Application application) { if(!isAnalyticsEnabled()) { AppCenter.start(application, "347cfec3-4ebc-443c-a9d6-4fdd34df27dd", Analytics.class, Crashes.class); } } public static boolean isAnalyticsEnabled() { return AppCenter.isEnabled().get(); } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/activities/AppInfoActivity.java package com.rootekstudio.repeatsandroid.activities; import android.content.ActivityNotFoundException; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.oss.licenses.OssLicensesMenuActivity; import com.rootekstudio.repeatsandroid.R; import com.rootekstudio.repeatsandroid.UIHelper; import com.rootekstudio.repeatsandroid.firstrun.FirstRunActivity; public class AppInfoActivity extends AppCompatActivity { int clicked = 0; String versionName; String versionNumber; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_app_info); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getVersionInfo(); TextView versionNameTextView = findViewById(R.id.versionNameTextView ); TextView versionNumberTextView = findViewById(R.id.versionNumberTextView ); ImageView logo = findViewById(R.id.logoAppInfo ); versionNameTextView.setText(versionName); versionNumberTextView.setText(versionNumber); if(!UIHelper.DarkTheme(this, true)) { logo.setImageDrawable(getDrawable(R.drawable.repeats_for_light_bg)); } } private void getVersionInfo() { try { PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); versionName = pInfo.versionName; versionNumber = String.valueOf(pInfo.versionCode); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } } public void numberClick(View view) { clicked++; if(clicked == 5) { startActivity(new Intent(this, FirstRunActivity.class)); clicked = 0; } } public void termsOfUseClick(View view) { try { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://rootekstudio.wordpress.com/warunki-uzytkowania"))); } catch (ActivityNotFoundException e) { Toast.makeText(this, R.string.browserNotFound, Toast.LENGTH_LONG).show(); } } public void privacyPolicyClick(View view) { try { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://rootekstudio.wordpress.com/polityka-prywatnosci"))); } catch (ActivityNotFoundException e) { Toast.makeText(this, R.string.browserNotFound, Toast.LENGTH_LONG).show(); } } public void sendFeedbackClick(View view) { Intent send = new Intent(Intent.ACTION_SEND); send.setType("plain/text"); send.putExtra(Intent.EXTRA_EMAIL, new String[]{"<EMAIL>"}); send.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.FeedbackSubject) + " " + versionName); startActivity(Intent.createChooser(send, getString(R.string.SendFeedback))); } public void rateAppClick(View view) { try { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.rootekstudio.repeatsandroid"))); } catch (ActivityNotFoundException e) { Toast.makeText(this, R.string.storeNotFound, Toast.LENGTH_LONG).show(); } } public void openSourceLicencesClick(View view) { OssLicensesMenuActivity.setActivityTitle(getString(R.string.openSourceLicences)); startActivity(new Intent(this, OssLicensesMenuActivity.class)); } public void iconsCreditClick(View view) { try { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/tabler/tabler-icons/blob/master/LICENSE"))); } catch (ActivityNotFoundException e) { Toast.makeText(this, R.string.browserNotFound, Toast.LENGTH_LONG).show(); } } public void iconsMaterialCreditClick(View view) { try { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://material.io/resources/icons"))); } catch (ActivityNotFoundException e) { Toast.makeText(this, R.string.browserNotFound, Toast.LENGTH_LONG).show(); } } public void calendarViewCreditClick(View view) { try { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/Applandeo/Material-Calendar-View/blob/master/LICENSE.md"))); } catch (ActivityNotFoundException e) { Toast.makeText(this, R.string.browserNotFound, Toast.LENGTH_LONG).show(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); } return true; } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/database/MigrateDatabase.java package com.rootekstudio.repeatsandroid.database; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.os.Environment; import java.io.File; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; public class MigrateDatabase { private Context context; public MigrateDatabase(Context context) { this.context = context; } public static Boolean oldDBExists() { File file = Environment.getDataDirectory(); String path = "/data/com.rootekstudio.repeatsandroid/databases/repeats"; File oldDB = new File(file, path); return oldDB.exists(); } public void migrateToNewDatabase() { RepeatsDatabase newDB = RepeatsDatabase.getInstance(context); LegacyDatabase oldDB = new LegacyDatabase(context); List<SingleSetInfo> setsInfo = oldDB.allSetsInfo(); SQLiteDatabase writableNewDB = newDB.getWritableDatabase(); for(int i = 0; i < setsInfo.size(); i++) { SingleSetInfo setInfo = setsInfo.get(i); String setID = setInfo.getSetID(); ContentValues contentValues = new ContentValues(); contentValues.put(Values.set_id, setID); contentValues.put(Values.set_name, setInfo.getSetName()); contentValues.put(Values.creation_date, getCreationDateInNewFormat(setInfo.getCreateDate())); contentValues.put(Values.ignore_chars, setInfo.getIgnoreChars()); contentValues.put(Values.first_lang, setInfo.getFirstLanguage()); contentValues.put(Values.second_lang, setInfo.getSecondLanguage()); contentValues.put(Values.good_answers, setInfo.getGoodAnswers()); contentValues.put(Values.wrong_answers, setInfo.getWrongAnswers()); writableNewDB.insert(Values.sets_info, null, contentValues); String calendarQuery = "INSERT INTO " + Values.calendar + " (" + Values.set_id + ") VALUES ('" + setID + "');"; writableNewDB.execSQL(calendarQuery); String CREATE_SET = "CREATE TABLE IF NOT EXISTS " + setID + " (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + Values.question + " TEXT, " + Values.answer + " TEXT, " + Values.image + " TEXT, " + Values.good_answers + " INTEGER DEFAULT 0, " + Values.wrong_answers + " INTEGER DEFAULT 0);"; writableNewDB.execSQL(CREATE_SET); List<SetSingleItem> setContent = oldDB.allItemsInSet(setID); for(int j = 0; j < setContent.size(); j++) { SetSingleItem singleItem = setContent.get(j); ContentValues contentValuesSet = new ContentValues(); contentValuesSet.put(Values.question, singleItem.getQuestion()); contentValuesSet.put(Values.answer, singleItem.getAnswer()); contentValuesSet.put(Values.image, singleItem.getImage()); contentValuesSet.put(Values.good_answers, singleItem.getGoodAnswers()); contentValuesSet.put(Values.wrong_answers, singleItem.getWrongAnswers()); writableNewDB.insert(setID, null, contentValuesSet); } } oldDB.close(); writableNewDB.close(); context.deleteDatabase("repeats"); } private String getCreationDateInNewFormat(String creationDate) { String newDate = ""; SimpleDateFormat oldDateFormat = new SimpleDateFormat("dd.MM.yyyy"); try { Date date = oldDateFormat.parse(creationDate); Calendar calendar = Calendar.getInstance(); assert date != null; calendar.setTime(date); int yearInt = calendar.get(Calendar.YEAR); int monthInt = calendar.get(Calendar.MONTH) + 1; int dayInt = calendar.get(Calendar.DAY_OF_MONTH); String month; String day; if(monthInt < 10) { month = "0" + monthInt; } else { month = String.valueOf(monthInt); } if(dayInt < 10) { day = "0" + dayInt; } else { day = String.valueOf(dayInt); } newDate = yearInt + "-" + month + "-" + day + " 00:00:00"; } catch (ParseException e) { e.printStackTrace(); } return newDate; } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/settings/EditNotificationsForSetActivity.java package com.rootekstudio.repeatsandroid.settings; import android.app.TimePickerDialog; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.CompoundButton; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Switch; import android.widget.TimePicker; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.google.android.material.chip.Chip; import com.rootekstudio.repeatsandroid.R; import com.rootekstudio.repeatsandroid.RepeatsHelper; import com.rootekstudio.repeatsandroid.database.RepeatsDatabase; import com.rootekstudio.repeatsandroid.mainpage.MainActivity; import com.rootekstudio.repeatsandroid.notifications.NotificationInfo; import com.rootekstudio.repeatsandroid.notifications.NotificationsScheduler; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Scanner; public class EditNotificationsForSetActivity extends AppCompatActivity { LinearLayout hoursLinear; boolean is24HourFormat; int mode; Chip mondayChip; Chip tuesdayChip; Chip wednesdayChip; Chip thursdayChip; Chip fridayChip; Chip saturdayChip; Chip sundayChip; String setID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); is24HourFormat = android.text.format.DateFormat.is24HourFormat(this); setContentView(R.layout.activity_edit_notifications_for_set); getSupportActionBar().setDisplayHomeAsUpEnabled(true); RelativeLayout relativeSwitch = findViewById(R.id.relativeSwitchNotifications); Switch notificationsSwitch = findViewById(R.id.notificationsSwitch); mondayChip = findViewById(R.id.mondayChip); tuesdayChip = findViewById(R.id.tuesdayChip); wednesdayChip = findViewById(R.id.wednesdayChip); thursdayChip = findViewById(R.id.thursdayChip); fridayChip = findViewById(R.id.fridayChip); saturdayChip = findViewById(R.id.saturdayChip); sundayChip = findViewById(R.id.sundayChip); Button addHorus = findViewById(R.id.addHoursButton); hoursLinear = findViewById(R.id.hoursLinearNotificationsSettings); List<String> hoursList = new ArrayList<>(); setID = getIntent().getStringExtra("setID"); if(getIntent().getBooleanExtra("fromSettings", false)) { relativeSwitch.setVisibility(View.GONE); } NotificationInfo notificationInfo = RepeatsDatabase.getInstance(this).singleSetNotificationInfo(setID); String daysOfWeek = notificationInfo.getDaysOfWeek(); String hours = notificationInfo.getHours(); String defaultFrom = "08:00"; String defaultTo = "20:00"; relativeSwitch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { notificationsSwitch.setChecked(!notificationsSwitch.isChecked()); } }); if (notificationInfo.getMode() == 0) { mode = 0; notificationsSwitch.setChecked(false); } else if (notificationInfo.getMode() == 1) { mode = 1; notificationsSwitch.setChecked(true); } if(getIntent().getBooleanExtra("requestedTurnOn", false)) { mode = 1; } notificationsSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { mode = 1; } else { mode = 0; } } }); addHorus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addHourLayout(defaultFrom, defaultTo); } }); if (daysOfWeek == null) { mondayChip.setChecked(true); tuesdayChip.setChecked(true); wednesdayChip.setChecked(true); thursdayChip.setChecked(true); fridayChip.setChecked(true); saturdayChip.setChecked(true); sundayChip.setChecked(true); addHourLayout(defaultFrom, defaultTo); } else { if (daysOfWeek.contains("1")) { sundayChip.setChecked(true); } if (daysOfWeek.contains("2")) { mondayChip.setChecked(true); } if (daysOfWeek.contains("3")) { tuesdayChip.setChecked(true); } if (daysOfWeek.contains("4")) { wednesdayChip.setChecked(true); } if (daysOfWeek.contains("5")) { thursdayChip.setChecked(true); } if (daysOfWeek.contains("6")) { fridayChip.setChecked(true); } if (daysOfWeek.contains("7")) { saturdayChip.setChecked(true); } Scanner scannerHours = new Scanner(hours); while (scannerHours.hasNextLine()) { hoursList.add(scannerHours.nextLine()); } for(int i = 0; i < hoursList.size(); i++) { String from = hoursList.get(i).substring(0,5); String to = hoursList.get(i).substring(6,11); addHourLayout(from, to); } } } void addHourLayout(String from, String to) { View viewHours = LayoutInflater.from(this).inflate(R.layout.hours_layout, hoursLinear, false); Button editFromButton = viewHours.findViewById(R.id.editFrom); Button editToButton = viewHours.findViewById(R.id.editTo); ImageButton deleteButton = viewHours.findViewById(R.id.deleteHour); if (is24HourFormat) { editFromButton.setText(from); editToButton.setText(to); } else { editFromButton.setText(h24Toh12Converter(from)); editToButton.setText(h24Toh12Converter(to)); } editFromButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { timePicker((Button) v); } }); editToButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { timePicker((Button) v); } }); deleteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (hoursLinear.getChildCount() != 1) { hoursLinear.removeView((View) v.getParent()); } } }); hoursLinear.addView(viewHours); } public void cancelClick(View view) { onBackPressed(); } public void saveClick(View view) { NotificationInfo saveNewNotificationInfo = new NotificationInfo(); saveNewNotificationInfo.setMode(mode); String days = ""; if (sundayChip.isChecked()) { days += "1" + RepeatsHelper.breakLine; } if (mondayChip.isChecked()) { days += "2" + RepeatsHelper.breakLine; } if (tuesdayChip.isChecked()) { days += "3" + RepeatsHelper.breakLine; } if (wednesdayChip.isChecked()) { days += "4" + RepeatsHelper.breakLine; } if (thursdayChip.isChecked()) { days += "5" + RepeatsHelper.breakLine; } if (fridayChip.isChecked()) { days += "6" + RepeatsHelper.breakLine; } if (saturdayChip.isChecked()) { days += "7" + RepeatsHelper.breakLine; } if(days.equals("")) { Toast.makeText(this, getString(R.string.select_at_least_one_day), Toast.LENGTH_LONG).show(); return; } saveNewNotificationInfo.setDaysOfWeek(days); StringBuilder hours = new StringBuilder(); for (int i = 0; i < hoursLinear.getChildCount(); i++) { RelativeLayout rl = (RelativeLayout) hoursLinear.getChildAt(i); Button fromButton = rl.findViewById(R.id.editFrom); Button toButton = rl.findViewById(R.id.editTo); String fromTime; String toTime; if(!is24HourFormat) { fromTime = h12Toh24Converter(fromButton.getText().toString()); toTime = h12Toh24Converter(toButton.getText().toString()); } else { fromTime = fromButton.getText().toString(); toTime = toButton.getText().toString(); } hours.append(fromTime).append("-").append(toTime).append(RepeatsHelper.breakLine); } saveNewNotificationInfo.setHours(hours.toString()); saveNewNotificationInfo.setSetID(setID); RepeatsDatabase.getInstance(this).updateSingleSetNotificationInfo(saveNewNotificationInfo); NotificationsScheduler.restartNotifications(this); onBackPressed(); } String h24Toh12Converter(String time) { SimpleDateFormat h12Format = new SimpleDateFormat("hh:mm a"); SimpleDateFormat h24Format = new SimpleDateFormat("HH:mm"); Date date = null; try { date = h24Format.parse(time); } catch (ParseException e) { e.printStackTrace(); } return h12Format.format(date); } String h12Toh24Converter(String time) { SimpleDateFormat h12Format = new SimpleDateFormat("hh:mm a"); SimpleDateFormat h24Format = new SimpleDateFormat("HH:mm"); Date date = null; try { date = h12Format.parse(time); } catch (ParseException e) { e.printStackTrace(); } return h24Format.format(date); } void timePicker(Button button) { TimePickerDialog.OnTimeSetListener timeSetListener = new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hour, int minute) { String stringHour; String stringMinute; if (hour <= 9) { stringHour = "0" + hour; } else { stringHour = String.valueOf(hour); } if (minute <= 9) { stringMinute = "0" + minute; } else { stringMinute = String.valueOf(minute); } String time = stringHour + ":" + stringMinute; View parent = (View)button.getParent(); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); long fromMillis = 0; long toMillis = 0; if(button == parent.findViewById(R.id.editFrom)) { calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, minute); fromMillis = calendar.getTimeInMillis(); Button toButton = parent.findViewById(R.id.editTo); String toTime = toButton.getText().toString(); calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(toTime.substring(0,2))); calendar.set(Calendar.MINUTE, Integer.parseInt(toTime.substring(3,5))); toMillis = calendar.getTimeInMillis(); } else if(button == parent.findViewById(R.id.editTo)) { calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, minute); toMillis = calendar.getTimeInMillis(); Button toButton = parent.findViewById(R.id.editFrom); String toTime = toButton.getText().toString(); calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(toTime.substring(0,2))); calendar.set(Calendar.MINUTE, Integer.parseInt(toTime.substring(3,5))); fromMillis = calendar.getTimeInMillis(); } if(fromMillis > toMillis) { Toast.makeText(button.getContext(), getString(R.string.from_not_greater_than_to), Toast.LENGTH_LONG).show(); return; } else if(fromMillis == toMillis) { Toast.makeText(button.getContext(), getString(R.string.from_to_cannot_be_same), Toast.LENGTH_SHORT).show(); return; } if (is24HourFormat) { button.setText(time); } else { button.setText(h24Toh12Converter(time)); } } }; int oldHour; int oldMinute; if (is24HourFormat) { oldHour = Integer.parseInt(button.getText().toString().substring(0, 2)); } else { oldHour = Integer.parseInt(h12Toh24Converter(button.getText().toString()).substring(0, 2)); } oldMinute = Integer.parseInt(button.getText().toString().substring(3, 5)); TimePickerDialog timePickerDialog = new TimePickerDialog(this, timeSetListener, oldHour, oldMinute, is24HourFormat); timePickerDialog.show(); } public void changeFrequencyClick(View view) { Intent intent = new Intent(this, MainActivity.class); intent.putExtra("showSettings", true); startActivity(intent); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); } return true; } }<file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/reminders/SetTestDate.java package com.rootekstudio.repeatsandroid.reminders; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; import com.applandeo.materialcalendarview.CalendarView; import com.applandeo.materialcalendarview.exceptions.OutOfDateRangeException; import com.rootekstudio.repeatsandroid.R; import com.rootekstudio.repeatsandroid.database.RepeatsDatabase; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Objects; public class SetTestDate { PopupWindow popupWindow; public SetTestDate(View view, String setID, boolean isSettings) throws OutOfDateRangeException, ParseException { ReminderInfo reminderInfo = RepeatsDatabase.getInstance(view.getContext()).getInfoAboutReminderFromCalendar(setID); View popupView = LayoutInflater.from(view.getContext()).inflate(R.layout.calendar_picker, null); CalendarView calendarView = popupView.findViewById(R.id.calendarViewReminders); Button cancel = popupView.findViewById(R.id.cancelPopupTestDate); Button save = popupView.findViewById(R.id.saveTestDate); if(reminderInfo.getDeadline() != null) { Calendar deadlineCalendar = Calendar.getInstance(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); deadlineCalendar.setTime(Objects.requireNonNull(simpleDateFormat.parse(reminderInfo.getDeadline()))); calendarView.setDate(deadlineCalendar); } cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { popupWindow.dismiss(); } }); save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar selectedDate = calendarView.getFirstSelectedDate(); if (selectedDate.getTimeInMillis() < Calendar.getInstance().getTimeInMillis()) { Toast.makeText(view.getContext(), v.getContext().getString(R.string.invalid_date), Toast.LENGTH_LONG).show(); return; } int day = selectedDate.get(Calendar.DAY_OF_MONTH); int month = selectedDate.get(Calendar.MONTH) + 1; int year = selectedDate.get(Calendar.YEAR); String dayString = String.valueOf(day); String monthString = String.valueOf(month); String yearString = String.valueOf(year); if (day < 10) { dayString = "0" + day; } if (month < 10) { monthString = "0" + month; } String deadlineDate = yearString + "-" + monthString + "-" + dayString; RepeatsDatabase.getInstance(view.getContext()).updateTestDate(setID, deadlineDate); View parent = (ViewGroup)view.getParent(); TextView textView = parent.findViewById(R.id.testDate); textView.setText(view.getContext().getString(R.string.test_date, DateFormat.getDateInstance().format(selectedDate.getTime()))); if(reminderInfo.getDeadline() != null) { if(selectedDate.getTimeInMillis() - reminderInfo.getReminderDaysBefore() * 1000 * 60 * 60 * 24 < Calendar.getInstance().getTimeInMillis()) { Toast.makeText(v.getContext(), v.getContext().getString(R.string.date_not_compatible), Toast.LENGTH_LONG).show(); if(isSettings) { View viewParent = (View)view.getParent(); Switch switchReminder = viewParent.findViewById(R.id.reminderSwitchSettings); switchReminder.setChecked(false); } else { TextView reminderStatus = parent.getRootView().findViewById(R.id.reminderStatus); reminderStatus.setText(view.getContext().getResources().getString(R.string.reminder_not_set)); reminderStatus.setTextColor(view.getContext().getResources().getColor(R.color.redRepeats)); } RepeatsDatabase.getInstance(view.getContext()).updateReminderEnabled(setID, false); } } popupWindow.dismiss(); } }); popupWindow = new PopupWindow(popupView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true); popupWindow.setAnimationStyle(R.style.animation); popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0); } } <file_sep>/app/src/main/java/com/rootekstudio/repeatsandroid/Backup.java package com.rootekstudio.repeatsandroid; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.view.LayoutInflater; import android.view.View; import android.widget.RelativeLayout; import android.widget.Toast; import androidx.appcompat.app.AlertDialog; import androidx.documentfile.provider.DocumentFile; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.rootekstudio.repeatsandroid.database.RepeatsDatabase; import com.rootekstudio.repeatsandroid.database.SaveShared; import com.rootekstudio.repeatsandroid.database.SingleSetInfo; import java.io.File; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; public class Backup { public static void createBackup(final Context context, final Activity activity) { RepeatsDatabase DB = RepeatsDatabase.getInstance(context); final MaterialAlertDialogBuilder ALERTbuilder = new MaterialAlertDialogBuilder(context); LayoutInflater layoutInflater = LayoutInflater.from(context); final View view1 = layoutInflater.inflate(R.layout.where_backup, null); ALERTbuilder.setView(view1); ALERTbuilder.setTitle(R.string.where_Backup); ALERTbuilder.setBackground(context.getDrawable(R.drawable.dialog_shape)); final AlertDialog alert = ALERTbuilder.show(); RelativeLayout relCloud = view1.findViewById(R.id.relCloud); RelativeLayout relLocal = view1.findViewById(R.id.relLocal); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { relLocal.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE); activity.startActivityForResult(intent, RequestCodes.PICK_CATALOG); alert.dismiss(); } }); } else { relLocal.setVisibility(View.INVISIBLE); } relCloud.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { alert.dismiss(); List<SingleSetInfo> list = DB.allSetsInfo(-1); final ArrayList<String> names = new ArrayList<>(); final ArrayList<String> setsID = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { SingleSetInfo item = list.get(i); names.add(item.getSetName()); setsID.add(item.getSetID()); } final AlertDialog dialog = UIHelper.loadingDialog(context.getString(R.string.loading), activity); Thread thread = new Thread(new Runnable() { @Override public void run() { SetToFile.saveSetsToFile(context, setsID, names); Uri zipUri = Uri.fromFile(SetToFile.zipFile); OutputStream outputStream = null; try { outputStream = context.getContentResolver().openOutputStream(zipUri); } catch (FileNotFoundException e) { e.printStackTrace(); } ZipSet.zip(SetToFile.filesToShare, outputStream); RepeatsHelper.shareSets(context, activity); activity.runOnUiThread(new Runnable() { @Override public void run() { dialog.dismiss(); } }); } }); thread.start(); } }); } public static void selectFileToRestore(Context context, Activity activity) { Intent zipPickerIntent = new Intent(Intent.ACTION_GET_CONTENT); zipPickerIntent.setType("application/zip"); try { activity.startActivityForResult(zipPickerIntent, RequestCodes.SELECT_FILE_TO_RESTORE); } catch (ActivityNotFoundException e) { Toast.makeText(context, R.string.explorerNotFound, Toast.LENGTH_LONG).show(); } } public static void saveBackupLocally(final Context context, Intent data, final Activity activity) { Uri selectedUri = data.getData(); final DocumentFile pickedDir = DocumentFile.fromTreeUri(context, selectedUri); String fileName = SetToFile.fileName; final AlertDialog dialog = UIHelper.loadingDialog(context.getString(R.string.loading), activity); Thread thread = new Thread(new Runnable() { @Override public void run() { List<SingleSetInfo> list = RepeatsDatabase.getInstance(context).allSetsInfo(-1); ArrayList<String> names = new ArrayList<>(); ArrayList<String> setsID = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { SingleSetInfo item = list.get(i); names.add(item.getSetName()); setsID.add(item.getSetID()); } SetToFile.saveSetsToFile(context, setsID, names); DocumentFile docFile = null; if (pickedDir != null) { docFile = pickedDir.createFile("application/zip", SetToFile.fileName); } OutputStream outputStream = null; try { outputStream = context.getContentResolver().openOutputStream(docFile.getUri()); } catch (FileNotFoundException e) { e.printStackTrace(); } ZipSet.zip(SetToFile.filesToShare, outputStream); activity.runOnUiThread(new Runnable() { @Override public void run() { dialog.dismiss(); Toast.makeText(context, R.string.backup_created, Toast.LENGTH_LONG).show(); } }); } }); thread.start(); } public static void restoreBackup(final Context context, Intent data, final Activity activity) { Uri selectedZip = data.getData(); final AlertDialog dialog = UIHelper.loadingDialog(context.getString(R.string.loading), activity); try { final InputStream inputStream = context.getContentResolver().openInputStream(selectedZip); Thread thread = new Thread(new Runnable() { @Override public void run() { ZipSet.UnZip(inputStream, new File(context.getFilesDir(), "shared")); SaveShared.SaveSetsToDB(context, RepeatsDatabase.getInstance(context)); activity.runOnUiThread(new Runnable() { @Override public void run() { dialog.dismiss(); Toast.makeText(context, R.string.backup_restored, Toast.LENGTH_LONG).show(); } }); } }); thread.start(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
f9174c81a1a60158ae7a78ee79415e4e544619ec
[ "Markdown", "Java", "Gradle" ]
39
Java
jakub-sieradzki/RepeatsJava
10d4eca08378d58b9506bd559c9ea691814428ca
e77a829e568a1c204072b860c78ab53225a85f81
refs/heads/master
<repo_name>ririkat/boxman<file_sep>/src/main/java/com/spring/bm/apv/model/service/ApvServiceImpl.java package com.spring.bm.apv.model.service; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.spring.bm.apv.model.dao.ApvDao; import com.spring.bm.calendar.model.vo.Calendar; @Service public class ApvServiceImpl implements ApvService { @Autowired ApvDao dao; @Autowired SqlSessionTemplate session; /*결재양식*/ @Override public int insertApvDoc(Map<String, Object> param) throws Exception{ int result=0; result=dao.insertApvDoc(session,param); if(result == 0) throw new Exception(); return result; } @Override public List<Map<String, Object>> selectDocCate() { return dao.selectDocCate(session); } @Override public List<Map<String, Object>> selectDocCCate() { return dao.selectDocCCate(session); } @Override public List<Map<String, Object>> selectDocHCate() { return dao.selectDocHCate(session); } @Override public List<Map<String, Object>> selectDocForm(int cPage, int numPerPage) { return dao.selectDocForm(session,cPage,numPerPage); } @Override public int selectDfCount() { return dao.selectDfCount(session); } @Override public Map<String, Object> selectDfModi(int dfNo) { return dao.selectDfModi(session,dfNo); } @Override public int updateApvDoc(Map<String, Object> param) throws Exception { int result=0; result=dao.updateApvDoc(session,param); if(result == 0) throw new Exception(); return result; } @Override public int deleteApvDoc(int dfNo) throws Exception { int result=0; result=dao.deleteApvDoc(session,dfNo); if(result == 0) throw new Exception(); return result; } @Override public int insertApvDocHead(Map<String, Object> param) throws Exception { int result=0; result=dao.insertApvDocHead(session,param); if(result == 0) throw new Exception(); return result; } @Override public int insertApvDocContent(Map<String, Object> param) throws Exception { int result=0; result=dao.insertApvDocContent(session,param); if(result == 0) throw new Exception(); return result; } @Override public String selectDfhContent(int no) { return dao.selectDfhContent(session,no); } @Override public String selectDfcContent(int no) { return dao.selectDfcContent(session,no); } /*결재라인*/ @Override public List<Map<String, Object>> selectDeptList() { return dao.selectDeptList(session); } @Override public List<Map<String, Object>> selectMyApvLineList(int cPage, int numPerPage,int loginNo) { return dao.selectMyApvLineList(session,cPage,numPerPage,loginNo); } @Override public int selectMyALCount(int loginNo) { return dao.selectMyALCount(session,loginNo); } @Override public List<Map<String, Object>> selectDeptToEmp(int deptNo) { return dao.selectDeptToEmp(session,deptNo); } @Override public int insertApvLine(Map<String, Object> param) throws Exception { int result=0; result=dao.insertApvLine(session,param); if(result==0) throw new Exception(); //트랜잭션 처리하기 ArrayList list=(ArrayList) param.get("selOpts"); int pno=1; int curr=Integer.parseInt((String) param.get("apvlNo")); for(int i=0; i<list.size(); i++) { Map<String,Object> param2=new HashMap<String,Object>(); param2.put("priorNo",pno); param2.put("empNo",Integer.parseInt(list.get(i).toString())); param2.put("apvlNo",curr); result=dao.insertApvlApplicant(session,param2); pno++; if(result==0) throw new Exception(); } return result; } @Override public int deleteApvLine(int alNo) throws Exception{ int result=dao.deleteApvlApplicant(session,alNo); if(result==0) throw new Exception(); result=dao.deleteApvLine(session,alNo); return result; } @Override public Map<String, Object> selectALModi(int alno) { return dao.selectALModi(session,alno); } @Override public List selectALApplicants(int alno) { return dao.selectALApplicants(session,alno); } @Override public int updateApvLine(Map<String, Object> param) throws Exception { int result=0; /*결재라인 자체테이블 수정*/ result=dao.updateApvLine(session,param); if(result==0) throw new Exception(); //트랜잭션 처리하기 /*기존 결재자들 삭제*/ result=dao.deleteApvlApplicants(session,param); if(result==0) throw new Exception(); /*새로 입력된 결재라인으로 등록*/ ArrayList list=(ArrayList) param.get("selOpts"); int pno=1; int curr=Integer.parseInt((String) param.get("apvlNo")); for(int i=0; i<list.size(); i++) { Map<String,Object> param2=new HashMap<String,Object>(); param2.put("priorNo",pno); param2.put("empNo",Integer.parseInt(list.get(i).toString())); param2.put("apvlNo",curr); result=dao.insertApvlApplicant(session,param2); pno++; if(result==0) throw new Exception(); } return result; } @Override public Map<String, Object> selectEmpInfoAll(Map<String, Object> param) { return dao.selectEmpInfoAll(session,param); } @Override public int insertRequestApv(Map<String, Object> param) throws Exception{ int result=0; result=dao.insertRequestApv(session,param); if(result==0) throw new Exception(); int apvNo=Integer.parseInt((String) param.get("apvNo")); //결재자,시행자,참조자 넣는 로직 if((param.get("apvLA"))!=null&&((ArrayList) param.get("apvLA")).size()>0) { int pno=1; ArrayList listA=(ArrayList) param.get("apvLA"); for(int i=0; i<listA.size(); i++) { Map<String,Object> param2=new HashMap<String,Object>(); param2.put("priorNo",pno); param2.put("empNo",Integer.parseInt(listA.get(i).toString())); param2.put("apvNo",apvNo); result=dao.insertApvApplicant(session,param2); pno++; if(result==0) throw new Exception(); } } if((param.get("apvLR"))!=null&&((ArrayList) param.get("apvLR")).size()>0) { int pno=1; ArrayList listR=(ArrayList) param.get("apvLR"); for(int i=0; i<listR.size(); i++) { Map<String,Object> param2=new HashMap<String,Object>(); param2.put("priorNo",pno); param2.put("empNo",Integer.parseInt(listR.get(i).toString())); param2.put("apvNo",apvNo); result=dao.insertApvReferer(session,param2); pno++; if(result==0) throw new Exception(); } } if(param.get("apvLE")!=null&&!((String.valueOf(param.get("apvLE"))).equals(""))) { System.out.println("들어오니?"); String apvE=String.valueOf(param.get("apvLE")); System.out.println(apvE); Map<String,Object> param2=new HashMap<String,Object>(); param2.put("empNo",Integer.parseInt(apvE)); param2.put("apvNo",apvNo); result=dao.insertApvEnforcer(session,param2); if(result==0) throw new Exception(); } return result; } /*상신함 리스트 불러오기*/ @Override public List<Map<String, Object>> selectSendApvList(int cPage, int numPerPage,int loginNo) { return dao.selectSendApvList(session,cPage,numPerPage,loginNo); } @Override public int selectSendApvCount(int loginNo) { return dao.selectSendApvCount(session,loginNo); } //상신함 -> 조회 뷰 @Override public Map<String, Object> selectLookupApv(int apvNo) { return dao.selectLookupApv(session,apvNo); } /*수신함 리스트 불러오기*/ @Override public List<Map<String, Object>> selectReceiveApvList(int cPage, int numPerPage, int loginNo) { return dao.selectReceiveApvList(session, cPage, numPerPage, loginNo); } @Override public int selectReceiveApvCount(int loginNo) { return dao.selectReceiveApvCount(session,loginNo); } /*시행함 리스트 불러오기*/ @Override public List<Map<String, Object>> selectEnforceApvList(int cPage, int numPerPage, int loginNo) { return dao.selectEnforceApvList(session, cPage, numPerPage, loginNo); } @Override public int selectEnforceApvCount(int loginNo) { return dao.selectEnforceApvCount(session,loginNo); } /*참조함 리스트 불러오기*/ @Override public List<Map<String, Object>> selectReferApvList(int cPage, int numPerPage, int loginNo) { return dao.selectReferApvList(session, cPage, numPerPage, loginNo); } @Override public int selectReferApvCount(int loginNo) { return dao.selectReferApvCount(session,loginNo); } /*참조함 -> 열람 뷰*/ @Override public Map<String, Object> selectLookupApvR(Map<String, Object> param) { return dao.selectLookupApvR(session,param); } @Override public int updateReferYN(Map<String, Object> param) throws Exception { int result=0; result=dao.updateReferYN(session,param); if(result==0) throw new Exception(); return result; } /*수신결재함 -> 결재하기*/ @Override public Map<String, Object> selectLookupApvA(Map<String, Object> param) { return dao.selectLookupApvA(session,param); } /*결재하기 -> 개인결재승인처리*/ @Override public int apvPermit(Map<String, Object> param) throws Exception{ int result=0; //먼저, 해당 결재문서에 결재자들 총 인원을 불러옴 result=dao.selectApvACount(session,param); int allCount=result; //개인을 전결처리시킴 result=dao.apvPermit(session,param); if(result==0) throw new Exception(); //총 인원과 현재 턴 번호가 일치하면 전체 종결상태가 되도록 , if(Integer.parseInt(String.valueOf(param.get("priorNo"))) ==allCount) { result=dao.updateApvPermitAll(session,param); }else { //아니라면 진행상태로 update 하고, currturn +1함. result=dao.updateApvPermit(session,param); } return result; } //도장 이미지 가져오기 @Override public Map<String, Object> selectStamp(Map<String, Object> param) { return dao.selectStamp(session,param); } /*결재하기 -> 반려하기*/ @Override public int apvReturn(Map<String, Object> param) throws Exception { int result=0; result=dao.apvAReturn(session,param); if(result==0) throw new Exception(); result=dao.updateApvReturn(session,param); if(result==0) throw new Exception(); return result; } /*시행함 -> 시행관리 뷰*/ @Override public Map<String, Object> selectLookupApvEOne(Map<String, Object> param) { return dao.selectLookupApvEOne(session,param); } /*시행관리뷰 -> 시행처리하기*/ @Override public int apvEnforce(Map<String, Object> param) throws Exception { // 개인 시행 처리하기 int result=0; result=dao.updateApvEEnforce(session,param); if(result==0) throw new Exception(); // 문서 시행처리하기 result=dao.updateApvEnforce(session,param); if(result==0) throw new Exception(); return result; } @Override public int apvEReturn(Map<String, Object> param) throws Exception { int result=0; result=dao.apvEEReturn(session,param); if(result==0) throw new Exception(); result=dao.updateApvEReturn(session,param); if(result==0) throw new Exception(); return result; } //비니꺼 추가결재 @Override public int apvAddPermit1(Map<String, Object> param) throws Exception { int result=0; //먼저, 해당 결재문서에 결재자들 총 인원을 불러옴 result=dao.selectApvACount(session,param); int allCount=result; //개인을 전결처리시킴 result=dao.apvPermit(session,param); if(result==0) throw new Exception(); //총 인원과 현재 턴 번호가 일치하면 전체 종결상태가 되도록 , if(Integer.parseInt(String.valueOf(param.get("priorNo"))) ==allCount) { result=dao.updateApvPermitAll(session,param); if(result==0) throw new Exception(); result=dao.updateAddApv(session,param); if(result==0) throw new Exception(); }else { //아니라면 진행상태로 update 하고, currturn +1함. result=dao.updateApvPermit(session,param); if(result==0) throw new Exception(); } return result; } //더기꺼 추가결재 @Override public int apvAddPermit2(Map<String, Object> param) throws Exception { int result=0; //먼저, 해당 결재문서에 결재자들 총 인원을 불러옴 result=dao.selectApvACount(session,param); int allCount=result; //개인을 전결처리시킴 result=dao.apvPermit(session,param); if(result==0) throw new Exception(); //총 인원과 현재 턴 번호가 일치하면 전체 종결상태가 되도록 , if(Integer.parseInt(String.valueOf(param.get("priorNo"))) ==allCount) { result=dao.updateApvPermitAll(session,param); if(result==0) throw new Exception(); result=dao.updateAddApv2(session,param); if(result==0) throw new Exception(); }else { //아니라면 진행상태로 update 하고, currturn +1함. result=dao.updateApvPermit(session,param); if(result==0) throw new Exception(); } return result; } @Override public int apvSaveUpdate(Map<String, Object> param) throws Exception { int result=0; result=dao.apvSaveUpdate(session,param); if(result==0) throw new Exception(); return result; } /*결재양식 검색*/ @Override public List<Map<String, String>> selectDfSearchList(int cPage, int numPerPage, Map<String, Object> param) { return dao.selectDfSearchList(session,cPage,numPerPage,param); } @Override public int selectDfSearchCount(Map<String, Object> param) { return dao.selectDfSearchCount(session,param); } /*결재라인 검색*/ @Override public List<Map<String, String>> selectApvlSearchList(int cPage, int numPerPage, Map<String, Object> param) { return dao.selectApvlSearchList(session,cPage,numPerPage,param); } @Override public int selectApvlSearchCount(Map<String, Object> param) { return dao.selectApvlSearchCount(session,param); } /*메인출력용*/ @Override public List<Map<String, Object>> selectApvList2(int empNo) { return dao.selectApvList2(session,empNo); } } <file_sep>/src/main/java/com/spring/bm/sale/model/dao/SaleDao.java package com.spring.bm.sale.model.dao; import java.util.List; import java.util.Map; import org.mybatis.spring.SqlSessionTemplate; public interface SaleDao { List<Map<String, String>> selectSaleList(SqlSessionTemplate session, int cPage, int numPerPage); int selectSaleCount(SqlSessionTemplate session); List<Map<String, String>> selectConnList(SqlSessionTemplate session); int enrollSaleInfo(SqlSessionTemplate session, Map<String, Object> param); int enrollSaleItem(SqlSessionTemplate session, Map<String,Object> paramMap); List<Map<String, String>> selectSaleSearchList(SqlSessionTemplate session, Map<String, Object> m); int selectSaleSearchCount(SqlSessionTemplate session, Map<String, Object> m); Map<String, String> selectSaleInfo(SqlSessionTemplate session, int salCode); List<Map<String, String>> selectSaleItemList(SqlSessionTemplate session, int salCode); Map<String, Object> selectSalOne(SqlSessionTemplate session, Map<String, Object> param); } <file_sep>/src/main/java/com/spring/bm/department/model/dao/DepartmentDaoImpl.java package com.spring.bm.department.model.dao; import java.util.List; import java.util.Map; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.stereotype.Repository; @Repository public class DepartmentDaoImpl implements DepartmentDao { /* 부서등록 */ @Override public int insertDept(SqlSessionTemplate session, Map<String, String> param) { // TODO Auto-generated method stub return session.insert("dept.insertDept", param); } /* 부서리스트 출력 */ @Override public List<Map<String, String>> selectDeptList(SqlSessionTemplate session) { // TODO Auto-generated method stub return session.selectList("dept.selectDeptList"); } /* 부서수정 */ @Override public int updateDept(SqlSessionTemplate session, Map<String, Object> map) { // TODO Auto-generated method stub return session.update("dept.updateDept", map); } /* 부서상세 */ @Override public Map<String, Object> selectDeptOne(SqlSessionTemplate session, int deptNo) { // TODO Auto-generated method stub return session.selectOne("dept.selectDeptOne", deptNo); } } <file_sep>/src/main/java/com/spring/bm/notice/model/vo/UploadNotice.java package com.spring.bm.notice.model.vo; import lombok.Data; @Data public class UploadNotice { private int upNoticeNo; private int nNo; private String upNoticeOrgName; private String upNoticeReName; public UploadNotice(int upNoticeNo, int nNo, String upNoticeOrgName, String upNoticeReName) { super(); this.upNoticeNo = upNoticeNo; this.nNo = nNo; this.upNoticeOrgName = upNoticeOrgName; this.upNoticeReName = upNoticeReName; } public UploadNotice() { // TODO Auto-generated constructor stub } } <file_sep>/src/main/java/com/spring/bm/common/Log4JTest.java package com.spring.bm.common; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Log4JTest { // log4J를 적용하기 위해서는 Logger 객체를 이용한다. private static Logger logger = LoggerFactory.getLogger(Log4JTest.class); // 이게 log4j를 생성하는 방식! public static void main(String[] args) { Log4JTest.test(); } public static void test() { logger.debug("Debug 야!"); logger.info("info 야!"); logger.warn("warn 야!"); logger.error("erro 야!"); } } <file_sep>/src/main/java/com/spring/bm/apv/model/dao/ApvDaoImpl.java package com.spring.bm.apv.model.dao; import java.util.List; import java.util.Map; import org.apache.ibatis.session.RowBounds; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.stereotype.Repository; import com.spring.bm.calendar.model.vo.Calendar; @Repository public class ApvDaoImpl implements ApvDao { /*결재양식*/ @Override public int insertApvDoc(SqlSessionTemplate session, Map<String, Object> param) { return session.insert("apv.insertApvDoc", param); } @Override public List<Map<String, Object>> selectDocCate(SqlSessionTemplate session) { return session.selectList("apv.selectDocCate"); } @Override public List<Map<String, Object>> selectDocCCate(SqlSessionTemplate session) { return session.selectList("apv.selectDocCCate"); } @Override public List<Map<String, Object>> selectDocHCate(SqlSessionTemplate session) { return session.selectList("apv.selectDocHCate"); } @Override public List<Map<String, Object>> selectDocForm(SqlSessionTemplate session,int cPage, int numPerPage) { RowBounds rows = new RowBounds((cPage-1) * numPerPage, numPerPage); return session.selectList("apv.selectDocForm", null, rows); } @Override public int selectDfCount(SqlSessionTemplate session) { return session.selectOne("apv.selectDfCount"); } @Override public Map<String, Object> selectDfModi(SqlSessionTemplate session, int dfNo) { return session.selectOne("apv.selectDfModi",dfNo); } @Override public int updateApvDoc(SqlSessionTemplate session, Map<String, Object> param) { return session.update("apv.updateApvDoc",param); } @Override public int deleteApvDoc(SqlSessionTemplate session, int dfNo) { return session.delete("apv.deleteApvDoc",dfNo); } @Override public int insertApvDocHead(SqlSessionTemplate session, Map<String, Object> param) { return session.insert("apv.insertApvDocHead",param); } @Override public int insertApvDocContent(SqlSessionTemplate session, Map<String, Object> param) { return session.insert("apv.insertApvDocContent",param); } @Override public String selectDfhContent(SqlSessionTemplate session, int no) { Map<String,String> map=session.selectOne("apv.selectDfhContent",no); String result=map.get("DFHCONTENT"); return result; } @Override public String selectDfcContent(SqlSessionTemplate session, int no) { Map<String,String> map=session.selectOne("apv.selectDfcContent",no); String result=map.get("DFCCONTENT"); return result; } /*결재라인*/ @Override public List<Map<String, Object>> selectDeptList(SqlSessionTemplate session) { return session.selectList("apv.selectDeptList"); } @Override public List<Map<String, Object>> selectMyApvLineList(SqlSessionTemplate session, int cPage, int numPerPage,int loginNo) { RowBounds rows = new RowBounds((cPage-1) * numPerPage, numPerPage); return session.selectList("apv.selectMyApvLineList",loginNo, rows); } @Override public int selectMyALCount(SqlSessionTemplate session, int loginNo) { return session.selectOne("apv.selectMyALCount",loginNo); } @Override public List<Map<String, Object>> selectDeptToEmp(SqlSessionTemplate session, int deptNo) { return session.selectList("apv.selectDeptToEmp",deptNo); } @Override public int insertApvLine(SqlSessionTemplate session, Map<String, Object> param) { return session.insert("apv.insertApvLine",param); } @Override public int insertApvlApplicant(SqlSessionTemplate session, Map<String, Object> param2) { return session.insert("apv.insertApvlApplicant",param2); } @Override public int deleteApvlApplicant(SqlSessionTemplate session, int alNo) { return session.delete("apv.deleteApvlApplicant",alNo); } @Override public int deleteApvLine(SqlSessionTemplate session, int alNo) { return session.delete("apv.deleteApvLine",alNo); } @Override public Map<String, Object> selectALModi(SqlSessionTemplate session, int alno) { return session.selectOne("apv.selectALModi",alno); } @Override public List selectALApplicants(SqlSessionTemplate session, int alno) { return session.selectList("apv.selectALApplicants",alno); } @Override public int updateApvLine(SqlSessionTemplate session, Map<String, Object> param) { return session.update("apv.updateApvLine",param); } @Override public int deleteApvlApplicants(SqlSessionTemplate session, Map<String, Object> param) { return session.delete("apv.deleteApvlApplicants",param); } @Override public Map<String, Object> selectEmpInfoAll(SqlSessionTemplate session, Map<String, Object> param) { return session.selectOne("apv.selectEmpInfoAll",param); } /*기안하기*/ //approval 테이블 @Override public int insertRequestApv(SqlSessionTemplate session, Map<String, Object> param) { return session.insert("apv.insertRequestApv",param); } //apvApplicant 테이블 @Override public int insertApvApplicant(SqlSessionTemplate session, Map<String, Object> param2) { return session.insert("apv.insertApvApplicant",param2); } //apvReferer 테이블 @Override public int insertApvReferer(SqlSessionTemplate session, Map<String, Object> param2) { return session.insert("apv.insertApvReferer",param2); } //apvEnforcer 테이블 @Override public int insertApvEnforcer(SqlSessionTemplate session, Map<String, Object> param2) { return session.insert("apv.insertApvEnforcer",param2); } /*상신함*/ @Override public List<Map<String, Object>> selectSendApvList(SqlSessionTemplate session, int cPage, int numPerPage, int loginNo) { RowBounds rows = new RowBounds((cPage-1) * numPerPage, numPerPage); return session.selectList("apv.selectSendApvList",loginNo, rows); } @Override public int selectSendApvCount(SqlSessionTemplate session, int loginNo) { return session.selectOne("apv.selectSendApvCount",loginNo); } //상신함,참조함 -> 조회 뷰 @Override public Map<String, Object> selectLookupApv(SqlSessionTemplate session, int apvNo) { return session.selectOne("apv.selectLookupApv",apvNo); } /*수신함*/ @Override public List<Map<String, Object>> selectReceiveApvList(SqlSessionTemplate session, int cPage, int numPerPage, int loginNo) { RowBounds rows = new RowBounds((cPage-1) * numPerPage, numPerPage); return session.selectList("apv.selectReceiveApvList",loginNo, rows); } @Override public int selectReceiveApvCount(SqlSessionTemplate session, int loginNo) { return session.selectOne("apv.selectReceiveApvCount",loginNo); } /*시행함*/ @Override public List<Map<String, Object>> selectEnforceApvList(SqlSessionTemplate session, int cPage, int numPerPage, int loginNo) { RowBounds rows = new RowBounds((cPage-1) * numPerPage, numPerPage); return session.selectList("apv.selectEnforceApvList",loginNo, rows); } @Override public int selectEnforceApvCount(SqlSessionTemplate session, int loginNo) { return session.selectOne("apv.selectEnforceApvCount",loginNo); } /*참조함*/ @Override public List<Map<String, Object>> selectReferApvList(SqlSessionTemplate session, int cPage, int numPerPage, int loginNo) { RowBounds rows = new RowBounds((cPage-1) * numPerPage, numPerPage); return session.selectList("apv.selectReferApvList",loginNo, rows); } @Override public int selectReferApvCount(SqlSessionTemplate session, int loginNo) { return session.selectOne("apv.selectReferApvCount",loginNo); } /*참조함 -> 열람 뷰*/ @Override public Map<String, Object> selectLookupApvR(SqlSessionTemplate session, Map<String, Object> param) { return session.selectOne("apv.selectLookupApvR",param); } @Override public int updateReferYN(SqlSessionTemplate session, Map<String, Object> param) { return session.update("apv.updateReferYN",param); } /*수신결재함 -> 결재하기*/ @Override public Map<String, Object> selectLookupApvA(SqlSessionTemplate session, Map<String, Object> param) { return session.selectOne("apv.selectLookupApvA",param); } /*결재하기 -> 개인결재승인처리*/ @Override public int selectApvACount(SqlSessionTemplate session, Map<String, Object> param) { return session.selectOne("apv.selectApvACount",param); } @Override public int apvPermit(SqlSessionTemplate session, Map<String, Object> param) { return session.update("apv.apvPermit",param); } @Override public int updateApvPermitAll(SqlSessionTemplate session, Map<String, Object> param) { return session.update("apv.updateApvPermitAll",param); } @Override public int updateApvPermit(SqlSessionTemplate session, Map<String, Object> param) { return session.update("apv.updateApvPermit",param); } @Override public int updateAddApv2(SqlSessionTemplate session, Map<String, Object> param) { return session.update("apv.updateAddApv2",param); } //도장 @Override public Map<String, Object> selectStamp(SqlSessionTemplate session, Map<String, Object> param) { return session.selectOne("apv.selectStamp",param); } @Override public int apvSaveUpdate(SqlSessionTemplate session, Map<String, Object> param) { return session.update("apv.apvSaveUpdate",param); } /*결재하기 -> 반려하기*/ @Override public int apvAReturn(SqlSessionTemplate session, Map<String, Object> param) { return session.update("apv.apvAReturn",param); } @Override public int updateApvReturn(SqlSessionTemplate session, Map<String, Object> param) { return session.update("apv.updateApvReturn",param); } /*시행함 -> 시행관리 뷰*/ @Override public Map<String, Object> selectLookupApvEOne(SqlSessionTemplate session, Map<String, Object> param) { return session.selectOne("apv.selectLookupApvEOne",param); } /*시행관리뷰 -> 시행처리*/ @Override public int updateApvEEnforce(SqlSessionTemplate session, Map<String, Object> param) { return session.update("apv.updateApvEEnforce",param); } @Override public int updateApvEnforce(SqlSessionTemplate session, Map<String, Object> param) { return session.update("apv.updateApvEnforce",param); } /*시행관리뷰 -> 반송처리*/ @Override public int apvEEReturn(SqlSessionTemplate session, Map<String, Object> param) { return session.update("apv.apvEEReturn",param); } @Override public int updateApvEReturn(SqlSessionTemplate session, Map<String, Object> param) { return session.update("apv.updateApvEReturn",param); } @Override public int updateAddApv(SqlSessionTemplate session, Map<String, Object> param) { return session.update("apv.updateAddApv",param); } /*결재양식 검색*/ @Override public List<Map<String, String>> selectDfSearchList(SqlSessionTemplate session, int cPage, int numPerPage, Map<String, Object> param) { RowBounds rows = new RowBounds((cPage-1) * numPerPage, numPerPage); return session.selectList("apv.selectDfSearchList",param, rows); } @Override public int selectDfSearchCount(SqlSessionTemplate session, Map<String, Object> param) { return session.selectOne("apv.selectDfSearchCount",param); } /*결재라인 검색*/ @Override public List<Map<String, String>> selectApvlSearchList(SqlSessionTemplate session, int cPage, int numPerPage, Map<String, Object> param) { RowBounds rows = new RowBounds((cPage-1) * numPerPage, numPerPage); return session.selectList("apv.selectApvlSearchList",param, rows); } @Override public int selectApvlSearchCount(SqlSessionTemplate session, Map<String, Object> param) { return session.selectOne("apv.selectApvlSearchCount",param); } /*메인출력용*/ @Override public List<Map<String,Object>> selectApvList2(SqlSessionTemplate session, int empNo) { return session.selectList("apv.selectApvList2",empNo); } } <file_sep>/src/main/java/com/spring/bm/chat/model/service/ChatServiceImpl.java package com.spring.bm.chat.model.service; import java.util.List; import java.util.Map; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.spring.bm.chat.model.dao.ChatDao; import com.spring.bm.chat.model.vo.Chat; import com.spring.bm.chat.model.vo.ChatRoom; import com.spring.bm.chatting.RTCMessage; import com.spring.bm.employee.model.vo.Employee; @Service public class ChatServiceImpl implements ChatService { @Autowired ChatDao dao; @Autowired SqlSessionTemplate sqlSession; @Override public List<Map<String, String>> selectChatList() { return dao.selectChatList(sqlSession); } @Override public List<Map<String, String>> selectChatListEmp(int empNo) { return dao.selectChatListEmp(sqlSession, empNo); } @Override public Employee selectChatOneEmp(int empNo) { return dao.selectChatOneEmp(sqlSession, empNo); } @Override public int insertChat(RTCMessage msg) { return dao.insertChat(sqlSession, msg); } @Override public int createChatRoom(Map<String,Object> m) { return dao.createChatRoom(sqlSession, m); } @Override public ChatRoom chatRoom(Map<String, Object> m) { return dao.chatRoom(sqlSession, m); } @Override public ChatRoom selectChatRoom(Map<String, Object> m) { return dao.selectChatRoom(sqlSession,m); } @Override public List<Chat> seletChat(int roomNo) { return dao.selectChat(sqlSession,roomNo); } @Override public int selectEmpno(int receiver) { // TODO Auto-generated method stub return dao.selectEmpno(sqlSession, receiver); } @Override public List<Map<String, String>> searchEmp(String data) { return dao.searchEmp(sqlSession, data); } @Override public int noReadCount(int userId) { return dao.noReadCount(sqlSession, userId); } @Override public int updateReadCount(Map<String, Object> m) { return dao.updateReadCount(sqlSession, m); } @Override public List<Map<String, String>> selectReadCount(Map<String,String> param) { return dao.selectReadCount(sqlSession, param); } } <file_sep>/src/main/java/com/spring/bm/purchase/model/service/PurchaseService.java package com.spring.bm.purchase.model.service; import java.util.List; import java.util.Map; public interface PurchaseService { List<Map<String,String>> selectPurList(int cPage, int numPerPage); int selectPurCount(); List<Map<String,String>> selectConnList(); Map<String,String> addStuffToTemp(String stuffNo); int enrollPurInfo(Map<String, Object> param) throws Exception; List<Map<String,String>> selectPurSearchList(Map<String, Object> m); int selectPurSearchCount(Map<String, Object> m); Map<String,String> selectPurInfo(int purCode); List<Map<String,String>> selectPurItemList(int purCode); Map<String, Object> selectPurOne(Map<String, Object> param); } <file_sep>/src/main/java/com/spring/bm/vc/controller/Sdp.java package com.spring.bm.vc.controller; import lombok.Data; @Data public class Sdp { private String type; private String sdp; } <file_sep>/src/main/java/com/spring/bm/employee/model/service/EmployeeServiceImpl.java package com.spring.bm.employee.model.service; import java.util.List; import java.util.Map; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.spring.bm.employee.model.dao.EmployeeDao; import com.spring.bm.employee.model.vo.EmpFile; @Service public class EmployeeServiceImpl implements EmployeeService { @Autowired EmployeeDao dao; @Autowired SqlSessionTemplate session; /* 사원리스트불러오기 */ @Override public List<Map<String, String>> selectEmpList(int cPage, int numPerPage) { return dao.selectEmpList(session, cPage, numPerPage); } @Override public int selectEmpCount() { // TODO Auto-generated method stub return dao.selectEmpCount(session); } /* 사원리스트불러오기끝 */ /* 사원등록 */ @Override public int insertEmp(Map<String, String> param, List<EmpFile> fileList) throws Exception{ int result = 0; result = dao.insertEmp(session, param); if(result == 0) throw new Exception(); if(fileList.size()>0) { for(EmpFile e : fileList) { e.setEmpNo(Integer.parseInt(param.get("empNo"))); result = dao.insertEmpFile(session, e); if(result == 0) throw new Exception(); } } return result; } /* 사원상세보기 */ @Override public Map<String, Object> selectEmpOne(int empNo) { return dao.selectEmpOne(session, empNo); } @Override public List<EmpFile> selectEmpFileList(int empNo) { // TODO Auto-generated method stub return dao.selectEmpFileList(session, empNo); } /* 사원로그인*/ @Override public Map<String, Object> selectLoginEmp(Map<String, Object> map) { return dao.selectLoginEmp(session,map); } /* 사원검색 */ @Override public List<Map<String, String>> selectEmpSearchList(int cPage, int numPerPage, Map<String, Object> param) { // TODO Auto-generated method stub return dao.selectEmpSearchList(session, cPage, numPerPage, param); } @Override public int selectEmpSearchCount(Map<String, Object> param) { // TODO Auto-generated method stub return dao.selectEmpSearchCount(session, param); } /* 아이디중복확인 */ @Override public int checkId(String empId) { // TODO Auto-generated method stub return dao.checkId(session, empId); } /* 첨부파일삭제 */ @Override public int deleteEmpFile(int efNo) throws Exception{ int result = 0; result = dao.deleteEmpFile(session, efNo); if(result == 0) throw new Exception(); return result; } /* 사원수정 */ @Override public int updateEmp(Map<String, Object> param, List<EmpFile> fileList) throws Exception { int result = 0; result = dao.updateEmp(session, param); if(result == 0) throw new Exception(); if(fileList.size()>0) { for(EmpFile e : fileList) { e.setEmpNo(Integer.parseInt(String.valueOf(param.get("empNo")))); result = dao.insertEmpFile(session, e); if(result == 0) throw new Exception(); } } return result; } /* 비밀번호수정 */ @Override public int updatePassword(Map<String, Object> param) throws Exception { int result = 0; result = dao.updatePassword(session, param); if(result == 0) throw new Exception(); return result; } /* 출퇴근위치정보 확인 */ @Override public int checkLocation(Map<String, Object> param) { // TODO Auto-generated method stub return dao.checkLocation(session, param); } /* 출근등록 */ @Override public int insertGotoWork(Map<String, Object> param) throws Exception { int result = 0; result = dao.insertGotoWork(session, param); if(result == 0) throw new Exception(); return result; } /* 퇴근등록 */ @Override public int updateOffWork(Map<String, Object> param) throws Exception{ int result = 0; result = dao.updateOffWork(session, param); if(result == 0) throw new Exception(); return result; } /* 근태하나보기 */ @Override public Map<String, Object> selectAttenOne(Map<String, Object> param) { // TODO Auto-generated method stub return dao.selectAttenOne(session, param); } /* 근태현황보기 */ @Override public List<Map<String, String>> selectAttenList(Map<String, Object> param, int cPage, int numPerPage) { // TODO Auto-generated method stub return dao.selectAttenList(session, param, cPage, numPerPage); } @Override public int selectAttenCount(Map<String, Object> param) { // TODO Auto-generated method stub return dao.selectAttenCount(session, param); } /* 근태현황보기끝 */ /* 휴가리스트출력 */ @Override public List<Map<String, String>> selectDayOffList(Map<String, Object> param, int cPage, int numPerPage) { // TODO Auto-generated method stub return dao.selectDayOffList(session, param, cPage, numPerPage); } @Override public int selectDayOffCount(Map<String, Object> param) { // TODO Auto-generated method stub return dao.selectDayOffCount(session, param); } /* 휴가리스트출력 끝 */ /* 출장리스트출력 */ @Override public List<Map<String, String>> selectBTList(Map<String, Object> param, int cPage, int numPerPage) { // TODO Auto-generated method stub return dao.selectBTList(session, param, cPage, numPerPage); } @Override public int selectBTCount(Map<String, Object> param) { // TODO Auto-generated method stub return dao.selectBTCount(session, param); } /* 출장리스트출력 끝 */ /* 근태수정용 한개보기 */ @Override public Map<String, Object> selectAttenNoOne(Map<String, Object> param) { // TODO Auto-generated method stub return dao.selectAttenNoOne(session, param); } /* 남은 휴가일수 보기 */ @Override public int selectDoRemaining(Map<String, Object> map) { // TODO Auto-generated method stub return dao.selectDoRemaining(session, map); } /* 휴가신청 */ @Override public int insertDayOff(Map<String, Object> param) throws Exception { int result = 0; result = dao.insertDayOff(session, param); if(result == 0) throw new Exception(); return result; } /* 출장신청 */ @Override public int insertBT(Map<String, Object> param) throws Exception { int result = 0; result = dao.insertBT(session, param); if(result == 0) throw new Exception(); return result; } /* 근태수정 */ @Override public int insertUpAttendance(Map<String, Object> param) throws Exception { int result = 0; result = dao.insertUpAttendance(session, param); if(result == 0) throw new Exception(); return result; } /* 출장비 리스트 */ @Override public List<Map<String, Object>> selectBTPList(Map<String, Object> param) { // TODO Auto-generated method stub return dao.selectBTPList(session, param); } /* 출장 하나 */ @Override public Map<String, Object> selectBTOne(Map<String, Object> param) { // TODO Auto-generated method stub return dao.selectBTOne(session, param); } /* 출장비등록 */ @Override public int insertBTP(Map<String, Object> param) throws Exception { int result = 0; result = dao.insertBTP(session, param); if(result == 0) throw new Exception(); return result; } /* 사원통계 */ @Override public List<Map<String, Object>> empYearCount() { // TODO Auto-generated method stub return dao.empYearCount(session); } @Override public List<Map<String, Object>> newEmpYearCount() { // TODO Auto-generated method stub return dao.newEmpYearCount(session); } @Override public List<Map<String, Object>> entEmpYearCount() { // TODO Auto-generated method stub return dao.entEmpYearCount(session); } /* 근태수정 한개보기 */ @Override public Map<String, Object> selectUpAttendanceOne(int result) { // TODO Auto-generated method stub return dao.selectUpAttendanceOne(session, result); } /* 휴가한개보기 */ @Override public Map<String, Object> selectDayoffOne(int doNo) { // TODO Auto-generated method stub return dao.selectDayoffOne(session, doNo); } /* 출장비한개보기 */ @Override public Map<String, Object> selectBTPOne(int btpNo) { // TODO Auto-generated method stub return dao.selectBTPOne(session, btpNo); } }<file_sep>/src/main/java/com/spring/bm/common/LoggerInterceptor.java package com.spring.bm.common; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; public class LoggerInterceptor extends HandlerInterceptorAdapter { private Logger logger= LoggerFactory.getLogger(LoggerInterceptor.class); // 전처리용 메소드 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if(request.getSession().getAttribute("loginEmp")==null) { request.setAttribute("msg", " 로그인 후 이용하세요!"); request.setAttribute("loc", "/"); request.getRequestDispatcher("/WEB-INF/views/common/msg.jsp").forward(request, response); return false; } else { return super.preHandle(request, response, handler); } } // 후 처리용 메소드 @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { super.postHandle(request, response, handler, modelAndView); } } <file_sep>/src/main/java/com/spring/bm/category/controller/CategoryController.java package com.spring.bm.category.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.spring.bm.category.model.service.CategoryService; import com.spring.bm.common.PageBarFactory; import com.spring.bm.common.PageUrlFactory; import com.spring.bm.stuff.model.vo.StuffMaincategory; import com.spring.bm.stuff.model.vo.StuffSubcategory; @Controller public class CategoryController { @Autowired CategoryService service; private PageUrlFactory path = new PageUrlFactory(); //메인 카테고리 조회 @RequestMapping("/category/maincategoryUpdate.do") public ModelAndView maincategoryUpdate(@RequestParam(value="cPage", required=false, defaultValue="0") int cPage) { ModelAndView mv = new ModelAndView(); int numPerPage = 10; List<StuffMaincategory> list=service.selectMaincategoryList(cPage,numPerPage); int totalCount = service.selectMaincategoryCount(); mv.addObject("pageBar",PageBarFactory.getPageBar(totalCount, cPage, numPerPage, path.getUrl() +"/category/maincategoryUpdate.do")); mv.addObject("count",totalCount); mv.addObject("list",list); mv.setViewName("category/maincategoryUpdate"); return mv; } //서브 카테고리 조회 @RequestMapping("/category/subcategoryUpdate.do") public ModelAndView subcategoryUpdate(@RequestParam(value="cPage", required=false, defaultValue="0") int cPage) { ModelAndView mv = new ModelAndView(); int numPerPage = 10; List<StuffMaincategory> maincategoryList = service.maincategoryList(); List<StuffSubcategory> subcategoryList = service.subcategoryList(cPage,numPerPage); int totalCount = service.selectSubcategoryCount(); mv.addObject("pageBar",PageBarFactory.getPageBar(totalCount, cPage, numPerPage, path.getUrl() +"/category/subcategoryUpdate.do")); mv.addObject("list", maincategoryList); mv.addObject("list2", subcategoryList); mv.setViewName("category/subcategoryUpdate"); return mv; } //메인 카테고리 추가 @RequestMapping("/category/maincategoryEnrollEnd.do") public String maincategoryEnrollEnd(@RequestParam("mcName") String mcName, Model model) { int result = service.maincategoryEnroll(mcName); System.out.println("메인카테고리 결과 : " + result); String msg = ""; String loc = "/category/maincategoryUpdate.do"; if(result > 0) { msg = "메인 카테고리 등록 완료!"; model.addAttribute("msg", msg); } else { msg = "메인 카테고리 등록 실패!"; model.addAttribute("msg", msg); } model.addAttribute("msg", msg); model.addAttribute("loc", loc); return "common/msg"; } //서브 카테고리 추가 @RequestMapping("/category/subcategoryEnrollEnd.do") public String subcategoryEnrollEnd(@RequestParam("scName") String scName, @RequestParam("stuffMain") String mcName, Model model) { Map<String, Object> m = new HashMap(); m.put("scName", scName); m.put("mcName", mcName); int result = service.subcategoryEnroll(m); String msg = ""; String loc = "/category/subcategoryUpdate.do"; if(result > 0) { msg = "서브 카테고리 등록 완료!"; model.addAttribute("msg", msg); } else { msg = "서브 카테고리 등록 실패!"; model.addAttribute("msg", msg); } model.addAttribute("msg", msg); model.addAttribute("loc", loc); return "common/msg"; } @RequestMapping("/category/maincategoryDelete.do") public String maincategoryDelete(@RequestParam("mcName") String mcName, Model model) { int result = service.maincategoryDelete(mcName); String msg = ""; String loc = "/category/maincategoryUpdate.do"; if(result > 0) { msg = "메인 카테고리 삭제 완료!"; model.addAttribute("msg", msg); } else { msg = "메인 카테고리 삭제 실패!"; model.addAttribute("msg", msg); } model.addAttribute("msg", msg); model.addAttribute("loc", loc); return "common/msg"; } @RequestMapping("/category/subcategoryDelete.do") public String subcategoryDelete(@RequestParam("scName") String scName, Model model) { int result = service.subcategoryDelete(scName); String msg = ""; String loc = "/category/subcategoryUpdate.do"; if(result > 0) { msg = "서브 카테고리 삭제 완료!"; model.addAttribute("msg", msg); } else { msg = "서브 카테고리 삭제 실패!"; model.addAttribute("msg", msg); } model.addAttribute("msg", msg); model.addAttribute("loc", loc); return "common/msg"; } //메인 카테고리 이름 중복 검사 @RequestMapping("/category/maincategoryNameDupliCheck.do") public @ResponseBody int maincategoryNameDupliCheck(@RequestParam("mcName") String mcName) { System.out.println(mcName); int result = service.maincategoryNameDupliCheck(mcName); System.out.println(result); return result; } //서브 카테고리 이름 중복 검사 @RequestMapping("/category/subcategoryNameDupliCheck.do") public @ResponseBody int subcategoryNameDupliCheck(@RequestParam("scName") String scName) { System.out.println(scName); int result = service.subcategoryNameDupliCheck(scName); System.out.println(result); return result; } } <file_sep>/src/main/java/com/spring/bm/category/model/dao/CategoryDao.java package com.spring.bm.category.model.dao; import java.util.List; import java.util.Map; import org.mybatis.spring.SqlSessionTemplate; import com.spring.bm.stuff.model.vo.StuffMaincategory; import com.spring.bm.stuff.model.vo.StuffSubcategory; public interface CategoryDao { List<StuffMaincategory> maincategoryList(SqlSessionTemplate sqlSession); int maincategoryEnroll(SqlSessionTemplate sqlSession, String mcName); List<StuffSubcategory> subcategoryList(SqlSessionTemplate sqlSession, int cPage, int numPerPage); int subcategoryEnroll(SqlSessionTemplate sqlSession, Map<String, Object> m); int maincategoryDelete(SqlSessionTemplate sqlSession, String mcName); int subcategoryDelete(SqlSessionTemplate sqlSession, String scName); List<StuffMaincategory> selectMaincategoryList(SqlSessionTemplate sqlSession, int cPage, int numPerPage); int selectMaincategoryCount(SqlSessionTemplate sqlSession); int selectSubcategoryCount(SqlSessionTemplate sqlSession); int maincategoryNameDupliCheck(SqlSessionTemplate sqlSession, String mcName); int subcategoryNameDupliCheck(SqlSessionTemplate sqlSession, String scName); } <file_sep>/src/main/java/com/spring/bm/notice/model/dao/NoticeDao.java package com.spring.bm.notice.model.dao; import java.util.List; import java.util.Map; import org.mybatis.spring.SqlSessionTemplate; import com.spring.bm.employee.model.vo.Employee; import com.spring.bm.notice.model.vo.Notice; import com.spring.bm.notice.model.vo.UploadNotice; public interface NoticeDao { Notice selectNoticeOne(SqlSessionTemplate sqlSession, String nName); int selectNoticeCount(SqlSessionTemplate sqlSession); int selectNoticeCount2(SqlSessionTemplate sqlSession); int selectNoticeCount3(SqlSessionTemplate sqlSession); List<Map<String, String>> selectNoticeList(SqlSessionTemplate sqlSession, int cPage, int numPerPage); int updateReadCount(SqlSessionTemplate sqlSession, int nReadCount); int insertNotice(SqlSessionTemplate sqlSession, Map<String, Object> param); int insertUploadNotice(SqlSessionTemplate sqlSession, UploadNotice n); List<UploadNotice> selectUpNoticeList(SqlSessionTemplate sqlSession, int nNo); List<Notice> selectNoticeList2(SqlSessionTemplate sqlSession); int insertSite(SqlSessionTemplate sqlSession, Map<String, Object> param); int updateNotice(SqlSessionTemplate sqlSession, Map<String, Object> param); int deleteNotice(SqlSessionTemplate sqlSession, Map<String, Object> param); List<Map<String, String>> selectNoticeCheck(SqlSessionTemplate sqlSession, String nName); int deleteUpNotice(SqlSessionTemplate sqlSession, Map<String, Object> param); List<Map<String, String>> selectNoticeSearchList(SqlSessionTemplate sqlSession, Map<String, Object> m); int selectNoticeSearchCount(SqlSessionTemplate sqlSession, Map<String, Object> m); List<Map<String, Object>> selectSiteList(SqlSessionTemplate sqlSession); List<Map<String, Object>> selectSiteList2(SqlSessionTemplate sqlSession); int deleteSite(SqlSessionTemplate sqlSession, String param); Employee selectNoticeEmp(SqlSessionTemplate sqlSession, int empNo); List<Map<String, String>> selectNoticeList3(SqlSessionTemplate sqlSession, int cPage, int numPerPage); List<Map<String, String>> selectNoticeList4(SqlSessionTemplate sqlSession, int cPage, int numPerPage); } <file_sep>/src/main/java/com/spring/bm/note/controller/NoteController.java package com.spring.bm.note.controller; import java.util.HashMap; import java.util.Map; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.spring.bm.note.service.NoteService; @Controller public class NoteController { @Autowired NoteService service; @RequestMapping("/note/saveCache.do") @ResponseBody public String saveCache(String note, HttpServletResponse response) throws JsonProcessingException { Cookie noteCookie = new Cookie("note", note); noteCookie.setMaxAge(60*60*24*365); noteCookie.setPath("/"); response.setCharacterEncoding("UTF-8"); response.addCookie(noteCookie); ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(note); } @RequestMapping("/note/saveNote.do") @ResponseBody public void saveNote(String note, int empNo, HttpServletResponse response) throws JsonProcessingException { Map<String, Object> map = new HashMap(); try { map.put("empNo", empNo); map.put("note", note); int result = service.updateNote(map); } catch (NullPointerException e) { } } } <file_sep>/src/main/java/com/spring/bm/employee/model/dao/EmployeeDao.java package com.spring.bm.employee.model.dao; import java.util.List; import java.util.Map; import org.mybatis.spring.SqlSessionTemplate; import com.spring.bm.employee.model.vo.EmpFile; public interface EmployeeDao { /* 사원리스트불러오기 */ List<Map<String, String>> selectEmpList(SqlSessionTemplate session, int cPage, int numPerPage); int selectEmpCount(SqlSessionTemplate session); /* 사원리스트불러오기끝 */ /* 사원등록 */ int insertEmp(SqlSessionTemplate session, Map<String, String> param); /* 사원첨부파일등록 */ int insertEmpFile(SqlSessionTemplate session, EmpFile e); /* 사원등록끝 */ /* 사원상세보기 */ Map<String, Object> selectEmpOne(SqlSessionTemplate session, int empNo); List<EmpFile> selectEmpFileList(SqlSessionTemplate session, int empNo); /* 사원로그인*/ Map<String, Object> selectLoginEmp(SqlSessionTemplate session, Map<String, Object> map); /* 사원검색 */ List<Map<String, String>> selectEmpSearchList(SqlSessionTemplate session, int cPage, int numPerPage, Map<String, Object> param); int selectEmpSearchCount(SqlSessionTemplate session, Map<String, Object> param); /* 아이디 중복확인 */ int checkId(SqlSessionTemplate session, String empId); /* 첨부파일삭제 */ int deleteEmpFile(SqlSessionTemplate session, int efNo); /* 사원수정 */ int updateEmp(SqlSessionTemplate session, Map<String, Object> param); /* 비밀번호변경 */ int updatePassword(SqlSessionTemplate session, Map<String, Object> param); /* 출퇴근 위치정보 확인 */ int checkLocation(SqlSessionTemplate session, Map<String, Object> param); /* 출근등록 */ int insertGotoWork(SqlSessionTemplate session, Map<String, Object> param); /* 퇴근등록 */ int updateOffWork(SqlSessionTemplate session, Map<String, Object> param); /* 근태하나보기 */ Map<String, Object> selectAttenOne(SqlSessionTemplate session, Map<String, Object> param); /* 근태현황보기 */ List<Map<String, String>> selectAttenList(SqlSessionTemplate session, Map<String, Object> param, int cPage, int numPerPage); int selectAttenCount(SqlSessionTemplate session, Map<String, Object> param); /* 휴가리스트 출력 */ List<Map<String, String>> selectDayOffList(SqlSessionTemplate session, Map<String, Object> param, int cPage, int numPerPage); int selectDayOffCount(SqlSessionTemplate session, Map<String, Object> param); /* 출장리스트 출력 */ List<Map<String, String>> selectBTList(SqlSessionTemplate session, Map<String, Object> param, int cPage, int numPerPage); int selectBTCount(SqlSessionTemplate session, Map<String, Object> param); /* 근태수정용 한개보기 */ Map<String, Object> selectAttenNoOne(SqlSessionTemplate session, Map<String, Object> param); /* 근태수정신청 */ int insertUpAttendance(SqlSessionTemplate session, Map<String, Object> param); /* 남은휴가일수 보기 */ int selectDoRemaining(SqlSessionTemplate session, Map<String, Object> map); /* 휴가신청 */ int insertDayOff(SqlSessionTemplate session, Map<String, Object> param); /* 출장신청 */ int insertBT(SqlSessionTemplate session, Map<String, Object> param); /* 출장비리스트 */ List<Map<String, Object>> selectBTPList(SqlSessionTemplate session, Map<String, Object> param); /* 출장하나 */ Map<String, Object> selectBTOne(SqlSessionTemplate session, Map<String, Object> param); /* 출장비신청 */ int insertBTP(SqlSessionTemplate session, Map<String, Object> param); /* 사원통계 */ List<Map<String, Object>> empYearCount(SqlSessionTemplate session); List<Map<String, Object>> newEmpYearCount(SqlSessionTemplate session); List<Map<String, Object>> entEmpYearCount(SqlSessionTemplate session); /* 사원통계끝 */ /* 근태수정한개보기 */ Map<String, Object> selectUpAttendanceOne(SqlSessionTemplate session, int result); /* 휴가한개보기 */ Map<String, Object> selectDayoffOne(SqlSessionTemplate session, int doNo); /* 출장비한개보기 */ Map<String, Object> selectBTPOne(SqlSessionTemplate session, int btpNo); }<file_sep>/src/main/java/com/spring/bm/sale/model/service/SaleServiceImpl.java package com.spring.bm.sale.model.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.spring.bm.sale.model.dao.SaleDao; @Service public class SaleServiceImpl implements SaleService { @Autowired SaleDao dao; @Autowired SqlSessionTemplate session; @Override public List<Map<String, String>> selectSaleList(int cPage, int numPerPage) { return dao.selectSaleList(session, cPage, numPerPage); } @Override public int selectSaleCount() { return dao.selectSaleCount(session); } @Override public List<Map<String, String>> selectConnList() { return dao.selectConnList(session); } @Override public int enrollSaleInfo(Map<String, Object> param) throws Exception { int result = 0; result = dao.enrollSaleInfo(session,param); //구매 정보 등록 if(result==0) throw new RuntimeException(); if(result!=0) { Map<String,Object> paramMap = new HashMap<String,Object>(); List<Map<String,Object>> stList = new ArrayList<Map<String,Object>>(); for(int i=0; i<Integer.parseInt(String.valueOf(param.get("cnt"))); i++) { Map<String,Object> stMap = new HashMap<String,Object>(); stMap.put("stNo", param.get("stNo"+i)); stMap.put("stNum", param.get("stNum"+i)); stList.add(stMap); } paramMap.put("stList",stList); result = dao.enrollSaleItem(session,paramMap); //물품 리스트 등록 if(result==0) throw new Exception(); } return result; } @Override public List<Map<String, String>> selectSaleSearchList(Map<String, Object> m) { return dao.selectSaleSearchList(session,m); } @Override public int selectSaleSearchCount(Map<String, Object> m) { return dao.selectSaleSearchCount(session,m); } @Override public Map<String, String> selectSaleInfo(int salCode) { return dao.selectSaleInfo(session,salCode); } @Override public List<Map<String, String>> selectSaleItemList(int salCode) { return dao.selectSaleItemList(session,salCode); } @Override public Map<String, Object> selectSalOne(Map<String, Object> param) { return dao.selectSalOne(session,param); } } <file_sep>/src/main/java/com/spring/bm/apv/controller/ApvLineController.java package com.spring.bm.apv.controller; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.spring.bm.apv.model.service.ApvService; import com.spring.bm.common.PageBarFactory; import com.spring.bm.common.PageUrlFactory; import net.sf.json.JSONArray; @Controller public class ApvLineController { private Logger logger=LoggerFactory.getLogger(ApvLineController.class); private String path=new PageUrlFactory().getUrl(); @Autowired ApvService service; /* 결재 라인 관리 리스트 뷰 호출 */ @RequestMapping("/apv/apvLineList.do") public ModelAndView apvLineList(@RequestParam(value="cPage", required=false, defaultValue="1") int cPage, int loginNo) { int numPerPage = 2; List<Map<String,Object>> myList=service.selectMyApvLineList(cPage,numPerPage,loginNo); int totalCount = service.selectMyALCount(loginNo); ModelAndView mv = new ModelAndView(); mv.addObject("pageBar",PageBarFactory.getPageBar(totalCount, cPage, numPerPage, path+"/apv/apvLineList.do",loginNo)); mv.addObject("count", totalCount); mv.addObject("myList",myList); mv.setViewName("apv/apvLineList"); return mv; } /* 결재 라인 등록뷰 호출 */ @RequestMapping("/apv/apvLineEnroll.do") public ModelAndView apvLineEnroll() { ModelAndView mv = new ModelAndView(); //결재라인 등록 로직 //개인/부서/회사 전체 라인 선택 버튼과 //조직도를 표시해줄 부서정보를 list로 가져옴. //저장되어 있는 결재라인도 list로 불러옴. List<Map<String,Object>> deptList=service.selectDeptList(); mv.addObject("deptList",deptList); mv.setViewName("apv/apvLineEnroll"); return mv; } /* 결재라인->부서선택->사원들출력하기 */ @RequestMapping(value="/apv/selectDeptToEmp.do",produces ="application/json; charset=utf8") @ResponseBody public List<Map<String,Object>> selectDeptToEmp(@RequestParam Map<String,Object> param){ int deptNo=Integer.parseInt((String) param.get("deptNo")); List<Map<String,Object>> list=service.selectDeptToEmp(deptNo); return list; } /* 결재라인 등록 처리 */ @RequestMapping(value="/apv/apvLineEnrollEnd.do",method=RequestMethod.POST) @ResponseBody public int apvLineEnrollEnd(@RequestBody Map<String,Object> param){ int result=0; try { result=service.insertApvLine(param); } catch (Exception e) { e.printStackTrace(); } return result; } /* 결재 라인 삭제 로직*/ @RequestMapping("/apv/apvLineDelete.do") public ModelAndView apvLineDelete(@RequestParam(value="alNo", required=true) int alNo,int loginNo){ ModelAndView mv = new ModelAndView(); int result=0; String msg=""; String loc="/apv/apvLineList.do?loginNo="+loginNo; try { result=service.deleteApvLine(alNo); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if(result>0) { msg="결재양식 삭제 성공"; }else { msg="결재 양식 삭제 실패"; } mv.addObject("msg",msg); mv.addObject("loc",loc); mv.setViewName("common/msg"); return mv; } /* 결재 양식 수정 팝업창 */ @RequestMapping("/apv/apvLineModify.do") public ModelAndView apvDocModify(@RequestParam(value="alNo", required=true) int alno) { ModelAndView mv = new ModelAndView(); Map<String,Object> apvl=service.selectALModi(alno); List applicants=new ArrayList(); applicants=service.selectALApplicants(alno); mv.addObject("apvl",apvl); mv.addObject("applicants",applicants); mv.setViewName("apv/apvLineModi"); return mv; } /* 결재라인 수정 처리 */ @RequestMapping(value="/apv/apvLineModiEnd.do",method=RequestMethod.POST) @ResponseBody public int apvLineModiEnd(@RequestBody Map<String,Object> param){ int result=0; try { result=service.updateApvLine(param); } catch (Exception e) { e.printStackTrace(); } return result; } /* 기안하기 -> 결재 라인 등록뷰 호출 */ @RequestMapping("/apv/requestApvLineEnroll.do") public ModelAndView requestApvLineEnroll() { ModelAndView mv = new ModelAndView(); List<Map<String,Object>> deptList=service.selectDeptList(); mv.addObject("deptList",deptList); mv.setViewName("apv/requestApvLineEnroll"); return mv; } /*결재라인 검색*/ @RequestMapping("/apv/searchApvLine.do") public ModelAndView searchDocFormReq(@RequestParam(value="cPage",required=false, defaultValue="1") int cPage, @RequestParam Map<String, Object> param) { int numPerPage = 10; List<Map<String, String>> list = service.selectApvlSearchList(cPage, numPerPage, param); int totalCount = service.selectApvlSearchCount(param); ModelAndView mv=new ModelAndView(); mv.addObject("pageBar", PageBarFactory.getPageBar(totalCount, cPage, numPerPage, path+"/apv/searchApvLine.do",""+param.get("type"), ""+param.get("data"))); mv.addObject("count", totalCount); mv.addObject("myList", list); mv.setViewName("apv/apvLineList"); return mv; } } <file_sep>/src/main/java/com/spring/bm/category/model/dao/CategoryDaoImpl.java package com.spring.bm.category.model.dao; import java.util.List; import java.util.Map; import org.apache.ibatis.session.RowBounds; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.stereotype.Repository; import com.spring.bm.stuff.model.vo.StuffMaincategory; import com.spring.bm.stuff.model.vo.StuffSubcategory; @Repository public class CategoryDaoImpl implements CategoryDao { @Override public List<StuffMaincategory> maincategoryList(SqlSessionTemplate sqlSession) { return sqlSession.selectList("category.maincategoryList"); } @Override public int maincategoryEnroll(SqlSessionTemplate sqlSession, String mcName) { return sqlSession.insert("category.maincategoryEnroll", mcName); } @Override public List<StuffSubcategory> subcategoryList(SqlSessionTemplate sqlSession, int cPage, int numPerPage) { RowBounds rows=new RowBounds((cPage-1)*numPerPage,numPerPage); return sqlSession.selectList("category.subcategoryList", null, rows); } @Override public int subcategoryEnroll(SqlSessionTemplate sqlSession, Map<String, Object> m) { return sqlSession.insert("category.subcategoryEnroll", m); } @Override public int maincategoryDelete(SqlSessionTemplate sqlSession, String mcName) { return sqlSession.delete("category.maincategoryDelete", mcName); } @Override public int subcategoryDelete(SqlSessionTemplate sqlSession, String scName) { return sqlSession.delete("category.subcategoryDelete", scName); } @Override public List<StuffMaincategory> selectMaincategoryList(SqlSessionTemplate sqlSession, int cPage, int numPerPage) { RowBounds rows=new RowBounds((cPage-1)*numPerPage,numPerPage); return sqlSession.selectList("category.selectMaincategoryList", null, rows); } @Override public int selectMaincategoryCount(SqlSessionTemplate sqlSession) { return sqlSession.selectOne("category.selectMaincategoryCount"); } @Override public int selectSubcategoryCount(SqlSessionTemplate sqlSession) { return sqlSession.selectOne("category.selectSubcategoryCount"); } @Override public int maincategoryNameDupliCheck(SqlSessionTemplate sqlSession, String mcName) { return sqlSession.selectOne("category.maincategoryNameDupliCheck", mcName); } @Override public int subcategoryNameDupliCheck(SqlSessionTemplate sqlSession, String scName) { return sqlSession.selectOne("category.subcategoryNameDupliCheck", scName); } } <file_sep>/src/main/java/com/spring/bm/purchase/model/service/PurchaseServiceImpl.java package com.spring.bm.purchase.model.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.spring.bm.purchase.model.dao.PurchaseDao; @Service public class PurchaseServiceImpl implements PurchaseService { @Autowired PurchaseDao dao; @Autowired SqlSessionTemplate session; @Override public List<Map<String, String>> selectPurList(int cPage, int numPerPage) { return dao.selectPurList(session, cPage, numPerPage); } @Override public int selectPurCount() { return dao.selectPurCount(session); } @Override public List<Map<String, String>> selectConnList() { return dao.selectConnList(session); } @Override public Map<String, String> addStuffToTemp(String stuffNo) { return dao.addStuffToTemp(session,stuffNo); } @Override public int enrollPurInfo(Map<String, Object> param) throws Exception { int result = 0; result = dao.enrollPurInfo(session,param); //구매 정보 등록 if(result==0) throw new RuntimeException(); if(result!=0) { result = 0; Map<String,Object> paramMap = new HashMap<String,Object>(); List<Map<String,Object>> stList = new ArrayList<Map<String,Object>>(); for(int i=0; i<Integer.parseInt(String.valueOf(param.get("cnt"))); i++) { Map<String,Object> stMap = new HashMap<String,Object>(); stMap.put("stNo", param.get("stNo"+i)); stMap.put("stNum", param.get("stNum"+i)); stList.add(stMap); } paramMap.put("stList",stList); result = dao.enrollPurItem(session,paramMap); //물품 리스트 등록 if(result==0) throw new Exception(); } return result; } @Override public List<Map<String, String>> selectPurSearchList(Map<String, Object> m) { return dao.selectPurSearchList(session,m); } @Override public int selectPurSearchCount(Map<String, Object> m) { return dao.selectPurSearchCount(session,m); } @Override public Map<String, String> selectPurInfo(int purCode) { return dao.selectPurInfo(session,purCode); } @Override public List<Map<String, String>> selectPurItemList(int purCode) { return dao.selectPurItemList(session,purCode); } @Override public Map<String, Object> selectPurOne(Map<String, Object> param) { return dao.selectPurOne(session,param); } } <file_sep>/src/main/java/com/spring/bm/note/dao/NoteDao.java package com.spring.bm.note.dao; import java.util.Map; import org.mybatis.spring.SqlSessionTemplate; public interface NoteDao { int updateNote(SqlSessionTemplate session, Map<String, Object> map); } <file_sep>/src/main/java/com/spring/bm/calendar/model/vo/Calendar.java package com.spring.bm.calendar.model.vo; import java.sql.Date; import lombok.Data; @Data public class Calendar { private int _id; private String title; private String description; private Date start; private Date end; private String type; private int username; private String backgroundColor; private String allDay; } <file_sep>/src/main/java/com/spring/bm/category/model/service/CategoryServiceImpl.java package com.spring.bm.category.model.service; import java.util.List; import java.util.Map; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.spring.bm.category.model.dao.CategoryDao; import com.spring.bm.stuff.model.vo.StuffMaincategory; import com.spring.bm.stuff.model.vo.StuffSubcategory; @Service public class CategoryServiceImpl implements CategoryService { @Autowired CategoryDao dao; @Autowired SqlSessionTemplate sqlSession; @Override public List<StuffMaincategory> maincategoryList() { return dao.maincategoryList(sqlSession); } @Override public int maincategoryEnroll(String mcName) { return dao.maincategoryEnroll(sqlSession, mcName); } @Override public List<StuffSubcategory> subcategoryList(int cPage, int numPerPage) { return dao.subcategoryList(sqlSession, cPage, numPerPage); } @Override public int subcategoryEnroll(Map<String, Object> m) { return dao.subcategoryEnroll(sqlSession, m); } @Override public int maincategoryDelete(String mcName) { return dao.maincategoryDelete(sqlSession, mcName); } @Override public int subcategoryDelete(String scName) { return dao.subcategoryDelete(sqlSession, scName); } @Override public List<StuffMaincategory> selectMaincategoryList(int cPage, int numPerPage) { return dao.selectMaincategoryList(sqlSession, cPage, numPerPage); } @Override public int selectMaincategoryCount() { return dao.selectMaincategoryCount(sqlSession); } @Override public int selectSubcategoryCount() { return dao.selectSubcategoryCount(sqlSession); } @Override public int maincategoryNameDupliCheck(String mcName) { return dao.maincategoryNameDupliCheck(sqlSession, mcName); } @Override public int subcategoryNameDupliCheck(String scName) { return dao.subcategoryNameDupliCheck(sqlSession, scName); } } <file_sep>/src/main/java/com/spring/bm/calendar/controller/CalendarController.java package com.spring.bm.calendar.controller; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.spring.bm.calendar.model.service.CalendarService; import com.spring.bm.calendar.model.vo.Calendar; import com.spring.bm.common.PageBarFactory; import com.spring.bm.common.PageUrlFactory; @Controller public class CalendarController { private Logger logger = LoggerFactory.getLogger(CalendarController.class); @Autowired CalendarService service; private PageUrlFactory path = new PageUrlFactory(); /* 일정관리첫페이지로 이동 */ @RequestMapping("/calendar/allView.do") // 사원등록 폼으로 전환 public ModelAndView allView(@RequestParam(value = "cPage", required = false, defaultValue = "0") int cPage, Model model, @RequestParam(value = "temp") int param) { int numPerPage = 5; ModelAndView mv = new ModelAndView(); // 스케줄 조회 페이징처리 List<Calendar> list = service.selectCalendarEmpNo(cPage, numPerPage, param); int totalCount = service.selectCalendarCount2(param); mv.addObject("pageBar", PageBarFactory.getPageBar(totalCount, cPage, numPerPage, path.getUrl() + "/calendar/allView.do", "" + param)); mv.addObject("list", list); mv.addObject("count", totalCount); mv.setViewName("calendar/calendarAll"); return mv; } // 스케줄 등록 @RequestMapping("/calendar/insertCalendarEnd.do") public @ResponseBody Calendar insertCalendar(@RequestParam Map<String, Object> param) { Calendar c = service.insertCalender(param); return c; } // 스케줄 조회 @RequestMapping("/calendar/selectCal.do") public @ResponseBody List<Calendar> selectCal(@RequestParam(value = "data") int data) { List<Calendar> list = service.selectCalendarEmpNo(data); return list; } // 스케줄 삭제 @RequestMapping("/calender/deleteCal.do") public ModelAndView updateCalendar(@RequestParam(value = "data") int data, @RequestParam(value = "empNo") int data2) { System.out.println(data); int result = service.deletecCal(data); String msg = ""; String loc = "/calendar/allView.do?temp=" + data2; if (result > 0) { msg = "스케줄 삭제 완료되었습니다."; } else { msg = "스케줄 삭제 실패하였습니다."; } ModelAndView mv = new ModelAndView(); mv.addObject("msg", msg); mv.addObject("loc", loc); mv.setViewName("common/msg"); return mv; } // 개인별 @RequestMapping("/calender/1Cal.do") public ModelAndView Calendar1(@RequestParam(value = "cPage", required = false, defaultValue = "0") int cPage, Model model, @RequestParam(value = "temp") int data) { ModelAndView mv = new ModelAndView(); int numPerPage = 5; List<Calendar> list = service.selectCalendar1(cPage, numPerPage, data); int totalCount = service.selectCalendar1Count(data); mv.addObject("pageBar", PageBarFactory.getPageBar(totalCount, cPage, numPerPage, path.getUrl() + "/calender/1Cal.do", "" + data)); mv.addObject("list", list); mv.addObject("count", totalCount); mv.setViewName("calendar/calendarAll"); return mv; } // 부서별 @RequestMapping("/calender/2Cal.do") public ModelAndView Calendar2(@RequestParam(value = "cPage", required = false, defaultValue = "0") int cPage, Model model, @RequestParam(value = "temp") int data) { ModelAndView mv = new ModelAndView(); int numPerPage = 5; List<Calendar> list = service.selectCalendar2(cPage, numPerPage, data); int totalCount = service.selectCalendar2Count(data); mv.addObject("pageBar", PageBarFactory.getPageBar(totalCount, cPage, numPerPage, path.getUrl() + "/calender/2Cal.do", "" + data)); mv.addObject("list", list); mv.addObject("count", totalCount); mv.setViewName("calendar/calendarAll"); return mv; } // 회사별 @RequestMapping("/calender/3Cal.do") public ModelAndView Calendar3(@RequestParam(value = "cPage", required = false, defaultValue = "0") int cPage, Model model, @RequestParam(value = "temp") int data) { ModelAndView mv = new ModelAndView(); int numPerPage = 5; List<Calendar> list = service.selectCalendar3(cPage, numPerPage, data); int totalCount = service.selectCalendar3Count(data); mv.addObject("pageBar", PageBarFactory.getPageBar(totalCount, cPage, numPerPage, path.getUrl() + "/calender/3Cal.do", "" + data)); mv.addObject("list", list); mv.addObject("count", totalCount); mv.setViewName("calendar/calendarAll"); return mv; } // 일정 수정 화면 전환 @RequestMapping("/calendar/updateCal.do") public ModelAndView updateCal(@RequestParam(value = "calNo") int data) { System.out.println(data); // 일정 번호로 조회 Calendar c = service.selectCno(data); System.out.println("잘 나왔냐 : " + c); ModelAndView mv = new ModelAndView(); mv.addObject("c", c); mv.setViewName("calendar/updateCal"); return mv; } // 일정 수정 동작 @RequestMapping("/calendar/updateCal2.do") public ModelAndView updateCalEnd(@RequestParam Map<String, Object> param) { for ( String key : param.keySet() ) { System.out.println("key : " + key +" / value : " + param.get(key)); } int result = service.updateCalendar(param); System.out.println("수정했어? : " + result); String msg = ""; String loc = "/calendar/updateCal.do?calNo=" + param.get("calNo"); if (result > 0) { msg = "스케줄 수정 완료"; } else { msg = "스케줄 수정 실패"; } ModelAndView mv = new ModelAndView(); mv.addObject("msg", msg); mv.addObject("loc", loc); mv.setViewName("common/msg"); return mv; } } <file_sep>/src/main/java/com/spring/bm/sale/model/dao/SaleDaoImpl.java package com.spring.bm.sale.model.dao; import java.util.List; import java.util.Map; import org.apache.ibatis.session.RowBounds; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.stereotype.Repository; @Repository public class SaleDaoImpl implements SaleDao { @Override public List<Map<String, String>> selectSaleList(SqlSessionTemplate session, int cPage, int numPerPage) { RowBounds rows=new RowBounds((cPage-1)*numPerPage,numPerPage); return session.selectList("sale.selectSaleList",null,rows); } @Override public int selectSaleCount(SqlSessionTemplate session) { return session.selectOne("sale.selectSaleCount"); } @Override public List<Map<String, String>> selectConnList(SqlSessionTemplate session) { return session.selectList("sale.selectConnList"); } @Override public int enrollSaleInfo(SqlSessionTemplate session, Map<String, Object> param) { return session.insert("sale.enrollSaleInfo", param); } @Override public int enrollSaleItem(SqlSessionTemplate session, Map<String,Object> paramMap) { return session.insert("sale.enrollSaleItem", paramMap); } @Override public List<Map<String, String>> selectSaleSearchList(SqlSessionTemplate session, Map<String, Object> m) { int cPage = (Integer)m.get("cPage"); int numPerPage = (Integer)m.get("numPerPage"); RowBounds rows = new RowBounds((cPage-1)*numPerPage,numPerPage); return session.selectList("sale.selectSaleSearchList",m,rows); } @Override public int selectSaleSearchCount(SqlSessionTemplate session, Map<String, Object> m) { return session.selectOne("sale.selectSaleSearchCount",m); } @Override public Map<String, String> selectSaleInfo(SqlSessionTemplate session, int salCode) { return session.selectOne("sale.selectSaleInfo", salCode); } @Override public List<Map<String, String>> selectSaleItemList(SqlSessionTemplate session, int salCode) { return session.selectList("sale.selectSaleItemList", salCode); } @Override public Map<String, Object> selectSalOne(SqlSessionTemplate session, Map<String, Object> param) { return session.selectOne("sale.selectSalOne", param); } } <file_sep>/src/main/java/com/spring/bm/notice/model/service/NoticeService.java package com.spring.bm.notice.model.service; import java.util.List; import java.util.Map; import com.spring.bm.employee.model.vo.Employee; import com.spring.bm.notice.model.vo.Notice; import com.spring.bm.notice.model.vo.UploadNotice; public interface NoticeService { //상세페이지 Notice selectNoticeOne(String nName); //게시판 목록 List<Map<String, String>> selectNoticeList(int cPage, int numPerPage); //조회수 +1 int updateReadCount(int nReadCount); //게시판 등록 int insertNotice(Map<String, Object> param, List<UploadNotice> upNoticeList) throws Exception; //게시판 등록(첨부파일) List<UploadNotice> selectUpNoticeList(int nNo); //필독체크리스트 List<Notice> selectNoticeList2(); //사이트등록 int insertSite(Map<String, Object> param); //게시글 삭제 int deleteNotice(Map<String, Object> param); //필독체크가져오기 List<Map<String, String>> selectNoticeCheck(String nName); //게시글 첨부파일 수정시 기존사진 삭제 int deleteUpNotice(Map<String, Object> param); //게시글 첨부파일 수정사진 업로드 int insertUpNotice(Map<String, Object> param, List<UploadNotice> upNoticeList); //게시글 제목으로 검색 List<Map<String, String>> selectNoticeSearchList(Map<String, Object> m); //게시글 제목으로 검색 int selectNoticeSearchCount(Map<String, Object> m); //등록한 사이트 목록 (내부) List<Map<String, Object>> selectSiteList(); //등록한 사이트 목록 (외부) List<Map<String, Object>> selectSiteList2(); //게시글 수정 첨부파일포함 int updateNotice(Map<String, Object> param, List<UploadNotice> upNoticeList) throws Exception; //게시글 수정 int updateNotice(Map<String, Object> param); //페이징 int selectNoticeCount(); int selectNoticeCount2(); int selectNoticeCount3(); //관련사이트 삭제 int deleteSite(String param); //empName 가져오기 Employee selectNoticeEmp(int empNo); List<Map<String, String>> selectNoticeList3(int cPage, int numPerPage); List<Map<String, String>> selectNoticeList4(int cPage, int numPerPage); } <file_sep>/src/main/java/com/spring/bm/acct/service/AcctService.java package com.spring.bm.acct.service; import java.util.List; import java.util.Map; public interface AcctService { List<Map<String, String>> selectICList(); /* salary */ List<Map<String, String>> selectEmpList(int cPage, int numPerPage); int selectEmpCount(); /* salary payment */ int updateWagePayment(int salno); int updateSeveranceStatus(Map<String, String> m); /* biztrip */ List<Map<String, String>> selectBizTripList(int cPage, int numPerPage); int selectBizTripCount(); /* severance */ List<Map<String, String>> selectSevList(int cPage, int numPerPage); int selectSevCount(); /* salary search */ List<Map<String, String>> selectsSalarySearchList(int cPage, int numPerPage, Map<String, Object> param); int salarySearchCount(Map<String, Object> param); /* biztrip search */ List<Map<String, String>> selectBiztripSearchList(int cPage, int numPerPage, Map<String, Object> param); int biztripSearchCount(Map<String, Object> param); /* severance search */ List<Map<String, String>> selectSevSearchList(int cPage, int numPerPage, Map<String, Object> param); int sevSearchCount(Map<String, Object> param); /* 퇴직금한개보기 */ Map<String, String> selectSevOne(String empno); /* biztrip payment */ int updateBizTripPayment(int data); /* severance payment */ int updateSevPayment(int empno); }<file_sep>/src/main/java/com/spring/bm/common/PageBarFactory.java package com.spring.bm.common; import java.sql.Date; public class PageBarFactory { public static String getPageBar(int totalCount, int cPage, int numPerPage, String url) { String pageBar=""; pageBar += PageBarBody(totalCount, cPage, numPerPage, pageBar); pageBar+="location.href='"+url+"?cPage='+cPage"; pageBar+="}"; pageBar+="</script>"; return pageBar; } public static String getPageBar(int totalCount, int cPage, int numPerPage, String url, String type, String data) { String pageBar=""; pageBar += PageBarBody(totalCount, cPage, numPerPage, pageBar); pageBar+="location.href='"+url+"?cPage='+cPage+'&type="+type+"&data="+data+"'"; pageBar+="}"; pageBar+="</script>"; return pageBar; } //데이트피커 검색용 페이지바 public static String getPageBar(int totalCount, int cPage, int numPerPage,String url, Date startDay, Date endDay, String temp) { String pageBar=""; pageBar += PageBarBody(totalCount, cPage, numPerPage, pageBar); pageBar+="location.href='"+url+"?cPage='+cPage+'&startDay="+startDay+"&endDay="+endDay+"&temp="+temp+"'"; pageBar+="}"; pageBar+="</script>"; return pageBar; } //temp용 검색용 페이지바 public static String getPageBar(int totalCount, int cPage, int numPerPage,String url, String temp) { String pageBar=""; pageBar += PageBarBody(totalCount, cPage, numPerPage, pageBar); pageBar+="location.href='"+url+"?cPage='+cPage+'&temp="+temp+"'"; pageBar+="}"; pageBar+="</script>"; return pageBar; } public static Object getPageBar(int totalCount, int cPage, int numPerPage, String url, Date startDay, Date endDay, String temp, String type, String data) { String pageBar=""; pageBar += PageBarBody(totalCount, cPage, numPerPage, pageBar); pageBar+="location.href='"+url+"?cPage='+cPage+'&startDay="+startDay+"&endDay="+endDay+"&temp="+temp+"&type="+type+"&data="+data+"'"; pageBar+="}"; pageBar+="</script>"; return pageBar; } public static Object getPageBar(int totalCount, int cPage, int numPerPage, String url, Date startDay, Date endDay, String temp, String empNo) { String pageBar=""; pageBar += PageBarBody(totalCount, cPage, numPerPage, pageBar); pageBar+="location.href='"+url+"?cPage='+cPage+'&startDay="+startDay+"&endDay="+endDay+"&temp="+temp+"&empNo="+empNo+"'"; pageBar+="}"; pageBar+="</script>"; return pageBar; } public static String getPageBar(int totalCount, int cPage, int numPerPage,String url, int loginNo) { String pageBar=""; pageBar += PageBarBody(totalCount, cPage, numPerPage, pageBar); pageBar+="location.href='"+url+"?cPage='+cPage+'&loginNo="+loginNo+"'"; pageBar+="}"; pageBar+="</script>"; return pageBar; } public static String PageBarBody(int totalCount, int cPage, int numPerPage, String pageBar) { int pageBarSize=5; int pageNo=((cPage-1)/pageBarSize)*pageBarSize+1; int pageEnd=pageNo+pageBarSize-1; int totalPage=(int)Math.ceil((double)totalCount/numPerPage); pageBar+="<ul class='pagination justify-content-center pagination-sm'>"; if(pageNo==1) { pageBar+="<li class='page-item disabled'>"; pageBar+="<a class='page-link' href='#' tabindex='-1'>이전</a>"; pageBar+="</li>"; }else { pageBar+="<li class='page-item'>"; pageBar+="<a class='page-link' " + "href='javascript:fn_paging("+(pageNo-1)+")'>이전</a>"; pageBar+="</li>"; } while(!(pageNo>pageEnd||pageNo>totalPage)) { if(cPage==pageNo) { pageBar+="<li class='page-item active'>"; pageBar+="<a class='page-link'>"+pageNo+"</a>"; pageBar+="</li>"; }else { pageBar+="<li class='page-item'>"; pageBar+="<a class='page-link' " + "href='javascript:fn_paging("+(pageNo)+")'>"+pageNo+"</a>"; pageBar+="</li>"; } pageNo++; } if(pageNo>totalPage) { pageBar+="<li class='page-item disabled'>"; pageBar+="<a class='page-link' href='#' tabindex='-1'>다음</a>"; pageBar+="</li>"; }else { pageBar+="<li class='page-item'>"; pageBar+="<a class='page-link' " + "href='javascript:fn_paging("+pageNo+")'>다음</a>"; pageBar+="</li>"; } pageBar+="</ul>"; pageBar+="<script>"; pageBar+="function fn_paging(cPage){"; return pageBar; } }<file_sep>/src/main/java/com/spring/bm/stuff/model/dao/StuffDaoImpl.java package com.spring.bm.stuff.model.dao; import java.util.List; import java.util.Map; import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.session.SqlSession; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.stereotype.Repository; import com.spring.bm.connection.model.vo.Connection; import com.spring.bm.stuff.model.vo.Stuff; import com.spring.bm.stuff.model.vo.StuffMaincategory; import com.spring.bm.stuff.model.vo.StuffSubcategory; import com.spring.bm.stuff.model.vo.StuffUpload; @Repository public class StuffDaoImpl implements StuffDao { @Override public List<StuffMaincategory> stuffMaincategoryList(SqlSessionTemplate sqlSession) { return sqlSession.selectList("stuff.maincategoryList"); } @Override public List<StuffSubcategory> stuffSubcategoryList(SqlSessionTemplate sqlSession, int mcNo) { return sqlSession.selectList("stuff.subcategoryList",mcNo); } @Override public int stuffEnrollEnd(SqlSessionTemplate sqlSession, Map<String, String> param) { return sqlSession.insert("stuff.stuffEnroll", param); } @Override public Stuff stuffSeeMore(SqlSessionTemplate sqlSession, int stuffNo) { return sqlSession.selectOne("stuff.stuffSeeMore", stuffNo); } @Override public StuffSubcategory stuffScName(SqlSessionTemplate sqlSession, int scNo) { return sqlSession.selectOne("stuff.stuffScName", scNo); } @Override public int insertStuffImage(SqlSessionTemplate sqlSession, StuffUpload su) { return sqlSession.insert("stuff.insertStuffImge", su); } @Override public List<Stuff> selectStuffList(SqlSessionTemplate sqlSession, int cPage, int numPerPage) { RowBounds rows=new RowBounds((cPage-1)*numPerPage,numPerPage); return sqlSession.selectList("stuff.selectStuffList",null,rows); } @Override public int selectStuffCount(SqlSessionTemplate sqlSession) { return sqlSession.selectOne("stuff.selectStuffCount"); } @Override public int stuffNameDupliCheck(SqlSessionTemplate sqlSession, String stuffName) { return sqlSession.selectOne("stuff.stuffNameDupliCheck", stuffName); } @Override public List<Stuff> selectStuffSearchList(SqlSessionTemplate sqlSession, Map<String, Object> m) { int cPage = (Integer)(m.get("cPage")); int numPerPage = (Integer)(m.get("numPerPage")); RowBounds rows = new RowBounds((cPage-1) * numPerPage, numPerPage); return sqlSession.selectList("stuff.selectStuffSearchList", m, rows); } @Override public int selectStuffSearchCount(SqlSessionTemplate sqlSession, Map<String, Object> m) { return sqlSession.selectOne("stuff.selectStuffSearchCount", m); } @Override public Stuff stuffOne(SqlSessionTemplate sqlSession, int stuffNo) { return sqlSession.selectOne("stuff.stuffOne", stuffNo); } @Override public StuffUpload stuffUploadOne(SqlSessionTemplate sqlSession, int stuffNo) { return sqlSession.selectOne("stuff.stuffUploadOne", stuffNo); } @Override public StuffMaincategory selectMaincategory(SqlSessionTemplate sqlSession, int scNo) { return sqlSession.selectOne("category.selectMaincategory", scNo); } @Override public int updateStuff(SqlSessionTemplate sqlSession, Map<String, String> param) { return sqlSession.update("stuff.updateStuff",param); } @Override public int deleteStuff(SqlSessionTemplate sqlSession, int stuffNo) { return sqlSession.delete("stuff.deleteStuff", stuffNo); } @Override public int deleteStuffUpload(SqlSessionTemplate sqlSession, Map<String, String> param) { return sqlSession.delete("stuff.deleteStuffUpload",param); } @Override public List<Connection> stuffConnectionList(SqlSessionTemplate sqlSession) { return sqlSession.selectList("stuff.selectConnectionList"); } @Override public Connection connectionName(SqlSessionTemplate sqlSession, int conCode) { return sqlSession.selectOne("stuff.connectionName", conCode); } @Override public List<Stuff> searchStuffName(SqlSessionTemplate sqlSession, Map<String,String> map) { return sqlSession.selectList("stuff.searchStuffName", map); } @Override public List<Stuff> searchStuffName2(SqlSessionTemplate sqlSession, Map<String,String> map) { return sqlSession.selectList("stuff.searchStuffName2", map); } } <file_sep>/src/main/java/com/spring/bm/connection/model/vo/Connection.java package com.spring.bm.connection.model.vo; import lombok.Data; @Data public class Connection { private int conCode; private String conName; private String conCateg; private String conRepname; private String conTel; private String conPhone; private int mcNo; private String conUsecheck; private String conTransck; private String conAddr; private int conLocy; private int conLocx; public Connection () { } public Connection(int conCode, String conName, String conCateg, String conRepname, String conTel, String conPhone, int mcNo, String conUsecheck, String conTransck, String conAddr, int conLocy, int conLocx) { super(); this.conCode = conCode; this.conName = conName; this.conCateg = conCateg; this.conRepname = conRepname; this.conTel = conTel; this.conPhone = conPhone; this.mcNo = mcNo; this.conUsecheck = conUsecheck; this.conTransck = conTransck; this.conAddr = conAddr; this.conLocy = conLocy; this.conLocx = conLocx; } } <file_sep>/src/main/java/com/spring/bm/calendar/model/service/CalendarServiceImpl.java package com.spring.bm.calendar.model.service; import java.util.List; import java.util.Map; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.spring.bm.calendar.model.dao.CalendarDao; import com.spring.bm.calendar.model.vo.Calendar; @Service public class CalendarServiceImpl implements CalendarService { @Autowired CalendarDao dao; @Autowired SqlSessionTemplate sqlSession; @Override public Calendar insertCalender(Map<String, Object> param) { int result = 0; Calendar c = null; result = dao.insertCalendar(sqlSession, param); if(result > 0) { c = new Calendar(); c.set_id(Integer.parseInt((String) param.get("scheNo"))); result = c.get_id(); c = dao.resultCalendar(sqlSession, result); } return c; } @Override public int updateCalendar(Map<String, Object> param) { return dao.updateCalendar(sqlSession, param); } @Override public List<Map<String, Object>> selectScheCategory() { return dao.selectScheCategory(sqlSession); } @Override public List<Calendar> selectCalendarEmpNo(int username) { return dao.selectCalendarEmpNo(sqlSession, username); } @Override public int selectCalendarCount(int username) { return dao.selectCalendarCount(sqlSession, username); } @Override public List<Calendar> selectCalendarEmpNo(int cPage, int numPerPage, int param) { return dao.selectCalendarEmpNo(sqlSession, cPage, numPerPage, param); } @Override public int selectCalendarCount2(int param) { return dao.selectCalendarCount2(sqlSession, param); } @Override public int deletecCal(int data) { return dao.deleteCal(sqlSession, data); } @Override public List<Calendar> selectCalendar1(int cPage, int numPerPage, int data) { return dao.selectCalendar1(sqlSession, cPage, numPerPage, data); } @Override public List<Calendar> selectCalendar2(int cPage, int numPerPage, int data) { return dao.selectCalendar2(sqlSession, cPage, numPerPage, data); } @Override public List<Calendar> selectCalendar3(int cPage, int numPerPage, int data) { return dao.selectCalendar3(sqlSession, cPage, numPerPage, data); } @Override public int selectCalendar1Count(int data) { return dao.selectCalendar1Count(sqlSession, data); } @Override public int selectCalendar2Count(int data) { return dao.selectCalendar2Count(sqlSession, data); } @Override public int selectCalendar3Count(int data) { return dao.selectCalendar3Count(sqlSession, data); } @Override public Calendar selectCno(int data) { return dao.selectCno(sqlSession, data); } @Override public List<Calendar> selectCalendarEmpNo2(int empNo) { return dao.selectCalendarEmpNo2(sqlSession, empNo); } } <file_sep>/src/main/java/com/spring/bm/stuff/model/vo/StuffSubcategory.java package com.spring.bm.stuff.model.vo; import lombok.Data; @Data public class StuffSubcategory { private int scNo; private String scName; private int mcNo; private String mcName; public StuffSubcategory() { } public StuffSubcategory(int scNo, String scName, int mcNo, String mcName) { super(); this.scNo = scNo; this.scName = scName; this.mcNo = mcNo; this.mcName = mcName; } } <file_sep>/src/main/java/com/spring/bm/stuff/model/vo/Stuff.java package com.spring.bm.stuff.model.vo; import java.sql.Date; import lombok.Data; @Data public class Stuff { private int stuffNo; private String stuffName; private int price; private int stuffCount; private int weight; private int size1; private int size2; private int size3; private Date manufacturingDate; private String manufacturingCountry; private String color; private String material; private String etc; private Date enrollDate; private int scNo; private String scName; private int conCode; private String conName; public Stuff() { } public Stuff(int stuffNo, String stuffName, int price, int stuffCount, int weight, int size1, int size2, int size3, Date manufacturingDate, String manufacturingCountry, String color, String material, String etc, Date enrollDate, int scNo, String scName, int conCode, String conName) { super(); this.stuffNo = stuffNo; this.stuffName = stuffName; this.price = price; this.stuffCount = stuffCount; this.weight = weight; this.size1 = size1; this.size2 = size2; this.size3 = size3; this.manufacturingDate = manufacturingDate; this.manufacturingCountry = manufacturingCountry; this.color = color; this.material = material; this.etc = etc; this.enrollDate = enrollDate; this.scNo = scNo; this.scName = scName; this.conCode = conCode; this.conName = conName; } } <file_sep>/src/main/java/com/spring/bm/note/service/NoteServiceImpl.java package com.spring.bm.note.service; import java.util.Map; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.spring.bm.note.dao.NoteDao; @Service public class NoteServiceImpl implements NoteService { @Autowired NoteDao dao; @Autowired SqlSessionTemplate session; @Override public int updateNote(Map<String, Object> map) { return dao.updateNote(session, map); } } <file_sep>/src/main/java/com/spring/bm/notice/model/service/NoticeServiceImpl.java package com.spring.bm.notice.model.service; import java.util.List; import java.util.Map; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.spring.bm.employee.model.vo.Employee; import com.spring.bm.notice.model.dao.NoticeDao; import com.spring.bm.notice.model.vo.Notice; import com.spring.bm.notice.model.vo.UploadNotice; @Service public class NoticeServiceImpl implements NoticeService { @Autowired NoticeDao dao; @Autowired SqlSessionTemplate sqlSession; @Override @Transactional(rollbackFor = Exception.class) //RuntimeException 발생시! public int insertNotice(Map<String, Object> param, List<UploadNotice> upNoticeList)throws Exception{ int result=0; int boardNo=0; result=dao.insertNotice(sqlSession, param); //board테이블에 데이터를 입력! if(result==0) throw new RuntimeException(); if(upNoticeList.size()>0) { for(UploadNotice n : upNoticeList) { n.setNNo(Integer.parseInt((String)param.get("nNo"))); result=dao.insertUploadNotice(sqlSession, n); if(result==0) throw new Exception(); } } return result; } @Override public Notice selectNoticeOne(String nName) { return dao.selectNoticeOne(sqlSession, nName); } @Override public int selectNoticeCount() { return dao.selectNoticeCount(sqlSession); } @Override public int selectNoticeCount2() { return dao.selectNoticeCount2(sqlSession); } @Override public int selectNoticeCount3() { return dao.selectNoticeCount3(sqlSession); } @Override public List<Map<String, String>> selectNoticeList(int cPage, int numPerPage) { return dao.selectNoticeList(sqlSession, cPage, numPerPage); } @Override public int updateReadCount(int nReadCount) { return dao.updateReadCount(sqlSession, nReadCount); } @Override public List<UploadNotice> selectUpNoticeList(int nNo) { return dao.selectUpNoticeList(sqlSession, nNo); } @Override public List<Notice> selectNoticeList2() { return dao.selectNoticeList2(sqlSession); } @Override public int insertSite(Map<String, Object> param) { return dao.insertSite(sqlSession, param); } @Override public int deleteNotice(Map<String, Object> param) { return dao.deleteNotice(sqlSession, param); } @Override public List<Map<String, String>> selectNoticeCheck(String nName) { return dao.selectNoticeCheck(sqlSession, nName); } @Override public int deleteUpNotice(Map<String, Object> param) { return dao.deleteUpNotice(sqlSession, param); } @Override @Transactional(rollbackFor = Exception.class) //RuntimeException 발생시! public int insertUpNotice(Map<String, Object> param, List<UploadNotice> upNoticeList){ int result=0; int boardNo=0; if(upNoticeList.size()>0) { for(UploadNotice n : upNoticeList) { n.setNNo(Integer.parseInt((String)param.get("nNo"))); result=dao.insertUploadNotice(sqlSession, n); } } return result; } @Override public List<Map<String, String>> selectNoticeSearchList(Map<String, Object> m) { return dao.selectNoticeSearchList(sqlSession, m); } @Override public int selectNoticeSearchCount(Map<String, Object> m) { return dao.selectNoticeSearchCount(sqlSession, m); } @Override public List<Map<String, Object>> selectSiteList() { return dao.selectSiteList(sqlSession); } @Override public List<Map<String, Object>> selectSiteList2() { return dao.selectSiteList2(sqlSession); } @Override public int updateNotice(Map<String, Object> param, List<UploadNotice> upNoticeList) throws Exception { int result=0; int boardNo=0; result = dao.updateNotice(sqlSession, param); if(result == 0 ) throw new RuntimeException(); if(upNoticeList.size()>0) { for(UploadNotice n : upNoticeList) { n.setNNo(Integer.parseInt((String)param.get("nNo"))); result=dao.insertUploadNotice(sqlSession, n); if(result == 0) throw new Exception(); } } return result; } @Override public int updateNotice(Map<String, Object> param) { return dao.updateNotice(sqlSession, param); } @Override public int deleteSite(String param) { return dao.deleteSite(sqlSession, param); } @Override public Employee selectNoticeEmp(int empNo) { return dao.selectNoticeEmp(sqlSession, empNo); } @Override public List<Map<String, String>> selectNoticeList3(int cPage, int numPerPage) { return dao.selectNoticeList3(sqlSession, cPage, numPerPage); } @Override public List<Map<String, String>> selectNoticeList4(int cPage, int numPerPage) { return dao.selectNoticeList4(sqlSession, cPage, numPerPage); } } <file_sep>/src/main/java/com/spring/bm/chat/model/vo/ChatRoom.java package com.spring.bm.chat.model.vo; import lombok.Data; @Data public class ChatRoom { private int roomNo; private int receiver; private int sender; public ChatRoom(int roomNo, int receiver, int sender) { super(); this.roomNo = roomNo; this.receiver = receiver; this.sender = sender; } public ChatRoom() { // TODO Auto-generated constructor stub } } <file_sep>/src/main/java/com/spring/bm/connection/model/dao/ConnectionDao.java package com.spring.bm.connection.model.dao; import java.util.List; import java.util.Map; import org.mybatis.spring.SqlSessionTemplate; import com.spring.bm.connection.model.vo.Connection; public interface ConnectionDao { public int selectConnCount(SqlSessionTemplate session); List<Map<String, String>> selectConnList(SqlSessionTemplate session, int cPage, int numPerPage); List<Map<String,String>> selectStfMainCateg(SqlSessionTemplate session); int searchDisCon(SqlSessionTemplate session, Map<String,String> param); int searchCon(SqlSessionTemplate session, Map<String,String> param); int enrollConn(SqlSessionTemplate session, Map<String,String> param); int enrollTransferInfo(SqlSessionTemplate session, Map<String,String> param); Map<String, String> selectConnection(SqlSessionTemplate session, int conCode); String selectThisMainCateg(SqlSessionTemplate session, int conCode); Map<String, String> selectTransferInfo(SqlSessionTemplate session, int conCode); int modifyConn(SqlSessionTemplate session, Map<String, String> param); int modifyTransferInfo(SqlSessionTemplate session, Map<String,String> param); int deleteConn(SqlSessionTemplate session, int conCode); List<Map<String, String>> selectConnSearchList(SqlSessionTemplate session, Map<String, Object> m); int selectConnSearchCount(SqlSessionTemplate session, Map<String, Object> m); //구매정보 등록 거래처 검색 public List<Connection> searchConnection(SqlSessionTemplate session, Map<String, Object> m); public int serchConnectionCount(SqlSessionTemplate session, Map<String, Object> m); //판매정보 등록 거래처 검색 public List<Connection> searchConnection2(SqlSessionTemplate session, Map<String, Object> m); public int serchConnectionCount2(SqlSessionTemplate session, Map<String, Object> m); }<file_sep>/src/main/java/com/spring/bm/stuff/model/vo/StuffUpload.java package com.spring.bm.stuff.model.vo; import java.sql.Date; import com.spring.bm.stuff.controller.StuffController; import lombok.Data; @Data public class StuffUpload { private int imgNo; private String imgOriname; private String imgRename; private int stuffNo; private Date imgDate; public StuffUpload() { } public StuffUpload(int imgNo, String imgOriname, String imgRename, int stuffNo, Date imgDate) { super(); this.imgNo = imgNo; this.imgOriname = imgOriname; this.imgRename = imgRename; this.stuffNo = stuffNo; this.imgDate = imgDate; } } <file_sep>/src/main/java/com/spring/bm/vc/controller/VideoChatController.java package com.spring.bm.vc.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class VideoChatController { // 화상채팅 구현 @RequestMapping("/viewChatting.do") public String videoChat() { return "chat/videochat"; } } <file_sep>/src/main/java/com/spring/bm/acct/dao/AccDaoImpl.java package com.spring.bm.acct.dao; import java.util.List; import java.util.Map; import org.apache.ibatis.session.RowBounds; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.stereotype.Repository; @Repository public class AccDaoImpl implements AcctDao { @Override public List<Map<String, String>> selectICList(SqlSessionTemplate session) { return session.selectList("acct.selectIcList"); } /* 월급 관련 리스트 가져오기 */ @Override public List<Map<String, String>> selectEmpList(int cPage, int numPerPage, SqlSessionTemplate session) { RowBounds rows = new RowBounds((cPage-1)*numPerPage, numPerPage); return session.selectList("acct.selectEmpList",null, rows); } @Override public int selectEmpCount(SqlSessionTemplate session) { return session.selectOne("acct.selectEmpCount"); } @Override public int updateWagePayment(SqlSessionTemplate session, int salno) { return session.update("acct.updateWagePayment", salno); } @Override public int updateSeveranceStatus(SqlSessionTemplate session, Map<String, String> m) { return session.update("acct.updateSeveranceStatus", m); } @Override public int updateEmployeeStatus(SqlSessionTemplate session, Map<String, String> m) { return session.update("acct.updateEmployeeStatus", m); } /* biztrip */ @Override public List<Map<String, String>> selectBizTripList(int cPage, int numPerPage, SqlSessionTemplate session) { RowBounds rows = new RowBounds((cPage-1)*numPerPage, numPerPage); return session.selectList("acct.selectBizTripList", null, rows); } @Override public int selecBizTripCount(SqlSessionTemplate session) { return session.selectOne("acct.selectBizTripCount"); } /* biztrip end */ /* severance */ @Override public List<Map<String, String>> selectSevList(SqlSessionTemplate session, int cPage, int numPerPage) { RowBounds rows = new RowBounds((cPage-1)*numPerPage, numPerPage); return session.selectList("acct.selectSevList", null, rows); } @Override public int selectSevCount(SqlSessionTemplate session) { return session.selectOne("acct.selectSevCount"); } /* salary search */ @Override public List<Map<String, String>> selectsSalarySearchList(SqlSessionTemplate session, int cPage, int numPerPage, Map<String, Object> param) { RowBounds rows = new RowBounds((cPage-1)*numPerPage, numPerPage); return session.selectList("acct.selectsSalarySearchList", param, rows); } @Override public int salarySearchCount(SqlSessionTemplate session, Map<String, Object> param) { return session.selectOne("acct.salarySearchCount", param); } /* biztrip search */ @Override public List<Map<String, String>> selectBiztripSearchList(SqlSessionTemplate session, int cPage, int numPerPage, Map<String, Object> param) { RowBounds rows = new RowBounds((cPage-1)*numPerPage, numPerPage); return session.selectList("acct.selectBiztripSearchList", param, rows); } @Override public int biztripSearchCount(SqlSessionTemplate session, Map<String, Object> param) { return session.selectOne("acct.biztripSearchCount", param); } /* severance search */ @Override public List<Map<String, String>> selectSevSearchList(SqlSessionTemplate session, int cPage, int numPerPage, Map<String, Object> param) { RowBounds rows = new RowBounds((cPage-1)*numPerPage, numPerPage); return session.selectList("acct.selectSevSearchList", param, rows); } @Override public int sevSearchCount(SqlSessionTemplate session, Map<String, Object> param) { return session.selectOne("acct.sevSearchCount", param); } /* 퇴직금한개보기 */ @Override public Map<String, String> selectSevOne(SqlSessionTemplate session, String empno) { // TODO Auto-generated method stub return session.selectOne("acct.selectSevOne", empno); } @Override public int updateBizTripPayment(SqlSessionTemplate session, int data) { return session.update("acct.updateBizTripPayment", data); } @Override public int updateSevPayment(SqlSessionTemplate session, int empno) { return session.update("acct.updateSevPayment", empno); } /* severance payment */ } <file_sep>/src/main/java/com/spring/bm/empjob/model/service/EmpJobService.java package com.spring.bm.empjob.model.service; import java.util.List; import java.util.Map; public interface EmpJobService { /* 직급등록 */ int insertEmpJob(Map<String, String> param) throws Exception; /* 직급리스트출력 */ List<Map<String, String>> empJobList(); /* 직급수정 */ int updateEmpJob(Map<String, String> param) throws Exception; /* 직급하나출력 */ Map<String, Object> selectEmpJobOne(int jobNo); } <file_sep>/src/main/java/com/spring/bm/purchase/model/dao/PurchaseDaoImpl.java package com.spring.bm.purchase.model.dao; import java.util.List; import java.util.Map; import org.apache.ibatis.session.RowBounds; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.stereotype.Repository; @Repository public class PurchaseDaoImpl implements PurchaseDao { @Override public List<Map<String, String>> selectPurList(SqlSessionTemplate session, int cPage, int numPerPage) { RowBounds rows=new RowBounds((cPage-1)*numPerPage,numPerPage); return session.selectList("purchase.selectPurList",null,rows); } @Override public int selectPurCount(SqlSessionTemplate session) { return session.selectOne("purchase.selectPurCount"); } @Override public List<Map<String, String>> selectConnList(SqlSessionTemplate session) { return session.selectList("purchase.selectConnList"); } @Override public Map<String, String> addStuffToTemp(SqlSessionTemplate session, String stuffNo) { return session.selectOne("purchase.addStuffToTemp", stuffNo); } @Override public int enrollPurInfo(SqlSessionTemplate session, Map<String, Object> param) { return session.insert("purchase.enrollPurInfo", param); } @Override public int enrollPurItem(SqlSessionTemplate session, Map<String,Object> paramMap) { return session.insert("purchase.enrollPurItem", paramMap); } @Override public List<Map<String, String>> selectPurSearchList(SqlSessionTemplate session, Map<String, Object> m) { int cPage = (Integer)m.get("cPage"); int numPerPage = (Integer)m.get("numPerPage"); RowBounds rows = new RowBounds((cPage-1)*numPerPage,numPerPage); return session.selectList("purchase.selectPurSearchList",m,rows); } @Override public int selectPurSearchCount(SqlSessionTemplate session, Map<String, Object> m) { return session.selectOne("purchase.selectPurSearchCount",m); } @Override public Map<String, String> selectPurInfo(SqlSessionTemplate session, int purCode) { return session.selectOne("purchase.selectPurInfo", purCode); } @Override public List<Map<String, String>> selectPurItemList(SqlSessionTemplate session, int purCode) { return session.selectList("purchase.selectPurItemList", purCode); } @Override public Map<String, Object> selectPurOne(SqlSessionTemplate session, Map<String, Object> param) { return session.selectOne("purchase.selectPurOne", param); } } <file_sep>/src/main/java/com/spring/bm/chatting/ViewChatting.java package com.spring.bm.chatting; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.BinaryWebSocketHandler; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.spring.bm.chat.model.service.ChatService; public class ViewChatting extends BinaryWebSocketHandler{ //session 관리를 직접해줘야함. // websocket 에 접속한 session 관리하기! @Autowired ChatService service; private static Map<String,WebSocketSession> clients = new HashMap(); @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) { // 얘가 onmessage 라고 생각해라 // client 가 보낸 데이터를 JSON 데이터를 파싱처리하기 위해 JACKSON 를 사용 ObjectMapper mapper = new ObjectMapper(); RTCMessage msg = getMessageObject(message); // 메세지 파싱용 메소드 session.getAttributes().put(String.valueOf(msg.getReceiver()), msg); // session 객체에 보낸 메세지를 저장 // session 관리를 위해 clients 객체에 세션을 추가 clients.put(String.valueOf(msg.getReceiver()), session); sessionChecking(); // 접속이 종료된 session 을 client 에서 삭제함. // 화면 연결하는 로직 구성 for(Map.Entry<String, WebSocketSession> client: clients.entrySet()) { WebSocketSession s = client.getValue(); if(!client.getKey().equals(msg.getReceiver())) { try { s.sendMessage(new TextMessage(mapper.writeValueAsString(msg))); } catch (Exception e) { e.printStackTrace(); } } } int result = service.insertChat(msg); } // private void adminBroadCast() { // ObjectMapper mapper = new ObjectMapper(); // RTCMessage msg = new RTCMessage(); // msg.setEmpNo(msg.getEmpNo()); // msg.setSender(msg.getSender()); // try { // for(Map.Entry<String, WebSocketSession> client : clients.entrySet()) { // client.getValue().sendMessage(new TextMessage(mapper.writeValueAsString(msg))); // } // } catch (Exception e) { // e.printStackTrace(); // } // } private void sessionChecking() { Iterator<Map.Entry<String, WebSocketSession>> it=clients.entrySet().iterator(); while(it.hasNext()) { Map.Entry<String, WebSocketSession> client = it.next(); if(!client.getValue().isOpen()) { it.remove(); } } } private RTCMessage getMessageObject(TextMessage message) { ObjectMapper mapper = new ObjectMapper(); RTCMessage m = null; try { m = mapper.readValue(message.getPayload(), RTCMessage.class); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return m; } } <file_sep>/src/main/java/com/spring/bm/acct/model/vo/Product.java package com.spring.bm.acct.model.vo; import java.math.BigDecimal; public class Product { // // private String productId; // private String description; // private String imageUrl; // private BigDecimal price; // // public Product(){} // public Product(String productId, String description, String imageUrl, BigDecimal price) { // this.productId = productId; // this.description = description; // this.imageUrl = imageUrl; // this.price = price; // } // public String getDescription() { return description; } // public void setDescription(String description) { this.description = description; } // public String getProductId() { return productId; } // public void setProductId(String productId) { this.productId = productId; } // public String getImageUrl() { return imageUrl; } // public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } // public BigDecimal getPrice() { return price; } // public void setPrice(BigDecimal price) { this.price = price; } // public String getVersion() { return version; } // public void setVersion(String version) { this.version = version; } // // @Override // public String toString() { // return "Product{" + // "productId='" + productId + '\'' + // ", description='" + description + '\'' + // ", imageUrl='" + imageUrl + '\'' + // ", price=" + price + // '}'; // } }<file_sep>/src/main/java/com/spring/bm/apv/controller/ApvDocController.java package com.spring.bm.apv.controller; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.spring.bm.apv.model.service.ApvService; import com.spring.bm.common.PageBarFactory; import com.spring.bm.common.PageUrlFactory; @Controller public class ApvDocController { private Logger logger=LoggerFactory.getLogger(ApvDocController.class); private String path=new PageUrlFactory().getUrl(); @Autowired ApvService service; /* 결재 양식 관리 리스트 뷰 호출 */ @RequestMapping("/apv/apvDoc.do") public ModelAndView apvDoc(@RequestParam(value="cPage", required=false, defaultValue="1") int cPage) { int numPerPage = 10; List<Map<String,Object>> list=service.selectDocForm(cPage,numPerPage); int totalCount = service.selectDfCount(); ModelAndView mv = new ModelAndView(); mv.addObject("pageBar",PageBarFactory.getPageBar(totalCount, cPage, numPerPage, path+"/apv/apvDoc.do")); mv.addObject("count", totalCount); mv.addObject("list",list); mv.setViewName("apv/apvDocList"); return mv; } /* 결재 양식 등록 팝업창 */ @RequestMapping("/apv/apvDocEnroll.do") public ModelAndView apvDocEnroll() { ModelAndView mv = new ModelAndView(); List<Map<String,Object>> docCate=service.selectDocCate(); List<Map<String,Object>> docHCate=service.selectDocHCate(); List<Map<String,Object>> docCCate=service.selectDocCCate(); mv.addObject("docCate",docCate); mv.addObject("docHCate",docHCate); mv.addObject("docCCate",docCCate); mv.setViewName("apv/apvDocEnroll"); return mv; } /* 결재 양식 등록 로직*/ @RequestMapping("/apv/apvDocEnrollEnd.do") @ResponseBody public int apvDocEnrollEnd(@RequestParam Map<String,Object> param){ int result=0; try { result=service.insertApvDoc(param); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } /* 결재 양식 수정 팝업창 */ @RequestMapping("/apv/apvDocModify.do") public ModelAndView apvDocModify(@RequestParam(value="dfNo", required=false, defaultValue="1") int dfNo) { ModelAndView mv = new ModelAndView(); List<Map<String,Object>> docCate=service.selectDocCate(); Map<String,Object> dfOne=service.selectDfModi(dfNo); mv.addObject("dfOne",dfOne); mv.addObject("docCate",docCate); mv.setViewName("apv/apvDocModi"); return mv; } /* 결재 양식 수정 로직*/ @RequestMapping("/apv/apvDocModiEnd.do") @ResponseBody public int apvDocModiEnd(@RequestParam Map<String,Object> param){ int result=0; try { result=service.updateApvDoc(param); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } /* 결재 양식 삭제 로직*/ @RequestMapping("/apv/apvDocDelete.do") public ModelAndView apvDocDelete(@RequestParam(value="dfNo", required=false, defaultValue="1") int dfNo){ ModelAndView mv = new ModelAndView(); int result=0; String msg=""; String loc="/apv/apvDoc.do"; try { result=service.deleteApvDoc(dfNo); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if(result>0) { msg="결재양식 삭제 성공"; }else { msg="결재 양식 삭제 실패"; } mv.addObject("msg",msg); mv.addObject("loc",loc); mv.setViewName("common/msg"); return mv; } /* 결재폼 양식 등록 팝업창 */ @RequestMapping("/apv/apvDocHeadEnroll.do") public String apvDocHeadEnroll() { return "apv/apvDocHeadEnroll"; } /* 결재폼 양식 등록 로직*/ @RequestMapping("/apv/apvDocHeadEnrollEnd.do") @ResponseBody public int apvDocHeadEnrollEnd(@RequestParam Map<String,Object> param){ int result=0; try { result=service.insertApvDocHead(param); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } /* 결재 본문 양식 등록 팝업창 */ @RequestMapping("/apv/apvDocContentEnroll.do") public String apvDocContentEnroll() { return "apv/apvDocContentEnroll"; } /* 결재본문 양식 등록 로직*/ @RequestMapping("/apv/apvDocContentEnrollEnd.do") @ResponseBody public int apvDocContentEnrollEnd(@RequestParam Map<String,Object> param){ int result=0; try { result=service.insertApvDocContent(param); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } /* 결재양식 등록->결재폼옵션 변경 로직 */ @RequestMapping(value="/apv/apvDocHChange.do",produces ="application/text; charset=utf8") @ResponseBody public String apvDocHChange(@RequestParam Map<String,Object> param){ int no=Integer.parseInt((String) param.get("no")); String code=service.selectDfhContent(no); return code; } /* 결재양식 등록->본문 양식 변경 로직 */ @RequestMapping(value="/apv/apvDocCChange.do",produces ="application/text; charset=utf8") @ResponseBody public String apvDocCChange(@RequestParam Map<String,Object> param){ int no=Integer.parseInt((String) param.get("no")); String code=service.selectDfcContent(no); return code; } // 기안하기------------ /* 기안하기 리스트 뷰 */ @RequestMapping("/apv/requestApv.do") public ModelAndView requestApvMain(@RequestParam(value="cPage", required=false, defaultValue="1") int cPage) { int numPerPage = 10; List<Map<String,Object>> list=service.selectDocForm(cPage,numPerPage); int totalCount = service.selectDfCount(); ModelAndView mv = new ModelAndView(); mv.addObject("pageBar",PageBarFactory.getPageBar(totalCount, cPage, numPerPage, path+"/apv/requestApv.do")); mv.addObject("count", totalCount); mv.addObject("list",list); mv.setViewName("apv/requestApvMain"); return mv; } /* 기안 등록 뷰 */ @RequestMapping("/apv/requestApvEnroll.do") public ModelAndView requestApvEnroll(@RequestParam(value="dfNo", required=false, defaultValue="1") int dfNo,HttpSession session) { ModelAndView mv = new ModelAndView(); /* List<Map<String,Object>> docCate=service.selectDocCate(); */ Map<String,Object> dfOne=service.selectDfModi(dfNo); //테이블에 값 넣기 //먼저 index로 변수들이 있는지 파악 //-1이면 테이블에 해당 변수 없음. //해당 변수가 있을 때 replace 시켜줌. //replace 시켜줄 때는, 태그로 감싸서 넣기!!나중에 뽑아 쓸 수 있도록 id값을 설정해서 넣기!! //그대로 출력 Map<String,Object> loginEmp=(Map<String, Object>) session.getAttribute("loginEmp"); Map<String,Object> empInfo=service.selectEmpInfoAll(loginEmp); String head=((String)dfOne.get("DFHEADFORM")); ///head에서 index 다 돌려~~!! if(head.indexOf("{{title}}")>-1) { String content=(String)dfOne.get("DFTITLE"); String form=((String)dfOne.get("DFHEADFORM")).replace("{{title}}", content); dfOne.put("DFHEADFORM", form); } if(head.indexOf("{{empName}}")>-1) { String content=(String)empInfo.get("EMPNAME"); String form=((String)dfOne.get("DFHEADFORM")).replace("{{empName}}", content); dfOne.put("DFHEADFORM", form); } if(head.indexOf("{{empEmail}}")>-1) { String content=(String)empInfo.get("EMPEMAIL"); String form=((String)dfOne.get("DFHEADFORM")).replace("{{empEmail}}", content); dfOne.put("DFHEADFORM", form); } if(head.indexOf("{{deptName}}")>-1) { String content=(String)empInfo.get("DEPTNAME"); String form=((String)dfOne.get("DFHEADFORM")).replace("{{deptName}}", content); dfOne.put("DFHEADFORM", form); } if(head.indexOf("{{jobName}}")>-1) { String content=(String)empInfo.get("JOBNAME"); String form=((String)dfOne.get("DFHEADFORM")).replace("{{jobName}}", content); dfOne.put("DFHEADFORM", form); } if(head.indexOf("{{text_box_1}}")>-1) { String content="<input type='text' id='textBox1'/>"; String form=((String)dfOne.get("DFHEADFORM")).replace("{{text_box_1}}", content); dfOne.put("DFHEADFORM", form); } if(head.indexOf("{{approval_line_html}}")>-1) { String content="<table id=\"approval_line_html\" border=\"1px;\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\" valign=\"middle\" width=\"100%\" height=\"100%\"><tr><td id=\"prior1\">1</td><td id=\"prior2\"></td><td id=\"prior3\"></td><td id=\"prior4\"></td><td id=\"prior5\"></td></tr><tr height=\"100px;\"><td id=\"stamp1\"></td><td id=\"stamp2\"></td><td id=\"stamp3\"></td><td id=\"stamp4\"></td><td id=\"stamp5\"></td></tr></table>"; String form=((String)dfOne.get("DFHEADFORM")).replace("{{approval_line_html}}", content); dfOne.put("DFHEADFORM", form); } if(head.indexOf("{{request_name}}")>-1) { String content="<p id=\"requestName\">시행자명</p>"; String form=((String)dfOne.get("DFHEADFORM")).replace("{{request_name}}", content); dfOne.put("DFHEADFORM", form); } if(head.indexOf("{{app_sdate}}")>-1) { String content="<input type='date' id=\"sDate\" />"; String form=((String)dfOne.get("DFHEADFORM")).replace("{{app_sdate}}", content); dfOne.put("DFHEADFORM", form); } if(head.indexOf("{{app_edate}}")>-1) { String content="<input type='date' id=\"eDate\" />"; String form=((String)dfOne.get("DFHEADFORM")).replace("{{app_edate}}", content); dfOne.put("DFHEADFORM", form); } if(head.indexOf("{{pay}}")>-1) { String content="<input type='number' id=\"pay\" />"; String form=((String)dfOne.get("DFHEADFORM")).replace("{{pay}}", content); dfOne.put("DFHEADFORM", form); } mv.addObject("dfOne",dfOne); /* mv.addObject("docCate",docCate); */ mv.setViewName("apv/requestApvEnroll"); return mv; } /* 기안 상신하기 로직 */ @RequestMapping(value="/apv/requestApvEnrollEnd.do",method=RequestMethod.POST) @ResponseBody public int requestApvEnrollEnd(@RequestBody Map<String,Object> param){ int result=0; try { result=service.insertRequestApv(param); } catch (Exception e) { e.printStackTrace(); } return result; } /*상신함*/ @RequestMapping("/apv/sendApv.do") public ModelAndView sendApvList(@RequestParam(value="cPage", required=false, defaultValue="1") int cPage,int loginNo) { int numPerPage = 10; List<Map<String,Object>> list=service.selectSendApvList(cPage,numPerPage,loginNo); int totalCount = service.selectSendApvCount(loginNo); ModelAndView mv = new ModelAndView(); mv.addObject("pageBar",PageBarFactory.getPageBar(totalCount, cPage, numPerPage, path+"/apv/sendApv.do", loginNo)); mv.addObject("count", totalCount); mv.addObject("list",list); mv.setViewName("apv/sendApv"); return mv; } /*상신함 -> 조회하기*/ @RequestMapping("/apv/lookupApvOne.do") public ModelAndView lookupApvOne(@RequestParam(value="no", required=true) int apvNo) { ModelAndView mv = new ModelAndView(); Map<String,Object> apvOne=service.selectLookupApv(apvNo); mv.addObject("apvOne",apvOne); mv.setViewName("apv/lookupApvOne"); return mv; } /*수신함*/ @RequestMapping("/apv/receiveApvList.do") public ModelAndView receiveApvList(@RequestParam(value="cPage", required=false, defaultValue="1") int cPage,int loginNo) { int numPerPage = 10; List<Map<String,Object>> list=service.selectReceiveApvList(cPage,numPerPage,loginNo); int totalCount = service.selectReceiveApvCount(loginNo); ModelAndView mv = new ModelAndView(); mv.addObject("pageBar",PageBarFactory.getPageBar(totalCount, cPage, numPerPage, path+"/apv/receiveApvList.do", loginNo)); mv.addObject("count", totalCount); mv.addObject("list",list); mv.setViewName("apv/receiveApvList"); return mv; } /*시행함*/ @RequestMapping("/apv/enforceApvList.do") public ModelAndView enforceApvList(@RequestParam(value="cPage", required=false, defaultValue="1") int cPage,int loginNo) { System.out.println(loginNo); int numPerPage = 10; List<Map<String,Object>> list=service.selectEnforceApvList(cPage,numPerPage,loginNo); int totalCount = service.selectEnforceApvCount(loginNo); ModelAndView mv = new ModelAndView(); mv.addObject("pageBar",PageBarFactory.getPageBar(totalCount, cPage, numPerPage, path+"/apv/enforceApvList.do", loginNo)); mv.addObject("count", totalCount); mv.addObject("list",list); mv.setViewName("apv/enforceApvList"); return mv; } /*참조함*/ @RequestMapping("/apv/referApvList.do") public ModelAndView referApvList(@RequestParam(value="cPage", required=false, defaultValue="1") int cPage,int loginNo) { int numPerPage = 10; List<Map<String,Object>> list=service.selectReferApvList(cPage,numPerPage,loginNo); int totalCount = service.selectReferApvCount(loginNo); ModelAndView mv = new ModelAndView(); mv.addObject("pageBar",PageBarFactory.getPageBar(totalCount, cPage, numPerPage, path+"/apv/referApvList.do", loginNo)); mv.addObject("count", totalCount); mv.addObject("list",list); mv.setViewName("apv/referApvList"); return mv; } /*참조함 -> 조회하기*/ @RequestMapping("/apv/lookupApvROne.do") public ModelAndView lookupApvROne(@RequestParam(value="apvNo", required=true) int apvNo,int empNo) { ModelAndView mv = new ModelAndView(); Map<String,Object> param=new HashMap<String, Object>(); param.put("apvNo", apvNo); param.put("empNo", empNo); Map<String,Object> apvOne=service.selectLookupApvR(param); if(String.valueOf(apvOne.get("OPENYN")).trim().equals("N")) { int result=0; try { result=service.updateReferYN(param); } catch (Exception e) { e.printStackTrace(); } } mv.addObject("apvOne",apvOne); mv.setViewName("apv/lookupApvOne"); return mv; } /*결재함 -> 결재하기 뷰*/ @RequestMapping("/apv/lookupApvAOne.do") public ModelAndView lookupApvAOne(@RequestParam(value="apvNo", required=true) int apvNo,int empNo) { ModelAndView mv = new ModelAndView(); Map<String,Object> param=new HashMap<String, Object>(); param.put("apvNo", apvNo); param.put("empNo", empNo); Map<String,Object> apvOne=service.selectLookupApvA(param); mv.addObject("apvOne",apvOne); mv.setViewName("apv/lookupApvOne"); return mv; } /*결재하기뷰->결재처리*/ @RequestMapping(value="/apv/apvPermit.do",method=RequestMethod.POST) @ResponseBody public Map<String,Object> apvPermit(@RequestParam Map<String,Object> param) { int result=0; String msg=""; try { result=service.apvPermit(param); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } Map<String,Object> map=new HashMap<String, Object>(); if(result>0) { msg="결재처리 완료"; map=service.selectStamp(param); map.put("msg", msg); }else { msg="결재처리 실패"; map.put("msg", msg); } return map; } /*결재하기뷰->반려처리*/ @RequestMapping("/apv/apvReturn.do") public ModelAndView apvReturn(@RequestParam(value="apvNo", required=true) int apvNo,int empNo,String moreInfo) { ModelAndView mv = new ModelAndView(); Map<String,Object> param=new HashMap<String, Object>(); param.put("apvNo", apvNo); param.put("empNo", empNo); param.put("moreInfo", moreInfo); int result=0; String msg=""; String loc="/apv/lookupApvAOne.do?apvNo="+apvNo+"&empNo="+empNo; try { result=service.apvReturn(param); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if(result>0) { msg="반려처리 완료"; }else { msg="반려처리 실패"; } mv.addObject("msg",msg); mv.addObject("loc",loc); mv.setViewName("common/msg"); return mv; } /*시행함 -> 시행관리 뷰*/ @RequestMapping("/apv/lookupApvEOne.do") public ModelAndView lookupApvEOne(@RequestParam(value="apvNo", required=true) int apvNo,int empNo) { ModelAndView mv = new ModelAndView(); Map<String,Object> param=new HashMap<String, Object>(); param.put("apvNo", apvNo); param.put("empNo", empNo); Map<String,Object> apvOne=service.selectLookupApvEOne(param); mv.addObject("apvOne",apvOne); mv.setViewName("apv/lookupApvOne"); return mv; } /*시행관리뷰->시행처리*/ @RequestMapping("/apv/apvEnforce.do") public ModelAndView apvEnforce(@RequestParam(value="apvNo", required=true) int apvNo,int empNo) { ModelAndView mv = new ModelAndView(); Map<String,Object> param=new HashMap<String, Object>(); param.put("apvNo", apvNo); param.put("empNo", empNo); int result=0; String msg=""; String loc="/apv/lookupApvEOne.do?apvNo="+apvNo+"&empNo="+empNo; try { result=service.apvEnforce(param); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if(result>0) { msg="시행처리 완료"; }else { msg="시행처리 실패"; } mv.addObject("msg",msg); mv.addObject("loc",loc); mv.setViewName("common/msg"); return mv; } /*결재하기뷰->반려처리*/ @RequestMapping("/apv/apvEReturn.do") public ModelAndView apvEReturn(@RequestParam(value="apvNo", required=true) int apvNo,int empNo,String moreInfo) { ModelAndView mv = new ModelAndView(); Map<String,Object> param=new HashMap<String, Object>(); param.put("apvNo", apvNo); param.put("empNo", empNo); param.put("moreInfo", moreInfo); int result=0; String msg=""; String loc="/apv/lookupApvEOne.do?apvNo="+apvNo+"&empNo="+empNo; try { result=service.apvEReturn(param); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if(result>0) { msg="반송처리 완료"; }else { msg="반송처리 실패"; } mv.addObject("msg",msg); mv.addObject("loc",loc); mv.setViewName("common/msg"); return mv; } @RequestMapping("/apv/addReqApvEnroll.do") public ModelAndView addReqApvEnroll(@RequestParam Map<String, Object> param,HttpSession session) { ModelAndView mv = new ModelAndView(); int dfNo=0; String cate=String.valueOf(param.get("temp")).trim(); String ckCol=String.valueOf(param.get("checkCol")).trim(); String pkey=String.valueOf(param.get("pkey")).trim(); int totalPay=0; String sDate=""; String eDate=""; int cateNo=0; String ckCol2=""; String ckColDate=""; String ckColDate2=""; switch(cate) { case "businessTripPay": cateNo=Integer.parseInt(String.valueOf(param.get("BTPNO"))); dfNo=102; totalPay=Integer.parseInt(String.valueOf(param.get("BTPROOM")))+Integer.parseInt(String.valueOf(param.get("BTPTRANSPORTATION")))+Integer.parseInt(String.valueOf(param.get("BTPENTERTAIN"))); sDate=String.valueOf(param.get("BTSTART")); eDate=String.valueOf(param.get("BTEND")); break; case "upAttendance": cateNo=Integer.parseInt(String.valueOf(param.get("UANO"))); dfNo=121; sDate=String.valueOf(param.get("UADATE")); break; case "dayoff": cateNo=Integer.parseInt(String.valueOf(param.get("DONO"))); dfNo=122; sDate=String.valueOf(param.get("DOSTART")); eDate=String.valueOf(param.get("DOEND")); break; case "businessTrip": cateNo=Integer.parseInt(String.valueOf(param.get("BTNO"))); dfNo=120; sDate=String.valueOf(param.get("BTSTART")); eDate=String.valueOf(param.get("BTEND")); break; case "purchaseTab": cateNo=Integer.parseInt(String.valueOf(param.get("PURCODE"))); dfNo=123;//여기 수정 totalPay=Integer.parseInt(String.valueOf(param.get("PURTOTAMT"))); ckCol2=String.valueOf(param.get("checkCol2")).trim(); ckColDate=String.valueOf(param.get("checkColDate")).trim(); ckColDate2=String.valueOf(param.get("checkColDate2")).trim(); break; case "saleTab": cateNo=Integer.parseInt(String.valueOf(param.get("SALCODE"))); dfNo=124;//여기 수정 totalPay=Integer.parseInt(String.valueOf(param.get("SALTOTAMT"))); ckCol2=String.valueOf(param.get("checkCol2")).trim(); ckColDate=String.valueOf(param.get("checkColDate")).trim(); ckColDate2=String.valueOf(param.get("checkColDate2")).trim(); break; } /* List<Map<String,Object>> docCate=service.selectDocCate(); */ Map<String,Object> dfOne=service.selectDfModi(dfNo); //테이블에 값 넣기 //먼저 index로 변수들이 있는지 파악 //-1이면 테이블에 해당 변수 없음. //해당 변수가 있을 때 replace 시켜줌. //replace 시켜줄 때는, 태그로 감싸서 넣기!!나중에 뽑아 쓸 수 있도록 id값을 설정해서 넣기!! //그대로 출력 Map<String,Object> loginEmp=(Map<String, Object>) session.getAttribute("loginEmp"); Map<String,Object> empInfo=service.selectEmpInfoAll(loginEmp); String head=((String)dfOne.get("DFHEADFORM")); ///head에서 index 다 돌려~~!! if(head.indexOf("{{pkey}}")>-1) { String content="<input type='hidden' id=\"pkey\" value='"+pkey+"' />"; String form=((String)dfOne.get("DFHEADFORM")).replace("{{pkey}}", content); dfOne.put("DFHEADFORM", form); } if(head.indexOf("{{ckCol}}")>-1) { String content="<input type='hidden' id=\"ckCol\" value='"+ckCol+"' />"; String form=((String)dfOne.get("DFHEADFORM")).replace("{{ckCol}}", content); dfOne.put("DFHEADFORM", form); } if(head.indexOf("{{ckCol2}}")>-1) { String content="<input type='hidden' id=\"ckCol2\" value='"+ckCol2+"' />"; String form=((String)dfOne.get("DFHEADFORM")).replace("{{ckCol2}}", content); dfOne.put("DFHEADFORM", form); } if(head.indexOf("{{ckColDate}}")>-1) { String content="<input type='hidden' id=\"ckColDate\" value='"+ckColDate+"' />"; String form=((String)dfOne.get("DFHEADFORM")).replace("{{ckColDate}}", content); dfOne.put("DFHEADFORM", form); } if(head.indexOf("{{ckColDate2}}")>-1) { String content="<input type='hidden' id=\"ckColDate2\" value='"+ckColDate2+"' />"; String form=((String)dfOne.get("DFHEADFORM")).replace("{{ckColDate2}}", content); dfOne.put("DFHEADFORM", form); } if(head.indexOf("{{cateName}}")>-1) { String content="<input type='hidden' id=\"cateName\" value='"+cate+"' />"; String form=((String)dfOne.get("DFHEADFORM")).replace("{{cateName}}", content); dfOne.put("DFHEADFORM", form); } if(head.indexOf("{{cateNo}}")>-1) { String content="<input type='hidden' id=\"cateNo\" value='"+cateNo+"' />"; String form=((String)dfOne.get("DFHEADFORM")).replace("{{cateNo}}", content); dfOne.put("DFHEADFORM", form); } if(head.indexOf("{{title}}")>-1) { String content=(String)dfOne.get("DFTITLE"); String form=((String)dfOne.get("DFHEADFORM")).replace("{{title}}", content); dfOne.put("DFHEADFORM", form); } if(head.indexOf("{{empName}}")>-1) { String content=(String)empInfo.get("EMPNAME"); String form=((String)dfOne.get("DFHEADFORM")).replace("{{empName}}", content); dfOne.put("DFHEADFORM", form); } if(head.indexOf("{{empEmail}}")>-1) { String content=(String)empInfo.get("EMPEMAIL"); String form=((String)dfOne.get("DFHEADFORM")).replace("{{empEmail}}", content); dfOne.put("DFHEADFORM", form); } if(head.indexOf("{{deptName}}")>-1) { String content=(String)empInfo.get("DEPTNAME"); String form=((String)dfOne.get("DFHEADFORM")).replace("{{deptName}}", content); dfOne.put("DFHEADFORM", form); } if(head.indexOf("{{jobName}}")>-1) { String content=(String)empInfo.get("JOBNAME"); String form=((String)dfOne.get("DFHEADFORM")).replace("{{jobName}}", content); dfOne.put("DFHEADFORM", form); } if(head.indexOf("{{text_box_1}}")>-1) { String content="<input type='text' id='textBox1'/>"; String form=((String)dfOne.get("DFHEADFORM")).replace("{{text_box_1}}", content); dfOne.put("DFHEADFORM", form); } if(head.indexOf("{{approval_line_html}}")>-1) { String content="<table id=\"approval_line_html\" border=\"1px;\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\" valign=\"middle\" width=\"100%\" height=\"100%\"><tr><td id=\"prior1\">1</td><td id=\"prior2\"></td><td id=\"prior3\"></td><td id=\"prior4\"></td><td id=\"prior5\"></td></tr><tr height=\"100px;\"><td id=\"stamp1\"></td><td id=\"stamp2\"></td><td id=\"stamp3\"></td><td id=\"stamp4\"></td><td id=\"stamp5\"></td></tr></table>"; String form=((String)dfOne.get("DFHEADFORM")).replace("{{approval_line_html}}", content); dfOne.put("DFHEADFORM", form); } if(head.indexOf("{{request_name}}")>-1) { String content="<p id=\"requestName\">시행자명</p>"; String form=((String)dfOne.get("DFHEADFORM")).replace("{{request_name}}", content); dfOne.put("DFHEADFORM", form); } if(head.indexOf("{{app_sdate}}")>-1) { String content="<p id=\"sDate\" >"+sDate+"</p>"; String form=((String)dfOne.get("DFHEADFORM")).replace("{{app_sdate}}", content); dfOne.put("DFHEADFORM", form); } if(head.indexOf("{{app_edate}}")>-1) { String content="<p id=\"eDate\" >"+eDate+"</p>"; String form=((String)dfOne.get("DFHEADFORM")).replace("{{app_edate}}", content); dfOne.put("DFHEADFORM", form); } if(head.indexOf("{{pay}}")>-1) { String content="<p id=\"pay\" >"+totalPay+"</p>"; String form=((String)dfOne.get("DFHEADFORM")).replace("{{pay}}", content); dfOne.put("DFHEADFORM", form); } mv.addObject("dfOne",dfOne); /* mv.addObject("docCate",docCate); */ mv.setViewName("apv/requestApvEnrollAdd"); return mv; } /*결재하기뷰->추가결재 결재처리*/ /*상태YN만 바꾸는 애!!*/ @RequestMapping(value="/apv/apvAddPermit.do",method=RequestMethod.POST) @ResponseBody public Map<String,Object> apvAddPermit(@RequestParam Map<String,Object> m) { //똑같이 처리하는데, serviceImpl에서 종결처리 될 경우에, 가진정보로 테이블 상태 'Y'로 바꿈 //가져온 정보가... //테이블이름,프라이머리키번호,시작일,끝일,청구비용, //상태 yn으로 바꿀 컬럼명 int result=0; String msg=""; try { if(String.valueOf(m.get("cateName")).equals("purchaseTab") || String.valueOf(m.get("cateName")).equals("saleTab")) { result=service.apvAddPermit2(m); }else { result=service.apvAddPermit1(m); } } catch (Exception e) { e.printStackTrace(); } Map<String,Object> map=new HashMap<String, Object>(); if(result>0) { msg="결재처리 완료"; map=service.selectStamp(m); map.put("msg", msg); }else { msg="결재처리 실패"; map.put("msg", msg); } return map; } @RequestMapping(value="/apv/apvSaveUpdate.do",method=RequestMethod.POST) @ResponseBody public int apvSaveUpdate(@RequestParam Map<String,Object> param) { int result=0; try { result=service.apvSaveUpdate(param); } catch (Exception e) { e.printStackTrace(); } return result; } /*결재양식 검색*/ @RequestMapping("/apv/searchDocForm.do") public ModelAndView searchDocForm(@RequestParam(value="cPage",required=false, defaultValue="0") int cPage, @RequestParam Map<String, Object> param) { int numPerPage = 10; List<Map<String, String>> list = service.selectDfSearchList(cPage, numPerPage, param); int totalCount = service.selectDfSearchCount(param); ModelAndView mv=new ModelAndView(); mv.addObject("pageBar", PageBarFactory.getPageBar(totalCount, cPage, numPerPage, path+"/apv/searchDocForm.do",""+param.get("type"), ""+param.get("data"))); mv.addObject("count", totalCount); mv.addObject("list", list); mv.setViewName("apv/apvDocList"); return mv; } @RequestMapping("/apv/searchDocFormReq.do") public ModelAndView searchDocFormReq(@RequestParam(value="cPage",required=false, defaultValue="0") int cPage, @RequestParam Map<String, Object> param) { int numPerPage = 10; List<Map<String, String>> list = service.selectDfSearchList(cPage, numPerPage, param); int totalCount = service.selectDfSearchCount(param); ModelAndView mv=new ModelAndView(); mv.addObject("pageBar", PageBarFactory.getPageBar(totalCount, cPage, numPerPage, path+"/apv/searchDocFormReq.do",""+param.get("type"), ""+param.get("data"))); mv.addObject("count", totalCount); mv.addObject("list", list); mv.setViewName("apv/requestApvMain"); return mv; } } <file_sep>/src/main/java/com/spring/bm/employee/model/vo/EmpFile.java package com.spring.bm.employee.model.vo; import lombok.Data; import lombok.ToString; @Data @ToString public class EmpFile { private int efNo; private int empNo; private String efcName; private String efOrgName; private String efReName; }
602b762b4ad7030e9c25fbce7f3018b77f8f5b5d
[ "Java" ]
46
Java
ririkat/boxman
830e42ebc1e43fc513878c60238eab6ed13ff6f9
8cebae83acb1d08850a6d4ba8c2b1db678ebbe4e
refs/heads/master
<repo_name>SFarida/fetcms<file_sep>/src/main/java/com/example/fetcms/excell/Shape.java package com.example.fetcms.excell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; public class Shape { public static void excellTemplate(XSSFSheet worksheet, int startRowIndex, int startColIndex) { worksheet.setColumnWidth(0, 3000); worksheet.setColumnWidth(1, 10000); Font font = worksheet.getWorkbook().createFont(); font.setBoldweight(Font.BOLDWEIGHT_BOLD); XSSFCellStyle headerCellStyle = worksheet.getWorkbook().createCellStyle(); headerCellStyle.setAlignment(CellStyle.ALIGN_CENTER); headerCellStyle.setWrapText(true); headerCellStyle.setFont(font); headerCellStyle.setBorderRight(CellStyle.BORDER_THICK); headerCellStyle.setBorderBottom(CellStyle.BORDER_THICK); XSSFRow rowHeader = worksheet.createRow((short) startRowIndex); rowHeader.setHeight((short) 500); XSSFCell cell1 = rowHeader.createCell(startColIndex+0); cell1.setCellValue("Chapter Number"); cell1.setCellStyle(headerCellStyle); XSSFCell cell2 = rowHeader.createCell(startColIndex+1); cell2.setCellValue("Course Outline"); cell2.setCellStyle(headerCellStyle); } } <file_sep>/settings.gradle rootProject.name = 'fetcms' <file_sep>/src/main/java/com/example/fetcms/domain/CourseOutline.java package com.example.fetcms.domain; import com.fasterxml.jackson.annotation.JsonBackReference; import javax.persistence.*; @Entity @Table(name = "courseOutline") public class CourseOutline { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "courseOutline_id") private long courseOutline_id; @Column(name = "chapter_id") private Long chapter; @Column(name = "content") private String content; @ManyToOne @JsonBackReference @JoinTable(name = "course_courseOutline", joinColumns = @JoinColumn(name = "courseOutline_id", referencedColumnName = "courseOutline_id"), inverseJoinColumns = @JoinColumn(name = "course_id", referencedColumnName = "course_id")) private Course course; public CourseOutline(){ } public CourseOutline(Long chapter, String content){ this.chapter = chapter; this.content = content; } public long getCourseOutline_id() { return courseOutline_id; } public void setCourseOutline_id(long courseOutline_id) { this.courseOutline_id = courseOutline_id; } public Long getChapter() { return chapter; } public void setChapter(Long chapter) { this.chapter = chapter; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Course getCourse() { return course; } public void setCourse(Course course) { this.course = course; } } <file_sep>/build.gradle buildscript { ext { springBootVersion = '1.5.14.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' group = 'com.example' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile('org.springframework.boot:spring-boot-starter-data-jpa') //compile('org.springframework.boot:spring-boot-starter-jdbc') compile('org.springframework.boot:spring-boot-starter-web') runtime('org.springframework.boot:spring-boot-devtools') runtime('mysql:mysql-connector-java') testCompile('org.springframework.boot:spring-boot-starter-test') // https://mvnrepository.com/artifact/org.hibernate/hibernate-core compile group: 'org.hibernate', name: 'hibernate-core', version: '5.0.2.Final' // https://mvnrepository.com/artifact/mysql/mysql-connector-java //compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.11' // https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml compile group: 'org.apache.poi', name: 'poi-ooxml', version: '3.9' // https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload compile group: 'commons-fileupload', name: 'commons-fileupload', version: '1.3.3' // https://mvnrepository.com/artifact/commons-io/commons-io compile group: 'commons-io', name: 'commons-io', version: '2.6' // https://mvnrepository.com/artifact/org.apache.xmlbeans/xmlbeans compile group: 'org.apache.xmlbeans', name: 'xmlbeans', version: '2.6.0' // https://mvnrepository.com/artifact/com.mchange/c3p0 //compile group: 'com.mchange', name: 'c3p0', version: '0.9.5.2' compile('com.lowagie:itext:2.1.7') } <file_sep>/src/main/java/com/example/fetcms/controller/CourseController.java package com.example.fetcms.controller; import com.example.fetcms.domain.Course; import com.example.fetcms.domain.CourseOutline; import com.example.fetcms.excell.Input; import com.example.fetcms.report.GeneratePdfReport; import com.example.fetcms.repository.CourseRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.List; @RestController public class CourseController { @Autowired private CourseRepository courseRepository; @RequestMapping("/courses") public ResponseEntity<List<Course>> getAllCourses(){ List<Course> courses; courses = (List<Course>) courseRepository.findAll(); return new ResponseEntity<>(courses, HttpStatus.OK); } @RequestMapping( "/courses/level/{level}") public ResponseEntity<List<Course>> getAllCourseByLevel(@PathVariable int level){ List<Course> courses; courses = courseRepository.findByLevel(level); return new ResponseEntity<>(courses, HttpStatus.OK); } @RequestMapping( "/courses/course_code/{course_code}") public ResponseEntity<List<Course>> getAllCourseByCode(@PathVariable String course_code){ List<Course> courses; courses = courseRepository.findByCode(course_code); return new ResponseEntity<>(courses, HttpStatus.OK); } @RequestMapping( "/Courses/{level}/{program}/{semester}") public ResponseEntity<List<Course>> getAllCourseByFilter(@PathVariable int level, @PathVariable String program, @PathVariable int semester){ List<Course> courses; courses = courseRepository.findByFilter(level, program, semester); return new ResponseEntity<>(courses, HttpStatus.OK); } @RequestMapping(method=RequestMethod.POST, value="/courses") public ResponseEntity<Course> addCourse(@RequestBody Course course){ Course newcourse; newcourse = courseRepository.save(course); return new ResponseEntity<>(newcourse, HttpStatus.OK); } @RequestMapping("/courses/{id}") public ResponseEntity<Course> getCourse(@PathVariable Long id){ Course particularCourse; particularCourse = courseRepository.findOne(id); return new ResponseEntity<>(particularCourse, HttpStatus.OK); } @RequestMapping(method=RequestMethod.DELETE, value="/courses/{id}") public ResponseEntity<?> deleteCourse(@PathVariable Long id){ courseRepository.delete(id); return new ResponseEntity<>("delete", HttpStatus.OK); } @RequestMapping(method=RequestMethod.PUT, value="/courses/{id}") public ResponseEntity<Course> updateCourse(@RequestBody Course course, @PathVariable Long id){ Course updatedcourse; updatedcourse = courseRepository.save(course); return new ResponseEntity<>(updatedcourse, HttpStatus.OK); } //***********************************Excell************************************// @RequestMapping( value = "/excelSheet", method = RequestMethod.GET, consumes = MediaType.ALL_VALUE ) public void downloadExcel(HttpServletResponse response) throws ClassNotFoundException, IOException { Input.download(response); } @RequestMapping( value = "/upload", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE ) public ResponseEntity<List<CourseOutline>> customersFormUpload(@RequestParam("file") MultipartFile file) throws IOException { List<CourseOutline> output; output =Input.ExcellUpload(file); return new ResponseEntity<>(output, HttpStatus.OK); } @RequestMapping("/all") public void allClass() { Class<?> current = Course.class; while (current.getSuperclass() != null) { // we don't want to process Object.class // do something with current's fields current = current.getSuperclass(); System.out.println(current); } } //************************************Pdf Report********************************// @RequestMapping(value = "/pdfreport", method = RequestMethod.POST, produces = MediaType.APPLICATION_PDF_VALUE) public ResponseEntity<InputStreamResource> pdfReport(@RequestBody List<Course> courselist) throws IOException { // List<Course> courselist=courseRepository.findAll(); ByteArrayInputStream bis = GeneratePdfReport.courseReport(courselist); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType("application/pdf")); headers.add("Content-Disposition", "offline; filename = courses.pdf"); return ResponseEntity .ok() .headers(headers) .contentType(MediaType.APPLICATION_PDF) .body(new InputStreamResource(bis)); } //@Autowired //private CourseService courseService; // get -view() -all courses irrespective of the program /* @RequestMapping("/departments/courses") public List<Course> getAllCourses(){ return courseService.getAllCourses(); } */ /* // get -view() @RequestMapping("/departments/programs/{id}/courses") public List<Course> getAllCoursesPerProgram(@PathVariable Long id){ return courseService.getAllCoursesPerProgram(id); } // get() -individual fetch @RequestMapping("/departments/{departmentId}/programs/{programId}/courses/{id}") public Course getProgram(@PathVariable Long id){ return courseService.getCourse(id); } */ /* // post -add() @RequestMapping(method=RequestMethod.POST, value="/departments/{departmentId}/programs/{programId}/courses") public void addCourse(@RequestBody Course course, @PathVariable Long programId, @PathVariable Long departmentId){ course.setProgram(new Program(programId, "", departmentId)); courseService.addCourse(course); } /* // put -update() @RequestMapping(method=RequestMethod.PUT, value="/departments/{departmentId}/programs/{programId}/courses/{id}") public void updateCourse(@RequestBody Course course, @PathVariable Long id, @PathVariable Long departmentId, @PathVariable Long programId){ course.setProgram(new Program(programId, "",departmentId)); courseService.updateCourse(course); } // delete() @RequestMapping(method=RequestMethod.DELETE, value="/departments/{departmentId}/programs/{programId}/courses/{id}") public void deleteCourse(@PathVariable Long id){ courseService.deleteCourse(id); } */ } <file_sep>/src/main/java/com/example/fetcms/service/CourseService.java package com.example.fetcms.service; import com.example.fetcms.domain.Course; import com.example.fetcms.repository.CourseRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class CourseService { @Autowired private CourseRepository courseRepository; // get() -gets all the list of courses irrespective of the program /* public List<Course> getAllCourses(){ List<Course> courses = new ArrayList<>(); CourseRepository.findAll() .forEach(courses::add); return courses; } // get() -gets all the list of courses of a particular program public List<Course> getAllCoursesPerLevel(Long programId){ List<Course> courses = new ArrayList<>(); courseRepository.findByLevel(level); return courses; } // add() service post public void addCourse(Course course) { courseRepository.save(course); } /* // get() -fetching individual courses public Course getCourse(Long id){ return courseRepository.findOne(id); } // update() -put public void updateCourse(Course course){ courseRepository.save(course); } // delete() public void deleteCourse(Long id) { courseRepository.delete(id); } */ }
30fcaf28dcffddff81c2602c8a096a02536b0198
[ "Java", "Gradle" ]
6
Java
SFarida/fetcms
da0e5758497327816cd515d85e619f7336920ba8
ac82b655a43f4ac4002284b81ca4b61738a8984b
refs/heads/master
<repo_name>nsanchez1980/freecodecamp.org<file_sep>/time_calculator.py def add_time(start, duration, day=""): new_time = "" current_time = [] current_hour = [] current_day = 0 days_later = 0 time_to_add = [] more_days = 0 day_of_the_week = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"] current_day = 0 if day!="": while current_day <= 6: if day.lower() == day_of_the_week[current_day].lower(): break else: current_day = current_day + 1 current_time = start.split(" ") current_hour = current_time[0].split(":") hour = int(current_hour[0]) if current_time[1] == "PM": hour = hour + 12 minute = int(current_hour[1]) time_to_add = duration.split(":") minute = minute + int(time_to_add[1]) if minute > 59: hour = hour + 1 minute = minute - 60 hour = hour + int(time_to_add[0]) while hour >= 24: hour = hour - 24 more_days = more_days + 1 days_later = more_days if hour == 24: hour = 0 if more_days > 0: while current_day <= 6: current_day = current_day + 1 more_days = more_days - 1 if current_day>6: current_day = 0 if more_days == 0: break if hour > 12: new_time = str(hour - 12)+":"+'{:02d}'.format(minute)+" PM" elif hour == 12: new_time = "12:"+'{:02d}'.format(minute)+" PM" elif hour == 0: new_time = "12:"+'{:02d}'.format(minute)+" AM" else: new_time = str(hour)+":"+'{:02d}'.format(minute) + " AM" if day!="": new_time = new_time + ", " + day_of_the_week[current_day] if days_later>0: if days_later==1: new_time = new_time + " (next day)" else: new_time = new_time + " (" + str(days_later) + " days later)" return new_time print(add_time("2:59 AM", "24:00", "saturDay")) <file_sep>/README.md # freecodecamp.org Several exercises/projects from the freecodecamp courses In Budget App: At first I thought the ledger object needed to be a 2d list, but i misread the instructions, it was meant to be a list of dictionaries, soooo... the code may be a little messy and unoptimized (even to my standards) <file_sep>/arithmetic_formatter.py def arithmetic_arranger(problems, display_solutions = ""): import re operands = [] operators = [] solutions = [] whichisbigger = [] sumaoresta = [] check = [] index = 0 arranged_problems = "" primera_linea = "" segunda_linea = "" tercera_linea = "" cuarta_linea = "" #check for # of problems if len(problems)>5: return("Error: Too many problems.") #extract data and perfom calculations while index < len(problems): operands.append(re.findall("[0-9]+", problems[index])) operators.append(re.findall("[+-]", problems[index])) if int(operands[index][0])>int(operands[index][1]): whichisbigger.append(True) else: whichisbigger.append(False) if str(operators[index]).find('+') == 2: sumaoresta.append(True) solutions.append(int(operands[index][0])+int(operands[index][1])) check.append(problems[index].split("+")) try: a = int(check[index][0]) b = int(check[index][1]) except: return ("Error: Numbers must only contain digits.") elif str(operators[index]).find('-') == 2: sumaoresta.append(False) solutions.append(int(operands[index][0])-int(operands[index][1])) check.append(problems[index].split("-")) try: a = int(check[index][0]) b = int(check[index][1]) except: return ("Error. Numbers must only contain digits.") else: return("Error: Operator must be '+' or '-'.") if int(operands[index][0])>9999 or int(operands[index][1])>9999: return("Error: Numbers cannot be more than four digits.") index = index + 1 index = 0 while index < len(problems): if whichisbigger[index]: #el de arriba es más grande if index==0: primera_linea = str(operands[index][0]).rjust(len(str(operands[index][0]))+2, " ") if sumaoresta[index]: segunda_linea = "+ " + str(operands[index][1]).rjust(len(str(operands[index][0])), " ") else: segunda_linea = "- " + str(operands[index][1]).rjust(len(str(operands[index][0])), " ") tercera_linea = "".rjust(len(str(operands[index][0]))+2, "-") if display_solutions: cuarta_linea = str(solutions[index]).rjust(len(str(operands[index][0]))+2, " ") else: primera_linea = primera_linea + str(operands[index][0]).rjust(len(str(operands[index][0]))+6, " ") if sumaoresta[index]: segunda_linea = segunda_linea + " +"+ str(operands[index][1]).rjust(len(str(operands[index][0])) + 1, " ") else: segunda_linea = segunda_linea + " -"+ str(operands[index][1]).rjust(len(str(operands[index][0])) + 1, " ") tercera_linea = tercera_linea + " " + "".rjust(len(str(operands[index][0]))+2, "-") if display_solutions: cuarta_linea = cuarta_linea + " " + str(solutions[index]).rjust(len(str(operands[index][0]))+2, " ") else: #el de abajo es más grande o son los dos iguales, segual if index==0: primera_linea = str(operands[index][0]).rjust(len(str(operands[index][1]))+2, " ") if sumaoresta[index]: segunda_linea = "+ " + str(operands[index][1]).rjust(len(str(operands[index][1])), " ") else: segunda_linea = "- " + str(operands[index][1]).rjust(len(str(operands[index][1])), " ") tercera_linea = "".rjust(len(str(operands[index][1]))+2, "-") if display_solutions: cuarta_linea = str(solutions[index]).rjust(len(str(operands[index][1]))+2, " ") else: primera_linea = primera_linea + str(operands[index][0]).rjust(len(str(operands[index][1]))+6, " ") if sumaoresta[index]: segunda_linea = segunda_linea + " + " + operands[index][1] else: segunda_linea = segunda_linea + " - " + operands[index][1] tercera_linea = tercera_linea + " " + "".rjust(len(str(operands[index][1]))+2, "-") if display_solutions: cuarta_linea = cuarta_linea + " " + str(solutions[index]).rjust(len(str(operands[index][1]))+2, " ") index = index + 1 #format the string to match the required solution arranged_problems = primera_linea + "\n" + segunda_linea + "\n" + tercera_linea if display_solutions == True: arranged_problems = arranged_problems + "\n" + cuarta_linea return arranged_problems print(arithmetic_arranger(["32 - 698", "1 - 3801", "45 + 43", "123 + 49"], True)) <file_sep>/budget_app.py class Category: def __init__(self, categoria): self.categoria = categoria self.ledger = [] def __str__(self): result = self.categoria.center(30,"*") for x in self.ledger: result = result + "\n" + x["description"].ljust(23)[:23] + str("%.2f"%float(x["amount"])).rjust(7) result = result + "\n" + "Total: " + str("%.2f"%float(self.get_balance())) return result def deposit(self, amount, description=""): self.ledger.append({"amount": amount, "description": description}) def withdraw(self, amount, description=""): if self.check_funds(amount): self.ledger.append({"amount": amount*-1, "description": description}) return True return False def get_balance(self): total = 0 for x in self.ledger: total = total + x["amount"] return total def transfer(self, cantidad, aquien): if self.check_funds(cantidad): self.withdraw(cantidad, "Transfer to " + aquien.categoria) aquien.deposit(cantidad, "Transfer from " + self.categoria) return True return False def check_funds(self, amount): total = 0 for x in self.ledger: total = total + x["amount"] if total < amount: return False return True def create_spend_chart(categories): sum = 0 result = "Percentage spent by category\n" spent = [] total = 0 porcentajes = [] maxlen = 0 for x in categories: for y in x.ledger: if y["amount"] < 0: sum = sum + abs(y["amount"]) total = total + abs(y["amount"]) spent.append([sum,x.categoria]) sum = 0 for x in spent: this = [int(x[0]*100/total),x[1]] porcentajes.append(this) index = 100 while index >=0: result= result + str(index).rjust(3)+"|" for n in range(len(porcentajes)): if porcentajes[n][0] >= index: result = result + " o " else: result = result + " " result = result + " \n" index = index - 10 result = result + " " for n in range(len(spent)): result = result + "---" result = result + "-\n " for n in porcentajes: if len(n[1]) > maxlen: maxlen = len(n[1]) for n in range(maxlen): for x in porcentajes: try: a = str(x[1])[n] result = result + a.center(3) except: a = " " result = result + a.center(3) result = result + " \n " return result[:-5] food = Category("Food") entertainment = Category("Entertainment") business = Category("Business") food.deposit(900, "deposit") entertainment.deposit(900, "deposit") business.deposit(900, "deposit") food.withdraw(105.55) entertainment.withdraw(33.40) business.withdraw(10.99) actual = create_spend_chart([business, food, entertainment]) expected = "Percentage spent by category\n100| \n 90| \n 80| \n 70| o \n 60| o \n 50| o \n 40| o \n 30| o \n 20| o o \n 10| o o \n 0| o o o \n ----------\n B F E \n u o n \n s o t \n i d e \n n r \n e t \n s a \n s i \n n \n m \n e \n n \n t " print(actual==expected) print(actual) print(expected) <file_sep>/shape_calculator.py class Rectangle: def __init__(self, width, height): self.width = width self.height = height def __str__(self): return "Rectangle(width=" + str(self.width) + ", height=" + str(self.height) + ")" def set_width(self, width): self.width = width def set_height(self, height): self.height = height def get_area(self): return self.width * self.height def get_perimeter(self): return self.width*2 + self.height*2 def get_diagonal(self): return (self.width**2 + self.height**2)**.5 def get_picture(self): result = "" if self.width>50 or self.height>50: return "Too big for picture." for x in range(self.height): for y in range(self.width): result = result + "*" y = y + 1 result = result + "\n" x = x + 1 y = 0 return result def get_amount_inside(self, shape): return int(self.width/shape.width)*int(self.height/shape.height) class Square(Rectangle): def __init__(self, side): self.width = side self.height = side def __str__(self): return "Square(side=" + str(self.width) + ")" def set_side(self, side): self.width = side self.height = side rect = Rectangle(10, 5) print(rect.get_area()) rect.set_height(3) print(rect.get_perimeter()) print(rect) print(rect.get_picture()) sq = Square(9) print(sq.get_area()) sq.set_side(4) print(sq.get_diagonal()) print(sq) print(sq.get_picture()) rect.set_height(8) rect.set_width(16) print(rect.get_amount_inside(sq))<file_sep>/prob_calculator.py import copy import random from collections import Counter class Hat(): def __init__(self, **args): self.args = args self.contents = [] for x,y in args.items(): for n in range(y): self.contents.append(x) n = n + 1 def draw(self, num): if num>=len(self.contents): return self.contents result = list() for x in range(num): a = random.choice(self.contents) result.append(a) self.contents.remove(a) x = x + 1 return result def experiment(hat, expected_balls, num_balls_drawn, num_experiments): index = 0 m = 0 counts = dict() istrue = list() originalhat = copy.deepcopy(hat) for x in range(num_experiments): for ball in originalhat.draw(num_balls_drawn): counts[ball] = counts.get(ball, 0) + 1 for ball in expected_balls: if counts.get(ball,0) >= expected_balls.get(ball,0): istrue.append(True) else: istrue.append(False) print(istrue) if len(istrue)==istrue.count(True): m = m + 1 istrue.clear() counts.clear() x = x + 1 originalhat = copy.deepcopy(hat) return m/num_experiments hat = Hat(blue=3,red=2,green=6) probability = experiment(hat=hat, expected_balls={"blue":2,"green":1}, num_balls_drawn=4, num_experiments=1000) actual = probability expected = 0.272 print(actual) print(expected) hat = Hat(yellow=5,red=1,green=3,blue=9,test=1) probability = experiment(hat=hat, expected_balls={"yellow":2,"blue":3,"test":1}, num_balls_drawn=20, num_experiments=100) actual = probability expected = 1.0 print(actual) print(expected)
d94171afaa1ca9122242900a9d8f19e9364e749c
[ "Markdown", "Python" ]
6
Python
nsanchez1980/freecodecamp.org
e738e79f9720e1f204e3509b49d26be5d49e22e1
045e251c4682ca424912527e69ade5a862c402f9
refs/heads/master
<repo_name>a1498506790/DatePicker<file_sep>/app/src/main/java/com/mir/datepicker/DialogUtils.java package com.mir.datepicker; import android.content.Context; import android.support.v7.app.AlertDialog; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; /** * @data 2018-08-01 * @desc */ class DialogUtils { static void showDialog(Context context, String title, String message, final View.OnClickListener onClickListener){ TextView tvTitle, tvMsg, tvCancel, tvAffirm; View view = LayoutInflater.from(context).inflate(R.layout.layout_dialog, null); tvTitle = view.findViewById(R.id.tv_title); tvMsg = view.findViewById(R.id.tv_msg); tvCancel = view.findViewById(R.id.tv_cancel); tvAffirm = view.findViewById(R.id.tv_affirm); final AlertDialog dialog = new AlertDialog.Builder(context) .setView(view) .create(); dialog.show(); WindowManager.LayoutParams layoutParams = dialog.getWindow().getAttributes(); layoutParams.width = dp2px(context, 300f); dialog.getWindow().setAttributes(layoutParams); if (!TextUtils.isEmpty(title)) tvTitle.setText(title); if (!TextUtils.isEmpty(message)) tvMsg.setText(message); tvCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); tvAffirm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); onClickListener.onClick(view); } }); } static void showEditDialog(Context context, String title, String hint, final OnEdtDialogClickListener onEdtDialogClickListener){ TextView tvTitle, tvCancel, tvAffirm; final EditText edt; View view = LayoutInflater.from(context).inflate(R.layout.layout_edit_dialog, null); tvTitle = view.findViewById(R.id.tv_title); edt = view.findViewById(R.id.edt); tvCancel = view.findViewById(R.id.tv_cancel); tvAffirm = view.findViewById(R.id.tv_affirm); final AlertDialog dialog = new AlertDialog.Builder(context) .setView(view) .create(); dialog.show(); WindowManager.LayoutParams layoutParams = dialog.getWindow().getAttributes(); layoutParams.width = dp2px(context, 300f); dialog.getWindow().setAttributes(layoutParams); dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); if (!TextUtils.isEmpty(title)) tvTitle.setText(title); if (!TextUtils.isEmpty(hint)) edt.setHint(hint); tvCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); tvAffirm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); if (onEdtDialogClickListener != null){ onEdtDialogClickListener.onEditDialog(edt.getText().toString()); } } }); } interface OnEdtDialogClickListener{ void onEditDialog(String content); } static void showItemDialog(Context context, String title, String[] items, final OnItemDialogClickListener onItemDialogClickListener){ TextView tvTitle; ListView listView; View view = LayoutInflater.from(context).inflate(R.layout.layout_item_dialog, null); tvTitle = view.findViewById(R.id.tv_title); listView = view.findViewById(R.id.listView); final AlertDialog dialog = new AlertDialog.Builder(context) .setView(view) .create(); dialog.show(); WindowManager.LayoutParams layoutParams = dialog.getWindow().getAttributes(); layoutParams.width = dp2px(context, 300f); dialog.getWindow().setAttributes(layoutParams); if (!TextUtils.isEmpty(title)) tvTitle.setText(title); listView.setAdapter(new ArrayAdapter<>(context, R.layout.layout_item_dialog_item, items)); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { dialog.dismiss(); if (onItemDialogClickListener != null){ onItemDialogClickListener.onItemDialog(i); } } }); } interface OnItemDialogClickListener{ void onItemDialog(int i); } private static int dp2px(Context context,float dpValue){ float scale = context.getResources().getDisplayMetrics().density; return (int)(dpValue * scale + 0.5f); } } <file_sep>/app/src/main/java/com/mir/datepicker/MainActivity.java package com.mir.datepicker; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.FrameLayout; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private FrameLayout mFrameLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mFrameLayout = findViewById(R.id.llt_content); findViewById(R.id.btn1).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { DialogUtils.showDialog(MainActivity.this, "温馨提示", "确定要清除内存吗?", new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this, "确定", Toast.LENGTH_SHORT).show(); } }); } }); findViewById(R.id.btn2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { DialogUtils.showEditDialog(MainActivity.this, "昵称", "请输入昵称", new DialogUtils.OnEdtDialogClickListener() { @Override public void onEditDialog(String content) { Toast.makeText(MainActivity.this, content, Toast.LENGTH_SHORT).show(); } }); } }); findViewById(R.id.btn3).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final String[] sexs = {"男", "女"}; DialogUtils.showItemDialog(MainActivity.this, "性别", sexs, new DialogUtils.OnItemDialogClickListener() { @Override public void onItemDialog(int i) { Toast.makeText(MainActivity.this, "选择了 : " + sexs[i], Toast.LENGTH_SHORT).show(); } }); } }); findViewById(R.id.btn4).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ProgressUtils.show(MainActivity.this); new Handler().postDelayed(new Runnable() { @Override public void run() { ProgressUtils.dissmiss(); } }, 2000); } }); findViewById(R.id.btn5).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //mFrameLayout 要展示多状态的布局返回 StatusUtils.create(mFrameLayout).showLoading(); //设置加载中状态 } }); findViewById(R.id.btn6).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { StatusUtils.create(mFrameLayout).fail(new View.OnClickListener() { //设置加载失败状态 @Override public void onClick(View view) { StatusUtils.create(mFrameLayout).showLoading(); new Handler().postDelayed(new Runnable() { @Override public void run() { StatusUtils.create(mFrameLayout).hint(); } }, 2000); } }); } }); findViewById(R.id.btn7).setOnClickListener(new View.OnClickListener() { //隐藏多状态布局, 显示主布局 @Override public void onClick(View view) { StatusUtils.create(mFrameLayout).hint(); } }); } } <file_sep>/app/src/main/java/com/mir/datepicker/StatusUtils.java package com.mir.datepicker; import android.app.Activity; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; /** * @data 2018-08-01 * @desc */ public class StatusUtils { private Activity mActivity; private ViewGroup mViewGroup; private StatusLayout mStatusLayout; private RelativeLayout mRlStatus; static StatusUtils mStatusUtils = null; public StatusUtils(Activity activity){ this.mActivity = activity; } public StatusUtils(ViewGroup viewGroup) { mViewGroup = viewGroup; } public static StatusUtils create(Activity activity){ mStatusUtils = new StatusUtils(activity); return mStatusUtils; } public static StatusUtils create(ViewGroup viewGroup){ mStatusUtils = new StatusUtils(viewGroup); return mStatusUtils; } void showLoading(){ if (mActivity != null) { mRlStatus = mActivity.findViewById(R.id.rl_status); if (mRlStatus == null) { mStatusLayout = new StatusLayout(mActivity); mActivity.addContentView(mStatusLayout, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); }else{ mStatusLayout = (StatusLayout) mRlStatus.getParent(); } mStatusLayout.setStatus(StatusLayout.STATUS_LOADING); } else if (mViewGroup != null) { mRlStatus = mViewGroup.findViewById(R.id.rl_status); if (mRlStatus == null) { mStatusLayout = new StatusLayout(mViewGroup.getContext()); mViewGroup.addView(mStatusLayout, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); }else{ mStatusLayout = (StatusLayout) mRlStatus.getParent(); } mStatusLayout.setStatus(StatusLayout.STATUS_LOADING); } } void hint(){ if (mActivity != null) { mRlStatus = mActivity.findViewById(R.id.rl_status); if (mRlStatus == null) { mStatusLayout = new StatusLayout(mActivity); mActivity.addContentView(mStatusLayout, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); }else{ mStatusLayout = (StatusLayout) mRlStatus.getParent(); } mStatusLayout.setStatus(StatusLayout.STATUS_HIDE); } else if (mViewGroup != null) { mRlStatus = mViewGroup.findViewById(R.id.rl_status); if (mRlStatus == null) { mStatusLayout = new StatusLayout(mViewGroup.getContext()); mViewGroup.addView(mStatusLayout, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); }else{ mStatusLayout = (StatusLayout) mRlStatus.getParent(); } mStatusLayout.setStatus(StatusLayout.STATUS_HIDE); } } void fail(View.OnClickListener onClickListener){ if (mActivity != null) { mRlStatus = mActivity.findViewById(R.id.rl_status); if (mRlStatus == null) { mStatusLayout = new StatusLayout(mActivity); mActivity.addContentView(mStatusLayout, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); }else{ mStatusLayout = (StatusLayout) mRlStatus.getParent(); } mStatusLayout.setStatus(StatusLayout.STATUS_LOAD_FAIL, onClickListener); } else if (mViewGroup != null) { mRlStatus = mViewGroup.findViewById(R.id.rl_status); if (mRlStatus == null) { mStatusLayout = new StatusLayout(mViewGroup.getContext()); mViewGroup.addView(mStatusLayout, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); }else{ mStatusLayout = (StatusLayout) mRlStatus.getParent(); } mStatusLayout.setStatus(StatusLayout.STATUS_LOAD_FAIL, onClickListener); } } }
c376cbf4bd91675bd2340613d6c0b2483b7bf53d
[ "Java" ]
3
Java
a1498506790/DatePicker
a90ae3259f97d4a695751f772b277332f94f1d30
7cde280107994a2db89f883ac88c144ba80ef547
refs/heads/master
<repo_name>harshyatishmishra/Credit-Card-System-Server<file_sep>/__test__/luhn.test.js const luhn = require('../Validator/luhnCheck'); test('Success Luhn Check ', () => { expect(luhn.luhn10Check('4916422822484260567')).toBe(true); }); test('Failed Luhn Check ', () => { expect(luhn.luhn10Check('49164228')).toBe(false); }); test('Failed Luhn Check with alpha value', () => { expect(luhn.luhn10Check('abcd')).toBe(false); }); test('Failed Luhn Check with null ', () => { expect(luhn.luhn10Check(null)).toBe(false); }); /** Other test cases * test('when file is not present. it should write the file with data') * test('when file is present. it should append data in the file') * test('creditCardController.addDetails with invalid card number') * test('creditCardController.addDetails with invalid card number') * test('mock creditCardController.creditCardDetails to check return value') */<file_sep>/Controller/creditCardController.js const writefile = require('./writefile'); const readfile = require('./readfile'); const luhn = require('../Validator/luhnCheck'); module.exports.addDetails = function (data, callback) { if (!luhn.luhn10Check(data.cardnumber)) { callback({ status: 422, msg: 'Luhn Check failed. Credit Card Number is not valid.' }); return; } writefile.writeDetails(data, function (d) { callback(d); }); } module.exports.creditCardDetails = function (callback) { readfile.getAllDetails(function (call) { callback(call); }); } <file_sep>/server.js const cors = require('cors') var express = require('express'); var bodyParser = require('body-parser'); const creditCardController = require('./Controller/creditCardController'); const { check, validationResult } = require('express-validator'); const app = express(); const port = 3000; app.use(express.json()); app.use(bodyParser.json()); var corsOptions = { origin: 'http://localhost:4000' } app.use(cors(corsOptions)); app.listen(port, () => console.log(`Credit card app listening on port ${port}!`)); let stu = { "cardholdername": "Sara", "cardlimit": 23, "cardnumber": "123443211234" }; app.post('/creditcard', [ check('cardholdername').not().isEmpty().withMessage('Card Holder Name should not be Empty.') .isAlpha().withMessage('Card Holder Name should contain only Alphabets'), check('cardnumber').isLength({ min: 16, max: 19 }).withMessage('Card Number length must be between 16 and 19') .isNumeric().withMessage('Card Number must be Numeric'), check('cardlimit').isNumeric().withMessage('Card limit must be Numeric') ], (req, res) => { const errorFormatter = ({ location, msg, param, value, nestedErrors }) => { return { "status": 422, "msg": `${msg}` }; }; const errors = validationResult(req).formatWith(errorFormatter); if (!errors.isEmpty()) { return res.status(422).json({ msg: errors.array() }); } creditCardController.addDetails(req.body, (result) => { // console.log("status" + result.status); res.status(result.status); res.send(result); }); }); app.get('/creditcard', (req, res) => { creditCardController.creditCardDetails((result) => { res.send(result); }); });<file_sep>/README.md # Credit-Card-System A small full stack application for a credit card provider. It allows to add new credit card accounts and view them as a list. ReactJs and NodeJs([Node Installation](https://nodejs.org/en/download/)) ## Creditcard-server is the backend(NodeJs) In the project directory, you can run: ``` npm install ``` To run the server use ``` node server.js ``` from the directory. To run the test cases ``` npm test ``` Run the server api in Postman. using http://localhost:3000 url #### Two Rest Api POST : /creditcard It accept the credit card details and save in the file at the server. Payload: { "cardholdername": "Harsh", "cardlimit": 10000, "cardnumber": "5182913491948975" } GET : /creditcard It fetch the all credit card details to display it on the UI. <file_sep>/Controller/readfile.js var fs = require('fs'); var constants = require('../Constants/Constants'); function getAllDetails(callback) { console.log('Executed before Async file read'); if (fs.existsSync(constants.FILE_PATH)) { fs.readFile(constants.FILE_PATH, constants.ENCODING, function (error, data) { if (error) { callback({ status: false, msg: 'Unable to process the reuest at the moment. Please try again later.', data: error }); } callback({ status: 200, msg: 'Successfull', data: JSON.parse(data) }); }); console.log('Executed after file read'); } else { console.log('File not found'); } } exports.getAllDetails = getAllDetails;<file_sep>/Controller/writefile.js var fs = require('fs'); var constants = require('../Constants/Constants'); function writeDetails(data, callback) { console.log('Executed before sync file write'); var existingData; var inputData = { "cardholdername": data.cardholdername, "cardlimit": data.cardlimit, "cardnumber": data.cardnumber, "balance": 0 }; if (fs.existsSync(constants.FILE_PATH)) { fs.readFile(constants.FILE_PATH, function (err, readData) { if (err) { callback({ status: 500, msg: 'Unable to process the request at the moment. Please try again later.', data: err }); return; } console.log('File Read' + readData); existingData = JSON.parse(readData); existingData.push(inputData); data = JSON.stringify(existingData); writeFileWithData(data, function (d) { callback(d); }); }); } else { var jsonData = JSON.parse("[]"); jsonData.push(inputData); data = JSON.stringify(jsonData); writeFileWithData(data, function (d) { callback(d); }); } console.log('Executed after file write'); } function writeFileWithData(inputData, callback) { fs.writeFile(constants.FILE_PATH, inputData, constants.ENCODING, (error) => { if (error) { callback({ status: 500, msg: 'Unable to process the request at the moment. Please try again later.', data: error }); return; } callback({ status: 201, msg: 'Record created successfully.', data: JSON.parse(inputData) }); console.log('Data written to file'); }); } exports.writeDetails = writeDetails;
b6fb38eca5edde429fbe8f43ef3cece1be0651f1
[ "JavaScript", "Markdown" ]
6
JavaScript
harshyatishmishra/Credit-Card-System-Server
a03e8fde9bee36f471f2c43b0e890866451237c2
b81cff919b0353e6848390e010f22c6dba74928b
refs/heads/master
<repo_name>Cortex-MC/Makaprez<file_sep>/src/main/java/com/github/sanctum/makaprez/construct/Candidate.java package com.github.sanctum.makaprez.construct; import com.github.sanctum.makaprez.api.ElectionProperty; import java.io.Serializable; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; public class Candidate implements ElectionProperty<OfflinePlayer>, Serializable { private final UUID id; public Candidate(UUID ID) { this.id = ID; } @Override public OfflinePlayer getData() { return Bukkit.getOfflinePlayer(this.id); } @Override public Type getType() { return Type.BODY; } } <file_sep>/src/main/java/com/github/sanctum/makaprez/event/PollRenderDisplayEvent.java package com.github.sanctum.makaprez.event; import com.github.sanctum.makaprez.construct.Candidate; import java.util.HashSet; import java.util.Set; import org.bukkit.entity.Player; public class PollRenderDisplayEvent extends ElectionEvent { private final Set<Candidate> candidates; private final Player player; public PollRenderDisplayEvent(Set<Candidate> candidates, Player player) { super(); this.player = player; this.candidates = new HashSet<>(candidates); } public Player getRenderer() { return this.player; } public Set<Candidate> getCandidates() { return candidates; } } <file_sep>/src/main/java/com/github/sanctum/makaprez/event/PollRenderEvent.java package com.github.sanctum.makaprez.event; import com.github.sanctum.makaprez.construct.Candidate; public class PollRenderEvent extends ElectionEvent { private final Candidate candidate; private final int progress; private String format; public PollRenderEvent(Candidate candidate, int progress) { super(); this.candidate = candidate; this.progress = progress; } public int getProgress() { return progress; } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } public Candidate getCandidate() { return candidate; } } <file_sep>/src/main/java/com/github/sanctum/makaprez/api/ElectionProperty.java package com.github.sanctum.makaprez.api; public interface ElectionProperty<T> { T getData(); default Type getType() { return Type.UNKNOWN; } enum Type { VOTE, BODY, UNKNOWN; } }
9d970ab6a684bc45d0694b87c1874c4f9765565c
[ "Java" ]
4
Java
Cortex-MC/Makaprez
3967ef641ba317fb7c19bd29504cb3c6e76befb4
8eb953defb1b792f2e0375d157eabd4a3a340afd
refs/heads/master
<repo_name>zuramai/countdown.js<file_sep>/README.md # Countdown.js A simple countdown class ## How to use ```javascript let countDownMaghrib = new Countdown; countDownMaghrib.until(maghribTime); ``` Then you can get day, hours, minutes and seconds left ```javascript dayLeft = countDownMaghrib.getRemainingDay(); // 00 hourLeft = countDownMaghrib.getRemainingHours(); // 3 minuteLeft = countDownMaghrib.getRemainingMinutes(); // 25 secondLeft = countDownMaghrib.getRemainingSeconds(); // 01 ``` You can check the example provided <file_sep>/app.js let todayDate = new Date(); let today = todayDate.getFullYear() + "-" + (todayDate.getMonth()+1)+"-"+todayDate.getDate(); let now = todayDate.getTime(); let sholatSetelahIni = document.getElementById('sholat') // change time here let subuhTime = today+" 04:30:00" let zuhurTime = today+" 12:30:00" let asharTime = today+" 15:20:00" let maghribTime = today+" 18:05:00" let isyaTime = today+" 19:20:00" // CREATE COUTNDOWN OBJECT let countDownSubuh = new Countdown; countDownSubuh.until(subuhTime); let countDownZuhur = new Countdown; countDownZuhur.until(zuhurTime); let countDownAshar = new Countdown; countDownAshar.until(asharTime); let countDownMaghrib = new Countdown; countDownMaghrib.until(maghribTime); let countDownIsya = new Countdown; countDownIsya.until(isyaTime); setInterval(() => { let dayLeft, hourLeft, minuteLeft, secondLeft; if(now > new Date(subuhTime).getTime() && now < new Date(zuhurTime).getTime()) { sholat.innerHTML = "ZUHUR" dayLeft = countDownZuhur.getRemainingDay(); hourLeft = countDownZuhur.getRemainingHours(); minuteLeft = countDownZuhur.getRemainingMinutes(); secondLeft = countDownZuhur.getRemainingSeconds(); }else if(now >= new Date(zuhurTime).getTime() && now < new Date(asharTime).getTime()) { sholat.innerHTML = "ASHAR" dayLeft = countDownAshar.getRemainingDay(); hourLeft = countDownAshar.getRemainingHours(); minuteLeft = countDownAshar.getRemainingMinutes(); secondLeft = countDownAshar.getRemainingSeconds(); }else if(now >= new Date(asharTime).getTime() && now < new Date(maghribTime).getTime()) { sholat.innerHTML = "MAGHRIB" dayLeft = countDownMaghrib.getRemainingDay(); hourLeft = countDownMaghrib.getRemainingHours(); minuteLeft = countDownMaghrib.getRemainingMinutes(); secondLeft = countDownMaghrib.getRemainingSeconds(); }else if(now >= new Date(maghribTime).getTime() && now < new Date(isyaTime).getTime()) { sholat.innerHTML = "ISYA" dayLeft = countDownIsya.getRemainingDay(); hourLeft = countDownIsya.getRemainingHours(); minuteLeft = countDownIsya.getRemainingMinutes(); secondLeft = countDownIsya.getRemainingSeconds(); }else if(now > new Date(isyaTime).getTime()) { sholat.innerHTML = "SUBUH" dayLeft = countDownZuhur.getRemainingDay(); hourLeft = countDownZuhur.getRemainingHours(); minuteLeft = countDownZuhur.getRemainingMinutes(); secondLeft = countDownZuhur.getRemainingSeconds(); } let day = document.getElementById('day'); let hour = document.getElementById('hour'); let minute = document.getElementById('minute'); let second = document.getElementById('second'); day.innerHTML = dayLeft hour.innerHTML = hourLeft minute.innerHTML = minuteLeft second.innerHTML = secondLeft; todayDate = new Date(); today = todayDate.getFullYear() + "-" + (todayDate.getMonth() + 1) + "-" + todayDate.getDate(); now = todayDate.getTime(); }, 1000);<file_sep>/countdown.js class Countdown { constructor() { this.daysLeft = 0; this.hoursLeft = 0; this.minutesLeft = 0; this.secondsLeft = 0; } until(datetime) { setInterval(() => { let theDate = Date.parse(datetime); let now = new Date().getTime(); let distance = theDate - now; var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); this.daysLeft = days; this.hoursLeft = hours; this.minutesLeft = minutes; this.secondsLeft = seconds; }, 1000); } getRemainingDay() { return this.daysLeft; } getRemainingHours() { return this.hoursLeft; } getRemainingMinutes() { return this.minutesLeft; } getRemainingSeconds() { return this.secondsLeft; } }
f0b7de896a70990c95bd8a62aab6a89db7f430b6
[ "Markdown", "JavaScript" ]
3
Markdown
zuramai/countdown.js
8c94558a0acc7dd6a7acdfb98b6901b1b1693585
57aab820a2ca9bc802c9727efefbffef12b1045a
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using Test2.Models; namespace Test2.ViewModels { public class RandomMovieViewModel { public List<Movie> Movie { get; set; } public List<Customer> Customer { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace Test2.Models { public class Movie { [Required] public string Name { get; set; } public int id { get; set; } [Required] [Range (0,20)] public int? Copies { get; set; } public string Rating { get; set; } [Required] [Display (Name ="Release Date")] public DateTime? ReleaseDate { get; set; } public Genre Genre { get; set; } [Required] [Display(Name = "Genre")] public int GenreId { get; set; } } }<file_sep>using System.Data.Entity; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Test2.Models; using Test2.ViewModels; namespace Test2.Controllers { public class CustomersController : Controller { private ApplicationDbContext _context; public CustomersController() { _context = new Models.ApplicationDbContext(); } protected override void Dispose(bool disposing) { _context.Dispose(); } public ActionResult New() { var MembershipTypes = _context.MembershipTypes.ToList(); CustomerFormViewModel temp = new CustomerFormViewModel { customer = new Customer(), membershipTypes = MembershipTypes, Title = "New Customer" }; return View("CustomerForm", temp); } [HttpPost]//Makes it not accessible via url public ActionResult Save(Customer customer) { if (!ModelState.IsValid) { string title = "Edit Customer"; if(customer.id == 0) { title = "New Customer"; } var viewModel = new CustomerFormViewModel { customer = customer, membershipTypes = _context.MembershipTypes.ToList(), Title = title }; return View("CustomerForm", viewModel); } //If id = 0, then it's new if(customer.id == 0) { _context.Customers.Add(customer); } else { var customerInDb = _context.Customers.Single(c => c.id == customer.id); customerInDb.Name = customer.Name; customerInDb.Age = customer.Age; customerInDb.MembershipTypeId = customer.MembershipTypeId; customerInDb.IsSubscribedToNewsletter = customer.IsSubscribedToNewsletter; customerInDb.Address = customer.Address; customerInDb.Phone = customer.Phone; } _context.SaveChanges(); return RedirectToAction("Index", "Customers"); } // GET: Customers public ActionResult Index() { //Hardcoded Customers since I'm not using a database List<Customer> customers = _context.Customers.Include(c => c.MembershipType).ToList(); RandomMovieViewModel ran = new RandomMovieViewModel(); ran.Customer = customers; return View(ran); } public ActionResult Details(Customer temp) { return View(temp); } public ActionResult Edit(int id) { var Customer = _context.Customers.SingleOrDefault(c => c.id == id); if(Customer == null) { return HttpNotFound(); } var viewModel = new CustomerFormViewModel { customer = Customer, membershipTypes = _context.MembershipTypes.ToList(), Title = "Edit Customer" }; return View("CustomerForm", viewModel); } } }<file_sep>namespace Test2.Migrations { using System; using System.Data.Entity.Migrations; public partial class EditedMovieModel : DbMigration { public override void Up() { AlterColumn("dbo.Movies", "ReleaseDate", c => c.DateTime(nullable: false)); DropColumn("dbo.Movies", "DateAddedToDb"); } public override void Down() { AddColumn("dbo.Movies", "DateAddedToDb", c => c.String(nullable: false)); AlterColumn("dbo.Movies", "ReleaseDate", c => c.String(nullable: false)); } } }
d465d331a684d0fb705f76cd191e87da3309241e
[ "C#" ]
4
C#
Sadat21/VidlyWebsite
496a5218c47d6c4161914cf2a49078d40d2ad730
c1dc33068bb85aafb5d6d7b5612b6d998b6d40d8
refs/heads/master
<file_sep>from keras.models import Model, load_model from keras.layers import Dense, Input, LSTM from keras import optimizers import numpy as np import time, os, re import sys import csv import argparse global input_chars_list, target_chars_list global num_encoder_tokens, num_decoder_tokens, max_encoder_seq_length, max_decoder_seq_length global input_char_to_i_dict, target_char_to_i_dict, input_i_to_char_dict, target_i_to_char_dict global encoder_input_data, decoder_input_data, decoder_target_data global input_texts, target_texts def import_params(params_file = 'params/params.csv'): params_list = [] with open(params_file, 'r') as csv_file: reader = csv.DictReader(csv_file) for row in reader: params_list.append({}) current_params = params_list[-1] current_params["epochs"] = int(row["epochs"]) current_params["batch_size"] = int(row["batch_size"]) current_params["latent_dim"] = int(row["latent_dim"]) current_params["learning_rate"] = float(row["learning_rate"]) return params_list def build_data(data_file): global input_texts, target_texts input_texts = [] target_texts = [] with open(data_file, 'r') as file: for line in file.readlines(): try: in_chunk, out_chunk = line.split('\t') input_texts.append(in_chunk) target_texts.append(out_chunk) except Exception as e: print(e) return input_texts, target_texts def process_data(input_texts, target_texts): global input_chars_list, target_chars_list global num_encoder_tokens, num_decoder_tokens, max_encoder_seq_length, max_decoder_seq_length global input_char_to_i_dict, target_char_to_i_dict, input_i_to_char_dict, target_i_to_char_dict global encoder_input_data, decoder_input_data, decoder_target_data for seq in range(len(target_texts)): target_texts[seq] = "\t" + target_texts[seq] + "\n" input_chars_list = set() target_chars_list = set() for chunk in input_texts: for char in chunk: input_chars_list.add(char) for chunk in target_texts: for char in chunk: target_chars_list.add(char) print(target_chars_list) input_chars_list = sorted(list(input_chars_list)) target_chars_list = sorted(list(target_chars_list)) num_encoder_tokens = len(input_chars_list) num_decoder_tokens = len(target_chars_list) max_encoder_seq_length = max([len(chunk) for chunk in input_texts]) max_decoder_seq_length = max([len(chunk) for chunk in target_texts]) print(len(input_texts), max_encoder_seq_length, num_encoder_tokens) print(len(target_texts), max_decoder_seq_length, num_decoder_tokens) input_char_to_i_dict = dict([(char, i) for i, char in enumerate(input_chars_list)]) target_char_to_i_dict = dict([(char, i) for i, char in enumerate(target_chars_list)]) print(target_char_to_i_dict) input_i_to_char_dict = dict([(i, char) for i, char in enumerate(input_chars_list)]) target_i_to_char_dict = dict([(i, char) for i, char in enumerate(target_chars_list)]) encoder_input_data = np.zeros((len(input_texts), max_encoder_seq_length, num_encoder_tokens), dtype=np.dtype('float32')) decoder_input_data = np.zeros((len(input_texts), max_decoder_seq_length, num_decoder_tokens), dtype=np.dtype('float32')) decoder_target_data = np.zeros((len(input_texts), max_decoder_seq_length, num_decoder_tokens), dtype=np.dtype('float32')) for chunk_i, (input_chunk, target_chunk) in enumerate(zip(input_texts, target_texts)): for char_i, char in enumerate(input_chunk): encoder_input_data[chunk_i, char_i, input_char_to_i_dict[char]] = 1 for char_i, char in enumerate(target_chunk): decoder_input_data[chunk_i, char_i, target_char_to_i_dict[char]] = 1 if char_i > 0: decoder_target_data[chunk_i, char_i - 1, target_char_to_i_dict[char]] = 1 def rnn(params_dict, predict=False): BATCH_SIZE = params_dict['batch_size'] EPOCHS = params_dict['epochs'] LATENT_DIM = params_dict['latent_dim'] LEARNING_RATE = params_dict['learning_rate'] encoder_inputs = Input(shape=(None, num_encoder_tokens)) encoder_lstm = LSTM(LATENT_DIM, return_state=True) encoder_outputs, state_h, state_c = encoder_lstm(encoder_inputs) encoder_states = [state_h, state_c] decoder_inputs = Input(shape=(None, num_decoder_tokens)) decoder_lstm = LSTM(LATENT_DIM, return_sequences=True, return_state=True) decoder_outputs, _, _ = decoder_lstm(decoder_inputs, initial_state=encoder_states) decoder_dense = Dense(num_decoder_tokens, activation='softmax') decoder_outputs = decoder_dense(decoder_outputs) training_model = Model([encoder_inputs, decoder_inputs], decoder_outputs) #optimizer = optimizers.RMSprop() training_model.compile(optimizer='rmsprop', loss='categorical_crossentropy') try: training_model.fit([encoder_input_data, decoder_input_data], decoder_target_data, batch_size=BATCH_SIZE, epochs = EPOCHS, validation_split=0.2) except KeyboardInterrupt: pass #defining encoder/decoder models encoder_model = Model(encoder_inputs, encoder_states) decoder_state_input_h = Input(shape=(LATENT_DIM,)) decoder_state_input_c = Input(shape=(LATENT_DIM,)) decoder_state_inputs = [decoder_state_input_h, decoder_state_input_c] decoder_outputs, state_h, state_c = decoder_lstm(decoder_inputs, initial_state=decoder_state_inputs) decoder_states = [state_h, state_c] decoder_outputs = decoder_dense(decoder_outputs) decoder_model = Model([decoder_inputs] + decoder_state_inputs, [decoder_outputs] + decoder_states) return training_model, encoder_model, decoder_model, encoder_input_data def decode_sequence(input_seq, encoder_model, decoder_model): states_value = encoder_model.predict(input_seq) target_seq = np.zeros((1, 1, num_decoder_tokens)) target_seq[0, 0, target_char_to_i_dict['\t']] = 1. stop_condition = False decoded_sentence = '' while not stop_condition: output_tokens, h, c = decoder_model.predict( [target_seq] + states_value) sampled_token_index = np.argmax(output_tokens[0, -1, :]) sampled_char = target_i_to_char_dict[sampled_token_index] decoded_sentence += sampled_char if (sampled_char == '\n' or len(decoded_sentence) > max_decoder_seq_length): stop_condition = True target_seq = np.zeros((1, 1, num_decoder_tokens)) target_seq[0, 0, sampled_token_index] = 1. states_value = [h, c] return decoded_sentence """ def decode_sequence(input_seq,encoder_model, decoder_model): states_value = encoder_model.predict(input_seq) target_seq = np.zeros((1,1,num_decoder_tokens)) target_seq[0,0,target_char_to_i_dict['\t']] = 1 stop_condition = False output_string = '' while not stop_condition: output_tokens, state_h, state_c = decoder_model.predict([target_seq] + states_value) output_tokens_index = np.argmax(output_tokens[0,-1,:]) output_char = target_i_to_char_dict[output_tokens_index] #print(output_char) if output_char == '\n' or len(output_string) > max_decoder_seq_length: stop_condition = True output_string += output_char target_seq = np.zeros((1,1,num_decoder_tokens)) target_seq[0,0,output_tokens_index] = 1 state_values = [state_h, state_c] return output_string """ def decode(input_str): #char_dict = dict((char,i) for i, char in enumerate(set(input_str.lower()))) input_seq = np.zeros((1,max_encoder_seq_length , num_encoder_tokens), dtype='float32') for i, char in enumerate(input_str): input_seq[0, i, input_token_index[char]] = 1 return decode_sequence(input_seq) def sample_test(num_tests, encoder_model, decoder_model, save=None, save_dir=None): try: file = open(f'{save_dir}/log_training_samples', 'w') except Exception: pass for seq_index in range(num_tests): input_seq = encoder_input_data[seq_index: seq_index + 1] decoded_sentence = decode_sequence(input_seq, encoder_model, decoder_model) if save: file.write('-\n') file.write(f'Input sentence: {input_texts[seq_index]}\n') file.write(f'Decoded sentence: {decoded_sentence}\n') else: print('-') print('Input sentence:', input_texts[seq_index]) print('Decoded sentence:', decoded_sentence) def launch_cli(encoder_model, decoder_model): while(True): user_input = input("Justin: ").lower() user_input_vector = np.zeros((1, max_encoder_seq_length, num_encoder_tokens), dtype='float32') for i, char in enumerate(user_input): user_input_vector[0,i,input_char_to_i_dict[char]] = 1 print("Roy: " + decode_sequence(user_input_vector, encoder_model, decoder_model)) def main(): parser = argparse.ArgumentParser() parser.add_argument('--train', nargs=3, help="[data_file] [params_file] [save_dir]: (1) path to file containing training data, path to file contain with two tab-separated columns, the first being input and second being output, (2) path to params CSV (3) Directory to save models") parser.add_argument('--predict', nargs=1, help="saved weights files dir") args = parser.parse_args() if args.train: params_list = import_params(args.train[1]) input_texts, target_texts = build_data(args.train[0]) process_data(input_texts, target_texts) for run in range(len(params_list)): training_model, encoder_model, decoder_model, encoder_input_data = rnn(params_list[run], True) save_dir = args.train[2] i = sorted([int(f.name) for f in os.scandir(save_dir) if f.is_dir()]) print(i) if i: i = str(int(i[-1]) + 1) else: i = '0' os.makedirs(f'{save_dir}/{i}') training_model.save(f'{save_dir}/{i}/training.h5') encoder_model.save(f'{save_dir}/{i}/encoder.h5') decoder_model.save(f'{save_dir}/{i}/decoder.h5') with open(f'{save_dir}/{i}/data_pointer', 'w') as data_file: data_file.write(args.train[0]) with open(f'{save_dir}/log.csv', 'a') as csv_file: params_dict = params_list[run] writer = csv.writer(csv_file, delimiter=',') writer.writerow([i, args.train[0], params_dict['epochs'], params_dict['batch_size'], params_dict['latent_dim'], params_dict['learning_rate']]) sample_test(10, encoder_model, decoder_model) sample_test(200, encoder_model, decoder_model, save=True, save_dir=f'{save_dir}/{i}') print(f'Saving to directory {save_dir}/{i}') elif args.predict: file_dir = args.predict[0] training_model = load_model(file_dir + '/training.h5') encoder_model = load_model(file_dir + '/encoder.h5') decoder_model = load_model(file_dir + '/decoder.h5') data_file = open(file_dir + '/data_pointer').readline() input_texts, target_texts = build_data(data_file) process_data(input_texts, target_texts) sample_test(20, encoder_model, decoder_model) launch_cli(encoder_model, decoder_model) else: print("Too few arguments") return 0 if __name__ == '__main__': main() <file_sep>from keras.models import Model, load_model from keras.layers import Dense, LSTM, Input import numpy as np import sys import time <file_sep>import os import pickle import sys import numpy as np np.random.seed(6788) import tensorflow as tf tf.set_random_seed(6788) from keras.layers import Input, Embedding, LSTM, TimeDistributed, Dense, SimpleRNN, Activation, dot, concatenate, Bidirectional from keras.models import Model, load_model from keras.callbacks import ModelCheckpoint # Defining constants here encoding_vector_size = 128 # Placeholder for max lengths of input and output which are user configruable constants max_input_length = None max_output_length = None char_start_encoding = 1 char_padding_encoding = 0 def build_sequence_encode_decode_dicts(input_data): encoding_dict = {} decoding_dict = {} for line in input_data: for char in line: if char not in encoding_dict: # Using 2 + because our sequence start encoding is 1 and padding encoding is 0 encoding_dict[char] = 2 + len(encoding_dict) decoding_dict[2 + len(decoding_dict)] = char return encoding_dict, decoding_dict, len(encoding_dict) + 2 def encode_sequences(encoding_dict, sequences, encoding_vector_size): encoded_data = np.zeros(shape=(len(sequences), encoding_vector_size)) for i in range(len(sequences)): for j in range(min(len(sequences[i]), encoding_vector_size)): encoded_data[i][j] = encoding_dict[sequences[i][j]] return encoded_data def decode_sequence(decoding_dict, sequence): text = '' for i in sequence: if i == 0: break text += decoding_dict[i] return text def generate(text, input_encoding_dict, model, max_input_length, max_output_length, beam_size, max_beams, min_cut_off_len, cut_off_ratio): min_cut_off_len = max(min_cut_off_len, cut_off_ratio*len(text)) min_cut_off_len = min(min_cut_off_len, max_output_length) encoder_input = encode_sequences(input_encoding_dict, [text], max_input_length) completed_beams = [] running_beams = [ [np.zeros(shape=(len(encoder_input), max_output_length)), [1]] ] running_beams[0][0][:,0] = char_start_encoding while len(running_beams) != 0: running_beams = sorted(running_beams, key=lambda tup:np.prod(tup[1]), reverse=True) running_beams = running_beams[:max_beams] temp_running_beams = [] for running_beam, probs in running_beams: if len(probs) >= min_cut_off_len: completed_beams.append([running_beam[:,1:], probs]) else: prediction = model.predict([encoder_input, running_beam])[0] sorted_args = prediction.argsort() sorted_probs = np.sort(prediction) for i in range(1, beam_size+1): temp_running_beam = np.copy(running_beam) i = -1 * i ith_arg = sorted_args[:, i][len(probs)] ith_prob = sorted_probs[:, i][len(probs)] temp_running_beam[:, len(probs)] = ith_arg temp_running_beams.append([temp_running_beam, probs + [ith_prob]]) running_beams = [b for b in temp_running_beams] return completed_beams def infer(text, model, params, beam_size=3, max_beams=3, min_cut_off_len=15, cut_off_ratio=1.5): input_encoding_dict = params['input_encoding'] output_decoding_dict = params['output_decoding'] max_input_length = params['max_input_length'] max_output_length = params['max_output_length'] decoder_outputs = generate(text, input_encoding_dict, model, max_input_length, max_output_length, beam_size, max_beams, min_cut_off_len, cut_off_ratio) outputs = [] for decoder_output, probs in decoder_outputs: outputs.append({'sequence': decode_sequence(output_decoding_dict, decoder_output[0]), 'prob': np.prod(probs)}) return outputs def build_params(input_data = [], output_data = [], params_path = 'test_params', max_lenghts = (50,50)): if os.path.exists(params_path): print('Loading the params file') params = pickle.load(open(params_path, 'rb')) return params print('Creating params file') input_encoding, input_decoding, input_dict_size = build_sequence_encode_decode_dicts(input_data) output_encoding, output_decoding, output_dict_size = build_sequence_encode_decode_dicts(output_data) params = {} params['input_encoding'] = input_encoding params['input_decoding'] = input_decoding params['input_dict_size'] = input_dict_size params['output_encoding'] = output_encoding params['output_decoding'] = output_decoding params['output_dict_size'] = output_dict_size params['max_input_length'] = max_lenghts[0] params['max_output_length'] = max_lenghts[1] pickle.dump(params, open(params_path, 'wb')) return params def convert_training_data(input_data, output_data, params): input_encoding = params['input_encoding'] input_decoding = params['input_decoding'] input_dict_size = params['input_dict_size'] output_encoding = params['output_encoding'] output_decoding = params['output_decoding'] output_dict_size = params['output_dict_size'] max_input_length = params['max_input_length'] max_output_length = params['max_output_length'] encoded_training_input = encode_sequences(input_encoding, input_data, max_input_length) encoded_training_output = encode_sequences(output_encoding, output_data, max_output_length) training_encoder_input = encoded_training_input training_decoder_input = np.zeros_like(encoded_training_output) training_decoder_input[:, 1:] = encoded_training_output[:,:-1] training_decoder_input[:, 0] = char_start_encoding training_decoder_output = np.eye(output_dict_size)[encoded_training_output.astype('int')] x=[training_encoder_input, training_decoder_input] y=[training_decoder_output] return x, y def build_model(params_path = 'test/params'): params = build_params(params_path = params_path) input_encoding = params['input_encoding'] input_decoding = params['input_decoding'] input_dict_size = params['input_dict_size'] output_encoding = params['output_encoding'] output_decoding = params['output_decoding'] output_dict_size = params['output_dict_size'] max_input_length = params['max_input_length'] max_output_length = params['max_output_length'] print('Input encoding', input_encoding) print('Input decoding', input_decoding) print('Output encoding', output_encoding) print('Output decoding', output_decoding) encoder_input = Input(shape=(max_input_length,)) decoder_input = Input(shape=(max_output_length,)) encoder = Embedding(input_dict_size, 128, input_length=max_input_length, mask_zero=True)(encoder_input) encoder = Bidirectional(LSTM(128, return_sequences=True, unroll=True), merge_mode='concat')(encoder) encoder_last = encoder[:,-1,:] decoder = Embedding(output_dict_size, 256, input_length=max_output_length, mask_zero=True)(decoder_input) decoder = LSTM(256, return_sequences=True, unroll=True)(decoder, initial_state=[encoder_last, encoder_last]) attention = dot([decoder, encoder], axes=[2, 2]) attention = Activation('softmax', name='attention')(attention) context = dot([attention, encoder], axes=[2,1]) decoder_combined_context = concatenate([context, decoder]) output = TimeDistributed(Dense(128, activation="tanh"))(decoder_combined_context) output = TimeDistributed(Dense(output_dict_size, activation="softmax"))(output) model = Model(inputs=[encoder_input, decoder_input], outputs=[output]) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) model.summary() return model, params def load_data(file_path): #grab data input_texts = [] target_texts = [] with open(file_path, 'r') as file: for line in file.readlines(): try: in_chunk, out_chunk = line.split('\t') except Exception as e: print(e) input_texts.append(in_chunk) target_texts.append(out_chunk) return input_texts, target_texts if __name__ == '__main__': if len(sys.argv) == 2: DATA_FILE = sys.argv[1] elif len(sys.argv) == 1: DATA_FILE = '../data2.txt' else: sys.argv[10000] #shortcut way to raise an exception lol input_data, output_data = load_data() #input_data = ['123', '213', '312', '321', '132', '231'] #output_data = ['123', '123', '123', '123', '123', '123'] build_params(input_data = input_data, output_data = output_data, params_path = 'test/params', max_lenghts=(50, 50)) model, params = build_model(params_path='test/params') input_data, output_data = convert_training_data(input_data, output_data, params) checkpoint = ModelCheckpoint('test/checkpoint', monitor='val_acc', verbose=1, save_best_only=True, mode='max') callbacks_list = [checkpoint] model.fit(input_data, output_data, validation_data=(input_data, output_data), batch_size=2, epochs=20, callbacks=callbacks_list) <file_sep>from bs4 import BeautifulSoup from keras.models import Model, load_model from keras.layers import Dense, Input, LSTM from keras import optimizers import numpy as np import time, os, re import sys MAX_SEQ_LEN = 10000000 html_file_path = './roy_messages_2017-2018.html' target_file = 'data3.txt' #make this a lot prettier if len(sys.argv) == 4: html_file_path = sys.argv[1] MAX_SEQ_LEN = int(sys.argv[3]) target_file = sys.argv[2] elif len(sys.argv) == 3: html_file_path = sys.argv[1] target_file = sys.argv[2] elif len(sys.argv) == 2: html_file_path = sys.argv[1] elif len(sys.argv) == 1: pass else: sys.argv[10000] #shortcut way to raise an exception lol justin_color = '#0084ff' roy_color = '#f1f0f0' roy_soup = BeautifulSoup(open(html_file_path),'html.parser') all_dialogue_list = roy_soup.find_all('div', style=re.compile("border-radius: 13px")) roy_chunks = [] justin_chunks = [] def only_ascii(string): return re.sub(r'[^\x00-\x7f]',r'', string) def shorten(string, seq_len, end=True): if len(string) > seq_len: if end: return string[len(string)-seq_len:] else: return string[:seq_len] return string for i in range(len(all_dialogue_list) - 1): curr_line = all_dialogue_list[i] next_line = all_dialogue_list[i+1] is_justin_curr = re.search(justin_color, curr_line['style']) is_roy_next = re.search(roy_color, next_line['style']) if is_justin_curr and is_roy_next: justin_chunks.append(shorten(curr_line.text, MAX_SEQ_LEN, True).lower().replace('\n','')) roy_chunks.append(shorten(next_line.text, MAX_SEQ_LEN, False).lower().replace('\n','')) #justin_chunks = justin_chunks[:-1] #this is because Justin has 1 more message than Roy with open(target_file, 'w') as file: for i in range(len(roy_chunks)): file.write(justin_chunks[i] + '\t' + roy_chunks[i] + '\n') <file_sep>from txt2txt import build_model, infer model, params = build_model('test/params') model.load_weights('test/checkpoint') while(True): user_in = input("Justin: ") print(infer(user_in.lower(), model, params)) <file_sep># messenger_bot Creating a chatbot that can emulate the speech of people on messenger <file_sep>import sys import numpy as np from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout from keras.layers import LSTM from keras.callbacks import ModelCheckpoint from keras.utils import np_utils DATA_FILE = './data2.txt' #grab data input_texts = [] target_texts = [] with open(DATA_FILE, 'r') as file: for line in file.readlines(): in_chunk, out_chunk = line.split('\t') input_texts.append(in_chunk.replace("\n", "")) target_texts.append(out_chunk.replace("\n", "")) input_chars_list = set() target_chars_list = set() for chunk in input_texts: for char in chunk: input_chars_list.add(char) for chunk in target_texts: for char in chunk: target_chars_list.add(char) print(target_chars_list) input_chars_list = sorted(list(input_chars_list)) target_chars_list = sorted(list(target_chars_list)) num_encoder_tokens = len(input_chars_list) num_decoder_tokens = len(target_chars_list) max_encoder_seq_length = max([len(chunk) for chunk in input_texts]) max_decoder_seq_length = max([len(chunk) for chunk in target_texts]) print(len(input_texts), max_encoder_seq_length, num_encoder_tokens) print(len(target_texts), max_decoder_seq_length, num_decoder_tokens) input_char_to_i_dict = dict([(char, i) for i, char in enumerate(input_chars_list)]) target_char_to_i_dict = dict([(char, i) for i, char in enumerate(target_chars_list)]) print(target_char_to_i_dict) input_i_to_char_dict = dict([(i, char) for i, char in enumerate(input_chars_list)]) target_i_to_char_dict = dict([(i, char) for i, char in enumerate(target_chars_list)]) encoder_input_data = np.zeros((len(input_texts), max_encoder_seq_length, num_encoder_tokens), dtype=np.dtype('?')) decoder_input_data = np.zeros((len(input_texts), num_decoder_tokens), dtype=np.dtype('?')) decoder_target_data = np.zeros((len(input_texts), max_decoder_seq_length, num_decoder_tokens), dtype=np.dtype('?')) for chunk_i, (input_chunk, target_chunk) in enumerate(zip(input_texts, target_texts)): for char_i, char in enumerate(input_chunk): encoder_input_data[chunk_i, char_i, input_char_to_i_dict[char]] = 1 try: target_char = target_chunk[0] except: target_char = " " decoder_input_data[chunk_i, target_char_to_i_dict[target_char]] = 1 """ # create mapping of unique chars to integers, and a reverse mapping chars = sorted(list(set(raw_text))) char_to_int = dict((c, i) for i, c in enumerate(chars)) int_to_char = dict((i, c) for i, c in enumerate(chars)) # summarize the loaded data n_chars = len(raw_text) n_vocab = len(chars) print "Total Characters: ", n_chars print "Total Vocab: ", n_vocab # prepare the dataset of input to output pairs encoded as integers seq_length = 100 dataX = [] dataY = [] for i in range(0, n_chars - seq_length, 1): seq_in = raw_text[i:i + seq_length] seq_out = raw_text[i + seq_length] dataX.append([char_to_int[char] for char in seq_in]) dataY.append(char_to_int[seq_out]) n_patterns = len(dataX) print "Total Patterns: ", n_patterns # reshape X to be [samples, time steps, features] X = numpy.reshape(dataX, (n_patterns, seq_length, 1)) # normalize X = X / float(n_vocab) # one hot encode the output variable y = np_utils.to_categorical(dataY) # define the LSTM model """ X = encoder_input_data y = decoder_input_data model = Sequential() model.add(LSTM(256, input_shape=(X.shape[1], X.shape[2]), return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM(256)) model.add(Dropout(0.2)) model.add(Dense(y.shape[1], activation='softmax')) # load the network weights model.compile(loss='categorical_crossentropy', optimizer='adam') # define the checkpoint filepath="weights-improvement-{epoch:02d}-{loss:.4f}-bigger.hdf5" checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=True, mode='min') callbacks_list = [checkpoint] # fit the model try: model.fit(X, y, epochs=500, batch_size=64, callbacks=callbacks_list) except KeyboardInterrupt: pass def into_vector(input_str): user_input_vector = np.zeros((1, max_encoder_seq_length, num_encoder_tokens)) for i, char in enumerate(input_str): user_input_vector[0, i, input_char_to_i_dict[char]] = 1 return user_input_vector def decode_sequence(input_seq, length=50): current_seq = input_seq current_output = "" for i in range(length): user_input_vector = np.zeros((1, max_encoder_seq_length, num_encoder_tokens)) for i, char in enumerate(current_seq): user_input_vector[0, i, input_char_to_i_dict[char]] = 1 #input_vector = into_vector(current_seq) #print(input_vector.shape) pred_softmax = model.predict(user_input_vector, verbose=False, steps=1) pred_char = target_i_to_char_dict[np.argmax(pred_softmax)] current_output += pred_char #print(current_output) current_seq = current_seq[1:] + pred_char return current_output while(True): user_input = input("Justin: ") print("Roy: " + decode_sequence(user_input)) """ # pick a random seed start = numpy.random.randint(0, len(dataX)-1) pattern = dataX[start] print "Seed:" print "\"", ''.join([int_to_char[value] for value in pattern]), "\"" # generate characters for i in range(1000): x = numpy.reshape(pattern, (1, len(pattern), 1)) x = x / float(n_vocab) prediction = model.predict(x, verbose=0) index = numpy.argmax(prediction) result = int_to_char[index] seq_in = [int_to_char[value] for value in pattern] sys.stdout.write(result) pattern.append(index) pattern = pattern[1:len(pattern)] print "\nDone." """
9b5b53617ead082da83270b303168f997a55e6f0
[ "Markdown", "Python" ]
7
Python
Justinyu1618/messenger_bot
28c5accdbf2028fe288d101b6c713f6bcb3b4b7a
2ff0647fdd19566ae8ebbe41542077bc48a1a6cf
refs/heads/master
<repo_name>SpencerAung/request-header-ms<file_sep>/README.md # Request Header Parser Microservice The API will return IP address, languge and operating system of the client browser. <file_sep>/server/routes/v1/whoamiRoutes.js const express = require('express'); var router = express.Router(); router.get('/', (req, res) => { var languages = req.headers['accept-language']; var language = languages.split(',')[0]; var userAgent = req.headers['user-agent']; var software = userAgent.substring(userAgent.indexOf('(') + 1, userAgent.indexOf(')')); var ipaddress = req.headers['x-forwarded-for'] || req.connection.remoteAddress; res.send({ip: ipaddress, language, software }); }); module.exports = router; <file_sep>/server/server.js require('./config/config'); const express = require('express'); const bodyParser = require('body-parser'); const path = require('path'); const compression = require('compression'); const consolidate = require('consolidate'); const assert = require('assert'); const _ = require('lodash'); const cookieParser = require('cookie-parser') var whoamiRoutesV1 = require('./routes/v1/whoamiRoutes'); const publicPath = path.join(__dirname + './../public'); const port = process.env.PORT; var app = express(); var server = app.listen(port, () => { console.log(`Server running on port ${port}`); }); app.use(compression()); app.use(express.static(publicPath)); app.engine('html', consolidate.ejs); app.set('view engine', 'html'); app.set('views', __dirname + "/views"); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false})); app.use(cookieParser()); app.get('/', (req, res) => { res.send('Hello World'); }); app.use('/v1/whoami', whoamiRoutesV1); app.use((req,res) => { res.status(404).send("Page Not Found."); }); module.exports = { app };
46a51bd87e41c32481ec85183e4d02a40b290c6c
[ "Markdown", "JavaScript" ]
3
Markdown
SpencerAung/request-header-ms
2f69e06090ee91826aedeefa0d63401b2fbe78cf
7883420422a8b407e937030688ca905ebbb0716b
refs/heads/master
<file_sep># Kartago Tours Zrt - INFX2 dokumentáció ![Infx2](./images/INFX2Structure.png) ## Dokumentáció tartalma Az oldal írásos dokumentációban összesíti a Kartago Tours Zrt P2P online foglalási rendszerét. Az egyes részekhez példakódot is közzé teszünk. A példák nem komplett megoldások, és csak egy lehetséges implementálása a feladatnak. ## INFX2 felépítése A rendszer offline letölthető adatokból és online API-n keresztül meghívott parancsokból áll össze. > Némi átfedés is van, mert egyes adatok offline letöltés mellett API híváson keresztül is elérhetőek. > Erre azért van szükség, mertt az offline adatok ütemezett időnként frissülnek, de az API-n keresztül a valós pillanatnyi állapotot kapjuk. ### Hozzáférés <a name="access"></a> A Kartago Tours INFX szerveréhez a hozzáférést regisztrálni kell, nincs publikus elérés. Bármely szerződött partnerünk kérhet hozzáférést, ehhez el kell küldenie azt a fix IPv4 címet, ahonnan a szolgáltatást igénybe kívánják venni. Tesztelés, fejlesztés nem feltétlen a production szerver IP címről történik, ezért van lehetőség több IP cím megadására is, de meg kell jelölni, melyik címet milyen céllal regisztráltak. > **Újdonság!** Amennyiben az IP címhez tartozik DNS név, akkor IP cím helyett azzal is lehet regisztrálni. ### Offline letöltendő adatok Az adatok nagy része offline elérhető. Ezek egy része XML formátumú, egy másik része TXT formátumú adatok, valamint a kínálathoz tartozó képek. #### XML formátumban letölthető adatok - [Szálloda adatok](HotelsInfo.md) - frissítés alkalmanként, ha változtatás történt - [Alapárak](BasePrices.md) - minden éjjel egy alaklommal, kiegészítő frissítése (külön fileban) 2 óránként, csak ha volt változás, csak a változott tételeket tartalmazza - [Felárak](AdditionalPrices.md) - frissítése minden éjjel egy alaklommal > **Javaslat!** A legjobb implementáció esetén az árak letöltése nem szükséges, mivel az alapárakat az INFX2.TXT file tartalmazza, a többi árat meg online le lehet kérni. #### TXT formátumban letölthető adatok - [INFX2](INFX2.md) - minden éjjel egy alaklommal, kiegészítő frissítése (külön fileban) 2 óránként, csak ha volt változás, csak a változott tételeket tartalmazza #### [Képek](Pictures.md) - Minden kép egy sorszámmal van azonosítva, ez a kép neve. A szállodainfóban hivatkozás erre a névre történik. > Közel 2600 szálloda 40.000 fotója van a rendszerben. Ez nagy mennyiség, ezért ezek frissítésére (szálloda infó + képek) konkrét megoldásunk van a leírásban. Érdemes ezt vagy ehhez hasonlót implementálni, mivel a sávszélesség korlátos. ### API hívások Egy [RuleBox](RuleBox.md) rendszer működik az API hívások mögött. Ennek segítségével, nem csak információt lehet lekérni, hanem komplett árkalkulációt lehet végezni, amelyek segítségével árajánlat készíthető vagy a foglalás is elvégezhető. ## Demó progam Példakódok jelenleg [PHP](phpDemo.md) nyelven áll rendelkezésre. [Használati esettanulmány](UseCase.md) pedig segít az INFX rendszer működését megérteni, így az integrációt elősegíteni. Kérem, amennyiben igény van **JavaScript** ill. **C#** kódra, jelezzék felénk. Amennyiben elegendő kérés érkezik, ezeken a nyelveken is biztosítjuk a példakódokat. Készítő: <NAME> <file_sep>[Kezdőoldal](README.md) ## Képek A képek egyedi sorszámmal vannak ellátva. Minden képnek a teljes rendszerben egydi számozása van és ez a szám egyben a kép neve is '.jpg' kiterjesztéssel. A [szálloda adatok](HotelsInfo.md) ezekre a sorszámokra hivatkoznak. ### Elérhető http://swiss.kartagotours.hu:88/hotel_xml/xml-nf/imgs/ ### Letöltési utasítás Közel 50.000 kép van a rendszerben, ezért fontos, hogy csak azokat a képeket töltsük le, amit még nem töltöttünk le korábban. Erre a legmegfelelőbb módszer, hogy első ízben letöltjük az elérhető tartalmat (ha lehet éjjeli időpontban), és a letöltés időpontját eltároljuk. Időközönként csak egy frissítő letöltést indítunk, ahol csak az utolsó letöltés dátumánál újabb fileokat töltjük le. Ugyan ezt az eljárást alkalmazzuk a [szálloda adatok](HotelsInfo.md) letöltésénél is.<file_sep>/* Létrehozott utolsó foglalás törlése */ <?php /* Foglalás elkészítése Itt most a params.php file tartalmazza, melyik ajánlatot akarjuk foglalni */ require_once('../params.php'); include '../api_infx2/infxservice.php'; global $tesztAjanlat, $tesztAjanlatSzobaTipus, $tesztAjanlatGiata; $xml2 = simplexml_load_file("./Responses/PriceAvailabilityCheckMakeBookingResponse.xml"); // ha foglalható, ezt az ajánlatot lehet megjeleníteni if (trim($xml2->Control->ResponseStatus) == "success") { // ha sikeres a foglalás if (trim($xml2->Booking->bnr_result) == "success") { // foglalási szám $bnr = $xml2->Booking->bnr; // Ez csak teszt, töröljük is le a foglalást!! $file = './Responses/BookingRemoveResponse.xml'; file_put_contents($file, BookingRemoveRequest($bnr)); } } ?><file_sep>[Kezdőoldal](README.md) ## RuleBox ### Bevezető A Kartago Tours a SWISS foglalási rendszeréhez nyújt egy alapvető webes szolgáltatási interfészt. Lehetőség van az ajánlatok árának és elérhetőségének ellenőrzésére, valamint opció befoglalására. További eljárásokkal lehetőség van az utasok adatainak átadására és így a foglalás véglegesítésére is. Egyes eljárásokkal pedig a foglalások állapotát, részleteinek megismerését lehet lekérdezni. Jelenleg meglévő foglalás módosítása vagy törlése nem lehetséges. Ilyen esetben fel kell venni a kapcsolatot a Kartago Tourssal és munkatársaink elvégzik a módosításokat a háttérrendszerünkkel. ### Webszervíz #### A webszolgáltatás elérése > Kérjük olvassa el a bevezető [Hozzáférés](README.md) szakaszát! A webszolgáltatás az alábbi címen érhető el [http://swiss.kartagotours.hu:88/ws2.asmx/WS1RQ](http://swiss.kartagotours.hu:88/ws2.asmx/WS1RQ) A biztosított webszolgáltatáshoz letölthető a SOAP (1.1 és 1.2) [WSDL](http://swiss.kartagotours.hu:88/ws2.asmx/?WSDL) file! Szintén megtekinthető az eljárások hívásához a szintaktika SOAP (1.1 és 1.2) GET és POST hívásokra. [link]() #### Azonosítás <a name="authentication"></a> Azok a funkciók, amelyek konkrét foglalással kapcsolatosak bekérnek felhasználó specifikus adatokat. Nyilván ez ahhoz kell, hogy a foglalásaink a saját azonosítónk alatt legyen elérhető és a [Swiss online](https://swiss.kartagotours.hu) rendszerben is láthassuk. A [swiss online](https://swiss.kartagotours.hu) programba belépve a felhasználó adatai menüpontnál az alábbihoz hasonló képet kapunk. Itt találhatóak a hitelesítő adatok, amelyeket egyes kéréseknél át kell adni. ![image](images/SwissInfo.png) Erről a SWISS_ID és a SWISS_RBPwd azonosítók kellenek. (Az azonosítás nem felhasználó, hanem, partner specifikus!) #### Fejlesztői környezet Csak egyetlen **éles** környezet van, nincs külön tesztelésre kialakított adatbázis. A tesztet az éles környezeten végezzük, ezért valódi foglalás esetén kérjük tartson szoros kapcsolatot a referatúra osztályunkkal, hogy visszavonhassuk a foglalását. Soha ne foglaljon egy hónapon belül induló járatra teszt célból, amennyire lehetséges, minél távolabbi időpontokon teszteljen. Teszteket hétköznap, munkaidőben végezzenek, hogy a próba foglalásoakt visszavonhassuk. > Célszerű az adatok megadásánál olyan neveket használni ami egyértelműen teszt célt szolgálnak, ezzel is segítve a munkánkat. : Pl. <NAME>, Nagyváros, Nemlétező utca 1 > A teszt foglalásokról mielőbb küldjenek emailt a foglalási szám feltüntetésével, hogy töröljük. Az email annak a desztinációnak az email címére küldjék, amelyiknek foglaltak. TODO kinek kell küldeni? uticél felelős? call center? online? ### Funkciók #### SeasonListRequest Szezonok listája XML kérdés ```XML <SeasonListRequest></SeasonListRequest> ``` XML válasz ```XML <?xml version="1.0" encoding="utf-8"?> <SeasonListResponse> <seasons> <season> <SID>1</SID> <dsc>HUNKAS17 </dsc> <isActive>N</isActive> </season> <season> <SID>2</SID> <dsc>HUNKAW17 </dsc> <isActive>N</isActive> </season> ``` Mező | Érték leírása ---- | ---- SID | Szezon azonosítója dsc | Szezon kódja isActive | Y/N Aktív vagy nem Lásd: [Demó adat](../src/php/Test/Responses/SeasonListResponse.xml) #### BoardsRequest Ellátás típusok lekérése XML kérdés ```XML <BoardsRequest></BoardsRequest> ``` XML válasz ```XML <BoardsResponse> <boards> <board> <season>HUNKAW18</season> <code>AI</code> <giata_code>A</giata_code> <descr>all inclusive</descr> <descr_global>all inclusive</descr_global> </board> <board> <season>HUNKAW18</season> <code>SOAI</code> <giata_code>A1</giata_code> <descr>soft all inclusive</descr> <descr_global>soft all inclusive</descr_global> </board> . . ``` Mező | Érték leírása ---- | ---- season | Szezon kódja code | Ellátás kódja giata_code | Rövid kód descr | Leírás desc_global | Ellátás típus leírás Lásd: [Demó adat](../src/php/Test/Responses/BoardsResponse.xml) #### RoomTypesRequest Szobatípusok lekérése XML kérdés ```XML <RoomTypesRequest></RoomTypesRequest> ``` XML válasz ```XML <RoomTypesResponse> <rooms> <room> <Season>HUNKAW18</Season> <room_swiss_id>1+0</room_swiss_id> <room_giata_id>E1</room_giata_id> <room_configuration>;A;C;</room_configuration> <room_descr_1pax>1 ágyas szoba</room_descr_1pax> <room_descr_2pax /> <room_descr_3pax /> <room_descr_4pax /> <room_descr_5pax /> <room_descr_6pax /> <room_descr_7pax /> <room_descr_8pax /> <room_descr_9pax /> <room_descr_10pax /> </room> . . ``` Mező | Érték leírása ---- | ---- season | Szezon kódja room_swiss_id | szoba swiss azonosító room_giata_id | Rövid kód room_configuration | Szoba konfigurációi, A – felnőtt, C - gyermek room_descr_#pax | Szoba leírás létszámtól függően Lásd: [Demó adat](../src/php/Test/Responses/RoomTypesResponse.xml) #### AirportsRequest Repterek lekérése XML kérdés ```XML <AirportsRequest></AirportsRequest> ``` XML válasz ```XML <AirportsResponse> <airports> <airport> <season>HUNKAS19 </season> <a_type>-</a_type> <a_id>A14</a_id> <a_descr>no transport</a_descr> </airport> <airport> <season>HUNKAS19 </season> <a_type>-</a_type> <a_id>AYT</a_id> <a_descr>Antalya</a_descr> </airport> . . ``` Mező | Érték leírása ---- | ---- season | Szezon kódja a_type | + = Otthoni, - = Külföldi a_id | Reptér kódja a_descr | Leírás Lásd: [Demó adat](../src/php/Test/Responses/AirportsResponse.xml) #### OtherPricesRequest Felárak listája XML kérdés ```XML <OtherPriceTypesRequest></OtherPriceTypesRequest> ``` XML válasz ```XML <OtherPriceTypesResponse> <price_types> <price_type> <season>HUNKAS19</season> <price_abb>OSRB_PMI</price_abb> <price_descr>Reptéri illeték - PMI</price_descr> <price_descr_long>Reptéri illeték - PMI</price_descr_long> <category>02 illetékek</category> <sub_type>kötelezo felár</sub_type> <AgeF>0</AgeF> <AgeT>99</AgeT> <PaxF>1</PaxF> <PaxT>99</PaxT> <type1>1</type1> <type2>N</type2> </price_type> . . ``` Mező | Érték leírása ---- | ---- season | Szezon kódja price_abb | Ár típus kódja price_descr | Ár leírása price_descr_long | Ár hosszú leírása category | Kategória sub_type | altípus AgeF | Ettől az életkortól alkalmazható AgeT | Eddig az életkorig alkalmazható PaxF | Személyek száma minimum PaxT | Személyek száma maximum type1 | 1 = személyenként alkalmazandó, S = szerződésenként alkalmazandó type2 | R = kérésre, N = kötelező Lásd: [Demó adat](../src/php/Test/Responses/OtherPricesResponse.xml) #### AccomodationPriceTypesRequest Szálláshelyek ár típusai XML kérdés ```XML <AccomodationPriceTypesRequest></AccomodationPriceTypesRequest> ``` XML válasz ```XML <AccomodationPriceTypesResponse> <price_types> <price_type> <season>HUNKAW18</season> <price_abb>SUP PLA1CHD-1</price_abb> <price_descr>Platinum suite 1. gyermek felár xx éves korig</price_descr> </price_type> <price_type> <season>HUNKAW18</season> <price_abb>SUP PLA2CHD-1</price_abb> <price_descr>Platinum suite 2. gyermek felár xx éves korig</price_descr> </price_type> . . ``` Mező | Érték leírása ---- | ---- season | Szezon kódja price_abb | Ár kódja price_descr | Leírás Lásd: [Demó adat](../src/php/Test/Responses/AccomodationPrceResponse.xml) #### ExtrasRequest Csomaghoz tartozó egyéb opciós felárak XML kérdés ```XML <ExtrasRequest><PackageID>60193</PackageID></ExtrasRequest> ``` Bementi paraméterek: Mező | Érték leírása ---- | ---- PackageID | Csomag azonosító XML válasz ```XML <ExtrasResponse> <term_info> <h_info> </h_info> </term_info> <extras> <extra> <category>05 Vizum</category> <sub_type>online*vizum</sub_type> <type>viza Egyiptom</type> <descr>Vízumdíj - Egyiptom</descr> <price>9000.0000</price> <AgeF>0</AgeF> <AgeT>99</AgeT> <PaxF>1</PaxF> <PaxT>99</PaxT> <type1>1</type1> <type2>N</type2> </extra> <extra> <category>04 Biztositás</category> <sub_type>online*bbp</sub_type> <type>z.poj.online.gold.8</type> <descr>Utazási Biztosítás - Air Gold 940 Ft/fo/nap</descr> <price>7520.0000</price> <AgeF>0</AgeF> <AgeT>99</AgeT> <PaxF>1</PaxF> <PaxT>99</PaxT> <type1>1</type1> <type2>N</type2> </extra> . . . ``` Mező | Érték leírása ---- | ---- h_info | Extra információ a szállásról és időpontról category | Kategória sub_type | Al típus type | Típus price | Ár AgeF | Ettől az életkortól alkalmazható AgeT | Eddig az életkorig alkalmazható PaxF | Személyek száma minimum PaxT | Személyek száma maximum type1 | 1 = személyenként alkalmazandó, S = szerződésenként alkalmazandó type2 | R = kérésre, N = kötelező Lásd: [Demó adat](../src/php/Test/Responses/ExtrasResponse.xml) #### PriceAvailabilityCheckRequest A Csomag azonosító, szállás típus, ellátás és utas adatok alapján árkalkuláció készítése XML kérdés ```XML <PriceAvailabilityCheckRequest> <MakeBooking/> <PartnerID></PartnerID> <UserID></UserID> <RBPwd></RBPwd> <Rcpt></Rcpt> <Package> <PackageID>2418765</PackageID> <BoardType>A</BoardType> <RoomType>2+2_CH</RoomType> </Package> <PaxDetails> <PaxDescription> <DateOfBirth>19990219</DateOfBirth> </PaxDescription> <PaxDescription> <DateOfBirth>19990219</DateOfBirth> </PaxDescription> <PaxDescription> <DateOfBirth>19990219</DateOfBirth> </PaxDescription> </PaxDetails> </PriceAvailabilityCheckRequest> ``` Bemenő paraméterek Mező | Érték leírása ---- | ---- PackageID | Csomag azonosító BoardType | Ellátás típusa RoomType | Szoba típusa DateOfBirth | Születési dátum MakeBooking* | Annak jelölése, hogy foglalás is történik, nem csak információ kérés PartnerID* | SWISS partner azonosító UserID* | SWISS felhasználó azonosító RBPwd* | SWISS felhasználó jelszó Rcpt* | email cím UserName* | Név \* Csak akkor kell, ha foglalás is történik XML válasz ```XML <PriceAvailabilityCheckResponse> <Control> <ResponseStatus>success </ResponseStatus> <ResponseMessage> </ResponseMessage> <ReqID>96797998-620F-4BC8-BADF-06D2D705C979</ReqID> </Control> <Package> <ReqDetails> <PackageID>2418765</PackageID> <RoomType>2+2_CH </RoomType> <BoardType>A </BoardType> <hotel_a1>AYTSEL </hotel_a1> <season_id>5</season_id> <season_dsc>HUNKAS19 </season_dsc> <hotel_type>L</hotel_type> <Paxs> <Pax> <pax_id>1</pax_id> <pax_bd>19.02.1999</pax_bd> </Pax> <Pax> <pax_id>2</pax_id> <pax_bd>19.02.1999</pax_bd> </Pax> <Pax> <pax_id>3</pax_id> <pax_bd>19.02.1999</pax_bd> </Pax> </Paxs> </ReqDetails> <PriceDetails> <PackagePrice>1658800.0000</PackagePrice> <PriceInfos> <PriceInfo> <pax_id>1</pax_id> <quantity>1</quantity> <item>DBL</item> <item_d>.2 ágyas szoba felnott ár/ fo</item_d> <price>676900.0000</price> <price_type>C</price_type> <price_type_d /> <rb_d>N</rb_d> <rb_id>0</rb_id> </PriceInfo> <PriceInfo> <pax_id>1</pax_id> <quantity>1</quantity> <item>SLV*EB3*DBL</item> <item_d>FM márc.20-ig-2 ágyas szoba felnott ár/ fo</item_d> <price>-109800.0000</price> <price_type>C</price_type> <price_type_d /> <rb_d>N</rb_d> <rb_id>0</rb_id> </PriceInfo> <PriceInfo> <pax_id>1</pax_id> <quantity>1</quantity> <item>OSRB_AYT</item> <item_d>Reptéri illeték AYT</item_d> <price>34900.0000</price> <price_type>C</price_type> <price_type_d /> <rb_d>N</rb_d> <rb_id>0</rb_id> </PriceInfo> <PriceInfo> <pax_id>2</pax_id> <quantity>1</quantity> <item>DBL</item> <item_d>.2 ágyas szoba felnott ár/ fo</item_d> <price>676900.0000</price> <price_type>C</price_type> <price_type_d /> <rb_d>N</rb_d> <rb_id>0</rb_id> </PriceInfo> <PriceInfo> <pax_id>2</pax_id> <quantity>1</quantity> <item>SLV*EB3*DBL</item> <item_d>FM márc.20-ig-2 ágyas szoba felnott ár/ fo</item_d> <price>-109800.0000</price> <price_type>C</price_type> <price_type_d /> <rb_d>N</rb_d> <rb_id>0</rb_id> </PriceInfo> <PriceInfo> <pax_id>2</pax_id> <quantity>1</quantity> <item>OSRB_AYT</item> <item_d>Reptéri illeték AYT</item_d> <price>34900.0000</price> <price_type>C</price_type> <price_type_d /> <rb_d>N</rb_d> <rb_id>0</rb_id> </PriceInfo> <PriceInfo> <pax_id>3</pax_id> <quantity>1</quantity> <item>1EXBED</item> <item_d>1. felnott pótágyon ár/ fo</item_d> <price>499900.0000</price> <price_type>C</price_type> <price_type_d /> <rb_d>N</rb_d> <rb_id>0</rb_id> </PriceInfo> <PriceInfo> <pax_id>3</pax_id> <quantity>1</quantity> <item>SLV*EB3*1EXBED</item> <item_d>FM márc.20-ig-1. felnott pótágyon ár/ fo</item_d> <price>-80000.0000</price> <price_type>C</price_type> <price_type_d /> <rb_d>N</rb_d> <rb_id>0</rb_id> </PriceInfo> <PriceInfo> <pax_id>3</pax_id> <quantity>1</quantity> <item>OSRB_AYT</item> <item_d>Reptéri illeték AYT</item_d> <price>34900.0000</price> <price_type>C</price_type> <price_type_d /> <rb_d>N</rb_d> <rb_id>0</rb_id> </PriceInfo> </PriceInfos> </PriceDetails> </Package> <Booking> <bnr /> <bnr_result /> <bnr_exp /> </Booking> </PriceAvailabilityCheckResponse> ``` Mező | Érték leírása ---- | ---- ResponseStatus | A kalkuláció eredménye (sikeres vagy sikertelen) ResponseMessage | Hiba leírása ReqID | Kalkuláció egyedi azonosítója PackagePrice | Csomag ára PriceInfos | Számítás részletei hotel_a1 | Szállás kódja season_id | Szezon azonosító season_dsc | Szezon kódja hotel_type | Szállás típusa L = túra, A = Autó pax_id | Utas sorszám quantity | Mennyiség Item | Ár típusa bnr* | Opció foglalási szám (a foglalást ezzel lehet kezdeményezni) bnr_result | Sikeres opciós foglalás, vagy a hiba leírása bnr_exp* | Opciós foglalás lejárata > A <Paxs> tartalmazza az utasok adatait ami a számításhoz szükséges, és a pax_id az azonosító. \* Csak abban az esetben ha foglalni is szeretnénk Lásd: [Demó adat](../src/php/Test/Responses/PriceAvailabilityCheckResponse.xml) #### BookingInfoRequest A foglalásról adja vissza az alap információkat XML kérdés ```XML <BookingInfoRequvest> <bnr></bnr> <PartnerID></PartenrID> <RBPwd></RBPwd> </BookingInfoRequvest> ``` Bemenő paraméterek Mező | Érték leírása ---- | ---- BNR | Foglalási szám PartnerID | SWISS partner azonostó RBPwd | SWISS jelszó XML válasz ```XML <BookingInfoResponse> <Result> <bnr>385004915</bnr> <bnr_expiration>2019-03-11T20:00:00</bnr_expiration> <bnr_status>R</bnr_status> <bnr_rlock>0</bnr_rlock> <package_id>2431452</package_id> <bnr_room>2+1_SV </bnr_room> <bnr_seats>3</bnr_seats> </Result> </BookingInfoResponse> ``` Mező | Érték leírása ---- | ---- BNR | Foglalási szám Bnr_expiration | Foglalás lejárati dátuma (Csak akkor, ha a bnr_status=R) Req_xml | Utazási szerződés (jelenleg kikapcsolt funkció) Bnr_status | O = Szerződés (visszaigazolt foglalás); R = Opciós foglalás; X= törölt foglalás Package_id | Csomag azonostó (Term ID) Bnr_room | Szoba típus Bnr_seat | Személyek száma (utaztatáshoz) Lásd: [Demó adat](../src/php/Test/Responses/BookingInfoResponse.xml) #### AvailabilityCheckRequest Ezzel a függvénnyel ellenőrizhetjük le, hogy egy adott csomag foglalható-e. XML kérdés ```XML <AvailabilityCheckRequest> <PackageID>2418765</PackageID> <RoomType>2+2_CH</RoomType> <PaxCount>3</PaxCount> <RoomCount>1</RoomCount> </AvailabilityCheckRequest> ``` Bemenő paraméterek Mező | Érték leírása ---- | ---- PackageID | Csomag azonosító RoomType | Szobatípus PaxCount | Utasok száma RoomCount | Szobák száma. Max 3. Ha nem adjuk meg, akkor a rendszer 1-nek veszi. XML válasz ```XML <AvailabilityCheckResponse> <Control> <ResponseStatus>success </ResponseStatus> <ResponseMessage /> <ReqID>9F455C9D-17B0-4BEA-9BD7-814B06A4ED3E</ReqID> </Control> <Availibility> <Book>N</Book> <LastCap>N</LastCap> </Availibility> </AvailabilityCheckResponse> ``` Mező | Érték leírása ---- | ---- ResponseStatus | A kalkuláció eredménye. (Siker vagy Hiba) ResponseMessage | Hiba esetén a hiba leírása. ReqID | A kalkuláció egyedi azonosítója Book | Y/N/R Foglalható / Nem foglalható / Lekérésre LastCap | Y/N Utolsó szoba (igen / nem) Lásd: [Demó adat](../src/php/Test/Responses/AvailabilityCheckResponse.xml) #### GetAddPriceRulesRequest Egy listát kapunk a kötelező felárakról egy adott Szezon, adott szálloda, adott szobatípusának adott ár típusához. XML kérdés ```XML <GetAddPriceRulesRequest></GetAddPriceRulesRequest> ``` XML válasz ```XML <GetAddPriceRulesResponse> <rules> <rule> <season_dsc>HUNKAW18</season_dsc> <hotel_code>LPABPH</hotel_code> <price_type>1EXBED</price_type> <room_type>2+1</room_type> <board>AI</board> <add_price_types> <add_price_type>SUP AI</add_price_type> </add_price_types> </rule> . . ``` Mező | Érték leírása ---- | ---- season_dsc | Szezon kódja hotel_code | Hotel kódja price_typ | Ár típus kódja room_type | Szobatípus kódja board | Ellátás. (* esetén minden, egyébként az étkezés rövid kódja pl: FP, AI) add_price_types | Kötelező ár típusok Lásd: [Demó adat](../src/php/Test/Responses/GetAddPriceRulesResponse.xml) #### PaymentsByXMLDataInfoRequest Egy adott foglalás esetére visszaadja, hogy legkésőbb mikor mennyit kell minimálisan fizetni. XML kérdés ```XML <PaymentsByXMLDataInfoRequest> <bnr></bnr> <xmls3> <contractdata> <calculation> <ReqID></ReqID> </calculation> </contractdata> </xmls3> </PaymentsByXMLDataInfoRequest> ``` Mező | Érték leírása ---- | ---- bnr | Foglalási szám ReqID | ReqID XML válasz ```XML <PaymentsByXMLDataInfoResponse> <Payments> <PaymentDate>10.03.2019</PaymentDate> <PaymentAmount>548999</PaymentAmount> </Payments> </PaymentsByXMLDataInfoResponse> ``` Mező | Érték leírása ---- | ---- PaymentDate | Fizetési határidő PaymentAmount | Fizetendő összeg Lásd: [Demó adat](../src/php/Test/Responses/PaymentByXMLDataInfoResponse.xml) #### BookingDataRequest Az utazási szerződés adatait lehet beküldeni. (Utasok és szerződő adatai) XML kérdés ```XML <BookingDataRequest> <bnr></bnr> <xmls3> <contractdata> <bnr></bnr> <partner_addr_id></partner_addr_id> <partner_addr_type></partner_addr_type> <address_customer> <pax_id></pax_id> <fname></fname> <sname></sname> <title /> <street></street> <city></city> <post_code></post_code> <country></country> <phone></phone> <email></email> </address_customer> <paxs> . <pax> <pax_id></pax_id> <fname></fname> <sname></sname> <title /> <idcrm /> <sex></sex> <bd></bd> <passport /> <nationality></nationality> </pax> . </paxs> <calculation> <ReqID></ReqID> </calculation> </contractdata> </xmls3> </BookingDataRequest> ``` Mező | Érték leírása ---- | ---- bnr | Foglalási szám pax_id | A szerződő utas sorszáma. Értéke 1 legyen! fname | Keresztnév sname | Vezetéknév title | Megszólítás street | cím city | Város post_code | Irányítószám country | Ország phone | Teefonszám email | Email cím pax_id | utas sorszáma. (Az első utas legyen a szerződő) sex | Férfi vagy Nő bd | Születési dátum passport | Útlevélszám nationality | Nemzetiség XML válasz ```XML <BookingDataResponse> <Result> <bnr>385004940</bnr> <bnr_expiration>2019-03-13T15:00:00</bnr_expiration> <bnr_status>R</bnr_status> <bnr_rlock>0</bnr_rlock> <package_id>2431452</package_id> <bnr_room>2+1_PRE </bnr_room> <bnr_seats>3</bnr_seats> </Result> </BookingDataResponse> ``` Mező | Érték leírása ---- | ---- BNR | Foglalási szám Bnr_expiration | Foglalás lejárati dátuma (Csak akkor, ha a bnr_status=R) Req_xml | Utazási szerződés (jelenleg kikapcsolt funkció) Bnr_status | O = Szerződés (visszaigazolt foglalás); R = Opciós foglalás; X= törölt foglalás Package_id | Csomag azonostó (Term ID) Bnr_room | Szoba típus Bnr_seat | Személyek száma (utaztatáshoz) Lásd: [Demó adat](../src/php/Test/Responses/BookingDataResponse.xml) #### BookingInfoRequest1 Részletes információ a foglalásról XML kérdés ```XML <BookingInfoRequvest1> <BNR></BNR> <PartnerID></PartenrID> <RBPwd></RBPwd> </BookingInfoRequvest1> ``` Bemenő paraméterek Mező | Érték leírása ---- | ---- BNR | Foglalási szám PartnerID | SWISS partner azonostó RBPwd | SWISS jelszó XML válasz Lásd: [Demó adat](../src/php/Test/Responses/BookingInfoResponse1.xml) #### BookingRemoveRequest Opciós foglalást tudunk törölni Ha a foglalás már nem opciós, akkor a törlés nem lehetséges, akkor a szokaás módon fel kell venni a kapcsolatot a kollégákkal. XML kérdés ```XML <BookingRemoveRequest> <bnr></bnr> <PartnerID></PartenrID> <RBPwd></RBPwd> </BookingRemoveRequest> ``` XML válasz ```XML <BookingRemoveResponse> <Result> <bnr>385004915</bnr> <bnr_expiration>2019-03-09T20:29:47.620</bnr_expiration> <bnr_status>R</bnr_status> <bnr_rlock>0</bnr_rlock> <package_id>2431452</package_id> <bnr_room>2+1_SV </bnr_room> <bnr_seats>3</bnr_seats> </Result> </BookingRemoveResponse> ``` Mező | Érték leírása -----|----- bnr | Foglalási szám bnr_expiration | Lejárati dátum bnr_status | O = Szerződés (visszaigazolt foglalás); R = Opciós foglalás; X= törölt foglalás bnr_rlock | TODO package_id | Csomag azonosító bnr_room | Szoba típús bnr_seats | Létszám Lásd: [Demó adat](../src/php/Test/Responses/BookingRemoveResponse.xml) <file_sep># Kartago.XML ## Fő struktúra ```XML <kartago_xml> <seasons> <season> </season> </seasons> <boards> <board> </board> </boards> <rooms> <room> </room> </rooms> <airports> <airport> </airport> </airports> <other_price_types> <price_type> </price_type> </other_price_types> <accomodatinon_price_types> <price_type> </price_type> </accomodatinon_price_types> <hotels> <offer> </offer> </hotels> </kartago_xml> ``` ## season Szezonok felsorolása, csak azokat érdemes átvenni, amelyik aktív. > Szinte az összes további elem hivatkozik egy szezonra, mert szezononként eltérhetnek a paraméterek. Szóval ugyan az a kód többször is szerepelhet eltérő szezon hivatkozással. ```XML <season> <SID>1</SID> <dsc>HUNKAS17 </dsc> <isActive>Y</isActive> </season> ``` Mező | Leírás ---- | ---- SID | Szezon azonosítója dsc | Szezon kódja isActive | Y/N Aktív vagy nem ## boards Létező ellátások. ```XML <board> <season>HUNKAS17</season> <code>AI</code> <giata_code>A</giata_code> <descr>all inclusive</descr> <descr_global>all inclusive</descr_global> </board> ``` Mező | Leírás ---- | ---- season | Szezon kódja code | Ellátás kódja giata_code | Rövid kód descr | Leírás desc_global | Ellátás típus leírás ## rooms Szobatípusok és azok paraméterei. A létszámtól függően van magyar elnevezés is megadva. ```XML <room> <Season>HUNKAS17</Season> <room_swiss_id>1+0</room_swiss_id> <room_giata_id>E1</room_giata_id> <room_configuration>;A;C;</room_configuration> <room_descr_1pax>1 ágyas szoba</room_descr_1pax> <room_descr_2pax /> <room_descr_3pax /> <room_descr_4pax /> <room_descr_5pax /> <room_descr_6pax /> <room_descr_7pax /> <room_descr_8pax /> <room_descr_9pax /> <room_descr_10pax /> </room> ``` Mező | Leírás ---- | ---- season | Szezon kódja room_swiss_id | szoba swiss azonosító room_giata_id | Rövid kód room_configuration | Szoba konfigurációi, A – felnőtt, C - gyermek room_descr_#pax | Szoba leírás létszámtól függően ## airports Repülőterek kódja és megnevezése ```XML <airport> <season>HUNKAS17 </season> <a_type>-</a_type> <a_id>MIR</a_id> <a_descr>Monastir</a_descr> </airport> ``` Mező | Leírás ---- | ---- season | Szezon kódja a_type | + = Otthoni, - = Külföldi a_id | Reptér kódja a_descr | Leírás ## other_price_types Egyéb költségek ártípusai. ```XML <price_type> <season>HUNKAS17</season> <price_abb>AIR_BLND_RT</price_abb> <price_descr>látássérült utas</price_descr> <price_descr_long>látássérült utas</price_descr_long> <category>06 Repülő extra</category> <sub_type>online*repülő</sub_type> <AgeF>0</AgeF> <AgeT>99</AgeT> <PaxF>1</PaxF> <PaxT>99</PaxT> <type1>1</type1> <type2>N</type2> </price_type> ``` Mező | Leírás ---- | ---- season | Szezon kódja price_abb | Ár típus kódja price_descr | Ár leírása price_descr_long | Ár hosszú leírása category | Kategória sub_type | altípus AgeF | Ettől az életkortól alkalmazható AgeT | Eddig az életkorig alkalmazható PaxF | Személyek száma minimum PaxT | Személyek száma maximum type1 | 1 = személyenként alkalmazandó, S = szerződésenként alkalmazandó type2 | R = kötelező felár, N = választható felár ## accomodatinon_price_types ALap ártípusok ```XML <price_type> <season>HUNKAS17</season> <price_abb>DBL</price_abb> <price_descr>.2 ágyas szoba felnőtt ár/ fo</price_descr> </price_type> ``` Mező | Leírás ---- | ---- season | Szezon kódja price_abb | Ár kódja price_descr | Leírás ## hotels Hotelek leírása ```XML <offer> <code> A07AGB</code> <name> AGATHAWIRT - BAD GOISERN</name> <dest_code> VDA</dest_code> <dest_name></dest_name> <dest_region></dest_region> <dest_subregion></dest_subregion> <dest_airport></dest_airport> <category> 3</category> <offertype> C</offertype> <exclusivity></exclusivity> <url></url> <texts> <perex><![CDATA[ A Landhotel Agathawirt Salzkammergut régió szívében található. A közlekedési szempontból jó fekvésű ház Agatha-ban épült, Bad Goisern egy külvárosi részén. A központ vásárlási lehetőségekkel kb. 3 km távolságra található. A hotel ideális kiindulási pont túrákhoz és kisebb sétákhoz.]]></perex> <distances><![CDATA[ távolság a központtól: 3 km<br>távolság a vásárlási lehetőségektől: 3 km]]></distances> <roomfacil><![CDATA[ rádió, telefon, műholdas TV<br>minibár ,Wi-Fi illetékmentesen<br>saját fürdőszoba (kád vagy zuhanyfülke, hajszárító, WC)]]></roomfacil> <hotelfacil><![CDATA[ recepció, bár, étterem<br>kávézó, gyerek játszószoba<br>parkolási lehetőség, Wi-Fi illetékmentesen<br>wellness - medence, szauna, fitnesz]]></hotelfacil> <beachdescr><![CDATA[]]></beachdescr> <entericnl><![CDATA[ szauna, gőzfürdő]]></entericnl> <enterchrg><![CDATA[ masszázs, szolárium]]></enterchrg> <boardincl><![CDATA[ büféjellegű reggeli<br><br>Kartago Tours hazai besorolás: 3*]]></boardincl> <boardchrg><![CDATA[]]></boardchrg> <youtubelnk></youtubelnk> <pictograms></pictograms> <icons></icons> <gps></gps> </texts> <images> <image image_id="26550" /> <image image_id="26555" /> <image image_id="26554" /> <image image_id="26553" /> <image image_id="26552" /> <image image_id="26551" /> </images> <seasons /> </offer> ``` Mező | Leírás ---- | ---- code | Kartago csoport hotel kód name | hotel megnevezése dest_code | Kartago csoport desztináció kódja dest_name | Desztináció neve dest_region | Desztináció régiója dest_subregion | Desztináció alrégiója dest_airport | Desztináció szálloda kódja category | Szállás kategória besorolása offertype | Foglalás típusa (pl síelés, tengerparti üdülés, stb..) exclusivity | Csak Kartago kínálat perex | Szállás információ, bevezető szöveg. distances | Szállás elhelyezkedése roomfacil | Vendégszobák leírása hotelfacil | Szállodai szolgáltatások beachdescr | Strand és a környék leírása entericnl | Ingyenes sportolási lehetőségek enterchrg | Sportolási lehetőségek illetékért boardincl | Ellátás, amit az ár tartalmaz boardchrg | Ellátások, amiket illetékért lehet igénybe venni youtubelnk | YouTube videó link pictograms | Szolgáltatás kínálat piktogramok (bináris kódolással) icons | Ikonok gps | GPS koordináta image | image_id="egyedi azonosító" coding="image/jpeg base64" --- <offertype> Foglalás típusa. Két betű jelöli. Fő és al típus. Fő típusok: Kód|Megnevezés --|-- P | Üdülés Z | kirándulás L | síút Altípus, ami a pontos típust jelöli Kód|Megnevezés --|-- PP | Tengerparti üdülés PX | Egzotikus üdülés PJ | Tóparti üdülés PH | Hegyvidéki üdülés PL | SPA / Wellness PB | Buszos üdülés ZO | Városnézés ZS | Szafari túra ZK | kombinációs út ZE | Városnézés / európai hétvége LL | Síelés --- <picotgrams></pictograms> 0 = nincs, 1 = van Piktogramok - Légkondicionáló a szobában - Wi-Fi - internet - Parkolás - Kerekesszékkel is járható - wellness / Spa - Gyereksarok - Úszás - tobogán / aquapark - Búvár - golf - tenisz - Vizi sportok - Tornaterem, fitnesz - röplabda - kerékpár - Mango club - Új - Tengerpari szállás - Csak felnőtteknek - Magyar nyelvű idegenvezető - Háziállat bevihető - Exim tipp - Exim minőség Megjegyzés: Ha a fejlécben másként nincs jelölve, akkor a kódolás „windows-1252” ### Seasons A hotel alatt vannak az adott hotelbe az ajánlatok szezononként. ```XML <seasons> <season SID="1" dsc="HUNKAS17"> <rules> <rule> </rules> <terms> <term id="49583" ….> <infx2s> <INFX2 …. /> </infx2s> <extras> <Extra …. /> </extras> <prices> <price> … </price> </prices> </term> </terms> </season> </seasons> ``` ### Rule ```XML <rule> <season_dsc>HUNKAS17</season_dsc> <hotel_code>FNCJAR</hotel_code> <price_type>1EXBED</price_type> <room_type>ST2+1</room_type> <board>*</board> <add_price_types> <add_price_type>SUP STU</add_price_type> </add_price_types> </rule> ``` Szabályokat határoz meg az ár képzéshez. A példa az adott szezon adott hoteljének 1EXBED ár típusa esetén ST2+1 típusú szobában az összes ellátás típusnál lehet alkalmazni a SUP STU típusú árat. ### Term Egy adott ajánlatot azonosít a kódjával. ```XML <term id="49583" DepartureDate="01.10.2017" ArrivalDate="08.10.2017" DepartureFromAirport="BUD" DepartureToAirport="FNC" ArrivalFromAirport="FNC" ArrivalToAirport="BUD" DepartureStartTime="0000" DepartureStopTime="0000" ArrivalStartTime="0000" ArrivalStopTime="0000"> ``` Mező | Leírás ---- | ---- id | Kartago csoport ajánlat azonosító DepartureDate | Odaút dátuma ArrivalDate | Visszaérkezés dátuma DepartureFromAirport | Odaút indulás reptér DepartureToAirport | Odaút cél reptér ArrivalFromAirport | Visszaút induló reptér ArrivalToAirport | Visszaút cél reptér DepartureStartTime | Odaút indulás időpont (ha 0000 érték, akkor még nincs meg a pontos idő) DepartureStopTime | Odaút érkezés időpontja ArrivalStartTime | Visszaút indulás időpontja ArrivalStopTime | Visszaút érkezés időpontja ### Extra Az extra sorok a felárakat tartalmazzák. ```XML <Extra i="49583" h="FNCJAR" t="OSRB_FNC" p="59900.0000" t1="1" t2="R" /> ``` Mező | Leírás ---- | ---- i | Csomag ID (TERM ID) t | Ár típus kódja h | Szállás kódja p | Ár t1 | 1 = minden főre alkalmazni kell; S = szerződésenként egyszer t2 | R = kérésre; N = nem kérésre ### Price A kiválasztott ajánlathoz tartozó árak. Azt hogy melyik árat kell alkalmazni az a kiválasztott szoba típustól, ellátás típustól, életkortól, stb függ. Ez a rész elavult, ne használjuk. Helyette a Kartago3.XML adatait használjuk. ```XML <price> <season_dsc>HUNKAS17</season_dsc> <package_id>49583</package_id> <h>FNCJAR</h> <price_type>DBL</price_type> <price_c>183900.00</price_c> <max_age>99</max_age> <price_c_vf>01.01.2000</price_c_vf> <price_c_vt>31.12.2099</price_c_vt> <price_lm>EMPTY</price_lm> <price_lm_vf>EMPTY</price_lm_vf> <price_lm_vt>EMPTY</price_lm_vt> <price_lm_d>EMPTY</price_lm_d> </price> ``` Mező | Leírás ---- | ---- season_dsc | Szezon kódja pakage_id | Csomag ID (TERM ID) price_type | Ár típus price_c | Katalógus ár max_age | Ekkora életkorig alkalmazható price_c_vf | Katalógus ár ettől az időponttól alkalmazható price_c_vt | Katalógus ár eddig az időpontig alkalmazható price_lm | Lastminute ár price_lm_vf | Lastminute ár ettől az időponttól alkalmazható price_lm_vt | Lastminute ár eddig az időpontig alkalmazható price_lm_d | Lastminute ár típusa ### INFX2 Az infx2 sorok kifejezetten a weboldalon történő megjelenítést szolgálja. Az adott időpontra az adott szobatípusra és ellátás típusra megadja a felnőtt alapárat. > --Fontos!-- Amennyiben reptéri illeték külön szerepel az árlistában, akkor az nincs ebben az árban. Ha nincs feltüntetve repülős utaknál a reptéri illeték, akkor az bele van kalkulálva az árakba! ```XML <INFX2 Person_Min="2" Person_Max="3" Adult_Min="1" Adult_Max="3" Child_Age_From_1="0" Child_Age_To_1="12" RoomSwissId="ST2+1_SV" BoardGiataCode="H" Price="0239040.00HUF" KatalogPrice="0265600.00HUF" /> ``` Mező | Leírás ---- | ---- Person_Min | A kiválasztott szobatípus miatt a minimum létszám Person_Max | A kiválasztott szobatípus miatt a maximum létszám Adult_Min | A kiválasztott szobatípus miatt a minimum felnőtt létszám Adult_Max | A kiválasztott szobatípus miatt a maximum felnőtt létszám Child_Age_From_1 | Első gyermek min életkor Child_Age_To_1 | Első gyermek max életkor RoomSwissId | Szoba azonosítója BoardGiataCode | Ellátás azonosítója Price | Ez az aktuálisan érvényes ár KatalogPrice | Az eredeti katalógus ár A példa egy két fő ággyal és egy pótággyal rendelkező, tengerre néző szoba esetén megadja az egy főre eső pillanatnyi árat és a katalógus árat. Megtudhatjuk továbbá, hogy ez abban az esetben érvényes, ha minimum 2 max 3 fő foglalja a szobát és minimum egy felnőttnek kell lennie. <file_sep># INFX2 dokumentáció és példa megvalósítás [Dokumentáció weboldala](https://kartago-tours-zrt.github.io/INFX2) ![Infx2](./docs/images/INFX2Structure.png) <file_sep># Bevezető Már évek óta elérhető a Kartago Tours partnerei számára egy letölthető XML file, ami tartalmazza az összes ajánlatunkat egyben. A file praktikus, hiszen tömörítve egy ftp oldalról gyorsan és könnyen letölthető, és az XML adatstruktúra miatt, egyszerűen betölthető a partnereink rendszerébe. A Kartago Tours az EXIM és a DER csoport részeként folyamatosan fejleszti foglalási rendszerét, weboldalát. Ennek főbb okai a kor követelményeinek teljesítése, valamint a több országot lefedő egységes rendszer kiépítése. Ezen folyamatok miatt a Kartago Tours XML adatstruktúrája megváltozik. Ez a dokumentum az egyben letölthető XML file struktúrájának a leírása. # Letöltés Az adatokat ftp szerverről lehet letölteni tömörített (zip) formátumban. ftp szerver: ftp://ftp2.kartagotours.hu/INFX2<br> felhasználónév: „KartagoPartners”<br> jelszó: „XMLDownload99”<br> - Kartago.zip tartalmazza a katalógus adatokat - KartagoPrices.zip a kalkulációs adatbázist tartalmazza - /Kepek mappában a fotók találhatóak. A fotókat nem kell állandóan letölteni, dátum alapján lehet szűrni, és csak az újdonságokat letölteni. Ez mindenképpen javasolt, mert nagy mennyiségű fotóról van szó. [Kartago.xml](Kartago.md) felépítése [Kartago3.xml](Kartago3.md) kalkulációs adatbázis felépítése # Hogyan használjuk Az adatokat áttöltve a Kartago.xml tartalmazza az összes elérhető szálloda információt. A Kartago3.xml adathalmazt információi alapján (ha bekértük hány felnőtt és hány gyermek utazik), le lehet szűrni az 'offer' Variation mezőjére. Felnőtteket A, gyermekeket C jelöli. Ilyenkor a keresés ne legyen kis/nagybetű érzékeny. Pl. Két felnőtt két gyerek aacc. > mindíg a felnőttek teljes létszáma 'a' betűvel majd a gyermekek száma 'c' betűvel reprezentálva. A DepartureDate és ArrivalDate mezőkkel dátum intervallumokra és napok számára is lehet szűrni. (Ellátásra és szoba típusra is szűrhetünk előre) A Kartago.xml alapján a szálloda kódokat desztinációkba is lehet sorolni, így lehet szűrni adott országra, régióra, szállodára is. A megmaradt halmaz az ajánlat az utasoknak. Gyermekek életkorát pontosan bekérve lehet pontos árat is kalkulálni. A kalkuláció nem tartlamazza az esetlegesen igénybe vehető egyéb szolgáltatásokat: pl: budapesti transzfer, parkolás, biztosítások <file_sep><?php $infxurl = 'http://swiss.kartagotours.hu:88/ws2.asmx/WS1RQ'; $infxhotels = 'http://swiss.kartagotours.hu:88/hotel_xml/xml-nf/'; $infxphotos = 'http://swiss.kartagotours.hu:88/hotel_xml/xml-nf/imgs/'; $infxdata = 'http://swiss.kartagotours.hu:88/infx2/'; $localHotelPath = '/Hotels/'; $localImagesPath = '/Hotels/Images/'; $localInfxFiles = '\\infxFiles\\'; $swiss_user_id = 127; $swiss_id = '945'; $swiss_RBPwd = 'xxxx'; $swiss_user_name = 'Lacika'; $swiss_rcpt = 'home.voxo.hu'; $tesztAjanlat = "2504143"; $tesztAjanlatSzobaTipus = "2+2_ACH"; $tesztAjanlatGiata = "A"; $indulas = '07.10.2021'; $hazaerkezes = '14.10.2021'; $priceFile = './infxFiles/pl_infx2.xml'; ?> <file_sep># php kliens megvalósítás ## Fejlesztői megjegyzés Elnézést ha a php kód nem mindenhol a legprofibb, de jómagam korábban nem használtam a nyelvet, de igyekeztem olvasható, használható kódot írni. > Ez csak egy példa megvalósítás a dokumentáció alapján, nem törekedve minden részében az éles környezetben változtatás nélküli futtatásra, de használható és működik, szabadon felhasználható. Ha hibát találtok, kérlek jelezzétek a Githubon. ## letöltés [Githubon](https://github.com/kartago-tours-zrt/INFX2) elérhető. ## RuleBox API Az api_infx2 mappában található az infxservice.php file. Ez a file a [RuleBox](RuleBox.md) összes funkcióját kezeli. A működéshez szüksége pár globális változót definiálni ```php $infxurl = 'http://swiss.kartagotours.hu:88/ws2.asmx/WS1RQ'; $swiss_user_id = 127; $swiss_id = 'xxx'; $swiss_RBPwd = 'xxx'; $swiss_user_name = 'Lacika'; $swiss_rcpt = 'home.voxo.hu'; ``` Ezek az adatok a [RuleBox](RuleBox.md) leírás alapján a SWISS programból nyerhetőek ki. ### Kommunikáció A megvalósítás curl POST hívásokat használ. Az ```infx2post($request)``` függvény átírásával könnyedén lehet GET vagy SOAP hívásokara áttérni. ## Statikus adatok letöltése Statikus adatok letöltésére is van php kód, ezt a FileLoadService.php file betöltésével tudjuk használni. ## Demó működés Az előző függvényeket használva, könnyen tudják a rendszerükkel illeszeni a Kartago Tours Zrt árualapját. Az infxDataSeed.php programmal a statikus fileokat tudjuk letölteni. Ez egy komplett megoldás, pár módosítással integrálható a rendszerünk mellé. Futtatásával a következő adatok töltődnek le a ```params.php``` beállításai szerinti mappákba - Hotel információk (kb 2600 xml file) - Hotel képei (kb 48000 jpg file) - infx2 file - updt_infx2 fileok (lehet több is egy nap) - pl_infx2 file - pl_updt file (lehet több is egy nap) - extras_list (2 db file) pl_updt file kivételével a zip-el tömörített változat töltődik le. > Fontos, hogy csak megfelelően paraméterezve indítsuk a letöltéseket. A Hotel információ és a képek nagyon nagy adatmennyiség viszont viszonylag ritkán módosulnak, ezért dátum szűréssel minimalizálni kell a letöltések mennyiségét. A program a Hotel és kép letöltését mindenképpen szabályozza egy dátum változóval, és csak a megadott dátumnál újabb fileokat tölti le. Ez a gyakorlatban azt jelenti, hogy legelső használatkor ezt a dátumot egy meglehetősen korai időre pl. 10 évvel ezelőttre kell állítani, hogy biztosan letöltsünk mindent. Az infxDataSeed.php file módosításával tudjuk elérni. Az alábbi kód 1 nappal korábbra állítja a szűrő dátumát. ```php $dt = new DateTime(); $dt->sub(new DateInterval('P1D')); ``` > Ha a **P1D** értéket **P10Y** értékre cseréljük, akkor a 10 évvel ezelőttre állítottuk a szűrőt. így csak egyszer futtassuk, utána állítsuk vissza az eredeti értékre. > Persze lehet paraméterezni is, és programból állítani, de ez csak mintaprogram, nem éles megvalósítás. A DataSeed.php program a dinamikusan (API) letölthető adatokat menti le. Futtatásával a következő adatok töltődnek le a ```params.php``` beállításai szerinti mappákba - Szezonok - Ellátás típusok - Szobatípusok - Repterek - Ártípusok - Felárak - Felár szabályok <file_sep><?php function xml_adopt2($root, $new, $namespace = null) { // first add the new node // NOTE: addChild does NOT escape "&" ampersands in (string)$new !!! // replace them or use htmlspecialchars(). see addchild docs comments. $node = $root->addChild($new->getName(), (string) $new, $namespace); // add any attributes for the new node foreach($new->attributes() as $attr => $value) { $node->addAttribute($attr, $value); } // get all namespaces, include a blank one $namespaces = array_merge(array(null), $new->getNameSpaces(true)); // add any child nodes, including optional namespace foreach($namespaces as $space) { foreach ($new->children($space) as $child) { xml_adopt($node, $child, $space); } } } function xml_adopt($root, $new) { $rootDom = dom_import_simplexml($root); $newDom = dom_import_simplexml($new); $rootDom->appendChild($rootDom->ownerDocument->importNode($newDom, true)); } ?><file_sep><?php require_once('xml_adopt.php'); function infx2post($request, $requestFileName = "") { if ($requestFileName != "") { //$request->saveXML($requestFileName); file_put_contents($requestFileName, $request); $temp = simplexml_load_file($requestFileName); $dom1 = dom_import_simplexml($temp)->ownerDocument; $dom1->formatOutput = true; file_put_contents($requestFileName, $dom1->saveXML()); } $fields = [ 'rXML' => $request ]; $fields_string = http_build_query($fields); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$GLOBALS['infxurl']); curl_setopt($ch, CURLOPT_VERBOSE, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded')); curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); return $response; } function AddAuthentication($xml, $extended = 0) { $xml->addChild('PartnerID', $GLOBALS['swiss_id']); $xml->addChild('RBPwd', $GLOBALS['swiss_RBPwd']); if ($extended != 0) { $xml->addChild('UserID', $GLOBALS['swiss_user_id']); $xml->addChild('rcpt', $GLOBALS['swiss_rcpt']); $xml->addChild('UserName', $GLOBALS['swiss_user_name']); } } function SeasonListRequest() { $xmlstr = <<<XML <SeasonListRequest></SeasonListRequest> XML; return infx2post($xmlstr); } function BoardsRequest() { $xmlstr = <<<XML <BoardsRequest></BoardsRequest> XML; return infx2post($xmlstr); } function RoomTypesRequest() { $xmlstr = <<<XML <RoomTypesRequest></RoomTypesRequest> XML; return infx2post($xmlstr); } function AirportsRequest() { $xmlstr = <<<XML <AirportsRequest></AirportsRequest> XML; return infx2post($xmlstr); } function OtherPricesRequest() { $xmlstr = <<<XML <OtherPriceTypesRequest></OtherPriceTypesRequest> XML; return infx2post($xmlstr); } function AccomodationPriceTypesRequest() { $xmlstr = <<<XML <AccomodationPriceTypesRequest></AccomodationPriceTypesRequest> XML; return infx2post($xmlstr); } function ExtrasRequest($term_id) { $xmlstr = <<<XML <ExtrasRequest> <PackageID></PackageID> </ExtrasRequest> XML; $xml = simplexml_load_string($xmlstr); $xml->PackageID = $term_id; return infx2post($xml->asXML()); } function PriceAvailabilityCheckRequest($term_id, $board_type, $room_type, $paxdetails, $makebooking = 0) { $xmlstr = <<<XML <PriceAvailabilityCheckRequest> <Package> <PackageID></PackageID> <BoardType></BoardType> <RoomType></RoomType> </Package> <PaxDetails> </PaxDetails> </PriceAvailabilityCheckRequest> XML; $xmlpaxdetailsstr = <<<XML <PaxDescription> <DateOfBirth></DateOfBirth> </PaxDescription> XML; $xml = simplexml_load_string($xmlstr); $xml->Package->PackageID = $term_id; $xml->Package->BoardType = $board_type; $xml->Package->RoomType = $room_type; if ($makebooking != 0) { $xml->addChild('MakeBooking', ''); AddAuthentication($xml,1); } $xmlpaxdetail = simplexml_load_string($xmlpaxdetailsstr); foreach($paxdetails as $paxdetail) { $xmlpaxdetail->DateOfBirth = $paxdetail; xml_adopt($xml->PaxDetails, $xmlpaxdetail); } return infx2post($xml->asXML(), "PriceAvailabilityCheckRequest.xml"); } function BookingInfoRequest($bnr) { $xmlstr = <<<XML <BookingInfoRequest> <bnr></bnr> </BookingInfoRequest> XML; $xml = simplexml_load_string($xmlstr); $xml->bnr = $bnr; AddAuthentication($xml,0); return infx2post($xml->asXML()); } function BookingInfoRequest1($bnr) { $xmlstr = <<<XML <BookingInfoRequest1> <BNR></BNR> </BookingInfoRequest1> XML; $xml = simplexml_load_string($xmlstr); $xml->BNR = $bnr; AddAuthentication($xml,0); return infx2post($xml->asXML()); } function BookingRemoveRequest($bnr) { $xmlstr = <<<XML <BookingRemoveRequest> <bnr></bnr> </BookingRemoveRequest> XML; $xml = simplexml_load_string($xmlstr); $xml->bnr = $bnr; AddAuthentication($xml,0); return infx2post($xml->asXML()); } function AvailabilityCheckRequest($term_id, $room_type, $paxcount, $roomcount = 1) { $xmlstr = <<<XML <AvailabilityCheckRequest> <PackageID></PackageID> <RoomType></RoomType> <PaxCount></PaxCount> <RoomCount></RoomCount> </AvailabilityCheckRequest> XML; $xml = simplexml_load_string($xmlstr); $xml->PackageID = $term_id; $xml->RoomType = $room_type; $xml->PaxCount = $paxcount; $xml->RoomCount = $roomcount; return infx2post($xml->asXML(), "AvailabilityCheckRequest.xml"); } function GetAddPriceRulesRequest() { $xmlstr = <<<XML <GetAddPriceRulesRequest></GetAddPriceRulesRequest> XML; return infx2post($xmlstr); } function PaymentsByXMLDataInfoRequest($basedata) { $bdr = <<<XML <PaymentsByXMLDataInfoRequest> <bnr></bnr> <xmls3> <contractdata> <calculation> <ReqID></ReqID> </calculation> </contractdata> </xmls3> </PaymentsByXMLDataInfoRequest> XML; $xml = simplexml_load_string($bdr); $xml->bnr = $basedata->Booking->bnr; AddAuthentication($xml,0); $xml->xmls3->contractdata->bnr = $basedata->Booking->bnr; $xml->xmls3->contractdata->partner_addr_id = $GLOBALS['swiss_id']; $xml->xmls3->contractdata->partner_addr_type = 0; // ReqID beállítása $xml->xmls3->contractdata->calculation->ReqID = $base->Control->ReqID; return infx2post($xml->asXML(), "PaymentsByXMLDataInfoRequest.xml"); } function GenerateCustomerRequest($pax) { $paxsrecord = <<<XML <address_customer> <pax_id></pax_id> <fname></fname> <sname></sname> <title></title> <street></street> <city></city> <post_code></post_code> <country></country> <phone></phone> <email></email> </address_customer> XML; $res = simplexml_load_string($paxsrecord); // customer data $res->pax_id = 1; $res->fname = $pax['name']; $res->sname = $pax['sname']; $res->title = $pax['title']; $res->street = $pax['street']; $res->city = $pax['city']; $res->post_code = $pax['post_code']; $res->country = $pax['country']; $res->phone = $pax['phone']; $res->email = $pax['email']; return $res; } function GeneratePaxRequest($paxs) { $paxrecord = <<<XML <pax> <pax_id></pax_id> <fname></fname> <sname></sname> <title /> <idcrm /> <sex></sex> <bd></bd> <passport /> <nationality></nationality> </pax> XML; $paxsrecord = <<<XML <paxs></paxs> XML; $res = simplexml_load_string($paxsrecord); // paxs $paxxml = simplexml_load_string($paxrecord); foreach($paxs as $pax) { $paxxml->pax_id = $pax['id']; $paxxml->fname = $pax['fname']; $paxxml->sname = $pax['sname']; $paxxml->title = $pax['title']; $paxxml->idcrm = $pax['idcrm']; $paxxml->sex = $pax['sex']; $paxxml->bd = $pax['bd']; $paxxml->passport = $pax['passport']; $paxxml->nationality = $pax['nationality']; xml_adopt($res ,$paxxml); } return $res; } function BookingDataRequest($base, $customer, $priceList, $paxs, $extras, $startDate, $endDate, $fileName = '') { $bdr = <<<XML <BookingDataRequest> <bnr></bnr> <xmls3> <contractdata> <bnr></bnr> <partner_addr_id></partner_addr_id> <partner_addr_type></partner_addr_type> <remark_order/> <remark_order0/> <remark_order1/> <remark_order2/> <join_bnr/> <vouchers/> </contractdata> </xmls3> </BookingDataRequest> XML; $xml = simplexml_load_string($bdr); $xml->bnr = $base->Booking->bnr; AddAuthentication($xml,0); $xml->xmls3->contractdata->bnr = $base->Booking->bnr; $xml->xmls3->contractdata->partner_addr_id = $GLOBALS['swiss_id']; $xml->xmls3->contractdata->partner_addr_type = 0; xml_adopt($xml->xmls3->contractdata, GenerateCustomerRequest($customer)); xml_adopt($xml->xmls3->contractdata, GeneratePaxRequest($paxs)); xml_adopt($xml->xmls3->contractdata, GenerateCalculation($base, $extras, $priceList, $endDate)); $otherPrice = 0.0; foreach ($xml->xmls3->contractdata->calculation->extras->price_record as $extra) { $otherPrice = $otherPrice + ((float)$extra->quantity)*((float)$extra->final_price); } xml_adopt($xml->xmls3->contractdata, GeneratePayments($startDate, (float)$base->Package->PriceDetails->PackagePrice, $otherPrice)); return infx2post($xml->asXML(), "BookingDataRequest.xml"); } // Paraméterben várja a <PriceAvailabilityCheckResponse> eredményét -> $base // $extras array tartalmazza az extra felárakat, amit kérnek (mindent csak 1x, a rendszer automatikusan minden utasra felrakja) // $endDate a hazaérkezés dátuma 'nap.honap.ev' formátumban szövegesen. (xml adatokból) function GenerateCalculation($base, $extras, $priceList, $endDate) { $calculationTemplate = <<<XML <calculation> <ReqID></ReqID> <base_prices> </base_prices> <extras> </extras> </calculation> XML; // first base prices $basepricestemplate = <<<XML <price_record> <pax_id></pax_id> <quantity></quantity> <item></item> <item_d></item_d> <base_price></base_price> <discount></discount> <final_price></final_price> <price_type></price_type> <price_type_d /> </price_record> XML; $extrarecordtemplate = <<<XML <price_record> <pax_id></pax_id> <quantity></quantity> <item></item> <item_d></item_d> <base_price></base_price> <discount></discount> <final_price></final_price> </price_record> XML; $res = simplexml_load_string($calculationTemplate); $res->ReqID = $base->Control->ReqID; $totalPrice = (float)$base->Package->PriceDetails->PackagePrice; print_r($priceList); foreach($base->Package->PriceDetails->PriceInfos->PriceInfo as $basepriceInput) { $price = getPrice($priceList, trim($basepriceInput->item)); $baseprice = simplexml_load_string($basepricestemplate); if (!$price) continue; // ilyen nem lehetne! hibakezelés!!! (most csak simán kihagyom) $baseprice->pax_id = $basepriceInput->pax_id; $baseprice->quantity = $basepriceInput->quantity; $baseprice->item = $basepriceInput->item; $baseprice->item_d = $basepriceInput->item_d; $baseprice->base_price = $price->price_c; $baseprice->final_price = $basepriceInput->price; $baseprice->discount = $baseprice->base_price - $baseprice->finla_price; $baseprice->price_type = $basepriceInput->price_type; $baseprice->price_type_d = $basepriceInput->price_type_d; xml_adopt($res->base_prices, $baseprice); } $firstPerson = true; // utasokra extra felárak foreach ($base->Package->ReqDetails->Paxs->Pax as $pax) { // extras foreach($extras as $extra) { // ha csak szerződésenként kell az ár, akkor csak a főutashoz adjuk hozzá if (!$firstPerson && $extra->type1 == 'S') continue; // az adott utas életkora megfelel e az ártípusnak? if (!IsYearOk($endDate, $pax->pax_bd, $extra->AgeF, $extra->AgeT )) continue; $extraprice = simplexml_load_string($extrarecordtemplate); $extraprice->pax_id = $pax->pax_id; $extraprice->quantity = 1; $extraprice->item = $extra->type; $extraprice->item_d = $extra->descr; $extraprice->base_price = $extra->price; $extraprice->discount = '0%'; $extraprice->final_price = $extra->price; if (substr($extra->type,0,8) == 'STOREXTA') { $extraprice->base_price = round($extra->price*$totalPrice/10000); $extraprice->final_price = round($extra->price*$totalPrice/10000); } xml_adopt($res->extras, $extraprice); } $firstPerson = false; } return $res; } function getPrice($priceList, $priceType) { foreach ($priceList->price as $pr) { if (trim($pr->price_type) == $priceType) { return $pr; } } return null; } function GeneratePayments($start, $packagePrice, $otherPrice) { $paymentTemplate = <<<XML <payment> <amount /> <due_date /> </payment> XML; $paymentsTemplate = <<<XML <payments> <payment_voucher /> </payments> XML; $res = simplexml_load_string($paymentsTemplate); $startDate = DateTime::createFromFormat('d.m.Y', $start); $day30 = DateTime::createFromFormat('d.m.Y', $start);; $day65 = DateTime::createFromFormat('d.m.Y', $start);; $day30->sub(new DateInterval('P15D')); $day65->sub(new DateInterval('P65D')); $today = new DateTime(); $totalPrice = $packagePrice + $otherPrice; $priceBag = 0; // 65 napont túl 10000 előleggel fizetés if ($today < $day65) { $pt = simplexml_load_string($paymentTemplate); $pt->amount = 10000; $pt->due_date = $today->format('d.m.Y'); $priceBag = 10000; xml_adopt($res, $pt); } // 40% előleg befizetése if ($today < $day30) { $pt = simplexml_load_string($paymentTemplate); $price40Percent = round($totalPrice*0.4); $pt->amount = $price40Percent-$priceBag; if ($today < $day65 && $priceBag > 0) { $pt->due_date = $day65->format('d.m.Y'); } else { $pt->due_date = $today->format('d.m.Y'); } $priceBag = $price40Percent; xml_adopt($res, $pt); } // 30 napon belül a teljes hátralék esedékes $pt = simplexml_load_string($paymentTemplate); $pt->amount = $totalPrice-$priceBag; if ($today < $day30) { $pt->due_date = $day30->format('d.m.Y'); } else { $pt->due_date = $today->format('d.m.Y'); } $priceBag = $price40Percent; xml_adopt($res, $pt); return $res; } // két dátum különbsége napokban 'nap.honap.év' formátumú szöveges dátumok között function IsYearOk($baseDate, $birth, $minYear, $maxYear) { $endDate = DateTime::createFromFormat('d.m.Y', $baseDate); $birthDate = DateTime::createFromFormat('d.m.Y', $birth); if ($birthDate->add(new DateInterval('P'.$minYear.'Y')) >= $endDate) return false; if ($birthDate->add(new DateInterval('P'.$maxYear.'Y')) < $endDate) return false; return true; } ?> <file_sep>[Kezdőoldal](README.md) ## Alapárak ### Elérhető Az adat XML formátumban a http://swiss.kartagotours.hu:88/infx2/ helyről tölthető le. A file elnevezési konvenziója a következő: pl_infx2_*.xml Ahol a "*" a file aktuális generálásakori idő értéke a következő formátumban: ÉÉÉÉ-HH-NN-ÓÓ-PP-MM-eee------- példa: pl_infx2_2019-03-07-02-11-36-017-------.xml Mivel a file mérete meglehetősen nagy ezért a file elérhető zip tömörítéssel is ahol a teljes név kiegészül a ".zip" kiterjesztéssel. példa: pl_infx2_2019-03-07-02-11-36-017-------.xml.zip ### Letöltési utasítás A fileból naponta egy készül hajnalban. Délelőtt 3:00 -ig elkészül, ezért az utánra érdemes időzíteni a letöltést és feldolgozást. ### Adat leírása #### Példa adat ```XML <price_list> <price> <season_dsc>HUNKAW18</season_dsc> <package_id>2372940</package_id> <h>HRGMNH</h> <price_type>DBL</price_type> <price_c>165900.00</price_c> <max_age>99</max_age> <price_c_vf>01.01.2000</price_c_vf> <price_c_vt>31.12.2099</price_c_vt> <price_lm>129900.00</price_lm> <price_lm_vf>02.03.2019</price_lm_vf> <price_lm_vt>29.03.2019</price_lm_vt> <price_lm_d>LM*39</price_lm_d> </price> . . . </price_list> ``` Mező | Érték leírása ---- | ---- season_dsc | Szezon kódja pakage_id | Csomag ID (TERM ID) price_type | Ár típus price_c | Katalógus ár max_age | Ekkora életkorig alkalmazható price_c_vf | Katalógus ár ettől az időponttól alkalmazható price_c_vt | Katalógus ár eddig az időpontig alkalmazható price_lm | Lastminute ár price_lm_vf | Lastminute ár ettől az időponttól alkalmazható price_lm_vt | Lastminute ár eddig az időpontig alkalmazható price_lm_d | Lastminute ár típusa ### Frissítés Napközben 2 óránkén készül(het) egy frissíés, ami a hajnalban elkészült filehoz képesti változásokat tartalmazza. Ha nam volt az árakban változás, akkor nem készül file, de ha volt, akkor igen. A file elnevezési konvenciója pl_updt*.xml Különbség file az előző pl_infx2_*.xml filehoz képest. A struktúra megegyezik. példa: pl_updt_2019-03-06-21-00-52-700-------.xml > Mivel ez a file alapvetően nem nagy, ezért tömörített változat ebből nem készül. <file_sep># Kartago Tours Zrt - adatkapcsolat dokumentáció A Kartago Tours Zrt folyamatosan fejleszt, hogy partnereinek minél hatékonyabban tudja átadni az árualapját, ezzel megkönnyítve a sikeres értékesítéseket. A partnerek igényei és lehetőségei viszont jelentősen eltérnek, ezért a Kartago Tours Zrt vezetése úgy döntött, hogy támogatja az offline és az online adatátadást is. ## Offline adatátadás Ez a már hagyományosnak mondható módszer, amikor egy vagy több fileban az árualapot átadjuk a partnereinknek. Ezt a Kartago Tours Zrt naponta többször frissülő XML formátumú adatstruktúrában adja át. Ez jelenleg 2db XML filet jelent, valamint az ajánlatokhoz tartozó képeket külön kell letölteni. Az offline adatokkal letölthetjük az árualapot, de a foglalásainkat kézzel kell a rendszerünkbe rögzíteni. Az [Offline](offline.md) adatátadás leírása és szerkezete. ## Online adatelérés Az online adateléréssel valós időben tudunk információkat lekérni az árualapunkról, valamint akár azonnal le is foglalhatjuk. Utasadatokat fizetési ütemezést is átadhatjuk, így akár teljesen automatizálhatják a weboldalukon a foglalást, ezzel időt és munkaerőt megspórolva. Az [Online](online.md) adatátadás leírása és szerkezete.<file_sep><?php // a path helyről beolvassa a pl_ filet és a $packageid által jelölt árlistát kiszedi // az updt_pl update file(okat) is megnyitja, és ha van benne a packageid-ra hivatkozás, akkor kiveszi és // összefésüli az alap árakkal. // eredményül visszaadja az árakat function getPrices($path, $packageid) { $ret = array(); // pricelist file keresése $plname = findLastFile($path, "pl_", ".xml"); if ($plname != "") { $pl = simplexml_load_file($path . $plname); $ret = $pl->xpath("/price_list/price/package_id[.='$packageid']/parent::*"); } var_dump($ret); } // egy mappából beolvassa a legutolsó előfordulását a $prefix kezdetű és a $suffix végű filekból. function findLastFile($path, $prefix, $suffix) { $ret = ""; $files = scandir($path); $lastDate = new DateTime(); foreach ($files as $name) { if (substr($name, 0, strlen($prefix)) === $prefix && substr($name, strlen($name)-strlen($suffix), strlen($suffix)) === $suffix) { if ($ret == null) { $ret = $name; $lastDate = date ("F d Y H:i:s.", filemtime($path . $name)); } else { $fileDate = date ("F d Y H:i:s.", filemtime($path . $name)); if ($lastDate < $fileDate) { $lastDate = $fileDate; $ret = $name; } } } } return $ret; } ?><file_sep><?php /* Online törzsadatok letöltése */ require_once('../params.php'); include '../api_infx2/infxservice.php'; // szezonok letöltése $file = './Responses/SeasonListResponse.xml'; file_put_contents($file, SeasonListRequest()); // ellátás típusok letöltése $file = './Responses/BoardsResponse.xml'; file_put_contents($file, BoardsRequest()); // szobatípusok letültése $file = './Responses/RoomTypesResponse.xml'; file_put_contents($file, RoomTypesRequest()); // repterek letöltése $file = './Responses/AirportsResponse.xml'; file_put_contents($file, AirportsRequest()); // egyéb ártípusok letöltése $file = './Responses/OtherPricesResponse.xml'; file_put_contents($file, OtherPricesRequest()); // felárak letöltése $file = './Responses/AccomodationPriceResponse.xml'; file_put_contents($file, AccomodationPriceTypesRequest()); // Ár szabályok letöltése $file = './Responses/GetAddPriceRulesResponse.xml'; file_put_contents($file, GetAddPriceRulesRequest()); ?> <file_sep><?php /* Online információ lekérése egy kiválasztott ajánlatról Itt most a params.php file tartalmazza, melyik ajánlatot akarjuk foglalni Előzetesen tudnunk kell hányan utaznak és az életkorokat. */ require_once('../params.php'); include '../api_infx2/infxservice.php'; global $tesztAjanlat, $tesztAjanlatSzobaTipus, $tesztAjanlatGiata; // kiegészítő szolgáltatások letöltése adott ajánlathoz $file = './Responses/ExtrasResponse.xml'; file_put_contents($file, ExtrasRequest($tesztAjanlat)); // ajánlat elérhetőségének ellenőrzése $file = './Responses/AvailabilityCheckResponse.xml'; file_put_contents($file, AvailabilityCheckRequest($tesztAjanlat, $tesztAjanlatSzobaTipus, '2' )); // betöltjük a választ // (éles rendszerben nem kell lementeni és betölteni!) $xml1 = simplexml_load_file("./Responses/AvailabilityCheckResponse.xml"); // ha a válasz rendben és foglalható if (trim($xml1->Control->ResponseStatus) == "success" && $xml1->Availibility->Book == "Y") { // utasok életkorai, a helyes árképzéshez // (nem kell pontosan, de gyerek hazaérkezéskor ne legyen idősebb mint az itt megadott, // felnőttek esetében lényegtelen, csak 18 évnél idősebb legyen beállítva) $paxs = array('19740104','19660202'); // ajánlat árképzésének betöltése $file = './Responses/PriceAvailabilityCheckResponse.xml'; file_put_contents($file, PriceAvailabilityCheckRequest($tesztAjanlat, $tesztAjanlatGiata, $tesztAjanlatSzobaTipus, $paxs )); // betöltjük a választ // (éles rendszerben nem kell lementeni és betölteni!) $xml2 = simplexml_load_file("./Responses/PriceAvailabilityCheckResponse.xml"); // ha foglalható, ezt az ajánlatot lehet megjeleníteni if (trim($xml2->Control->ResponseStatus) == "success") { var_dump($xml2->Package->PriceDetails->asXML()); } } ?><file_sep>[Kezdőoldal](README.md) ## INFX2 Az INFX2 egy egyszerű szöveges file, kötött adatszerkezettel. Csak a zölddel jelölt sorokat használja az EXIM csoport. Az INFX file konkrét ajánlatokat tartalmaz kalkulált árakkal. Az adott szobatípuson belül a fő utasra kikalkulált / fő árat tartalmazza. Használata nagyon hasznos, amennyiben az utas böngészik az ajánlatok között, mert ehhez konkrét árat tudunk rendelni egy egy ajánlathoz. Az INFX2 struktúra, egy nemzetközi szabványon alapul, viszont nem minden mezöjét használjuk. A struktúra végén a használaton kívüli nagy részt az EXIM csoport kiegészítő információk tárolására használja. [Beágyazott XML adat](#embedded-data). ### Elérhető Az adat TXT formátumban a http://swiss.kartagotours.hu:88/infx2/ helyről tölthető le. A file elnevezési konvenziója a következő: infx2_*.txt Ahol a "*" a file aktuális generálásakori idő értéke a következő formátumban: ÉÉÉÉ-HH-NN-ÓÓ-PP-MM-eee------- példa: infx2_2019-03-07-02-11-36-017-------.txt Mivel a file mérete meglehetősen nagy ezért a file elérhető zip tömörítéssel is ahol a teljes név kiegészül a ".zip" kiterjesztéssel. példa: infx2_2019-03-07-02-11-36-017-------.txt.zip ### Frissítés Napközben 2 óránkén készül(het) egy frissíés, ami a hajnalban elkészült filehoz képesti változásokat tartalmazza. Ha nam volt az árakban változás, akkor nem készül file, de ha volt, akkor igen. A file elnevezési konvenciója updt_infx2_*.txt Különbség file az előző pl_infx2_*.xml filehoz képest. A struktúra megegyezik. példa: updt_infx2_2019-03-06-13-00-49-750-------.txt A file elérhető zip tömörítéssel is ahol a teljes név kiegészül a ".zip" kiterjesztéssel. példa: updt_infx2_2019-03-06-13-00-49-750-------.txt.zip ### Letöltési utasítás A fileból naponta egy készül hajnalban. Délelőtt 3:00 -ig elkészül, ezért az utánra érdemes időzíteni a letöltést és feldolgozást. Frissítés kb 2 óránként minden páratlan órában készül. ### Adat leírása Mező | Pozíció kezdete | Pozíció vége | Hossz | Megjegyzés ---- | ---- | ---- | ---- | ---- Verzió | 1 | 2 | 2 | Akció | 3 | 3 | 1 | **Szervező** | 4 | 8 | 5 | Üres | 9 | 14 | 6 | Ajánlat száma | 15 | 24 | 10 | Felhasználó csoportok | 25 | 33 | 9 | **Indulás dátuma** | 34 | 43 | 10 | **Hazaérkezés dátuma** | 44 | 53 | 10 | **Oda út indulási repülőtér** | 54 | 56 | 3 | **Oda út cél repülőtér** | 57 | 59 | 3 | **Visszaút indulási reptér** | 60 | 62 | 3 | **Visszaút cél reptér** | 63 | 65 | 3 | **Oda út légitársaság** | 66 | 68 | 3 | Visszaút légitársaság | 69 | 71 | 3 | Oda út gép száma | 72 | 74 | 3 | Visszaút gép száma | 75 | 77 | 3 | **Oda út beszállás** | 78 | 81 | 4 | Ha értéke 0000 akkor még nincs pontos idő. Ünnepnap jelölése kiutazáskor | 82 | 82 | 1 | **Oda út érkezés** | 83 | 86 | 4 | Ha értéke 0000 akkor még nincs pontos idő. **Visszaút beszállás** | 87 | 90 | 4 | Ha értéke 0000 akkor még nincs pontos idő. Ünnepnap jelölése visszaútkor | 91 | 91 | 1 | **Visszaút érkezés** | 92 | 95 | 4 | Ha értéke 0000 akkor még nincs pontos idő. Oda út járatszám | 96 | 99 | 4 | Visszaút járatszám | 100 | 103 | 4 | **Kijelölés** | 104 | 104 | 1 | Gyermek kijelölés | 105 | 105 | 1 | **Személyek minimum száma** | 106 | 106 | 1 | **Személyek maximális száma** | 107 | 107 | 1 | **Felnőttek min száma** | 108 | 108 | 1 | **Felnőttek max száma** | 109 | 109 | 1 | **Valuta** | 110 | 112 | 3 | **Ár** | 113 | 124 | 12 | Időskori ár | 125 | 136 | 12 | Csecsemő ár | 137 | 148 | 12 | **Gyermek 1 kortól** | 149 | 150 | 2 | **Gyermek 1 korig** | 151 | 152 | 2 | Gyermekár 1 | 153 | 164 | 12 | Gyermek 2 kortól | 165 | 166 | 2 | Gyermek 2 korig | 167 | 168 | 2 | Gyermekár 2 | 169 | 180 | 12 | Különleges kedvezmény | 181 | 181 | 1 | Különleges gyermek kedvezmény | 182 | 182 | 1 | Pótágy korig | 183 | 184 | 2 | **Pótágyak száma** | 185 | 185 | 1 | Üres | 186 | 187 | 2 | **Úti cél** | 188 | 212 | 25 | **Hotel neve** | 213 | 237 | 25 | **Kategória** | 238 | 240 | 3 | **Szállás kód** | 241 | 242 | 2 | **Szállás megnevezése** | 243 | 267 | 25 | **Étkezés kód** | 268 | 269 | 2 | Étkezés megnevezése | 270 | 294 | 25 | Utazás típus kód | 295 | 296 | 2 | Utazás típus megnevezés | 297 | 321 | 25 | **TOMA Szervező** | 322 | 325 | 4 | **TOMA Strand** | 326 | 329 | 4 | TOMA Akció | 330 | 331 | 2 | TOMA Feltételek 1 | 332 | 334 | 3 | TOMA Feltételek 2 | 335 | 337 | 3 | TOMA Feltételek 3 | 338 | 340 | 3 | TOMA Feltételek 4 | 341 | 343 | 3 | **TOMA Repterek 1** | 344 | 360 | 17 | **TOMA Repterek 2** | 361 | 377 | 17 | TOMA Repterek 3 | 378 | 394 | 17 | TOMA Repterek 4 | 395 | 411 | 17 | **TOMA Szállás 1** | 412 | 417 | 6 | **TOMA Szállás 2** | 418 | 423 | 6 | TOMA Szállás 3 | 424 | 429 | 6 | TOMA Szállás 4 | 430 | 435 | 6 | Hotel neve 1 | 436 | 515 | 80 | Felszerelés | 516 | 595 | 80 | ***Felszerelés helye*** | 596 | 675 | 80 | ***További infó*** | 676 | 755 | 80 | ***Katalógus neve*** | 756 | 795 | 40 | ***Katalógus oldal*** | 796 | 799 | 4 | ***Repülőtér*** | 800 | 802 | 3 | ***Hotel*** | 803 | 805 | 3 | ***Prioritás*** | 806 | 807 | 2 | ***Infó cím*** | 808 | 825 | 18 | ***Hivatkozás*** | 826 | 985 | 160 | ### Beágyazott XML struktúra <a name="embedded-data"></a> Az INFX2 szabványos struktúra 596-os pozíciójától 390 karakter hosszan az EXIM XML struktúrában tárol adatot. Ez a kiegészítő információ fontos a megfelelő működéshez. Egy példa struktúra itt látható. Sortörések és szünetek nélkül tartalmazza. Nem feltétlen van minden mező a struktúrában. ````XML <INFO> <ISU>Y</ISU> <SDOV>21.04.2019</SDOV> <SODV>07.04.2019</SODV> <SID>4</SID> <TID>000002372936</TID> <RT>1+0</RT> <DAB>HRGBELA</DAB> <PRC>0281800.00HUF</PRC> <KC>0336800.00HUF</KC> <FX>0.00325</FX> <PT>LM*39</PT> <OnR>0</OnR> <PG>N</PG> <SL>N</SL> <ST>AAAA</ST> <Q>8</Q> </INFO> ```` Mező | Érték leírása ---- | ---- F2LD | Haza érkezés időpont F1SD | Indulás időpont SDOV | Szállás kijelentkezés napja SODV | Szállás bejelentkezés napja SID | Szezon azonosító TID | Csomag azonosító (régen TERM ID) RT | Szállás típusa DAB | Kartago csoport hotel azonosító PRC | Ár és pénznem FX | Használt EUR árfolyam PT | Ár típusa C, LM,ULM,… PG | Y/N ingyen gyermekár lehetséges PG% SL | Y/N Kedvezményes ár SLV*% KC | Katalógus ár és pénznem OnR | Foglalhatóság típusa. 1 = lekérésre, egyébként 0 ISU | Y/N Változott e a sor, vagy új az előző INFX2-höz képest. kb. 4:30-kor készül naponta. ST | négyjegyű kód marketing események (pl. valós kedvezmény) <file_sep># Kartago3.XML felépłtése ```XML <offer code="HRGCORA" hotel_dsc="CORAL BEACH" season="HUNKAS19" term_id="2456324" DepartureDate="13.07.2020" ArrivalDate="20.07.2020" RoomSwissId="2+2_FR_CHA" BoardCode="AI" BoardGiataCode="A" AdultCount="2" ChildCount="1" Variation="AAc" KatalogPrice="0240400.00HUF" Price="0240400.00HUF"> <prices> <price PersonNumber="1" MinAge="14" MaxAge="99" Price="278900.00" PriceDescription=".2 ágyas szoba felnott ár/ fo" PriceType="DBL" Extra="N" IsChild="N" IsDiscount="N" IsLastMinute="N" ChildNumber="0" /> <price PersonNumber="1" MinAge="14" MaxAge="99" Price="45900.00" PriceDescription="Családi szoba felnott felár/ fo" PriceType="SUP FR" Extra="N" IsChild="N" IsDiscount="N" IsLastMinute="N" ChildNumber="0" /> <price PersonNumber="2" MinAge="14" MaxAge="99" Price="278900.00" PriceDescription=".2 ágyas szoba felnott ár/ fo" PriceType="DBL" Extra="N" IsChild="N" IsDiscount="N" IsLastMinute="N" ChildNumber="0" /> <price PersonNumber="2" MinAge="14" MaxAge="99" Price="45900.00" PriceDescription="Családi szoba felnott felár/ fo" PriceType="SUP FR" Extra="N" IsChild="N" IsDiscount="N" IsLastMinute="N" ChildNumber="0" /> <price PersonNumber="3" MinAge="2" MaxAge="14" Price="119900.00" PriceDescription="1. gyermek pótágyon ár xx éves korig" PriceType="1CHEXB-1 F" Extra="N" IsChild="Y" IsDiscount="N" IsLastMinute="N" ChildNumber="1" /> <price PersonNumber="3" MinAge="2" MaxAge="14" Price="0.00" PriceDescription="Családi szoba 1. gyermek felár xx éves korig" PriceType="SUP FR1CH-1" Extra="N" IsChild="Y" IsDiscount="N" IsLastMinute="N" ChildNumber="1" /> <price PersonNumber="3" MinAge="0" MaxAge="2" Price="13900.00" PriceDescription="Baby ár" PriceType="INFN" Extra="N" IsChild="Y" IsDiscount="N" IsLastMinute="N" ChildNumber="1" /> </prices> </offer> ``` Offer adatai: Mező | Leírás ---- | ---- code | Szálloda kódja (lásd Kartago.xml leírást) hotel_dsc | Szálloda megnevezés season | szezon azonosító (lásd Kartago.xml leírást) term_id | ajánlat azonosító (lásd Kartago.xml leírást) DepartureDate | Indulási dátum ArrivalDate | Hazaérkezés dátuma RoomSwissId | Szoba kódja (lásd Kartago.xml leírást) BoardCode | Ellátás kódja (lásd Kartago.xml leírást) BoardGiataCode | Ellátás Giata rendszerbeli kódja. INFX összerendelés miatt (lásd Kartago.xml leírást) AdultCount | Felnőttek száma ChildCount | Gyermekek száma Variation | Ágyak leosztása. Nagy betű: fő ágy. Kis betű: pót ágy. A: Adult - felnőtt, C : Child - gyermek KatalogPrice | Katalógus ára a fő utasnak Price | Ár a fő utasnak Price adatai: Mező | Leírás ---- | ---- PersonNumber | Az ajánlaton belül a szemlyeket sorszámmal látjuk el. (Felnőtt és gyermek is.) MinAge | Minimum korhatár akire az ár érvényes (Ezt már be kell töltenie hazaérkezéskor) MaxAge | Maximum korhatár akire az ár érvényes (ezt még nem töltheti be hazaérkezéskor) Price | Ár PriceDescription | Ár megnevezése PriceType | Ár típusa a Kartago Tours renszerében Extra | Ha 'Y', akkor ez egy extra felár. IsChild | Ha 'Y', akkor egy gyermekre vonatkozó ár IsDiscount | Ha 'Y', akkor ez egy kedvezményes ár IsLastMinute | Ha 'Y', akkor lastminute kedvezményt tartalmazó ár ChildNumber | Ha gyermek ár, akkor megadja hányadik gyermek. ## Utasok elhelyezése a szobában - legjobb ajánlat Az offer Variation attribútuma megadja, hogy hány fő megy a szobába. Felnőtt és gyermek, és ki megy főagyra és ki pótágyra. Alapvetően először a felnőttekkel töltjük fel a helyeket. A fő ágyakat a legidősebb utassal elkezdve töltjük fel. Ennek akkor van jelentősége, ha gyermek is kerül fő ágyra. A pótágyakat ha van felnőtt, akkor szintén azzal kezdjük tölteni, majd a gyermekek következnek, a --legfiatalabbal-- kezdve, kivéve a csecsemőt. A csecsemőkre speciális ár van, ezért a csecsemők mindíg a legutolsók a sorban. Ha így elhelyezzük az utasokat a szobákban, akkor minden utasra a PersonNumber értékének megfelelően alkalmazzuk az árakat, figyelembe véve a MinAge és a MaxAge életkor szűrőt. A fenti példában két felnőtt és egy gyerek kerül a szobába. Felnőttek főágyon, gyerek pótágyon. Ha a gyerek 2-14 éves kor között van a hazainduláskor, akkor a 1CHEXB-1 F + SUP FR1CH-1 értípusú árakat kell számolni. Ha csecsemő a gyermek, akkor az INFN ártípus érvényes csak. Az offer nem tartalmaz kalkulált teljes árat, mivel a gyermekek életkorától függően véltozhat az ár. Ha valakinek a rendszere csak teljes kikalkulált árakkal működik, akkor az ezekből az információkból legenerálhatja az összes variációt.<file_sep># Megvalósítási esettanulmány A statikus adatokat beszerezzük. Erre példa az [infxDataSeed.php](phpDemo.md). A beszerzett adatokat a weboldalunk adatbázisába integráljuk. ## INFX használata Az INFX egy szöveges állomány, statikusan letölthető. Lényege, hogy minden szálloda, minden időpontjára, minden szobatípusára és minden turnusára (1 hetes, 2 hetes, stb) tartalmazza a fő utas teljes árát. > A Kartago Tours Zrt 2020 nyári időszaktól az árba bele kalkulálja a reptéri illetéket is. Mire is jó az INFX? Ha egy ügyfél keres utat, akkor az INFX alapján tudunk kezdeti árajánlatot írni. Ha tengerre néző szobát szeretne, akkor csak olyan szobatípusokra szűrünk, és máris csak azokat az árakat látja. Az INFX tartalmazza a minimum, maximum létszámot és ebből mennyi lehet minimum és maximum felnőtt. Ahhoz, hogy egy utasnak konkrét árkalkulációt adhassunk, el kell jutnunk addig, hogy az INFX alapján kiválasszon az ügyfél egy konkrét ajánlatot. Ennek az ajánlatnak az INFX-ben van egy PackadeID azonosítója (TID). Kell tudnunk a létszámot és a gyermekek életkorát. (A pontos életkorok itt még nem fontosak, de a gyerekek életkora a hazaérkezés dátumakor évben stimmeljen.) INFX alapján tudjuk a szobatípust és az étkezés kódot. A termInfoSeed.php egy ilyen lekérést valósít meg. Az INFX paramétereket a params.php-ban a $tesztAjanlat mezőkben vannak beállítva. ### Árajánlat 1. Letölti az ajánlathoz tartozó Extrákat. (Reptéri parkolás, Budapest transzfer, vízum, Storno biztosítás, BBP, stb). Ezek nem kötelezőek, de egyrészük csak foglaláskor köthető, ezért érdemes ajánlani. 2. Az ```AvailabilityCheckRequest``` függvénnyel megnézzük, hogy az ajánlat foglalható e. > Miért van a listában, ha nem foglalható? Egy szállodában korlátozottan vannak előre lekötött szobák. Lehet, hoyg standard szoba elérhető a rendszer szerint de tengerre néző nem. Ez viszont nem jelenti azt, hogy nem lehet lekéréssel foglalni. Abban az esetben, ha egy ajánlat nem elérhető, akkor az utasnak azt jelenítsük meg, hogy lekérésre foglalható. 3. Ha elérhető az ajánlat, akkor a ```PriceAvailiablityCheckRequest``` fügvénnyel árajánlatot kérünk a rendszertől. Itt pontos árat kapunk, reptéri illetékekkel és esetleges kedvezményekkel. Az árak részletezve, utasonként vannak. Ez még nem foglalás, csak pontos, részletes árajánlat az ügyfélnek. Ezt az ajánlatot kell az 1. pontban letöltött extrákkal ajánlani. ### Foglalás Amennyiben egy ajánlat tetszik az ügyfélnek, lehet foglalást kezdeményezni. <file_sep><?php // filelist listában léfő fileokat tölti le a megadott url-ről a $path -ban lévő helyre. function downloadList($filelist, $url, $path) { foreach ($filelist as $fileinfo) { echo $fileinfo->name . " letöltése\r\n"; file_download($url, $fileinfo->name, $path); } } // a megadott url-en listázza a fileokat és fileinfo listába rakja function getFilteredFilesList($url, $date) { // sorok letöltése $rows = file_list($url); // fileifo-vá alakítás $fileinfos = array(); foreach($rows as $row) { $fileinfo = get_fileinfo($row); if ($fileinfo) { $fileinfos[] = $fileinfo; } } return filterrows($fileinfos, $date); } function findFilesFromFilteredList($filelist, $prefix, $suffix) { $ret = array(); foreach ($filelist as $file) { $name = $file->name; if (substr($name, 0, strlen($prefix)) === $prefix && substr($name, strlen($name)-strlen($suffix), strlen($suffix)) === $suffix) { $ret[] = $file; } } return $ret; } // adott web folder tartalmának letöltése function file_list($url) { echo $url; echo "\r\n"; $c_session = curl_init(); curl_setopt ($c_session, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($c_session, CURLOPT_URL, $url); curl_setopt ($c_session, CURLOPT_TIMEOUT, '100'); $content = curl_exec($c_session); curl_close ($c_session); $rows = explode('<br>', $content); echo 'Found ' . count($rows) . " rows."; echo "\r\n"; return $rows; } // adott file letöltése function file_download($url, $filename, $path) { set_time_limit(0); //This is the file where we save the information $fp = fopen ($path . $filename, 'w+'); // downloaded file $durl = $url . $filename; //Here is the file we are downloading, replace spaces with %20 $ch = curl_init(str_replace(" ","%20",$durl)); curl_setopt($ch, CURLOPT_TIMEOUT, 50); // write curl response to file curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // get curl response curl_exec($ch); curl_close($ch); fclose($fp); } // web folder adatsor fileinfo-vá alakítása function get_fileinfo($row) { $ret = new \stdClass(); if (preg_match('/(?<time>.*)(?<D>[PA]M)(?<size>.*)<A HREF=\".*\">(?<name>.*)<\/a>/i', $row, $matches)) // { $ret->name = trim($matches["name"]); $ret->size = intval($matches["size"]); $ret->date = date_create_from_format('D, M d, Y H:i', trim($matches["time"])); if ($matches["D"] == "PM") { $ret->date->add(new DateInterval('PT10H')); } // 0 hosszúságú, akkor könyvtár, vagy hibás file, ami úgyse kell. if ($ret->size == 0) return NULL; } else { return NULL; } return $ret; } // fileinfo tömb dátum alapján szűrése function filterrows($fileinfos, $date) { $ret = array(); foreach($fileinfos as $fileinfo) { if ($fileinfo->date >= $date) { $ret[] = $fileinfo; } } return $ret; } ?> <file_sep><?php /* Az offline fileok letöltése */ function xml_adopt($root, $new) { $rootDom = dom_import_simplexml($root); $newDom = dom_import_simplexml($new); $rootDom->appendChild($rootDom->ownerDocument->importNode($newDom, true)); } // price listből kikeresi az adott foglalás árait, csak a teszthez kell, éles környezetből ezt nem az xml-ből kell venni function GetPriceList($bnr, $plFile) { $pricesTemp = <<<XML <prices> </prices> XML; $pt = simplexml_load_file($plFile); $ret = simplexml_load_string($pricesTemp); foreach ($pt->price as $price) { if ($price->package_id == $bnr) { xml_adopt($ret, $price); } } // $dom = new DomDocument('1.0'); // $dom->preserveWhiteSpace = false; // $dom->formatOutput = true; // $domdata= dom_import_simplexml($ret); // $domdata = $dom->importNode($domdata, true); // $domdata = $dom->appendChild($domdata); // return $dom->saveXML(); return $ret->asXML(); } require_once('../params.php'); include '../api_infx2/FileLoadService.php'; global $infxdata, $localInfxFiles, $localHotelPath, $infxhotels, $infxphotos, $localImagesPath, $priceFile , $tesztAjanlat; // Hotel adatok letöltése echo "Hotel adatok letöltése\r\n"; // dátum. Ennél régebbit ne töltsön le. Ha minden nap futtatjuk, akkor pl mindíg az előző napot állítsuk be. "P1D" // első futtatáskor állítsunk be egy nagyon régi dátumot az összes adat letöltéséhez (pl: "P10Y" ) $dt = new DateTime(); $dt->sub(new DateInterval('P1D')); // params fileban rögzített helyről töltünk le a hotelinfokat $files = getFilteredFilesList($infxhotels, $dt); echo "Összes letöltendő file: " . count($files) . "\r\n"; downloadList($files, $infxhotels, dirname(__FILE__) . $localHotelPath); // // képek letöltése (ugyan azt a dátumot használhatjuk) // $files = getFilteredFilesList($infxphotos, $date); // echo "Összes letöltendő file: " . count($files) . "\r\n"; // downloadList($files, $infxphotos, dirname(__FILE__) . $localImagesPath); // Mai nap, tegnapi adat nem kell $dt = new DateTime('12:00am'); // szerveren elérhető fileok listája $filelist = getFilteredFilesList($infxdata , $dt); // az így kapott listában keressük a nekünk szükséges fileokat // INFX file letöltése (a tömörítettet!) // file keresése $files = findFilesFromFilteredList($filelist, "infx2_", ".txt.zip"); // letöltés //var_dump($files); downloadList($files, $infxdata, dirname(__FILE__) . $localInfxFiles); // INFX Updt letöltése // file keresése $files = findFilesFromFilteredList($filelist, "updt_infx2_", ".txt.zip"); // letöltés //var_dump($files); downloadList($files, $infxdata, dirname(__FILE__) . $localInfxFiles); // Price list letöltése. // file keresése $files = findFilesFromFilteredList($filelist, "pl_infx2_", ".xml.zip"); // letöltés //var_dump($files); downloadList($files, $infxdata, dirname(__FILE__) . $localInfxFiles); // Extrák letöltése. Igazi online működés esetén nem szükséges // file keresése $files = findFilesFromFilteredList($filelist, "extras_list_", ".xml.zip"); // letöltés //var_dump($files); downloadList($files, $infxdata, dirname(__FILE__) . $localInfxFiles); // Price list update letöltése. // file keresése $files = findFilesFromFilteredList($filelist, "pl_updt_", ".xml"); // letöltés //var_dump($files); downloadList($files, $infxdata, dirname(__FILE__) . $localInfxFiles); file_put_contents('./infxFiles/priceList.xml', GetPriceList($tesztAjanlat, $priceFile)); ?><file_sep>[Kezdőoldal](README.md) ## Felárak A választható felárakat tartalmazza. (A [req_ OtherPricesRequest]() funkcióval is elérhető) ### Elérhető Az adat XML formátumban a http://swiss.kartagotours.hu:88/infx2/ helyről tölthető le. A file elnevezési konvenziója a következő: extras_list_*_[0,1].xml Ahol a "*" a file aktuális generálásakori idő értéke a következő formátumban: ÉÉÉÉ-HH-NN-ÓÓ-PP-MM-eee------- példa: extras_list_2019-03-07-02-11-36-017-------_0.xml Mivel nagyon nagy az adat mennyiség, ezért két file tartalmazza az adatokat. *_1.xml és *_2.xml A fileok elérhetőek zip tömörítéssel is ahol a teljes név kiegészül a ".zip" kiterjesztéssel. példa: extras_list_2019-03-07-02-11-36-017-------_0.xml.zip ### Letöltési utasítás A fileból naponta egy készül hajnalban. Délelőtt 3:00 -ig elkészül, ezért az utánra érdemes időzíteni a letöltést és feldolgozást. ### Adat leírása #### Példa adat ```XML <Extras> <Extra i="2373967" h="LPALOP" t="OSRB_LPA" p="39900.0000" t1="1" t2="N"/> <Extra i="2373967" h="LPALOP" t="z.poj.online.silver.8" p="5280.0000" t1="1" t2="N"/> <Extra i="2373967" h="LPALOP" t="STOREXTA-LPA" p="200.0000" t1="S" t2="N"/> <Extra i="2373967" h="LPALOP" t="z.poj.online.gold.8" p="7120.0000" t1="1" t2="N"/> . . . </Extras> ``` Mező | Érték leírása ---- | ---- i | Csomag ID (TERM ID) t | Ár típus kódja h | Szállás kódja p | Ár t1 | 1 = minden utasra alkalmazni kell; S = szerződésenként egyszer t2 | R = kérésre; N = ?? TODO <file_sep><?php /* Foglalás elkészítése Itt most a params.php file tartalmazza, melyik ajánlatot akarjuk foglalni */ require_once('../params.php'); include '../api_infx2/infxservice.php'; global $tesztAjanlat, $tesztAjanlatSzobaTipus, $tesztAjanlatGiata, $indulas, $hazaerkezes; // ajánlat elérhetőségének ellenőrzése $file = './Responses/AvailabilityCheckResponse.xml'; //file_put_contents($file, AvailabilityCheckRequest($tesztAjanlat, $tesztAjanlatSzobaTipus, '2' )); // betöltjük a választ // (éles rendszerben nem kell lementeni és betölteni!) $xml1 = simplexml_load_file("./Responses/AvailabilityCheckResponse.xml"); // ha a válasz rendben és foglalható if (trim($xml1->Control->ResponseStatus) == "success" && $xml1->Availibility->Book == "Y") { echo "Availability success!"; // utasok életkorai, a helyes árképzéshez // (nem kell pontosan, de gyerek hazaérkezéskor ne legyen idősebb mint az itt megadott, // felnőttek esetében lényegtelen, csak 18 évnél idősebb legyen beállítva) $paxs = array('19740104','19660202'); // ajánlat árképzésének betöltése $file = './Responses/PriceAvailabilityCheckMakeBookingResponse.xml'; // utolsó paraméter nem 0, ezért opciós ajánlat készül file_put_contents($file, PriceAvailabilityCheckRequest($tesztAjanlat, $tesztAjanlatGiata, $tesztAjanlatSzobaTipus, $paxs, 1 )); // betöltjük a választ // (éles rendszerben nem kell lementeni és betölteni!) $xml2 = simplexml_load_file("./Responses/PriceAvailabilityCheckMakeBookingResponse.xml"); // extra felárak. Teszt miatt ebből kiválasztjuk a silver biztosítást, a storno biztosítást és a parkolást // ez itt most erre a foglalásra igaz, más foglalásnál egyedileg kell megnézni, milyen lehetőségek vannak. // a lehetőségek a ExtrasResponse.xml-ben vannak $extrasFull = simplexml_load_file("./Responses/ExtrasResponse.xml"); $priceList = simplexml_load_file("./infxFiles/priceList.xml"); $extras[] = []; foreach ($extrasFull->extras->extra as $extra) { if ($extra->type == 'z.poj.online.silver.8') { $extras[] = $extra; } if ($extra->type == 'STOREXTA-HRG') { $extras[] = $extra; } if ($extra->type == 'PARKING_EB_7') { $extras[] = $extra; } } // az első 0 elemet töröljük array_shift($extras); // ha foglalható, ezt az ajánlatot lehet megjeleníteni if (trim($xml2->Control->ResponseStatus) == "success") { // ha sikeres a foglalás if (trim($xml2->Booking->bnr_result) == "success") { // foglalási szám $bnr = $xml2->Booking->bnr; echo "Availability success! Bnr: " . $bnr; // foglalás alapadatok $file = './Responses/BookingInfoResponse.xml'; file_put_contents($file, BookingInfoRequest($bnr)); // utasadatok $customer = array ("name"=>"Geza", "sname"=>"Proba", "title"=>"", "street"=>"Locsei ut 57", "city"=>"Budapest", "post_code"=>"1147", "country"=>"HUN", "phone"=>"209472212", "email"=>"<EMAIL>"); $pax1 = array ("id"=>"1", "fname"=>"Elek", "sname"=>"Teszt", "title"=>"", "idcrm"=>"", "sex"=>"M", "bd"=>"02.02.1966", "passport"=>"", "nationality"=>"HUN"); $pax2 = array ("id"=>"2", "fname"=>"BÉLA", "sname"=>"PRÓBA", "title"=>"", "idcrm"=>"", "sex"=>"M", "bd"=>"04.01.1974", "passport"=>"", "nationality"=>"HUN"); // $pax3 = array ("id"=>"3", "fname"=>"Bella", "sname"=>"Proba", // "title"=>"", "idcrm"=>"", "sex"=>"W", // "bd"=>"01.01.2010", "passport"=>"", "nationality"=>"HUN"); // utasadatok tömb: szerződő és az utasok $paxs = array ($pax1, $pax2); // Szerződő és utas adatok átadása $file = './Responses/BookingDataResponse.xml'; file_put_contents($file, BookingDataRequest($xml2, $customer, $priceList, $paxs, $extras, $indulas, $hazaerkezes)); // fizetési ütemezés lekérése $file = './Responses/PaymentsByXMLDataInfoResponse.xml'; file_put_contents($file, PaymentsByXMLDataInfoRequest($xml2, $paxs)); // Foglalás részletes infó $file = './Responses/BookingInfoResponse1.xml'; file_put_contents($file, BookingInfoRequest1($bnr)); // Ez csak teszt, töröljük is le a foglalást!! $file = './Responses/BookingRemoveResponse.xml'; //file_put_contents($file, BookingRemoveRequest($bnr)); } } } ?><file_sep>[Kezdőoldal](README.md) ## Szálloda információk ### Elérhető [http://swiss.kartagotours.hu:88/hotel_xml/xml-nf](http://swiss.kartagotours.hu:88/hotel_xml/xml-nf) #### Alternatív elérhetőségek: #beágyazott kép formátum A szálloda információk elérhetőek a - [http://swiss.kartagotours.hu:88/hotel_xml](http://swiss.kartagotours.hu:88/hotel_xml) - [http://swiss.kartagotours.hu:88/hotel_xml/xmllint-format](http://swiss.kartagotours.hu:88/hotel_xml/xmllint-format) helyeken is. Mindkét alternatív helyen az első helyen lévő XML adatot kapjuk, de itt a képekre nem csupán hivatkozás van, hanem az XML file tartalmazza a képeket is Base64 kódolással. > Lehet ezt is használni, de a frissítés nehézkesebb. A képek frissítésére ebben az esetben nem kell külön eljárást készíteni, viszont a képek dekódolása és mentése plusz kódolási folyamat, így végeredményben nem tudunk kódolási időt spórolni. ### Letöltési utasítás Közel 2600 szálloda leírás van a rendszerben XML formátumban, ezért fontos, hogy csak azokat az adatokat töltsük le, amit még nem töltöttünk le korábban. Erre a legmegfelelőbb módszer, hogy első ízben letöltjük az elérhető tartalmat (ha lehet éjjeli időpontban), és a letöltés időpontját eltároljuk. Időközönként csak egy frissítő letöltést indítunk, ahol csak az utolsó letöltés dátumánál újabb fileokat töltjük le. Ugyan ezt az eljárást alkalmazzuk a [képek](Pictures.md) letöltésénél is. ### Adat leírása #### Példa adat ```XML <offer> <code> MIRHOU</code> <name> HOUDA GOLF & BEACH CLUB</name> <dest_code> TUNP</dest_code> <dest_name> Tunézia</dest_name> <dest_region> Monastir</dest_region> <dest_subregion> Monastir</dest_subregion> <dest_airport> Monastir</dest_airport> <category> 3</category> <offertype> PP</offertype> <exclusivity/> <url/> <texts> <perex> Közvetlenül a homokos tengerparton fekvő szálloda, mely jó szolgáltatásokkal várja a pihenni vágyókat. A hotel nem messze fekszik Sousse és Monastir központjától, mindkét központ buszjárattal könnyedén megközelíthető. A golfozás szerelmesei itt valóban megtalálhatják számításaikat. Minden korosztály számára ajánljukUtazásszervező iroda hazai besorolása: 3*.</perex> <distances> távolság a tengerparttól: közvetlen<br>távolság a repülőtértől (Monastir): 10 km<br>távolság a központtól (Sousse): 10 km<br>távolság az üzletektől: 10 km</distances> <roomfacil> kétágyas szoba <br>tengerre nézo szoba felárért lekérésre<br>egyéni légkondicionáló (foszezonban)<br>telefon, muholdas TV<br>saját fürdoszoba (kád vagy zuhanyfülke, WC)<br>széf - külön fizetendo<br>erkély vagy terasz</roomfacil> <hotelfacil> recepció, főétterem<br>2 a la carte étterem (tunéziai, olasz)<br>bár, snack bár, diszkó<br>üzlet<br>internet sarok - külön fizetendő<br>medence (napágyak és napernyők ingyenesen)<br>gyermekmedence, miniklub<br>aquapark, csúszdák</hotelfacil> <beachdescr> homokos part<br>napágyak és napernyők ingyen, matrac illetékért<br>vízi sportok illetékért<br></beachdescr> <entericnl> animációs programok<br>alkalmanként esti műsorok<br>fitnesz, török gőzfürdő, szauna<br>aerobik, teniszpálya, asztalitenisz, minigolf<br>darts, röplabda, kosárlabda, íjászat</entericnl> <enterchrg> biliárd<br>jacuzzi, masszázs</enterchrg> <boardincl> all inclusive: napi háromszori foétkezés, helyi alkoholos és alkoholmentes italok korlátlan fogyasztása 10:00-tol 02:00-ig, heti 2 szer étkezés az a la carte étteremben, napközben snack (snack bár, szendvics). Az all inclusive szállodák szolgáltatásai bizonyos részletekben szállodánként eltérhetnek.</boardincl> <boardchrg></boardchrg> <youtubelnk/> <pictograms> 110001111011111001101000</pictograms> <icons/> <gps> 35.781953; 10.693483</gps> </texts> <images> <image image_id="24549"/> <image image_id="24572"/> <image image_id="24571"/> <image image_id="24569"/> <image image_id="24568"/> <image image_id="24567"/> <image image_id="24566"/> <image image_id="24565"/> <image image_id="24564"/> <image image_id="24563"/> <image image_id="24562"/> <image image_id="24561"/> <image image_id="24560"/> <image image_id="24557"/> <image image_id="24556"/> <image image_id="24555"/> <image image_id="24554"/> <image image_id="24553"/> <image image_id="24552"/> <image image_id="24551"/> <image image_id="24550"/> </images> </offer> ``` #### Mező leírások Mező | Érték leírása -----|----- code | Kartago csoport hotel kód name | hotel megnevezése dest_code | Kartago csoport desztináció kódja dest_name | Desztináció neve dest_region | Desztináció régiója dest_subregion | Desztináció alrégiója dest_airport | Desztináció szálloda kódja category | Szállás kategória besorolása offertype | Foglalás típusa (pl síelés, tengerparti üdülés, stb..) exclusivity | Csak Kartago kínálat perex | Szállás információ, bevezető szöveg. distances | Szállás elhelyezkedése roomfacil | Vendégszobák leírása hotelfacil | Szállodai szolgáltatások beachdescr | Strand és a környék leírása entericnl | Ingyenes sportolási lehetőségek enterchrg | Sportolási lehetőségek illetékért boardincl | Ellátás, amit az ár tartalmaz boardchrg | Ellátások, amiket illetékért lehet igénybe venni youtubelnk | YouTube videó link pictograms | Szolgáltatás kínálat piktogramok (bináris kódolással) icons | Ikonok gps | GPS koordináta image | image_id="egyedi azonosító" coding="image/jpeg base64" *coding rész, csak ha a #beágyazott formátumot használjuk* #### `<offertype>` Foglalás típusa. Két betű jelöli. Fő és al típus. Fő típusok: Jel | Leírás --- | --- P | Üdülés Z | kirándulás L | síút Altípus, ami a pontos típust jelöli Jel | Leírás --- | --- PP | Tengerparti üdülés PX | Egzotikus üdülés PJ | Tóparti üdülés PH | Hegyvidéki üdülés PL | SPA / Wellness PB | Buszos üdülés ZO | Városnézés ZS | Szafari túra ZK | kombinációs út ZE | Városnézés / európai hétvége LL | Síelés #### `<picotgrams>` 24 karakter hosszan. Minden karakter két értéket vehet fel, ami jelöli a szolgáltatás meglétét 0 = nincs, 1 = van Piktogramok sorrendben - Légkondicionáló a szobában - Wi-Fi - internet - Parkolás - Kerekesszékkel is járható - wellness / Spa - Gyereksarok - Úszás - tobogán / aquapark - Búvár - golf - tenisz - Vizi sportok - Tornaterem, fitnesz - röplabda - kerékpár - Mango club - Új - Tengerpari szállás - Csak felnőtteknek - Magyar nyelvű idegenvezető - Háziállat bevihető - Exim tipp - Exim minőség > Megjegyzés: > Ha a fejlécben másként nincs jelölve, akkor a kódolás „windows-1252”
31c92e33d08eed2991b32efb1c60a2ef66c399c2
[ "Markdown", "PHP" ]
24
Markdown
kartago-tours-zrt/INFX2
b8d5b83c29e8917dffe4475946e094f9773f5f96
4b4b59720170f181a1ad43377e22c46380e6c756
refs/heads/master
<file_sep># Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ begin = ListNode("begin") tmp = begin while l1 is not None or l2 is not None: if l1 is None: begin.next = l2 break elif l2 is None: begin.next = l1 break elif l1.val < l2.val: begin.next = l1 l1 = l1.next begin = begin.next else: begin.next = l2 l2 = l2.next begin = begin.next return tmp.next def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ if len(lists) == 1: return lists[0] elif len(lists) == 2: return self.mergeTwoLists(lists[0], lists[1]) else: res = lists[0] for i in range(1,len(lists)): res = self.mergeTwoLists(res, lists[i]) return res<file_sep># Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ bef = ListNode("begin") tmp = bef if head is None: return None if head.next is None: return head while head is not None: if head.next is not None: bef.next = head.next head.next = head.next.next bef.next.next = head bef = head head = head.next else: break return tmp.next def printListNode(head): if head is None: print("None") return while head.next is not None: print(head.val) head = head.next print(head.val) def create(NodeList): last = ListNode(NodeList[0]) a = last for i in NodeList[1:]: tmp = ListNode(i) last.next = tmp last = tmp return a if __name__ == "__main__": test = create([1, 2,3,4,5]) printListNode(Solution().swapPairs(test)) <file_sep>class Solution: def myPow(self, x, n): """ :type x: float :type n: int :rtype: float """ if n == 0: return 1 if x == 0: return 0 if n < 0 : x = 1/x n = -n res = 1 for _ in n: res = res * x if __name__ == "__main__": print(pow())<file_sep>import math class Solution(object): saved = dict() def numSquares(self, n): """ :type n: int :rtype: int """ max_num = int(math.sqrt(n)) if n in self.saved.keys(): return self.saved[n] if n == pow(max_num, 2): self.saved[n] = 1 return 1 min_num = 1000000000000 index = max_num while index > 0: cur = 1 + self.numSquares(n - index * index) if cur == 2: min_num = cur break if cur < min_num: min_num = cur index -= 1 self.saved[n] = min_num return min_num if __name__ == "__main__": print(Solution().numSquares(7168)) <file_sep>class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 0 last = nums[0] leng = 1 for i in range(1, len(nums)): if nums[i] == last: continue else: nums[leng] = nums[i] leng += 1 last = nums[i] print(nums[:leng]) return leng if __name__ == "__main__": print(Solution().removeDuplicates([1,1,2,3,5,5,6]))<file_sep>class Solution(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ length = len(haystack) - len(needle) if length < 0: return -1 else: for i in range(length+1): if haystack[i:i+(len(needle))] == needle: return i return -1 if __name__ == "__main__": print(Solution().strStr("a", ""))<file_sep># Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None def __str__(self): return self.val def __repr__(self): return str(self.val) class Solution(object): def reverseKGroup(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if head is None: return None last1 = ListNode("begin") last1.next = head tmo = last1 while head is not None: group = head # 首先判断是不是还有k个node 如果有 进行reverse 否则 直接返回 for i in range(k - 1): if head.next is not None: head = head.next else: return tmo.next line1 = group line2 = line1.next for i in range(k - 1): tmp = line2.next line2.next = line1 line1 = line2 line2 = tmp last1.next = line1 last1 = group # 如果刚好结束 接k的整数倍个节点 那么直接返回即可 如果没有结束 先把当前k-group的1接到下一个group的1 # 接续下一个轮回 group.next = line2 head = line2 return tmo.next def printListNode(head): if head is None: print("None") return while head.next is not None: print(head.val) head = head.next print(head.val) def create(NodeList): last = ListNode(NodeList[0]) a = last for i in NodeList[1:]: tmp = ListNode(i) last.next = tmp last = tmp return a if __name__ == "__main__": test = create([1]) printListNode(Solution().reverseKGroup(test, 3)) <file_sep>class Solution(object): def isValidSudoku(self, board): """ :type board: List[List[str]] :rtype: bool """ columes = [] subs = [] for row in board: if len([e for e in row if e != "."]) != len(set(row)) - 1: return False for i in range(9): column = [row[i] for row in board] columes.append(column) if len([e for e in column if e != "."]) != len(set(column)) - 1: return False for i in range(3): for j in range(3): sub = board[i * 3][j * 3:(j+1) * 3] + board[i * 3 + 1][j * 3:(j+1) * 3] + board[i * 3 + 2][j * 3:(j+1) * 3 ] subs.append(sub) if len([e for e in sub if e != "."]) != len(set(sub)) - 1: return False possibility = [] for i in range(9): prob_row = [] for j in range(9): if board[i][j] == ".": prob_row.append([str(e) for e in range(1,10) if str(e) not in list(board[i])]) else: prob_row.append([board[i][j]]) possibility.append(prob_row) for i in range(9): for j in range(9): if columes[i][j] == ".": possibility[j][i] = [e for e in possibility[j][i] if e not in list(columes[i])] for i in range(9): for j in range(9): if subs[i][j] == ".": rown = int(i / 3 + j / 3) columnn = int(i % 3 * 3 + j % 3) possibility[rown][columnn] = [e for e in possibility[j][i] if e not in list(subs[i])] print(possibility) for r in possibility: for c in r: if len(c) == 0: return False return True if __name__ == "__main__": board = [".87654321", "2........", "3........", "4........", "5........", "6........", "7........", "8........", "9........"] Solution().isValidSudoku(board=board) <file_sep>class Solution: def wordBreak(self, s, wordDict): """ :type s: str :type wordDict: List[str] :rtype: List[str] """ reserve = dict() def dfs(s, wordDict, start): if start in reserve.keys(): return reserve[start] final = [] alternative = [] for word in wordDict: if len(word) <= len(s) and s[:len(word)] == word: alternative.append(word) if not len(alternative): return None for alt in alternative: if len(alt) == len(s): final.append([alt]) continue next = dfs(s[len(alt):], wordDict, start + len(alt)) if next: for t in next: final.append([alt] + t) reserve[start] = final return final re = dfs(s, wordDict, 0) if not re: return [] return [' '.join(s) for s in re] if __name__ == "__main__": print(Solution().wordBreak("aaa", ["a", "aa"])) <file_sep>class Solution(object): def myAtoi(self, str): """ :type str: str :rtype: int """ num_list = list(str.strip()) if len(num_list) == 0: return 0 signal = -1 if num_list[0] == '-' else 1 num = 0 if num_list[0] in ['+', '-']: del num_list[0] i = 0 while i < len(num_list) and num_list[i].isdigit(): num = num * 10 + ord(num_list[i]) - ord("0") i = i + 1 return signal * min(2**31, num) if signal == -1 else min(2**31-1, num) if __name__ == "__main__": a = Solution() print(a.myAtoi("123")) <file_sep>class Solution(object): def firstMissingPositive(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 1 flag = [] for e in nums: if e >= 0: if len(flag) == 0: flag = [0] * (len(nums) + 2) for e in nums: if 0 < e < len(nums) + 2: flag[e-1] = 1 for i in range(len(flag)): if flag[i] != 1: return i + 1 return len(nums) + 2 if __name__ == "__main__": print(Solution().firstMissingPositive([0])) <file_sep>class Solution(object): def trap(self, height): """ :type height: List[int] :rtype: int """ if len(height) <= 1: return 0 begin = 0 trap = 0 for i in range(1, len(height)): if height[i] >= height[begin]: trap += sum(height[begin] - e for e in height[begin:i]) begin = i else: if height[i] > height[i - 1]: j = i - 1 while j >= 0 and height[j] < height[i]: j -= 1 trap += sum(height[i] - e for e in height[j + 1:i]) for k in range(j + 1, i): height[k] = height[i] return trap if __name__ == "__main__": print(Solution().trap([4, 2, 3])) <file_sep>import math class Solution(object): saved = dict() def numSquares(self, n): """ :type n: int :rtype: int """ i = 1 base = [] while i * i <= n: base.append(i * i) i += 1 index = 1 tmp = base while True: new_tmp = set() for k in tmp: if n == k: return index for b in base: new_tmp.add(k + b) tmp = new_tmp index += 1 if __name__ == "__main__": print(Solution().numSquares(12)) <file_sep># Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ begin = ListNode("begin") tmp = begin while l1 is not None or l2 is not None: if l1 is None: begin.next = l2 break elif l2 is None: begin.next = l1 break elif l1.val < l2.val: begin.next = l1 l1 = l1.next begin = begin.next else: begin.next = l2 l2 = l2.next begin = begin.next return tmp.next def printListNode(head): if head is None: print("None") return while head.next is not None: print(head.val) head = head.next print(head.val) def create(NodeList): last = ListNode(NodeList[0]) a = last for i in NodeList[1:]: tmp = ListNode(i) last.next = tmp last = tmp return a if __name__ == "__main__": a = create([1]) b = create([2]) printListNode(a) printListNode(b) printListNode(Solution().mergeTwoLists(a,b)) <file_sep>import time class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ def simple_match(s, p): all_index = [] for i in range(len(s) - len(p) + 1): if s[i:i + len(p)] == p: all_index.append(i) return all_index def match_rule(s, index, rule): if rule == "": return rule == s[:index] if "*" in rule: return len(s[:index]) >= rule.count("?") else: return len(s[:index]) == rule.count("?") # p_s = p.replace("*", "").replace("?", "") p_s = [] # 第一个函数,把pattern重新组织成数组。用*来分割。 # 两个规则:1.多个连续的*等于一个* # 2. 多个连续的字母串起来 i = 0 while i < len(p): if p[i] == "*": while i < len(p) and p[i] == "*": i += 1 p_s.append("*") elif p[i] == "?": p_s.append("?") i += 1 else: char = [] while i < len(p) and p[i] != "*" and p[i] != "?": char.append(p[i]) i += 1 p_s.append(''.join(char)) # 第二步,对ps遍历,不断寻找符合条件的候选集合 i = 0 rule = [""] candidate = set() candidate.add(0) last_character = "" while i < len(p_s): if "?" not in p_s[i] and "*" not in p_s[i]: filtered = set() for candi in candidate: candi_index = simple_match(s[candi+len(last_character):], p_s[i]) for index in candi_index: if match_rule(s[candi+len(last_character):], index, ''.join(rule)): filtered.add(candi + len(last_character) + index) candidate = filtered rule = [""] last_character = p_s[i] else: rule.append(p_s[i]) i += 1 filtered = set() for candi in candidate: if match_rule(s[candi+len(last_character):], len(s[candi+len(last_character):]), ''.join(rule)): filtered.add(candi) if len(filtered) >= 1: return True else: return False if __name__ == "__main__": sol = Solution() bt = time.time() print(sol.isMatch( "aa", "*")) et = time.time() print(et - bt) <file_sep>""" 总结几种常用的排序算法 """ def bubble_sort(nums): """ 冒泡排序,从后往前,依次把最小的放到前面 :param nums: :return: """ # TODO : python中list的赋值机制 if not nums: return None for i in range(len(nums)): index = len(nums) - 1 while index >= min(i, 1): if nums[index] < nums[index - 1]: nums[index - 1], nums[index] = nums[index], nums[index - 1] index -= 1 return nums def select_sort(nums): """ 选择排序,每次选择后面所有list中最小的进行交换 :param nums: :return: """ for i in range(len(nums) - 1): cur_min = i + 1 for j in range(i, len(nums)): if nums[j] < nums[cur_min]: cur_min = j nums[i], nums[cur_min] = nums[cur_min], nums[i] return nums def insert_sort(nums): """ 插入排序,从0开始,对每一个元素,依次选择合适的位置插入 TODO:不够优雅 看看别人怎么写 :param nums: :return: """ for i in range(1, len(nums)): target = nums[i] j = i - 1 while j >= 0: if nums[j] > target: nums[j + 1] = nums[j] j -= 1 else: nums[j + 1] = target break if j == -1: nums[0] = target return nums def quick_sort(nums): """ 快速排序,分治的思路,先根据一个基数将原始的列表分成两部分,然后递归的分别调用 :param nums: :return: """ def partition(nums, l, r): i, j = l, r pivot = nums[l] while i < j: while j > i and nums[j] > pivot: j -= 1 while i < j and nums[i] <= pivot: i += 1 if i == j: nums[i], nums[l] = nums[l], nums[i] partition(nums, l, i) partition(nums, i + 1, r) else: nums[i], nums[j] = nums[j], nums[i] return return partition(nums, 0, len(nums) - 1) if __name__ == "__main__": test1 = [23, 2, 43, 2, 13, 1, 432, 23, 32, 543, 465, 23, 54, 56, 28, 54] test2 = [5, 3, 8, 6, 4] # TODO : 多种test case quick_sort(test1) print(test1) <file_sep>class Solution(object): def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ # if n < 1: # return [] # elif n == 1: # return ["()"] # elif n == 2: # return ["(())", "()()"] # else: # res = [] # for s in self.generateParenthesis(n - 1): # res += ["(" + s + ")", s + "()", "()" + s] # res.remove("()" * n) # return res res = ['('] i = 0 while i < 2 * n - 1: i += 1 tmp =[] for s in res: l = n - list(s).count("(") r = n - list(s).count(")") if l == 0: tmp.append(s + ")") elif l > 0 and n > 0: if l < r: tmp.append(s + "(") tmp.append(s + ")") else: tmp.append(s + "(") res = tmp return res if __name__ == "__main__": print(len(Solution().generateParenthesis(4))) <file_sep># Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def create(self, NodeList): if len(NodeList) == 0: return [] last = ListNode(NodeList[0]) a = last for i in NodeList[1:]: tmp = ListNode(i) last.next = tmp last = tmp return a def sortNodeList(self, sortList): return sorted(sortList, key=lambda x: x.val) def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ begin = ListNode("begin") tmp = begin val_dict = dict() for node in lists: while node is not None: if node.val in val_dict.keys(): val_dict[node.val] += 1 else: val_dict.setdefault(node.val, 1) node = node.next res = [] for key, value in val_dict.items(): res += [key] * int(value) return self.create(sorted(res)) def printListNode(head): if head is None: print("None") return while head.next is not None: print(head.val) head = head.next print(head.val) def create(NodeList): last = ListNode(NodeList[0]) a = last for i in NodeList[1:]: tmp = ListNode(i) last.next = tmp last = tmp return a if __name__ == "__main__": alist = [[0, 2, 5], [2, 3], [1, 2]] tmpList = [] for a in alist: tmpList.append(create(a)) print(type(tmpList)) print(type(tmpList[0])) # printListNode(Solution().sortNodeList(tmpList)) # printListNode(Solution().mergeKLists(tmpList)) <file_sep>class Solution: def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: bool """ beg = 0 end = len(nums) - 1 while beg < end: mid = int((beg + end) / 2) if target == nums[mid]: return True if nums[mid] > nums[beg]: if target > nums[mid] or target < nums[beg]: beg <file_sep>class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if len(nums) == 0: return 0 if len(nums) == 1: if nums[0] >= target: return 0 else: return 1 begin, end = 0, len(nums) - 1 if target < nums[begin]: return 0 if target > nums[end]: return len(nums) while begin < end: if end - begin == 1: if nums[begin] == target: return begin if nums[end] == target: return end if target > nums[end]: return end + 1 if target < nums[begin]: return begin else: return end mid = int((begin + end) / 2) if target < nums[mid]: end = mid elif target > nums[mid]: begin = mid else: return mid if __name__ == "__main__": print(Solution().searchInsert([1, 2, 3, 4, 5, 7, 8, 9, 10], 6)) <file_sep>def binary_search(A, target): """ 二分法查找每个数值 原始的数字是升序的,可能存在重复的数字/没有重复的数字 :param A: :param target: :return: """ if len(A) == 0: return False if len(A) == 1: return target == A[0] begin = 0 end = len(A) - 1 while begin < end: mid = int((begin + end) / 2) if A[mid] == target: return mid elif target > A[mid]: begin = mid else: end = mid return False if __name__ == "__main__": c = binary_search([1, 3, 6], 3) print(c) <file_sep>class Solution(object): def get(self, nums, mid): m = 1 while mid + m < len(nums): if nums[mid + m] == nums[mid]: m += 1 else: break n = 1 while mid - n >= 0: if nums[mid - n] == nums[mid]: n += 1 else: break return [mid - n + 1, mid + m - 1] def searchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ if len(nums) == 0: return [-1, -1] begin, end = 0, len(nums) - 1 while begin < end: if end - begin == 1: if nums[begin] == target: return self.get(nums, begin) if nums[end] == target: return self.get(nums, end) return [-1, -1] mid = int((begin + end) / 2) if target < nums[mid]: end = mid elif target > nums[mid]: begin = mid else: return self.get(nums, mid) if nums[begin] == target: return [begin, begin] return [-1, -1] if __name__ == "__main__": print(Solution().searchRange([1,1,2], 1)) <file_sep>class Solution(object): def countAndSay(self, n): """ :type n: int :rtype: str """ if n == 1: return "1" bef = self.countAndSay(n - 1) cur = bef[0] count = 0 res = "" for char in bef: if char == cur: count += 1 else: res += str(count) + str(cur) cur = char count = 1 res += str(count) + str(cur) return res if __name__ == "__main__": print(Solution().countAndSay(5)) <file_sep>class Solution: def findLUSlength(self, strs): """ :type strs: List[str] :rtype: int """ def common_sub_sequence(a, b): i, j = 0, 0 while i < len(a) and j < len(b): j = b[j:].index(a[i]) if not j: return -1 i += 1 return -1 if __name__ == "__main__": print()<file_sep>class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ # implement a map from (i,j) to (j,n-i) n-i n -j n-j i i j n = len(matrix) for i in range(int(n / 2 + 0.5)): for j in range(i, int((n - i)) - 1 ): begin = matrix[i][j] matrix[i][j] = matrix[n - j - 1][i] matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1] matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1] matrix[j][n - i - 1] = begin print(matrix) return matrix if __name__ == "__main__": sol = Solution() c = [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]] c2 = [[1, 2], [3, 4]] print(sol.rotate(c)) <file_sep>class Solution(object): def rerange(self, nums): for i in range(int(len(nums) / 2)): nums[i], nums[len(nums) - i - 1] = nums[len(nums) - i - 1], nums[i] def nextPermutation(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ i = len(nums) - 2 while i >= 0: if nums[i] >= nums[i + 1]: i -= 1 else: tmp = nums[i] j = i + 1 while j < len(nums): if nums[j] > tmp: j += 1 else: break nums[i], nums[j-1] = nums[j-1], nums[i] for k in range(int(len(nums[i+1:]) / 2)): nums[i+1+k], nums[i+1+len(nums[i+1:]) - k - 1] = nums[i+1+len(nums[i+1:]) - k - 1], nums[i+1+k] print(nums) return for j in range(int(len(nums) / 2)): nums[j], nums[len(nums) - j - 1] = nums[len(nums) - j - 1], nums[j] print(nums) if __name__ == "__main__": Solution().nextPermutation([5,1,1]) <file_sep>class Solution(object): @staticmethod def get_index(s, word): res = [] for i in range(len(s) - len(word) + 1): if s[i:i + len(word)] == word: res.append(i) return res def get_word_index(self, s, words): word_index = dict() i = 0 while i < len(s): for word in words: if s[i:i + len(word)] == word: word_index.setdefault(i, [word]) break i += 1 return word_index def findSubstring(self, s, words): """ :type s: str :type words: List[str] :rtype: List[int] """ length = sum([len(e) for e in words]) res = [] # index = [] # # # 第一步获取index # for word in words: # index.append(self.get_index(s, word)) # for ind in index: # if len(ind) < 1: # return [] # # 构建word和index 的dict # word_index = dict() # # for i, ind in enumerate(index): # for j in ind: # if j in word_index.keys(): # if words[i] not in word_index[j]: # word_index[j].append(words[i]) # else: # word_index.setdefault(j, [words[i]]) # # print(len(word_index)) word_index = self.get_word_index(s, words) print(len(word_index)) # 第二步 遍历寻找 for i in range(len(s) - length + 1): if i not in word_index.keys(): continue words_set = [e for e in words] flag = 0 path_length = 0 forward = [] path = [] forward.append(word_index[i]) while True: if len(path) == len(words): res.append(i) break if sum([len(e) for e in forward]) <= 0: break if len(forward[flag]) > 0: path.append(forward[flag][0]) path_length += len(forward[flag][0]) forward[flag][0:] = forward[flag][1:] flag += 1 words_set.remove(path[-1]) if i + path_length in word_index.keys(): forward.append([e for e in word_index[i + path_length] if e in words_set]) else: forward.append([]) else: forward[0:] = forward[:-1] flag -= 1 if len(path) > 0: path_length -= len(path[-1]) words_set.append(path[-1]) del path[-1] print([key for key, value in word_index.items() if len(value) > 1]) return res if __name__ == "__main__": s = "<KEY>" sub = ["wxnazzgwzlincurnioleblays", "<KEY>", "<KEY>", "<KEY>", "advmnlciojurgbfdohaworgir", "gbwpprhetfmjddaqxqwmeshas", "vmjcjlzasgtnrazmvfbnrfkuf", "zjxvnmfxayxlgnzssgayidibw", "xmsdwclozzurtesskdrofufkc", "gglmhnnrhwaetgrelkyjrlwbx", "galldybmwzrsozbnxyvfniqyl", "ofrbxnxgnefbaueghcbqldetf", "ltaczrtrtvigvpnqrncazoacp", "psacpkyhfsazmgkkadygnmnio", "mztmeoukmtmsdohlugclrjhgs", "gjdaqjsxphojgoihlowfxoyih", "gpcztxizzwsfvjdmhthsdvlbb", "bksjgvvglkdtuxhlnhkymtgto", "mewbjatnnylmlamrjrumfzkpx", "orsqpyotjlhlskcricbwveqec", "ws<KEY>", "zehikwbrcaqagjrahnbgozsve", "<KEY>", "<KEY>", "zdadsqaumdqnykozmbaerbiac", "zxyoruvlioevfbtvjzsdwugri", "xtvotgutpmetmoiwcxidgwwkx", "cpvxtcnnvmaisoucjvehwdxst", "jfgzacxstacwrwxnrkmagvhkz", "n<KEY>mrmpt", "rwahikxnbanqyveeafgxloepq", "zncxvbeiaxcombypgriszdywt", "ottznlgmljvbcwzxqvouezeop", "rqguzqyfuclhgvoixbotkylmp", "zdsvpffvubvrhlrjkrgecxbjk", "kqbvgarsjtduvdobyduyfhumk", "azhkdexxiqgkgzcfjccmmtdcy", "igcudsdkouxvqfdhinzvzphbd", "igylpaqhxlavtemfrkfbcgtzz", "ezdfanpirjnmnxcjxxbccimpj", "hwydjosbxvsuqcijkiovbfvcf", "lzgwaiijmogbcrtpwmmbffzdt", "fsqgolcvbncttmriivgagppbp", "hsqbiaauxzqeogwrarpfuipmp", "mxonxghsmrqazldhfhuakvdba", "legajnsmaqdhfrsednjrlrhch", "eebwbgifcrjdyunprrhgzamjz", "suxzpxiruizscmubdapkvgoen", "uvnekcbtcfreqywtrjiwymeqb", "pquuuvmknvsafawymztykfphw", "bhxfwbssquhcmpkwupzpuetih", "pshdpvvkotfzcjrrzbarpljus", "<KEY>", "pw<KEY>", "wimiohxvhtlhn<KEY>bx", "<KEY>", "<KEY>", "thmqsvaywlqwdxuozpjddrvpw", "jdpuawgqycxavr<KEY>", "xphftvkfkvtdnsk<KEY>", "mwkcaowmafwecxdrpcwdkoxez", "rrlbbvietzvkhbeonpsqpiogh", "gyglgplsphtjuarwldnhnkrlc", "sqshgljhutkbtjjjrvrtzxcdb", "ihvnmwectywomjdibfnddnsfh", "dymvirpvsqarzwiqnymiodjpn", "evrocfhbeuleghbkdsobdbjdm", "sbbfnsxujdnkeyqziptzkpemt", "gmlucsfhiscphrwbvforsvnur", "nfbceicqizfufcwfzjlmidhrf", "tbqxanffjiubddidfrgbyeemr", "fszmebvmvdsuiiprxkpbemcuf", "ziwqcqzawkinvbcewnawezkhm", "dmolmtryfobswfrujsckykhva", "ewcflmhhprotrtnzcnbxyufad", "qcebmfvorruiawoqyqrotlgnb", "qdnwpemljzmudmyiqpqxpjcsf", "xhaewbjgsdrmpencismzrqlyt", "iyrrcbxvwgjwcdfagcqybywjm", "rhezwydtrswwbzavkfdriqwbe", "kljmfvnkyseotzcyrpwcfyoiy", "xtygncsqeramomcgwupanqmng", "uzoegsotzycktizwzswrvmles", "fzlpchdikhotlgbllxsotxnci", "rrwrxwqqzahgwhhjcvmlswdne", "xt<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "mzeqqrmcewepsrvkyvjgfhehb", "ulzbezgwrroowtoraaifaaucf", "<KEY>", "qtryvjjcrnoiirnlqdewcgvkp", "slemeueamiapngfbuskzbfaxc", "<KEY>", "lhgdmptbdbyptezaxgjshsnxn", "qheoqszaxbvfnshrsjtqkcwhq", "twwkkamuxcwpbylngylhcpgps", "fszrvadibvxnynvkccjgftmxq", "hftqnhwfgpdislmnkzmxwybbj", "i<KEY>hdabisrfcenzf", "mztizykktjbpnsqgjagyhnldz", "eacvxzcmnnigozbjzrazvauct", "<KEY>b<KEY>", "uknkzjtldsgyygjwyctxqaqwh", "lduheaglipveqogteizobzxoc", "ggvzcgkbngexqplfvmhpizlul", "omjeoridfthannguvvhntdvom", "uulivjajzfhhnhunyeqkmojrn", "npofvbdqwtjfnewcjpozzmbwx", "altzpuboytrkxphfnumxhxfan", "scbdcfpqodxmqikioadndchsy", "jfontgnoftejlunfuzvidcezt", "pvohffrkmslopfhpigigfvzpi", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "ljvtceodrqrktbendtdstinos", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "cnnletsdehinmsyugthnuuyrm", "<KEY>", "<KEY>", "ttiemxdgkpaoxpdnzefudcxko", "<KEY>", "eumtsmovwqhgxsuzdvmkkdjih", "irbvapivpnwigpeeykzpxphmt", "czeqbkexwiyleknlgtnfwgwae", "eklxclicwwcbfbeiuxpquficm", "xatbwbssbbcnapobehzzlfcsm", "ztnmuciopqkyqtxxbgkkczihr", "heoqtjzetiuszbuokloowaqnv", "vbdhkekufkwkqdqumhhzynawt", "fjrqhknearpcukfaclsahmrsw", "xlxxweposbstyfasishkbdbrf", "qfrftyzjgtkzrrtwcacaqmxrd", "<KEY>", "ecygwfqaaqq<KEY>", "lwnzokqggkdeavfdelbmsmopa", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "gnmjttbrssaqrxexvetvbbitl", "<KEY>", "<KEY>", "pqlvjmbsdtcnigpzxsukzwmko", "<KEY>", "gttinaushwdwqsz<KEY>", "jawziwsmzxpemhvrehhmrpdrt", "jraqsdwrhbuwtencsbrrdaocd", "<KEY>gz", "zsupwrrbmfqxhznqvgzwncnuc", "isxoessjaxelwczdrfgzvpzuf", "mkvcyneoihyivzdjjyarvpptt", "tblcltdkrtbnonydtvkwofhnz", "bvdiheadshixavlsgzhljyvrh", "wgyfxnvpdglythhclicnaspmk", "jczrsbedwzgcolugcgagmpliu", "hbtaozfiyuncpbxttubdjuawl", "ysesrelasduqdvmqlivkemjwv", "dvegpzylwacuitqstkwhexmfm", "qpohxkseifqgjvzhtpvcudgbs", "xnqfjgnptzygmrpkrtezkklwi", "loagputwqufsnuiliwzkkswbm", "qmaygqwpoluqgnluswyiqtkii", "kfkgujfjnceqgnrfrhruhjbyt", "h<KEY>vwc<KEY>", "<KEY>", "<KEY>", "wfojhsg<KEY>", "<KEY>", "<KEY>", "eah<KEY>", "neawoysnozwgnpfntrgescdna", "<KEY>", "orniwvnuhieayasqajpythnst", "ckaaadehgciomnrg<KEY>", "sy<KEY>", "dssksvddztfkrdasocdhthqic", "vcivwcpuxpghqjprhzgteihsd", "lcfuiasytbjayvaklpqmprckw", "ycjvozfarxyakorbrhvchhowt", "fpvstyicqmnyykqyqxrxhlxlj", "puofavimwtasugazodnbbblky", "nhqeihlxsygethktxbwlvnbja", "xbstdokilljvqkkrjauydntpw"] # s1 = "" print(Solution().findSubstring(s, sub)) <file_sep>class Solution(object): def divide(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int """ # 用减法来实现除法不可行 会超时。。应该使用移位运算符 # 技不如人 甘拜下风 # discuss 答案 sign = (dividend < 0) == (divisor < 0) dividend, divisor = abs(dividend), abs(divisor) res = 0 while dividend >= divisor: mod, weight = divisor, 1 while dividend >= mod: dividend -= mod res += weight weight <<= 1 mod <<= 1 res = res if sign else -res return min(max(-2 ** 31, res), 2 ** 31 -1) if __name__ == "__main__": print(Solution().divide(-2147483648, -1)) <file_sep>class Solution(object): def subset(self, sets): if len(sets) == 0: return [] # 长度分别从1 到 len(sets)的子集 res = [] for i in range(1, 2 ** len(sets)): flag = list(bin(i).replace("0b", "")) flag.reverse() res.append([sets[k] for k in range(len(flag)) if flag[k] == '1']) return res def combinationSum(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ if target == 0: return [] candidates = [ele for ele in candidates if ele <= target] if len(candidates) < 1: return [] times = [int(target / e) for e in candidates] def get_combination(sets, tar): if len(sets) == 1: return [[sets[0]] * int(tar / sets[0])] if tar % sets[0] == 0 else [] else: res = [] cur = 0 while cur * sets[-1] <= tar and cur <= times[len(sets) - 1]: tmp = get_combination(sets[:-1], tar - cur*sets[-1]) if len(tmp) > 0: for t in tmp: res.append(t+[sets[-1]] * cur) cur += 1 return res return get_combination(candidates, target) if __name__ == "__main__": # print(Solution().subset([1, 2, 3])) print(Solution().combinationSum([2], 1)) <file_sep>class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if len(strs) == 0: return "" if len(strs) == 1: return strs[0] lcp = strs[0] def compare(s1, s2): if s1 == s2 : return s1 leng = min(len(s1), len(s2)) if leng == 0: return "" for i in range(leng): if s1[i] != s2[i]: return s1[:i] return s1[:leng] for s in strs[1:]: lcp = compare(lcp, s) if lcp == "": break return lcp if __name__ == "__main__": print(Solution().longestCommonPrefix(["aaa","aa","aaa"]))<file_sep>import time class Solution(object): def jump(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 1: return 0 i = 1 last_arrive = set() last_arrive.add(0) left = list(range(1, len(nums))) while True: cur_arrive = set() for ele in last_arrive: rem = list() for tmp in left: if tmp <= ele + nums[ele]: cur_arrive.add(tmp) rem.append(tmp) # cur_arrive.add(ele + 1 + step) if tmp == len(nums) - 1: return i else: break for ele in rem: left.remove(ele) last_arrive = cur_arrive i += 1 if __name__ == "__main__": bt = time.time() sol = Solution() c = [1] * 100000 print(sol.jump(c)) et = time.time() print(et - bt) <file_sep>class Solution(object): def shortestToChar(self, S, C): """ :type S: str :type C: str :rtype: List[int] """ # 第一种解法,先找个每个C,然后分别计算每个字符到每个C的距离,取最小值 # C_position = [] # # for i, e in enumerate(S): # if e == C: # C_position.append(i) # # return [min(abs(i - s) for s in C_position) for i, e in enumerate(S)] # 第二种解法,双向扫描 if __name__ == "__main__": sol = Solution() print(sol.shortestToChar("loveleetcode" , "e")) <file_sep>class Solution(object): saved = set() def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ def hash(l): res = "" for ele in l: res += str(ele) + "_" return res[:-1] def dehash(h): return [int(k) for k in h.split("_")] def subf(num): if len(num) == 0: return [] if len(num) == 1: return [str(num[0])] res = set() for k in range(len(num)): left = num[:k] + num[k + 1:] for re in subf(left): res.add(str(num[k]) + "_" + re) return res return [dehash(s) for s in subf(nums)] if __name__ == "__main__": sol = Solution() print(sol.permute([-1, 2])) <file_sep>class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ cache = dict() def match(s, p): sp_id = "%s_%s" % (s, p) if sp_id in cache.keys(): return cache[sp_id] # s == 0 的情况 if len(s) == 0: for e in p: if e != "*": cache[sp_id] = False return False cache[sp_id] = True return True i = 0 j = 0 while i < len(p) and j < len(s): if p[i] == "*": i += 1 while i < len(p) and p[i] == "*": i += 1 if i == len(p): cache[sp_id] = True return True while j < len(s): if s[j] == p[i] or p[i] == "?": if match(s[j:], p[i:]): cache[sp_id] = True return True j += 1 elif p[i] == "?": i += 1 j += 1 else: if s[j] == p[i]: j += 1 i += 1 else: cache[sp_id] = False return False if i == len(p) and j == len(s): cache[sp_id] = True return True elif i < len(p) and j == len(s): for e in p[i:]: if e != "*": cache[sp_id] = False return False cache[sp_id] = True return True else: cache[sp_id] = False return False return match(s, p) if __name__ == "__main__": print(Solution().isMatch("aa", "*")) <file_sep>class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ def correct(s1, s2): if s1 == "{": return True if s2 == "}" else False if s1 == "(": return True if s2 == ")" else False if s1 == "[": return True if s2 == "]" else False return False if len(s) == 0: return True elif len(s) % 2 == 1: return False else: # i, j = int(len(s) / 2 - 1), int(len(s) / 2) # while i >= 0: # if not correct(s[i], s[j]): # return False # i, j = i - 1, j + 1 # return True bef = [] for c in s: if c in ["{", "(", "["]: bef.append(c) else: if len(bef) == 0: return False if correct(bef[-1], c): bef = bef[:-1] else: return False return True if len(bef) == 0 else False if __name__ == "__main__": print(Solution().isValid("[([]])")) <file_sep>class Solution(object): def get_candidate_times(self, candidates, target): res = dict() for e in candidates: if e in res.keys(): res[e] += 1 else: res.setdefault(e, 1) can, tim = [], [] for key, value in res.items(): if key <= target: can.append(key) tim.append(value) return can, tim def combinationSum2(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ if target == 0: return [] candidates, times = self.get_candidate_times(candidates, target) if len(candidates) < 1: return [] def get_combination(sets, tar): if len(sets) == 1: if int(tar / sets[0]) <= times[0]: return [[sets[0]] * int(tar / sets[0])] if tar % sets[0] == 0 else [] else: return [] else: res = [] cur = 0 while cur * sets[-1] <= tar and cur <= times[len(sets) - 1]: tmp = get_combination(sets[:-1], tar - cur * sets[-1]) if len(tmp) > 0: for t in tmp: res.append(t + [sets[-1]] * cur) cur += 1 return res return get_combination(candidates, target) if __name__ == "__main__": print(Solution().combinationSum2([2], 1)) <file_sep>class Solution(object): def threeSum(self, nums, target): """ :type nums: List[int] :rtype: List[List[int]] """ fb = sorted(nums) result = [] for i in range(len(fb) - 2): if i >= 1 and fb[i] == fb[i - 1]: continue begin, end = i + 1, len(fb) - 1 while begin < end: s = fb[i] + fb[begin] + fb[end] if s > target: end -= 1 elif s < target: begin += 1 else: result.append([fb[i], fb[begin], fb[end]]) while begin < end and fb[begin + 1] == fb[begin]: begin += 1 while end > begin and fb[end] == fb[end - 1]: end -= 1 begin += 1 end -= 1 return result def fourSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[List[int]] """ fb = sorted(nums) result = [] for i in range(len(fb) - 3): if i >= 1 and fb[i] == fb[i - 1]: continue result += [[fb[i]] + k for k in self.threeSum(fb[i+1:], target-fb[i])] return result if __name__ == "__main__": print(Solution().fourSum([0,0,0,0], 1)) <file_sep># Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ a = head nList = [head] length = 1 while head.next is not None: length += 1 nList.append(head.next) if len(nList) >= n + 1: nList = nList[len(nList) - n - 1:] head = head.next if n == length: return a.next if nList[0].next is not None: if nList[0].next.next is not None: nList[0].next = nList[0].next.next else: nList[0].next = None return a else: return None def printListNode(head): if head is None: print("None") return while head.next is not None: print(head.val) head = head.next print(head.val) def create(NodeList): last = ListNode(NodeList[0]) a = last for i in NodeList[1:]: tmp = ListNode(i) last.next = tmp last = tmp return a if __name__ == "__main__": a = create([1,2]) printListNode(a) printListNode(Solution().removeNthFromEnd(a, 2)) <file_sep>class Solution(object): def copy(self, poss): res = [] for row in poss: res_row = [] for e in row: res_row.append(list(e) if isinstance(e, list) else e) res.append(res_row) return res def check_bug(self, poss): for i in range(9): for j in range(9): if isinstance(poss[i][j], list) and len(poss[i][j]) == 0: return False return True def update(self, poss): flag = True while flag: flag = False for i in range(len(poss)): for j in range(len(poss[i])): # 如果可能性只降到一个 就赋值 if isinstance(poss[i][j], list) and len(poss[i][j]) == 1: poss[i][j] = poss[i][j][0] flag = True # 赋值完后 对可能被影响的其他的区域更新 # row for pos_row in poss[i]: if isinstance(pos_row, list) and poss[i][j] in pos_row: pos_row.remove(poss[i][j]) # column for c in range(9): if isinstance(poss[c][j], list) and poss[i][j] in poss[c][j]: poss[c][j].remove(poss[i][j]) # sub sub_row = range(int(i / 3) * 3, int(i / 3) * 3 + 3) sub_column = range(int(j / 3) * 3, int(j / 3) * 3 + 3) for sub_i in sub_row: for sub_j in sub_column: if isinstance(poss[sub_i][sub_j], list) and \ poss[i][j] in poss[sub_i][sub_j]: poss[sub_i][sub_j].remove(poss[i][j]) for i in range(9): for j in range(9): if isinstance(poss[i][j], list) and len(poss[i][j]) == 0: return False return True def check_void(self, poss): for i in range(len(poss)): for j in range(len(poss[i])): if len(poss[i][j]) != 1: return False return True def assumption(self, poss): for i in range(len(poss)): for j in range(len(poss[i])): if len(poss[i][j]) == 2: tmp = poss[i][j][1] poss[i][j] = poss[i][j][0] return [i, j, tmp, poss[i][j]] return False def cover(self, poss, board): for i in range(9): board[i] = ''.join(poss[i]) def solveSudoku(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ columes = [] subs = [] for i in range(9): column = [row[i] for row in board] columes.append(column) for i in range(3): for j in range(3): sub = board[i * 3][j * 3:(j + 1) * 3] + board[i * 3 + 1][j * 3:(j + 1) * 3] + board[i * 3 + 2][ j * 3:(j + 1) * 3] subs.append(sub) possibility = [] for i in range(9): prob_row = [] for j in range(9): if board[i][j] == ".": prob_row.append([str(e) for e in range(1, 10) if str(e) not in list(board[i])]) else: prob_row.append(board[i][j]) possibility.append(prob_row) for i in range(9): for j in range(9): if columes[i][j] == ".": possibility[j][i] = [e for e in possibility[j][i] if e not in list(columes[i])] for i in range(9): for j in range(9): if subs[i][j] == ".": rown = int(int(i / 3) * 3 + j / 3) columnn = int(i % 3 * 3 + j % 3) possibility[rown][columnn] = [e for e in possibility[rown][columnn] if e not in list(subs[i])] # print_prob(possibility) self.update(possibility) print("第一次消歧后") # print_prob(possibility) if self.check_void(possibility): self.cover(possibility, board) return stack = [] stack_prob = [] copy = self.copy(possibility) while True: res = self.assumption(copy) backup = self.copy(copy) if isinstance(res, list): stack.append(res) stack_prob.append(backup) if not self.update(copy): # 消除假设 while not self.check_bug(copy): if len(stack) <= 0: break tmp = stack[-1] copy = stack_prob[-1] copy[tmp[0]][tmp[1]] = tmp[2] # for mid in stack[:-1]: # copy[mid[0]][mid[1]] = mid[3] # self.update(copy) stack = stack[:-1] stack_prob = stack_prob[:-1] self.update(copy) # print_prob(copy) if self.check_void(copy): self.cover(copy, board) return else: # 判断是否成功 if self.check_void(copy): self.cover(copy, board) return else: tmp = stack[-1] copy = self.copy(possibility) copy[tmp[0]][tmp[1]] = tmp[2] # print_prob(copy) self.update(copy) stack = [] if self.check_void(copy): self.cover(copy, board) return def printSudoku(board): for row in board: print(' '.join(row)) print("\n") def print_prob(poss): for row in poss: tmp = [] for ele in row: if len(ele) == 1: tmp.append(ele[0]) else: tmp.append('.') print(' '.join(tmp)) print('\n') if __name__ == "__main__": board = [".....7..9",".4..812..","...9...1.","..53...72","293....5.",".....53..","8...23...","7...5..4.","531.7...."] printSudoku(board) Solution().solveSudoku(board) print("最终结果") printSudoku(board) <file_sep>import time class Solution(object): times = 0 cache = dict() def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ sp_id = "%s_%s" % (s, p) if sp_id in self.cache.keys(): self.times += 1 return self.cache[sp_id] # s == 0 的情况 if len(s) == 0: for e in p: if e != "*": self.cache[sp_id] = False return False self.cache[sp_id] = True return True i = 0 j = 0 while i < len(p) and j < len(s): if p[i] == "*": i += 1 while i < len(p) and p[i] == "*": i += 1 if i == len(p): self.cache[sp_id] = True return True while j < len(s): if s[j] == p[i] or p[i] == "?": if self.isMatch(s[j:], p[i:]): self.cache[sp_id] = True return True j += 1 elif p[i] == "?": i += 1 j += 1 else: if s[j] == p[i]: j += 1 i += 1 else: self.cache[sp_id] = False return False if i == len(p) and j == len(s): self.cache[sp_id] = True return True elif i < len(p) and j == len(s): for e in p[i:]: if e != "*": self.cache[sp_id] = False return False self.cache[sp_id] = True return True else: self.cache[sp_id] = False return False if __name__ == "__main__": sol = Solution() bt = time.time() print(sol.isMatch( "abbbabaaabbabbabbabaabbbaabaaaabbbabaaabbbbbaaababbb", "**a*b*aa***b***bbb*ba*a")) et = time.time() print(et - bt) print(sol.times) <file_sep>class Solution(object): def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ fb = sorted(nums) cp = fb[0] + fb[1] + fb[2] for i in range(len(fb) - 2): if i >= 1 and fb[i] == fb[i - 1]: continue begin, end = i + 1, len(fb) - 1 while begin < end: s = fb[i] + fb[begin] + fb[end] if s > target: cp = cp if abs(cp - target) < abs(s - target) else s end -= 1 elif s < target: begin += 1 cp = cp if abs(cp - target) < abs(s - target) else s else: return target return cp if __name__ == "__main__": print(Solution().threeSumClosest([-1, 2, 1, -4], 1)) <file_sep>class Solution(object): def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ if len(nums) == 0: return [] if len(nums) == 1: return [nums] res = [] for k in range(len(nums)): left = nums[:k] + nums[k+1:] for re in self.permute(left): res.append([nums[k]] + re) return res if __name__ == "__main__": sol = Solution() print(sol.permute([1,1]))<file_sep>class Solution: def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ saved = dict() def hash(s): return ''.join(sorted(s)) for st in strs: hashed = hash(st) if hashed in saved.keys(): saved[hashed].append(st) else: saved[hashed] = [st] return [v for k, v in saved.items()]
455276bc7975a058b1498d8e16c1d8a00bb32fe6
[ "Python" ]
43
Python
Apeoud/LeetCode
ed0316454218c77e6ccabc4c19e35c825ba9ded8
d6669884ea6a44ffdd9532bbc8d975436aeb195c
refs/heads/main
<repo_name>jcfranco/demo-stencil-watch<file_sep>/repro-case/index.js import { defineCustomElements } from '../dist/custom-elements/index'; defineCustomElements();
8d55e73f010cde6633ff8ba0a8e22587b7832c02
[ "JavaScript" ]
1
JavaScript
jcfranco/demo-stencil-watch
67f9fce7946bf1a226ef3160cddf56c83ceb590d
9ff0475882a1e392789fc70c6a8d358dcdcf7ba8
refs/heads/master
<repo_name>amroahmed90/joda-care<file_sep>/src/layouts/SignedOutLayout.js import React from "react"; import { Component } from "react"; import NavBar from "../components/NavBar"; import SignInForm from "../components/SigInForm"; import SignOutForm from "../components/SignOutForm"; import axios from "axios"; import MessageBox from "../components/MessageBox"; class SignedOutLayout extends Component { state = { isSignedIn: false, isClicked: false }; verifyUser = event => { event.preventDefault(); const username = event.target.elements.username.value; const password = event.target.elements.password.value; localStorage.setItem("username", username); localStorage.setItem("password", password); axios({ method: "POST", url: "https://jodacare-assignment.herokuapp.com/api/authenticate", data: { username: username, password: <PASSWORD> }, header: "content-type: application/jason" }) .then(response => { localStorage.setItem("token", response.data.token); this.setState({ isSignedIn: true }); this.setState({ isClicked: false }); }) .catch(() => { this.setState({ isClicked: true }); }); }; signOut = () => { this.setState({ isSignedIn: false }); localStorage.removeItem("username"); localStorage.removeItem("password"); localStorage.removeItem("token"); }; render() { if (!this.state.isSignedIn && !this.state.isClicked) { return ( <div> <NavBar /> <SignInForm verifyUser={this.verifyUser} /> </div> ); } else if (!this.state.isSignedIn && this.state.isClicked) { return ( <div> <NavBar /> <SignInForm verifyUser={this.verifyUser} /> <p id="incorrect-input">Username or password do not match!</p> </div> ); } else { return ( <div> <NavBar /> <SignOutForm signOut={this.signOut} /> <MessageBox /> </div> ); } } } export default SignedOutLayout; <file_sep>/src/components/SignOutForm.js import React from "react"; const SignOutForm = props => { const username = localStorage.getItem("username"); const usernamewelcome = username ? username.split("@")[0] : ""; return ( <div id="sign-out"> <h3>Hello, {usernamewelcome}!</h3> <button onClick={props.signOut} className="btn btn-secondary"> Sign Out </button> </div> ); }; export default SignOutForm;
59137e9b6786a4df01da6716d4822ab767038598
[ "JavaScript" ]
2
JavaScript
amroahmed90/joda-care
966ab71585a46e968355af61c0413ddc017b4a54
9c34a11543c873e545bb14ba21b470b31bfefafc
refs/heads/master
<repo_name>Juanpablo02/super6pm<file_sep>/index.php <?php $producto1='arroz'; $producto2='huevos'; $producto3='panela'; $producto4='cafe'; $producto5='cerveza'; $producto6='pastas'; $producto7='aceite'; $producto8='sal'; $producto9='carne'; $producto10='papas'; $precio1=5600; $precio2=10000; $precio3=5000; $precio4=3800; $precio5=20000; $precio6=4000; $precio7=6500; $precio8=2300; $precio9=15000; $precio10=4000; $total=$precio1+$precio2+$precio3+$precio4+$precio5+$precio6+$precio7+$precio8+$precio9+$precio10; //echo('El total es de: '.$total); if($total <= 80000){ echo('Gracias por su compra :D'); } else { echo('Usted debe de pedir un fiado'); } ?>
79681cb479a40fa1a1ac52ca86dc9ffa9392ad63
[ "PHP" ]
1
PHP
Juanpablo02/super6pm
73b4a946c29b0f0f6b23cdadbfa0b00a19283a97
7620cdae4ca6589e09a15babd6df6ee121629eb1
refs/heads/master
<file_sep>// show sidebar on scroll sidebar = $("aside").fadeTo(0, 0); $(window).scroll(function(d,h) { sidebar.each(function(i) { a = $(this).offset().top + $(this).height(); b = $(window).scrollTop() + $(window).height(); if (a < b) $(this).fadeTo(600,1); }); }) // SMOOTH SCROLLING $(document).on('click', 'a[href^="#"]', function(e) { var id = $(this).attr('href'); var $id = $(id); if ($id.length === 0) { return; } e.preventDefault(); // top position relative to the document. offset by menu height var pos = $id.offset().top - 64; $('body, html').animate({scrollTop: pos}); }); // // Progress reading ticker jQuery(document).ready(function($){ var articlesWrapper = $('.cd-articles'); if( articlesWrapper.length > 0 ) { // cache jQuery objects var windowHeight = $(window).height(), articles = articlesWrapper.find('article'), nav = $('.menu'), articleSidebarLinks = nav.find('li'); // initialize variables var scrolling = false, sidebarAnimation = false, resizing = false, mq = checkMQ(), windowWidth = $(window).width(), svgCircleLength = parseInt(Math.PI*(articleSidebarLinks.eq(0).find('circle').attr('r')*2)); // check media query and bind corresponding events // if( mq == 'desktop' ) { if( windowWidth > 1100) { $(window).on('scroll', checkRead); $(window).on('scroll', checkSidebar); } $(window).on('resize', resetScroll); updateArticle(); updateSidebarPosition(); nav.on('click', '.menu a', function(event){ event.preventDefault(); var selectedArticle = articles.eq($(this).parent('li').index()), selectedArticleTop = selectedArticle.offset().top - 64; $(window).off('scroll', checkRead); $('body,html').animate( {'scrollTop': selectedArticleTop}, 300, function(){ // console.log("scrollTop: ", selectedArticleTop); checkRead(); $(window).on('scroll', checkRead); } ); }); } function checkRead() { // console.log("checkRead"); if( !scrolling ) { scrolling = true; (!window.requestAnimationFrame) ? setTimeout(updateArticle, 300) : window.requestAnimationFrame(updateArticle); } } function checkSidebar() { if( !sidebarAnimation ) { sidebarAnimation = true; (!window.requestAnimationFrame) ? setTimeout(updateSidebarPosition, 300) : window.requestAnimationFrame(updateSidebarPosition); } } function resetScroll() { if( !resizing ) { resizing = true; (!window.requestAnimationFrame) ? setTimeout(updateParams, 300) : window.requestAnimationFrame(updateParams); } } function updateParams() { windowHeight = $(window).height(); mq = checkMQ(); $(window).off('scroll', checkRead); $(window).off('scroll', checkSidebar); // if( mq == 'desktop') { if( windowWidth > 1100) { $(window).on('scroll', checkRead); $(window).on('scroll', checkSidebar); } resizing = false; } function updateArticle() { var scrollTop = $(window).scrollTop(); // console.log("updateArticle", scrollTop); articles.each(function(){ var article = $(this), // articleTop has to be offset 1 extra px so clicking on the link makes it active articleTop = article.offset().top - 65, articleHeight = article.outerHeight(), articleSidebarLink = articleSidebarLinks.eq(article.index()).children('a'); if( article.is(':last-of-type') ) articleHeight = articleHeight - windowHeight; // console.log(articleTop, scrollTop); if( articleTop > scrollTop) { articleSidebarLink.removeClass('read reading'); } else if( scrollTop >= articleTop && articleTop + articleHeight > scrollTop) { var dashoffsetValue = svgCircleLength*( 1 - (scrollTop - articleTop)/articleHeight); articleSidebarLink.addClass('reading').removeClass('read').find('circle').attr({ 'stroke-dashoffset': dashoffsetValue }); changeUrl(articleSidebarLink.attr('href')); } else { articleSidebarLink.removeClass('reading').addClass('read'); } }); scrolling = false; } function updateSidebarPosition() { // console.log("updateSidebarPosition"); var articlesWrapperTop = articlesWrapper.offset().top, articlesWrapperHeight = articlesWrapper.outerHeight(), scrollTop = $(window).scrollTop(); // console.log(articlesWrapperTop, articlesWrapperHeight, scrollTop); if( scrollTop < articlesWrapperTop) { nav.removeClass('fixed').attr('style', ''); } else if( scrollTop >= articlesWrapperTop && scrollTop < articlesWrapperTop + articlesWrapperHeight - windowHeight) { nav.addClass('fixed').attr('style', ''); } else { var articlePaddingTop = Number(articles.eq(1).css('padding-top').replace('px', '')); if( nav.hasClass('fixed') ) nav.removeClass('fixed').css('top', articlesWrapperHeight + articlePaddingTop - windowHeight + 'px'); } sidebarAnimation = false; } function changeUrl(link) { var pageArray = location.pathname.split('/'), actualPage = pageArray[pageArray.length - 1] ; if( actualPage != link && history.pushState ) window.history.pushState({path: link},'',link); } function checkMQ() { return window.getComputedStyle(articlesWrapper.get(0), '::before').getPropertyValue('content').replace(/'/g, "").replace(/"/g, ""); } });
878aadd77710c7d209f505c63ea51224f0731ad5
[ "JavaScript" ]
1
JavaScript
jennyfan/datavoids
08ac88b79ef7d993ea61a059d56bcd69e48b23d5
2e55ab4de3ce555e6bac187c9de1c6f7cdb3cec8
refs/heads/master
<repo_name>takseki/mayoi<file_sep>/mayoi.cpp #include <iostream> #include <vector> using std::cin; using std::cout; using std::endl; using std::vector; // 進行方向 enum Dir { POS = 0, // A(X)->B->C の方向 NEG, // 逆方向 }; class Solver { public: Solver() {} public: /** 動的計画法による探索 p(n, dir) : B から出発して、反転 n 回以内の経路数とする. dir は方向の初期状態. 初期値4つの漸化式で表せる。 p(0, +) = 0, p(0, -) = 1, p(1, +) = 2, p(1, -) = 1 p(n, +) = p(n-1, -) + p(n-2, +) + 1 (ただし n >= 2) p(n, -) = p(n-1, +) + p(n-2, -) + 1 (ただし n >= 2) 以下のように n の小さい方から計算していく. p(2, +) = p(1, -) + p(0, +) + 1 = 1 + 0 + 1 = 2 p(2, -) = p(1, +) + p(0, -) + 1 = 2 + 1 + 1 = 4 p(3, +) = p(2, -) + p(1, +) + 1 = 4 + 2 + 1 = 7 p(3, -) = p(2, +) + p(1, -) + 1 = 2 + 1 + 1 = 4 なお、 p(1, +) = p(2, +), p(3, +) = p(4, +), ... p(0, -) = p(1, -), p(2, -) = p(3, -), ... のような性質があることも使えるが、大差ないと思われるのでやっていない。 */ unsigned long long solve(int n) { if (n == 0) { return 0; } else if (n == 1) { return 2; } else { vector<vector<unsigned long long> > dp_table(n, vector<unsigned long long>(2)); dp_table[0][POS] = 0; dp_table[0][NEG] = 1; dp_table[1][POS] = 2; dp_table[1][NEG] = 1; for (int i = 2; i < n; i++) { dp_table[i][POS] = dp_table[i - 1][NEG] + dp_table[i - 2][POS] + 1; dp_table[i][NEG] = dp_table[i - 1][POS] + dp_table[i - 2][NEG] + 1; } return dp_table[n - 1][NEG] + dp_table[n - 2][POS] + 1; } } }; /** マヨイドーロ問題. 標準入力から N を入力し、標準出力に P を出力する. */ int main() { // 与えられた N に対して P を求める int n; cin >> n; Solver solver; unsigned long long p = solver.solve(n); cout << p << endl; } <file_sep>/mayoi.rb class Solver POS = 0 NEG = 1 # 動的計画法による探索 # p(n, dir) : B から出発して、反転 n 回以内の経路数とする. dir は方向の初期状態. # 初期値4つの漸化式で表せる. # p(0, +) = 0, p(0, -) = 1, p(1, +) = 2, p(1, -) = 1 # p(n, +) = p(n-1, -) + p(n-2, +) + 1 (ただし n >= 2) # p(n, -) = p(n-1, +) + p(n-2, -) + 1 (ただし n >= 2) # 以下のように n の小さい方から計算していく. # p(2, +) = p(1, -) + p(0, +) + 1 = 1 + 0 + 1 = 2 # p(2, -) = p(1, +) + p(0, -) + 1 = 2 + 1 + 1 = 4 # p(3, +) = p(2, -) + p(1, +) + 1 = 4 + 2 + 1 = 7 # p(3, -) = p(2, +) + p(1, -) + 1 = 2 + 1 + 1 = 4 def solve(n) if n == 0 return 0 elsif n == 1 return 2 else # Ruby の多次元配列の生成の仕方に注意! dp_table = Array.new(n).map{ Array.new(2, 0) } dp_table[0][POS] = 0 dp_table[0][NEG] = 1 dp_table[1][POS] = 2 dp_table[1][NEG] = 1 for i in 2..n - 1 dp_table[i][POS] = dp_table[i - 1][NEG] + dp_table[i - 2][POS] + 1 dp_table[i][NEG] = dp_table[i - 1][POS] + dp_table[i - 2][NEG] + 1 end return dp_table[n - 1][NEG] + dp_table[n - 2][POS] + 1 end end end # マヨイドーロ問題. # 標準入力から N を入力し、標準出力に P を出力する. str = gets n = str.to_i solver = Solver.new p = solver.solve(n) puts p <file_sep>/README.md # README # ### What is this repository for? ### * 2015年12月 結城浩 マヨイドーロ問題 https://codeiq.jp/q/2549
55c31b99de76ac51f3e8c665dd31ea8f6ae96f33
[ "Markdown", "Ruby", "C++" ]
3
C++
takseki/mayoi
931f48e9bd0313475856e99d8a87f9d47277cf3c
ebc46f51dcc5c51b8f62b7b7eb380f31b0a26632
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KBSRules { class ActionSet { public Transition tran; public List<ActionSet> branches; public ActionSet(Transition tran) { this.tran = tran; branches = new List<ActionSet>(); } } } <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; namespace KBSRules { public partial class ActionRulesDisplay : Form { List<String> res; Transition dec; public ActionRulesDisplay() { InitializeComponent(); } private void ActionRulesDisplay_Load(object sender, EventArgs e) { } internal void loadResultData(List<String> res, Transition dec) { this.res = res; this.dec = dec; tb_results.Text = ""; foreach(String result in res) { tb_results.Text += result+"\r\n"; } } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KBSRules { class RuleGenerator { #region Class Attributes public DataTable table { get; set; } public String[] header { get; set; } public Transition decision { get; set; } public double supp { get; set; } public double conf { get; set; } public double tsup, tconf; public Dictionary<String, List<Transition>> atomics; public List<String> keys; public Dictionary<Transition, ActionSet> trie; public List<String> finalResult; public static String flex = "Flexible"; public static String stab = "Stable"; public static String excl = "Exclude"; public static String dec = "Decision"; public static String noTran = "NoTransition"; #endregion public RuleGenerator() { atomics = new Dictionary<string,List<Transition>>(); keys = new List<string>(); trie = new Dictionary<Transition, ActionSet>(); finalResult = new List<string>(); supp = conf = tsup = tconf = 0.0; } public DataTable fetchRawData(StreamReader reader) { String line = ""; table = new DataTable(); using (reader) { if (!(line = reader.ReadLine()).Equals(null)) { header = line.Split(','); foreach (String head in header) { table.Columns.Add(head, typeof(String)); } while ((line = reader.ReadLine()) != null) { DataRow nextRow = table.NewRow(); String[] splitLine = line.Split(','); for (int i = 0; i < header.Length; i++) { nextRow[header[i]] = splitLine[i]; } table.Rows.Add(nextRow); } } } return table; } public void generateAtomics(Dictionary<String, List<String>> types) { Dictionary<String, List<String>> elements = new Dictionary<string,List<String>>(); //getting the distinct elements in each column foreach(String str in header) { elements.Add(str, (from DataRow dr in table.Rows select (string)dr[str]).Distinct().ToList<String>()); } //generating the atomic action sets foreach(String key in types.Keys) { foreach(String attr in types[key]) { List<Transition> atom = new List<Transition>(); if(key == flex) foreach(String el in elements[attr]) foreach (String els in elements[attr]) { Transition t = new Transition(attr, el, els); List<Transition> temp = new List<Transition>(); temp.Add(t); checkSuppConf(temp); if (tsup >= supp) { atom.Add(t); if(tconf >= conf) { String res = generateResult(temp, tsup, tconf); if (res != noTran) finalResult.Add(res); } } } else if(key == stab) foreach (String el in elements[attr]) { Transition t = new Transition(attr, el, el); List<Transition> temp = new List<Transition>(); temp.Add(t); checkSuppConf(temp); if (tsup >= supp) { atom.Add(t); } } if(atom.Count>0) atomics.Add(attr, atom); } } //storing the sorted list of keys keys = atomics.Keys.ToList<String>(); keys.Sort(); //Seeding the actionset generator with atomics foreach(String key in keys) { foreach(Transition t in atomics[key]) { ActionSet axn = new ActionSet(t); List<Transition> seq = new List<Transition>(); seq.Add(t); trie.Add(t, findActionSets(axn, seq)); } } } public ActionSet findActionSets(ActionSet axn, List<Transition> seq) { //following code runs for internal nodes if (axn.branches.Count > 0) { for (int i = 0; i < axn.branches.Count; i++) { seq.Add(axn.branches[i].tran); axn.branches[i] = findActionSets(axn.branches[i], seq); } return axn; } else { //following code runs for leaf nodes int index = keys.IndexOf(axn.tran.beacon) + 1; for (int i = index; i < keys.Count(); i++) { foreach (Transition t in atomics[keys[i]]) { seq.Add(t); checkSuppConf(seq); if (tsup >= supp) { if (tconf >= conf) { String res = generateResult(seq, tsup, tconf); if (res != noTran) finalResult.Add(res); } axn.branches.Add(new ActionSet(t)); } seq.RemoveAt(seq.Count - 1); } } if ((index + 1) < keys.Count) return findActionSets(axn, seq); return axn; } } public void checkSuppConf(List<Transition> seq) { double lhsPre = 0, lhsPost = 0, preCount = 0, postCount = 0; List<DataRow> pre = (from DataRow dr in table.Rows select dr).ToList<DataRow>(); List<DataRow> post = (from DataRow dr in table.Rows select dr).ToList<DataRow>(); foreach(Transition tran in seq) { pre = (pre.Where(dr => (string)dr[tran.beacon] == tran.from)).ToList<DataRow>(); post = (post.Where(dr => (string)dr[tran.beacon] == tran.to)).ToList<DataRow>(); } lhsPre = pre.Count(); lhsPost = post.Count(); pre = (pre.Where(dr => (string)dr[decision.beacon] == decision.from)).ToList<DataRow>(); post = (post.Where(dr => (string)dr[decision.beacon] == decision.to)).ToList<DataRow>(); preCount = pre.Count(); postCount = post.Count(); tsup = Math.Min(preCount, postCount); tconf = 100 * ((preCount / lhsPre)*(postCount / lhsPost)); //if (tsup >= supp && tconf >= conf) // return true; //else // return false; } public String generateResult(List<Transition> seq, double sup, double conf) { StringBuilder sb = new StringBuilder(); int count = 0; foreach(Transition tr in seq) { if (tr.from == tr.to) count++; sb.Append(tr.ToString()); } if (count == seq.Count) return noTran; sb.Append(" => "+decision.ToString()); sb.Append("; Support: "+sup+"; confidence: "+conf); return sb.ToString(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KBSRules { class Transition { public String beacon, from, to; public Transition(String beacon, String from, String to) { this.beacon = beacon; this.from = from; this.to = to; } public override string ToString() { return "("+beacon+","+from+"->"+to+")"; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace KBSRules { public partial class Form1 : Form { DataTable table; RuleGenerator generator; public static int decNum=0; public static String decision = "Decision"; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void btn_broswe_Click(object sender, EventArgs e) { StreamReader myStream = null; generator = new RuleGenerator(); OpenFileDialog openFileDialog1 = new OpenFileDialog(); //Displaying a browse dialog for selecting the file openFileDialog1.InitialDirectory = "c:\\"; //openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; openFileDialog1.FilterIndex = 2; openFileDialog1.RestoreDirectory = true; if (openFileDialog1.ShowDialog() == DialogResult.OK) { try { if ((myStream = new StreamReader(openFileDialog1.OpenFile())) != null) { txt_path.Text = openFileDialog1.FileName.ToString(); using (myStream) { table = generator.fetchRawData(myStream); } gv_Data.DataSource = table; gv_Data.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; } gv_Attributes.Columns.Add("typ", "Type"); gv_Attributes.Columns.Add("atr", "Attribute"); gv_Attributes.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(gv_Attributes_EditingControlShowing); for (int i = 0; i < table.Columns.Count; i++) { DataGridViewComboBoxCell comboCell = new DataGridViewComboBoxCell(); comboCell.DataSource = new List<String> { "Stable", "Flexible", "Decision", "Exclude" }; gv_Attributes.Rows.Add(new DataGridViewRow()); gv_Attributes.Rows[i].Cells[0] = comboCell; gv_Attributes.Rows[i].Cells[1].Value = table.Columns[i].ColumnName;//header[i]; } gv_Attributes.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; } catch (Exception ex) { MessageBox.Show("Error: Could not read file from disk.\nOriginal error: " + ex.Message); } } } private void gv_Attributes_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { ComboBox combo = e.Control as ComboBox; if (combo != null) { combo.SelectedIndexChanged -= new EventHandler(ComboBox_SelectedIndexChanged); combo.SelectedIndexChanged += new EventHandler(ComboBox_SelectedIndexChanged); } } private void ComboBox_SelectedIndexChanged(object sender, EventArgs e) { var comboBox = (DataGridViewComboBoxEditingControl)sender; int colNum = comboBox.EditingControlRowIndex; String tstr = ""; string item = comboBox.Text; List<String> comboSource = new List<String>(); if (item == "Decision") { decNum = colNum; for (int i = 0; i < gv_Attributes.Rows.Count; i++) { if (i != colNum) { DataGridViewComboBoxCell tcell = (DataGridViewComboBoxCell)gv_Attributes.Rows[i].Cells[0]; if (tcell.Value == null) tstr = ""; else tstr = (tcell.Value.ToString()); if (!(tstr == "Decision")) { tcell.DataSource = new List<String> { "Stable", "Flexible", "Exclude" }; tcell.Value = tstr; } } } for (int i = 0; i < table.Rows.Count; i++) { if (!(comboSource.Contains(table.Rows[i][colNum]))) comboSource.Add(table.Rows[i][colNum].ToString()); } comboBox1.DataSource = comboSource; comboBox2.DataSource = new List<String>(comboSource); } else if(colNum == decNum) { for (int i = 0; i < gv_Attributes.Rows.Count; i++) { if (i != colNum) { DataGridViewComboBoxCell tcell = (DataGridViewComboBoxCell)gv_Attributes.Rows[i].Cells[0]; if (tcell.Value == null) tstr = ""; else tstr = (tcell.Value.ToString()); if (!(tstr == "Decision")) { tcell.DataSource = new List<String> { "Stable", "Flexible", "Decision", "Exclude" }; tcell.Value = tstr; } } } comboBox1.DataSource = null; comboBox1.SelectedText = ""; comboBox2.DataSource = null; comboBox2.SelectedText = ""; } } private void btn_Generate_Click(object sender, EventArgs e) { int flag = 0; for (int i = 0; i < gv_Attributes.Rows.Count; i++) { if (((DataGridViewComboBoxCell)(gv_Attributes.Rows[i].Cells[0])).Value == null) { flag = 1; break; } } if(comboBox1.SelectedValue!=null && comboBox2.SelectedValue!=null && nud_Support.Value>0 && nud_Confidence.Value>0 && flag == 0) { Dictionary<String, List<String>> types = new Dictionary<string, List<string>>(); ActionRulesDisplay resDisp; String decBeacon = ""; foreach(DataGridViewRow row in gv_Attributes.Rows) { String key = row.Cells[0].Value.ToString(); String val = row.Cells[1].Value.ToString().Trim(); List<String> temp = new List<String>(); if(key == decision) decBeacon = val; if (types.ContainsKey(key)) { temp = types[key]; types.Remove(key); } temp.Add(val); types.Add(key, temp); } generator.decision = new Transition(decBeacon,comboBox1.SelectedValue.ToString(),comboBox2.SelectedValue.ToString()); generator.supp = Convert.ToDouble(nud_Support.Value); generator.conf = Convert.ToDouble(nud_Confidence.Value); generator.generateAtomics(types); resDisp = new ActionRulesDisplay(); resDisp.loadResultData(generator.finalResult, generator.decision); resDisp.Show(); } else { MessageBox.Show("Kindly make valid selections and try again."); } } } }
86af9d5c4d995c51606583f00a153af522a37a4c
[ "C#" ]
5
C#
kaguduru/Association-Action-Rules-in-.NET
f2538e2728626021be8dcf80866e9ba8d0148c71
55b70d922e5aa9d26df18d1ce0d479e014fc4ec1
refs/heads/main
<file_sep># HW1_Image-Classification step 0. 解壓縮檔案train_col_hist.part01~train_col_hist.part04 \ step 1. 至「# In[] Train model」區塊,修改訓練模型超參數(batch_size、learning_rate、num_epochs),完成模型訓練設定 \ step 2. 執行LinearClassfication.py即可訓練模型並查看相關結果 <file_sep># -*- coding: utf-8 -*- """ Created on Mon Mar 22 09:03:43 2021 @author: JerryDai """ # In[] import package import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader, TensorDataset import numpy as np import pandas as pd import matplotlib.pyplot as plt import cv2 # In[] Build model def run_gradient_descent(model, batch_size=64, learning_rate=0.01, weight_decay=0, num_epochs=10): criterion = nn.CrossEntropyLoss() # optimizer = optim.SGD(model.parameters(), lr=learning_rate, weight_decay=weight_decay) optimizer = optim.Adam(model.parameters(), lr=learning_rate, weight_decay=weight_decay) iters, losses = [], [] iters_sub, train_acc, val_acc, test_acc, train_acc_top5, val_acc_top5, test_acc_top5 = [], [], [], [], [], [], [] train_loader = DataLoader(train_data, batch_size=batch_size, shuffle=True) # training n = 0 # the number of iterations for epoch in range(num_epochs): for xs, ts in iter(train_loader): if len(ts) != batch_size: continue zs = model(xs) ts = torch.tensor(ts, dtype=torch.long) loss = criterion(zs, ts) # compute the total loss loss.backward() # compute updates for each parameter optimizer.step() # make the updates for each parameter optimizer.zero_grad() # a clean up step for PyTorch # save the current training information iters.append(n) losses.append(float(loss)/batch_size) # compute *average* loss if n % 10 == 0: print('n:', n) iters_sub.append(n) train_acc.append(get_accuracy_top1(model, train_data)) # train acc top1 val_acc.append(get_accuracy_top1(model, val_data)) # val acc top1 test_acc.append(get_accuracy_top1(model, test_data)) # test acc top1 # train_acc_top5.append(get_accuracy_top5(model, train_data)) # train acc top5 # val_acc_top5.append(get_accuracy_top5(model, val_data)) # val acc top5 # test_acc_top5.append(get_accuracy_top5(model, test_data)) # test acc top5 # increment the iteration number n += 1 print('The Top-1 accuaray of Linear perceptron on training set', np.mean(train_acc)) print('The Top-1 accuaray of Linear perceptron Classifier on validation set', np.mean(val_acc)) print('The Top-1 accuaray of Linear perceptron Classifier on testing set', np.mean(test_acc)) # print('The Top-5 accuaray of Linear perceptron on training set', np.mean(train_acc_top5)) # print('The Top-5 accuaray of Linear perceptron Classifier on validation set', np.mean(val_acc_top5)) # print('The Top-5 accuaray of Linear perceptron Classifier on testing set', np.mean(test_acc_top5)) # plotting plt.figure() plt.title("Training Curve (batch_size={}, lr={})".format(batch_size, learning_rate)) plt.plot(iters, losses, label="Train loss") plt.xlabel("Iterations") plt.ylabel("Loss") plt.show() plt.figure() plt.title("Training Curve (batch_size={}, lr={})".format(batch_size, learning_rate)) plt.plot(iters_sub, train_acc, label="Train") plt.plot(iters_sub, val_acc, label="Validation") plt.xlabel("Iterations") plt.ylabel("Accuracy") plt.legend(loc='best') plt.show() return model def get_accuracy_top1(model, data): loader = torch.utils.data.DataLoader(data, batch_size=500) correct, total = 0, 0 for xs, ts in loader: zs = model(xs) ts = torch.tensor(ts, dtype=torch.long) pred = zs.max(1, keepdim=True)[1] # get the index of the max logit correct += pred.eq(ts.view_as(pred)).sum().item() print('correct:', correct) total += int(ts.shape[0]) return correct / total # def get_accuracy_top5(model, data): # loader = torch.utils.data.DataLoader(data, batch_size=500) # correct, total = 0, 0 # for xs, ts in loader: # zs = model(xs) # ts = torch.tensor(ts, dtype=torch.long) # pred = zs.max(1, keepdim=True)[1] # get the index of the max logit # pred_top5 = torch.topk(zs, 5, dim = 1)[0] # print('pred_top5:', pred_top5) # for i in pred_top5: # if i in ts.view_as(i): # correct += pred.eq(ts.view_as(pred)).sum().item() # print('correct:', correct) # total += int(ts.shape[0]) # return correct / total # In[] Load Data train_path_list = pd.read_csv('train.txt', header = None, sep = ' ', names = ['image_path', 'label']) val_path_list = pd.read_csv('val.txt', header = None, sep = ' ', names = ['image_path', 'label']) test_path_list = pd.read_csv('test.txt', header = None, sep = ' ', names = ['image_path', 'label']) # In[] Exact feature by global color histogram # train_col_hist = np.zeros(768) # for index, tmp_pic_path in enumerate(train_path_list.loc[:, 'image_path']): # print(index) # temp_pic = cv2.imread(tmp_pic_path) # colors = ('b', 'g', 'r') # tmp_hist_array = np.array([]) # for i, col in enumerate(colors): # hist = cv2.calcHist([temp_pic], [i], None, [256], [0, 256]) # hist = hist.flatten() # tmp_hist_array = np.append(tmp_hist_array, hist) # train_col_hist = np.vstack((train_col_hist, tmp_hist_array)) # train_col_hist = np.delete(train_col_hist, 0, axis = 0) # val_col_hist = np.zeros(768) # for index, tmp_pic_path in enumerate(val_path_list.loc[:, 'image_path']): # print(index) # temp_pic = cv2.imread(tmp_pic_path) # colors = ('b', 'g', 'r') # tmp_hist_array = np.array([]) # for i, col in enumerate(colors): # hist = cv2.calcHist([temp_pic], [i], None, [256], [0, 256]) # hist = hist.flatten() # tmp_hist_array = np.append(tmp_hist_array, hist) # val_col_hist = np.vstack((val_col_hist, tmp_hist_array)) # val_col_hist = np.delete(val_col_hist, 0, axis = 0) # test_col_hist = np.zeros(768) # for index, tmp_pic_path in enumerate(test_path_list.loc[:, 'image_path']): # print(index) # temp_pic = cv2.imread(tmp_pic_path) # colors = ('b', 'g', 'r') # tmp_hist_array = np.array([]) # for i, col in enumerate(colors): # hist = cv2.calcHist([temp_pic], [i], None, [256], [0, 256]) # hist = hist.flatten() # tmp_hist_array = np.append(tmp_hist_array, hist) # test_col_hist = np.vstack((test_col_hist, tmp_hist_array)) # test_col_hist = np.delete(test_col_hist, 0, axis = 0) train_col_hist = np.load('train_col_hist.npy') val_col_hist = np.load('val_col_hist.npy') test_col_hist = np.load('test_col_hist.npy') # In[] Map feature and label train_col_hist = torch.tensor(train_col_hist, dtype=torch.float) train_label = torch.tensor(np.array(train_path_list.iloc[:, 1].values), dtype=torch.float) train_data = TensorDataset(train_col_hist, train_label) val_col_hist = torch.tensor(val_col_hist, dtype=torch.float) val_label = torch.tensor(np.array(val_path_list.iloc[:, 1].values), dtype=torch.float) val_data = TensorDataset(val_col_hist, val_label) test_col_hist = torch.tensor(test_col_hist, dtype=torch.float) test_label = torch.tensor(np.array(test_path_list.iloc[:, 1].values), dtype=torch.float) test_data = TensorDataset(test_col_hist, test_label) # In[] Train model model = nn.Linear(768, 50) run_gradient_descent(model, batch_size=256, learning_rate=0.01, num_epochs=10) # In[] RandomForest from sklearn.ensemble import RandomForestClassifier train_X = train_col_hist.numpy() train_Y = train_label.numpy() val_X = val_col_hist.numpy() val_Y = val_label.numpy() test_X = test_col_hist.numpy() test_Y = test_label.numpy() rf_model = RandomForestClassifier(n_estimators = 100) rf_model.fit(train_X, train_Y) print('The accuaray of Random Forest Classifier on training set', rf_model.score(train_X, train_Y)) print('The accuaray of Random Forest Classifier on validation set', rf_model.score(val_X, val_Y)) print('The accuaray of Random Forest Classifier on testing set', rf_model.score(test_X, test_Y)) # In[] XGBoost from xgboost import XGBClassifier params = {'tree_method':'gpu_hist', 'predictor':'gpu_predictor', 'max_depth': 2, 'n_estimators':20, 'learning_rate':0.1, 'early_stopping_rounds':5, 'nthread':6} xgbc = XGBClassifier(**params) xgbc.fit(train_X, train_Y) print('The accuaray of eXtreme Gradient Boosting Classifier on training set', xgbc.score(train_X, train_Y)) print('The accuaray of eXtreme Gradient Boosting Classifier on validation set', xgbc.score(val_X, val_Y)) print('The accuaray of eXtreme Gradient Boosting Classifier on testing set', xgbc.score(test_X, test_Y))
41dbe5c9817f9c87fe25a53c879c6e486b2bfa9b
[ "Markdown", "Python" ]
2
Markdown
jerry88277/HW1_Image-Classification
6ef7a7cfbbdb6da0376424741d37a2c7836de0e3
bbcf2515b4394995da4fa9f59df4a7e736d069d1
refs/heads/master
<repo_name>YkSix/ViewHolder2<file_sep>/library/src/main/java/com/ericluapp/libs/OnRecyclerViewItemClickListener.java package com.ericluapp.libs; import android.view.View; public interface OnRecyclerViewItemClickListener extends View.OnClickListener { /** * @param holder The ViewHolder of the RecyclerView item. * @param position The position in which the item is clicked. */ void onItemClick(ViewHolder holder, int position); /** * Note that the ViewHolder can be got by <code>v.getTag(R.id.tag_viewholder)</code> * or using SimpleOnRecyclerViewItemClickListener#getViewHolder */ @Override void onClick(View v); } <file_sep>/README.md [![API](https://img.shields.io/badge/API-7%2B-blue.svg?style=flat)](https://android-arsenal.com/api?level=7) <img src="https://img.shields.io/badge/method%20count-52-e91e63.svg"></img> <img src="https://img.shields.io/badge/size-7 KB-e91e63.svg"></img> # The last ViewHolder ## Advantages * No need to create custom `RecyclerView.ViewHolder` anymore. * No need to create custom OnItemClickListener anymore, the only interface for click listener is: ```java public interface OnRecyclerViewItemClickListener extends View.OnClickListener { /** * @param holder The ViewHolder of the RecyclerView item. * @param position The position in which the item is clicked. */ void onItemClick(ViewHolder holder, int position); /** * Note that the ViewHolder can be got by <code>v.getTag(R.id.tag_viewholder)</code> * or using SimpleOnRecyclerViewItemClickListener#getViewHolder */ @Override void onClick(View v); } ``` * This may be the last ViewHolder class you would need. ## Download ```gradle dependencies { compile 'com.ericluapp.android.libs:viewholder:1.0.0' } ``` ## Usage ```java // No need to create any custom *ItemClickListener private OnRecyclerViewItemClickListener mListener = new SimpleOnRecyclerViewItemClickListener() { @Override public void onItemClick(ViewHolder holder, int position) { Toast.makeText(MainActivity.this, "click item: " + position, Toast.LENGTH_SHORT) .show(); } @Override public void onClick(View v) { ViewHolder holder = getViewHolder(v); switch (v.getId()) { case R.id.btn_button: { Toast.makeText(MainActivity.this, "click button: " + holder.getAdapterPosition(), Toast.LENGTH_SHORT) .show(); break; } } } }; private static class MyAdapter extends RecyclerView.Adapter<ViewHolder> { private OnRecyclerViewItemClickListener mListener; public MyAdapter(OnRecyclerViewItemClickListener listener) { mListener = listener; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // mListener: the item click listener. return new ViewHolder(R.layout.item_simple, parent, mListener); } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.setText(R.id.btn_button, position + ""); // mListener: the view click listener. holder.setOnClickListener(R.id.btn_button, mListener); // See below section holder.loadUrl(R.id.iv_image, IMAGES[position % IMAGES.length]); } … } ``` If you want to load images from Internet, you can extend this ViewHolder class. This time it is the last custom ViewHolder class you need I promise. ```java public class MyViewHolder extends ViewHolder { … public MyViewHolder loadUrl(@IdRes int viewId, String url) { Glide.with(getContext()) .load(url) .into((ImageView) getView(viewId)); return this; } } ``` ## Blog post [The last ViewHolder you may need][1] ## Screenshot ![](sample/screenshot/viewholder_sample.jpg) ## Description With this library, you no longer need to customize `RecyclerView.ViewHolder` classes or add one-time-use interfaces for click listeners anymore. Customizing `RecyclerView.ViewHolder` classes are extremely common in Android projects. These classes are used for binding views with data. That's right: we're talking about those custom ViewHolder classes where you wind up adding lots of one-time-use variables in a bloated, repetitive and formulaic yet error-prone fashion. Adding these member variables and binding them one time is not so bad. But once written, they continue to burden reviewers and future readers with extra code. The ViewHolder class provides a more elegant way to bind data to `RecyclerView`, with a lot less code and less room for error. Save your time. Save your code. Save your sanity. [1]: https://medium.com/@ericluapp/the-last-viewholder-you-may-need-4e4ce46efcae<file_sep>/library/src/test/java/com/ericluapp/libs/AndroidUnitTest.java package com.ericluapp.libs; import android.app.Activity; import android.app.Application; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; public class AndroidUnitTest { @Test public void dummyUnitTestWithMockito() { Activity activity = mock(Activity.class); assertThat(activity, notNullValue()); Application app = mock(Application.class); when(activity.getApplication()).thenReturn(app); assertThat(app, is(equalTo(activity.getApplication()))); verify(activity).getApplication(); verifyNoMoreInteractions(activity); } }<file_sep>/sample/src/main/java/com/ericluapp/viewholderdemo/MainActivity.java package com.ericluapp.viewholderdemo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.ericluapp.libs.OnRecyclerViewItemClickListener; import com.ericluapp.libs.SimpleOnRecyclerViewItemClickListener; import com.ericluapp.libs.ViewHolder; public class MainActivity extends AppCompatActivity { public static final String[] IMAGES = new String[] { "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg", "https://lh4.googleusercontent.com/--dq8niRp7W4/URquVgmXvgI/AAAAAAAAAbs/-gnuLQfNnBA/s1024/A%252520Song%252520of%252520Ice%252520and%252520Fire.jpg", "https://lh5.googleusercontent.com/-7qZeDtRKFKc/URquWZT1gOI/AAAAAAAAAbs/hqWgteyNXsg/s1024/Another%252520Rockaway%252520Sunset.jpg", "https://lh3.googleusercontent.com/--L0Km39l5J8/URquXHGcdNI/AAAAAAAAAbs/3ZrSJNrSomQ/s1024/Antelope%252520Butte.jpg", "https://lh6.googleusercontent.com/-8HO-4vIFnlw/URquZnsFgtI/AAAAAAAAAbs/WT8jViTF7vw/s1024/Antelope%252520Hallway.jpg", "https://lh4.googleusercontent.com/-WIuWgVcU3Qw/URqubRVcj4I/AAAAAAAAAbs/YvbwgGjwdIQ/s1024/Antelope%252520Walls.jpg", "https://lh6.googleusercontent.com/-UBmLbPELvoQ/URqucCdv0kI/AAAAAAAAAbs/IdNhr2VQoQs/s1024/Apre%2525CC%252580s%252520la%252520Pluie.jpg", "https://lh3.googleusercontent.com/-s-AFpvgSeew/URquc6dF-JI/AAAAAAAAAbs/Mt3xNGRUd68/s1024/Backlit%252520Cloud.jpg", "https://lh5.googleusercontent.com/-bvmif9a9YOQ/URquea3heHI/AAAAAAAAAbs/rcr6wyeQtAo/s1024/Bee%252520and%252520Flower.jpg", "https://lh5.googleusercontent.com/-n7mdm7I7FGs/URqueT_BT-I/AAAAAAAAAbs/9MYmXlmpSAo/s1024/Bonzai%252520Rock%252520Sunset.jpg" }; private RecyclerView mRecyclerView; private MyAdapter mMyAdapter; // No need to create any custom *ItemClickListener private OnRecyclerViewItemClickListener mListener = new SimpleOnRecyclerViewItemClickListener() { @Override public void onItemClick(ViewHolder holder, int position) { Toast.makeText(MainActivity.this, "click item: " + position, Toast.LENGTH_SHORT) .show(); } @Override public void onClick(View v) { ViewHolder holder = getViewHolder(v); switch (v.getId()) { case R.id.btn_button: { Toast.makeText(MainActivity.this, "click button: " + holder.getAdapterPosition(), Toast.LENGTH_SHORT) .show(); break; } } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view); mMyAdapter = new MyAdapter(mListener); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mRecyclerView.setAdapter(mMyAdapter); } private static class MyAdapter extends RecyclerView.Adapter<MyViewHolder> { private OnRecyclerViewItemClickListener mListener; public MyAdapter(OnRecyclerViewItemClickListener listener) { mListener = listener; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // mListener: the item click listener. return new MyViewHolder(R.layout.item_simple, parent, mListener); } @Override public void onBindViewHolder(MyViewHolder holder, int position) { holder.setText(R.id.btn_button, position + ""); // mListener: the view click listener. holder.setOnClickListener(R.id.btn_button, mListener); holder.loadUrl(R.id.iv_image, IMAGES[position % IMAGES.length]); } @Override public int getItemCount() { return 50; } } } <file_sep>/jcenter-push.gradle publish { userOrg = "ericlu" groupId = "com.ericluapp.libs" artifactId = "viewholder" publishVersion = "0.0.2" desc = "The last ViewHolder you need." website = "https://github.com/YkSix/ViewHolder2" dryRun = false } <file_sep>/sample/src/main/java/com/ericluapp/viewholderdemo/MyViewHolder.java package com.ericluapp.viewholderdemo; import android.support.annotation.IdRes; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.ericluapp.libs.OnRecyclerViewItemClickListener; import com.ericluapp.libs.ViewHolder; public class MyViewHolder extends ViewHolder { public MyViewHolder(@LayoutRes int itemLayoutId, @NonNull ViewGroup parent) { super(itemLayoutId, parent); } public MyViewHolder(@LayoutRes int itemLayoutId, @NonNull ViewGroup parent, OnRecyclerViewItemClickListener listener) { super(itemLayoutId, parent, listener); } public MyViewHolder(View itemView, ViewGroup parent) { super(itemView, parent); } public MyViewHolder(View itemView, ViewGroup parent, OnRecyclerViewItemClickListener listener) { super(itemView, parent, listener); } public MyViewHolder loadUrl(@IdRes int viewId, String url) { Glide.with(getContext()) .load(url) .into((ImageView) getView(viewId)); return this; } } <file_sep>/library/build.gradle apply plugin: 'com.android.library' group = 'com.ericluapp.libs' version = "0.0.2" def lib_version_name = version def lib_artifact_Id = "viewholder" android { compileSdkVersion rootProject.ext.compileSdkVersion buildToolsVersion rootProject.ext.buildToolsVersion lintOptions { abortOnError false } defaultConfig { minSdkVersion 10 targetSdkVersion 25 versionCode 1 versionName lib_version_name } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } // Test Android jar comes with unimplemented methods that throw exceptions by default. This // option forces the methods to return default values instead. Required for static methods, // such as TextUtils, as those cannot be mocked with Mockito. // Refer http://tools.android.com/tech-docs/unit-testing-support#TOC-Method-...-not-mocked.- testOptions { unitTests.returnDefaultValues = true } } // apply from: '../gradle-mvn-push.gradle' apply plugin: 'com.novoda.bintray-release' apply from: '../jcenter-push.gradle' // apply from: 'https://raw.githubusercontent.com/nuuneoi/JCenter/master/installv1.gradle' // apply from: 'https://raw.githubusercontent.com/nuuneoi/JCenter/master/bintrayv1.gradle' // Disable JavaDoc task // tasks.getByPath(":library:javadoc").enabled = false task generateSourcesJar(type: Jar) { from android.sourceSets.main.java.srcDirs classifier 'sources' } task generateJavadocs(type: Javadoc) { source = android.sourceSets.main.java.srcDirs classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) } task generateJavadocsJar(type: Jar, dependsOn: generateJavadocs) { from generateJavadocs.destinationDir classifier 'javadoc' } artifacts { archives generateSourcesJar } // Properties properties = new Properties() // properties.load(project.rootProject.file('local.properties').newDataInputStream()) // bintray { // user = properties.getProperty("bintray.user") // key = properties.getProperty("bintray.apikey") // pkg { // userOrg = "ericlu" // repo = 'maven' // name = lib_artifact_Id // version { // name = "${lib_version_name}-release" // desc = "The last ViewHolder." // vcsTag = lib_version_name // } // licenses = ['Apache-2.0'] // vcsUrl = 'https://github.com/YkSix/ViewHolder2.git' // websiteUrl = 'https://github.com/YkSix/ViewHolder2' // publish = true // } // configurations = ['archives'] // } // install { // repositories.mavenInstaller { // pom { // project { // artifactId lib_artifact_Id // } // } // } // } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:support-annotations:23.1.1' compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.android.support:recyclerview-v7:23.1.1' // Dependencies for unit tests which reside in the "tests" src folder. testCompile 'junit:junit:4.12' testCompile 'org.hamcrest:hamcrest-core:1.3' testCompile 'org.mockito:mockito-core:1.10.8' testCompile 'org.powermock:powermock-api-mockito:1.6.4' testCompile 'org.powermock:powermock-module-junit4-rule-agent:1.6.4' testCompile 'org.powermock:powermock-module-junit4-rule:1.6.4' testCompile 'org.powermock:powermock-module-junit4:1.6.4' testCompile 'org.json:json:20090211' }
2bb0a87eb1ddc31fdeaaec0c8baf87ca6ffe5a6c
[ "Markdown", "Java", "Gradle" ]
7
Java
YkSix/ViewHolder2
80f4901a9c400bb5d8c386c69ea022d26195b238
f9f21162788294b6e457bbc6e5d643fb5b888347
refs/heads/master
<repo_name>15735046155/yijushidai<file_sep>/js/chanpin.js //产品介绍效果 { let next = document.querySelector(".finish_bottom_jiantou_you"); let prev = document.querySelector(".finish_bottom_jiantou_zuo"); let inner = document.querySelector(".chanpin_inner"); let pager = document.querySelectorAll(".finish_bottom_jiantou_shuzi"); let n = 0; next.onclick = function () { n++; if (n === pager.length) { n = pager.length - 1; return; } inner.style.marginLeft = n * -1200 + "px"; pager[n].classList.add("active"); pager[n - 1].classList.remove("active"); obj = pager[n]; }; prev.onclick = function () { n--; if (n < 0) { n = 0; return; } inner.style.marginLeft = n * -1200 + "px"; pager[n].classList.add("active"); pager[n + 1].classList.remove("active"); obj = pager[n]; }; let obj = pager[0]; pager.forEach(function (ele, index) { ele.onclick = function () { obj.classList.remove("active"); ele.classList.add("active"); obj = ele; inner.style.marginLeft = index * -1200 + "px"; n = index; } }) } <file_sep>/js/index.js //banner { $(".banner_1").mouseenter(function () { let index = $(this).index(".banner_1"); $(".banner_lan").removeClass("active").eq(index).addClass("active"); $(".banner-img").removeClass("active1").eq(index).addClass("active1"); n = index; }) let n = 0; let l = $(".banner-img").length; let st = setInterval(move, 3000); function move() { n++; if (n === l) { n = 0; } if (n < 0) { n = l - 1; } $(".banner_lan").removeClass("active").eq(n).addClass("active"); $(".banner-img").removeClass("active1").eq(n).addClass("active1"); } $(".banner_center").mouseenter(function () { clearInterval(st); }); $(".banner_center").mouseleave(function () { st = setInterval(move, 3000); }) } //btn { let n=0; $(".al_rjt").click(function () { n++; if(n>1){ $("al_rjt").addClass(".active2"); } $("al-img").cssText( ) }) } <file_sep>/js/anli.js { $(".wc_biaoti1") .mouseenter(function () { let index = $(this).index(".wc_biaoti1"); $(".jindutiao").removeClass("active2").eq(index).addClass("active2"); $(".yangtai").removeClass("active1").eq(index).addClass("active1"); }) } //翻页 // { // let next = document.querySelector(".finish_bottom_jiantou_you"); // let prev = document.querySelector(".finish_bottom_jiantou_zuo"); // let inner = document.querySelector(".inner"); // let pager = document.querySelectorAll(".finish_bottom_jiantou_shuzi"); // let n = 0; // next.onclick = function () { // n++; // if (n === pager.length) { // n = pager.length - 1; // return; // } // inner.style.transition="all 1s"; // inner.style.marginLeft = n * -996 + "px"; // pager[n].classList.add("active"); // pager[n - 1].classList.remove("active"); // obj = pager[n]; // }; // prev.onclick = function () { // n--; // if (n < 0) { // n = 0; // return; // } // inner.style.marginLeft = n * -996 + "px"; // pager[n].classList.add("active"); // pager[n + 1].classList.remove("active"); // obj = pager[n]; // }; // let obj = pager[0]; // pager.forEach(function (ele, index) { // ele.onclick = function () { // obj.classList.remove("active"); // ele.classList.add("active"); // obj = ele; // inner.style.marginLeft = index * -996 + "px"; // n = index; // } // }) // }
9eddc7fdbedff05e32a6bab7e1f029861b81729c
[ "JavaScript" ]
3
JavaScript
15735046155/yijushidai
c35658876b1375739a7de3aa715e315128cbef69
c4dd2e0c1a2f80967d76e73153cd97a12453b673
refs/heads/master
<repo_name>FilippoChiarello/ExData_Plotting1<file_sep>/plot2.R ##2nd plot data <-read.table("household_power_consumption.txt",sep=";",col.names=c("Date","Time","Global_active_power","Global_reactive_power","Voltage","Global_intensity","Sub_metering_1","Sub_metering_2","Sub_metering_3"), nrows=2878, skip=66637); Dateandtime <- paste(data$Date,data$Time) Dateandtime <- strptime(Dateandtime, "%d/%m/%Y %H:%M:%S") Sys.setlocale('LC_TIME', 'C') plot(Dateandtime,data$Global_active_power,type="l",xlab="",ylab="Global_active_power") dev.print(png, file = "plot1.png", width = 480, height = 480) ##i've chose to use trasparent background dev.off()<file_sep>/plot4.R ##4th plot data <-read.table("household_power_consumption.txt",sep=";",col.names=c("Date","Time","Global_active_power","Global_reactive_power","Voltage","Global_intensity","Sub_metering_1","Sub_metering_2","Sub_metering_3"), nrows=2878, skip=66637); par(mfrow = c(2, 2), mar = c(4, 4 ,4, 4)) with(data, { plot(Dateandtime,Global_active_power,type="l",xlab="",ylab="Global Active Power") plot(Dateandtime,Voltage,type="l",xlab="datetime",ylab="Voltage") with(data, plot(Dateandtime,Sub_metering_1,type="l",xlab="",ylab="Energy sub metering") ) with(data, lines(Dateandtime,Sub_metering_2,col="red")) with(data, lines(Dateandtime,Sub_metering_3,col="blue")) legend("topright", lty = 1, col = c("black", "red","blue"), legend = c("Sub_metering_1", "Sub_metering_2","Sub_metering_3")) plot(Dateandtime,Global_reactive_power,type="l",xlab="datetime",ylab="Global_reactive_power") }) dev.print(png, file = "plot4.png", width = 480, height = 480)##i've chose to use trasparent background dev.off() <file_sep>/plot3.R ##3th plot data <-read.table("household_power_consumption.txt",sep=";",col.names=c("Date","Time","Global_active_power","Global_reactive_power","Voltage","Global_intensity","Sub_metering_1","Sub_metering_2","Sub_metering_3"), nrows=2878, skip=66637); with(data, plot(Dateandtime,Sub_metering_1,type="l",xlab="",ylab="Energy sub metering") ) with(data, lines(Dateandtime,Sub_metering_2,col="red")) with(data, lines(Dateandtime,Sub_metering_3,col="blue")) legend("topright", lty = 1, col = c("black", "red","blue"), legend = c("Sub_metering_1", "Sub_metering_2","Sub_metering_3")) dev.print(png, file = "plot3.png", width = 480, height = 480) ##i've chose to use trasparent background dev.off() <file_sep>/plot1.R ##1st plot data <-read.table("household_power_consumption.txt",sep=";",col.names=c("Date","Time","Global_active_power","Global_reactive_power","Voltage","Global_intensity","Sub_metering_1","Sub_metering_2","Sub_metering_3"), nrows=2878, skip=66637); hist(data$Global_active_power,main = "Global Active Power",xlab="Global Active Power (kilowats)",col="red"); dev.print(png, file = "plot1.png", width = 480, height = 480) ##i've chose to use trasparent background dev.off()
e9f427274bdbbe416b55ea15ee5115120ef3497e
[ "R" ]
4
R
FilippoChiarello/ExData_Plotting1
1d1c6b89d8bda514fd31134c3da05a9ef4888122
35c2787c1eaa9556484493821b717fe29f702925
refs/heads/master
<repo_name>liuxuqing/hapi-scaffold<file_sep>/bin/cli.js #!/usr/bin/env node const Init = require('../logic/init'); const DbMongo = require('../logic/db_mongo'); const Model = require('../logic/model'); const Route = require('../logic/route'); const Service = require('../logic/service'); const Controller = require('../logic/controller'); const [,, ...args] = process.argv; const validOptions = [ 'init', 'destroy', 'scaffold', 'generate', 'remove' ] if (validOptions.indexOf(args[0]) == -1) { console.log('Invalid options'); return; } if (args[0] == 'init') { Init.generate(); } if (args[0] == 'destroy') { Init.undo(); } if (args[0] == 'generate') { if (args[1] == 'db:mongo') { DbMongo.generate(); } } if (args[0] == 'scaffold') { if (args[1] == 'model' && args[2] != undefined) { const attributes = args.slice(3); Model.generate(args[2], attributes); } else if (args[1] == 'route' && args[2] != undefined) { Route.generate(args[2]); Route.register(args[2]); } else if (args[1] == 'service' && args[2] != undefined) { Service.generate(args[2]); } else if (args[1] == 'controller' && args[2] != undefined) { Controller.generate(args[2]); } else if (args[1] != undefined) { const attributes = args.slice(2); Model.generate(args[1], attributes); Service.generate(args[1]); Controller.generate(args[1]); Route.generate(args[1]); Route.register(args[1]); } } if (args[0] == 'remove') { if (args[1] == 'db') { DbMongo.undo(); } else if (args[1] == 'model' && args[2] != undefined) { Model.undo(args[2]); } else if (args[1] == 'route' && args[2] != undefined) { Route.undo(args[2]); Route.unregister(args[2]); } else if (args[1] == 'service' && args[2] != undefined) { Service.undo(args[2]); } else if (args[1] == 'controller' && args[2] != undefined) { Controller.undo(args[2]); } else if (args[1] != undefined) { Model.undo(args[1]); Service.undo(args[1]); Controller.undo(args[1]); Route.undo(args[1]); Route.unregister(args[1]); } }<file_sep>/utils/file_edit.js const fs = require('fs'); class FileEdit { static async injectTextToFile(fileName, searchText, text) { var result = ''; const lines = fs.readFileSync(fileName).toString().split('\n'); for (const line of lines) { if (line.indexOf(searchText) != -1) { result += `${line}\n`; result += text; } else { result += `${line}\n`; } } fs.writeFileSync(fileName, result); } static async removeTextFromFile(fileName, searchText) { var result = ''; const lines = fs.readFileSync(fileName).toString().split('\n'); for (const line of lines) { if (line.indexOf(searchText) == -1) { result += `${line}\n`; } } fs.writeFileSync(fileName, result); } } module.exports = FileEdit;<file_sep>/logic/db_mongo.js #!/usr/bin/env node const fs = require('fs'); const path = require('path'); class DbMongo { static generate() { fs.readFile(path.resolve(__dirname, '../snippets/db_mongo'), function(err, data) { fs.writeFileSync(`config/database.js`, data.toString()); }); console.log('Database config created!'); } static undo() { fs.unlinkSync('config/database.js'); console.log('Removed database config!'); } } module.exports = DbMongo;<file_sep>/logic/controller.js #!/usr/bin/env node const fs = require('fs'); const path = require('path'); const pluralize = require('pluralize'); class Controller { static generate(modelName) { const modelNameCapitalized = modelName.charAt(0).toUpperCase() + modelName.slice(1); const modelNameLowered = modelName.toLowerCase(); const controllerName = pluralize.plural(modelName); const controllerNameCapitalized = controllerName.charAt(0).toUpperCase() + controllerName.slice(1); const controllerNameLowered = controllerName.toLowerCase(); fs.readFile(path.resolve(__dirname, '../snippets/controller'), function(err, data) { data = data.toString().split('<ModelNameCapitalized>').join(modelNameCapitalized); data = data.toString().split('<ModelNameLowered>').join(modelNameLowered); data = data.toString().split('<ControllerNameCapitalized>').join(controllerNameCapitalized); data = data.toString().split('<ServiceNameCapitalized>').join(controllerNameCapitalized); data = data.toString().split('<ServiceNameLowered>').join(controllerNameLowered); fs.writeFileSync(`controllers/${controllerNameLowered}_controller.js`, data.toString()); }); console.log('Controller created!'); } static undo(modelName) { const controllerNameLowered = pluralize.plural(modelName.toLowerCase()); fs.unlinkSync(`controllers/${controllerNameLowered}_controller.js`); console.log('Controller removed!'); } } module.exports = Controller;<file_sep>/README.md # hapi-scaffold Code generation for the [hapijs](https://hapijs.com/) framework. **(work in progress)** ### Install it. > $ npm install hapi-scaffold -g ### Initialize de application. Create the index.js with a basic config. > $ hapi-scaffold init ### Erase all folders and files generated. Use it carefully. > $ hapi-scaffold destroy ### Create the database configuration file. > $ hapi-scaffold generate db:mongo ### Generate a default CRUD for the given resource name. > $ hapi-scaffold scaffold post **title:string:required** **content:string** **rating:number** ### Generate a route file (and register it on the server). > $ hapi-scaffold scaffold route post ### Generate a controller file. > $ hapi-scaffold scaffold controller post ### Generate a service file. Here is where all the logic will be placed. > $ hapi-scaffold scaffold service post ### Generate the model file. > $ hapi-scaffold scaffold model post **title:string:required** **content:string** **rating:number** ### Remove the database configuration file. > $ hapi-scaffold remove db ### Remove CRUD files. > $ hapi-scaffold remove post ### Remove a route file (and unregister it on the server). > $ hapi-scaffold remove route post ### Remove a controller file. > $ hapi-scaffold remove controller post ### Remove a service file. > $ hapi-scaffold remove service post ### Remove the model file. > $ hapi-scaffold remove model post<file_sep>/logic/model.js #!/usr/bin/env node const fs = require('fs'); const path = require('path'); const formatAttributes = require('../utils/format_attributes'); class Model { static generate(modelName, attributes) { const modelNameCapitalized = modelName.charAt(0).toUpperCase() + modelName.slice(1); const modelNameLowered = modelName.toLowerCase(); fs.readFile(path.resolve(__dirname, '../snippets/model'), function(err, data) { attributes = formatAttributes(attributes); data = data.toString().split('<ModelName>').join(modelNameCapitalized); data = data.toString().split('<Attributes>').join(attributes); fs.writeFileSync(`models/${modelNameLowered}.js`, data.toString()); }); console.log('Model created!'); } static undo(modelName) { const modelNameLowered = modelName.toLowerCase(); fs.unlinkSync(`models/${modelNameLowered}.js`); console.log('Model removed!'); } } module.exports = Model;<file_sep>/utils/format_attributes.js module.exports = (attributes) => { var attrs = ''; for (var i = 0; i < attributes.length; i++) { var attr = attributes[i].split(':'); var type = attr[1].charAt(0).toUpperCase() + attr[1].slice(1); var required = attr[2] == 'required' ? true : false; attrs += `\t${attr[0]}: { type: ${type}, required: ${required} }`; if (i+1 != attributes.length) attrs += ',\n'; } return attrs; }
7e2acc918c0d5c64737ea3b3fa7af8c01c08e096
[ "JavaScript", "Markdown" ]
7
JavaScript
liuxuqing/hapi-scaffold
e4e08bc4fa68668834dbccf58562524e76555bb8
aff1fc8ae762aa79fffe6b1b6df923218d982c39
refs/heads/main
<file_sep>import { Request, Response } from "express"; import { ShowUserProfileUseCase } from "./ShowUserProfileUseCase"; class ShowUserProfileController { constructor(private showUserProfileUseCase: ShowUserProfileUseCase) { // } handle(request: Request, response: Response): Response { const { user_id } = request.params; const userExists = this.showUserProfileUseCase.validateUserExists( String(user_id) ); if (!userExists) { return response .status(404) .json({ error: "User does not exists!" }); } const user = this.showUserProfileUseCase.execute({ user_id, }); return response.status(200).json(user); } } export { ShowUserProfileController };
689b622590ab4cb6f6e4e4fa9f8c0e544e113dc2
[ "TypeScript" ]
1
TypeScript
PedroDev4/solid-introduction-ignite
cdcfd85f2c099e12fada2a193566143648798fff
d5a21d15ae1f78c8e35ee36618edd2c1dfca9714
refs/heads/master
<file_sep>com.didispace.blog.name=progroess com.didispace.blog.title=Spring Boot jiaocheng prod<file_sep>import com.cms.test.springboot.controller.UserController import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.springframework.boot.test.SpringApplicationConfiguration import org.springframework.mock.web.MockServletContext import org.springframework.test.context.junit4.SpringJUnit4ClassRunner import org.springframework.test.context.web.WebAppConfiguration import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.RequestBuilder import org.springframework.test.web.servlet.result.MockMvcResultHandlers import org.springframework.test.web.servlet.setup.MockMvcBuilders import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.* import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status //@RunWith(SpringJUnit4ClassRunner::class) //@SpringApplicationConfiguration(classes = arrayOf(MockServletContext::class)) //@WebAppConfiguration class ApplicationTests { private var mvc: MockMvc? = null // @Before // @Throws(Exception::class) // fun setUp() { // mvc = MockMvcBuilders.standaloneSetup(UserController()).build() // } // @Test // @Throws(Exception::class) fun testUserController() { // 测试UserController var request: RequestBuilder? = null // 1、get查一下user列表,应该为空 request = get("/users/") mvc!!.perform(request!!) .andExpect(status().isOk) .andDo(MockMvcResultHandlers.print()).andReturn() // 2、post提交一个user request = post("/users/") .param("id", "1") .param("name", "测试大师") .param("age", "20") mvc!!.perform(request!!) .andDo(MockMvcResultHandlers.print()).andReturn() // 3、get获取user列表,应该有刚才插入的数据 request = get("/users/") mvc!!.perform(request!!) .andExpect(status().isOk) .andDo(MockMvcResultHandlers.print()).andReturn() // 4、put修改id为1的user request = put("/users/1") .param("name", "测试终极大师") .param("age", "30") mvc!!.perform(request!!) .andDo(MockMvcResultHandlers.print()).andReturn() // 5、get一个id为1的user request = get("/users/1") mvc!!.perform(request!!) .andDo(MockMvcResultHandlers.print()).andReturn() // 6、del删除id为1的user request = delete("/users/1") mvc!!.perform(request!!) .andDo(MockMvcResultHandlers.print()).andReturn() // 7、get查一下user列表,应该为空 request = get("/users/") mvc!!.perform(request!!) .andExpect(status().isOk) .andDo(MockMvcResultHandlers.print()).andReturn() } }<file_sep>package com.cms.test.springboot.service.impl; import com.cms.test.springboot.dao.SettingDao; import com.cms.test.springboot.domain.Setting; import com.cms.test.springboot.service.SettingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class SettingServiceImpl implements SettingService { @Autowired private SettingDao settingDao; @Override public Setting findSettingById(int id) { Setting setting=settingDao.findById(id); return setting; } } <file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>oaextra</groupId> <artifactId>com.cms.test</artifactId> <version>1.0-SNAPSHOT</version> <name>springBoot</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <mybatis-spring-boot>1.2.0</mybatis-spring-boot> <mysql-connector>5.1.39</mysql-connector> <druid>1.0.18</druid> <kotlin.version>1.3.21</kotlin.version> <activiti.version>6.0.0</activiti.version> <activiti-exp.version>5.22.0</activiti-exp.version> </properties> <!--引入Spring Boot的parent模块--> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.1.RELEASE</version> </parent> <dependencies> <!--引入Spring Boot 的web依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--引入Spring Boot 的单元测试依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <!-- swagger2 文档相关依赖--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.2.2</version> </dependency> <!-- Spring Boot Mybatis 依赖 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis-spring-boot}</version> </dependency> <!-- MySQL 连接驱动依赖 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql-connector}</version> </dependency> <!-- https://mvnrepository.com/artifact/com.microsoft.sqlserver/sqljdbc4 --> <!--<dependency>--> <!--<groupId>com.microsoft.sqlserver</groupId>--> <!--<artifactId>sqljdbc4</artifactId>--> <!--<version>4.2-6</version>--> <!--</dependency>--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid}</version> </dependency> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-spring-boot-starter-basic</artifactId> <version>6.0.0</version> </dependency> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-spring-boot-starter-rest-api</artifactId> <version>6.0.0</version> </dependency> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-spring-boot-starter-actuator</artifactId> <version>${activiti.version}</version> </dependency> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-spring-boot-starter-jpa</artifactId> <version>${activiti.version}</version> </dependency> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-explorer</artifactId> <version>${activiti-exp.version}</version> </dependency> <!--<dependency> 这个包看起来没什么用,一旦加入的话由于他依赖于5.22的activiti-engine包,所以不能兼容6.0.0 <groupId>org.activiti</groupId> <artifactId>activiti-diagram-rest</artifactId> <version>${activiti-exp.version}</version> </dependency>--> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-simple-workflow</artifactId> <version>${activiti-exp.version}</version> </dependency> <!--springboot 数据采集--> <dependency> <groupId>io.prometheus</groupId> <artifactId>simpleclient_spring_boot</artifactId> <version>0.0.26</version> </dependency> </dependencies> <build> <finalName>test</finalName> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <fork>true</fork> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <executions> <execution> <id>compile</id> <phase>compile</phase> <goals> <goal>compile</goal> </goals> </execution> <execution> <id>testCompile</id> <phase>test-compile</phase> <goals> <goal>testCompile</goal> </goals> </execution> </executions> <!--指定JDK版本1.8--> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> <!-- <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-engine</artifactId> <version>5.18.0</version> </dependency> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-spring</artifactId> <version>5.18.0</version> <exclusions> <exclusion> <artifactId>commons-dbcp</artifactId> <groupId>commons-dbcp</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-diagram-rest</artifactId> <version>5.18.0</version> </dependency> <dependency> <groupId>batik</groupId> <artifactId>batik-transcoder</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>batik</groupId> <artifactId>batik-dom</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-json-converter</artifactId> <version>5.18.0</version> <exclusions> <exclusion> <artifactId>commons-collections</artifactId> <groupId>commons-collections</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>batik</groupId> <artifactId>batik-bridge</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>batik</groupId> <artifactId>batik-css</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>batik</groupId> <artifactId>batik-anim</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>batik</groupId> <artifactId>batik-codec</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>batik</groupId> <artifactId>batik-ext</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>batik</groupId> <artifactId>batik-gvt</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>batik</groupId> <artifactId>batik-script</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>batik</groupId> <artifactId>batik-parser</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>batik</groupId> <artifactId>batik-svg-dom</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>batik</groupId> <artifactId>batik-svggen</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>batik</groupId> <artifactId>batik-util</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>batik</groupId> <artifactId>batik-xml</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>org.apache.xmlgraphics</groupId> <artifactId>batik-js</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>xml-apis</groupId> <artifactId>xml-apis-ext</artifactId> <version>1.3.04</version> </dependency> <dependency> <groupId>xml-apis</groupId> <artifactId>xml-apis</artifactId> <version>1.3.04</version> </dependency> <dependency> <groupId>org.apache.xmlgraphics</groupId> <artifactId>xmlgraphics-commons</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>batik</groupId> <artifactId>batik-awt-util</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.1</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency> --> </project><file_sep>import org.activiti.engine.*; import org.activiti.engine.repository.Deployment; import org.activiti.engine.repository.ProcessDefinition; import org.activiti.engine.runtime.ProcessInstance; import org.activiti.engine.task.Task; import org.activiti.engine.task.TaskQuery; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.io.File; import java.io.InputStream; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest(classes = HelloTest.class) public class HelloTest { private ProcessEngine processEngine; @Before public void getHello() throws Exception { ProcessEngineConfiguration engineConfiguration= ProcessEngineConfiguration.createStandaloneProcessEngineConfiguration(); //设置数据库连接属性 engineConfiguration.setJdbcDriver("com.mysql.jdbc.Driver"); engineConfiguration.setJdbcUrl("jdbc:mysql://localhost:3306/activiti_cmdb?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=utf8"); engineConfiguration.setJdbcUsername("root"); engineConfiguration.setJdbcPassword("<PASSWORD>"); engineConfiguration.setJdbcMaxIdleConnections(100); engineConfiguration.setJdbcMaxActiveConnections(50); // 设置创建表的策略 (当没有表时,自动创建表) engineConfiguration.setDatabaseSchemaUpdate("true"); //通过ProcessEngineConfiguration对象创建 ProcessEngine 对象 processEngine = engineConfiguration.buildProcessEngine(); System.out.println("流程引擎创建成功!"); } @Test public void deploy() { //根据acitivit disiger 插件管理流程定义 RepositoryService repositoryService = processEngine.getRepositoryService(); Deployment deploy = repositoryService.createDeployment()//创建一个部署的构建器 .addClasspathResource("disgrams/NewShopping.bpmn")//从类路径中添加资源,一次只能添加一个资源 .name("采购流程")//设置部署的名称 .category("采购")//设置部署的类别 .deploy(); System.out.println("部署的id"+deploy.getId()); System.out.println("部署的名称"+deploy.getName()); } @Test public void startProcess(){ //指定执行我们刚才部署的工作流程 String processDefiKey="TestActiviti"; //取运行时服务 RuntimeService runtimeService = processEngine.getRuntimeService(); //取得流程实例 ProcessInstance pi = runtimeService.startProcessInstanceByKey(processDefiKey);//通过流程定义的key 来执行流程 System.out.println("流程实例id:"+pi.getId());//流程实例id System.out.println("流程定义id:"+pi.getProcessDefinitionId());//输出流程定义的id // Map<String, Object> variables = new HashMap<String, Object>(); // variables.put("employeeName", "Kermit"); // variables.put("numberOfDays", new Integer(4)); // variables.put("vacationMotivation", "I'm really tired!"); // // RuntimeService runtimeService = processEngine.getRuntimeService(); // ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("ForkShopping", variables); // // System.out.println("Number of process instances: " + runtimeService.createProcessInstanceQuery().count()); } //查询任务 @Test public void queryTask(){ //任务的办理人 String assignee="kowi"; //取得任务服务 TaskService taskService = processEngine.getTaskService(); //创建一个任务查询对象 TaskQuery taskQuery = taskService.createTaskQuery(); //办理人的任务列表 List<Task> list = taskQuery.taskAssignee(assignee).list();//指定办理人 //遍历任务列表 if(list!=null&&list.size()>0){ for(Task task:list){ System.out.println("任务的办理人:"+task.getAssignee()); System.out.println("任务的id:"+task.getId()); System.out.println("任务的名称:"+task.getName()); } } } //完成任务 @Test public void compileTask(){ String taskId="47502"; //taskId:任务id // Map<String,Object> params=new HashMap<>(); // params.put("message",2);流程中有分支的控制参数设置 // processEngine.getTaskService().complete(taskId,params); processEngine.getTaskService().complete(taskId); System.out.println("当前任务执行完毕"); } @Test public void viewImage() throws Exception{ String deploymentId="17501"; String imageName=null; //取得某个部署的资源的名称 deploymentId List<String> resourceNames = processEngine.getRepositoryService().getDeploymentResourceNames(deploymentId); // buybill.bpmn buybill.png if(resourceNames!=null&&resourceNames.size()>0){ for(String temp :resourceNames){ if(temp.indexOf(".png")>0){ imageName=temp; } } } /** * 读取资源 * deploymentId:部署的id * resourceName:资源的文件名 */ InputStream resourceAsStream = processEngine.getRepositoryService().getResourceAsStream(deploymentId, imageName); //把文件输入流写入到文件中 File file=new File("d:/"+imageName); FileUtils.copyInputStreamToFile(resourceAsStream, file); } //查看流程定义 @Test public void queryProcessDefination(){ String processDefiKey="autoBpmn";//流程定义key //获取流程定义列表 List<ProcessDefinition> list = processEngine.getRepositoryService().createProcessDefinitionQuery() //查询 ,好比where // .processDefinitionId(proDefiId) //流程定义id // 流程定义id : buyBill:2:704 组成 : proDefikey(流程定义key)+version(版本)+自动生成id .processDefinitionKey(processDefiKey)//流程定义key 由bpmn 的 process 的 id属性决定 // .processDefinitionName(name)//流程定义名称 由bpmn 的 process 的 name属性决定 // .processDefinitionVersion(version)//流程定义的版本 .latestVersion()//最新版本 //排序 .orderByProcessDefinitionVersion().desc()//按版本的降序排序 //结果 // .count()//统计结果 // .listPage(arg0, arg1)//分页查询 .list(); //遍历结果 if(list!=null&&list.size()>0){ for(ProcessDefinition temp:list){ System.out.print("流程定义的id: "+temp.getId()); System.out.print("流程定义的key: "+temp.getKey()); System.out.print("流程定义的版本: "+temp.getVersion()); System.out.print("流程定义部署的id: "+temp.getDeploymentId()); System.out.println("流程定义的名称: "+temp.getName()); } } } }
0df435b3d0381b87b0df9a759347b19ebeff0741
[ "Java", "Maven POM", "Kotlin", "INI" ]
5
INI
281831964/activiti
20279b1c5064fd91098de698b7dcab367d75f3b5
6673a922717ddc87cdb0edd23f602a4db0b1d8cb
refs/heads/master
<file_sep>/** Module: mockbot-document Author: <NAME> */ /*jshint node: true */ /*jshint esversion: 6 */ "use strict"; /** * Mock Element * @external mockbot-element * @see {@link https://www.npmjs.com/package/mockbot-element|mockbot-element} */ var elementFactory = require("mockbot-element"); /** * Module * @module mockbot-document */ /** * * Factory module * @module mockbot-document-factory */ /** * Factory method * It takes one spec parameter that must be an object with named parameters * @param {Object} spec Named parameters object * @returns {module:mockbot-document} * @example <caption>Usage example</caption> * var factory = require("mockbot-document"); * var obj = factory.create({}); */ module.exports.create = (spec) => { spec = spec || {}; var elements = []; return { /** Creates a mock element to simulate html elements. * @function * @instance * @param {Object} spec Named parameters object * @param {string} spec.tagName Required element type name (a, div, x-thing, etc.) * @param {string} spec.id Optional element id * @memberof module:mockbot-document * @returns {external:mockbot-element} * @example <caption>usage</caption> * document.mockElement( { tagName: tagName, id: id } ); * var result = document.getElementById(id); * should.exist(result); */ mockElement: function(spec) { var el = elementFactory.create( spec ); elements.push( el ); return el; }, /** Mock document.querySelector(). * CURRENTLY NON-FUNCTIONAL - just a place holder for now. * @function * @instance * @memberof module:mockbot-document * @returns {null} * @example <caption>usage</caption> * document.querySelector("..."); */ querySelector: function () { return null; }, /** Mock document.getElementById() * @function * @instance * @param {string} id Element id * @memberof module:mockbot-document * @returns {external:mockbot-element} * @example <caption>usage</caption> * var el = document.getElementById("id"); */ getElementById: function (id) { var result = elements.filter( (el) => el.id === id ); return result.length > 0 ? result[0] : null; }, /** Mock document.getElementsByTagName() * @function * @instance * @param {string} tagName Element tagName (div,p,a,etc.) * @memberof module:mockbot-document * @returns {Array.<external:mockbot-element>} * @example <caption>usage</caption> * var elArray = document.getElementsByTagName("div"); */ getElementsByTagName: function (tagName) { var result = elements.filter( (el) => el.tagName === tagName.toUpperCase() ); return result.length > 0 ? result : null; }, /** Mock document.createElement() * @function * @instance * @param {string} tagName name of HTML element (a, div, x-thing, etc.) * @memberof module:mockbot-document * @returns {external:mockbot-element} * @example <caption>usage</caption> * var el = document.createElement("div"); */ createElement: function(tagName) { return elementFactory.create( { tagName: tagName } ); } }; }; <file_sep>mockbot-document == mock html dom document -- <p align="left"> <a href="https://travis-ci.org/mitchallen/mockbot-document"> <img src="https://img.shields.io/travis/mitchallen/mockbot-document.svg?style=flat-square" alt="Version"> </a> <a href="https://codecov.io/gh/mitchallen/mockbot-document"> <img src="https://codecov.io/gh/mitchallen/mockbot-document/branch/master/graph/badge.svg" alt="Coverage Status"> </a> <a href="https://npmjs.org/package/mockbot-document"> <img src="http://img.shields.io/npm/dt/mockbot-document.svg?style=flat-square" alt="Downloads"> </a> <a href="https://npmjs.org/package/mockbot-document"> <img src="http://img.shields.io/npm/v/mockbot-document.svg?style=flat-square" alt="Version"> </a> <a href="https://npmjs.com/package/mockbot-document"> <img src="https://img.shields.io/npm/l/mockbot-document.svg?style=flat-square" alt="License"></a> </a> </p> ## Installation $ npm init $ npm install mockbot-document --save-dev * * * ## Usage With tools like __browserify__, it's easy to create client side code in node.js. But, when testing with tools like __mocha__, code that references browser elements or the document object will throw an error. This can be worked around by creating a mock object that simulates the document object. Assign it to __global__ before each test starts, then delete it from global when each test finishes. Here is an example using mocha: "use strict"; var documentFactory = require("mockbot-document"); describe('module smoke test', () => { beforeEach( done => { // Call before all tests // mock browser document global.document = documentFactory.create(); done(); }); afterEach( done => { // Call after all tests delete global.document; done(); }); it('createElement should return object', done => { var result = document.createElement('div'); should.exist(result); done(); }) } * * * ## Limitations The main objective of this module is to provide placeholders to avoid lint and compiler errors. Duplicating functionality of a real browser is not as important. Though attempts will be made to simulate a response from a browser, actual functionality is not guaranteed. ## Available Methods Only a small subset of mock document methods are currently available. Over time others will be added. See the module reference below to see what is currently available. ## Requesting Methods If a specific method is desired ASAP, open up an issue on github.com to request it. ## Elements For information on available element methods, see __[mockbot-element](https://www.npmjs.com/package/mockbot-element)__. * * * ## Modules <dl> <dt><a href="#module_mockbot-document">mockbot-document</a></dt> <dd><p>Module</p> </dd> <dt><a href="#module_mockbot-document-factory">mockbot-document-factory</a></dt> <dd><p>Factory module</p> </dd> </dl> ## External <dl> <dt><a href="#external_mockbot-element">mockbot-element</a></dt> <dd><p>Mock Element</p> </dd> </dl> <a name="module_mockbot-document"></a> ## mockbot-document Module * [mockbot-document](#module_mockbot-document) * [.mockElement(spec)](#module_mockbot-document+mockElement) ⇒ <code>[mockbot-element](#external_mockbot-element)</code> * [.querySelector()](#module_mockbot-document+querySelector) ⇒ <code>null</code> * [.getElementById(id)](#module_mockbot-document+getElementById) ⇒ <code>[mockbot-element](#external_mockbot-element)</code> * [.getElementsByTagName(tagName)](#module_mockbot-document+getElementsByTagName) ⇒ <code>[Array.&lt;mockbot-element&gt;](#external_mockbot-element)</code> * [.createElement(tagName)](#module_mockbot-document+createElement) ⇒ <code>[mockbot-element](#external_mockbot-element)</code> <a name="module_mockbot-document+mockElement"></a> ### mockbot-document.mockElement(spec) ⇒ <code>[mockbot-element](#external_mockbot-element)</code> Creates a mock element to simulate html elements. **Kind**: instance method of <code>[mockbot-document](#module_mockbot-document)</code> | Param | Type | Description | | --- | --- | --- | | spec | <code>Object</code> | Named parameters object | | spec.tagName | <code>string</code> | Required element type name (a, div, x-thing, etc.) | | spec.id | <code>string</code> | Optional element id | **Example** *(usage)* ```js document.mockElement( { tagName: tagName, id: id } ); var result = document.getElementById(id); should.exist(result); ``` <a name="module_mockbot-document+querySelector"></a> ### mockbot-document.querySelector() ⇒ <code>null</code> Mock document.querySelector(). CURRENTLY NON-FUNCTIONAL - just a place holder for now. **Kind**: instance method of <code>[mockbot-document](#module_mockbot-document)</code> **Example** *(usage)* ```js document.querySelector("..."); ``` <a name="module_mockbot-document+getElementById"></a> ### mockbot-document.getElementById(id) ⇒ <code>[mockbot-element](#external_mockbot-element)</code> Mock document.getElementById() **Kind**: instance method of <code>[mockbot-document](#module_mockbot-document)</code> | Param | Type | Description | | --- | --- | --- | | id | <code>string</code> | Element id | **Example** *(usage)* ```js var el = document.getElementById("id"); ``` <a name="module_mockbot-document+getElementsByTagName"></a> ### mockbot-document.getElementsByTagName(tagName) ⇒ <code>[Array.&lt;mockbot-element&gt;](#external_mockbot-element)</code> Mock document.getElementsByTagName() **Kind**: instance method of <code>[mockbot-document](#module_mockbot-document)</code> | Param | Type | Description | | --- | --- | --- | | tagName | <code>string</code> | Element tagName (div,p,a,etc.) | **Example** *(usage)* ```js var elArray = document.getElementsByTagName("div"); ``` <a name="module_mockbot-document+createElement"></a> ### mockbot-document.createElement(tagName) ⇒ <code>[mockbot-element](#external_mockbot-element)</code> Mock document.createElement() **Kind**: instance method of <code>[mockbot-document](#module_mockbot-document)</code> | Param | Type | Description | | --- | --- | --- | | tagName | <code>string</code> | name of HTML element (a, div, x-thing, etc.) | **Example** *(usage)* ```js var el = document.createElement("div"); ``` <a name="module_mockbot-document-factory"></a> ## mockbot-document-factory Factory module <a name="module_mockbot-document-factory.create"></a> ### mockbot-document-factory.create(spec) ⇒ <code>[mockbot-document](#module_mockbot-document)</code> Factory method It takes one spec parameter that must be an object with named parameters **Kind**: static method of <code>[mockbot-document-factory](#module_mockbot-document-factory)</code> | Param | Type | Description | | --- | --- | --- | | spec | <code>Object</code> | Named parameters object | **Example** *(Usage example)* ```js var factory = require("mockbot-document"); var obj = factory.create({}); ``` <a name="external_mockbot-element"></a> ## mockbot-element Mock Element **Kind**: global external **See**: [mockbot-element](https://www.npmjs.com/package/mockbot-element) * * * ## Testing To test, go to the root folder and type (sans __$__): $ npm test * * * ## Repo(s) * [bitbucket.org/mitchallen/mockbot-document.git](https://bitbucket.org/mitchallen/mockbot-document.git) * [github.com/mitchallen/mockbot-document.git](https://github.com/mitchallen/mockbot-document.git) * * * ## Contributing In lieu of a formal style guide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code. * * * ## Version History #### Version 0.1.14 * fixex getElementsByTagName documentation #### Version 0.1.13 * added getElementsByTagName * fixed mockElement documentation #### Version 0.1.12 * fixed issue where getElementById was returning array instead of first element #### Version 0.1.11 * updated mockbot-element to version 0.1.8 #### Version 0.1.10 * fixed type-o in doc #### Version 0.1.9 * refactored getElementById * cleaned up documentation #### Version 0.1.8 * fixed version history #### Version 0.1.7 * updated mockbot-element to version 0.1.7 * removed client example #### Version 0.1.6 * updated mockbot-element to version 0.1.6 #### Version 0.1.5 * updated mockbot-element to version 0.1.5 #### Version 0.1.4 * updated mockbot-element to version 0.1.4 (contains tagName property) * updated createElement to create element using tagName #### Version 0.1.3 * fixed doc errors #### Version 0.1.2 * fixed version history #### Version 0.1.1 * added test cases to bring coverage up to 100% * added mockElement method * updated to latest version of mockbot-element #### Version 0.1.0 * initial release * * * <file_sep>## Modules <dl> <dt><a href="#module_mockbot-document">mockbot-document</a></dt> <dd><p>Module</p> </dd> <dt><a href="#module_mockbot-document-factory">mockbot-document-factory</a></dt> <dd><p>Factory module</p> </dd> </dl> ## External <dl> <dt><a href="#external_mockbot-element">mockbot-element</a></dt> <dd><p>Mock Element</p> </dd> </dl> <a name="module_mockbot-document"></a> ## mockbot-document Module * [mockbot-document](#module_mockbot-document) * [.mockElement(spec)](#module_mockbot-document+mockElement) ⇒ <code>[mockbot-element](#external_mockbot-element)</code> * [.querySelector()](#module_mockbot-document+querySelector) ⇒ <code>null</code> * [.getElementById(id)](#module_mockbot-document+getElementById) ⇒ <code>[mockbot-element](#external_mockbot-element)</code> * [.getElementsByTagName(tagName)](#module_mockbot-document+getElementsByTagName) ⇒ <code>[Array.&lt;mockbot-element&gt;](#external_mockbot-element)</code> * [.createElement(tagName)](#module_mockbot-document+createElement) ⇒ <code>[mockbot-element](#external_mockbot-element)</code> <a name="module_mockbot-document+mockElement"></a> ### mockbot-document.mockElement(spec) ⇒ <code>[mockbot-element](#external_mockbot-element)</code> Creates a mock element to simulate html elements. **Kind**: instance method of <code>[mockbot-document](#module_mockbot-document)</code> | Param | Type | Description | | --- | --- | --- | | spec | <code>Object</code> | Named parameters object | | spec.tagName | <code>string</code> | Required element type name (a, div, x-thing, etc.) | | spec.id | <code>string</code> | Optional element id | **Example** *(usage)* ```js document.mockElement( { tagName: tagName, id: id } ); var result = document.getElementById(id); should.exist(result); ``` <a name="module_mockbot-document+querySelector"></a> ### mockbot-document.querySelector() ⇒ <code>null</code> Mock document.querySelector(). CURRENTLY NON-FUNCTIONAL - just a place holder for now. **Kind**: instance method of <code>[mockbot-document](#module_mockbot-document)</code> **Example** *(usage)* ```js document.querySelector("..."); ``` <a name="module_mockbot-document+getElementById"></a> ### mockbot-document.getElementById(id) ⇒ <code>[mockbot-element](#external_mockbot-element)</code> Mock document.getElementById() **Kind**: instance method of <code>[mockbot-document](#module_mockbot-document)</code> | Param | Type | Description | | --- | --- | --- | | id | <code>string</code> | Element id | **Example** *(usage)* ```js var el = document.getElementById("id"); ``` <a name="module_mockbot-document+getElementsByTagName"></a> ### mockbot-document.getElementsByTagName(tagName) ⇒ <code>[Array.&lt;mockbot-element&gt;](#external_mockbot-element)</code> Mock document.getElementsByTagName() **Kind**: instance method of <code>[mockbot-document](#module_mockbot-document)</code> | Param | Type | Description | | --- | --- | --- | | tagName | <code>string</code> | Element tagName (div,p,a,etc.) | **Example** *(usage)* ```js var elArray = document.getElementsByTagName("div"); ``` <a name="module_mockbot-document+createElement"></a> ### mockbot-document.createElement(tagName) ⇒ <code>[mockbot-element](#external_mockbot-element)</code> Mock document.createElement() **Kind**: instance method of <code>[mockbot-document](#module_mockbot-document)</code> | Param | Type | Description | | --- | --- | --- | | tagName | <code>string</code> | name of HTML element (a, div, x-thing, etc.) | **Example** *(usage)* ```js var el = document.createElement("div"); ``` <a name="module_mockbot-document-factory"></a> ## mockbot-document-factory Factory module <a name="module_mockbot-document-factory.create"></a> ### mockbot-document-factory.create(spec) ⇒ <code>[mockbot-document](#module_mockbot-document)</code> Factory method It takes one spec parameter that must be an object with named parameters **Kind**: static method of <code>[mockbot-document-factory](#module_mockbot-document-factory)</code> | Param | Type | Description | | --- | --- | --- | | spec | <code>Object</code> | Named parameters object | **Example** *(Usage example)* ```js var factory = require("mockbot-document"); var obj = factory.create({}); ``` <a name="external_mockbot-element"></a> ## mockbot-element Mock Element **Kind**: global external **See**: [mockbot-element](https://www.npmjs.com/package/mockbot-element) <file_sep>/** Module: @mitchallen/mockbot-document Test: mock-element-test Author: <NAME> */ "use strict"; var request = require('supertest'), should = require('should'), modulePath = "../modules/index"; describe('mockElement', () => { var _factory = null; before( done => { // Call before all tests done(); }); after( done => { // Call after all tests done(); }); beforeEach( done => { // Call before each test delete require.cache[require.resolve(modulePath)]; _factory = require(modulePath); global.document = _factory.create(); done(); }); afterEach( done => { // Call after each test delete global.document; done(); }); it('should exist', done => { should.exist(document.mockElement); done(); }) it('should create element', done => { var tag = "div", id = "m1", el1 = document.mockElement( { tagName: tag, id: id } ); should.exist(el1); done(); }) it('should return element with tagName as uppercase', done => { var tag = "div", id = "m1", el = document.mockElement( { tagName: tag, id: id } ); should.exist(el); el.tagName.should.eql(tag.toUpperCase()); done(); }) it('should return element with id property', done => { var tag = "div", id = "m1", el = document.mockElement( { tagName: tag, id: id } ); should.exist(el); el.id.should.eql(id); done(); }) it('should create element that getElementById can find', done => { var tag = "div", id = "m1", el1 = document.mockElement( { tagName: tag, id: id } ); should.exist(el1); var el2 = document.getElementById(id); should.exist(el2); el2.tagName.should.eql(tag.toUpperCase()); el2.id.should.eql(id); done(); }) it('should return an object that can be found by getElementsByTagName', done => { var tag = "div", id = "m1", el = document.mockElement( { tagName: tag, id: id } ); should.exist(el); var elArray = document.getElementsByTagName(tag); should.exist(elArray); elArray.length.should.eql(1); elArray[0].tagName.should.eql(tag.toUpperCase()); elArray[0].id.should.eql(id); done(); }) }); <file_sep>/** Module: @mitchallen/mockbot-document Test: smoke-test Author: <NAME> */ "use strict"; var request = require('supertest'), should = require('should'), modulePath = "../modules/index"; describe('module factory smoke test', () => { var _factory = null; before( done => { // Call before all tests done(); }); after( done => { // Call after all tests done(); }); beforeEach( done => { // Call before each test delete require.cache[require.resolve(modulePath)]; _factory = require(modulePath); global.document = _factory.create(); done(); }); afterEach( done => { // Call after each test delete global.document; done(); }); it('module should exist', done => { should.exist(_factory); done(); }) it('create method with no spec should return object', done => { var obj = _factory.create(); should.exist(obj); done(); }); it('create method with spec should return object', done => { var obj = _factory.create({}); should.exist(obj); done(); }); it('querySelector should be available', done => { should.exist(document.querySelector); done(); }) it('querySelector with no spec should return null', done => { var result = document.querySelector(); should.not.exist(result); done(); }) }); <file_sep>/** Module: @mitchallen/mockbot-document Test: get-elements-by-tagname-test Author: <NAME> */ "use strict"; var request = require('supertest'), should = require('should'), modulePath = "../modules/index"; describe('getElementsByTagName', () => { var _factory = null; before( done => { // Call before all tests done(); }); after( done => { // Call after all tests done(); }); beforeEach( done => { // Call before each test delete require.cache[require.resolve(modulePath)]; _factory = require(modulePath); global.document = _factory.create(); done(); }); afterEach( done => { // Call after each test delete global.document; done(); }); it('should exist', done => { should.exist(document.getElementsByTagName); done(); }) it('with no elements should return null', done => { var result = document.getElementsByTagName('foo'); should.not.exist(result); done(); }) it('for non-existant id should return null', done => { var tagName = "div", id = 'alpha'; // must have at least one other item document.mockElement( { tagName: tagName, id: id } ); var result = document.getElementsByTagName('foo'); should.not.exist(result); done(); }) it('for mocked element should return array', done => { var tagName = "div", id = 'alpha'; document.mockElement( { tagName: tagName, id: id } ); var result = document.getElementsByTagName(tagName); should.exist(result); result.should.be.instanceOf(Array); result.should.have.lengthOf(1); done(); }) it('for mocked element should return matching array element', done => { var tagName = "div", id = 'alpha'; document.mockElement( { tagName: tagName, id: id } ); var result = document.getElementsByTagName(tagName); should.exist(result); should.exist(result[0]); var el = result[0]; el.tagName.should.eql(tagName.toUpperCase()); el.id.should.eql(id); done(); }) it('should return multiple elements', done => { var tagName = "div", id = ['alpha', 'beta']; id.forEach( function( i ) { document.mockElement( { tagName: tagName, id: i } ); }); var result = document.getElementsByTagName(tagName); should.exist(result); result.should.have.lengthOf(2); should.exist(result[0]); should.exist(result[1]); result.forEach( function( el, ix ) { el.tagName.should.eql(tagName.toUpperCase()); el.id.should.eql(id[ix]); }); done(); }) }); <file_sep>/** Module: @mitchallen/mockbot-document Test: get-element-by-id-test Author: <NAME> */ "use strict"; var request = require('supertest'), should = require('should'), modulePath = "../modules/index"; describe('getElementById', () => { var _factory = null; before( done => { // Call before all tests done(); }); after( done => { // Call after all tests done(); }); beforeEach( done => { // Call before each test delete require.cache[require.resolve(modulePath)]; _factory = require(modulePath); global.document = _factory.create(); done(); }); afterEach( done => { // Call after each test delete global.document; done(); }); it('should exist', done => { should.exist(document.getElementById); done(); }) it('with no elements should return null', done => { var result = document.getElementById('foo'); should.not.exist(result); done(); }) it('for non-existant id should return null', done => { var tagName = "div", id = 'alpha'; // must have at least one other item document.mockElement( { tagName: tagName, id: id } ); var result = document.getElementById('foo'); should.not.exist(result); done(); }) it('for mocked element should return object', done => { var tagName = "div", id = 'alpha'; document.mockElement( { tagName: tagName, id: id } ); var result = document.getElementById(id); should.exist(result); done(); }) });
759b350710385d411c047df47ae521bd60848663
[ "JavaScript", "Markdown" ]
7
JavaScript
mitchallen/mockbot-document
e8f3cf675d683d5778038ec3b51e2f677439dbf3
ec32683ee3044a5397fdab11872b506b5e9c3bb7
refs/heads/master
<file_sep><?php return [ 'short_code' => env('GLOBE_SHORTCODE', '') ]; <file_sep><?php namespace Globe; use GuzzleHttp\Client; use Illuminate\Container\Container; use Illuminate\Foundation\Application as LaravelApplication; use Illuminate\Support\ServiceProvider; use Laravel\Lumen\Application as LumenApplication; class GlobeServiceProvider extends ServiceProvider { public function register() { $this->app->singleton('globe', function(Container $app) { $config = $app->make('config')->get('globe'); $short_code = $config['short_code']; $client = new Client([ 'base_uri' => 'https://devapi.globelabs.com.ph/smsmessaging/' . 'v1/outbound/' . $short_code . '/' ]); return new GlobeApi($client); }); } public function boot() { $source = realpath($raw = __DIR__.'/../config/globe.php') ?: $raw; if ($this->app instanceof LaravelApplication && $this->app->runningInConsole()) { $this->publishes([$source => config_path('globe.php')]); } elseif ($this->app instanceof LumenApplication) { $this->app->configure('globe'); } } } <file_sep># laravel-globelabs-api<file_sep><?php namespace Globe; use Illuminate\Support\Facades\Facade; class Globe extends Facade { protected static function getFacadeAccessor() { return 'globe'; } } <file_sep><?php namespace Globe; use Globe\Traits\Sms; use GuzzleHttp\Client; class GlobeApi { use Sms; protected $client; public function __construct(Client $client) { $this->client = $client; } } <file_sep><?php namespace Globe\Traits; trait Sms { protected function setPassphrase($passphrase) { $this->passphrase = $passphrase; } protected function setAppId($app_id) { $this->app_id = $app_id; } protected function setAppSecret($app_secret) { $this->app_secret = $app_secret; } public function setCredentials($passphrase, $app_id, $app_secret) { $this->setPassphrase($passphrase); $this->setAppId($app_id); $this->setAppSecret($app_secret); } public function getPassphrase() { if (isset($this->passphrase)) { return $this->passphrase; } else { throw new \Exception("Globe passphrase is not set"); } } public function getAppId() { if (isset($this->app_id)) { return $this->app_id; } else { throw new \Exception("Globe app_id is not set"); } } public function getAppSecret() { if (isset($this->app_secret)) { return $this->app_secret; } else { throw new \Exception("Globe app_secret is not set"); } } protected function getCredentials() { $this->getPassphrase(); $this->getAppId(); $this->getAppSecret(); } public function send($number, $message) { $this->getCredentials(); $url = '/requests/'; $params = [ 'form_params' => [ 'address' => $number, 'message' => $message, 'passphrase' => $<PASSWORD>, 'app_id' => $this->app_id, 'app_secret' => $this->app_secret ] ]; $response = $this->client->post($url, $params); return $response->getBody(); } }
272cb1922e3759786aa47a7fb82dbb7e078c4fd2
[ "Markdown", "PHP" ]
6
PHP
kpdcdg/laravel-globelabs-api
870871ab12d10091d4c8619c1cc4d114d9815d58
62065009f1961da5b01d2eb1edf48ca769fdc2b1
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package insa.client; import insa.db.UserAccount; import insa.ws.UserAccountWS; import insa.ws.UserProfileWS; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author prmm95 */ @WebServlet(name = "DeleteAccount", urlPatterns = {"/DeleteAccount"}) public class DeleteAccount extends HttpServlet { private static UserAccountWS userAccountService = new insa.ws.UserAccountWS(); private static UserProfileWS userProfileService = new insa.ws.UserProfileWS(); /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet DeleteAccount</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet DeleteAccount at " + request.getContextPath() + "</h1>"); out.println("</body>"); out.println("</html>"); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { UserAccount ua = userProfileService.getUserAccountByLogin(request.getParameter("login")); String userCategory = ua.getUserCategory(); if(userCategory.compareTo("Student")==0){ request.setAttribute("userType","Student"); } else if (userCategory.compareTo("Company")==0) { request.setAttribute("userType","Company"); } else if (userCategory.compareTo("INSA Staff")==0){ request.setAttribute("userType","INSA Staff"); } this.getServletContext().getRequestDispatcher("/WEB-INF/jsp/DeleteAccount.jsp").forward(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Search for the UserAccount to Delete: long idOfUserToDelete = userProfileService.getUserAccountByLogin(request.getParameter("login")).getId(); // Delete the UserAccount and the UserProfile: userProfileService.deleteUserAccountById(idOfUserToDelete); // Redirect to the login page: this.getServletContext().getRequestDispatcher("/WEB-INF/jsp/Login.jsp").forward(request, response); // Session? } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package insa.bus; import insa.client.Search; import insa.db.Category; import insa.db.Company; import insa.db.Internship; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.json.JSONException; import org.json.JSONObject; /** * * @author zaurelzo */ public class BusResultTreatment { private String busResult; public BusResultTreatment(String busResult) { this.busResult=busResult; } public List<Internship> getListOfInternship() throws JSONException { try { List<Internship> internshipList = new ArrayList<Internship>(); JSONObject jObjectWithInternshipResult = new JSONObject(this.busResult.substring(1, this.busResult.length()-1)); // json //System.out.println("////////////// 1st conversion worked "); for (int a= 0 ; a < jObjectWithInternshipResult.length();a++) { Integer ind = new Integer(a); String oneInternship = jObjectWithInternshipResult.getString(ind.toString()); //System.out.println("***********************" + oneInternship); //System.out.println("**********************************************"); //convert current intership to json JSONObject AnInternshipJsonObject = new JSONObject(oneInternship); String name = AnInternshipJsonObject.getString("name"); String pdfPath= AnInternshipJsonObject.getString("pdfPath"); String description= AnInternshipJsonObject.getString("description"); Long category_id = new Long (AnInternshipJsonObject.getString("category_id")); String category_name = AnInternshipJsonObject.getString("category_name"); Category cat = new Category(category_name); Company com = new Company(); com.setName(AnInternshipJsonObject.getString("company")); cat.setId(category_id); // also get company information (not pass a null object to the function) Internship internshipToAdd = new Internship(name, pdfPath, description, com, cat); internshipList.add(internshipToAdd); //System.out.println("***************** THE CONVERSION WORKED" ); } return internshipList; } catch (JSONException ex) { throw ex; } } } <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- import pymysql listTables = ['UserAccount', 'Internship', 'Company', 'Category', 'UserProfile'] #userAccount = { # 'name':'user', # 'password' : '<PASSWORD>', # 'mail' : '<EMAIL>' #} userProfile = { 'firstName':'fname', 'lastName' : 'lname', 'mail' : '<EMAIL>', 'phone' : '0494668842', 'cvPath' : '/home/file.pdf' } class databaseManager: def __init__(self,dbName): self.conn = pymysql.connect(host="localhost",user="root",password="<PASSWORD>", database=dbName) self.cursor = self.conn.cursor() def emptyDatase(self): try: for table in listTables: self.cursor.execute(""" delete from %s; """ % (table)) self.conn.commit() except Exception as e: print str(e) self.conn.rollback() def addUserAccount(self,name,password,mail,userCategory,id_profile_id=None): try: if id_profile_id==None: self.cursor.execute(""" INSERT INTO UserAccount (login, password, mail,userCategory) VALUES ('%s', '%s', '%s','%s'); """ % (name, password,mail,userCategory)) else: self.cursor.execute(""" INSERT INTO UserAccount (login, password, mail,userCategory,id_profile_id) VALUES ('%s','%s' ,'%s', '%s','%s'); """ % (name, password,mail,userCategory,id_profile_id)) self.conn.commit() except Exception as e: print str(e) self.conn.rollback() def addUserProfile(self,firstName,lastName,mail,phone,cvPath): try: self.cursor.execute(""" INSERT INTO UserProfile (firstName, lastName, mail, phone, cvPath) VALUES ('%s', '%s', '%s', '%s', '%s'); """ % (firstName,lastName,mail, phone, cvPath)) self.conn.commit() except Exception as e: print str(e) self.conn.rollback() def getIdProfile(self,firstName,lastName): try: self.cursor.execute("""SELECT id FROM UserProfile WHERE firstName ='%s' AND lastName ='%s'""" % (firstName, lastName)) result = self.cursor.fetchone() if result is not None: return result[0] else: return -1#si erreur except Exception as e: print str(e) return -1#si erreur def addListOfInterships(self,listOfinternships): try: for internship in listOfinternships: self.cursor.execute(""" INSERT INTO Internship (name, pdfPath, description,id_category_id) VALUES ('%s','%s', '%s', '%s'); """ % (internship[0],internship[1],internship[2],str(internship[3]))) self.conn.commit() except Exception as e: print str(e) self.conn.rollback() def addCategories(self,listOfCategories): try: for cat in listOfCategories: self.cursor.execute(""" INSERT INTO Category (name) VALUES ('%s'); """ % (cat)) self.conn.commit() except Exception as e: print str(e) self.conn.rollback() def getCategoryId(self,name): try: self.cursor.execute("""SELECT id FROM Category WHERE name ='%s' """ % (name)) result = self.cursor.fetchone() if result is not None: return result[0] else: return -1#si erreur except Exception as e: print str(e) return -1#si erreur if __name__ == '__main__': d1= databaseManager("imanage") d1.emptyDatase() #======================================================================== #new account (test create account already exist) d1.addUserAccount("user","passwd","<EMAIL>","Student") #======================================================================== #new profile(test create profile already exist) d1.addUserProfile("Steve", "Job", "<EMAIL>", "0614008530", "home/apple.pdf") #======================================================================== #account to delete (test delete account already exist) d1.addUserAccount("ichigo","bleach","<EMAIL>","Student") #======================================================================== #profile to delete, must be link to accound (test delete profile already exist) d1.addUserProfile("BelleFontaine","fred","<EMAIL>","0494668842","/home/fredcv.pdf") id_profile = d1.getIdProfile("BelleFontaine","fred") d1.addUserAccount("BelleFontaine","<EMAIL>","popoye","Student",id_profile) #======================================================================== #add some categories listOfCategories=["informatique","biologie"] d1.addCategories(listOfCategories) idInfo= d1.getCategoryId("informatique") idBio = d1.getCategoryId("biologie") #add some internships listOfinternships = [("prototype application critique","/home/appCritique.pdf","entreprise a taille humaine cherche petit stagiaire",idInfo),\ ("developpement web services","/home/webServiveces","expert SOA qui doit travailler dur",idInfo),\ ("developpement Objet connecte","/home/iot.pdf","prototype toilettes connectees",idInfo),\ ('amelioration nouvelle enzyme',"/home/enzyme.pdf","amelioration process developpement enzyme",idBio)] d1.addListOfInterships(listOfinternships)<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 insa.ws; import insa.db.Internship; import insa.db.Candidature; import insa.db.Category; import insa.db.Company; import insa.db.UserAccount; import insa.metier.IMetier; import java.util.List; import javax.jws.WebService; import javax.jws.WebMethod; import javax.jws.WebParam; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * * @author prmm95 */ @WebService(serviceName = "CandidaturesWS") public class CandidatureWS { private IMetier metier; public CandidatureWS() { ApplicationContext ap = new ClassPathXmlApplicationContext("../../WEB-INF/applicationContext.xml"); metier = (IMetier)ap.getBean("metier"); } /** * This is a sample web service operation */ @WebMethod(operationName = "hello") public String hello(@WebParam(name = "name") String txt) { return "Hello " + txt + " !"; } /** * Web service operation * @param title * @param message * @return */ @WebMethod(operationName = "createCandidature") public Candidature createCandidature(@WebParam(name="candTitle") String title, @WebParam(name="candMessage") String message, @WebParam(name="coverLetterPath") String coverLetterPath,@WebParam(name="offer_name") String offer_name) { return metier.createCandidature(title,message,coverLetterPath,offer_name); } /** * Web service operation */ @WebMethod(operationName = "deleteCandidature") public Boolean deleteCandidature(@WebParam(name = "cand_id") long cand_id) { return metier.deleteCandidatureById(cand_id); } // @WebMethod(operationName = "linkOfferToCandidature") // public Candidature linkOfferToCandidature(@WebParam(name="cand_id") long cand_id, @WebParam(name="offer") Internship offer) { // return metier.linkOfferToCandidature(cand_id,offer); // } @WebMethod(operationName = "linkUserToCandidature") public Candidature linkUserToCandidature(@WebParam(name="cand_id") long cand_id, @WebParam(name="userAccount") UserAccount userAccount){ return metier.linkUserToCandidature(cand_id,userAccount); } @WebMethod(operationName = "linkCompanyToCandidature") public Candidature linkCompanyToCandidature(@WebParam(name="cand_id") long cand_id, @WebParam(name="company") Company company) { return metier.linkCompanyToCandidature(cand_id,company); } public List<Candidature> getCandidaturesByUserID(long user_id) { return metier.getCandidaturesByUserID(user_id); } public List<Candidature> getCandidaturesByOfferName(String offer_name) { return metier.getCandidaturesByOfferName(offer_name); } /** * Web service operation */ @WebMethod(operationName = "getCandidatureById") public Candidature getCandidatureById(@WebParam(name="cand_id") long cand_id) { return metier.getCandidatureById(cand_id); } /** * Web service operation */ @WebMethod(operationName = "updateCandidature") public Candidature updateCandidature(@WebParam(name="candidature") Candidature candidature) { return metier.updateCandidature(candidature); } public List<Candidature> getCandidaturesByCategory(Category category) { return metier.getCandidaturesByCategory(category); } } <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- import pymysql listTables = ['UserAccount', 'Internship', 'Company', 'Category', 'UserProfile'] userAccount = { 'name':'user', 'password' : '<PASSWORD>', 'mail' : '<EMAIL>' } userProfile = { 'firstName':'fname', 'lastName' : 'lname', 'mail' : '<EMAIL>', 'phone' : '0494668842', 'cvPath' : '/home/file.pdf' } class databaseManager: def __init__(self): self.conn = pymysql.connect(host="localhost",user="root",password="<PASSWORD>", database="imanage") self.cursor = self.conn.cursor() def emptyDatase(self): try: for table in listTables: self.cursor.execute(""" delete from %s; """ % (table)) self.conn.commit() except Exception as e: print str(e) self.conn.rollback() def addUserAccount(self): try: self.cursor.execute(""" INSERT INTO UserAccount (login, password, mail) VALUES ('%s', '%s', '%s'); """ % (userAccount['name'], userAccount['password'], userAccount['mail'])) self.conn.commit() except Exception as e: print str(e) self.conn.rollback() def addUserProfile(self): try: self.cursor.execute(""" INSERT INTO UserProfile (firstName, lastName, mail, phone, cvPath) VALUES ('%s', '%s', '%s', '%s', '%s'); """ % (userProfile['firstName'], userProfile['lastName'], userProfile['mail'], userProfile['phone'], userProfile['cvPath'])) self.conn.commit() except Exception as e: print str(e) self.conn.rollback() if __name__ == '__main__': d1= databaseManager() d1.emptyDatase() d1.addUserAccount() d1.addUserProfile()<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 insa.metier; import insa.dao.IDao; import insa.db.*; import java.util.List; /** * * @author Halim */ public class MetierImpl implements IMetier { private IDao dao; public IDao getDao() { return dao; } public void setDao(IDao dao) { this.dao = dao; } @Override public List<Internship> searchInternship() { List<Internship> list = dao.getAllInternships(); return list; } @Override public List<Category> getCategories() { List<Category> list = dao.getAllCategories(); return list; } @Override public List<Internship> getInternshipByCriteria(String category, String keywords) { List<Internship> list = dao.getInternshipByCategoryNameWhereTitleContains(category, keywords); return list; } @Override public Boolean deleteInternshipById(long offer_id) { return dao.deleteInternshipById(offer_id); } @Override public Internship getInternshipByID(long id) { return dao.getInternshipById(id); } } <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 insa.metier; import insa.db.Candidature; import insa.db.Category; import insa.db.Company; import insa.db.Internship; import insa.db.Message; import insa.db.UserProfile; import insa.db.UserAccount; import java.util.Collection; import java.util.Date; import java.util.List; /** * * @author Halim */ public interface IMetier { // User accounts: public UserAccount getUserAccountByLogin(String login); public UserAccount verifyUserAccount(String login, String password); public UserAccount addUserAccount(String login , String mail , String password, String userCategory); public UserAccount deleteUserAccountById(Long id); public UserAccount getUserAccountByEmail(String mail); public List<UserAccount> getAllUserAccount(); // User profiles: public UserProfile getUserProfileById(Long id); public UserProfile getUserProfileUsingAccountLogin(String login); public UserProfile addUserProfile(String firstName, String lastName, String mail, String phone, String cvPath); public UserAccount linkUserProfile(String login, UserProfile up); public UserProfile deleteUserProfile(Long id); public UserProfile updateUserProfile(UserProfile userProfile); public List<Internship> searchInternship(); public List<Category> getCategories(); public List<Company> getCompanies(); public List<Internship> getInternshipByCriteria(String company, String category, String keywords); // Candidatures: public Candidature getCandidatureById(Long id); public Candidature createCandidature(String title, String message, String coverLetterPath, String offer_name); public Boolean deleteCandidatureById(Long id); public Candidature updateCandidature(Candidature candidature); //public Candidature linkOfferToCandidature(long candID, Internship offer); public Candidature linkUserToCandidature(long cand_id,UserAccount userAccount); public Candidature linkCompanyToCandidature(long cand_id,Company company); public List<Candidature> getCandidaturesByUserID(long user_id); public List<Candidature> getCandidaturesByOfferName(String offer_name); // Internships: public Internship getInternshipByID(long id); // public Boolean deleteInternshipByID(Long id); public Boolean deleteInternshipById(long offer_id); // Messages: public Message getMessageById(Long id); public Message addMessage(String object, String content, Date date, Boolean read); public Message deleteMessageById(Long id); public Message updateMessage(String object, String content, Date date, Boolean read); public List<Message> searchMessage(UserAccount ua); public Message linkUserAccountSender(UserAccount ua, Long id); public Message linkUserAccountListRecipients(Collection<UserAccount> list, Long id); public List<Message> searchSentMessages(Long id); public List<UserAccount> getAllReceiverAccount(Message message); public Message updateReadMessage(Long id); // Companies and categories: public Company addCompanyProfile(String name, String phone, String mail, String address); public UserAccount linkCompanyProfile(String login, Company comp); public Company deleteCompanyProfile(Long id); public Company getCompanyById(Long id); public Company updateCompany(Company company); public Company getCompanyByName(String company_name); // Candidatures: //public Candidature getCandidatureById(Long id); //public Candidature addCandidature(Candidature candidature); //public Candidature deleteCandidatureById(Long id); //public Candidature updateCandidature(Candidature candidature); // Companies and categories: //public UserAccount linkCompanyProfile(String login, Company comp); //public Company deleteCompanyProfile(Long id); //public Company getCompanyById(Long id); //public Company updateCompany(Company company); public List<Candidature> getCandidaturesByCategory(Category category); } <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 insa.client; import insa.db.Candidature; import insa.db.Company; import insa.db.UserAccount; import insa.ws.InternshipWS; import insa.ws.CandidatureWS; import insa.ws.UserProfileWS; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author prmm95 */ @WebServlet(name = "SendCandidature", urlPatterns = {"/SendCandidature"}) public class SendCandidature extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ private static InternshipWS internshipService = new insa.ws.InternshipWS(); private static CandidatureWS candidatureService = new insa.ws.CandidatureWS(); private static UserProfileWS userProfileService = new insa.ws.UserProfileWS(); protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet SendCandidature</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet SendCandidature at " + request.getContextPath() + "</h1>"); out.println("</body>"); out.println("</html>"); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("offer_name",request.getParameter("offer_name")); request.setAttribute("company_name",request.getParameter("company_name")); request.setAttribute("login",request.getParameter("login")); this.getServletContext().getRequestDispatcher("/WEB-INF/jsp/SendCandidature.jsp").forward(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { UserAccount ua = userProfileService.getUserAccountByLogin(request.getParameter("login")); String userCategory = ua.getUserCategory(); if(userCategory.compareTo("Student")==0){ request.setAttribute("student","true"); } else { request.setAttribute("student","false"); } // Parameters: String login = request.getParameter("login"); long user_id = ua.getId(); String candTitle = request.getParameter("title"); String candMessage = request.getParameter("message"); String offer_name = request.getParameter("offer_name"); String company_name = request.getParameter("company_name"); // TODO: Verify if a file was sent // TODO: Save the file on the correct path String coverLetterPath = "/Users/jordycabannes/Desktop/iManage/web/Web-content/pdf/internshipOffer/Offre1.pdf"; // + login + "/" + offer_id + ".pdf"; Candidature candidature = candidatureService.createCandidature(candTitle,candMessage,coverLetterPath,offer_name); // Link candidature with the respective user: UserAccount userAccount = userProfileService.getUserAccountByLogin(login); candidatureService.linkUserToCandidature(candidature.getId(),userAccount); // Link candidature with the respective company: Company company = userProfileService.getCompanyByName(company_name); candidatureService.linkCompanyToCandidature(candidature.getId(),company); // Redirect to Candidatures view: request.setAttribute("login",login); request.setAttribute("candidatureList",candidatureService.getCandidaturesByUserID(user_id)); request.setAttribute("deletedCand",false); this.getServletContext().getRequestDispatcher("/WEB-INF/jsp/Candidatures.jsp").forward(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package insa.client; import insa.bus.BusResultTreatment; import insa.db.Candidature; import insa.db.Company; import insa.db.Internship; import insa.db.UserAccount; import insa.ws.CandidatureWS; import insa.ws.InternshipWS; import insa.ws.UserAccountWS; import insa.ws.UserProfileWS; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import insa.bus.httpWrapper; import insa.db.Category; import java.io.PrintWriter; import java.net.URL; import java.lang.String; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.Logger; import static javax.ws.rs.core.HttpHeaders.USER_AGENT; import org.*; import org.json.JSONException; import org.json.JSONObject; /** * * @author paul */ @WebServlet(name = "Search", urlPatterns = {"/Search"}) public class Search extends HttpServlet { private static UserAccountWS userAccountService = new insa.ws.UserAccountWS() ; private static UserProfileWS userProfileService = new insa.ws.UserProfileWS() ; private static InternshipWS InternshipService = new InternshipWS() ; private static CandidatureWS candidatureService = new insa.ws.CandidatureWS(); /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet EditOffer</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet EditOffer at " + request.getContextPath() + "</h1>"); out.println("</body>"); out.println("</html>"); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String url = "http://localhost:11223/getInternship"; Map<String,String[]> mapRequestParameters = new HashMap<String,String[]>(); mapRequestParameters.put("selectCompany",new String[]{"All"}); mapRequestParameters.put("selectCategory",new String[]{"All"}); mapRequestParameters.put("keywords",new String[]{""}); httpWrapper httpW = new httpWrapper(url, mapRequestParameters); //received json object with internship information (from zato) String httpRes = httpW.sendRequest() ; BusResultTreatment thebusResultTreatment = new BusResultTreatment(httpRes); response.setContentType("text/html"); String login = request.getParameter("login"); long user_id = userProfileService.getUserAccountByLogin(login).getId(); List<Internship> internshipList = thebusResultTreatment.getListOfInternship(); List<Candidature> candidatureList = candidatureService.getCandidaturesByUserID(user_id); Iterator<Internship> iOffer = internshipList.iterator(); Iterator<Candidature> iCandidature = candidatureList.iterator(); // Delete candidatures from the list where there is a Candidature sent // from the current student: while (iCandidature.hasNext()) { Candidature currentCandidature = iCandidature.next(); while (iOffer.hasNext()) { Internship currentOffer = iOffer.next(); if (currentOffer.getName().replaceAll(" ","").equalsIgnoreCase(currentCandidature.getOffer_name().replaceAll(" ",""))) { iOffer.remove(); iCandidature.remove(); break; } } } request.setAttribute("internshipList",internshipList); request.setAttribute("companyList", InternshipService.getCompanies()); request.setAttribute("categoryList", InternshipService.getCategories()); UserAccount ua = userProfileService.getUserAccountByLogin(request.getParameter("login")); if(ua==null){ System.out.println("////////////ua est null"); } else{ System.out.println("////////////ua n'est pas null"); } System.out.println("---------------- valeur du login en haut : "+request.getParameter("login")); System.out.println("---------------- valeur du login : " +ua.getLogin()); System.out.println("---------------- valeur de category : " +ua.getUserCategory()); String userCategory = ua.getUserCategory(); if(userCategory.compareTo("Student")==0){ request.setAttribute("userType","Student"); } else if (userCategory.compareTo("Company")==0) { request.setAttribute("userType","Company"); } else if (userCategory.compareTo("INSA Staff")==0){ request.setAttribute("userType","INSA Staff"); } this.getServletContext().getRequestDispatcher("/WEB-INF/jsp/Search.jsp").forward(request, response); } catch (JSONException ex) { System.out.println("+++++++++++++++++++++++++++++++++++++++ ERROR "); //System.out.println("******************************************"); Logger.getLogger(Search.class.getName()).log(Level.SEVERE, null, ex); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String url = "http://localhost:11223/getInternship"; httpWrapper httpW = new httpWrapper(url, request.getParameterMap()); //received json object with internship information (from zato) String httpRes = httpW.sendRequest() ; BusResultTreatment thebusResultTreatment = new BusResultTreatment(httpRes); response.setContentType("text/html"); String login = request.getParameter("login"); long user_id = userProfileService.getUserAccountByLogin(login).getId(); UserAccount ua = userProfileService.getUserAccountByLogin(request.getParameter("login")); String userCategory = ua.getUserCategory(); if(userCategory.compareTo("Student")==0){ request.setAttribute("userType","Student"); } else if (userCategory.compareTo("Company")==0) { request.setAttribute("userType","Company"); } else if (userCategory.compareTo("INSA Staff")==0){ request.setAttribute("userType","INSA Staff"); } request.setAttribute("companyList", InternshipService.getCompanies()); request.setAttribute("categoryList", InternshipService.getCategories()); String keywords = new String(request.getParameter("keywords").getBytes(),"UTF-8"); byte[] bytesKeyW = keywords.getBytes(StandardCharsets.ISO_8859_1); keywords = new String(bytesKeyW, StandardCharsets.UTF_8); String company = new String(request.getParameter("selectCompany").getBytes(),"UTF-8"); byte[] bytesComp = company.getBytes(StandardCharsets.ISO_8859_1); company = new String(bytesComp, StandardCharsets.UTF_8); String category = new String(request.getParameter("selectCategory").getBytes(),"UTF-8"); byte[] bytesCat = category.getBytes(StandardCharsets.ISO_8859_1); category = new String(bytesCat, StandardCharsets.UTF_8); //let rebuild the internship list using the received json object //List<Internship> internshipList = InternshipService.getInternshipByCriteria(company, category, keywords); List<Internship> internshipList= thebusResultTreatment.getListOfInternship(); List<Candidature> candidatureList = candidatureService.getCandidaturesByUserID(user_id); Iterator<Internship> iOffer = internshipList.iterator(); Iterator<Candidature> iCandidature = candidatureList.iterator(); // Delete candidatures from the list where there is a Candidature sent // from the current student: while (iCandidature.hasNext()) { Candidature currentCandidature = iCandidature.next(); while (iOffer.hasNext()) { Internship currentOffer = iOffer.next(); if (currentOffer.getName().replaceAll(" ","").equalsIgnoreCase(currentCandidature.getOffer_name().replaceAll(" ",""))) { iOffer.remove(); iCandidature.remove(); break; } } } request.setAttribute("keywords", keywords.toUpperCase()); if (company.equals("All")) request.setAttribute("company", "ALL COMPANIES"); else request.setAttribute("company", company.toUpperCase()); if (category.equals("All")) request.setAttribute("category", "ALL CATEGORIES"); else request.setAttribute("category", category.toUpperCase()); request.setAttribute("test", "keywords: " + keywords + "\tcompany: " + company + "\tcategory: " + category); //request.setAttribute("internshipList",internshipList); request.setAttribute("internshipList", internshipList); this.getServletContext().getRequestDispatcher("/WEB-INF/jsp/Search.jsp").forward(request, response); } catch (JSONException ex) { System.out.println("+++++++++++++++++++++++++++++++++++++++ ERROR "); //System.out.println("******************************************"); Logger.getLogger(Search.class.getName()).log(Level.SEVERE, null, ex); } } } <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- import json from zato.server.service import Service class GetInternshipDetails(Service): def handle(self): try: self.logger.info('Request: {}'.format(self.request.payload)) with self.outgoing.soap.get('getInternshipWebService1').conn.client() as companyA: with self.outgoing.soap.get('getInternshipWebService2').conn.client() as companyB: company=self.request.payload["selectCompany"] category=self.request.payload["selectCategory"] keywords=self.request.payload["keywords"] self.logger.info("********* company : " + company +" category :"+ category + " keywords :" + keywords) #permet de savoir si on a envoyé une requête à l'entreprise A RequestedEntrepriseA=0 ListInternshipCompA=[] if company=="entreprisea" or company=="All": ListInternshipCompA=companyA.service.getInternshipByCriteria(category,keywords) self.logger.info("================ result company A : " + str (ListInternshipCompA) + " "+str(type(ListInternshipCompA))) RequestedEntrepriseA=len(ListInternshipCompA) ListInternshipCompB=[] if company=="entrepriseb" or company=="All": ListInternshipCompB=companyB.service.getInternshipByCriteria(category,keywords) self.logger.info("================ result company B : " + str (ListInternshipCompB) + " "+str(type(ListInternshipCompB))) # #let's build the final response finalResponse = {} for ind, internship in enumerate(ListInternshipCompA): finalResponse[str(ind)]={"description":str(internship.description),"elementId":str(internship.id),\ "category_id":str(internship.id_category.id),"category_name":str(internship.id_category.name),\ "name":str(internship.name),"pdfPath":str(internship.pdfPath),"company":"entreprisea"} #self.logger.info("////////////////////type of internship " + str(internship.id_category.name)) for ind, internship in enumerate(ListInternshipCompB): finalResponse[str(ind+RequestedEntrepriseA)]={"description":str(internship.description),"elementId":str(internship.id),\ "category_id":str(internship.id_category.id),"category_name":str(internship.id_category.name),\ "name":str(internship.name),"pdfPath":str(internship.pdfPath),"company":"entrepriseb"} ##return response to the caller self.response.payload="\""+str(finalResponse)+"\"" except Exception as e: self.logger.info("++++++++++++++++ ERROR : " +str(e)) <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- import pymysql listTables = ['Internship', 'Category'] class databaseManager: def __init__(self,dbName): self.conn = pymysql.connect(host="localhost",user="root",password="<PASSWORD>", database=dbName) self.cursor = self.conn.cursor() def emptyDatase(self): try: for table in listTables: self.cursor.execute(""" delete from %s; """ % (table)) self.conn.commit() except Exception as e: print str(e) self.conn.rollback() def addListOfInterships(self,listOfinternships): try: for internship in listOfinternships: self.cursor.execute(""" INSERT INTO Internship (name, pdfPath, description,id_category_id) VALUES ('%s','%s', '%s', '%s'); """ % (internship[0],internship[1],internship[2],str(internship[3]))) self.conn.commit() except Exception as e: print str(e) self.conn.rollback() def addCategories(self,listOfCategories): try: for cat in listOfCategories: self.cursor.execute(""" INSERT INTO Category (name) VALUES ('%s'); """ % (cat)) self.conn.commit() except Exception as e: print str(e) self.conn.rollback() def getCategoryId(self,name): try: self.cursor.execute("""SELECT id FROM Category WHERE name ='%s' """ % (name)) result = self.cursor.fetchone() if result is not None: return result[0] else: return -1#si erreur except Exception as e: print str(e) return -1#si erreur if __name__ == '__main__': d1= databaseManager("entreprisea") d1.emptyDatase() #add some categories listOfCategories=["informatique","biologie"] d1.addCategories(listOfCategories) idInfo= d1.getCategoryId("informatique") idBio = d1.getCategoryId("biologie") #add some internships listOfinternships = [ ( "Stage de fin detudes - INGENIEUR - Java J2EE / Agile Lyon", "/home/appCritique.pdf", "Vous etes passione(e) de technologies et vous avez envie de vous investir dans une equipe et un projet. \n Vous etes une \ personne rigoureuse et autonome, et etes force de proposition. \n Nous vous proposons de decouvrir notre approche.", idInfo), ( "Stagiaire Java JEE", "/home/webServiveces", "Votre mission consistera a intervenir sur les phases de conception techique, developpement, tests et recettes dapplications \ developpees au forfait.", idInfo), ( "Stage Developpement Web/Mobile H/F", "/home/iot.pdf", "Au sein dune equipe de 7 personnes directement en contact avec le client, vous participerez au developpement dune application \ cross-platform sur des technologies innovantes.", idInfo), ( 'Amelioration process enzyme de la life qui tue', "/home/enzyme.pdf", "amelioration process developpement enzyme de la life", idBio) ] d1.addListOfInterships(listOfinternships)<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 insa.utils; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import java.util.*; /** * * @author Halim */ public class HibernateManager { private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public Long addObjectToDatabase(Object o) { Long res = null; try { Session s = sessionFactory.openSession(); try { Transaction tx = s.beginTransaction(); res = (Long)s.save(o); tx.commit(); } catch(Exception e) { res = null; } finally { s.close(); } } catch(HibernateException e) { res = null; } finally { } return res; } public boolean updateObjectInDatabase(Object o) { boolean res = true; try { Session s = sessionFactory.openSession(); try { Transaction tx = s.beginTransaction(); s.update(o); tx.commit(); } catch(Exception e) { res = false; } finally { s.close(); } } catch(HibernateException e) { res = false; } finally { } return res; } public <T> T getObjectFromDatabase(Class<T> type, Long id) { Object res = null; try { Session s = sessionFactory.openSession(); try { Transaction tx = s.beginTransaction(); res = s.get(type, id); tx.commit(); } catch(Exception e) { res = null; } finally { s.close(); } } catch(HibernateException e) { res = null; } finally { } return (T)res; } public boolean deleteObjectFromDatabase(Object o) { boolean res = true; try { Session s = sessionFactory.openSession(); try { Transaction tx = s.beginTransaction(); s.delete(o); tx.commit(); } catch(Exception e) { res = false; } finally { s.close(); } } catch(HibernateException e) { res = false; } finally { } return res; } public <T> List<T> execute(String sQuery, HashMap<String, Object> params, Class<T> type) { Session s = sessionFactory.openSession(); List<T> list = null; try { Query query = s.createQuery(sQuery); Set<String> set = params.keySet(); Iterator<String> it = set.iterator(); System.out.println("----------- Happy"); while(it.hasNext()) { String key = it.next(); System.out.println("----------- valeur de la clé : "+key); Object param = params.get(key); query.setParameter(key, param); } System.out.println(query.toString()); list = query.list(); } catch(HibernateException e) { System.out.println("----------- Exception : "+ e.toString()); list = null; } finally { s.close(); } return list; } public <T> List<T> execute(String sQuery, Class<T> type) { return this.execute(sQuery, new HashMap<String, Object>(), type); } } <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 insa.db; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.PrimaryKeyJoinColumn; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; /** * * @author Halim */ @Entity public class UserProfile implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotNull private String lastName; @NotNull private String firstName; @NotNull @Column(columnDefinition="char(10)",unique=true) @Pattern(regexp="[0-9]{10}") private String phone; @NotNull @Pattern(regexp="[0-9A-Za-z_]+[@][0-9A-Za-z_]+[.][0-9A-Za-z_]+") @Column(unique=true) private String mail; @Column private String cvPath; public UserProfile() {} public UserProfile(String lastName, String firstName, String phone, String mail, String cvPath) { this.lastName = lastName; this.firstName = firstName; this.phone = phone; this.mail = mail; this.cvPath = cvPath; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getMail() { return mail; } public void setMail(String mail) { this.mail = mail; } public String getCvPath() { return cvPath; } public void setCvPath(String cvPath) { this.cvPath = cvPath; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof UserProfile)) { return false; } UserProfile other = (UserProfile) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } } <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 insa.ws; import insa.dao.IDao; import insa.db.Company; import insa.db.UserAccount; import insa.db.UserProfile; import insa.metier.IMetier; import insa.metier.MetierImpl; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; import javax.ws.rs.Produces; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PUT; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import insa.models.AddUserAccountRequest; import insa.models.LinkCompanyProfileRequest; import insa.models.LinkUserProfileRequest; import java.util.List; import javax.ws.rs.PathParam; /** * REST Web Service * * @author Halim */ @Path("Accounts") @Produces(MediaType.APPLICATION_JSON) public class UserAccountWS { @Context private UriInfo context; private IMetier metier; /** * Creates a new instance of AccountsResource */ public UserAccountWS() { ApplicationContext ap = new ClassPathXmlApplicationContext("../../WEB-INF/applicationContext.xml"); metier = (IMetier)ap.getBean("metier"); } @POST @Consumes(MediaType.APPLICATION_JSON) @Path("/account") public UserAccount addUserAccount(AddUserAccountRequest request) { //TODO write your implementation code here: return metier.addUserAccount(request.getLogin(), request.getMail(), request.getPassword(), request.getUserCategory()); } @GET @Path("/login") public UserAccount getUserAccountByLogin(@QueryParam("login") String login) { return metier.getUserAccountByLogin(login); } @GET @Path("/mail") public UserAccount getUserAccountByEmail(@QueryParam("mail") String mail) { return metier.getUserAccountByEmail(mail); } @GET @Path("/verify") public UserAccount verifyUserAccount(@QueryParam("login") String login, @QueryParam("password") String password) { //TODO write your implementation code here: return metier.verifyUserAccount(login, password); } @GET @Path("/accounts") public List<UserAccount> getAllUserAccount(){ return metier.getAllUserAccount(); } @POST @Consumes(MediaType.APPLICATION_JSON) @Path("/link/userProfile") public UserAccount linkUserProfile(LinkUserProfileRequest request) { //TODO write your implementation code here: return metier.linkUserProfile(request.getLogin(), request.getUserProfile()); } @POST @Consumes(MediaType.APPLICATION_JSON) @Path("/link/company") public UserAccount linkCompanyProfile(LinkCompanyProfileRequest request) { //TODO write your implementation code here: return metier.linkCompanyProfile(request.getLogin(), request.getCompany()); } @GET @Path("/link/password") public UserAccount linkPassword(@QueryParam("login") String login, @QueryParam("mail") String mail) { return metier.getUserAccountByLogin(login); } } <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 insa.dao; import insa.db.*; import java.util.List; /** * * @author Halim */ public interface IDao { // Internships: public Internship getInternshipById(Long id); public List<Internship> getInternshipByCategory(Category category); public List<Internship> getInternshipByCategoryName(String name); public List<Internship> getInternshipByCategoryNameWhereTitleContains(String categoryName, String keywords); public Internship addInternship(Internship internship); public Boolean deleteInternshipById(Long id); public Internship updateInternship(Internship internship); public List<Internship> getAllInternships(); //Categories : public Category getCategoryById(Long id); public Category getCategoryByName(String name); public Category addCategory(Category category); public Category deleteCategoryById(Long id); public Category updateCategory(Category category); public List<Category> getAllCategories(); } <file_sep>#!/bin/bash python databaseIcompany2.py python databaseIcompany.py python databaseImanage.py<file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- import pymysql listTables = ['Internship', 'Category'] class databaseManager: def __init__(self,dbName): self.conn = pymysql.connect(host="localhost",user="root",password="<PASSWORD>", database=dbName) self.cursor = self.conn.cursor() def emptyDatase(self): try: for table in listTables: self.cursor.execute(""" delete from %s; """ % (table)) self.conn.commit() except Exception as e: print str(e) self.conn.rollback() def addListOfInterships(self,listOfinternships): try: for internship in listOfinternships: self.cursor.execute(""" INSERT INTO Internship (name, pdfPath, description,id_category_id) VALUES ('%s','%s', '%s', '%s'); """ % (internship[0],internship[1],internship[2],str(internship[3]))) self.conn.commit() except Exception as e: print str(e) self.conn.rollback() def addCategories(self,listOfCategories): try: for cat in listOfCategories: self.cursor.execute(""" INSERT INTO Category (name) VALUES ('%s'); """ % (cat)) self.conn.commit() except Exception as e: print str(e) self.conn.rollback() def getCategoryId(self,name): try: self.cursor.execute("""SELECT id FROM Category WHERE name ='%s' """ % (name)) result = self.cursor.fetchone() if result is not None: return result[0] else: return -1#si erreur except Exception as e: print str(e) return -1#si erreur if __name__ == '__main__': d1= databaseManager("entrepriseb") d1.emptyDatase() #add some categories listOfCategories=["informatique","biologie","genie civil"] d1.addCategories(listOfCategories) idInfo= d1.getCategoryId("informatique") idBio = d1.getCategoryId("biologie") idGC=d1.getCategoryId("genie civil") #add some internships listOfinternships = [ ( "Stage - Consultant BI/Datastage", "/home/appCritique.pdf/20/21", "Vous interviendrez sur un projet en phase devolution dedie a la mise en place dun systeme permettant \ levolution pour notre client de ses besoins dimmobilisation en fonds propes", idInfo), ( "Stage - Consultant Cyberdefense", "/home/webServiveces/32/33", "Participer au developpement de solutions de Kill Chain en Cyberdefense. Soutenu par ds systemes toujous plus \ ouvertes, le numerique est une source de menaes toujours plus nombreuses.", idInfo), ( "Stage - Ingenieru dEtudes et Developpement WEB en Espagne", "/home/compilateur.pdf/14/15", "Participer a une mission doutsourcing applicatif dans le secteur energie en espagne. Notre client est le \ principal distributeur de gaz naturel en France.", idInfo), ( 'Amelioration biologie moleculaire', "/home/enzyme.pdf", "amelioration de l enzyme de digestion", idBio), ( 'Construction pont Rangueil', "/home/pont.pdf", "il faut le construire ce pont", idGC), ( 'Amelioration rotation des travailleurs sur un chantier', "/home/chantier.pdf", "amelioration d un chantier",idGC) ] d1.addListOfInterships(listOfinternships)<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /*function onYouTubeIframeAPIReady() { var player; player = new YT.Player('videoPlayer', { videoId: 'M5hnrks2zow', // YouTube Video ID height: $(window).height()+'px', width: $(window).width()+'px',// Player height (in px) playerVars: { autoplay: 1, // Auto-play the video on load controls: 0, // Show pause/play buttons in player showinfo: 0, // Hide the video title modestbranding: 0, // Hide the Youtube Logo loop: 1, // Run the video in a loop fs: 0, // Hide the full screen button cc_load_policy: 0, // Hide closed captions iv_load_policy: 3, // Hide the Video Annotations autohide: 1 // Hide video controls when playing }, events: { onReady: function(e) { e.target.mute(); } } }); document.getElementById('main').style.height=$(window).height()+'px'; //document.getElementById('videoPlayer').style.marginTop=-(($('#videoPlayer').height()-$(window).height())/2)+'px'; //document.getElementById('videoPlayer').style.marginRight=-(($('#videoPlayer').width()-$(window).width())/2)+'px'; }*/ function sizeTitleApp(){ var largeurFenetre= $(window).width(); document.getElementById("titleApp").style.fontSize="60pt"; if(largeurFenetre<500){ document.getElementById("titleApp").style.fontSize="40pt"; } } /*var wrongLog=true; function onclickwrongLogin(request.getParameter("numberOfResults")){ if(document.URL==="http://localhost:8080/iManage/Login" && wrongLog===false){ $("#formulaireConnexion").append("<div class='container-fluid col-xs-12'><div class='row'><div class='col-xs-push-1 col-xs-10' style='text-align: center; color: red; font-family: Helvetica'>Wrong login or password</div></div></div>"); wrongLog=true; } }*/ jQuery(document).ready(function(){ setInterval(sizeTitleApp, 1); }); /*jQuery(document).ready(function(){ setInterval(onclickwrongLogin, 1); });*/ <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 insa.bus; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.*; import static javax.ws.rs.core.HttpHeaders.USER_AGENT; /** * * @author zaurelzo */ public class httpWrapper { private String url ; private Map<String,String[]> mapRequestParameters; public httpWrapper( String url ,Map<String,String[]> mapRequestParameters ) { this.url=url; this.mapRequestParameters=mapRequestParameters; } public String sendRequest() { try { URL obj = new URL(this.url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); con.setRequestProperty("Content-Type","application/json"); //build json paramaters // String postJsonData = "{\"id\":5,\"countryName\":\"USA\",\"population\":8000}"; String postJsonData ="{"; for (Map.Entry<String, String[]> entry : this.mapRequestParameters.entrySet()) { postJsonData += "\""+entry.getKey() + "\"" + ":"; for (String value : entry.getValue()) { if (!value.equals("")) postJsonData += "\""+ value + "\"" + ","; else postJsonData += "\"\"" + ","; } } String finalPostJsonData = postJsonData.substring(0, postJsonData.length()-1)+"}"; // System.out.println("************** ==================" + finalPostJsonData); //System.out.println("******************************************"); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(finalPostJsonData); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String output; StringBuffer res = new StringBuffer(); while ((output = in.readLine()) != null) { res.append(output); } in.close(); return res.toString(); } catch (Exception e) { return null ; } } } <file_sep># iManage Web Application ### INSA Toulouse - 5IL ## Description: iManage is a web application conceived to serve as the sole platform which will help 5th year INSA students through the stages related to their internship application and administrative validation processes. These steps are currently accomplished through different websites but iManage simplifies these processes by reuniting them on the same interface. This product was developed using Java Enterprise Edition, Spring MVC framework, and Hibernate ORM to manipulate the transactions of the application database. In the aim of guaranteeing its scalability and maintainability, this product was developed following the Service Oriented Architecture approach and using the Zato Enterprise Service Bus technology. One of its main features is a search engine which looks for internship offers that are retrieved from several company databases. Students can to apply to multiple offers, and once one of them has attracted the attention of a company, a messaging system will be activated to establish the communication between them. The administrative processes related with the internship validation by the INSA staff and the generation of the internship convention are also managed by the web application. ## Team members: - <NAME>. - <NAME>. - <NAME>. - <NAME>. - <NAME>. ## Requirements: * Java 8: you may find the installation instructions [here](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html) * Netbeans IDE 8.2: you may find the installation instructions [here](https://netbeans.org/downloads/) * Docker Engine: you may find the installation instructions [here](https://docs.docker.com/engine/installation/) ## Installation instructions: ### Clone the repository To use iManage, please clone this repository to the desired folder of your computer. You will find the required libraries and also the source code of the three projects of iManage. ## Set up the databases: 1. You must create three databases with the following names: * imanage * entreprisea * entrepriseb 2. Create a user with the following credentials with all the prvileges to all the mentioned databases: * user: root * password: <PASSWORD> ### Set up the iManage project (Web application) 1. Open Netbeans and create a new project (Java Web -> Web application from existing sources) 2. Name the project as iManage and select the /src folder from the repository. 3. As server and settings select GlassFish Server and Java EE 7 Web. 4. Remember to add the Spring MVC and the Hibernate frameworks. 5. Create the project. 6. Set up the connection for the imanage database. You may follow [these instructions](https://netbeans.org/kb/docs/ide/oracle-db.html#connect) 7. Fix the paths of the file savings of the iManage project: * asdas * Internship convention generation: src/java/insa/client/Convention.java * CV and Cover letter: /src/java/insa/client/FileUploadServlet.java ### Set up the iCompany project (Company A) 1. Open Netbeans and create a new project (Java Web -> Web application from existing sources) 2. Name the project as iCompany and select the /iCompany/src/ folder from the repository. 3. As server and settings select GlassFish Server and Java EE 7 Web. 4. Remember to add the Spring MVC and the Hibernate frameworks. 5. Create the project. 6. Set up the connection for the entreprisea database. You may follow [these instructions](https://netbeans.org/kb/docs/ide/oracle-db.html#connect) ### Set up the iCompany2 project (Company B) 1. Open Netbeans and create a new project (Java Web -> Web application from existing sources) 2. Name the project as iCompany2 and select the /iCompany2/src/ folder from the repository. 3. As server and settings select GlassFish Server and Java EE 7 Web. 4. Remember to add the Spring MVC and the Hibernate frameworks. 5. Create the project. 6. Set up the connection for the entrepriseb database. You may follow [these instructions](https://netbeans.org/kb/docs/ide/oracle-db.html#connect) ### Populate the databases of each project: 1. Run the Python script available at /scriptTests/populateDatabases.sh to populate all the databases. ### Set up the Zato ESB 1. Installation: * Follow the instalation instructions available [here](https://zato.io/docs/admin/guide/install/docker.html) * Remember to save the web admin password to have access to the zato interface. * After finishing the instructions, you may test that your zato instance is running on the address [http://localhost:8183](http://localhost:8183) 2. Service configuration: ![alt text](https://github.com/PeaceMaker503/iManage/blob/master/busIntegration/config_channel.png "Logo Title Text 1") 3. Response configuration: ![alt text](https://github.com/PeaceMaker503/iManage/blob/master/busIntegration/config_outgoing_soap1.png "Logo Title Text 1") ![alt text](https://github.com/PeaceMaker503/iManage/blob/master/busIntegration/config_outgoing_soap2.png "Logo Title Text 1") ## Deployment instructions: 1. Connect all the databases through the services tab of your Netbeans IDE. 2. Build and deploy iCompany. 3. Build and deploy iCompany2. 4. Start the Zato ESB Docker image by running the following command: * ```docker start -a -i <image_id>``` 5. Build and deploy iManage. 6. Check the address [http://localhost:8080/iManage](http://localhost:8080/iManage) <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 insa.client; import insa.db.UserAccount; import insa.db.Company; import insa.ws.UserAccountWS; import insa.ws.UserProfileWS; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author zaurelzo */ @WebServlet(name = "ViewUpdateCompanyProfile", urlPatterns = {"/ViewUpdateCompanyProfile"}) public class ViewUpdateCompanyProfile extends HttpServlet { private static UserAccountWS userAccountService = new insa.ws.UserAccountWS(); private static UserProfileWS userProfileService = new insa.ws.UserProfileWS(); /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet EditOffer</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet EditOffer at " + request.getContextPath() + "</h1>"); out.println("</body>"); out.println("</html>"); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { UserAccount ua = userProfileService.getUserAccountByLogin(request.getParameter("login")); String userCategory = ua.getUserCategory(); if(userCategory.compareTo("Student")==0){ request.setAttribute("userType","Student"); } else if (userCategory.compareTo("Company")==0) { request.setAttribute("userType","Company"); } else if (userCategory.compareTo("INSA Staff")==0){ request.setAttribute("userType","INSA Staff"); } long companyProfileID = userProfileService.getUserAccountByLogin(request.getParameter("login")).getId_Company_profile().getId(); Company company = userProfileService.getCompanyById(companyProfileID); request.setAttribute("company",company); this.getServletContext().getRequestDispatcher("/WEB-INF/jsp/ViewUpdateCompanyProfile.jsp").forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { UserAccount userAccount = userProfileService.getUserAccountByLogin(request.getParameter("login")); UserAccount ua = userProfileService.getUserAccountByLogin(request.getParameter("login")); String userCategory = ua.getUserCategory(); if(userCategory.compareTo("Student")==0){ request.setAttribute("userType","Student"); } else if (userCategory.compareTo("Company")==0) { request.setAttribute("userType","Company"); } else if (userCategory.compareTo("INSA Staff")==0){ request.setAttribute("userType","INSA Staff"); } long companyProfileID = userAccount.getId_Company_profile().getId(); Company company = userProfileService.getCompanyById(companyProfileID); company.setName(request.getParameter("name")); company.setPhone(request.getParameter("phone")); company.setMail(request.getParameter("mail")); company.setAddress(request.getParameter("address")); userProfileService.updateCompany(company); request.setAttribute("company",company); this.getServletContext().getRequestDispatcher("/WEB-INF/jsp/ViewUpdateCompanyProfile.jsp").forward(request,response); } } <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 insa.ws; import insa.db.UserAccount; import insa.db.UserProfile; import insa.db.Company; import insa.metier.IMetier; import javax.jws.WebService; import javax.jws.WebMethod; import javax.jws.WebParam; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * * @author zaurelzo */ @WebService(serviceName = "UserProfileWS") public class UserProfileWS { private IMetier metier; public UserProfileWS() { ApplicationContext ap = new ClassPathXmlApplicationContext("../../WEB-INF/applicationContext.xml"); metier = (IMetier)ap.getBean("metier"); } /** * Web service operation */ @WebMethod(operationName = "addUserProfile") public UserProfile addUserProfile(@WebParam(name = "firstName") String firstName, @WebParam(name = "lastName") String lastName, @WebParam(name = "phone") String phone, @WebParam(name = "cvPath") String cvPath, @WebParam(name = "mail") String mail) { //TODO write your implementation code here: return metier.addUserProfile(firstName, lastName, mail, phone, cvPath); } @WebMethod(operationName = "addCompanyProfile") public Company addCompanyProfile(@WebParam(name = "name") String name, @WebParam(name = "phone") String phone, @WebParam(name = "mail") String mail, @WebParam(name = "address") String address) { //TODO write your implementation code here: return metier.addCompanyProfile(name, phone, mail, address); } /** * Web service operation */ @WebMethod(operationName = "deleteUserProfile") public UserProfile deleteUserProfile(@WebParam(name = "id") long id) { //TODO write your implementation code here: return metier.deleteUserProfile(id); } public Company deleteCompanyProfile(@WebParam(name = "id") long id) { return metier.deleteCompanyProfile(id); } @WebMethod(operationName = "updateUserProfile") public UserProfile updateUserProfile(UserProfile userProfile) { return metier.updateUserProfile(userProfile); } @WebMethod(operationName = "deleteUserAccount") public UserAccount deleteUserAccountById(Long id) { return metier.deleteUserAccountById(id); } /** * Web service operation */ @WebMethod(operationName = "getUserProfile") public UserProfile getUserProfileById(@WebParam(name = "id") long id) { return metier.getUserProfileById(id); } @WebMethod(operationName = "getUserAccountByLogin") public UserAccount getUserAccountByLogin(@WebParam(name = "login") String login) { return metier.getUserAccountByLogin(login); } @WebMethod(operationName = "getCompanyById") public Company getCompanyById(@WebParam(name = "id") long id) { return metier.getCompanyById(id); } @WebMethod(operationName = "updateCompany") public Company updateCompany(Company company) { return metier.updateCompany(company); } public Company getCompanyByName(String company_name) { return metier.getCompanyByName(company_name); } }
eea978229d8f220d81396605b9d216dd5ac0d8d8
[ "JavaScript", "Markdown", "Java", "Python", "Shell" ]
22
Java
PeaceMaker503/iManage
b0be881091e3ab170d3b78efb25f359dd4f4ba68
b19da61bb278e2eba7f1634dcdf243bf51004336
refs/heads/master
<file_sep>#ifndef CORE1_THREAD_H #define CORE1_THREAD_H #include <pico/util/queue.h> extern queue_t results_queue; extern queue_t data_queue; void core1_run(void); void core1_entry(void); #endif /* CORE1_THREAD_H */<file_sep># Edge Impulse Example: multicore inferencing (Raspberry Pi Pico) This repository runs an exported impulse on the Raspberry Pi Pico / RP2040. See the documentation at [Running your impulse locally](https://docs.edgeimpulse.com/docs/running-your-impulse-locally-1). This repository is based on the [Edge Impulse Example: stand-alone inferencing (Raspberry Pi Pico)](https://github.com/edgeimpulse/example-standalone-inferencing-pico). ## Requirements ### Hardware * [Raspberry Pi Pico](https://www.raspberrypi.org/products/raspberry-pi-pico/). * [MPU-6050 Module](https://www.dfrobot.com/product-880.html) ### Software * [Edge Impulse CLI](https://docs.edgeimpulse.com/docs/cli-installation). * [GNU ARM Embedded Toolchain](https://developer.arm.com/tools-and-software/open-source-software/developer-tools/gnu-toolchain/gnu-rm/downloads). * [CMake](https://cmake.org/install/). * Rasperry Pi Pico SDK: ```bash git clone -b master https://github.com/raspberrypi/pico-sdk.git cd pico-sdk git submodule update --init export PICO_SDK_PATH=`pwd` ``` ## Building the application ### Get the Edge Impulse SDK Unzip the deployed `C++ library` from your Edge Impulse project and copy only the folders to the root directory of this repository: ``` example-multicore-inferencing-pico/ ├─ edge-impulse-sdk/ ├─ model-parameters/ ├─ source/ ├─ tflite-model/ ├─ .gitignore ├─ CMakeLists.txt ├─ LICENSE ├─ README.md └─ pico_sdk_import.cmake ``` ### Compile 1. Create the `build` folder: ```bash mkdir build && cd build ``` 1. Compile: ```bash cmake .. && cmake --build . --parallel ``` ### Flash Connect the Raspberry Pi Pico to your computer using a micro-USB cable while pressing and holding the **BOOTSEL** button. Drag and drop the `build/example_multicore.uf2` file to the **RPI-RP2** disk in your file explorer. ### Serial connection Use screen or minicom to set up a serial connection over USB. The following UART settings are used: 115200 baud, 8N1. <file_sep>#ifndef ACCELEROMETER_H #define ACCELEROMETER_H void accel_init(void); void accel_get_data(float* data); #endif /* ACCELEROMETER_H */<file_sep>#include <stdio.h> #include <string.h> #include <hardware/gpio.h> #include <pico/stdio_usb.h> #include <pico/stdlib.h> #include <pico/multicore.h> #include <pico/util/queue.h> #include "ei_classifier_types.h" #include "porting/ei_classifier_porting.h" #include "core1_thread.h" #include "accelerometer.h" int main() { ei_impulse_result_t res = {nullptr}; float acceleration[EI_CLASSIFIER_RAW_SAMPLES_PER_FRAME]; uint64_t last_sample_time = 0; stdio_init_all(); accel_init(); core1_run(); while (true) { ei_printf("Edge Impulse standalone inferencing on multicore (Raspberry Pi Pico)\n"); while (1) { if(queue_try_remove(&results_queue, &res)) { ei_printf("Predictions (DSP: %d ms., Classification: %d ms., Anomaly: %d ms.): \n", res.timing.dsp, res.timing.classification, res.timing.anomaly); for (size_t ix = 0; ix < EI_CLASSIFIER_LABEL_COUNT; ix++) { ei_printf("\t%s: %.5f\n", res.classification[ix].label, res.classification[ix].value); } #if EI_CLASSIFIER_HAS_ANOMALY == 1 ei_printf("\tanomaly score: %.3f\n", res.anomaly); #endif ei_sleep(2000); } // read sample every 10000 us = 10ms (= 100 Hz) if(ei_read_timer_us() - last_sample_time >= 10000) { accel_get_data(acceleration); for(int i=0; i<EI_CLASSIFIER_RAW_SAMPLES_PER_FRAME; i++) { if(queue_try_add(&data_queue, &acceleration[i]) == false) { // ei_printf("Data queue full!\n"); break; } } last_sample_time = ei_read_timer_us(); } } } }<file_sep>#include <pico/util/queue.h> #include <pico/multicore.h> #include <hardware/gpio.h> #include "ei_run_classifier.h" #include "core1_thread.h" queue_t results_queue; queue_t data_queue; const uint LED_PIN = 25; float signal_buf[EI_CLASSIFIER_DSP_INPUT_FRAME_SIZE]; int raw_feature_get_data(size_t offset, size_t length, float *out_ptr) { memcpy(out_ptr, signal_buf + offset, length * sizeof(float)); return 0; } void core1_run(void) { queue_init(&results_queue, sizeof(ei_impulse_result_t), 2); // add space for 4 additional samples to avoid blocking main thread queue_init(&data_queue, sizeof(float), EI_CLASSIFIER_DSP_INPUT_FRAME_SIZE + (4 * sizeof(float))); multicore_launch_core1(core1_entry); } void core1_entry() { ei_impulse_result_t result = {nullptr}; signal_t features_signal; // init LED gpio_init(LED_PIN); gpio_set_dir(LED_PIN, GPIO_OUT); features_signal.total_length = EI_CLASSIFIER_DSP_INPUT_FRAME_SIZE; features_signal.get_data = &raw_feature_get_data; while (1) { // get data from sensor for(int i = 0; i < EI_CLASSIFIER_DSP_INPUT_FRAME_SIZE; i++) { queue_remove_blocking(&data_queue, &signal_buf[i]); } // invoke the impulse EI_IMPULSE_ERROR res = run_classifier(&features_signal, &result, false); if (res != 0) continue; // return results to core0 queue_add_blocking(&results_queue, &result); // toggle LED gpio_put(LED_PIN, !gpio_get(LED_PIN)); } }<file_sep>#include "accelerometer.h" #include <hardware/gpio.h> #include <hardware/i2c.h> #include <pico/binary_info.h> #define I2C_INTERFACE i2c1 #define I2C_DEV_ADDR 0x68 #define I2C_SDA_PIN 18 #define I2C_SCL_PIN 19 static void mpu6050_reset() { // Two byte reset. First byte register, second byte data // There are a load more options to set up the device in different ways that could be added here uint8_t buf[] = {0x6B, 0x00}; i2c_write_blocking(I2C_INTERFACE, I2C_DEV_ADDR, buf, 2, false); } static void mpu6050_read_raw(int16_t accel[3], int16_t gyro[3], int16_t *temp) { // For this particular device, we send the device the register we want to read // first, then subsequently read from the device. The register is auto incrementing // so we don't need to keep sending the register we want, just the first. uint8_t buffer[6]; // Start reading acceleration registers from register 0x3B for 6 bytes uint8_t val = 0x3B; i2c_write_blocking(I2C_INTERFACE, I2C_DEV_ADDR, &val, 1, true); // true to keep master control of bus i2c_read_blocking(I2C_INTERFACE, I2C_DEV_ADDR, buffer, 6, false); for (int i = 0; i < 3; i++) { accel[i] = (buffer[i * 2] << 8 | buffer[(i * 2) + 1]); } // Now gyro data from reg 0x43 for 6 bytes // The register is auto incrementing on each read val = 0x43; i2c_write_blocking(I2C_INTERFACE, I2C_DEV_ADDR, &val, 1, true); i2c_read_blocking(I2C_INTERFACE, I2C_DEV_ADDR, buffer, 6, false); // False - finished with bus for (int i = 0; i < 3; i++) { gyro[i] = (buffer[i * 2] << 8 | buffer[(i * 2) + 1]);; } // Now temperature from reg 0x41 for 2 bytes // The register is auto incrementing on each read val = 0x41; i2c_write_blocking(I2C_INTERFACE, I2C_DEV_ADDR, &val, 1, true); i2c_read_blocking(I2C_INTERFACE, I2C_DEV_ADDR, buffer, 2, false); // False - finished with bus *temp = buffer[0] << 8 | buffer[1]; } void accel_init(void) { i2c_init(I2C_INTERFACE, 400 * 1000); gpio_set_function(I2C_SDA_PIN, GPIO_FUNC_I2C); gpio_set_function(I2C_SCL_PIN, GPIO_FUNC_I2C); gpio_pull_up(I2C_SDA_PIN); gpio_pull_up(I2C_SCL_PIN); // Make the I2C pins available to picotool bi_decl(bi_2pins_with_func(PICO_DEFAULT_I2C_SDA_PIN, PICO_DEFAULT_I2C_SCL_PIN, GPIO_FUNC_I2C)); mpu6050_reset(); } void accel_get_data(float* data) { int16_t acceleration_raw[3], gyro[3], temp; mpu6050_read_raw(acceleration_raw, gyro, &temp); for(int i=0; i<3; i++) { // convert raw reading to m/s2 assuming accelerometer range is 2g data[i] = (float)acceleration_raw[i]/1638.40f; } }
b647d2b155ea3d33e8c06cd968853b06539d2de9
[ "Markdown", "C", "C++" ]
6
C
edgeimpulse/example-multicore-inferencing-pico
781e6630ba490c20fe85311d2a6bc8fee440c619
4d35e43486731a64eb861eb83fe180ae8df5ce58
refs/heads/master
<repo_name>tomberek/nix-bundle<file_sep>/nix-bundle.sh #!/usr/bin/env sh if [ "$#" -lt 2 ]; then cat <<EOF Usage: $0 TARGET EXECUTABLE Create a single-file bundle from the nixpkgs attribute "TARGET". EXECUTABLE should be relative to the TARGET's output path. For example: $ $0 hello /bin/hello $ ./hello Hello, world! EOF exit 1 fi nix_file=`dirname $0`/default.nix target="$1" shift extraTargets= if [ "$#" -gt 1 ]; then while [ "$#" -gt 1 ]; do extraTargets="$extraTargets $1" shift done fi exec="$1" shift bootstrap=nix-bootstrap if [ "$target" = "nix-bundle" ] || [ "$target" = "nixStable" ] || [ "$target" = "nixUnstable" ] || [ "$target" = "nix" ]; then bootstrap=nix-bootstrap-nix elif ! [ -z "$extraTargets" ]; then bootstrap=nix-bootstrap-path fi expr="with import <nixpkgs> {}; with import $nix_file {}; $bootstrap { target = $target; extraTargets = [ $extraTargets ]; run = \"$exec\"; }" out=$(nix-store --no-gc-warning -r --option binary-caches '' $(nix-instantiate --no-gc-warning -E "$expr")) #out=$(nix-store --no-gc-warning -r $(nix-instantiate --no-gc-warning -E "$expr")) if [ -z "$out" ]; then >&2 echo "$0 failed. Exiting." exit 1 elif [ -t 1 ]; then filename=$(basename $exec) echo "Nix bundle created at $filename." cat <<"EOF" > $filename #!/bin/sh if [ ! -z "$IN_NIX_USER_CHROOT"]; then #! /nix/env nix-shell #! nix-shell --pure -I nixpkgs=channel://nixpkgs-unstable -p hello -i sh echo Modify this script for a self-installing nix-shell in a chroot. echo "The store will persist in TMPDIR due to nix-bundle's arx approach." echo "This hard-codes a channel, feel free to modify." echo echo "Perhaps try '-i python' for a run-anywhere-with-nix python script" echo "Cons:" echo " Linux only due to nix-user-chroot" echo " nix-shell is slow to start" echo "Arguments:" shift echo "$@" ### Don't remove this exit, or weird things happen ### exit #ENDSENTINEL fi ABSPATH="$(cd "$(dirname "$0")" && pwd)/$(basename "$0")" EOF cat $out | sed 's|exec ../run |exec ../run "$ABSPATH" |g' >> $filename else cat $out fi
92a96b433b7135b99a0f4dd66dbac31732d0112e
[ "Shell" ]
1
Shell
tomberek/nix-bundle
7fb94f732657cfad72436a417d73d435a0944924
0452a9dc4ecb734e273674f8a8eb6f5eac4421ee
refs/heads/main
<file_sep> exports.showHelp = () => { const text = ` How to use this program: 1. When you input a new string with more than 1 space the program will sanitize it for you. 2. If you typed the name of a city without capitalization the program will capitalize it for you. 3. If you included a Capitalized letter in the wrong place of your string the program will sanitize it for you. `; console.log(text); }; exports.showVersion = () => { const text = `1.0.0v`; console.log(text); }; exports.prepareString = (str) => { let newArray = str.map((word) => { let fixedWord = word.trim(); return fixedWord.charAt(0).toUpperCase() + fixedWord.slice(1).toLowerCase(); }); console.log(newArray.join(" ").replace(/[^a-zA-Z ]/g, "")); }; <file_sep>#!/usr/bin/env node const { showHelp, showVersion, prepareString} = require("./src/lib/help"); const weather = require("./src/lib/weather"); const args = process.argv.slice(2); // if (args.includes("--help")) { // showHelp(); // } if (args.includes("-v")) { showVersion(); } if (weather){ //console.log(args); prepareString(args); } console.log(args); const [city, country] = args; weather(args, country).then(console.log).catch(console.error);
49ad5edb1649f4efdee28cb6c7e2b19db35b2839
[ "JavaScript" ]
2
JavaScript
anabbaa/weather
80930011e970b63ea565c4083c0ca55cf7711512
b04515af78b7f7d1f799eb1d0e73ea192538dae7
refs/heads/master
<repo_name>sebastibe/brunch<file_sep>/skeleton/simple-js/app/views/home_view.js module.exports = Backbone.View.extend({ id: 'home-view', render: function() { this.$el.html(require('./templates/home')); return this; } }); <file_sep>/skeleton/simple-js/app/initialize.js var MainRouter = require('routers/main_router'); var HomeView = require('views/home_view'); exports.Application = (function() { function Application() { var _this = this; $(function() { _this.initialize(); return Backbone.history.start(); }); } Application.prototype.initialize = function() { this.router = new MainRouter; return this.homeView = new HomeView; }; return Application; })(); window.app = new exports.Application; <file_sep>/docs/structure.rst ******************* Directory structure ******************* Simple (included with brunch) ============================= :: config.coffee README.md /app/ /assets/ index.html humans.txt images/ collections/ models/ styles/ routers/ templates/ views/ initialize.coffee /build/ (generated by brunch) index.html (copied from app/assets) scripts/ app.js (compiled & compressed) styles/ app.css (compiled & compressed) images/ (copied from app/assets) /test/ functional/ unit/ /vendor/ scripts/ backbone.js jquery.js console-helper.js underscore.js styles/ normalize.css helpers.css * ``config.coffee`` contains configuration of your app. You can set plugins / languages that would be used here. * ``app/assets`` contains images / static files. Contents of the directory would be copied to ``build/`` without change. * Other ``app/`` directories could contain files that would be compiled. Languages, that compile to JS (coffeescript, roy etc.) or js files and located in ``app`` are automatically wrapped in module closure so they can be loaded by ``require('module/location')``. * ``build`` is generated automatically, so you don't need to put anything there. * ``test/`` contains feature & unit tests. * ``vendor`` contains all third-party code. The code wouldn't be wrapped in modules, it would be loaded instantly instead.
b63dec2ffd032822b9da022037f4ce6444e97963
[ "JavaScript", "reStructuredText" ]
3
JavaScript
sebastibe/brunch
bd19cc9bf11023f1eb2a9e887691d2b5922a86ba
a95cb7c2f6a284154c3d77185e46176e7ff09c49
refs/heads/master
<repo_name>spbots/tuple_utils<file_sep>/flatten.hpp #pragma once #include <tuple> namespace tuple_utils { namespace detail { /** flatten converts a tree of std::tuple to to a flat std::tuple. flatten takes in an std::tuple as its ...Inputs type, an empty tuple as its output, and the ::type of the deduced type will be a flat tuple of all the non-tuple types from the input. It's most likely that you actually want to use flatten_t. */ template <typename Output = std::tuple<>, //< output typename... Inputs> //< inputs struct flatten; /** If the first of the input parameters is a tuple, extract the individual types from the tuple. */ template <typename... OutTs, typename... Ts, typename... Rest> struct flatten<std::tuple<OutTs...>, //< output std::tuple<Ts...>, //< input tuple Rest...> : flatten<std::tuple<OutTs...>, Ts..., Rest...> { }; /** If the first of the input parameters is not a tuple, add it to the output tuple. */ template <typename Input, typename... OutTs, typename... Rest> struct flatten<std::tuple<OutTs...>, //< output Input, //< non-tuple type Rest...> : flatten<std::tuple<OutTs..., Input>, Rest...> { }; /** If there are no more inputs "return" the flattened output tuple. */ template <typename... OutTs> struct flatten<std::tuple<OutTs...>> { using type = std::tuple<OutTs...>; }; } // namespace detail template <typename T> using flatten = detail::flatten<std::tuple<>, T>; template <typename T> using flatten_t = typename flatten<T>::type; } // namespace tuple_utils <file_sep>/tuple_utils.hpp #pragma once #include "filter.hpp" #include "flatten.hpp" #include "is_in_tuple.hpp" #include "unique.hpp" <file_sep>/unique.hpp #pragma once #include "is_in_tuple.hpp" #include <tuple> #include <type_traits> namespace tuple_utils { namespace detail { template <typename InputTuple, typename OutputTuple> struct unique {}; template <typename OutputTuple> struct unique<std::tuple<>, OutputTuple> { using type = OutputTuple; }; template <typename T, typename... Ts, typename... Us> struct unique<std::tuple<T, Ts...>, std::tuple<Us...>> : unique< std::tuple<Ts...>, typename std::conditional<is_in_tuple<T, std::tuple<Us...>>::value, std::tuple<Us...>, std::tuple<Us..., T >>::type> { }; } // namespace detail /** Provide a tuple that has no duplicate types. Requires that the input is a flat tuple (i.e. no nested tuples). */ template <typename T> using unique = detail::unique<T, std::tuple<>>; template <typename T> using unique_t = typename unique<T>::type; } // namespace tuple_utils <file_sep>/filter.hpp #pragma once #include <tuple> #include <type_traits> namespace tuple_utils { namespace detail { template <template <typename> class Predicate, typename InputTuple, typename OutputTuple = std::tuple<>> struct filter; template <template <typename> class Predicate, typename Result> struct filter<Predicate, std::tuple<>, Result> { using type = Result; }; template <template <typename> class Predicate, typename T, typename... Ts, typename... Filtered> struct filter<Predicate, std::tuple<T, Ts...>, std::tuple<Filtered...>> : filter< Predicate, std::tuple<Ts...>, typename std::conditional<Predicate<T>::value, std::tuple<Filtered..., T>, std::tuple<Filtered... >>::type> { }; } // namespace detail /** Return a tuple type that only contains types that satisfy the Predicate. */ template <typename unfiltered_t, template <typename> class Predicate> using filtered_t = typename detail::filter<Predicate, unfiltered_t>::type; } // namespace tuple_utils <file_sep>/is_in_tuple.hpp #pragma once #include <tuple> #include <type_traits> namespace tuple_utils { /** is_in_tuple is used to check whether a given type exists in a tuple. Note that it only looks at the top level of the tuple - if you provide a tuple tree it will not flatten it to search for the type. */ template <typename TypeToCheck, typename Tuple> struct is_in_tuple; template <typename TypeToCheck, typename T, typename... Ts> struct is_in_tuple <TypeToCheck, std::tuple<T, Ts...>> { static const bool value = is_in_tuple<TypeToCheck, std::tuple<Ts...>>::value; }; template <typename TypeToCheck, typename... Ts> struct is_in_tuple <TypeToCheck, std::tuple<TypeToCheck, Ts...>> : std::true_type { }; template <typename TypeToCheck> struct is_in_tuple <TypeToCheck, std::tuple<>> : std::false_type { }; } // namespace tuple_utils <file_sep>/tst_tuple_utils.cpp #include "filter.hpp" #include "flatten.hpp" #include "is_in_tuple.hpp" #include "unique.hpp" namespace tuple_utils { namespace test { template <typename T> struct IsGreaterThanOne { static const bool value = T::value > 1; }; using test_filtered_t = filtered_t<std::tuple< std::integral_constant<size_t, 0>, std::integral_constant<size_t, 1>, std::integral_constant<size_t, 2>, std::integral_constant<size_t, 3>>, IsGreaterThanOne>; using expected_filtered_t = std::tuple< std::integral_constant<size_t, 2>, std::integral_constant<size_t, 3>>; static_assert(std::is_same<test_filtered_t, expected_filtered_t>::value, "filter is broken."); using test_flatten_t = flatten_t< std::tuple< std::tuple< double, int, int, std::tuple< float, char, std::tuple<>, std::tuple<int> > >, size_t >>; using expected_flatten_t = std::tuple<double, int, int, float, char, int, size_t>; static_assert(std::is_same<test_flatten_t, expected_flatten_t>::value, "flatten is broken."); using test_is_in_tuple_t = std::tuple<int, float, std::tuple<double>>; static_assert(is_in_tuple<int, test_is_in_tuple_t>::value, "is_in_tuple broken."); static_assert(is_in_tuple<float, test_is_in_tuple_t>::value, "is_in_tuple broken."); static_assert(!is_in_tuple<double, test_is_in_tuple_t>::value, "is_in_tuple broken."); using test_unique_t = unique_t<std::tuple<int, float, int, float, double, int, bool>>; using expected_unique_t = std::tuple<int, float, double, bool>; static_assert(std::is_same<test_unique_t, expected_unique_t>::value, "unique is broken."); } // namespace test } // namespace tuple_utils int main() { return 0; }<file_sep>/README.md # tuple_utils C++11 compile time tuple utilities.
f2e2a45ef84f69ac1db5ff7613f69d87c2563cb8
[ "Markdown", "C++" ]
7
C++
spbots/tuple_utils
40a55812da09102057dafd6a97d02f0030ac0433
e0836cf83eedb0cb5303179c98d605051348bdf4
refs/heads/master
<file_sep><?= $this->Html->css('login') ?> <?= $this->Html->script('login') ?> <div id="background-carousel"> <div id="myCarousel" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div class="item active" style="background-image:url(http://cdn-image.travelandleisure.com/sites/default/files/styles/1600x1000/public/201407-w-most-beautiful-libraries-in-the-world-klementinum-prague.jpg?itok=iEn3LTLq)"></div> <div class="item" style="background-image:url(http://mentalfloss.com/sites/default/legacy/blogs/wp-content/uploads/2012/04/370663920_b87c065936_z-565x378.jpg)"></div> <div class="item" style="background-image:url(http://cdn-image.travelandleisure.com/sites/default/files/styles/tnl_redesign_article_landing_page/public/201407-w-most-beautiful-libraries-in-the-world-austrias-national-library.jpg?itok=4KtEs9tX)"></div> </div> </div> </div> <div id="content-wrapper"> <div class="container"> <div class="row vertical-offset-100"> <div class="col-md-4 col-md-offset-4"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Por favor, identifíquese</h3> </div> <div class="panel-body"> <?= $this->Flash->render('auth') ?> <?= $this->Form->create() ?> <fieldset> <?php echo '<div class="form-group">'; echo $this->Form->input('email',['class' => 'form-control', 'placeholder' => 'Correo Electrónico', 'label' => false]); echo '</div>'; echo '<div class="form-group">'; echo $this->Form->input('password',['class' => 'form-control', 'placeholder' => '<PASSWORD>', 'label' => false]); echo '</div>'; echo ' <div class="checkbox"> <label> <input name="remember" type="checkbox" value="Remember Me"> Recordarme </label> </div>'; ?> </fieldset> <?= $this->Form->button('Ingresar', ['class' => 'btn btn-lg btn-success btn-block']) ?> <?= $this->Form->end() ?> </div> </div> </div> </div> </div> </div><file_sep><?= $this->Html->css('menu') ?> <!-- http://bootsnipp.com/snippets/xaQoQ --> <nav class="navbar navbar-default navbar-static-top"> <div class="container-fluid"> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <div class="container"> <div class="row"> <div class="col-sm-1"> <b><?= $this->Html->link('Biblioteca', ['controller' => 'Books', 'action' => 'index'], ['class' => 'navbar-brand', 'escape' => false]); ?></b> </div> <?php if(isset($current_user)): ?> <div class="col-sm-6"> <ul class="list-unstyled row row-no-gutter"> <li class="col-sm-3"></li> <li class="col-sm-3"> <a href="#" class="navbar-btn btn-lg btn-danger btn-plus dropdown-toggle" data-toggle="dropdown"> Administrar<small> <span class="glyphicon glyphicon-chevron-down" aria-hidden="true"></span></small> </a> <ul class="nav dropdown-menu"> <li> <?= $this->Html->link('<i class="glyphicon glyphicon-user" style="color:#0830f7;"></i> Admins', ['controller' => 'Users', 'action' => 'index'], ['escape' => false]); ?> </li> <li><?= $this->Html->link('<i class="glyphicon glyphicon-book" style="color:#20a25f;"></i> Libros', ['controller' => 'Books', 'action' => 'adminbooks'], ['escape' => false]); ?> </li> <li class="divider"></li> <li><?= $this->Html->link('<i class="glyphicon glyphicon-off" style="color:#f80d0d;"></i> Cerrar Sesión', ['controller' => 'Users', 'action' => 'logout'], ['escape' => false]); ?> </li> </ul> </li> <li class="col-sm-3"></li> </ul> </div> <?php else: ?> <div class="col-sm-5"></div> <?php endif; ?> <div class="col-sm-5"> <div class="vertical-align-md"> <form role="search"> <div class="input-group input-group-lg input-group-full"> <input type="text" class="form-control" aria-label="Search" placeholder="Buscar PDF"> <div class="input-group-btn"> <button type="button" class="btn btn-default" aria-label="Buscar"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></button> </div> </div> </form> </div> </div> </div> </div> </div> </div> </nav><file_sep><?= $this->Html->css('add') ?> <link href='http://fonts.googleapis.com/css?family=Roboto:100' rel='stylesheet' type='text/css'> <div class="container"> <div class="row"> <div class="col-md-12"> <?= $this->Form->create($user, ['novalidate'], ['class' => 'form-horizontal']) ?> <div class="row"> <div class="col-md-offset-2 col-md-8"> <div class="panel"> <div class="panel-heading custom-header-panel"> <h3 class="panel-title roboto">Crear Usuario Administrador</h3> </div> <div class="panel-body"> <fieldset> <?php echo '<div class="form-group">'; echo $this->Form->input('first_name',['class' => 'form-control', 'label' => 'Nombre:']); echo '</div>'; echo '<div class="form-group">'; echo $this->Form->input('last_name', ['class' => 'form-control', 'label' => 'Apellido:']); echo '</div>'; echo '<div class="form-group">'; echo $this->Form->input('email',['class' => 'form-control', 'label' => 'Correo Electrónico:']); echo '</div>'; echo '<div class="form-group">'; echo $this->Form->input('password', ['class' => 'form-control', 'label' => 'Contraseña']); echo '</div>'; ?> </fieldset> <div class="form-group text-center"></br></br> <?= $this->Form->button('Crear Admin', ['class' => 'btn btn-orange-md roboto']) ?> </div> </div> </div> </div> </div> <?= $this->Form->end() ?> </div> </div> </div> <file_sep><?= $this->Html->css('books') ?> <?= $this->Html->script('books') ?> <div class="container" style="margin-top:40px"> <?php foreach ($books as $book): ?> <div class="row"> <div class="col-xs-10 col-xs-offset-1 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3"> <div class="panel panel-default panel-horizontal"> <div class="panel-heading"> <img src="<?= h($book->image_dir) ?>" alt="<?= h($book->image) ?>" class="imgn"> </div> <div class="panel-body"> <h2 id="tittle" class="panel-tittle"><bold><?= h($book->titulo) ?></bold></h2> <h6 id="autor">Autor: <?= h($book->autor) ?></h6> <p><?= h($book->descripcion) ?></p> <?= $this->Form->postLink('Descargar', ['controller' => 'Books', 'action' => 'download', $book->id], ['class' => 'btn-lg btn-success', 'escape' => false]) ?> </div> </div> </div> </div> <?php endforeach ?> </div> <div class="panel-footer"> <div class="paginator"> <ul class="pagination"> <?= $this->Paginator->prev('< Anterior') ?> <?= $this->Paginator->numbers(['before' => '', 'after' => '']) ?> <?= $this->Paginator->next('Siguiente >') ?> </ul> <p><?= $this->Paginator->counter() ?></p> </div> </div><file_sep><?= $this->Html->css('add') ?> <?= $this->Html->css('sweetalert') ?> <?= $this->Html->script('add') ?> <?= $this->Html->script('sweetalert.min') ?> <link href='http://fonts.googleapis.com/css?family=Roboto:100' rel='stylesheet' type='text/css'> <div class="container"> <div class="row"> <div class="col-md-12"> <?= $this->Form->create($book, ['type' => 'file', 'novalidate']) ?> <div class="row"> <div class="col-md-offset-2 col-md-8"> <div class="panel"> <div class="panel-heading custom-header-panel"> <h3 class="panel-title roboto">Agregar Libro</h3> </div> <div class="panel-body"> <fieldset> <?php echo '<div class="form-group">'; echo $this->Form->input('titulo',['class' => 'form-control', 'label' => 'Título:']); echo '</div>'; echo '<div class="form-group">'; echo $this->Form->input('autor', ['class' => 'form-control', 'label' => 'Autor:']); echo '</div>'; echo '<div class="form-group">'; echo $this->Form->input('descripcion',['class' => 'form-control', 'label' => 'Descripción:']); echo '</div>'; echo '<div class="form-group">'; echo $this->Form->input('image', ['class' => 'form-control', 'label' => 'Descripción de la Imagen:']); echo '</div>'; echo '<div class="form-group">'; echo $this->Form->input('image_dir',['class' => 'form-control', 'label' => 'Dirección de la Imagen:', 'type' => 'text', 'placeholder' => 'Copia y pega la url']); echo '</div>'; echo '</br>'; echo '<span class="btn-lg btn-info btn-file"> Seleccionar PDF <input type="file" name="UploadBook" id="UploadBook" accept="application/pdf" > </span>'; ?> </fieldset> <div class="form-group text-center"></br></br> <?= $this->Form->button('Añadir Libro', ['id' => 'upload', 'name' => 'upload', 'class' => 'btn btn-orange-md roboto']) ?> </div> </div> </div> </div> </div> <?= $this->Form->end() ?> </div> </div> </div> <file_sep><?php namespace App\Controller; use App\Controller\AppController; /** * Books Controller * * @property \App\Model\Table\BooksTable $Books */ class BooksController extends AppController { /** * Index method * * @return \Cake\Network\Response|null */ function beforeFilter(\Cake\Event\Event $event ) { parent::beforeFilter($event); $this->Auth->allow(['index', 'download']); } public function index() { $books = $this->paginate($this->Books); $this->set(compact('books')); $this->set('_serialize', ['books']); } public function adminbooks() { $books = $this->paginate($this->Books); $this->set('books', $books); } /** * View method * * @param string|null $id Book id. * @return \Cake\Network\Response|null * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found. */ public function view($id = null) { $book = $this->Books->get($id, [ 'contain' => [] ]); $this->set('book', $book); $this->set('_serialize', ['book']); } /** * Add method * * @return \Cake\Network\Response|null Redirects on successful add, renders view otherwise. */ public function add() { $book = $this->Books->newEntity(); if ($this->request->is('post')) { if(isset($_FILES["UploadBook"]["name"])) { $hash = $book->id * 5; //Cada libro va a ser unico //$target_dir = "pdf/"; //Donde se van a guardar los pdf $target_file = "pdf/" . basename($_FILES["UploadBook"]["name"], ".pdf") . $hash . ".pdf"; //La ruta del pdf $book = $this->Books->patchEntity($book, $this->request->data); $book->path = $target_file; if ($this->Books->save($book)) { move_uploaded_file($_FILES["UploadBook"]["tmp_name"], $target_file); $this->Flash->success('El libro ha sido agregado correctamente.'); return $this->redirect(['action' => 'index']); } else{ $this->Flash->error('No se pudo crear al user.'); } } else{ $this->Flash->error('No se pudo cargar el PDF.'); } } $this->set(compact('book')); $this->set('_serialize', ['book']); } /** * Edit method * * @param string|null $id Book id. * @return \Cake\Network\Response|null Redirects on successful edit, renders view otherwise. * @throws \Cake\Network\Exception\NotFoundException When record not found. */ public function edit($id = null) { $book = $this->Books->get($id, [ 'contain' => [] ]); if ($this->request->is(['patch', 'post', 'put'])) { $book = $this->Books->patchEntity($book, $this->request->data); if ($this->Books->save($book)) { $this->Flash->success('El libro se edito correctamente'); return $this->redirect(['action' => 'adminbooks']); } $this->Flash->error('No se pudo guardar el libro, por favor intente nuevamente.'); } $this->set(compact('book')); $this->set('_serialize', ['book']); } /** * Delete method * * @param string|null $id Book id. * @return \Cake\Network\Response|null Redirects to index. * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found. */ public function delete($id = null) { $this->request->allowMethod(['post', 'delete']); $book = $this->Books->get($id); if ($this->Books->delete($book)) { $this->Flash->success('El libro se ha eliminado.'); } else { $this->Flash->error('Ocurrio un error, el libro no pudo ser eliminado.'); } return $this->redirect(['action' => 'adminbooks']); } public function download($id = null) { $this->request->allowMethod(['post', 'download']); $book = $this->Books->get($id); if (file_exists($book->path)) { header('content-Disposition: attachment; filename = '.$book->path.''); header('content-type:appliction/octent-strem'); header('content-length='.filesize($book->path)); readfile($book->path); } else { $this->Flash->error('El link de descarga no funciona.'); } return $this->redirect(['action' => 'index']); } public function isAuthorized() { if($this->Auth->user()) { return true; } return false; } } <file_sep><?= $this->Html->css('add') ?> <link href='http://fonts.googleapis.com/css?family=Roboto:100' rel='stylesheet' type='text/css'> <div class="container"> <div class="row"> <div class="col-md-12"> <?= $this->Form->create($book, ['novalidate']) ?> <div class="row"> <div class="col-md-offset-2 col-md-8"> <div class="panel"> <div class="panel-heading custom-header-panel"> <h3 class="panel-title roboto">Editar Libro</h3> </div> <div class="panel-body"> <fieldset> <?php echo '<div class="form-group">'; echo $this->Form->input('titulo',['class' => 'form-control', 'label' => 'Título:']); echo '</div>'; echo '<div class="form-group">'; echo $this->Form->input('autor', ['class' => 'form-control', 'label' => 'Autor:']); echo '</div>'; echo '<div class="form-group">'; echo $this->Form->input('descripcion',['class' => 'form-control', 'label' => 'Descripción:']); echo '</div>'; echo '<div class="form-group">'; echo $this->Form->input('image', ['class' => 'form-control', 'label' => 'Descripción de la Imagen:']); echo '</div>'; echo '<div class="form-group">'; echo $this->Form->input('image_dir',['class' => 'form-control', 'label' => 'Dirección de la Imagen:', 'type' => 'text', 'placeholder' => 'Copia y pega la url']); echo '</div>'; ?> </fieldset> <div class="form-group text-left"></br></br> <?= $this->Form->button('Editar', ['class' => 'btn btn-lightblue-md roboto']) ?> </div> </div> </div> </div> </div> <?= $this->Form->end() ?> </div> </div> </div> <file_sep># Biblioteca Online Aplicación web desarrollada para el manejo de una biblioteca online. Esta aplicación permite gestionar los libros y a los administradores del sitio. Se obtiene un listado de los libros displonibles y el usuario comun los puede descargar. ## Tecnologías utilizadas Aplicación desarrollada en PHP con el framework CakePHP v3.4 y Bootstrap 3. ## Screenshots ![index](https://cloud.githubusercontent.com/assets/25287008/23461835/42eae7b2-fe6a-11e6-8b84-e6a8e8abfb56.png) ![login](https://cloud.githubusercontent.com/assets/25287008/23462484/bed016c0-fe6c-11e6-837e-88d56e7ccdbc.png) ![adminbooks](https://cloud.githubusercontent.com/assets/25287008/23461856/59acb8fe-fe6a-11e6-8b1f-08e5cb8fd7c5.png) ![add](https://cloud.githubusercontent.com/assets/25287008/23461861/6080459c-fe6a-11e6-8b6c-24e822a6b0d4.png) ![admins](https://cloud.githubusercontent.com/assets/25287008/23461870/67057536-fe6a-11e6-8c95-9b0b33fd6cd5.png) <file_sep><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css" rel='stylesheet' type='text/css'> <div class="container"> <div class="row"> <div class="col-md-10 col-md-offset-1"> <div class="panel panel-default panel-table"> <div class="panel-heading"> <div class="row"> <div class="col col-xs-6"> <h2 class="panel-title">Administradores</h2> </div> <div class="col col-xs-6 text-right"> <?= $this->Html->link('Crear Nuevo', ['controller' => 'Users', 'action' => 'add'], ['class' => 'btn btn-sm btn-primary btn-create', 'escape' => false]); ?> </div> </div> </div> <div class="panel-body"> <table class="table table-striped table-bordered table-list"> <thead> <tr> <th><em class="fa fa-cog"></em></th> <th class="hidden-xs"><?= $this->Paginator->sort('id') ?></th> <th><?= $this->Paginator->sort('first_name', ['Nombre']) ?></th> <th><?= $this->Paginator->sort('last_name', ['Apellido']) ?></th> <th><?= $this->Paginator->sort('email', ['Correo Electrónico']) ?></th> </tr> </thead> <tbody> <?php foreach ($users as $user): ?> <tr> <td align="center"> <?= $this->Html->link('<em class="fa fa-pencil"></em>', ['controller' => 'Users', 'action' => 'edit', $user->id], ['class' => 'btn btn-info', 'escape' => false]); ?> <?= $this->Form->postLink('<em class="fa fa-trash"></em>', ['controller' => 'Users', 'action' => 'delete', $user->id], ['confirm' => '¿Eliminar enlace?', 'class' => 'btn btn-danger', 'escape' => false]) ?> </td> <td class="hidden-xs"><?= $this->Number->format($user->id) ?></td> <td><?= h($user->first_name) ?></td> <td><?= h($user->last_name) ?></td> <td><?= h($user->email) ?></td> </tr> <?php endforeach; ?> </tbody> </table> </div> <div class="panel-footer"> <div class="paginator"> <ul class="pagination"> <?= $this->Paginator->prev('< Anterior') ?> <?= $this->Paginator->numbers(['before' => '', 'after' => '']) ?> <?= $this->Paginator->next('Siguiente >') ?> </ul> <p><?= $this->Paginator->counter() ?></p> </div> </div> </div> </div> </div> </div>
25f7f8c144319b72312efee11d4a0f6cd78a32fe
[ "Markdown", "PHP" ]
9
PHP
JoaquindelaCanal/BibliotecaOnline
9dce96ca46678ad68b57795b732c6f85e1dc9ed1
6d35f527103ab64ad54b64f572fd162eb86ef65a
refs/heads/master
<file_sep>require('dotenv').config() const request = require('postman-request'); const chalk = require('chalk'); const log = console.log; const url = 'http://api.weatherstack.com/current?access_key=3a29528fe3cab2468821e9c844e2a6d1&query=London' // WEATHER STACK API request({url: url, json: true}, (error, response) => { if (error) { log(chalk.red.bold('Connection to the weather service can not be found!')) } else if (response.body.error){ } else { log( `${response.body.current.weather_descriptions[0]}. It's currently ${response.body.current.temperature} degrees out and feels like ${response.body.current.feelslike} degrees` ) } }) <file_sep>require('dotenv').config() const request = require('postman-request') const chalk = require('chalk') const log = console.log const url = 'https://api.mapbox.com/geocoding/v5/mapbox.places/London.json?access_token=<KEY>&limit=1' // MAPBOX API request({url: url, json: true}, (err, res) => { if (err) { log(err) } else if (res.body.features.length === 0){ log(chalk.red.bold('unable to locate location data')) } else { const latitude = res.body.features[0].center[1] const longitude = res.body.features[0].center[0] log(`lat = ${latitude} \nlong = ${longitude}`) } })<file_sep>// npm modules const yargs = require('yargs'); // my modules const notes = require('./notes'); // customise yargs version yargs.version('1.1.0'); // create add cmd --- yargs.command({ command: 'add', describe: 'Add a new note.', builder: { title: { describe: 'Note Title', demandOption: true, type: 'string', }, body: { describe: 'Note Body', demandOption: true, type: 'string', }, }, handler(argv) { notes.addNote(argv.title, argv.body); }, }); // create remove cmd --- yargs.command({ command: 'remove', describe: 'Remove a note.', builder: { title: { describe: 'Note Title', demandOption: true, type: 'string', }, }, handler(argv) { notes.removeNote(argv.title); }, }); // create read cmd --- yargs.command({ command: 'read', describe: 'Reading your notes', builder: { title: { describe: 'Note Title', demandOption: true, type: 'string', }, }, handler(argv) { notes.readNotes(argv.title); }, }); // create list cmd --- yargs.command({ command: 'list', describe: 'Listing your notes', handler() { notes.listNotes(); }, }); yargs.parse(); <file_sep>// ES5 Functions const square = function(x) { return x * x; }; console.log(square(3)); // ES6 Arrow Functions const arrowSquare = x => { return x * x; }; console.log(arrowSquare(4)); const event = { name: 'JAMStack', guestList: ['Paul', 'Fiona', 'Charlie'], printGuestList() { console.log('Guest List for ' + this.name); this.guestList.forEach(guest => { console.log(guest + ' is attending ' + this.name); }); }, }; event.printGuestList(); <file_sep>const fse = require('fs-extra'); const chalk = require('chalk'); const log = console.log; const readNotes = title => { const notes = loadNotes(); const note = notes.find(note => note.title === title); if (note) { console.log(chalk.red(note.title)); console.log(note.body); } else { console.log(chalk.red('NO! Notes found')); } }; // Add Note function. const addNote = (title, body) => { const notes = loadNotes(); const duplicateNote = notes.find(note => note.title === title); if (!duplicateNote) { notes.push({ title: title, body: body, }); saveNotes(notes); log(chalk.blue.bold('A new note was added!')); } else { log(chalk.red('The note title you have picked is already taken!')); } saveNotes(notes); }; // Remove Notes function. const removeNote = title => { const notes = loadNotes(); const notesToKeep = notes.filter(note => note.title !== title); if (notes.length > notesToKeep.length) { log(chalk.green('Your note was removed!')); saveNotes(notesToKeep); } else { log(chalk.red.inverse('No note found!')); } }; const saveNotes = notes => { const dataJSON = JSON.stringify(notes); fse.writeFileSync('notes.json', dataJSON); }; const listNotes = () => { const notes = loadNotes(); console.log(chalk.green('Your notes')); notes.forEach(note => { console.log(note.title); }); }; const loadNotes = () => { try { const dataBuffer = fse.readFileSync('notes.json'); const dataJSON = dataBuffer.toString(); return JSON.parse(dataJSON); } catch (e) { return []; } }; module.exports = { addNote: addNote, removeNote: removeNote, listNotes: listNotes, readNotes: readNotes, }; <file_sep># The Complete Node.js Developer Course (3rd Edition) https://www.udemy.com/course/the-complete-nodejs-developer-course-2/ ## What you'll learn - Completely refilmed for 2019 - Build, test, and launch Node apps - Create Express web servers and APIs - Store data with Mongoose and MongoDB - Use cutting-edge ES6/ES7 JavaScript - Deploy your Node apps to production - Create real-time web apps with SocketIO ### During eight chapters you'll learn: 1. Node.js 2. Npm 3. Asynchronous programming 4. ES6/ES7 5. MongoDB 6. Express 7. Socket.IO 8. JWT Authentication 9. Mongoose 10. File and image uploads 11. Email sending 12. Application deployment with Heroku 13. Version control with Git 14. GitHub 15. REST API Design 16. Code testing 17. Debugging 18. Jest 19. Many more tools
09694e261e3149db9a087373fb1174c952ba3ee6
[ "JavaScript", "Markdown" ]
6
JavaScript
mrpbennett/udemy-complete-node.js-dev-course
46b7c48e52f2ad232d76245e2cc4078f60bcc675
40aee642617ef99d51c36b1304911321e7fe7dc7
refs/heads/master
<file_sep>package com.example.gateway.testvalidationandregex; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.InputFilter; import android.text.Spanned; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MainActivity extends AppCompatActivity { EditText testField; String userName; // just one way to use validation code, not really a regex but it is using Pattern* and Matcher* InputFilter userNameFilter= new InputFilter() { public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { for (int i = start; i < end; i++) { String checkMe = String.valueOf(source.charAt(i)); Pattern pattern = Pattern.compile("[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789_]*"); Matcher matcher = pattern.matcher(checkMe); boolean valid = matcher.matches(); if(!valid){ Log.d("", "invalid"); return ""; } } return null; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setVariables(); } private void setVariables() { testField = (EditText) findViewById(R.id.editText); // validates field to see if its empty when the user is done with it testField.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean focus) { if(!focus){ if( testField.getText().toString().length() == 0 ){ testField.setError( "First name is required!" ); }else if(testField.getText().toString().length() < 4){ testField.setError(" Must be longer than 3 characters"); } } } }); // pretty sweet because it prevents the user from even being able to enter anything but what i stated in the pattern object, so saves processing time to validate testField.setFilters(new InputFilter[]{userNameFilter}); } }
f675132856dd21d813265685b9d3fa624d891adc
[ "Java" ]
1
Java
cBoulio/TestValidationAndRegex
ae80cf8ba3be5f76828ba2046e41b7250a8a8325
861aa4d9a4977b22bf0a32eebe335b22052ca147
refs/heads/master
<file_sep>using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Text.Style; using Android.Views; using Android.Widget; using SBX.Ado; namespace SBX { [Activity(Label = "InventarioActivity")] public class InventarioActivity : Activity { int Validado = 0; string ProductoModificar = ""; string[] Producto; Boolean Guardar = true; string toast = ""; AdoInventario adoInventario = new AdoInventario(); protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your application here SetContentView(Resource.Layout.activity_inventario); Toolbar toolbar = FindViewById<Toolbar>(Resource.Id.toolbar1); SetActionBar(toolbar); ActionBar.Title = "Inventario"; //Cargar proveedor en spinner var Proveedores = adoInventario.AdoSelectProveedores(); Spinner spinner = FindViewById<Spinner>(Resource.Id.spinner); List<string> Proveedor = new List<string>(); foreach (var item in Proveedores) { var resl = item; Proveedor.Add(resl); } var adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerItem, Proveedor); adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); spinner.Adapter = adapter; var recibir = Intent; ProductoModificar = recibir.GetStringExtra("Item"); if (ProductoModificar != null) { Guardar = false; Producto = ProductoModificar.Split("-"); EditText editText_Item = FindViewById<EditText>(Resource.Id.editText_Item); editText_Item.Text = Producto[0]; editText_Item.Enabled = false; EditText editText_Nombre = FindViewById<EditText>(Resource.Id.editText_Nombre); editText_Nombre.Text = Producto[1]; adoInventario.Producto = Producto[0].Trim(); var Productoss = adoInventario.AdoSelectIDTodos(); string Cli = Productoss[0]; string[] Cli2 = Cli.Split("--"); EditText editText_Referencia = FindViewById<EditText>(Resource.Id.editText_Referencia); editText_Referencia.Text = Cli2[2]; EditText editText_iva = FindViewById<EditText>(Resource.Id.editText_iva); editText_iva.Text = Cli2[3]; int IdSeleccionProveedor = 0; string Seleccion = ""; for (int i = 0; i < spinner.Count; i++) { spinner.SetSelection(i); Seleccion = spinner.SelectedItem.ToString().Substring(0, 1); if (Seleccion == Cli2[4].Trim().Substring(0, 1)) { IdSeleccionProveedor = Convert.ToInt32(Seleccion); } } spinner.SetSelection(IdSeleccionProveedor); EditText editText_costo = FindViewById<EditText>(Resource.Id.editText_costo); editText_costo.Text = Cli2[5]; EditText editText_PrecioVenta = FindViewById<EditText>(Resource.Id.editText_PrecioVenta); editText_PrecioVenta.Text = Cli2[6]; } RadioButton radioButtonEntrada = FindViewById<RadioButton>(Resource.Id.rb_entradas); radioButtonEntrada.Checked = true; RadioButton radioButtonSalida = FindViewById<RadioButton>(Resource.Id.rb_Salidas); //Cargar maximo Item if (Guardar == true) { var Productos = adoInventario.AdoSelectMaxItem(); EditText editText = FindViewById<EditText>(Resource.Id.editText_Item); if (Productos[0] != "") { var ItemMax = Convert.ToDouble(Productos[0]) + 1; editText.Text = ItemMax.ToString(); } else { editText.Text = "1"; } } //Button btnSalir = FindViewById<Button>(Resource.Id.btn_salir); //btnSalir.Click += (sender, e) => //{ // var intent = new Intent(this, typeof(MainActivity)); // StartActivity(intent); //}; radioButtonEntrada.Click += (sender, e) => { radioButtonSalida.Checked = false; }; radioButtonSalida.Click += (sender, e) => { radioButtonEntrada.Checked = false; }; //btnGuardar.Click += (sender, e) => //{ //}; } private void spinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { Spinner spinner = (Spinner)sender; string toast = string.Format("The planet is {0}", spinner.GetItemAtPosition(e.Position)); Toast.MakeText(this, toast, ToastLength.Long).Show(); } public override bool OnCreateOptionsMenu(IMenu menu) { MenuInflater.Inflate(Resource.Menu.top_menu, menu); return base.OnCreateOptionsMenu(menu); } public override bool OnOptionsItemSelected(IMenuItem item) { RadioButton radioButtonEntrada = FindViewById<RadioButton>(Resource.Id.rb_entradas); RadioButton radioButtonSalida = FindViewById<RadioButton>(Resource.Id.rb_Salidas); EditText editText_Item = FindViewById<EditText>(Resource.Id.editText_Item); EditText editText_Nombre = FindViewById<EditText>(Resource.Id.editText_Nombre); EditText editText_Referencia = FindViewById<EditText>(Resource.Id.editText_Referencia); EditText editText_iva = FindViewById<EditText>(Resource.Id.editText_iva); Spinner planet_prompt = FindViewById<Spinner>(Resource.Id.spinner); EditText editText_costo = FindViewById<EditText>(Resource.Id.editText_costo); EditText editText_PrecioVenta = FindViewById<EditText>(Resource.Id.editText_PrecioVenta); EditText editText_Cantidad = FindViewById<EditText>(Resource.Id.editText_Cantidad); int Validado = 0; switch (item.TitleFormatted.ToString()) { case "Save": Validado = 0; TextView textViewNombre = FindViewById<TextView>(Resource.Id.text_Nombre); TextView textViewIVA = FindViewById<TextView>(Resource.Id.text_iva); TextView textViewCosto = FindViewById<TextView>(Resource.Id.text_costo); TextView textViewPrecio = FindViewById<TextView>(Resource.Id.text_PrecioVenta); if (editText_Nombre.Text == "") { Validado++; textViewNombre.SetTextColor(Android.Graphics.Color.ParseColor("#E85434")); } else { textViewNombre.SetTextColor(Android.Graphics.Color.ParseColor("#2C3E50")); } if (editText_iva.Text == "") { Validado++; textViewIVA.SetTextColor(Android.Graphics.Color.ParseColor("#E85434")); } else { textViewIVA.SetTextColor(Android.Graphics.Color.ParseColor("#2C3E50")); } if (editText_costo.Text == "") { Validado++; textViewCosto.SetTextColor(Android.Graphics.Color.ParseColor("#E85434")); } else { textViewCosto.SetTextColor(Android.Graphics.Color.ParseColor("#2C3E50")); } if (editText_PrecioVenta.Text == "") { Validado++; textViewPrecio.SetTextColor(Android.Graphics.Color.ParseColor("#E85434")); } else { textViewPrecio.SetTextColor(Android.Graphics.Color.ParseColor("#2C3E50")); } if (Validado == 0) { adoInventario.Item = editText_Item.Text; adoInventario.Nombre = editText_Nombre.Text; adoInventario.Referencia = editText_Referencia.Text; adoInventario.IVA = editText_iva.Text; adoInventario.proveedor = planet_prompt.SelectedItem.ToString(); adoInventario.costo = editText_costo.Text; adoInventario.precioventa = editText_PrecioVenta.Text; if (radioButtonEntrada.Checked) { adoInventario.movimiento = radioButtonEntrada.Text; } else { adoInventario.movimiento = radioButtonSalida.Text; } if (Guardar == true) { toast = adoInventario.AdoCreate(); } else { toast = adoInventario.AdoEditar(); } if (toast == "Producto creado correctamente" || toast == "Producto Editado correctamente") { AdoInventario adoInventario = new AdoInventario(); var Productos2 = adoInventario.AdoSelectMaxItem(); var ItemMax2 = Convert.ToDouble(Productos2[0]) + 1; editText_Item.Text = ItemMax2.ToString(); editText_Nombre.Text = ""; editText_Referencia.Text = ""; editText_iva.Text = ""; editText_costo.Text = ""; editText_PrecioVenta.Text = ""; editText_Cantidad.Text = ""; radioButtonEntrada.Checked = true; Toast.MakeText(this, toast, ToastLength.Long).Show(); } else { Toast.MakeText(this, toast, ToastLength.Long).Show(); } if (toast == "Producto Editado correctamente") { this.FinishAndRemoveTask(); var intent2 = new Intent(this, typeof(ProductoActivity)); StartActivity(intent2); } } else { Toast.MakeText(this, "Ingrese informacion requerida", ToastLength.Long).Show(); } break; case "Consulta": this.FinishAndRemoveTask(); var intent = new Intent(this, typeof(ProductoActivity)); StartActivity(intent); break; case "Delete": if (Guardar == false) { if (editText_Item.Text != "" || editText_Nombre.Text != "") { adoInventario.Item = editText_Item.Text; toast = adoInventario.AdoEliminar(); Toast.MakeText(this, toast, ToastLength.Long).Show(); if (toast == "Producto eliminado correctamente") { this.FinishAndRemoveTask(); var intent2 = new Intent(this, typeof(ProductoActivity)); StartActivity(intent2); } } else { Toast.MakeText(this, "Elije un Producto", ToastLength.Long).Show(); } } else { Toast.MakeText(this, "Elije un Producto", ToastLength.Long).Show(); } break; case "Clear": var Productos = adoInventario.AdoSelectMaxItem(); var ItemMax = Convert.ToDouble(Productos[0]) + 1; editText_Item.Text = ItemMax.ToString(); editText_Nombre.Text = ""; editText_Referencia.Text = ""; editText_iva.Text = ""; editText_costo.Text = ""; editText_PrecioVenta.Text = ""; editText_Cantidad.Text = ""; radioButtonEntrada.Checked = true; Guardar = true; break; default: break; } return base.OnOptionsItemSelected(item); } } }<file_sep>using Android.App; using Android.OS; using Android.Support.V7.App; using Android.Runtime; using Android.Util; using System.Threading.Tasks; using Android.Content; using Android.Widget; using System; using SBX.Ado; using System.IO; namespace SBX { [Activity(Label = "@string/app_name", Theme = "@style/AppTheme")] public class MainActivity : AppCompatActivity { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.activity_main); Button btnProducto = FindViewById<Button>(Resource.Id.btn_producto); btnProducto.Click += (sender, e) => { AdoDataBaseSBX adoDataBaseSBX = new AdoDataBaseSBX(); string toast = adoDataBaseSBX.CreateDataBase(); var intent = new Intent(this, typeof(ProductoActivity)); StartActivity(intent); }; Button btn_EliminarDB = FindViewById<Button>(Resource.Id.btn_eliminarDB); btn_EliminarDB.Click += (sender, e) => { string dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "adoDB_SBX.db3"); File.Delete(dbPath); }; Button btnInventario = FindViewById<Button>(Resource.Id.btn_inventario); btnInventario.Click += (sender, e) => { ////crear base de datos AdoDataBaseSBX adoDataBaseSBX = new AdoDataBaseSBX(); string toast = adoDataBaseSBX.CreateDataBase(); var intent = new Intent(this, typeof(InventarioActivity)); StartActivity(intent); }; Button btnProveedor = FindViewById<Button>(Resource.Id.btn_proveedor); btnProveedor.Click += (sender, e) => { ////crear base de datos AdoDataBaseSBX adoDataBaseSBX = new AdoDataBaseSBX(); string toast = adoDataBaseSBX.CreateDataBase(); var intent = new Intent(this, typeof(ProveedorActivity)); StartActivity(intent); }; Button btnCliente = FindViewById<Button>(Resource.Id.btn_cliente); btnCliente.Click += (sender, e) => { ////crear base de datos AdoDataBaseSBX adoDataBaseSBX = new AdoDataBaseSBX(); string toast = adoDataBaseSBX.CreateDataBase(); var intent = new Intent(this, typeof(ClienteActivity)); StartActivity(intent); }; } public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults) { Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults); base.OnRequestPermissionsResult(requestCode, permissions, grantResults); } } }<file_sep>using System; using Android.App; using Android.Content; using Android.OS; using Android.Views; using Android.Widget; using SBX.Ado; namespace SBX { [Activity(Label = "ViewClienteActivity")] public class ViewClienteActivity : ListActivity { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your application here SetContentView(Resource.Layout.activity_viewCliente); //Button button = FindViewById<Button>(Resource.Id.btn_buscar_cliente); Button btnBuscar = FindViewById<Button>(Resource.Id.btn_buscar_cliente); btnBuscar.Click += ButtonClick; } private void ButtonClick(object sender, EventArgs e) { AutoCompleteTextView textView = FindViewById<AutoCompleteTextView>(Resource.Id.autoCompleteCliente); AdoCliente adoCliente = new AdoCliente(); string cliente = ""; if (textView.Text != "") { cliente = textView.Text; } adoCliente.Cliente = cliente; var Clientes = adoCliente.AdoSelectID(); var adapter = new ArrayAdapter<String>(this, Resource.Layout.list_item, Clientes); textView.Adapter = adapter; ListAdapter = new ArrayAdapter<string>(this, Resource.Layout.list_item, Clientes); ListView.TextFilterEnabled = true; ListView.ItemClick += delegate (object sender, AdapterView.ItemClickEventArgs args) { Toast.MakeText(Application, ((TextView)args.View).Text, ToastLength.Short).Show(); this.FinishAndRemoveTask(); var intent = new Intent(this, typeof(ClienteActivity)); intent.PutExtra("Cliente", ((TextView)args.View).Text); StartActivity(intent); }; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using SBX.Ado; namespace SBX { [Activity(Label = "ViewProveedorActivity")] public class ViewProveedorActivity : ListActivity { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your application here SetContentView(Resource.Layout.activity_viewProveedor); Button button = FindViewById<Button>(Resource.Id.btn_buscar_Proveedor); Button btnBuscar = FindViewById<Button>(Resource.Id.btn_buscar_Proveedor); btnBuscar.Click += ButtonClick; } private void ButtonClick(object sender, EventArgs e) { AutoCompleteTextView textView = FindViewById<AutoCompleteTextView>(Resource.Id.autoCompleteProveedor); AdoProveedor adoProveedor = new AdoProveedor(); string Proveedor = ""; if (textView.Text != "") { Proveedor = textView.Text; } adoProveedor.Proveedor = Proveedor; var Proveedores = adoProveedor.AdoSelectID(); var adapter = new ArrayAdapter<String>(this, Resource.Layout.list_item, Proveedores); textView.Adapter = adapter; ListAdapter = new ArrayAdapter<string>(this, Resource.Layout.list_item, Proveedores); ListView.TextFilterEnabled = true; ListView.ItemClick += delegate (object sender, AdapterView.ItemClickEventArgs args) { Toast.MakeText(Application, ((TextView)args.View).Text, ToastLength.Short).Show(); this.FinishAndRemoveTask(); var intent = new Intent(this, typeof(ProveedorActivity)); intent.PutExtra("Proveedor", ((TextView)args.View).Text); StartActivity(intent); }; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using SBX.Ado; namespace SBX { [Activity(Label = "ProveedorActivity")] public class ProveedorActivity : Activity { int Validado = 0; string ProveedorModificar = ""; string[] Proveedor; AdoProveedor adoProveedor = new AdoProveedor(); Boolean Guardar = true; string toast = ""; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your application here SetContentView(Resource.Layout.activity_proveedor); Toolbar toolbar = FindViewById<Toolbar>(Resource.Id.toolbar1); SetActionBar(toolbar); ActionBar.Title = "Proveedor"; //Button btnSalir = FindViewById<Button>(Resource.Id.btn_salir); //btnSalir.Click += (sender, e) => //{ // var intent = new Intent(this, typeof(MainActivity)); // StartActivity(intent); //}; var recibir = Intent; ProveedorModificar = recibir.GetStringExtra("Proveedor"); if (ProveedorModificar != null) { Guardar = false; Proveedor = ProveedorModificar.Split("-"); EditText editText_DNI = FindViewById<EditText>(Resource.Id.editText_DNI); editText_DNI.Text = Proveedor[0]; editText_DNI.Enabled = false; EditText editText_Nombre = FindViewById<EditText>(Resource.Id.editText_Nombre); editText_Nombre.Text = Proveedor[1]; adoProveedor.Proveedor = Proveedor[0].Trim(); var Proveedores = adoProveedor.AdoSelectIDTodos(); string Cli = Proveedores[0]; string[] Cli2 = Cli.Split("-"); EditText editText_Ciudad = FindViewById<EditText>(Resource.Id.editText_Ciudad); editText_Ciudad.Text = Cli2[2]; EditText editText_Direccion = FindViewById<EditText>(Resource.Id.editText_Direccion); editText_Direccion.Text = Cli2[3]; EditText editText_Telefono = FindViewById<EditText>(Resource.Id.editText_telefono); editText_Telefono.Text = Cli2[4]; EditText editText_Celular = FindViewById<EditText>(Resource.Id.editText_Celular); editText_Celular.Text = Cli2[5]; EditText editText_Email = FindViewById<EditText>(Resource.Id.editText_Email); editText_Email.Text = Cli2[6]; EditText editText_SitioWeb = FindViewById<EditText>(Resource.Id.editText_StiioWeb); editText_SitioWeb.Text = Cli2[7]; } } public override bool OnCreateOptionsMenu(IMenu menu) { MenuInflater.Inflate(Resource.Menu.top_menu, menu); return base.OnCreateOptionsMenu(menu); } public override bool OnOptionsItemSelected(IMenuItem item) { TextView textViewDNI = FindViewById<TextView>(Resource.Id.text_DNI); textViewDNI.SetTextColor(Android.Graphics.Color.ParseColor("#2C3E50")); TextView textViewNombre = FindViewById<TextView>(Resource.Id.text_Nombre); textViewNombre.SetTextColor(Android.Graphics.Color.ParseColor("#2C3E50")); TextView textViewCiudad = FindViewById<TextView>(Resource.Id.text_Ciudad); textViewCiudad.SetTextColor(Android.Graphics.Color.ParseColor("#2C3E50")); TextView textViewDireccion = FindViewById<TextView>(Resource.Id.text_Direccion); textViewDireccion.SetTextColor(Android.Graphics.Color.ParseColor("#2C3E50")); TextView textViewTelefono = FindViewById<TextView>(Resource.Id.text_telefono); textViewTelefono.SetTextColor(Android.Graphics.Color.ParseColor("#2C3E50")); TextView textViewCelular = FindViewById<TextView>(Resource.Id.text_celular); textViewCelular.SetTextColor(Android.Graphics.Color.ParseColor("#2C3E50")); TextView textViewEmail = FindViewById<TextView>(Resource.Id.text_Email); textViewEmail.SetTextColor(Android.Graphics.Color.ParseColor("#2C3E50")); TextView textViewSitioWeb = FindViewById<TextView>(Resource.Id.text_sitioWeb); textViewSitioWeb.SetTextColor(Android.Graphics.Color.ParseColor("#2C3E50")); EditText editText_DNI = FindViewById<EditText>(Resource.Id.editText_DNI); EditText editText_Nombre = FindViewById<EditText>(Resource.Id.editText_Nombre); EditText editText_Ciudad = FindViewById<EditText>(Resource.Id.editText_Ciudad); EditText editText_Direccion = FindViewById<EditText>(Resource.Id.editText_Direccion); EditText editText_Telefono = FindViewById<EditText>(Resource.Id.editText_telefono); EditText editText_Celular = FindViewById<EditText>(Resource.Id.editText_Celular); EditText editText_Email = FindViewById<EditText>(Resource.Id.editText_Email); EditText editText_SitioWeb = FindViewById<EditText>(Resource.Id.editText_StiioWeb); AdoProveedor adoProveedor = new AdoProveedor(); switch (item.TitleFormatted.ToString()) { case "Save": Validado = 0; //TextView textViewDNI = FindViewById<TextView>(Resource.Id.text_DNI); if (editText_DNI.Text == "") { Validado++; textViewDNI.SetTextColor(Android.Graphics.Color.ParseColor("#E85434")); } else { //valida existencia de DNI adoProveedor.Proveedor = editText_DNI.Text; var resp = adoProveedor.AdoSelectID(); if (resp[0] != "") { Toast.MakeText(this, "DNI ya existe", ToastLength.Long).Show(); textViewDNI.SetTextColor(Android.Graphics.Color.ParseColor("#E85434")); Validado++; } else { textViewDNI.SetTextColor(Android.Graphics.Color.ParseColor("#2C3E50")); } } //TextView textViewNombre = FindViewById<TextView>(Resource.Id.text_Nombre); if (editText_Nombre.Text == "") { Validado++; textViewNombre.SetTextColor(Android.Graphics.Color.ParseColor("#E85434")); } else { textViewNombre.SetTextColor(Android.Graphics.Color.ParseColor("#2C3E50")); } //TextView textViewCelular = FindViewById<TextView>(Resource.Id.text_celular); if (editText_Celular.Text == "") { Validado++; textViewCelular.SetTextColor(Android.Graphics.Color.ParseColor("#E85434")); } else { textViewCelular.SetTextColor(Android.Graphics.Color.ParseColor("#2C3E50")); } if (Validado == 0) { adoProveedor.DNI = editText_DNI.Text; adoProveedor.Nombre = editText_Nombre.Text; adoProveedor.Ciudad = editText_Ciudad.Text; adoProveedor.Direccion = editText_Direccion.Text; adoProveedor.Telefono = editText_Telefono.Text; adoProveedor.Celular = editText_Celular.Text; adoProveedor.Email = editText_Email.Text; adoProveedor.SitioWeb = editText_SitioWeb.Text; if (Guardar == true) { toast = adoProveedor.AdoCreate(); } else { toast = adoProveedor.AdoEditar(); } if (toast == "Proveedor creado correctamente" || toast == "Proveedor Editado correctamente") { editText_DNI.Text = ""; editText_Nombre.Text = ""; editText_Ciudad.Text = ""; editText_Direccion.Text = ""; editText_Telefono.Text = ""; editText_Celular.Text = ""; editText_Email.Text = ""; editText_SitioWeb.Text = ""; Toast.MakeText(this, toast, ToastLength.Long).Show(); } else { Toast.MakeText(this, toast, ToastLength.Long).Show(); } if (toast == "Cliente Editado correctamente") { this.FinishAndRemoveTask(); var intent2 = new Intent(this, typeof(ViewProveedorActivity)); StartActivity(intent2); } } break; case "Consulta": this.FinishAndRemoveTask(); var intent = new Intent(this, typeof(ViewProveedorActivity)); StartActivity(intent); break; case "Delete": if (Guardar == false) { if (editText_DNI.Text != "") { adoProveedor.DNI = editText_DNI.Text; toast = adoProveedor.AdoEliminar(); Toast.MakeText(this, toast, ToastLength.Long).Show(); if (toast == "Proveedor eliminado correctamente") { this.FinishAndRemoveTask(); var intent2 = new Intent(this, typeof(ViewProveedorActivity)); StartActivity(intent2); } } else { Toast.MakeText(this, "Elije un Proveedor", ToastLength.Long).Show(); } } else { Toast.MakeText(this, "Elije un Proveedor", ToastLength.Long).Show(); } break; case "Clear": editText_DNI.Text = ""; editText_Nombre.Text = ""; editText_Ciudad.Text = ""; editText_Direccion.Text = ""; editText_Telefono.Text = ""; editText_Celular.Text = ""; editText_Email.Text = ""; editText_SitioWeb.Text = ""; Guardar = true; break; default: break; } return base.OnOptionsItemSelected(item); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Org.Apache.Http.Conn; using SBX.Ado; namespace SBX { [Activity(Label = "ClienteActivity")] public class ClienteActivity : Activity { int Validado = 0; string ClienteModificar = ""; string[] Cliente; AdoCliente AdoCliente = new AdoCliente(); Boolean Guardar = true; string toast = ""; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your application here SetContentView(Resource.Layout.activity_cliente); Toolbar toolbar = FindViewById<Toolbar>(Resource.Id.toolbar1); SetActionBar(toolbar); ActionBar.Title = "Cliente"; //Button btnSalir = FindViewById<Button>(Resource.Id.btn_salir); //btnSalir.Click += (sender, e) => //{ // var intent = new Intent(this, typeof(MainActivity)); // StartActivity(intent); //}; var recibir = Intent; ClienteModificar = recibir.GetStringExtra("Cliente"); if (ClienteModificar != null) { Guardar = false; Cliente = ClienteModificar.Split("-"); EditText editText_DNI = FindViewById<EditText>(Resource.Id.editText_DNI); editText_DNI.Text = Cliente[0]; editText_DNI.Enabled = false; EditText editText_Nombre = FindViewById<EditText>(Resource.Id.editText_Nombre); editText_Nombre.Text = Cliente[1]; AdoCliente.Cliente = Cliente[0].Trim(); var Clientes = AdoCliente.AdoSelectIDTodos(); string Cli = Clientes[0]; string[] Cli2 = Cli.Split("-"); EditText editText_Ciudad = FindViewById<EditText>(Resource.Id.editText_Ciudad); editText_Ciudad.Text = Cli2[2]; EditText editText_Direccion = FindViewById<EditText>(Resource.Id.editText_Direccion); editText_Direccion.Text = Cli2[3]; EditText editText_Telefono = FindViewById<EditText>(Resource.Id.editText_telefono); editText_Telefono.Text = Cli2[4]; EditText editText_Celular = FindViewById<EditText>(Resource.Id.editText_Celular); editText_Celular.Text = Cli2[5]; EditText editText_Email = FindViewById<EditText>(Resource.Id.editText_Email); editText_Email.Text = Cli2[6]; EditText editText_SitioWeb = FindViewById<EditText>(Resource.Id.editText_StiioWeb); editText_SitioWeb.Text = Cli2[7]; } } public override bool OnCreateOptionsMenu(IMenu menu) { MenuInflater.Inflate(Resource.Menu.top_menu, menu); return base.OnCreateOptionsMenu(menu); } public override bool OnOptionsItemSelected(IMenuItem item) { TextView textViewDNI = FindViewById<TextView>(Resource.Id.text_DNI); textViewDNI.SetTextColor(Android.Graphics.Color.ParseColor("#2C3E50")); TextView textViewNombre = FindViewById<TextView>(Resource.Id.text_Nombre); textViewNombre.SetTextColor(Android.Graphics.Color.ParseColor("#2C3E50")); TextView textViewCiudad = FindViewById<TextView>(Resource.Id.text_Ciudad); textViewCiudad.SetTextColor(Android.Graphics.Color.ParseColor("#2C3E50")); TextView textViewDireccion = FindViewById<TextView>(Resource.Id.text_Direccion); textViewDireccion.SetTextColor(Android.Graphics.Color.ParseColor("#2C3E50")); TextView textViewTelefono = FindViewById<TextView>(Resource.Id.text_telefono); textViewTelefono.SetTextColor(Android.Graphics.Color.ParseColor("#2C3E50")); TextView textViewCelular = FindViewById<TextView>(Resource.Id.text_celular); textViewCelular.SetTextColor(Android.Graphics.Color.ParseColor("#2C3E50")); TextView textViewEmail = FindViewById<TextView>(Resource.Id.text_Email); textViewEmail.SetTextColor(Android.Graphics.Color.ParseColor("#2C3E50")); TextView textViewSitioWeb = FindViewById<TextView>(Resource.Id.text_sitioWeb); textViewSitioWeb.SetTextColor(Android.Graphics.Color.ParseColor("#2C3E50")); EditText editText_DNI = FindViewById<EditText>(Resource.Id.editText_DNI); EditText editText_Nombre = FindViewById<EditText>(Resource.Id.editText_Nombre); EditText editText_Ciudad = FindViewById<EditText>(Resource.Id.editText_Ciudad); EditText editText_Direccion = FindViewById<EditText>(Resource.Id.editText_Direccion); EditText editText_Telefono = FindViewById<EditText>(Resource.Id.editText_telefono); EditText editText_Celular = FindViewById<EditText>(Resource.Id.editText_Celular); EditText editText_Email = FindViewById<EditText>(Resource.Id.editText_Email); EditText editText_SitioWeb = FindViewById<EditText>(Resource.Id.editText_StiioWeb); AdoCliente adoCliente = new AdoCliente(); switch (item.TitleFormatted.ToString()) { case "Save": Validado = 0; //TextView textViewDNI = FindViewById<TextView>(Resource.Id.text_DNI); if (editText_DNI.Text == "") { Validado++; textViewDNI.SetTextColor(Android.Graphics.Color.ParseColor("#E85434")); } else { //valida existencia de DNI adoCliente.Cliente = editText_DNI.Text; var resp = adoCliente.AdoSelectID(); if (resp[0] != "") { Toast.MakeText(this, "DNI ya existe", ToastLength.Long).Show(); textViewDNI.SetTextColor(Android.Graphics.Color.ParseColor("#E85434")); Validado++; } else { textViewDNI.SetTextColor(Android.Graphics.Color.ParseColor("#2C3E50")); } } //TextView textViewNombre = FindViewById<TextView>(Resource.Id.text_Nombre); if (editText_Nombre.Text == "") { Validado++; textViewNombre.SetTextColor(Android.Graphics.Color.ParseColor("#E85434")); } else { textViewNombre.SetTextColor(Android.Graphics.Color.ParseColor("#2C3E50")); } //TextView textViewCelular = FindViewById<TextView>(Resource.Id.text_celular); if (editText_Celular.Text == "") { Validado++; textViewCelular.SetTextColor(Android.Graphics.Color.ParseColor("#E85434")); } else { textViewCelular.SetTextColor(Android.Graphics.Color.ParseColor("#2C3E50")); } if (Validado == 0) { adoCliente.DNI = editText_DNI.Text; adoCliente.Nombre = editText_Nombre.Text; adoCliente.Ciudad = editText_Ciudad.Text; adoCliente.Direccion = editText_Direccion.Text; adoCliente.Telefono = editText_Telefono.Text; adoCliente.Celular = editText_Celular.Text; adoCliente.Email = editText_Email.Text; adoCliente.SitioWeb = editText_SitioWeb.Text; if (Guardar == true) { toast = adoCliente.AdoCreate(); } else { toast = adoCliente.AdoEditar(); } if (toast == "Cliente creado correctamente" || toast == "Cliente Editado correctamente") { editText_DNI.Text = ""; editText_Nombre.Text = ""; editText_Ciudad.Text = ""; editText_Direccion.Text = ""; editText_Telefono.Text = ""; editText_Celular.Text = ""; editText_Email.Text = ""; editText_SitioWeb.Text = ""; Toast.MakeText(this, toast, ToastLength.Long).Show(); } else { Toast.MakeText(this, toast, ToastLength.Long).Show(); } if (toast == "Cliente Editado correctamente") { this.FinishAndRemoveTask(); var intent2 = new Intent(this, typeof(ViewClienteActivity)); StartActivity(intent2); } } break; case "Consulta": this.FinishAndRemoveTask(); var intent = new Intent(this, typeof(ViewClienteActivity)); StartActivity(intent); break; case "Delete": if (Guardar == false) { if (editText_DNI.Text != "") { adoCliente.DNI = editText_DNI.Text; toast = adoCliente.AdoEliminar(); Toast.MakeText(this, toast, ToastLength.Long).Show(); if (toast == "Cliente eliminado correctamente") { this.FinishAndRemoveTask(); var intent2 = new Intent(this, typeof(ViewClienteActivity)); StartActivity(intent2); } } else { Toast.MakeText(this, "Elije un Cliente", ToastLength.Long).Show(); } } else { Toast.MakeText(this, "Elije un Cliente", ToastLength.Long).Show(); } break; case "Clear": editText_DNI.Text = ""; editText_Nombre.Text = ""; editText_Ciudad.Text = ""; editText_Direccion.Text = ""; editText_Telefono.Text = ""; editText_Celular.Text = ""; editText_Email.Text = ""; editText_SitioWeb.Text = ""; Guardar = true; break; default: break; } return base.OnOptionsItemSelected(item); } } }<file_sep>using System; using System.ComponentModel; using System.IO; using Android.Database.Sqlite; using Mono.Data.Sqlite; namespace SBX.Ado { class AdoInventario { public static SqliteConnection connection; public string Item { get; set; } public string Nombre { get; set; } public string Referencia { get; set; } public string IVA { get; set; } public string proveedor { get; set; } public string Cantidad { get; set; } public string costo { get; set; } public string precioventa { get; set; } public string Producto { get; set; } public string movimiento { get; set; } public string output = ""; public string AdoCreate() { string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "adoDB_SBX.db3"); bool exists = File.Exists(dbPath); if (exists) { connection = new SqliteConnection("Data Source=" + dbPath); connection.Open(); var commandsInsert = new[] { "INSERT INTO [Producto] ([Item], [Nombre],[Referencia],[IVA],[Proveedor],[Cantidad],[Costo],[PrecioVenta],[Movimiento]) " + "VALUES ('"+Item+"', '"+Nombre+"','"+Referencia+"','"+IVA+"','"+proveedor+"','"+Cantidad+"','"+costo+"','"+precioventa+"','"+movimiento+"')" }; foreach (var command in commandsInsert) { using (var c = connection.CreateCommand()) { c.CommandText = command; var i = c.ExecuteNonQuery(); } } output = "Producto creado correctamente"; connection.Close(); } else { output += "No existe base de datos"; } return output; } public String[] AdoSelect() { string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "adoDB_SBX.db3"); bool exists = File.Exists(dbPath); String[] foos = null; if (exists) { connection = new SqliteConnection("Data Source=" + dbPath); connection.Open(); using (var contents = connection.CreateCommand()) { contents.CommandText = "SELECT (SELECT COUNT(*) FROM Producto) fila,[Item],[Nombre],[Referencia],[IVA],[Proveedor],[Cantidad],[Costo],[PrecioVenta] from [Producto]"; var r = contents.ExecuteReader(); int contador = 0; if (r.HasRows) { int filas = Convert.ToInt32(r["fila"]); foos = new String[filas]; while (r.Read()) { foos[contador] = r["Item"].ToString() + " - "+ r["Nombre"].ToString() + " - " +r["Referencia"].ToString(); contador++; } } else { foos = new String[1]; foos[0] = ""; } } connection.Close(); } return foos; } public String[] AdoSelectMaxItem() { string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "adoDB_SBX.db3"); bool exists = File.Exists(dbPath); String[] foos = null; if (exists) { connection = new SqliteConnection("Data Source=" + dbPath); connection.Open(); using (var contents = connection.CreateCommand()) { contents.CommandText = "SELECT MAX([Item]) Item from [Producto]"; var r = contents.ExecuteReader(); int contador = 0; if (r.HasRows) { int filas = 1; foos = new String[filas]; while (r.Read()) { foos[contador] = r["Item"].ToString(); contador++; } } else { foos = new String[1]; foos[0] = ""; } } connection.Close(); } return foos; } public String[] AdoSelectProveedores() { string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "adoDB_SBX.db3"); bool exists = File.Exists(dbPath); String[] foos = null; if (exists) { connection = new SqliteConnection("Data Source=" + dbPath); connection.Open(); using (var contents = connection.CreateCommand()) { contents.CommandText = "SELECT (SELECT COUNT(*) FROM Proveedor) fila,[DNI],[Nombre] from [Proveedor]"; var r = contents.ExecuteReader(); int contador = 0; if (r.HasRows) { int filas = Convert.ToInt32(r["fila"]); ; foos = new String[filas]; while (r.Read()) { foos[contador] = r["DNI"].ToString() + "-" + r["Nombre"].ToString(); contador++; } } else { foos = new String[1]; foos[0] = ""; } } connection.Close(); } return foos; } public String[] AdoSelectID() { string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "adoDB_SBX.db3"); bool exists = File.Exists(dbPath); String[] foos = null; if (exists) { connection = new SqliteConnection("Data Source=" + dbPath); connection.Open(); using (var contents = connection.CreateCommand()) { if (Item != "") { contents.CommandText = "SELECT (SELECT COUNT(*) FROM Producto WHERE [Item] = '" + Item + "') fila,[Item],[Nombre],[Referencia],[IVA]," + "[Proveedor],[Costo],[PrecioVenta] from [Producto]" + "WHERE [Item] = '" + Item +"'"; } else { contents.CommandText = "SELECT (SELECT COUNT(*) FROM Producto) fila,[Item],[Nombre],[Referencia],[IVA]," + "[Proveedor],[Costo],[PrecioVenta] from [Producto] "; } var r = contents.ExecuteReader(); int contador = 0; if (r.HasRows) { int filas = Convert.ToInt32(r["fila"]); foos = new String[filas]; while (r.Read()) { foos[contador] = r["Item"].ToString() + " - " + r["Nombre"].ToString() + " - " + r["Referencia"].ToString(); contador++; } } else { foos = new String[1]; foos[0] = ""; } } connection.Close(); } return foos; } public String[] AdoSelectIDTodos() { string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "adoDB_SBX.db3"); bool exists = File.Exists(dbPath); String[] foos = null; if (exists) { connection = new SqliteConnection("Data Source=" + dbPath); connection.Open(); using (var contents = connection.CreateCommand()) { if (Producto != "") { contents.CommandText = "SELECT (SELECT COUNT(*) FROM Producto WHERE [Item] = '" + Producto + "') fila,[Item],[Nombre],[Referencia],[IVA]," + "[Proveedor],[Costo],[PrecioVenta] from [Producto]" + "WHERE [Item] = '" + Producto + "'"; } else { contents.CommandText = "SELECT (SELECT COUNT(*) FROM Producto WHERE [Item] = '" + Producto + "') fila,[Item],[Nombre],[Referencia],[IVA]," + "[Proveedor],[Costo],[PrecioVenta] from [Producto] "; } var r = contents.ExecuteReader(); int contador = 0; if (r.HasRows) { int filas = Convert.ToInt32(r["fila"]); foos = new String[filas]; while (r.Read()) { foos[contador] = r["Item"].ToString() + " -- " + r["Nombre"].ToString() + " -- " + r["Referencia"].ToString() + " -- " + r["IVA"].ToString() + " -- " + r["Proveedor"].ToString() + " -- " + r["Costo"].ToString() + " -- " + r["PrecioVenta"].ToString(); contador++; } } else { foos = new String[1]; foos[0] = ""; } } connection.Close(); } return foos; } public string AdoEditar() { try { string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "adoDB_SBX.db3"); bool exists = File.Exists(dbPath); if (exists) { connection = new SqliteConnection("Data Source=" + dbPath); connection.Open(); var commandsInsert = new[] { " UPDATE [Producto] SET [Nombre] = '"+Nombre+"',[Referencia] = '"+Referencia+"',[IVA] = '"+IVA+"',[Proveedor] = '"+proveedor+"',[Cantidad] = '"+Cantidad+"',[Costo] = '"+costo+"',[PrecioVenta] = '"+precioventa+"' "+ " WHERE [Item] = '"+Item.Trim()+"'" }; foreach (var command in commandsInsert) { using (var c = connection.CreateCommand()) { c.CommandText = command; var i = c.ExecuteNonQuery(); } } output = "Producto Editado correctamente"; connection.Close(); } else { output += "No existe base de datos"; } } catch (Exception ex) { output = "Error: " + ex.Message; } return output; } public string AdoEliminar() { try { string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "adoDB_SBX.db3"); bool exists = File.Exists(dbPath); if (exists) { connection = new SqliteConnection("Data Source=" + dbPath); connection.Open(); var commandsInsert = new[] { " DELETE FROM [Producto] "+ " WHERE [Item] = '"+Item.Trim()+"'" }; foreach (var command in commandsInsert) { using (var c = connection.CreateCommand()) { c.CommandText = command; var i = c.ExecuteNonQuery(); } } output = "Producto eliminado correctamente"; connection.Close(); } else { output += "No existe base de datos"; } } catch (Exception ex) { output = "Error: " + ex.Message; } return output; } } }<file_sep>using System; using System.IO; using Mono.Data.Sqlite; namespace SBX.Ado { class AdoProveedor { public static SqliteConnection connection; public string DNI { get; set; } public string Nombre { get; set; } public string Ciudad { get; set; } public string Direccion { get; set; } public string Telefono { get; set; } public string Celular { get; set; } public string Email { get; set; } public string Proveedor { get; set; } public string SitioWeb { get; set; } public string output = ""; public string AdoCreate() { try { string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "adoDB_SBX.db3"); bool exists = File.Exists(dbPath); if (exists) { connection = new SqliteConnection("Data Source=" + dbPath); connection.Open(); var commandsInsert = new[] { "INSERT INTO [Proveedor] ([DNI], [Nombre],[Ciudad],[Direccion],[Telefono],[Celular],[Email],[SitioWeb]) " + "VALUES ('"+DNI+"', '"+Nombre+"','"+Ciudad+"','"+Direccion+"','"+Telefono+"','"+Celular+"','"+Email+"','"+SitioWeb+"')" }; foreach (var command in commandsInsert) { using (var c = connection.CreateCommand()) { c.CommandText = command; var i = c.ExecuteNonQuery(); } } output = "Proveedor creado correctamente"; connection.Close(); } else { output += "No existe base de datos"; } } catch (Exception ex) { output = "Error: " + ex.Message; } return output; } public string AdoEditar() { try { string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "adoDB_SBX.db3"); bool exists = File.Exists(dbPath); if (exists) { connection = new SqliteConnection("Data Source=" + dbPath); connection.Open(); var commandsInsert = new[] { " UPDATE [Proveedor] SET [Nombre] = '"+Nombre+"',[Ciudad] = '"+Ciudad+"',[Direccion] = '"+Direccion+"',[Telefono] = '"+Telefono+"',[Celular] = '"+Celular+"',[Email] = '"+Email+"',[SitioWeb] = '"+SitioWeb+"' "+ " WHERE [DNI] = '"+DNI.Trim()+"'" }; foreach (var command in commandsInsert) { using (var c = connection.CreateCommand()) { c.CommandText = command; var i = c.ExecuteNonQuery(); } } output = "Proveedor Editado correctamente"; connection.Close(); } else { output += "No existe base de datos"; } } catch (Exception ex) { output = "Error: " + ex.Message; } return output; } public String[] AdoSelectID() { string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "adoDB_SBX.db3"); bool exists = File.Exists(dbPath); String[] foos = null; if (exists) { connection = new SqliteConnection("Data Source=" + dbPath); connection.Open(); using (var contents = connection.CreateCommand()) { if (Proveedor != "") { contents.CommandText = "SELECT (SELECT COUNT(*) FROM Proveedor WHERE [DNI] = '" + Proveedor + "') fila,DNI,Nombre,Ciudad,Direccion,Telefono,Celular,Email,SitioWeb" + " from [Proveedor]" + "WHERE [DNI] = '" + Proveedor + "'"; } else { contents.CommandText = "SELECT (SELECT COUNT(*) FROM Proveedor) fila,DNI,Nombre,Ciudad,Direccion,Telefono,Celular,Email,SitioWeb " + "from [Proveedor] "; } var r = contents.ExecuteReader(); int contador = 0; if (r.HasRows) { int filas = Convert.ToInt32(r["fila"]); foos = new String[filas]; while (r.Read()) { foos[contador] = r["DNI"].ToString() + " - " + r["Nombre"].ToString(); contador++; } } else { foos = new String[1]; foos[0] = ""; } } connection.Close(); } return foos; } public string AdoEliminar() { try { string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "adoDB_SBX.db3"); bool exists = File.Exists(dbPath); if (exists) { connection = new SqliteConnection("Data Source=" + dbPath); connection.Open(); var commandsInsert = new[] { " DELETE FROM [Proveedor] "+ " WHERE [DNI] = '"+DNI.Trim()+"'" }; foreach (var command in commandsInsert) { using (var c = connection.CreateCommand()) { c.CommandText = command; var i = c.ExecuteNonQuery(); } } output = "Proveedor eliminado correctamente"; connection.Close(); } else { output += "No existe base de datos"; } } catch (Exception ex) { output = "Error: " + ex.Message; } return output; } public String[] AdoSelectIDTodos() { string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "adoDB_SBX.db3"); bool exists = File.Exists(dbPath); String[] foos = null; if (exists) { connection = new SqliteConnection("Data Source=" + dbPath); connection.Open(); using (var contents = connection.CreateCommand()) { if (Proveedor != "") { contents.CommandText = "SELECT (SELECT COUNT(*) FROM Proveedor WHERE [DNI] = '" + Proveedor + "') fila,DNI,Nombre,Ciudad,Direccion,Telefono,Celular,Email,SitioWeb" + " from [Proveedor]" + "WHERE [DNI] = '" + Proveedor + "'"; } else { contents.CommandText = "SELECT (SELECT COUNT(*) FROM Proveedor) fila,DNI,Nombre,Ciudad,Direccion,Telefono,Celular,Email,SitioWeb " + "from [Proveedor] "; } var r = contents.ExecuteReader(); int contador = 0; if (r.HasRows) { int filas = Convert.ToInt32(r["fila"]); foos = new String[filas]; while (r.Read()) { foos[contador] = r["DNI"].ToString() + " -- " + r["Nombre"].ToString() + " -- " + r["Ciudad"].ToString() + " -- " + r["Direccion"].ToString() + " -- " + r["Telefono"].ToString() + " -- " + r["Celular"].ToString() + " -- " + r["Email"].ToString() + " -- " + r["SitioWeb"].ToString(); contador++; } } else { foos = new String[1]; foos[0] = ""; } } connection.Close(); } return foos; } } }<file_sep>using System; using System.IO; using Mono.Data.Sqlite; namespace SBX.Ado { class AdoDataBaseSBX { public static SqliteConnection connection; public string CreateDataBase() { var respuesta = ""; string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "adoDB_SBX.db3"); bool exists = File.Exists(dbPath); if (!exists) { Mono.Data.Sqlite.SqliteConnection.CreateFile(dbPath); connection = new SqliteConnection("Data Source=" + dbPath); connection.Open(); var commands = new[] { "CREATE TABLE [Proveedor] (DNI ntext PRIMARY KEY, Nombre ntext, Ciudad ntext, Direccion ntext, " + "Telefono ntext, Celular ntext, Email ntext,SitioWeb ntext);" , "INSERT INTO [Proveedor] ([DNI], [Nombre],[Ciudad],[Direccion],[Telefono],[Celular],[Email],[SitioWeb]) " + "VALUES ('0', 'N/A','','','0','0','0','0')" , "CREATE TABLE [Producto] (Item ntext, Nombre ntext, Referencia ntext," + " IVA FLOAT, Proveedor ntext,Cantidad ntext, Costo MONEY, PrecioVenta MONEY, Movimiento ntext, " + " FOREIGN KEY(Proveedor) REFERENCES Proveedor(DNI));" , "CREATE TABLE [Cliente] (DNI ntext PRIMARY KEY, Nombre ntext, Ciudad ntext, Direccion ntext, " + "Telefono ntext, Celular ntext, Email ntext,SitioWeb ntext);" , "INSERT INTO [Cliente] ([DNI], [Nombre],[Ciudad],[Direccion],[Telefono],[Celular],[Email],[SitioWeb]) " + "VALUES ('0', 'N/A','','','0','0','0','0')" }; foreach (var command in commands) { using (var c = connection.CreateCommand()) { c.CommandText = command; var i = c.ExecuteNonQuery(); } } respuesta = "Base de datos Creada Correctamente"; connection.Close(); } else { respuesta = "adoDB_SBX.db3"; } return respuesta; } } }<file_sep>using System; using Android.App; using Android.Content; using Android.OS; using Android.Views; using Android.Widget; using SBX.Ado; namespace SBX { [Activity(Label = "Producto")] public class ProductoActivity : ListActivity { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your application here SetContentView(Resource.Layout.activity_producto); //AdoInventario adoInventario = new AdoInventario(); //AutoCompleteTextView textView = FindViewById<AutoCompleteTextView>(Resource.Id.autoCompleteProducto); //var Productos = adoInventario.AdoSelect(); //var adapter = new ArrayAdapter<String>(this, Resource.Layout.list_item, Productos); //textView.Adapter = adapter; //textView.ItemClick += delegate (object sender, AdapterView.ItemClickEventArgs args) //{ // Toast.MakeText(Application,"hola", ToastLength.Short).Show(); //}; //ListAdapter = new ArrayAdapter<string>(this, Resource.Layout.list_item, Productos); //ListView.TextFilterEnabled = true; //ListView.ItemClick += delegate (object sender, AdapterView.ItemClickEventArgs args) //{ // Toast.MakeText(Application, ((TextView)args.View).Text, ToastLength.Short).Show(); //}; Button btnBuscar = FindViewById<Button>(Resource.Id.btn_buscar); btnBuscar.Click += ButtonClick; } private void ButtonClick(object sender, EventArgs e) { AutoCompleteTextView textView = FindViewById<AutoCompleteTextView>(Resource.Id.autoCompleteProducto); AdoInventario adoInventarioID = new AdoInventario(); string item = ""; if (textView.Text != "") { item = textView.Text.Substring(0, 1); } adoInventarioID.Item = item; var Productos = adoInventarioID.AdoSelectID(); var adapter = new ArrayAdapter<String>(this, Resource.Layout.list_item, Productos); textView.Adapter = adapter; ListAdapter = new ArrayAdapter<string>(this, Resource.Layout.list_item, Productos); ListView.TextFilterEnabled = true; ListView.ItemClick += delegate (object sender, AdapterView.ItemClickEventArgs args) { Toast.MakeText(Application, ((TextView)args.View).Text, ToastLength.Short).Show(); this.FinishAndRemoveTask(); var intent = new Intent(this, typeof(InventarioActivity)); intent.PutExtra("Item", ((TextView)args.View).Text); StartActivity(intent); }; } } }
eb8f2deaeea602716ee39660dccd57b431f8ef09
[ "C#" ]
10
C#
rubenxd/SBX_Movil
911ae7df1c5dd9e664419d6e0c87ea8e1964d0d8
5e209ca50008190ccdd99ae1961d619e86546ab3
refs/heads/master
<file_sep>function UserController ($scope, $http, SERVER, $state, $cookies, $rootScope) { $scope.signUp = (user) => { console.log(user); $http.post(`${SERVER}/users`, user).then(resp => { console.log(resp); console.log('user created'); }).catch(error => { console.log(error); }); }; $scope.signIn = (user) => { //console.log('from inside signin'); // console.log(user); $http.post(`${SERVER}/login`, user).then(resp => { // console.log(user) $rootScope.loggedIn = true; console.log(resp.data); $cookies.put('access-token', resp.data.token); $cookies.put('user-id', resp.data.user.id); $http.defaults.headers.common['access-token'] = resp.data.token; $state.go('root.home'); }).catch(error => { console.log(error); }); }; } UserController.$inject = ['$scope', '$http', 'SERVER', '$state', '$cookies', '$rootScope']; export default UserController; <file_sep># Hackathon-Frontend This was a team based project where my teammate <NAME> and I worked to build an Instagram like website in a Hackathon over the course of two and a half days. This was also our first shot at building and deploying a full site with both an integrated front and backend. We used Node.js, Express, and Sequelize for our backend and AngularJS for our frontend. #### The Home Page The first page of the website displays all of the the photos uploaded by our users. If you wish to take a closer look at an image, you may hover over an image and click the view icon. This will then take you to a new page with a larger picture of that image. #### The Image Page Not only does this page allow you view a bigger image but also allows users to comment on the image and share their thoughts. #### User Page Users also have their own user page which displays all of their work. If you see a particular image you like and want to see more of what that user has uploaded, you can hover an image and click the user icon. This will then take you to their user page. Users can also upload a profile picture to their user page. #### Sign Up Signing up for our site is easy. Just click on the sign up/ sign in button at the top of the page and fill out the information. [Live Site](http://tiy-houseofkal-el-hackathon-frontend.surge.sh) <file_sep>function PhotoSingleController ($scope, $http, SERVER, $state) { $scope.comments = []; function init () { //need to change and add correct id params $http.get(`${SERVER}/photo/${$state.params.photoid}`).then( resp => { console.log(resp.data); $scope.photo = resp.data; $scope.user = resp.data.user; $scope.comments = resp.data.comments; console.log(resp.data.comments, 'array of comments'); }) .catch(error => { console.log(error); }); } init(); $scope.addComment = (comment) => { //need to change and add correct id params $http.post(`${SERVER}/comments/${$state.params.photoid}`, comment).then(resp => { console.log(resp, comment); }) .then($state.reload()) .catch(error => { console.log(error); }); }; } PhotoSingleController.$inject = ['$scope', '$http', 'SERVER', '$state']; export default PhotoSingleController; <file_sep>function Config ($stateProvider, $urlRouterProvider) { $stateProvider .state('root', { abstract: true, templateUrl: 'templates/layout.tpl.html', controller: 'LayoutController' }) .state('root.signup', { url: '/sign-up', controller: 'UserController', templateUrl: 'templates/sign-up.tpl.html' }) .state('root.home', { url: '/home', templateUrl: 'templates/photo-list.tpl.html', controller: 'PhotoController' }) .state('root.user', { url: '/user/:userid', templateUrl: 'templates/user-page.tpl.html', controller: 'UserPageController' }) .state('root.addphoto', { url: '/photo/add', controller: 'PhotoController', templateUrl: 'templates/add-photo.tpl.html' }) .state('root.photo', { url: '/photo/:photoid', controller: 'PhotoSingleController', templateUrl: 'templates/photo-single.tpl.html' }); $urlRouterProvider.when('', '/home'); $urlRouterProvider.otherwise('/not-found'); } Config.$inject = ['$stateProvider', '$urlRouterProvider']; export default Config; <file_sep>function PhotoController ($scope, $http, SERVER, $state) { $scope.photos = []; function init () { $http.get(`${SERVER}/photos`).then(resp => { $scope.photos = resp.data; console.log($scope.photos); }); } init(); $scope.addPhoto = (info) => { $http.post(`${SERVER}/photos`, info).then(resp => { console.log(resp.data); }) .then($state.go('root.home')) .catch(error => { console.log(error); }); }; } PhotoController.$inject = ['$scope', '$http', 'SERVER', '$state']; export default PhotoController; <file_sep>export default 'https://dry-river-11900.herokuapp.com';<file_sep>function UserPageController ($cookies, $scope, $http, SERVER, $state, $stateParams) { $scope.photos = []; $scope.myVar = false; function init () { $http.get(`${SERVER}/user/${$stateParams.userid}/photos`).then(resp => { $scope.user = resp.data; $scope.photos = resp.data.photos; }); } init(); $scope.addProfilepic = (info) => { $http.put(`${SERVER}/update/${$stateParams.userid}`, info) .then( $state.reload()) .catch(error => { console.log(error); }); }; $scope.toggle = function() { console.log($cookies.get('user-id') === $stateParams.userid); if ($cookies.get('user-id') === $stateParams.userid) { $scope.myVar = true; } }; } UserPageController.$inject = ['$cookies','$scope', '$http', 'SERVER', '$state', '$stateParams']; export default UserPageController;
d7df6b72b9a61c9379d61f77dae08adfacd7978e
[ "JavaScript", "Markdown" ]
7
JavaScript
artem-alek/hackathon-frontend
a545ca8883f40cd49dc35905d01c403e7de94c58
734791e1d1e568a194ac3fd7ad2d7a1502fda321
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExceptionHandlerDemo { /// <summary> /// TODO:异常处理 /// 1、同步编程 /// 2、异步编程 /// </summary> class Program { static Stopwatch _watch = new Stopwatch(); static async Task ThrowAfter(int timeout,Exception ex) { await Task.Delay(timeout); throw ex; } static void PrintException(Exception ex) { Console.WriteLine("Time:{0}\n{1}\n===========",_watch.Elapsed,ex); } static async Task MissHandling() { var t1 = ThrowAfter(1000, new NotSupportedException("error1")); var t2 = ThrowAfter(2000,new NotImplementedException("error2")); try { await t1; } catch (NotSupportedException ex) { PrintException(ex); } } static void Main(string[] args) { } } }
f7f9b33251ebf7e5775665823fb2b1329a515f65
[ "C#" ]
1
C#
ZeroCamel/ExceptionHandlerDemo
021a134d2b3b41e3048b7acde18f63ee10747f87
9d6adfdf8c71014136e3ef4c50684a440dee3012
refs/heads/master
<file_sep> let readFile = (file, callback) => { let rawFile = new XMLHttpRequest(); rawFile.overrideMimeType("application/json"); rawFile.open("GET", file, true); rawFile.onreadystatechange = function() { if (rawFile.readyState === 4 && rawFile.status == "200") { callback(rawFile.responseText); } } rawFile.send(null); } readFile('file:///C:/Users/Andrej/Desktop/adv/data%20.json', (text) => { var data = JSON.parse(text); let table = document.querySelector('table') table.innerHTML = ` <tr> <td>${data.name} ${data.size} </td> </tr> <tr> <td>${data.name} - ${data.nodes[0].name} ${data.nodes[0].size} </td> </tr> <tr> <td>${data.name} - ${data.nodes[0].name} - ${data.nodes[0].nodes[0].name} ${data.nodes[0].nodes[0].size} </td> </tr> <tr> <td>${data.name} - ${data.nodes[0].name} - ${data.nodes[0].nodes[0].name} - ${data.nodes[0].nodes[0].nodes[0].name} ${data.nodes[0].nodes[0].nodes[0].size} </td> </tr> <tr> <td>${data.name} - ${data.nodes[0].name} - ${data.nodes[0].nodes[1].name} ${data.nodes[0].nodes[1].size} </td> </tr> <tr> <td>${data.name} - ${data.nodes[1].name} ${data.nodes[1].size} </td> </tr>` });
27e988e734b31583d1a48cb85bf96169fc47fe5c
[ "JavaScript" ]
1
JavaScript
Andrej-Polujanskij/adv
9b40d8d076c21382a02e29692cff76908224c30a
675009d2939906b36435feef14167d7641a7d858
refs/heads/master
<file_sep>import React from 'react'; import { withRouter } from 'react-router-dom'; import PropTypes from 'prop-types'; import style from './selectdifficulty.module.scss'; function SelectDifficulty({ difficulty, changeDifficulty }) { return ( <div className={style.difficulty}> <p className={style['difficulty-prompt']}>Select Difficulty: </p> <select value={difficulty} onChange={changeDifficulty} className={style['difficulty-select']} > <option value="easy">Easy</option> <option value="medium">Medium</option> <option value="hard">Hard</option> <option value="expert">Expert</option> </select> </div> ); } SelectDifficulty.propTypes = { changeDifficulty: PropTypes.func.isRequired, } export default withRouter(SelectDifficulty); <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import { link, row, message } from './playagain.module.scss'; function PlayAgain({ gameData }) { const { score, backgroundColor, playAgain } = gameData; return ( <div className={row} style={{ backgroundColor }}> <p className={message}>Game Over!</p> <p className={message}>Score: {score}</p> <button className={link} onClick={playAgain}> Play Again </button> </div> ); } PlayAgain.propTypes = { gameData: PropTypes.shape({ score: PropTypes.number.isRequired, backgroundColor: PropTypes.string.isRequired, playAgain: PropTypes.func.isRequired, }).isRequired,}; PlayAgain.defaultProps = { score: 0, backgroundColor: 'rgb(35, 35, 35)', }; export default PlayAgain; <file_sep>// Get random (rgb) color export function randomColor() { let r = Math.floor(Math.random() * 256); let g = Math.floor(Math.random() * 256); let b = Math.floor(Math.random() * 256); return `rgb(${r}, ${g}, ${b})`; } // Set length of color list array as a funciton of difficulty export function colorsListLength(difficulty) { switch (difficulty) { case 'expert': return 25; case 'hard': return 20; case 'medium': return 10; default: return 5; } } // Get color list array export function colorsList(colorsLength = 5) { const colors = []; while (colors.length < colorsLength) { colors.push(randomColor()); } return colors; } // Set random color to guess from (above) color list array export function randomColorToGuess(colors) { const index = Math.floor(Math.random() * colors.length); return colors[index]; } // Set number of game tries as a function of difficulty export function numberOfTries(difficulty) { switch (difficulty) { case 'expert': case 'hard': return 2; case 'medium': return 1; default: return 0; } } <file_sep>import React from 'react'; // import style from './notfound.module.scss'; function NotFoundPage() { return ( <div> Not Found Page </div> ) } export default NotFoundPage; <file_sep>import React from 'react'; import style from './footer.module.scss'; const currentYear = new Date().getFullYear(); function Footer() { const { footer } = style; return ( <footer className={footer}> <div className={style['footer-row']}> <p className="copyright"> &copy; {currentYear} | RGB Challenge | All Rights Reserved </p> <a href="https://github.com/collinstheuncoder/rgb-challenge" target="_blank" rel="noopener noreferrer" className={style['repo-link']} > <i className="fab fa-github"></i> </a> </div> </footer> ); } export default Footer; <file_sep>import React from 'react'; import { Switch, Route } from 'react-router-dom'; import { TransitionGroup, CSSTransition } from 'react-transition-group'; import HomePage from '../../../views/home'; import MainGamePage from '../../../views/main-game'; import EndGamePage from '../../../views/end-game'; import NotFoundPage from '../../../views/not-found'; function Main(props, { playAgain, difficulty, changeDifficulty }) { return ( <main className="main"> <Switch> <Route exact path="/" component={HomePage} /> <Route path="/game/play" component={() => <MainGamePage {...props} />} /> <Route path="/game/play-again" component={() => <EndGamePage {...props} />} /> <Route component={NotFoundPage} /> </Switch> </main> ); } export default Main; <file_sep>import React, { Component, Fragment } from 'react'; import { withRouter } from 'react-router-dom'; import Header from './layout/header'; import Main from './layout/main'; import Footer from './layout/footer'; import { colorsListLength, colorsList, randomColorToGuess, numberOfTries, } from '../helpers'; const initialState = { difficulty: 'easy', colorsList: [], colorToGuess: '', gameTries: 0, score: 0, backgroundColor: 'rgb(35, 35, 35)', isDisplayed: true, }; class App extends Component { state = initialState; componentDidMount() { this.onSetGameData(this.state.difficulty); } onSetGameData = difficulty => { const colors = colorsList(colorsListLength(difficulty)); const colorToGuess = randomColorToGuess(colors); this.setState(prevState => ({ colorsList: prevState.colorsList.concat(colors), gameTries: numberOfTries(difficulty), colorToGuess, })); }; onChangeDifficulty = e => { this.setState({ ...initialState, difficulty: e.target.value }, () => this.onSetGameData(this.state.difficulty) ); }; onPlay = colorBox => { if (colorBox === this.state.colorToGuess) { this.setState( prevState => ({ ...initialState, difficulty: prevState.difficulty, gameTries: prevState.gameTries, score: prevState.score + 1, }), () => this.onSetGameData(this.state.difficulty) ); } else if ( colorBox !== this.state.colorToGuess && this.state.gameTries !== 0 ) { this.setState(prevState => ({ gameTries: prevState.gameTries - 1, })); } else { this.setState( { isDisplayed: false, backgroundColor: this.state.colorToGuess, }, () => this.props.history.push('/game/play-again') ); } }; onPlayAgain = () => { this.setState( prevState => ({ ...initialState, difficulty: prevState.difficulty }), () => { this.props.history.push('/game/play'); this.onSetGameData(this.state.difficulty); } ); }; render() { const { isDisplayed, ...gameData } = this.state; return ( <Fragment> {isDisplayed && <Header />} <Main gameData={{ ...gameData, playGame: this.onPlay, playAgain: this.onPlayAgain, changeDifficulty: this.onChangeDifficulty, }} /> {isDisplayed && <Footer />} </Fragment> ); } } export default withRouter(App); <file_sep>import React from 'react'; import { Link } from 'react-router-dom'; import style from './home.module.scss'; function HomePage() { const { home, rules, link } = style; return ( <div className={home}> <div className={rules}> <h2 className={style['rules-title']}>Game Information/Rules</h2> <ul className={style['rules-list']}> <li className={style['list-item']}> Difficulty levels: Easy, Medium, Hard, Expert. </li> <li className={style['list-item']}> Number of color boxes (circles) per difficulty level: 5 for Easy, 10 for Medium, 20 for Hard, and 25 for Expert. </li> <li className={style['list-item']}> Number of tries for each round per difficulty level: 1 for Easy, 2 for Medium, and 3 for Hard and Expert. Game ends after tries are over. </li> <li className={style['list-item']}> Click on color corresponding to generated RGB code to play. </li> <li className={style['list-item']}>Changing difficulty mid-game restarts game.</li> <li className={style['list-item']}>Most of all, enjoy!</li> </ul> <Link to="/game/play" className={link}>Play Game</Link> </div> </div> ); } export default HomePage; <file_sep>import React from 'react'; import { Link, NavLink } from 'react-router-dom'; import style from './header.module.scss'; function Header() { const { header, h1, link, nav, rgb } = style; return ( <header className={header}> <h1 className={h1}> <Link to="/" className={link}> The Great <br /> <span className={rgb}>RGB</span> <br /> Challenge </Link> </h1> <nav className={`nav ${nav}`}> <ul className={style['nav-list']}> <li className={style['nav-item']}> <NavLink activeClassName="active" exact to="/">Home</NavLink> </li> <li className={style['nav-item']}> <NavLink to="/game/play">Play Game</NavLink> </li> </ul> </nav> </header> ); } export default Header; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import SelectDifficulty from '../../components/main-game/select-difficulty'; import GameDetails from '../../components/main-game/game-details'; import ColorGrid from '../../components/main-game/color-grid'; function MainGamePage({ gameData }) { const { colorsList, colorToGuess, gameTries, score, playGame, difficulty, changeDifficulty, } = gameData; return ( <div className="game"> <SelectDifficulty difficulty={difficulty} changeDifficulty={changeDifficulty} /> <GameDetails details={{ colorToGuess, gameTries, score, difficulty }} /> <ColorGrid colorsList={colorsList} playGame={playGame} /> </div> ); } MainGamePage.propTypes = { gameData: PropTypes.shape({ colorsList: PropTypes.array.isRequired, colorToGuess: PropTypes.string.isRequired, gameTries: PropTypes.number.isRequired, score: PropTypes.number.isRequired, playGame: PropTypes.func.isRequired, changeDifficulty: PropTypes.func.isRequired, }).isRequired, }; export default MainGamePage; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import style from './colorgrid.module.scss'; function ColorGrid({ colorsList, playGame }) { return ( <div className={style['color-grid']}> {colorsList.length > 0 ? ( colorsList.map(color => ( <div style={{ backgroundColor: color }} className={style['color-box']} key={color} onClick={() => playGame(color)} /> )) ) : ( <div>Loading colors...</div> )} </div> ); } ColorGrid.propTypes = { colorsList: PropTypes.array.isRequired, playGame: PropTypes.func.isRequired, }; export default ColorGrid; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import PlayAgain from '../../components/end-game/PlayAgain'; function EndGamePage(props) { return <PlayAgain {...props} />; } EndGamePage.propTypes = { gameData: PropTypes.shape({ score: PropTypes.number.isRequired, backgroundColor: PropTypes.string.isRequired, playAgain: PropTypes.func.isRequired, }).isRequired, }; export default EndGamePage;
aacd9d1b020323f23f6b9778582dab97c1408836
[ "JavaScript" ]
12
JavaScript
collinstheuncoder/rgb-challenge
9d60012f8e4cebeb35c371a6874460e684baa873
7e7fd836d113f311cad2e739118b0a5a7fc26c80
refs/heads/master
<file_sep><?php namespace Draw\Bundle\CronBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class DrawCronBundle extends Bundle { } <file_sep><?php namespace Draw\Bundle\CronBundle\Tests; use Draw\Bundle\CronBundle\CronManager; use Draw\Bundle\CronBundle\Model\Job; use PHPUnit\Framework\TestCase; class CronManagerTest extends TestCase { /** * @var CronManager */ private $cronManager; public function setUp(): void { $this->cronManager = new CronManager(); } public function testDumpJobs(): void { $job = new Job('Job name', 'echo "test"'); $this->cronManager->addJob($job); $cronTab = <<<CRONTAB #Description: * * * * * echo "test" >/dev/null 2>&1 CRONTAB; $this->assertSame( $cronTab, $this->cronManager->dumpJobs() ); } public function testDumpJobsTwoJobs(): void { $job = new Job('Job name', 'echo "test"'); $this->cronManager->addJob($job); $job = new Job('Job 2', 'echo "test"', '*/5 * * * *', true, 'Job every 5 minutes'); $this->cronManager->addJob($job); $cronTab = <<<CRONTAB #Description: * * * * * echo "test" >/dev/null 2>&1 #Description: Job every 5 minutes */5 * * * * echo "test" >/dev/null 2>&1 CRONTAB; $this->assertSame( $cronTab, $this->cronManager->dumpJobs() ); } public function testDumpJobsDisabled(): void { $job = new Job('Job 2', 'echo "test"'); $job->setEnabled(false); $this->cronManager->addJob($job); $this->assertSame( PHP_EOL, $this->cronManager->dumpJobs() ); } } <file_sep><?php namespace Draw\Bundle\CronBundle\Tests\DependencyInjection; use Draw\Bundle\CronBundle\Command\DumpToFileCommand; use Draw\Bundle\CronBundle\CronManager; use Draw\Bundle\CronBundle\DependencyInjection\DrawCronExtension; use Draw\Bundle\CronBundle\Model\Job; use Draw\Component\Tester\DependencyInjection\ExtensionTestCase; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Extension\Extension; class DrawCronExtensionTest extends ExtensionTestCase { private static $defaultJobConfiguration = [ 'name' => 'test', 'command' => 'echo test', 'expression' => '* * * * *', ]; public function createExtension(): Extension { return new DrawCronExtension(); } public function getConfiguration(): array { return []; } public function provideTestHasServiceDefinition(): iterable { yield [CronManager::class]; yield [DumpToFileCommand::class]; } public function testLoadNoJob() { $containerBuilder = $this->load([]); $this->assertJobDefinition($containerBuilder, []); } public function testLoadDefaultJob() { $containerBuilder = $this->load([ 'jobs' => [ self::$defaultJobConfiguration, ], ]); $this->assertJobDefinition( $containerBuilder, [ self::$defaultJobConfiguration + [ 'output' => '>/dev/null 2>&1', 'enabled' => true, 'description' => null, ], ]//Default value of the configuration ); } public function testLoadConfiguredJob() { $jobConfiguration = self::$defaultJobConfiguration + ['output' => 'other', 'enabled' => false, 'description' => 'description']; $containerBuilder = $this->load([ 'jobs' => [ $jobConfiguration, ], ]); $this->assertJobDefinition( $containerBuilder, [$jobConfiguration] ); } private function assertJobDefinition(ContainerBuilder $containerBuilder, array $jobConfigurations) { $definition = $containerBuilder->getDefinition(CronManager::class); $methodCalls = $definition->getMethodCalls(); $this->assertCount(count($jobConfigurations), $methodCalls); foreach ($methodCalls as $key => $methodCall) { $jobConfiguration = $jobConfigurations[$key]; $this->assertSame('addJob', $methodCall[0]); /** @var Definition $jobDefinition */ $jobDefinition = $methodCall[1][0]; $this->assertInstanceOf(Definition::class, $jobDefinition); $this->assertSame(Job::class, $jobDefinition->getClass()); $this->assertSame( [ $jobConfiguration['name'], $jobConfiguration['command'], $jobConfiguration['expression'], $jobConfiguration['enabled'], $jobConfiguration['description'], ], $jobDefinition->getArguments() ); $jobMethodCalls = $jobDefinition->getMethodCalls(); $this->assertCount(1, $jobMethodCalls); $this->assertSame('setOutput', $jobMethodCalls[0][0]); $this->assertSame($jobConfiguration['output'], $jobMethodCalls[0][1][0]); } } } <file_sep><?php namespace Draw\Bundle\CronBundle\DependencyInjection; use Draw\Bundle\CronBundle\CronManager; use Draw\Bundle\CronBundle\Model\Job; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\Extension\Extension; use Symfony\Component\DependencyInjection\Loader; class DrawCronExtension extends Extension { public function load(array $configs, ContainerBuilder $container) { $config = $this->processConfiguration($this->getConfiguration($configs, $container), $configs); $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml'); $cronManagerDefinition = $container->getDefinition(CronManager::class); foreach ($config['jobs'] as $jobData) { $jobDefinition = new Definition(Job::class); $jobDefinition->setArguments([ $jobData['name'], $jobData['command'], $jobData['expression'], $jobData['enabled'], $jobData['description'], ]); $jobDefinition->addMethodCall('setOutput', [$jobData['output']]); $cronManagerDefinition->addMethodCall('addJob', [$jobDefinition]); } } } <file_sep><?php namespace Draw\Bundle\CronBundle\Tests\Model; use Draw\Bundle\CronBundle\Model\Job; use PHPUnit\Framework\TestCase; class JobTest extends TestCase { private const DEFAULT_NAME = 'name'; private const DEFAULT_COMMAND = 'ls'; /** * @var Job */ private $job; public function setUp(): void { $this->job = new Job(self::DEFAULT_NAME, self::DEFAULT_COMMAND); } public function testGetName(): void { $this->assertSame(self::DEFAULT_NAME, $this->job->getName()); } public function testGetDescription(): void { $this->assertSame('', $this->job->getDescription()); } public function testGetCommand(): void { $this->assertSame(self::DEFAULT_COMMAND, $this->job->getCommand()); } public function testGetEnabled(): void { $this->assertSame(true, $this->job->getEnabled()); } public function testGetOutPut(): void { $this->assertSame('>/dev/null 2>&1', $this->job->getOutput()); } public function testGetExpression(): void { $this->assertSame('* * * * *', $this->job->getExpression()); } public function testToArray(): void { $this->assertEquals( [ 'name' => 'name', 'description' => '', 'expression' => '* * * * *', 'command' => 'ls', 'enabled' => true, 'output' => '>/dev/null 2>&1', ], $this->job->toArray() ); } } <file_sep><?php namespace Draw\Bundle\CronBundle\Tests\Command; use Draw\Bundle\CronBundle\Command\DumpToFileCommand; use Draw\Bundle\CronBundle\CronManager; use Draw\Component\Tester\Application\CommandDataTester; use Draw\Component\Tester\Application\CommandTestCase; use RuntimeException; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; class DumpToFileCommandTest extends CommandTestCase { public function createCommand(): Command { $mock = $this->createMock(CronManager::class); $mock->method('dumpJobs') ->willReturn('Output'); return new DumpToFileCommand($mock); } public function getCommandName(): string { return 'draw:cron:dump-to-file'; } public function getCommandDescription(): string { return 'Dump the cron job configuration to a file compatible with crontab.'; } public function provideTestArgument(): iterable { yield ['filePath', InputArgument::REQUIRED, 'The file path where to dump.']; } public function provideTestOption(): iterable { yield ['override', null, InputOption::VALUE_NONE, 'If the file is present we override it.']; } public function testExecuteNewFile() { $filePath = sys_get_temp_dir().'/'.uniqid().'.txt'; register_shutdown_function('unlink', $filePath); $this ->execute(['filePath' => $filePath]) ->test(CommandDataTester::create()); $this->assertSame('Output', file_get_contents($filePath)); } public function testExecuteNewFileOverride() { $filePath = sys_get_temp_dir().'/'.uniqid().'.txt'; file_put_contents($filePath, 'Before'); register_shutdown_function('unlink', $filePath); $this ->execute(['filePath' => $filePath, '--override' => '1']) ->test(CommandDataTester::create()); $this->assertSame('Output', file_get_contents($filePath)); } public function testExecuteNewFileNoOverrideException() { $filePath = sys_get_temp_dir().'/'.uniqid().'.txt'; file_put_contents($filePath, 'Before'); register_shutdown_function('unlink', $filePath); $this->expectException(RuntimeException::class); $this->expectExceptionMessage(sprintf( 'The file [%s] already exists. Remove the file or use option --override.', $filePath )); $this->execute(['filePath' => $filePath]); } } <file_sep>Draw Cron Bundle ================ This bundle is use to configure cron job that can be dump into a compatible cron job file format. You can configure cron base on the environment configuration or a **enabled** setting. This is mainly useful if you want to configure the cron in the project and during your deployment flow you call the command to dump the cron file with the proper environment configure. **This bundle does no intent to run the cron, it's just to allow a centralize configuration.** ## Configuration Here is a sample of the configuration: ```YAML parameters: cron.console.execution: "www-data php %kernel.project_dir%/bin/console" cron.context.enabled: true draw_cron: jobs: acme_cron: description: "Execute acme:command every 5 minutes" command: "%cron.console.execution% acme:command" expression: "*/5 * * * *" output: ">/dev/null 2>&1" #This is the default value enabled: "%cron.context.enabled%" ``` This would output something like this: ``` #Description: Execute acme:command every 5 minutes * * * * * www-data php /var/www/acme/bin/console acme:command >/dev/null 2>&1 ``` ## Command The command to dump the file is *draw:cron:dump-to-file*. If you want to dump it the first time or in a new file path you can simply do this: ``` bin/console draw:cron:dump-to-file /path/to/the/file ``` It will throw a exception if the file already exists. If you want to override it simply add the --override option. ``` bin/console draw:cron:dump-to-file /path/to/the/file --override ``` Normally you should integrate this in you deployment pipeline<file_sep><?php namespace Draw\Bundle\CronBundle; use Draw\Bundle\CronBundle\Model\Job; class CronManager { private const JOB_STRING_PATTERN = "#Description: {description}\n{expression} {command} {output}\n"; /** * @var array|Job[] */ private $jobs = []; public function addJob(Job $job): void { $this->jobs[] = $job; } /** * Dump all the jobs to a crontab compatible string. */ public function dumpJobs(): string { $result = []; foreach ($this->jobs as $job) { if (!$job->getEnabled()) { continue; } $jobData = $job->toArray(); $mapping = []; foreach ($jobData as $key => $value) { $mapping['{'.$key.'}'] = $value; } $cronLine = str_replace(array_keys($mapping), array_values($mapping), self::JOB_STRING_PATTERN); $result[] = $cronLine; } return trim(implode(PHP_EOL, $result)).PHP_EOL; } } <file_sep><?php namespace Draw\Bundle\CronBundle\Tests\DependencyInjection; use Draw\Bundle\CronBundle\DependencyInjection\Configuration; use Draw\Component\Tester\DependencyInjection\ConfigurationTestCase; use Symfony\Component\Config\Definition\ConfigurationInterface; class ConfigurationTest extends ConfigurationTestCase { private const JOB_MINIMUM = [ 'name' => 'test', 'expression' => '* * * * *', 'command' => 'echo', ]; private const JOB_DEFAULT = [ 'description' => null, 'output' => '>/dev/null 2>&1', 'enabled' => true, ]; public function createConfiguration(): ConfigurationInterface { return new Configuration(); } public function getDefaultConfiguration(): array { return ['jobs' => []]; } public function provideTestInvalidConfiguration(): iterable { yield [ ['jobs' => [['expression' => '* * * * *', 'command' => 'echo']]], 'Invalid configuration for path "draw_cron.jobs.0.name": You must specify a name for the job. Can be via the attribute or the key.', ]; yield [ ['jobs' => [['name' => 'test', 'command' => 'echo']]], 'The child node "expression" at path "draw_cron.jobs.test" must be configured.', ]; yield [ ['jobs' => [['name' => 'test', 'expression' => '* * * * *']]], 'The child node "command" at path "draw_cron.jobs.test" must be configured.', ]; yield [ ['jobs' => [array_merge(self::JOB_MINIMUM, ['enabled' => []])]], 'Invalid type for path "draw_cron.jobs.test.enabled". Expected boolean, but got array.', ]; yield [ ['jobs' => [array_merge(self::JOB_MINIMUM, ['command' => []])]], 'Invalid type for path "draw_cron.jobs.test.command". Expected scalar, but got array.', ]; yield [ ['jobs' => [array_merge(self::JOB_MINIMUM, ['output' => []])]], 'Invalid type for path "draw_cron.jobs.test.output". Expected scalar, but got array.', ]; yield [ ['jobs' => [array_merge(self::JOB_MINIMUM, ['expression' => []])]], 'Invalid type for path "draw_cron.jobs.test.expression". Expected scalar, but got array.', ]; yield [ ['jobs' => [array_merge(self::JOB_MINIMUM, ['description' => []])]], 'Invalid type for path "draw_cron.jobs.test.description". Expected scalar, but got array.', ]; } public function testJobNameAsKey() { $config = $this->processConfiguration([ ['jobs' => [self::JOB_MINIMUM]], ]); $this->assertArrayHasKey( self::JOB_MINIMUM['name'], $config['jobs'] ); } public function testJobDefault() { $config = $this->processConfiguration([ ['jobs' => [self::JOB_MINIMUM]], ]); $this->assertEquals( self::JOB_MINIMUM + self::JOB_DEFAULT, reset($config['jobs']) ); } public function testJobKeyAsName() { $job = self::JOB_MINIMUM; $name = $job['name']; unset($job['name']); $config = $this->processConfiguration([ ['jobs' => [$name => $job]], ]); $this->assertEquals( $name, reset($config['jobs'])['name'] ); } } <file_sep><?php namespace Draw\Bundle\CronBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files. * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder('draw_cron'); $node = $treeBuilder->getRootNode(); $node ->children() ->arrayNode('jobs') ->defaultValue([]) ->beforeNormalization() ->always(function ($config) { foreach ($config as $name => $configuration) { if (!isset($configuration['name'])) { $config[$name]['name'] = $name; } } return $config; }) ->end() ->useAttributeAsKey('name', false) ->arrayPrototype() ->children() ->scalarNode('name') ->validate() ->ifTrue(function ($value) { return is_int($value); }) ->thenInvalid('You must specify a name for the job. Can be via the attribute or the key.') ->end() ->isRequired() ->end() ->scalarNode('description') ->defaultNull() ->end() ->scalarNode('expression') ->isRequired() ->end() ->scalarNode('output') ->defaultValue('>/dev/null 2>&1') ->end() ->scalarNode('command') ->isRequired() ->end() ->booleanNode('enabled') ->defaultValue(true) ->end() ->end() ->end() ->end() ->end() ; return $treeBuilder; } }
f603fae6f2a203127de3bcad6f28b17b82d3647e
[ "Markdown", "PHP" ]
10
PHP
mpoiriert/cron-bundle
432994a5cc52e4a3553b15a17ec1bea19a157ec0
4ae3c9a8f51303dadc98b939ab2d210f32d164a7
refs/heads/master
<file_sep># Behaviour Driven Development: Powering Your Agile Project with Cucumber and Ruby This project is a companion to a [presentation](http://prezi.com/dhe2aqr3x2wq/?utm_campaign=share&utm_medium=copy) for the Australian Computer Society. During the presentation we imagine we are a team tasked with updating the Australian Tax Office's [Tax Calculator](https://www.ato.gov.au/Calculators-and-tools/Comprehensive-tax-calculator). This project demonstrates how Cucumber, Ruby, Capybara and RSpec might help with that. ## Structure * features/*.feature : cucumber features * features/step_definitions/web_steps.rb : generic steps that apply to all features * features/step_definitions/[feature]_steps.rb : steps specific to an individual feature file * support/env.rb : configures the driver and the hostname to use ## Prerequisites * Ruby http://www.ruby-lang.org/en/downloads/ * Ruby Gems http://rubygems.org/ * Bundler: sudo gem install bundler rake ## Configuration * sudo bundle install ## Running Features * To run all features: cucumber * To run a specific feature: cucumber features/tax_calculator_individuals/full_year_residents.feature * To run a specific scenario within a feature: cucumber features/tax_calculator_individuals/full_year_residents.feature:24 ## Debugging Features * The @javascript tag makes the test run in a browser so you can see what's happening. Remove it to run headless. * This project includes debugging helpers: * Add the step 'And I debug' to open the pry console from a feature * Add the method 'debug' to open the [pry console](http://pryrepl.org/) with [byebug](https://github.com/deivid-rodriguez/pry-byebug) from a step ## Running Unit Tests * To run all tests: rspec * To run all tests and display results as documentation: rspec -f d -c * To run a specific test: rspec ./spec/tax_calculator_spec.rb:71 ## Debugging Unit Tests * Add 'binding.pry' to open the [pry console](http://pryrepl.org/) with [byebug](https://github.com/deivid-rodriguez/pry-byebug) from a spec ## More about BDD from me * [The Presentation](http://prezi.com/dhe2aqr3x2wq/?utm_campaign=share&utm_medium=copy) * [Transcript of the Presentation](transcript.md) * [Making the Most of BDD](http://webuild.envato.com/blog/making-the-most-of-bdd-part-1/) * [BDD with Android](http://prezi.com/78y82u9ld2yy/?utm_campaign=share&utm_medium=copy) (Android Bootcamp week 2) * [Behaviour Driven Development in Android Studio](http://prezi.com/fxxkpgakbivh/?utm_campaign=share&utm_medium=copy) (a presentation given at the Sydney Android Developers Group) ## Other References * [Cucumber](http://cukes.info), [Cucumber Platforms](https://cukes.info/platforms.html) and [Cucumber Backgrounder](https://github.com/cucumber/cucumber/wiki/Cucumber-Backgrounder) * [Ruby](https://www.ruby-lang.org) * [RSpec](http://rspec.info/) * [Installation on Windows](http://www.spritecloud.com/2011/04/complete-setup-guide-for-ruby-cucumber-and-watir-or-selenium-on-windows/) * [Installation on MAC](https://mayxu.wordpress.com/2012/04/17/complete-mac-setup-guide-for-rubycucumberwatirselenium-12/) * [Capybara](http://github.com/jnicklas/capybara) (for actions such as click_link, click_button, etc...) * [Java Functional Testing with JRuby and RSpec](http://pivotallabs.com/functional-tests-for-java-project-rspec-story-framework-jruby/) Pivotal Labs * [Test Driven Development](http://www.amazon.com/Test-Driven-Development-By-Example/dp/0321146530) <NAME> 2002 * [Behaviour Driven Development](http://dannorth.net/introducing-bdd/) <NAME> 2006 <file_sep>[1] Hi, I'm <NAME>. I am currently a Senior Developer in the Marketplace development team for Envato. We build a suite of eight online marketplaces for selling digital creations such as website themes, graphic art, audio and video. We currently have over 1.75 million active buyers. In September last year themeforest.net became one of the world's top 100 websites, with more page views than Netflix and google.com.au. The code behind the marketplaces is constantly evolving, crafted by 7 teams using state of the art Agile development practices. These practices give us the confidence to deliver continual incremental improvements to our sites, with production deployments typically happening 8 - 12 times a day. Previous to my role at Envato I was an Agile consultant for ThoughtWorks Australia in Sydney, mentoring Agile teams at various organisations including NBN Co, Suncorp and Vodafone. Today I want to share with you some of the practices and tools that have made all these Agile teams successful. [1.1] But first, tell me a little about yourselves... Who here is currently a developer... or has been a developer? Who is a tester, BA, project manager What platforms are your development teams using? Java? .NET? Others? [2] One of the practices that I have seen applied most successfully is Behaviour Driven Development, or BDD. It was first described by Dan North in 2006. It is a development practice that incorporates the older practice of Test Driven Development (TDD), first described by Kent Beck in his 2002 book. Is anyone here working with teams that use TDD? [3] When developing with TDD, we start by writing a failing unit test. Then we write just enough code to make the test pass. Finally, we refactor the code to make it neat and maintainable. [4] Writing the tests first guarantees that we have a high coverage of tests over our code. This is a safety net that gives developers the confidence they need to refactor. This refactor stage is a key benefit of TDD; without it, code tends to become brittle as time goes on. Eventually, a codebase that is developed without refactoring becomes impossible to maintain and must be rewritten. The suite of tests you build up over time becomes technical documentation of the classes in your system. Unlike written documentation, passing tests are guaranteed to be up to date. Like the swinging of the pendulum in a grandfather clock, the rhythm of red - green - refactor forms a cadence that drives the work of the developers and testers in your team. [5] If the TDD cycle is the minute hand of a clock, the BDD cycle is the hour hand. With BDD you start with writing a failing functional test, or scenario - a test that describes the feature you are developing from the _user's_ point of view. Then you begin the TDD loop. After your refactoring is done, you run the feature test. Now if it passes, you know your feature is complete. If it's still failing, you return to the TDD loop. [6] The scenario has become a roadmap for the development of your feature - the passing steps within the scenario are an accurate gauge of your progress. [7] Let's look at an example. Imagine that the Government has decided to solve its budget woes by increasing personal income tax! Our mission is to update the ATO tax calculator. [8] The tax calculator is a wizard style section of the ATO website. [9] Clicking on the link opens the tax calculator info page in a new window. [10] The wizard asks a series of questions, such as - were you an Australian resident for the full year? [11] How much income did you receive from various sources? [12] Which screens of the wizard are relevant to you? [13] What were your tax credits and offsets? [14] Finally, the wizard tells you your total and net tax payable. It is the figures on this final screen that our team must change as part of the work to adjust the tax rates. [15] When maintaining existing software, if you've been through the BDD cycle before you will already have a passing scenario for the feature. So let's begin with a passing scenario for the 2014 tax calculator. It really doesn't matter how that website was developed - it could be Java or .NET or PHP - anything. But we can STILL power our project using one of the most powerful BDD tools, Cucumber. Here's what that scenario looks like. This is a real Cucumber test that I wrote to test the live ATO website. The code is available for download from my Github account. [16] Cucumber scenarios are grouped together in files for each Feature. At the top of the file is a description of the Feature; here we want to calculate individual taxes for full year residents. Next comes a statement of what that feature is designed to achieve. The statement is often written in the form "In order to \<achieve a goal\>, as a \<user role\> I want to \<do something\>". This focuses the team on the end goal of the user, who that user is, and how they are to achieve their goal. It helps build empathy for the user within the development team. For this feature, "In order to know how much more tax I have to pay, As an Australian full year resident, I want to calculate my net tax owing". [17] The operational part of the Cucumber scenario begins with the keyword Scenario. Scenarios are written in the language "Given \<some starting conditions\>, When \<I take some actions\> Then \<I expect some outcomes\>". In our example, "Given I have started the tax calculator and I am a resident, When I enter my income details, and choose these screens, and enter these tax credits, [18] Then I expect my tax payable to be around $39k". These final figures are the figures on the last page of the wizard, the ones we need to adjust. [19] The process by which you arrive at your scenario is very important! BDD is at its most powerful when scenarios are developed together, by cross-functional teams - teams that include a mix of developers, testers, a BA and a product or feature owner. Each of these roles brings their own skills, knowledge and points of view to the table. When your team spends time working together on the scenarios at the start of each sprint, you have an opportunity to explore the feature, to ask questions of each other such as "who is going to be using our feature", "what are they trying to achieve", "what should happen under these circumstances", and so on. You start your development work with a deep shared understanding of the scenarios you are about to code, and an empathy for the end user and the goals they are trying to achieve. [20] Let's see our working scenario in action! To start it running, we type 'cucumber' in the console. We can watch Cucumber drive the ATO tax calculator through each page of the wizard, ending with the verification of the figures on the final page. As it runs, the steps in our scenario appear in the console window on the right. Each green line is a step that has passed. The test ends with a summary letting us know that we ran 1 scenario containing 6 steps, which have all passed. [21] The first time you see one of these scenarios in action, it seems like magic! How do you get from a description written in ordinary English, that is really a form of documentation of your feature, to working code? Would you like to have a brief look behind the scenes? This will get a little technical - if you're not comfortable with looking at code we can skim over this section and spend more time discussing what it's like to use these processes in your Agile team at the end of the presentation. [22] Each line in the Feature is matched to Steps that are coded in a separate file. [23] For example, when the Feature says "Given I have started the latest comprehensive tax calculator", there's a step behind the scenes that matches that line. The matching is done using regular expressions, which can include placeholders for values so that the same step definition can be customised and reused across multiple scenarios. So in this example, to start the tax calculator, we visit the base page, click the tax calculator link, switch to the new window that opens up, then submit the form to progress to the next step in the wizard. [24] Tags at the start of a scenario allow you to modify how the scenario will operate. You may have noticed the @javascript tag that our scenario uses. This tag ensures that the scenario runs inside a browser. It is necessary if your scenario requires JavaScript to operate. It is also very useful for debugging, as it allows you to see what your test is doing, or inspect your page at points during the test. Another commonly used tag is @wip, for Work In Progress. Scenarios that are committed to your source repository with this tag are generally skipped when the continuous integration build runs, so that developers can work on implementing a feature over a period of time without breaking the build. It's also easy to define your own tags, for example to break up your build into batches that run at different times or on different machines. [25] There is a Ruby gem (a kind of plugin) called Capybara that Cucumber uses behind the scenes to interface with the web page you are testing. Capybara provides a variety of Finders, Actions and Matchers to make writing your steps easy. Finders help you locate elements on your web page. Actions emulate user actions such as clicking on buttons or typing text. And Matchers allow you to verify the content of your page. In our scenario, "I am a Resident for the full year" calls a helper method I have written. The helper "choose_by_value" uses a Capybara finder to locate the radio button whose value is FULL_YEAR_RESIDENT. It then uses a Capybara action to emulate clicking on that radio button. (Just an aside - If I had control over the coding of the web page, I could use a much simpler finder here by connecting the label "Resident for the full year" to the radio button itself. That's something that should be done for accessibility anyway, but has not been done on this page. When the label is connected correctly to the input element you can simply find by the label text.) [26] Another feature of Cucumber that we used extensively in this feature are Tables. Tables allow us to express our features very succinctly. When the feature says "My tax estimates are expected to be" "Tax on taxable income" of $37k, Medicare levy of $2k etc, that's all covered by a single step which takes in a table. [27] For each row in the table there's an expectation that our web page has a row containing the Estimate Type label, which also contains the amount text. [27.1] "have_text" is an example of a Capybara Matcher. Here the test will fail if the element found does not contain the amount text. [28] We can use tables not only for individual steps within scenarios, but also for entire scenarios, by calling it a "Scenario Outline" (instead of just "Scenario") and including a set of values in a table at the end of the outline. The scenario then runs once for each row in the table, using the provided values in that row to customise it. [29] Let's imagine now that we have our working scenario for the current version of the webpage, and we now need to update our values to suit the new tax rates. The first thing we do when we start working on our change, is change our scenario to make it fail. Let's see that in action. First we update the amount that is tax on taxable income. Now we run our tests to make sure that the scenario is failing in the manner we expect it to fail. This gives us a goal to aim for with the next little piece of our work, making the tax on taxable income match the new expectation. [30] So... Cucumber in a Nutshell (if you'll forgive the mixed metaphor). BDD with Cucumber is at its most powerful when your scenarios are written together by your whole team. The diverse roles in a cross-functional team will all bring different perspectives, and as a result you'll end up with a set of scenarios that express the main use cases for your feature well. Your team will come away from that workshop with a clear, shared understanding of your new feature at the start of your sprint. Cucumber scenarios read like English and become living documentation of your feature, guaranteed never to be out of date if they are passing. The set of scenarios is a roadmap for the creation of your feature, and the passing steps are an accurate gauge of your team's progress through the work. [31] But there are a couple of things you need to be careful of. [32] The first is reusing steps. It's tempting to get as much reuse out of steps as possible, but I've worked on projects where the steps ended up so disorganised that it took more time to write the features in the exact language of the steps you wanted to reuse, than it would have to write the steps from scratch. It's often better to have just a small set of commonly used steps, and write most features with their own set of fresh steps that use only those plus the basic Capybara finders, actions and matchers. [33] Sometimes when the process is new, the team forgets that there's a set of scenarios they are supposed to be using. They may need to be reminded to allow the scenarios to drive their work forward, otherwise you'll end up with a bunch of scenarios that must be 'dewipped' after the work is already complete. [34] Cucumber scenarios, because they are driving through your user interface, take much longer to run than unit tests that exercise the underlying code classes directly. To keep your whole test suite runnable in a reasonably short period of time, aim for the test pyramid. The vast majority of your tests should be unit tests, isolated to the class they are testing. You can run thousands of these in the time it takes to run one scenario. They should exercise all the edge and corner cases - the error conditions, logical boundaries and so on. Write a few integration tests - tests that communicate with other services such as a database or a third party API. [34.1] Cucumber scenarios should outline only the main happy-path use cases of your feature. And finally, manual testing should only be exploratory. If a test can be scripted, it can be automated. [35] Now that we've written our failing Cucumber scenario, [36] it's time to enter the TDD cycle by writing our first failing unit test. [37] I strongly encourage you to consider writing your unit tests with RSpec. Although RSpec was originally developed for testing Ruby projects, I have also worked on Java projects that used it by running JRuby on the JVM. I've provided a reference on how to do that in the Github project that accompanies this presentation. [38] One reason for preferring RSpec is that, like Cucumber, it encourages more readable tests, turning them into living documentation. With RSpec, this is technical documentation of your classes rather than the feature level documentation you get out of Cucumber. [39] Here's an example of output from running an RSpec test against a class that might form part of the code for our tax update project. Here the test is failing because we've updated one of the figures in the test to match the new tax rates. [40] A clear description of the failure is printed at the bottom of the test output. [41] So how is it that our test knows enough to produce this kind of documentation when it runs? Would you like to have a look at the code? RSpec is a domain specific language for testing, that is layered on top of Ruby. This language encourages the developer to provide good descriptions of the object under test, the environment the test is running in, the actions that are taken, and the expected outcome. [42] Here we see the keyword 'describe' documenting the class and methods under test. 'context', for example 'when reportable fringe benefits are...', like the 'Given' in a scenario, documents the environment the test is running in. 'it' encourages the coder to write a description of the expected outcome. [42.1] These descriptions come together in the output as 'TaxCalculator#initialize when reportable fringe benefits are 1, raises an error.' The code itself reads well too, for example 'Expect tax_calculator to raise_error'. [43] In RSpec we can take advantage of all the beautiful features of Ruby that coders love, for example String interpolation and easy enumeration over hashes and arrays. Here we see a hash of tax payable keyed on income, driving a set of tests of the total tax payable. The RSpec matcher "be_within" allows us to match floating point numbers without having to worry about their precision. [44] Finally, RSpec makes it really easy to isolate your unit tests to individual classes and even methods, by supplying methods for mocking instances of other classes (for example, an interface to a third party API) and stubbing individual methods. Here we are testing the net tax payable by stubbing out the #total_tax_payable method. 'before' the test runs, we 'allow' the tax calculator 'to receive' the total_tax_payable method, 'and return' the value we want. [45] So summing up, BDD is a powerful process for driving your Agile projects. Cucumber, Ruby, Capybara and RSpec are invaluable tools for supporting that process. Cucumber can be used with any web project, regardless of the language it was developed in. RSpec can be used on any Java or Ruby project. [46] If you'd like to learn more, I encourage you to explore the project that contains the working examples for the tax calculator. It also contains a transcript of this talk, and references. It's under my Github account, named bdd-for-acs. Feel free to contact me - just remember 'macosgrove' on LinkedIn and Twitter, and @envato.com. <file_sep>class TaxCalculator # If this were a real working class I'd use the Money gem (http://rubymoney.github.io/money/) for values, not integers and floats TAX_BRACKETS = {180000 => 0.45, 80000 => 0.37, 37000 => 0.325, 18200 => 0.19} def initialize(income_details, tax_credits) @taxable_income = income_details[:taxable_income] || 0 @tax_credits = tax_credits || 0 @reportable_fringe_benefits = income_details[:reportable_fringe_benefits] || 0 if @reportable_fringe_benefits > 0 && @reportable_fringe_benefits <= 3737 raise "Total reportable fringe benefits must be more than $3737. If you have entered less than $3738, please enter $0 to proceed." end end def total_tax_payable tax = 0 ceiling = [@taxable_income, TAX_BRACKETS.keys.first].max TAX_BRACKETS.each do | floor, rate | tax = tax + bracket_tax(ceiling, floor, rate) if @taxable_income > floor ceiling = [floor, @taxable_income].min end tax end def net_tax_payable total_tax_payable - sum_of_tax_credits end private def bracket_tax(ceiling, floor, rate) (ceiling - floor) * rate end def sum_of_tax_credits @tax_credits.values.inject(0) { |sum, value| value + sum} end end<file_sep>module Helpers def debug # This opens the Pry console. I've included pry-byebug, which gives stepping commands n=next in this method, s=step into called method, c=continue etc. require 'pry' binding.pry end def switch_to_linked_window(link) new_window = window_opened_by { click_link(link) } switch_to_window new_window end def submit_form(which) # It would be preferable to have a button on the form you could click to submit. This is a workaround for times when you can't modify the page. case which when :first index = 0 when :last index = 'forms.length-1' else index = "#{which}" end # I would prefer to use jQuery selectors, but for times when jQuery is not included and you can't modify the page, this uses pure javascript page.execute_script("forms = document.querySelectorAll('form'); forms[#{index}].submit()") end def choose_by_value(value) page.find("input[value='#{value}']").click end def choose_by_name_and_value(name, value) page.find("input[name='#{name}'][value='#{value}']").click end def income_details_field_name(suffix) "XO_4_#{suffix.gsub(' ', '_')}" end def tax_credits_field_name(readable_name) names = ['0-NA', 'PAYG installments', 'Total credits from summaries', 'Credit for tax withheld', 'Other tax withheld', 'Voluntary agreement', 'Labour hire', 'TFN amounts withheld', 'Early payment interest', 'Other offsets', 'Franking tax offset', 'Foreign resident withholding', 'Rental affordability'] "XO_4_refundable#{names.index(readable_name)}" end def table_row_containing(text) page.all("tr", :text => text, exact: true).last end end After do |scenario| save_and_open_page if scenario.failed? end World(Helpers)<file_sep>require 'capybara' require 'capybara/cucumber' Capybara.configure do |config| config.default_driver = :selenium config.app_host = 'https://www.ato.gov.au' end Capybara.register_driver :chrome do |app| Capybara::Selenium::Driver.new(app, :browser => :chrome) end Capybara.javascript_driver = :chrome Capybara.save_and_open_page_path = 'tmp/' World(Capybara) <file_sep>FULL_YEAR_RESIDENT = '5265736964656E74' NO_SPOUSE = '4E6F' YES = '596573' Given(/^I have started the latest comprehensive tax calculator$/) do visit('/Calculators-and-tools/Comprehensive-tax-calculator') switch_to_linked_window 'Comprehensive tax calculator 2015' submit_form(:last) end And(/^I am a Resident for the full year$/) do # We are using the radio input's name here, because the label has not been connected to the input with a 'for=' attribute # If you had control over the page it would be better to connect the label to the input field correctly, then the line below would be `choose 'Resident for the full year' ` choose_by_value(FULL_YEAR_RESIDENT) submit_form(:last) end When(/^my income details are:$/) do |table| table.hashes.each do |row| page.fill_in(income_details_field_name(row['Income type']), with: row['Amount']) end submit_form(:last) end And(/^I choose to include the following tax calculation items:$/) do |table| table.hashes.each do |row| choose_by_name_and_value("XO_10_#{row['Item']}", YES) end submit_form(:last) end And(/^my tax credits are:$/) do |table| table.hashes.each do |row| page.fill_in(tax_credits_field_name(row['Credit type']), with: row['Amount']) end submit_form(:last) end And(/^I have no dependent children$/) do choose_by_value(NO_SPOUSE) page.fill_in('XO_4_PHI_dependents', with: '0') submit_form(:last) end Then(/^my tax estimates are expected to be:$/) do |table| # table is a table.hashes.keys # => [:Tax on taxable income, :37601.00] table.hashes.each do |row| expect(table_row_containing(row['Estimate type'])).to have_text(row['Amount']) end end <file_sep>Dir[File.join(File.dirname(__FILE__), "../lib" , "**.rb")].each do |file| require file end require 'rspec' require 'rspec/mocks' require 'pry' RSpec.configure do |conf| conf.color = true conf.tty = true end<file_sep>require 'spec_helper' describe TaxCalculator do let(:income_details) { {} } let(:tax_credits) { {} } subject(:tax_calculator) { TaxCalculator.new(income_details, tax_credits) } describe '#initialize' do [1, 3737, 1234].each do |rfb| context "when reportable fringe benefits are #{rfb}" do let(:income_details) { {:reportable_fringe_benefits => rfb} } it 'raises an error' do expect { tax_calculator }.to raise_error end end end end describe '#total_tax_payable' do # See https://www.ato.gov.au/Individuals/Income-and-deductions/How-much-income-tax-you-pay/Individual-income-tax-rates/ {18200 => 0, 37000 => 3572, 80000 => 17547, 180000 => 54547}.each do |income, tax| context "when taxable income is at the top of its bracket (#{income})" do let(:income_details) { {:taxable_income => income} } it "is the base tax of the next bracket (#{tax})" do expect(tax_calculator.total_tax_payable).to be_within(0.001).of(tax) end end end {1 => 0, 18201 => 0.19, 37001 => 3572.325, 80001 => 17547.37, 180001 => 54547.45}.each do |income, tax| context "when taxable income (#{income}) is at the bottom of its bracket" do let(:income_details) { {:taxable_income => income} } it "is the base tax of the next bracket plus the rate (#{tax})" do expect(tax_calculator.total_tax_payable).to be_within(0.001).of(tax) end end end {12000 => 0, 26500 => 1577, 53500 => 8934.5, 135463 => 38068.31, 500000 => 198547}.each do |income, tax| context "when taxable income is inside its bracket" do let(:income_details) { {:taxable_income => income} } it "is #{tax}" do expect(tax_calculator.total_tax_payable).to be_within(0.001).of tax end end end end describe '#net_tax_payable' do context 'when there are no tax credits' do before { allow(tax_calculator).to receive(:total_tax_payable).and_return(100000) } it 'is the same as total tax payable' do expect(tax_calculator.net_tax_payable).to be_within(0.001).of 100000 end end context 'when there are tax credits' do let(:tax_credits) { {:payg_installments => 23000, :franking_tax_offset => 1200} } before { allow(tax_calculator).to receive(:total_tax_payable).and_return(39614) } it 'is the total tax payable minus the sum of the tax credits' do expect(tax_calculator.net_tax_payable).to be_within(0.001).of 15414 end end end end
5d197335a926e3eec3e827bf52c36d338761bcb2
[ "Markdown", "Ruby" ]
8
Markdown
macosgrove/bdd-for-acs
42adf4211a9c44bd6cfe0b8be28cfb2e28a6942b
417690e92c98ae371ba5d36a7151ab7c394a4fb7
refs/heads/master
<file_sep>using System.Collections.Generic; using System.Threading.Tasks; using DatingApp.API.Models; namespace DatingApp.API.Data { public interface IDatingRepository { // Dit is een generieke methode. De <T> kan op photo's en users betrekking hebben. void Add<T>(T entity) where T: class; void Delete<T>(T entity) where T: class; // Controleert of er null of meer wijzigen hebben plaats gevonden. Task<bool> SaveAll(); // Lijst van users Task<IEnumerable<User>> GetUsers(); // Een enkele user Task<User> GetUser(int id); } }
62a7175b962f7a54b34e99d9b425cd66fb5ed506
[ "C#" ]
1
C#
harrymaartens/DatingApp
22453960ffeb0d719cd72147cbddf2c117762aac
bb8307f6e9815c1d23dce98d6fe04f966782e561
refs/heads/master
<file_sep> // RFID reader ID-12 for Arduino // #include <EEPROM.h> #include <PLCTimer.h> #include <Wire.h> #include <LiquidTWI.h> #define __ID12__ //#define __MFRC-522_SPI__ #ifdef __MFRC-522_SPI__ #include <SPI.h> #include <MFRC522.h> #define RST_PIN 9 //Pin 9 para el reset del RC522 #define SS_PIN 10 //Pin 10 para el SS (SDA) del RC522 MFRC522 mfrc522(SS_PIN, RST_PIN); //Creamos el objeto para el RC522 #endif #define __DEBUGGING__ #define __CODE_SIZE__ 5 // numero de bytes de cada codigo #define __DURATION_LIGHT__ 2 // duracion de la luz encendida [min] #define __DURATION_CODE__ 1./6. // time-out para la identificacion [min] #define __MAX_NUM_CODES__ 7 // maximo numero de codigos almacenables #define __POS_CODES_EEPROM__ 2 // byte en el que comienza el almacenamiento de codigos en eeprom #define __POS_NUMCODES_EEPROM__ 0 // byte en el que se almacena el numero de codigos en eeprom #define __POS_STATE_EEPROM__ 1 // byte en el que se almacena el estado #define __NUM_CYCLES_NO_COMM__ 10000 // numero de ciclos que espera para volver a probar la comm con el LCD #define __LCD_ADDR__ 0 // direccion del LCD en el bus I2C #define __RELAY_ON__ 0 #define __RELAY_OFF__ 1 #define __SWIPES_MASTERKEY__ 5 // numero de pasadas de una masterkey para eliminar la EEPROM #define __MAX_DENIED_TRIES__ 5 #define __DENIED_TRIES_DECRMT_TIME__ 60 // minutes to decrement one denied try // declaracion de variables globales byte actual_duration_light=__DURATION_LIGHT__; byte master_code[__CODE_SIZE__] = {25, 00, 113, 93, 171}; byte accepted_codes[__MAX_NUM_CODES__][__CODE_SIZE__]; byte buffCode[__CODE_SIZE__]; byte *ptrbuffCode = &buffCode[0]; // puntero al buffer donde se almacena el codigo leido volatile byte cuenta_minutos = 0, cuenta_segundos = 0; // variables actualizadas en la interrupcion volatile static boolean actualizaLCD; volatile static boolean tryComm; volatile static byte denied_codes=0; struct CODES_TBL { byte *code; byte num_cols; byte num_rows; }; struct CODES_TBL _tabla_codigos = {&accepted_codes[0][0], __CODE_SIZE__, 1}; const byte lightPin = 6; // OUT encender luz const byte hornPin = 7; // OUT activar alarma const byte NOTdoorClosedPin = 2; // IN puerta no cerrada const byte keyDesactPin = 3; // IN llave desactivada const byte beepPin = 4; // Beep pin const byte codeMemPin = 5; // IN memorizar nuevo codigo static byte estado = 0; // variable que recoge el estado actual del sistema static byte estado_ant = 255; static bool sistema_bloqueado = false; // Connect via i2c, default address #0 (A0-A2 not jumpered) LiquidTWI lcd(__LCD_ADDR__); static bool LCDinit=false; volatile PLCTimer TC1(TEMP_CON),TC2(TEMP_CON),TC3(TEMP_CON); void setup() { byte error,n, i, j; // set up the LCD's number of rows and columns: #ifdef __DEBUGGING__ Serial.begin(9600); // connect to the serial port Serial.print("Initializing LCD"); Serial.println(); #endif lcd.begin(16, 2); if (!lcd.NoComm) { lcd.print("Inicializando"); LCDinit=true; } else { #ifdef __DEBUGGING__ Serial.print("LCD is not responding"); Serial.println(); #endif } n = EEPROM.read(__POS_NUMCODES_EEPROM__); // retrieve the number of accepted codes if (n == 255) // it is the first time to write in EEPROM { EEPROM.write(__POS_NUMCODES_EEPROM__, 1); for (i = 0; i < __CODE_SIZE__; i++) { EEPROM.write(i + __POS_CODES_EEPROM__, master_code[i]); delay(100); } n = 1; #ifdef __DEBUGGING__ Serial.print("First initialization. Default access code"); Serial.println(); #endif } else { _tabla_codigos.num_rows = n; } code_load_EEPROM(&_tabla_codigos); #ifdef __DEBUGGING__ Serial.print("Registered codes: "); Serial.print(n, DEC); Serial.println(); for (i = 0; i < n; i++) { Serial.print("Code "); Serial.print(i, DEC); Serial.print(": "); for (j = 0; j < __CODE_SIZE__; j++) { Serial.print(*(_tabla_codigos.code + _tabla_codigos.num_cols * i + j), DEC); Serial.print(","); } Serial.println(); } #endif digitalWrite(lightPin, __RELAY_OFF__); // to avoid initial energization pinMode(lightPin, OUTPUT); // sets the digital pin as output digitalWrite(hornPin, __RELAY_OFF__); // to avoid initial energization pinMode(hornPin, OUTPUT); // sets the digital pin as output pinMode(NOTdoorClosedPin, INPUT); // sets the digital pin as input digitalWrite(NOTdoorClosedPin, HIGH); // turn on pullup resistors pinMode(keyDesactPin, INPUT); // sets the digital pin as input digitalWrite(keyDesactPin, HIGH); // turn on pullup resistors pinMode(codeMemPin, INPUT); // sets the digital pin as input digitalWrite(codeMemPin, HIGH); // turn on pullup resistors digitalWrite(beepPin, 0); // to avoid initial energization pinMode(beepPin, OUTPUT); // sets the digital pin as output cli();//stop interrupts // CONFIGURACION TIMER 1 for INTERRUPTING EACH SECOND (1Hz) //set timer1 interrupt at 1Hz TCCR1A = 0;// set entire TCCR1A register to 0 TCCR1B = 0;// same for TCCR1B TCNT1 = 0;//initialize counter value to 0 // set compare match register for 1hz increments OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536) // turn on CTC mode TCCR1B |= (1 << WGM12); // Set CS10 and CS12 bits for 1024 prescaler TCCR1B |= (1 << CS12) | (1 << CS10); sei();//allow interrupts if (!lcd.NoComm) { delay(1000); lcd.setCursor(0, 1); lcd.print("Inicializado OK"); delay(1000); lcd.setBacklight(LOW); } TC1.Delay = 2; TC2.Delay = 100; TC3.In = false; TC3.Delay = 60*__DENIED_TRIES_DECRMT_TIME__; #ifdef __MFRC-522_SPI__ SPI.begin(); //Iniciamos el Bus SPI mfrc522.PCD_Init(); // Iniciamos el MFRC522 #endif } void enable_T1_interrupt() { // enable timer compare interrupt TIMSK1 |= (1 << OCIE1A); } void disable_T1_interrupt() { // disables timer compare interrupt TIMSK1 &= (0 << OCIE1A); cuenta_minutos = 0; cuenta_segundos = 0; } ISR(TIMER1_COMPA_vect) // interrupcion del timer 1 { cuenta_segundos++; if (cuenta_segundos > 60) { cuenta_segundos -= 60; cuenta_minutos++; if (cuenta_minutos > 60) { cuenta_minutos -= 60; } } actualizaLCD = true; TC1.Execute(); TC3.Execute(); if (TC3.OUT) // se ha cumpido el tiempo de espera { TC3.In = false; denied_codes--; #ifdef __DEBUGGING__ Serial.print("Se reducen los intentos fallidos "); Serial.println(denied_codes); #endif }else{TC3.In = (denied_codes > 0);} } void loop () { boolean code_OK = false; boolean read_OK = false; boolean MasterCode = false; static int counterNoComm=0; int i; byte kk; TC2.In = (!digitalRead(keyDesactPin)); TC2.Execute(); if (TC2.OUT) // se activa la llave { estado = 200; sistema_bloqueado=false; denied_codes=0; } if (denied_codes>=__MAX_DENIED_TRIES__) { sistema_bloqueado=true; }else{sistema_bloqueado=false;} switch (estado) { case 0: // IDLE STATE enable_T1_interrupt(); digitalWrite(lightPin, __RELAY_OFF__); digitalWrite(hornPin, __RELAY_OFF__); actual_duration_light=__DURATION_LIGHT__; read_code(&_tabla_codigos, &code_OK, ptrbuffCode, &read_OK,&MasterCode); TC1.In = (digitalRead(NOTdoorClosedPin)==HIGH); if (TC1.OUT) // se abre la puerta { disable_T1_interrupt(); #ifdef __DEBUGGING__ Serial.print("Puerta abierta"); Serial.println(); #endif estado = 1; } if (code_OK) { disable_T1_interrupt(); if (MasterCode) { estado = 11; MasterCode=false;} else{estado = 10;} code_OK = false; } break; case 1: // PUERTA ABIERTA DETECTADA enable_T1_interrupt(); digitalWrite(lightPin, __RELAY_OFF__); digitalWrite(hornPin, __RELAY_OFF__); if ((actualizaLCD) && (!lcd.NoComm)) { actualizaLCD = false; kk = __DURATION_CODE__ * 60 - (cuenta_minutos * 60 + cuenta_segundos); if (kk < 10) { lcd.setCursor(11, 1); } lcd.print(kk); lcd.setCursor(10, 1); } if ((cuenta_segundos % 2 == 0) && (!lcd.NoComm)) // modulo, blinks the backlight each second { lcd.setBacklight(HIGH); digitalWrite(beepPin, 1); } else if (!lcd.NoComm) { lcd.setBacklight(LOW); digitalWrite(beepPin, 0); } read_code(&_tabla_codigos, &code_OK, ptrbuffCode, &read_OK,&MasterCode); if (cuenta_minutos*60+cuenta_segundos >= __DURATION_CODE__*60) { #ifdef __DEBUGGING__ Serial.print("Activar alarma"); Serial.println(); #endif digitalWrite(beepPin, 0); estado = 100; } if (code_OK) { disable_T1_interrupt(); if (MasterCode) { estado=11; MasterCode=false; }else{ estado = 10;} digitalWrite(beepPin, 0); code_OK = false; } break; case 10: // IDENTIFICACION OK, TEMPORIZANDO LA LUZ digitalWrite(lightPin, __RELAY_ON__); digitalWrite(hornPin, __RELAY_OFF__); enable_T1_interrupt(); if ((actualizaLCD) && (!lcd.NoComm)) { kk = actual_duration_light - cuenta_minutos; actualizaLCD = false; lcd.setBacklight(HIGH); if (kk <= 1) { kk = actual_duration_light * 60 - (cuenta_minutos * 60 + cuenta_segundos); lcd.print(" seg "); lcd.print(kk); if ((kk < 10) && (kk % 2 == 0)) { digitalWrite(beepPin, 1); }else { digitalWrite(beepPin, 0); } } else { lcd.print(kk); } lcd.setCursor(9, 1); } read_code(&_tabla_codigos, &code_OK, ptrbuffCode, &read_OK,&MasterCode); if (code_OK) { actual_duration_light+=__DURATION_LIGHT__- cuenta_minutos; lcd.setCursor(0, 1); lcd.print("Luz off: min "); lcd.setCursor(9, 1); disable_T1_interrupt(); code_OK = false; digitalWrite(beepPin, 0); if (MasterCode) { estado=11; MasterCode=false; } } if (cuenta_minutos >= actual_duration_light) { #ifdef __DEBUGGING__ Serial.print("Apagar luz"); Serial.println(); #endif digitalWrite(beepPin, 0); estado = 0; } if (!digitalRead(codeMemPin)) // new mem code button pushed { estado = 250; } break; case 11: // IDENTIFICACION MASTERKEY OK, TEMPORIZANDO LA LUZ static byte numswipes=0; digitalWrite(lightPin, __RELAY_ON__); digitalWrite(hornPin, __RELAY_OFF__); enable_T1_interrupt(); read_code(&_tabla_codigos, &code_OK, ptrbuffCode, &read_OK,&MasterCode); if (MasterCode) { if (numswipes++ >= __SWIPES_MASTERKEY__) { EEPROM.write(__POS_NUMCODES_EEPROM__, 1); delay(100); _tabla_codigos.num_rows = 1; code_load_EEPROM(&_tabla_codigos); lcd.setCursor(0, 0); lcd.print("Codes Erased "); lcd.setCursor(0, 1); lcd.print(" "); delay(1000); disable_T1_interrupt(); estado=10; numswipes =0; }else { lcd.print(__SWIPES_MASTERKEY__-numswipes+1); } lcd.setCursor(0, 1); code_OK = false; MasterCode=false; }else{lcd.print(__SWIPES_MASTERKEY__-numswipes+1);} if (cuenta_minutos >= actual_duration_light) { disable_T1_interrupt(); #ifdef __DEBUGGING__ Serial.print("Volver al estado 0"); Serial.println(); #endif digitalWrite(beepPin, 0); estado = 0; numswipes =0; } if (!digitalRead(codeMemPin)) // new mem code button pushed { estado = 250; } break; case 100: // TIMEOUT PARA LA IDENTIFICACION, ACTIVAR ALARMA disable_T1_interrupt(); digitalWrite(lightPin, __RELAY_OFF__); digitalWrite(hornPin, __RELAY_ON__); read_code(&_tabla_codigos, &code_OK, ptrbuffCode, &read_OK,&MasterCode); if (code_OK) { #ifdef __DEBUGGING__ Serial.print("Alarma desactivada"); Serial.println(); #endif estado = 10; code_OK = false; } break; case 200: // se activa el modo manual mediante la llave disable_T1_interrupt(); digitalWrite(lightPin, __RELAY_ON__); digitalWrite(hornPin, __RELAY_OFF__); if (!digitalRead(codeMemPin)) // se pulsa boton de memorizar nuevo codigo { estado = 250; } if (digitalRead(keyDesactPin)) // se desactiva la llave { estado = 10; #ifdef __DEBUGGING__ Serial.print("Llave desactivada. Modo auto"); Serial.println(); #endif } break; case 250: // se activa el modo de reconocer nuevo codigo enable_T1_interrupt(); digitalWrite(lightPin, __RELAY_ON__); digitalWrite(hornPin, __RELAY_OFF__); read_code(&_tabla_codigos, &code_OK, ptrbuffCode, &read_OK,&MasterCode); if (read_OK) { read_OK = false; lcd.clear(); lcd.setCursor(0, 0); lcd.print("Detectado codigo"); lcd.setCursor(0, 1); #ifdef __DEBUGGING__ Serial.print("Nuevo codigo almacenado: "); #endif byte fila; if (_tabla_codigos.num_rows < __MAX_NUM_CODES__) { fila= _tabla_codigos.num_rows; _tabla_codigos.num_rows++; }else { fila= _tabla_codigos.num_rows; } for (i = 0; i < _tabla_codigos.num_cols; i++) { EEPROM.write(fila * _tabla_codigos.num_cols + i + __POS_CODES_EEPROM__, *(ptrbuffCode + i)); lcd.print(*(ptrbuffCode + i)); #ifdef __DEBUGGING__ Serial.print(*(ptrbuffCode + i), DEC); Serial.print(","); #endif delay(100); } EEPROM.write(__POS_NUMCODES_EEPROM__, _tabla_codigos.num_rows); delay(1000); code_load_EEPROM(&_tabla_codigos); #ifdef __DEBUGGING__ Serial.println(); #endif estado = 10; } if (cuenta_minutos >= __DURATION_CODE__) { #ifdef __DEBUGGING__ Serial.print("Codigo no registrado"); Serial.println(); #endif estado = 0; } break; } if (estado != estado_ant) { #ifdef __DEBUGGING__ Serial.print("Estado: "); Serial.print(estado, DEC); Serial.println(); #endif TC1.OUT = false; // to keep TC1.OUT= LOW estado_ant = estado; if ((estado == 0) && (!lcd.NoComm)) { lcd.noDisplay(); lcd.setBacklight(LOW); } else if (!lcd.NoComm) { lcd.display(); lcd.setCursor(0, 0); text2lcd(estado); } } } void text2lcd(byte estado) { lcd.setCursor(0, 0); switch (estado) { case 0: // ESPERANDO IDENTIFICACION lcd.clear(); lcd.setBacklight(LOW); break; case 1: // PUERTA ABIERTA DETECTADA lcd.print("Puerta abierta "); lcd.setCursor(0, 1); lcd.print("Alarma en: seg"); lcd.setCursor(10, 1); break; case 10: // IDENTIFICACION OK, TEMPORIZANDO LA LUZ lcd.setBacklight(HIGH); lcd.print("Identif. OK "); lcd.setCursor(0, 1); lcd.print("Luz off: min "); lcd.setCursor(9, 1); break; case 11: // IDENTIFICACION MASTERKEY OK, TEMPORIZANDO LA LUZ lcd.setBacklight(HIGH); lcd.print("MASTERKEY "); lcd.setCursor(0, 1); lcd.print(" to erase CODES"); lcd.setCursor(0, 1); break; case 100: // TIMEOUT PARA LA IDENTIFICACION, ACTIVAR ALARMA lcd.setBacklight(HIGH); lcd.print("Alarma activa "); lcd.setCursor(0, 1); lcd.print("Aviso policia "); break; case 200: // se activa el modo manual mediante la llave lcd.clear(); lcd.setBacklight(HIGH); lcd.print("Modo manual "); break; case 250: // se activa el modo de reconocer nuevo codigo lcd.setBacklight(HIGH); lcd.print("Nuevo codigo "); lcd.setCursor(0, 1); lcd.print("Pasar pastilla "); lcd.setCursor(0, 1); break; } } #ifdef __ID12__ void read_code(struct CODES_TBL *tabla_codigos, boolean *code_OK, byte *codeRead, boolean *read_OK, boolean *masterKey) { byte i = 0; byte val = 0; byte code[6]; byte checksum = 0; byte bytesread = 0; byte tempbyte = 0; if (Serial.available() >= 12) { if ((val = Serial.read()) == 2) { // check for header bytesread = 0; while (bytesread < 12) { // read 10 digit code + 2 digit checksum if ( Serial.available() > 0) { val = Serial.read(); if ((val == 0x0D) || (val == 0x0A) || (val == 0x03) || (val == 0x02)) { // if header or stop bytes before the 10 digit reading break; // stop reading } // Do Ascii/Hex conversion: if ((val >= '0') && (val <= '9')) { val = val - '0'; } else if ((val >= 'A') && (val <= 'F')) { val = 10 + val - 'A'; } // Every two hex-digits, add byte to code: if (bytesread & 1 == 1) { // make some space for this hex-digit by // shifting the previous hex-digit with 4 bits to the left: code[bytesread >> 1] = (val | (tempbyte << 4)); if (bytesread >> 1 != __CODE_SIZE__) { // If we're at the checksum byte, checksum ^= code[bytesread >> 1]; // Calculate the checksum... (XOR) }; } else { tempbyte = val; // Store the first hex digit first... }; bytesread++; // ready to read next digit } } // Output to Serial: if (bytesread == 12){ // if 12 digit read is complete *read_OK = true; code_check(tabla_codigos, &code[0], code_OK,masterKey); #ifdef __DEBUGGING__ Serial.print("5-byte code: "); #endif for (i = 0; i < __CODE_SIZE__; i++) { *(codeRead + i) = code[i]; #ifdef __DEBUGGING__ if (code[i] < 16) Serial.print("0"); Serial.print(code[i], DEC); Serial.print(","); #endif } #ifdef __DEBUGGING__ Serial.println(); if (*code_OK) { if (*masterKey){Serial.print("Access granted to MasterKey");} else{Serial.print("Access granted");} Serial.println(); serialFlush(); } else { Serial.print("Access denied"); Serial.println(); } #endif } bytesread = 0; } } } #endif #ifdef __MFRC-522_SPI__ void read_code(struct CODES_TBL *tabla_codigos, boolean *code_OK, byte *codeRead, boolean *read_OK, boolean *masterKey) { byte code[6]; if (mfrc522.PICC_IsNewCardPresent()) { //Verifica si hay una tarjeta if (mfrc522.PICC_ReadCardSerial()) { //Funcion que lee la tarjeta Serial.println(" "); Serial.println(" "); Serial.println("El numero de serie de la tarjeta es : "); for(int i=0; i < mfrc522.uid.size; i++){ if(i!=mfrc522.uid.size){ Serial.print(mfrc522.uid.uidByte[i],HEX); Serial.print(" "); } else{ Serial.print(mfrc522.uid.uidByte[i],HEX); Serial.print(" "); } //code[i]=mfrc522.uid.uidByte[i]; } MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak); Serial.println(mfrc522.PICC_GetTypeName(piccType)); } } mfrc522.PICC_HaltA(); } #endif void code_load_EEPROM(struct CODES_TBL *tabla_codigos) { int i, j; for (i = 0; i < tabla_codigos->num_rows; i++) { for (j = 0; j < tabla_codigos->num_cols; j++) { *(tabla_codigos->code + tabla_codigos->num_cols * i + j) = EEPROM.read(tabla_codigos->num_cols * i + j + __POS_CODES_EEPROM__); } } } void code_check(struct CODES_TBL *tabla_codigos, byte *codigo, boolean *code_check, boolean *IsmasterKey) { int i, j; if (!sistema_bloqueado) { for (i = 0; i < tabla_codigos->num_rows; i++) { *code_check = true; for (j = 0; j < tabla_codigos->num_cols; j++) { if (*(tabla_codigos->code + tabla_codigos->num_cols * i + j) != *(codigo + j)) { *code_check = false; break; } } if (*code_check) { if (i==0){*IsmasterKey=true;} // si la coincidencia es con el primer codigo, es llave maestra else{*IsmasterKey=false;} break; } } if (!(*code_check)) { denied_codes++; #ifdef __DEBUGGING__ Serial.print("Intentos fallidos "); Serial.println(denied_codes); #endif } }else { (*code_check)=false; (*IsmasterKey)=false; } } void serialFlush(){ while(Serial.available() > 0) { char t = Serial.read(); } } <file_sep># INTRODUCTION Find out more details on http://www.aboutmyarduinos.com/rfid-access-control/ This device performs an access control by means of 125 kHz RFID tags as the one shown in Figure 1. It consists of a microcontroller and a RFID reader which are communicated by means of a serial link. ![Alt text](/media/RFID_tag.jpg?raw=true "Figure 1") When an accepted RFID tag is swiped around the reader, the device grants access to a protected zone by means of switching on a relay that power on the lights. The capabilities of this device can be further increased by integrating an electro-mechanical locking mechanism to the door. This could be locked and unlocked by means of two additional digital outputs. # SPECIFICATIONS The following table shows the general specifications for the access control system. # HARDWARE DESCRIPTION The hardware is divided into two boards as can be seen on Figure 2. This architecture increases the safety as the mainboard (board 1) can be safely placed (or even hidden) inside the protected area whereas the human-machine interface (HMI) board (board 2) can be left exposed in the un-protected area. ![Alt text](/media/General_Layout.png?raw=true "Figure 2") The board 1 acquires all the inputs (such as door opened) and executes the algorithm activating the outputs (alarm) as required; even in the absence of board 2. This guarantees that even in the case of vandalism that may destroy the exposed part (board 2), the alarm will keep on being activated in case required. ## Board 1 The board 1 comprises the microprocessor, the digital inputs (DI) and digital outputs (DO) as well as the communication links with the board 2. This board receives the input voltage (Vin) and generates the 5 Vdc required by the microprocessor. ![Alt text](/media/Board1.PNG?raw=true "Figure 3") In the initial prototypes of this board, there was no onboard 5V voltage regulator so an external one should be used to avoid relying on the microcontroller’s regulator. In this situation, the Vin pin in the microcontroller should be cut and left floating and it should be powered from the external voltage regulator at 5V (see Figure 4). ![Alt text](/media/Board1_regulator.png?raw=true "Figure 4 Initial prototype boards") ### Links with the board 2 The link with the board 2 is splitted in two connectors for the sake of routing simplicity. These can be highlighted in Figure 5. The connector highlighted in red implements the communication with the RFID module whereas the one in blue sends the power supply to the board 2 and the communication with the LCD display. Both links can be accommodated using a single UTP8 cable. Lengths up to 2,5 m have been properly tested and validated. The pin Tx in the red connector is not used so it should not be wired. ![Alt text](/media/Board1_to_2_connectors.png?raw=true "Figure 5 Connectors towards board 2") ### Digital inputs The board includes two digital inputs that will gather the information about the status of the door (pins DOOR and DOOR1 in Figure 3) and the status of the manual key that turns the unit into manual mode (pins KEY and KEY1). The digital inputs are optocoupled as seen on Figure 6. Here, the Vcc tag equals Vin so the value of the limiting resistors R1 and R2 should be chosen according to the actual value of Vin (12V usually). ![Alt text](/media/digital_in.png?raw=true "Figure 6") ### Digital outputs The board includes two digital outputs that will control the status of the lights (pin LIGHT in Figure 3) and the status of the alarm (ALARM pin). Additionally, two more digital outputs are prepared to include an electro-mechanical lock system to the door (pins LOCK and UNLOCK); but currently these feature has not been implemented in the firmware. The digital outputs are conceived to be used with standard relay boards as the one shown in Figure 7. These can be sourced from many internet suppliers for very few euros. ![Alt text](/media/relays.jpg?raw=true "Figure 7") To operate with these relay boards, the following cabling should be performed (Figure 8): - Digital outputs driving signals (green and blue traces) - Driving signals voltage (yellow trace) - Relay coils voltage (red and black traces) ![Alt text](/media/Board1-relay.PNG?raw=true "Figure 8 Cabling between the board 1 and a 12V relay board") The blue bridge shown in Figure 8 should only be used in case the voltage of the coils of the relays coincides with the driving signals voltage (5V). In any other case, it should be removed. Normally these relay boards have inverted input; i.e., to activate the relay, a logic 0 should be applied to the corresponding driving signal. This is how the firmware is programmed as default; in case a non-inverted output is required, the values of the code tags __RELAY_ON__ and __RELAY_OFF__ should be exchanged. ### Mechanical interface The board 1 includes four 2 mm diameter holes to be fixed to a frame by means of plastic spacers. The pattern for the holes is shown in Figure 9. ![Alt text](/media/Holes_board1.png?raw=true "Figure 9") ## Board 2 The board 2 comprises the RFID reader and an LCD display that shows information about the status of the device. This board is intended to be used with an ID-12LA reader and a breakout board (https://www.sparkfun.com/products/13030) but other serial interfaced readers might be used. This board receives the power supply from the link with the board 1 and converts it to a 5 Vdc stabilized voltage by means of its onboard regulator (U2_1 in Figure 10). ![Alt text](/media/Board2.PNG?raw=true "Figure 10") Board 2 also includes a buzzer (SG1 in Figure 10) that gives a sound feedback when a RFID tag has been read. It is additionally used to give some other information to the user such as a counter that is about to finish. ###Links with the board 1 The links with the board 1 are highlighted in the next figure with corresponding colors to Figure 5. An important remark is that the pin ID1_TX1 in Figure 11 should be wired to the pin Rx in Figure 5. ![Alt text](/media/Board2_to_1_connectors.png?raw=true "Figure 11") ### Mechanical interface The board 2 includes four 2 mm diameter holes to be fixed to a frame by means of plastic spacers. The pattern for the holes is shown in Figure 12. ![Alt text](/media/Holes_board2.png?raw=true "Figure 12") ## Boards interconnection The following figure summarizes the cabling between both boards. ![Alt text](/media/interconnection.png?raw=true "Figure 13")
5a08fe40cb4a545428972de8e352092b3ebf9959
[ "Markdown", "C++" ]
2
C++
mizamae/SafeAccess
96d1751ad62014befc24ae0b589a0f995e0448e7
65a531e4f7d4b2ed9842c2ba34cc476083ff3911
refs/heads/master
<file_sep>using System; using System.Linq; using System.Reflection; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyModel; namespace TagHelperPack.Sample.Services { public class AspNetCoreVersion { private readonly IHostingEnvironment _env; private string _version; public AspNetCoreVersion(IHostingEnvironment env) { _env = env; } public string CurrentVersion { get { if (_version == null) { var appAssembly = Assembly.Load(new AssemblyName(_env.ApplicationName)); _version = DependencyContext.Load(appAssembly) .RuntimeLibraries .FirstOrDefault(l => string.Equals(l.Name, "Microsoft.AspNetCore.Hosting", StringComparison.OrdinalIgnoreCase)) .Version; } return _version; } } } }
4707a1c0831f7338601ce4cbcd11abe86385d7fe
[ "C#" ]
1
C#
bikobanter/TagHelperPack
cbcdd77a6d953d4317d5cea047388b0693f424c0
73ea67ebf0cb531d51b812a556dd32b2cc578ae3
refs/heads/master
<repo_name>Yeeget31/islizxBlog<file_sep>/src/main/java/com/islizx/model/enums/TrueFalseEnum.java package com.islizx.model.enums; /** * @author lizx * @date 2020-02-14 - 16:23 */ public enum TrueFalseEnum { /** * 真 */ TRUE("true"), /** * 假 */ FALSE("false"); private String value; TrueFalseEnum(String value) { this.value = value; } public String getValue() { return value; } } <file_sep>/src/main/java/com/islizx/controller/home/HomeCategoryController.java package com.islizx.controller.home; import com.github.pagehelper.PageInfo; import com.islizx.entity.Type; import com.islizx.model.enums.BlogStatusEnum; import com.islizx.model.enums.PostTypeEnum; import com.islizx.service.BlogService; import com.islizx.service.TypeService; import com.islizx.vo.BlogQuery; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import java.util.HashMap; import java.util.List; /** * @author lizx * @date 2020-02-19 - 13:28 */ @Controller @RequestMapping(value = "/category") public class HomeCategoryController { @Autowired TypeService typeService; @Autowired BlogService blogService; @RequestMapping(value = "", method = RequestMethod.GET) public String categories(Model model){ return this.categories(model, -1, 1, 8, "updateTime", "desc"); } /** * 根据分类路径查询文章 * * @param model model * @param id 分类ID * @return string */ @RequestMapping(value = "/{cateId}/page/{page}", method = RequestMethod.GET) public String categories(Model model, @PathVariable("cateId") Integer id, @PathVariable(value = "page") Integer pageNumber, @RequestParam(value = "size", defaultValue = "8") Integer pageSize, @RequestParam(value = "sort", defaultValue = "updateTime") String sort, @RequestParam(value = "order", defaultValue = "desc") String order) { List<Type> types = typeService.listTypeWithCountAtHome(); if (id == -1) { for(Type type:types){ if(type.getBlogCount() != 0){ id = type.getId(); break; } } } HashMap<String, Object> criteria = new HashMap<>(1); criteria.put("postType", PostTypeEnum.POST_TYPE_POST.getCode()); criteria.put("published", BlogStatusEnum.PUBLISHED.getCode()); criteria.put("typeId", id); criteria.put("sort", sort); criteria.put("order", order); PageInfo pageInfo = blogService.pageBlog(pageNumber, pageSize, criteria); model.addAttribute("types", types); model.addAttribute("page", pageInfo); model.addAttribute("activeTypeId", id); return "home/types"; } } <file_sep>/src/main/java/com/islizx/mapper/AttachmentMapper.java package com.islizx.mapper; import com.islizx.entity.Attachment; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.HashMap; import java.util.List; /** * @author lizx * @date 2020-02-07 - 20:16 */ @Mapper public interface AttachmentMapper { /** * 根据id删除附件 * @param id * @return */ Integer deleteById(Integer id); /** * 添加附件 * @param attachment * @return */ Integer insert(Attachment attachment); /** * 修改附件 * @param attachment * @return */ Integer update(Attachment attachment); /** * 条件查询所有附件 * @param criteria * @return */ List<Attachment> findAll(HashMap<String, Object> criteria); /** * 查询所有附件 * @return */ List<Attachment> listAttachment(); /** * 根据id查询附件 * @param id * @return */ Attachment getAttachmentById(@Param(value = "id") Integer id); /** * 附件总数 * * @return */ Integer countAttachment(); /** * 获取附件总大小 * @return */ List<Long> sumAttachmentSize(); } <file_sep>/src/main/java/com/islizx/controller/admin/AdminController.java package com.islizx.controller.admin; import com.github.pagehelper.PageInfo; import com.islizx.config.annotation.SystemLog; import com.islizx.entity.Comment; import com.islizx.entity.Log; import com.islizx.model.dto.Msg; import com.islizx.entity.User; import com.islizx.model.enums.BlogStatusEnum; import com.islizx.model.enums.CommentStatusEnum; import com.islizx.model.enums.LogTypeEnum; import com.islizx.model.enums.PostTypeEnum; import com.islizx.service.*; import com.islizx.util.MyUtils; import com.islizx.util.VerifyCodeUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.imageio.ImageIO; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.*; import static com.islizx.util.MyUtils.getIpAddr; import static com.islizx.util.MyUtils.code; /** * @author lizx * @date 2020-01-30 - 11:17 */ @Controller @Slf4j public class AdminController { @Autowired private UserService userService; @Autowired private BlogService blogService; @Autowired private CommentService commentService; @Autowired private AttachmentService attachmentService; @Autowired private LogService logService; @RequestMapping("/error") public String error(){ return "error/404"; } /** * 登录页面显示 * @return */ @RequestMapping("/login") public String loginPage(HttpServletRequest request,HttpSession session, Map<String, Object> map) { String username = ""; String password = ""; //获取当前站点的所有Cookie Cookie[] cookies = request.getCookies(); for (int i = 0; i < cookies.length; i++) {//对cookies中的数据进行遍历,找到用户名、密码的数据 if ("username".equals(cookies[i].getName())) { username = cookies[i].getValue(); } else if ("password".equals(cookies[i].getName())) { password = cookies[i].getValue(); } } // 判断是否为通过拦截器重定向到这 String msg = (String) session.getAttribute("msg"); if(msg != null && !msg.equals("")){ map.put("msg", msg); session.removeAttribute("msg"); } map.put("username", username); map.put("password", <PASSWORD>); return "admin/login"; } /** * 后台首页 * @return */ @RequestMapping("/admin") public String indexPage(Model model, HttpSession session) throws Exception{ // 三种文章类型个数,文章数 Integer articlePublish = blogService.countBlog(BlogStatusEnum.PUBLISHED.getCode(), PostTypeEnum.POST_TYPE_POST.getCode()); Integer articleDraft = blogService.countBlog(BlogStatusEnum.DRAFT.getCode(), PostTypeEnum.POST_TYPE_POST.getCode()); Integer articleTrash =blogService.countBlog(BlogStatusEnum.TRASH.getCode(), PostTypeEnum.POST_TYPE_POST.getCode()); model.addAttribute("articlePublish", articlePublish); model.addAttribute("articleDraft", articleDraft); model.addAttribute("articleTrash", articleTrash); model.addAttribute("articleSum", articlePublish+articleDraft+articleTrash); // 三种评论类型个数 Integer commentPublish = commentService.countCommentByPass(CommentStatusEnum.PUBLISHED.getCode()); Integer commentDraft = commentService.countCommentByPass(CommentStatusEnum.CHECKING.getCode()); Integer commentTrash = commentService.countCommentByPass(CommentStatusEnum.RECYCLE.getCode()); model.addAttribute("commentPublish", commentPublish); model.addAttribute("commentDraft", commentDraft); model.addAttribute("commentTrash", commentTrash); model.addAttribute("commentSum", commentPublish+commentDraft+commentTrash); // 获取附件总数 Integer attachementSum = attachmentService.countAttachment(); String attachSizeSum = attachmentService.sumAttachmentSize(); model.addAttribute("attachementSum", attachementSum); model.addAttribute("attachSizeSum", attachSizeSum); // 获取登录用户 SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd"); User loginUser = (User) session.getAttribute("user"); String startTime = formatter.format(loginUser.getRegisterTime()); String endTime = formatter.format(new Date()); model.addAttribute("joinTime", MyUtils.caculateTotalTime(startTime, endTime)); // 获取所有用户 List<User> userList = userService.listUser(); model.addAttribute("userList", userList); // 获取最新评论 List<Comment> commentList = commentService.getCommentLimit(6); model.addAttribute("commentLit", commentList); // 获取最新文章 //model.addAttribute("article",blogService.listRecentBlog(6)); return "admin/index"; } /** * 登录验证 * * @param request * @param response * @return */ @RequestMapping(value = "/loginVerify",method = RequestMethod.POST) @ResponseBody @SystemLog(description = "用户登录", type = LogTypeEnum.LOGIN) public Msg loginVerify(HttpServletRequest request, HttpServletResponse response, HttpSession session) { log.info("hello================"); String username = request.getParameter("username"); String password = request.getParameter("<PASSWORD>"); String rememberme = request.getParameter("rememberme"); String verifyCode = request.getParameter("verifyCode"); if(verifyCode==null || verifyCode.equals("")){ return Msg.fail().add("msg","请输入验证码").add("code",101); } else if(!verifyCode.equals(request.getSession().getAttribute("verifyCode"))){ return Msg.fail().add("msg","验证码错误").add("code", 101); } else if(username==null || username.equals("")){ return Msg.fail().add("msg","请输入用户名").add("code", 103); } else if(password==null || password.equals("")){ return Msg.fail().add("msg","请输入密码").add("code", 102); } User user = userService.getUserByNameOrEmail(username); if(user==null) { return Msg.fail().add("msg","用户名不存在!").add("code", 103); } else if(!user.getType()){ return Msg.fail().add("msg","该用户不是管理员!").add("code", 103); } else if(!code(password).equals(user.getPassword())) { return Msg.fail().add("msg","密码错误!").add("code", 102); } String contextPath = request.getContextPath(); //添加session session.setAttribute("user", user); //添加cookie if(rememberme!=null) { //创建两个Cookie对象 Cookie nameCookie = new Cookie("username", username); //设置Cookie的有效期为3天 nameCookie.setMaxAge(60 * 60 * 24 * 3); nameCookie.setPath(contextPath + "/"); Cookie pwdCookie = new Cookie("password", <PASSWORD>); pwdCookie.setMaxAge(60 * 60 * 24 * 3); pwdCookie.setPath(contextPath + "/"); response.addCookie(nameCookie); response.addCookie(pwdCookie); }else{ Cookie[] cookies = request.getCookies(); for (int i = 0; i < cookies.length; i++) {//对cookies中的数据进行遍历,找到用户名、密码的数据 if ("username".equals(cookies[i].getName()) || "password".equals(cookies[i].getName())) { Cookie cookie = new Cookie(cookies[i].getName(), null); cookie.setMaxAge(0); cookie.setPath(contextPath + "/"); response.addCookie(cookie); } } } user.setLastLoginTime(new Date()); user.setLastLoginIp(getIpAddr(request)); userService.updateUser(user); //登录成功 return Msg.success(); } /** * 刷新验证码 * @param request * @param response */ @RequestMapping(value = "/verifyCode", method = RequestMethod.GET) public void verifyCode(HttpServletRequest request ,HttpServletResponse response){ System.out.println("verifyCode执行====================="); response.setContentType("image/jpeg"); //设置页面不缓存 response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); VerifyCodeUtil vcUtil = VerifyCodeUtil.Instance(); //将随机码设置在session中 request.getSession().setAttribute("verifyCode", vcUtil.getResult()+""); try { ImageIO.write(vcUtil.getImage(), "jpeg", response.getOutputStream()); response.getOutputStream().flush(); response.getOutputStream().close(); response.flushBuffer(); } catch (IOException e) { e.printStackTrace(); } } /** * 退出登录 * * @param session * @return */ @RequestMapping(value = "/admin/logout") public String logout(HttpSession session) { session.removeAttribute("user"); session.invalidate(); return "redirect:/login"; } } <file_sep>/src/main/java/com/islizx/controller/admin/TypeController.java package com.islizx.controller.admin; import com.github.pagehelper.PageInfo; import com.islizx.config.annotation.SystemLog; import com.islizx.model.dto.Msg; import com.islizx.model.enums.LogTypeEnum; import com.islizx.service.BlogService; import com.islizx.service.TypeService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import com.islizx.entity.Type; import javax.servlet.http.HttpSession; /** * @author lizx * @date 2020-02-03 - 19:25 */ @Controller @RequestMapping("/admin") @Slf4j public class TypeController { @Autowired private TypeService typeService; @Autowired private BlogService blogService; /** * 后台分类列表显示 * * @param model * @return */ /* @RequestMapping(value = "/types", method = RequestMethod.GET) public String types(Model model, HttpSession session) { List<Type> typeList = typeService.listTypeWithCount(); model.addAttribute("typelist",typeList); String msg = (String) session.getAttribute("msg"); if(msg != null && !msg.equals("")){ model.addAttribute("msg", msg); session.removeAttribute("msg"); } return "Admin/types"; }*/ /** * 进入新增页面 * * @param model * @return */ @RequestMapping(value = "/types/input", method = RequestMethod.GET) @SystemLog(description = "新增分类", type = LogTypeEnum.OPERATION) public String input(@RequestParam(required = false, defaultValue = "1") Integer pageIndex, @RequestParam(required = false, defaultValue = "15") Integer pageSize, Model model, HttpSession session) { PageInfo<Type> typePageInfo = typeService.pageType(pageIndex, pageSize); model.addAttribute("pageInfo",typePageInfo); String msg = (String) session.getAttribute("msg"); if(msg != null && !msg.equals("")){ model.addAttribute("msg", msg); session.removeAttribute("msg"); } model.addAttribute("type", new Type()); return "admin/article/types-input"; } /** * 进入更新页面 * * @param id * @param model * @return */ @RequestMapping(value = "/types/input/{id}", method = RequestMethod.GET) public String editInput(@RequestParam(required = false, defaultValue = "1") Integer pageIndex, @RequestParam(required = false, defaultValue = "15") Integer pageSize, @PathVariable Integer id, Model model, HttpSession session) { PageInfo<Type> typePageInfo = typeService.pageType(pageIndex, pageSize); model.addAttribute("pageInfo",typePageInfo); String msg = (String) session.getAttribute("msg"); if(msg != null && !msg.equals("")){ model.addAttribute("msg", msg); session.removeAttribute("msg"); } model.addAttribute("type", typeService.getTypeById(id)); return "admin/article/types-input"; } /** * 分类更新提交 * @param type * @param session * @return */ @RequestMapping(value = "/types", method = RequestMethod.POST) @SystemLog(description = "更新分类", type = LogTypeEnum.OPERATION) public String post(Type type, HttpSession session){ String msg = ""; Type typeDB = typeService.getTypeByName(type.getName()); if(type.getId() == 0 && typeDB == null){ typeService.insertType(type); msg = "分类更新成功"; }else if(type.getId() != 0){ if((typeDB == null) || (typeDB.getId() == type.getId())){ typeService.updateType(type); msg = "分类更新成功"; }else{ msg = "该分类已存在"; } }else{ msg = "该分类已存在"; } session.setAttribute("msg", msg); return "redirect:/admin/types/input"; } /** * 删除分类 * * @param id * @return */ @RequestMapping(value = "/types/{id}", method = RequestMethod.DELETE) @ResponseBody @SystemLog(description = "删除分类", type = LogTypeEnum.OPERATION) public Msg delete(@PathVariable("id") Integer id) { //禁止删除有文章的分类 int count = blogService.countBlogByTypeId(id); if (count == 0) { typeService.deleteType(id); return Msg.success().add("msg", "分类删除成功"); } return Msg.fail().add("msg", "不能删除包含文章的分类"); } /** * 返回json格式的typelist * * @param model * @return */ @RequestMapping(value = "/typesByJson") public String typesJson(@RequestParam(required = false, defaultValue = "1") Integer pageIndex, @RequestParam(required = false, defaultValue = "15") Integer pageSize, Model model) { PageInfo<Type> typePageInfo = typeService.pageType(pageIndex, pageSize); model.addAttribute("pageInfo",typePageInfo); return "admin/article/types-input :: typeList"; } @RequestMapping(value = "/checkTypeName") @ResponseBody public Msg typenameexist(String typename, Integer id){ Type typeDB = typeService.getTypeByName(typename); if(typeDB != null){ if(typeDB.getId() != id){ return Msg.fail().add("msg", "该分类已存在"); } } return Msg.success().add("msg", "该分类名有效"); } } <file_sep>/src/main/java/com/islizx/entity/Notice.java package com.islizx.entity; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * @author lizx * @date 2020-01-30 - 12:27 */ @Data public class Notice implements Serializable { private static final long serialVersionUID = -6721825786484798754L; private Integer id; private String title; private String content; private Date createTime; private Date updateTime; private Integer status; private Integer order; } <file_sep>/src/main/java/com/islizx/service/impl/CommentServiceImpl.java package com.islizx.service.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.islizx.entity.Blog; import com.islizx.entity.Comment; import com.islizx.mapper.BlogMapper; import com.islizx.mapper.CommentMapper; import com.islizx.service.CommentService; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; /** * @author lizx * @date 2020-02-14 - 13:12 */ @Service public class CommentServiceImpl implements CommentService { @Autowired(required = false) private CommentMapper commentMapper; @Autowired(required = false) private BlogMapper blogMapper; @Override public PageInfo<Comment> pageComment(Integer pageIndex, Integer pageSize, HashMap<String, Object> criteria) { PageHelper.startPage(pageIndex, pageSize); List<Comment> commentList = commentMapper.findAll(criteria); for (int i = 0; i < commentList.size(); i++) { //封装Blog Blog blog = blogMapper.getBlogByPublishedAndId(null,null, commentList.get(i).getBlogId()); commentList.get(i).setBlog(blog); // 封装parentComment Integer parentCommentId = commentList.get(i).getParentCommentId(); if(parentCommentId != null){ Comment parentComment = commentMapper.getById(null, parentCommentId); commentList.get(i).setParentComment(parentComment); } } return new PageInfo<>(commentList, 5); } @Override @CacheEvict(value= "comment", allEntries=true) public Comment updateCommentPass(Integer id, Integer pass) { //子评论随父评论状态一起改变 //1.修改该评论状态 Comment comment = commentMapper.getById(null, id); comment.setPass(pass); commentMapper.updateCommentPass(id, pass); //2.修改该评论的子评论状态 List<Integer> childIds = commentMapper.selectChildCommentIds(id); childIds.forEach(childId -> commentMapper.updateCommentPass(childId, pass)); //3.修改文章评论数 blogMapper.updateCommentCount(comment.getBlogId()); return comment; } @Override @CacheEvict(value= "comment", allEntries=true) public Comment insertComment(Comment comment) { comment.setCreateTime(new Date()); commentMapper.insertComment(comment); blogMapper.updateCommentCount(comment.getBlogId()); return comment; } @Override @CacheEvict(value= "comment", allEntries=true) public void deleteComment(Integer commentId) { Comment comment = commentMapper.getById(null, commentId); if (comment != null) { //1.删除评论 commentMapper.deleteById(commentId); //2.修改文章的评论数量 blogMapper.updateCommentCount(comment.getBlogId()); } } @Override @Cacheable(value = "comment", key = "'getListCommentByBlogId_' + #blogPublished + '_' + #commentPublished + '_' + #postType + '_' + #pageIndex + '_' + #pageSize + '_' + #blogId") public PageInfo<Comment> getListCommentByBlogId(Integer blogPublished,Integer commentPublished, Integer postType, Integer pageIndex, Integer pageSize,Integer blogId) { PageHelper.startPage(pageIndex, pageSize); List<Comment> comments = commentMapper.findByBlogIdAndParentCommentNull(blogId); PageInfo<Comment> pageInfo = new PageInfo<>(comments, 5); List<Comment> commentsCopy = new ArrayList<>(); for(Comment comment:pageInfo.getList()){ commentsCopy.add(packagingComment(blogPublished, commentPublished, postType, comment)); } /*return eachComment(commentsCopy);*/ pageInfo.setList(eachComment(commentsCopy)); return pageInfo; } @Override public Comment getById(Integer blogPublished,Integer commentPublished, Integer postType,Integer id) { Comment comment = commentMapper.getById(commentPublished, id); if(comment == null){ return null; } return packagingComment(blogPublished,commentPublished, postType, comment); } @Override public Integer countCommentByPass(Integer pass) { return commentMapper.countComment(pass); } @Override public List<Comment> findByBatchIds(List<Integer> ids) { return commentMapper.selectByIds(ids); } @Override public List<Comment> getCommentLimit(Integer limit) { return commentMapper.findLatestCommentByLimit(limit); } /** * 封装评论 * @param comment * @return */ public Comment packagingComment(Integer blogPublished, Integer commentPublished, Integer postType,Comment comment){ // 封装文章 comment.setBlog(blogMapper.getBlogByPublishedAndId(blogPublished,postType, comment.getBlogId())); // 封装父级评论 if(comment.getParentCommentId() != -1){ comment.setParentComment(commentMapper.getById(commentPublished, comment.getParentCommentId())); } // 封装被回复评论 // 1.获取所有的子评论 List<Integer> childIds = commentMapper.selectChildCommentIds(comment.getId()); for(Integer childId:childIds){ /*comment.getReplyComments().add(commentMapper.getById(childId));*/ Comment tempComment = this.getById(blogPublished,commentPublished, postType, childId); if(tempComment != null){ comment.getReplyComments().add(tempComment); } } return comment; } /** * 循环每个顶级的评论节点 * @param comments * @return */ private List<Comment> eachComment(List<Comment> comments) { List<Comment> commentsView = new ArrayList<>(); for (Comment comment : comments) { Comment c = new Comment(); BeanUtils.copyProperties(comment,c); commentsView.add(c); } //合并评论的各层子代到第一级子代集合中 combineChildren(commentsView); return commentsView; } /** * * @param comments root根节点,blog不为空的对象集合 * @return */ private void combineChildren(List<Comment> comments) { for (Comment comment : comments) { List<Comment> replys1 = comment.getReplyComments(); for(Comment reply1 : replys1) { //循环迭代,找出子代,存放在tempReplys中 recursively(reply1); } //修改顶级节点的reply集合为迭代处理后的集合 comment.setReplyComments(tempReplys); //清除临时存放区 tempReplys = new ArrayList<>(); } } //存放迭代找出的所有子代的集合 private List<Comment> tempReplys = new ArrayList<>(); /** * 递归迭代,剥洋葱 * @param comment 被迭代的对象 * @return */ private void recursively(Comment comment) { tempReplys.add(comment);//顶节点添加到临时存放集合 if(comment == null || comment.getReplyComments() == null){ return; } if (comment.getReplyComments().size()>0) { List<Comment> replys = comment.getReplyComments(); for (Comment reply : replys) { tempReplys.add(reply); if (reply.getReplyComments().size()>0) { recursively(reply); } } } } } <file_sep>/src/main/java/com/islizx/entity/Options.java package com.islizx.entity; import lombok.Data; import java.io.Serializable; /** * @author lizx * @date 2020-01-30 - 12:26 */ @Data public class Options implements Serializable { private static final long serialVersionUID = 3667068831906647771L; private Integer id; private String siteTitle; private String siteDescrption; private String metaDescrption; private String metaKeyword; private String aboutsiteAvatar; private String aboutsiteTitle; private String aboutsiteContent; private String aboutsiteWechat; private String aboutsiteQq; private String aboutsiteGithub; private String aboutsiteWeibo; private String tongji; private Integer status; } <file_sep>/src/main/java/com/islizx/vo/UserQuery.java package com.islizx.vo; import lombok.Data; /** * @author lizx * @date 2020-02-05 - 23:35 */ @Data public class UserQuery { private Integer id; private String username; private String nickname; private String email; private String avatar; private String url; private String description; private Boolean status; } <file_sep>/src/main/java/com/islizx/service/impl/AttachmentServiceImpl.java package com.islizx.service.impl; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.StrUtil; import com.aliyun.oss.OSSClient; import com.aliyun.oss.model.ObjectMetadata; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.islizx.entity.Attachment; import com.islizx.mapper.AttachmentMapper; import com.islizx.service.AttachmentService; import com.islizx.util.ConfigManager; import com.islizx.util.MyUtils; import net.coobird.thumbnailator.Thumbnails; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import java.awt.image.BufferedImage; import java.io.*; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author lizx * @date 2020-02-07 - 15:56 */ @Service public class AttachmentServiceImpl implements AttachmentService { @Autowired(required = false) AttachmentMapper attachmentMapper; private static String ENDPOINT = null; private static String ACCESSKEYID = null; private static String ACCESSKEYSECRET = null; private static String BUCKETNAME = null; private static String URLPREFIX = null; private OSSClient client = null; private ObjectMetadata meta = null; // 允许上传的格式 private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".gif", ".png"}; static{ try { ENDPOINT = ConfigManager.getProperty("aliyun.endpoint"); ACCESSKEYID = ConfigManager.getProperty("aliyun.accessKeyId"); ACCESSKEYSECRET = ConfigManager.getProperty("aliyun.accessKeySecret"); BUCKETNAME = ConfigManager.getProperty("aliyun.bucketName"); URLPREFIX = ConfigManager.getProperty("aliyun.urlPrefix"); } catch (java.lang.Exception e) { e.printStackTrace(); } } public void init(){ // 初始化一个OSSClient client = new OSSClient(ENDPOINT,ACCESSKEYID, ACCESSKEYSECRET); meta = new ObjectMetadata(); } @Override public Map<String, Object> attachUpload(MultipartFile file, HttpServletRequest request) { final Map<String, Object> resultMap = new HashMap<>(7); try { //用户目录 final StringBuilder uploadPath = new StringBuilder(request.getSession().getServletContext().getRealPath("/static/upload/")); uploadPath.append(DateUtil.thisYear()).append("/").append(DateUtil.thisMonth() + 1).append("/"); final File mediaPath = new File(uploadPath.toString()); if (!mediaPath.exists()) { if (!mediaPath.mkdirs()) { resultMap.put("success", "0"); return resultMap; } } String nameWithOutSuffix = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date().getTime()); nameWithOutSuffix+= "_" + String.valueOf((int)(Math.random()*1000)); //文件后缀 final String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.') + 1); //带后缀 String fileName = nameWithOutSuffix + "." + fileSuffix; //判断文件名是否已存在 File descFile = new File(mediaPath.getAbsoluteFile(), fileName.toString()); int i = 1; while (descFile.exists()) { nameWithOutSuffix = nameWithOutSuffix + "(" + i + ")"; descFile = new File(mediaPath.getAbsoluteFile(), nameWithOutSuffix + "." + fileSuffix); i++; } file.transferTo(descFile); //文件原路径 final StringBuilder fullPath = new StringBuilder(mediaPath.getAbsolutePath()); fullPath.append("/"); fullPath.append(nameWithOutSuffix + "." + fileSuffix); //压缩文件路径 final StringBuilder fullSmallPath = new StringBuilder(mediaPath.getAbsolutePath()); fullSmallPath.append("/"); fullSmallPath.append(nameWithOutSuffix); fullSmallPath.append("_small."); fullSmallPath.append(fileSuffix); //压缩图片 Thumbnails.of(fullPath.toString()).size(256, 256).keepAspectRatio(false).toFile(fullSmallPath.toString()); //映射路径 final StringBuilder filePath = new StringBuilder("/upload/"); filePath.append(DateUtil.thisYear()); filePath.append("/"); filePath.append(DateUtil.thisMonth() + 1); filePath.append("/"); filePath.append(nameWithOutSuffix + "." + fileSuffix); //缩略图映射路径 final StringBuilder fileSmallPath = new StringBuilder("/upload/"); fileSmallPath.append(DateUtil.thisYear()); fileSmallPath.append("/"); fileSmallPath.append(DateUtil.thisMonth() + 1); fileSmallPath.append("/"); fileSmallPath.append(nameWithOutSuffix); fileSmallPath.append("_small."); fileSmallPath.append(fileSuffix); Long l = new File(fullPath.toString()).length(); final String size = MyUtils.parseSize(l); final String wh = MyUtils.getImageWh(new File(fullPath.toString())); resultMap.put("rowSize", l); resultMap.put("fileName", fileName.toString()); resultMap.put("filePath", filePath.toString()); resultMap.put("smallPath", fileSmallPath.toString()); resultMap.put("suffix", fileSuffix); resultMap.put("size", size); resultMap.put("wh", wh); } catch (IOException e) { e.printStackTrace(); } return resultMap; } /*public Map<String, Object> attachUpload(MultipartFile file, HttpServletRequest request) { final Map<String, Object> resultMap = new HashMap<>(7); try { //用户目录 final StringBuilder uploadPath = new StringBuilder("images/"); uploadPath.append(DateUtil.thisYear()).append("/").append(DateUtil.thisMonth() + 1).append("/"); // 存储路径:images/2020/08/ final File mediaPath = new File(uploadPath.toString()); String nameWithOutSuffix = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date().getTime()); nameWithOutSuffix+= "_" + String.valueOf((int)(Math.random()*1000)); //文件后缀 final String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.') + 1); //带后缀(文件名:15564277465972939.jpg) String fileName = nameWithOutSuffix + "." + fileSuffix; init(); // 校验图片格式 boolean isLegal = false; for (String type : IMAGE_TYPE) { if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(), type)) { isLegal = true; break; } } // 压缩代码 InputStream input = file.getInputStream(); ByteArrayOutputStream byteArrayOutputStreamut = new ByteArrayOutputStream(); Thumbnails.of(input).size(256, 256).keepAspectRatio(false).toOutputStream(byteArrayOutputStreamut); input = new ByteArrayInputStream(byteArrayOutputStreamut.toByteArray()); // 上传到阿里云 try { client.putObject(BUCKETNAME, uploadPath.toString() + fileName, new ByteArrayInputStream(file.getBytes())); client.putObject(BUCKETNAME, uploadPath.toString() + nameWithOutSuffix + "_small." + fileSuffix, input); } catch (Exception e) { e.printStackTrace(); } finally { client.shutdown(); } Long l = file.getSize(); final String size = MyUtils.parseSize(l); final BufferedImage image = ImageIO.read(file.getInputStream()); if (image != null) { resultMap.put("wh", image.getWidth() + "x" + image.getHeight()); } resultMap.put("rowSize", l); resultMap.put("fileName", fileName.toString()); resultMap.put("filePath", URLPREFIX + "/" + uploadPath.toString() + fileName); resultMap.put("smallPath", URLPREFIX + "/" + uploadPath.toString() + nameWithOutSuffix + "_small." + fileSuffix); resultMap.put("suffix", fileSuffix); resultMap.put("size", size); } catch (IOException e) { e.printStackTrace(); } return resultMap; }*/ @Override public Attachment insert(Attachment attachment) { attachmentMapper.insert(attachment); return attachment; } @Override public Attachment update(Attachment attachment) { attachmentMapper.update(attachment); return attachment; } @Override public PageInfo<Attachment> pageAttachment(Integer pageIndex, Integer pageSize, HashMap<String, Object> criteria) { PageHelper.startPage(pageIndex, pageSize); List<Attachment> attachmentList = attachmentMapper.findAll(criteria); return new PageInfo<>(attachmentList, 5); } @Override public Attachment getAttachment(Integer id) { return attachmentMapper.getAttachmentById(id); } @Override public void deleteAttachment(Integer id) { attachmentMapper.deleteById(id); } @Override public Integer countAttachment() { return attachmentMapper.countAttachment(); } @Override public String sumAttachmentSize() { List<Long> sumAttachSize = attachmentMapper.sumAttachmentSize(); Long sum = 0l; for(Long size:sumAttachSize){ sum += size; } return MyUtils.parseSize(sum); } } <file_sep>/src/main/java/com/islizx/util/MyUtils.java package com.islizx.util; import com.islizx.model.enums.CommonParamsEnum; import io.github.biezhi.ome.OhMyEmail; import org.commonmark.Extension; import org.commonmark.ext.gfm.tables.TableBlock; import org.commonmark.ext.gfm.tables.TablesExtension; import org.commonmark.ext.heading.anchor.HeadingAnchorExtension; import org.commonmark.node.Link; import org.commonmark.node.Node; import org.commonmark.parser.Parser; import org.commonmark.renderer.html.AttributeProvider; import org.commonmark.renderer.html.AttributeProviderContext; import org.commonmark.renderer.html.AttributeProviderFactory; import org.commonmark.renderer.html.HtmlRenderer; import org.springframework.beans.BeanWrapper; import org.springframework.beans.BeanWrapperImpl; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import java.awt.image.BufferedImage; import java.beans.PropertyDescriptor; import java.io.File; import java.io.FileInputStream; import java.net.InetAddress; import java.net.UnknownHostException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author lizx * @date 2020-01-30 - 16:42 */ public class MyUtils { /** * 获得IP地址 * * @param request * @return */ public static String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); if ("127.0.0.1".equals(ip)) { //根据网卡取本机配置的IP InetAddress inet = null; try { inet = InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); } ip = inet.getHostAddress(); } } // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割 if (ip != null && ip.length() > 15) { if (ip.indexOf(",") > 0) { ip = ip.substring(0, ip.indexOf(",")); } } if("0:0:0:0:0:0:0:1".equals(ip)){ ip = "127.0.0.1"; } return ip; } public static String onlyName(){ SimpleDateFormat sdf = new SimpleDateFormat("yyy"); Random random = new Random(); Date date = new Date(); String resu = sdf.format(date)+(random.nextInt(1000)+1000); return resu; } /** * MD5加密类 * @param str 要加密的字符串 * @return 加密后的字符串 */ public static String code(String str){ try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[]byteDigest = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < byteDigest.length; offset++) { i = byteDigest[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } //32位加密 return buf.toString(); // 16位的加密 //return buf.toString().substring(8, 24); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } /** * 转换文件大小 * * @param size size * @return String */ public static String parseSize(long size) { if (size < CommonParamsEnum.BYTE.getValue()) { return String.valueOf(size) + "B"; } else { size = size / 1024; } if (size < CommonParamsEnum.BYTE.getValue()) { return String.valueOf(size) + "KB"; } else { size = size / 1024; } if (size < CommonParamsEnum.BYTE.getValue()) { size = size * 100; return String.valueOf((size / 100)) + "." + String.valueOf((size % 100)) + "MB"; } else { size = size * 100 / 1024; return String.valueOf((size / 100)) + "." + String.valueOf((size % 100)) + "GB"; } } /** * 获取文件长和宽 * * @param file file * @return String */ public static String getImageWh(File file) { try { BufferedImage image = ImageIO.read(new FileInputStream(file)); return image.getWidth() + "x" + image.getHeight(); } catch (Exception e) { e.printStackTrace(); return ""; } } /** * 配置邮件 * * @param userName 邮件地址 * @param password <PASSWORD> */ public static void configMail(String userName, String password) { OhMyEmail.config(OhMyEmail.SMTP_QQ(false), userName, password); } /** * 获取所有的属性值为空属性名数组 * @param source * @return */ public static String[] getNullPropertyNames(Object source) { BeanWrapper beanWrapper = new BeanWrapperImpl(source); PropertyDescriptor[] pds = beanWrapper.getPropertyDescriptors(); List<String> nullPropertyNames = new ArrayList<>(); for (PropertyDescriptor pd : pds) { String propertyName = pd.getName(); if (beanWrapper.getPropertyValue(propertyName) == null) { nullPropertyNames.add(propertyName); } } return nullPropertyNames.toArray(new String[nullPropertyNames.size()]); } /** * markdown格式转换成HTML格式 * @param markdown * @return */ public static String markdownToHtml(String markdown) { Parser parser = Parser.builder().build(); Node document = parser.parse(markdown); HtmlRenderer renderer = HtmlRenderer.builder().build(); return renderer.render(document); } /** * 增加扩展[标题锚点,表格生成] * Markdown转换成HTML * @param markdown * @return */ public static String markdownToHtmlExtensions(String markdown) { //h标题生成id Set<Extension> headingAnchorExtensions = Collections.singleton(HeadingAnchorExtension.create()); //转换table的HTML List<Extension> tableExtension = Arrays.asList(TablesExtension.create()); Parser parser = Parser.builder() .extensions(tableExtension) .build(); Node document = parser.parse(markdown); HtmlRenderer renderer = HtmlRenderer.builder() .extensions(headingAnchorExtensions) .extensions(tableExtension) .attributeProviderFactory(new AttributeProviderFactory() { public AttributeProvider create(AttributeProviderContext context) { return new CustomAttributeProvider(); } }) .build(); return renderer.render(document); } /** * 处理标签的属性 */ static class CustomAttributeProvider implements AttributeProvider { @Override public void setAttributes(Node node, String tagName, Map<String, String> attributes) { //改变a标签的target属性为_blank if (node instanceof Link) { attributes.put("target", "_blank"); } if (node instanceof TableBlock) { attributes.put("class", "ui celled table"); } } } /** * 计算两个时间之间相差的天数 * @param startTime : 开始时间 * @param endTime : 结束时间 * @return */ public static int caculateTotalTime(String startTime,String endTime) { SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd"); Date date1=null; Date date = null; Long l = 0L; try { date = formatter.parse(startTime); long ts = date.getTime(); date1 = formatter.parse(endTime); long ts1 = date1.getTime(); l = (ts1 - ts) / (1000 * 60 * 60 * 24); } catch (ParseException e) { e.printStackTrace(); } return l.intValue(); } public static Integer strToInt(String str){ String regEx="[^0-9]"; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(str); String numStr = m.replaceAll("").trim(); return Integer.parseInt(numStr); } } <file_sep>/src/main/java/com/islizx/config/redis/RedisConfig.java package com.islizx.config.redis; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import redis.clients.jedis.JedisPoolConfig; import java.util.ArrayList; import java.util.List; /** * @author lizx * @date 2020-03-10 - 19:18 */ @Configuration public class RedisConfig { @Value("${redis.database}") private int database; @Value("${redis.hostName}") private String hostName; @Value("${redis.port}") private int port; @Value("${redis.password}") private String password; @Value("${redis.maxIdle}") private int maxIdle; @Value("${redis.maxTotal}") private int maxTotal; @Value("${redis.maxWaitMillis}") private long maxWaitMillis; @Value("${redis.expiration}") private long expiration; @Bean public JedisConnectionFactory jedisConnectionFactory() { JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(); jedisConnectionFactory.setDatabase(database); jedisConnectionFactory.setHostName(hostName); ; jedisConnectionFactory.setPort(port); ; jedisConnectionFactory.setPassword(password); jedisConnectionFactory.setPoolConfig(jedisPoolConfig()); return jedisConnectionFactory; } @Bean public JedisPoolConfig jedisPoolConfig() { JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxIdle(maxIdle); jedisPoolConfig.setMaxTotal(maxTotal); jedisPoolConfig.setMaxWaitMillis(maxWaitMillis); return jedisPoolConfig; } @Bean public ObjectMapper getObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); // 支持任意对象的json序列化和反序列化 objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); return objectMapper; } @Bean public Jackson2JsonRedisSerializer jackson2JsonRedisSerializer() { Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); jackson2JsonRedisSerializer.setObjectMapper(getObjectMapper()); return jackson2JsonRedisSerializer; } @Bean public RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(jedisConnectionFactory()); redisTemplate.setKeySerializer(jackson2JsonRedisSerializer()); redisTemplate.setValueSerializer(jackson2JsonRedisSerializer()); redisTemplate.setHashKeySerializer(jackson2JsonRedisSerializer()); redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer()); // 开启事务支持 redisTemplate.setEnableTransactionSupport(true); return redisTemplate; } /** * 配置RedisCacheManager * * @return */ @Bean(name = "cacheManager") public RedisCacheManager redisCacheManager() { RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate()); redisCacheManager.setDefaultExpiration(expiration); // 配置缓存区间 List<String> cacheNames = new ArrayList<String>(); cacheNames.add("blog"); cacheNames.add("comment"); redisCacheManager.setCacheNames(cacheNames); return redisCacheManager; } @Bean public RedisCacheConfig redisCacheConfig() { RedisCacheConfig redisCacheConfig = new RedisCacheConfig( jedisConnectionFactory(), redisTemplate(), redisCacheManager() ); return redisCacheConfig; } } <file_sep>/src/main/java/com/islizx/entity/Blog.java package com.islizx.entity; import lombok.Data; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @author lizx * @date 2020-01-30 - 12:05 */ @Data public class Blog implements Serializable { private static final long serialVersionUID = -212654738057672788L; private Integer id; private Boolean appreciation; private Boolean commentabled; private String content; private Date createTime; private String description; private String firstPicture; private String flag; private Integer published; private Boolean recommend; private Boolean shareStatement; private String title; private Date updateTime; private Integer views; private Integer typeId; private Integer userId; private Integer commentCount; private Integer likeCount; /** * 文章类型 * post 文章 * page 页面 */ private Integer postType; private String url; private Type type; private User user; private List<Tag> tags = new ArrayList<>(); private List<Integer> tagIdList; /* private String tagIds;*/ public void init() { this.tagIdList = tagsToIds(this.getTags()); } //1,2,3 private List<Integer> tagsToIds(List<Tag> tags) { if (!tags.isEmpty()) { List<Integer> taglist = new ArrayList<Integer>(); for (Tag tag : tags) { taglist.add(tag.getId()); } return taglist; } else { return tagIdList; } } } <file_sep>/src/main/java/com/islizx/mapper/BlogTagRefMapper.java package com.islizx.mapper; import com.islizx.entity.BlogTagRef; import com.islizx.entity.Tag; import org.apache.ibatis.annotations.Mapper; import java.util.List; /** * @author lizx * @date 2020-01-31 - 19:36 */ @Mapper public interface BlogTagRefMapper { /** * 添加文章和标签关联记录 * @param record 关联对象 * @return 影响行数 */ int insert(BlogTagRef record); /** * 根据标签ID删除记录 * @param tagId 标签ID * @return 影响行数 */ int deleteByTagId(Integer tagId); /** * 根据文章ID删除记录 * @param BlogId 文章ID * @return 影响行数 */ int deleteByBlogId(Integer BlogId); /** * 根据标签ID统计文章数 * @param tagId 标签ID * @return 文章数量 */ int countBlogByTagId(Integer tagId); /** * 根据文章获得标签列表 * * @param blogId 文章ID * @return 标签列表 */ List<Tag> listTagByBlogId(Integer blogId); /** * 根据标签ID统计文章数 前台 * @param tagId 标签ID * @return 文章数量 */ int countBlogByTagIdByHome(Integer tagId); } <file_sep>/src/main/java/com/islizx/entity/Type.java package com.islizx.entity; import lombok.Data; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * @author lizx * @date 2020-01-30 - 12:00 */ @Data public class Type implements Serializable { private static final long serialVersionUID = 5160366370329403551L; private Integer id; private String name; private String description; private String icon; private List<Blog> blogs = new ArrayList<>(); /** * 文章数量(不是数据库字段) */ private Integer blogCount; public Type(Integer id, String name, String description, String icon, Integer blogCount) { this.id = id; this.name = name; this.description = description; this.icon = icon; this.blogCount = blogCount; } public Type(Integer id, String name) { this.id = id; this.name = name; } public Type() { } } <file_sep>/src/main/java/com/islizx/service/LogService.java package com.islizx.service; import com.github.pagehelper.PageInfo; import com.islizx.entity.Log; import java.util.List; /** * @author lizx * @date 2020-02-21 - 14:36 */ public interface LogService { /** * 移除所有日志 */ void removeAllLog(); PageInfo<Log> getAll(Integer pageIndex, Integer pageSize); Integer delete(Integer id); Log insertOrUpdate(Log log); Log getById(Integer id); List<Log> findByBatchIds(List<Integer> ids); } <file_sep>/src/main/webapp/static/js/swiper.js const swiper = { _parent:null, _parentW:null, _imgArr:null, _callBack:null, _clickEvent:null, _config:null, _swiperContent:null, _swiperPoint:null, _arrowLeft:null, _arrowRight:null, _timerFn:null, _itemArr:[], _pointArr:[], _currentPage:0, _num:null, _time:3000, _movePos:0, _canMove:false, _startX:null, _endX:null, _prevLeft:null, _nextLeft:null, _touchItem:null, _autoPlay:true, _isMobile:false, _showPoint:true, _startTime:null, _endTime:null, _prevFlag:true, _nextFlag:true, init:function(parent,imgArr,config,clickEvent,callBack){ this._parent = parent; this._parentW = parent.width(); this._imgArr = imgArr; this._config = config; this._callBack = callBack; this._clickEvent = clickEvent; this._currentPage = 0; this._time = 3000; this._itemArr = []; this._pointArr = []; this._num = imgArr ? imgArr.length : 0; this._isMobile = (typeof this._config.ismobile === 'boolean') ? this._config.ismobile : this.isMobile(); this._autoPlay = (typeof this._config.autoplay === 'boolean') ? this._config.autoplay : true; this._showPoint = (typeof this._config.showpoint === 'boolean') ? this._config.showpoint : true; this._canMove = false; this.addEle(); }, /**判断是否是移动端 */ isMobile : function(){ let userAgentInfo = navigator.userAgent;//获取游览器请求的用户代理头的值 let Agents = ["Android", "iPhone","SymbianOS", "Windows Phone","iPad","iPod"];//定义移动设备数组 let isMobile = false; for (let v = 0; v < Agents.length; v++) { if (userAgentInfo.indexOf(Agents[v]) > 0) { isMobile = true; break; } } return isMobile; }, /**填充元素 */ addEle:function(){ if(this._num <= 0)return; this._swiperContent = this._parent.children(".swiper-content"); this._swiperPoint = this._parent.children(".swiper-point"); this._imgArr.map((item,index)=>{ let slidePictureUrl; let slideTitle; let slideUrl; let slideTarget; let targetType = ''; if(typeof item === 'object'){ slidePictureUrl = item.slidePictureUrl; slideTitle = item.slideTitle; slideUrl = item.slideUrl; slideTarget = item.slideTarget; }else{ slidePictureUrl = item; } if(slideTarget == '新窗口'){ targetType = '_blank'; } let swiperItem = $('<div class="swiper-item"><a href="' + slideUrl + '" target="' + targetType + '"><img src="' + slidePictureUrl + '"></a><a href="' + slideUrl + '" target="' + targetType + '" class="ui teal button" style="border-radius: unset;position: absolute;top: 0;left: 0">' + slideTitle + '</a></div>'); /*let swiperTitle = $('<p class="ui teal button" style="border-radius: unset;position: absolute;top: 0;left: 0">' + slideTitle + '</p>');*/ /*swiperTitle.appendTo(this._parent);*/ swiperItem.appendTo(this._swiperContent); /*if(typeof item === 'object'){ for (let key in item){ swiperItem.prop(key,item[key]); } }*/ this._itemArr.push(swiperItem); let pointItem = $(`<div class="swiper-circle"></div>`); pointItem.appendTo(this._swiperPoint); this._pointArr.push(pointItem); if(index == 0){ swiperItem.css('left', '0'); pointItem.addClass("current-point"); }else{ swiperItem.css('left', '100%'); pointItem.removeClass("current-point"); } }) this.arrow(); this.autoPlay(); this.addTouch(); this.showPoint(); this._callBack && this._callBack(this._itemArr); }, /**判断是都显示轮播点 */ showPoint:function(){ if(!this._showPoint){ this._parent.children('.swiper-point').hide(); } }, /**判断是否显示左右按钮 */ arrow:function(){ let that = this; if(this._config.arrowtype == 'move'){ this._parent.children('.arrow-left').hide(); this._parent.children('.arrow-right').hide(); this._parent.on('mouseenter', function(){ that._parent.children('.arrow-left').fadeIn(); }); this._parent.on('mouseleave', function(){ that._parent.children('.arrow-left').fadeOut(); }); this._parent.on('mouseenter', function(){ that._parent.children('.arrow-right').fadeIn(); }); this._parent.on('mouseleave', function(){ that._parent.children('.arrow-right').fadeOut(); }); }else if(this._config.arrowtype == 'none'){ this._parent.children('.arrow-left').hide(); this._parent.children('.arrow-right').hide(); } this.addArrowListener(); }, addArrowListener:function(){ let that = this; this._arrowRight = this._parent.children(".arrow-right"); this._arrowRight.click(function(){ that.next(); }) this._arrowLeft = this._parent.children(".arrow-left"); this._arrowLeft.click(function(){ that.prev(); }); }, /**判断是否自动轮播*/ autoPlay:function(){ if(this._autoPlay){ let that = this; this._time = this._config.time || 3000; this.createTimer(); this._parent.on('mouseover', function(){ clearInterval(that._timerFn); that._timerFn = null; }); this._parent.on('mouseout', function(){ that.createTimer(); }); } }, createTimer:function(){ let that = this; this._timerFn = setInterval(function(){ that.next(); }, this._time); }, /**转到下一个 */ next:function(){ if(this._num <= 1) return; this._itemArr[this._currentPage].animate({'left': "-100%"},300); this._pointArr[this._currentPage].removeClass("current-point"); this._currentPage ++; if(this._currentPage > this._num - 1) this._currentPage = 0; this._itemArr[this._currentPage].css('left', '100%').show().animate({'left':0},300); this._pointArr[this._currentPage].addClass("current-point"); this.addTouch(); }, /**转到上一个*/ prev:function(){ if(this._num <= 1) return; this._itemArr[this._currentPage].animate({'left': "100%"},300); this._pointArr[this._currentPage].removeClass("current-point"); this._currentPage --; if(this._currentPage < 0) this._currentPage = this._num -1; this._itemArr[this._currentPage].css('left', '-100%').show().animate({'left':0},300); this._pointArr[this._currentPage].addClass("current-point"); this.addTouch(); }, downFn:function(e){ e.preventDefault(); this._startTime = new Date().getTime(); this._movePos = 0; this._canMove = true; this._startX = this._isMobile ? e.originalEvent.targetTouches[0].pageX : e.pageX; this._itemArr[this._currentPage].css('left',"0"); if(this._num > 2){ if(this._currentPage == 0){ this._itemArr[this._num - 1].css('left',"-100%"); this._itemArr[this._currentPage +1].css('left',"100%"); this._prevLeft = this._itemArr[this._num - 1].position().left; this._nextLeft = this._itemArr[this._currentPage +1].position().left; }else if(this._currentPage == this._num - 1){ this._itemArr[this._currentPage - 1].css('left',"-100%"); this._itemArr[0].css('left',"100%"); this._prevLeft = this._itemArr[this._currentPage - 1].position().left; this._nextLeft = this._itemArr[0].position().left; }else{ this._itemArr[this._currentPage - 1].css('left',"-100%"); this._itemArr[this._currentPage +1].css('left',"100%"); this._prevLeft = this._itemArr[this._currentPage - 1].position().left; this._nextLeft = this._itemArr[this._currentPage +1].position().left; } } if(this._isMobile){ this._touchItem.on('touchmove',this.moveFn.bind(this)); $(document).on('touchend',this.upFn.bind(this)); }else{ this._touchItem.on('mousemove',this.moveFn.bind(this)); $(document).on('mouseup',this.upFn.bind(this)); } }, moveFn:function(e){ if(this._canMove){ if(this._isMobile && this._autoPlay && this._timerFn != null){ clearInterval(this._timerFn); this._timerFn = null; } this._endX = this._isMobile ? e.originalEvent.targetTouches[0].pageX : e.pageX; this._movePos = this._endX - this._startX; this._itemArr[this._currentPage].animate({'left':this._movePos},0); if(this._num > 2){ if(this._currentPage == 0){ this._itemArr[this._num - 1].animate({'left':this._prevLeft + this._movePos},0); this._itemArr[this._currentPage +1].animate({'left':this._nextLeft + this._movePos},0); }else if(this._currentPage == this._num - 1){ this._itemArr[this._currentPage - 1].animate({'left':this._prevLeft + this._movePos},0); this._itemArr[0].animate({'left':this._nextLeft + this._movePos},0); }else{ this._itemArr[this._currentPage - 1].animate({'left':this._prevLeft + this._movePos},0); this._itemArr[this._currentPage +1].animate({'left':this._nextLeft + this._movePos},0); } }else if(this._num == 2){ let index = this._currentPage == 0 ? 1 : 0; if(this._movePos > 0){ if(!this._nextFlag) this._nextFlag = true; if(this._prevFlag){ this._prevFlag = false; this._itemArr[index].css('left','-100%'); this._prevLeft = this._itemArr[index].position().left; } this._itemArr[index].animate({'left':this._prevLeft + this._movePos},0); }else{ if(!this._prevFlag) this._prevFlag = true; if(this._nextFlag){ this._nextFlag = false; this._itemArr[index].css('left','100%'); this._nextLeft = this._itemArr[index].position().left; } this._itemArr[index].animate({'left':this._nextLeft + this._movePos},0); } } } }, upFn(e){ if(!this._canMove) return; this._endTime = new Date().getTime(); if(this._endTime - this._startTime < 200){ this._clickEvent && this._clickEvent(this._touchItem); } if(this._isMobile){ this._touchItem.off('touchstart'); this._touchItem.off('touchmove'); $(document).off('touchend'); }else{ this._touchItem.off('mousedown'); this._touchItem.off('mousemove'); $(document).off('mouseup'); } if(this._isMobile && this._autoPlay && this._timerFn == null){ this.createTimer(); } if(this._canMove) this._canMove = false; if(this._num > 2){ if(Math.abs(this._movePos) > this._parentW / 3){ if(this._movePos > 0){ this._itemArr[this._currentPage].animate({'left':'100%'},300); if(this._currentPage == 0){ this._itemArr[this._num - 1].animate({'left':0},300); this._itemArr[this._currentPage +1].css('left','100%'); }else if(this._currentPage == this._num - 1){ this._itemArr[this._currentPage - 1].animate({'left':0},300); this._itemArr[0].css('left','100%'); }else{ this._itemArr[this._currentPage - 1].animate({'left':0},300); this._itemArr[this._currentPage +1].css('left','100%'); } this._pointArr[this._currentPage].removeClass("current-point"); this._currentPage --; if(this._currentPage < 0) this._currentPage = this._num -1; this._pointArr[this._currentPage].addClass("current-point"); }else{ this._itemArr[this._currentPage].animate({'left':'-100%'},300); if(this._currentPage == 0){ this._itemArr[this._num - 1].css('left','-100%'); this._itemArr[this._currentPage +1].animate({'left':0},300); }else if(this._currentPage == this._num - 1){ this._itemArr[this._currentPage - 1].css('left','-100%'); this._itemArr[0].animate({'left':0},300); }else{ this._itemArr[this._currentPage - 1].css('left','-100%'); this._itemArr[this._currentPage + 1].animate({'left':0},300); } this._pointArr[this._currentPage].removeClass("current-point"); this._currentPage ++; if(this._currentPage > this._num - 1) this._currentPage = 0; this._pointArr[this._currentPage].addClass("current-point"); } }else{ this._itemArr[this._currentPage].animate({'left':0},300); if(this._currentPage == 0){ this._itemArr[this._num - 1].animate({'left':'-100%'},300); this._itemArr[this._currentPage +1].animate({'left':'100%'},300); }else if(this._currentPage == this._num - 1){ this._itemArr[this._currentPage - 1].animate({'left':'-100%'},300); this._itemArr[0].animate({'left':'100%'},300); }else{ this._itemArr[this._currentPage - 1].animate({'left':'-100%'},300); this._itemArr[this._currentPage + 1].animate({'left':'100%'},300); } } }else if(this._num == 2){ let index = this._currentPage == 0 ? 1 : 0; if(Math.abs(this._movePos) > this._parentW / 3){ if(this._movePos > 0){ this._itemArr[this._currentPage].animate({'left':'100%'},300); }else{ this._itemArr[this._currentPage].animate({'left':'-100%'},300); } this._itemArr[index].animate({'left':0},300); this._pointArr[this._currentPage].removeClass("current-point"); this._pointArr[index].addClass("current-point"); this._currentPage = index; }else{ this._itemArr[this._currentPage].animate({'left':0},300); if(this._movePos > 0){ this._itemArr[index].animate({'left':'-100%'},300); }else{ this._itemArr[index].animate({'left':'100%'},300); } } }else if(this._num == 1){ this._itemArr[this._currentPage].animate({'left':0},300); } this.addTouch(); }, /** 添加触摸事件*/ addTouch:function(){ let cantouch = (typeof this._config.cantouch === 'boolean') ? this._config.cantouch : true; if(cantouch){ this._touchItem = this._itemArr[this._currentPage]; if(this._isMobile){ this._touchItem.on('touchstart',this.downFn.bind(this)); }else{ this._touchItem.on('mousedown',this.downFn.bind(this)); } } } } <file_sep>/src/main/java/com/islizx/mapper/TagMapper.java package com.islizx.mapper; import com.islizx.entity.Tag; import org.apache.ibatis.annotations.Mapper; import java.util.List; /** * @author lizx * @date 2020-01-31 - 19:20 */ @Mapper public interface TagMapper { /** * 根据ID删除 * * @param id 标签ID * @return 影响行数 */ int deleteById(Integer id); /** * 添加 * * @param tag 标签 * @return 影响行数 */ int insert(Tag tag); /** * 根据ID查询 * * @param id 标签ID * @return 标签 */ Tag getTagById(Integer id); /** * 更新 * @param tag 标签 * @return 影响行数 */ int update(Tag tag); /** * 获得标签总数 * * @return 数量 */ Integer countTag() ; /** * 获得标签列表 * * @return 列表 */ List<Tag> listTag(Integer limit) ; /** * 根据标签名获取标签 * * @param name 名称 * @return 标签 */ Tag getTagByName(String name) ; } <file_sep>/src/main/java/com/islizx/controller/admin/WidgetController.java package com.islizx.controller.admin; import com.islizx.config.annotation.SystemLog; import com.islizx.entity.Widget; import com.islizx.model.dto.Msg; import com.islizx.model.enums.LogTypeEnum; import com.islizx.model.enums.WidgetTypeEnum; import com.islizx.service.WidgetService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.List; /** * @author lizx * @date 2020-02-16 - 11:18 */ @Slf4j @Controller @RequestMapping(value = "/admin") public class WidgetController { @Autowired WidgetService widgetService; @Autowired RedisTemplate redisTemplate; /** * 渲染小工具设置页面 * * @return 模板路径/admin/admin_widget */ @RequestMapping(value = "/widgets", method = RequestMethod.GET) public String widgets(Model model) { //前台主要小工具 List<Widget> footerWidgets = widgetService.findWidgetByType(WidgetTypeEnum.FOOTER_WIDGET.getCode()); List<Widget> postDetailSidebarWidgets = widgetService.findWidgetByType(WidgetTypeEnum.POST_DETAIL_SIDEBAR_WIDGET.getCode()); model.addAttribute("footerWidgets", footerWidgets); model.addAttribute("postDetailSidebarWidgets", postDetailSidebarWidgets); model.addAttribute("widget", new Widget()); return "/admin/widget/widgets-input"; } /** * 新增/修改小工具 * * @param widget widget * @return 重定向到/admin/widget */ @RequestMapping(value = "/widgets/save", method = RequestMethod.POST) @SystemLog(description = "更新小工具", type = LogTypeEnum.OPERATION) public String saveWidget(@ModelAttribute Widget widget) { widgetService.insertOrUpdate(widget); redisTemplate.delete("footerWidgets"); return "redirect:/admin/widgets"; } /** * 跳转到修改页面 * * @param widgetId 小工具编号 * @param model model * @return 模板路径/admin/admin_widget */ @RequestMapping(value = "/widgets/edit/{id}", method = RequestMethod.GET) public String updateWidget(@PathVariable("id") Integer widgetId, Model model) { Widget widget = widgetService.get(widgetId); model.addAttribute("widget", widget); //前台主要小工具 List<Widget> postDetailSidebarWidgets = widgetService.findWidgetByType(WidgetTypeEnum.POST_DETAIL_SIDEBAR_WIDGET.getCode()); List<Widget> footerWidgets = widgetService.findWidgetByType(WidgetTypeEnum.FOOTER_WIDGET.getCode()); model.addAttribute("footerWidgets", footerWidgets); model.addAttribute("postDetailSidebarWidgets", postDetailSidebarWidgets); return "/admin/widget/widgets-input"; } /** * 删除小工具 * * @param widgetId 小工具编号 * @return 重定向到/admin/widget */ @RequestMapping(value = "/widgets/delete", method = RequestMethod.DELETE) @ResponseBody @SystemLog(description = "删除小工具", type = LogTypeEnum.OPERATION) public Msg removeWidget(@RequestParam("id") Integer widgetId) { widgetService.delete(widgetId); redisTemplate.delete("footerWidgets"); return Msg.success().add("msg", "小工具删除成功!"); } /** * 渲染小工具设置页面 * * @return 模板路径/admin/widgets */ @RequestMapping(value = "/widgets/widgetByJson", method = RequestMethod.POST) public String widgetByJson(Model model) { List<Widget> footerWidgets = widgetService.findWidgetByType(WidgetTypeEnum.FOOTER_WIDGET.getCode()); List<Widget> postDetailSidebarWidgets = widgetService.findWidgetByType(WidgetTypeEnum.POST_DETAIL_SIDEBAR_WIDGET.getCode()); model.addAttribute("footerWidgets", footerWidgets); model.addAttribute("postDetailSidebarWidgets", postDetailSidebarWidgets); model.addAttribute("widget", new Widget()); return "/admin/widget/widgets-input :: widgetList"; } } <file_sep>/src/main/java/com/islizx/exception/MyDispatcherServlet.java package com.islizx.exception; import org.springframework.stereotype.Component; import org.springframework.web.servlet.DispatcherServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author lizx * @date 2020-02-21 - 12:37 */ @Component public class MyDispatcherServlet extends DispatcherServlet { @Override protected void noHandlerFound(HttpServletRequest request, HttpServletResponse response) throws Exception { request.getRequestDispatcher("/error").forward(request, response); // response.sendRedirect(request.getContextPath().concat("/error/404.html")); } } <file_sep>/src/main/java/com/islizx/util/VerifyCodeUtil.java package com.islizx.util; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; /** * @author lizx * @date 2020-01-30 - 16:36 */ public class VerifyCodeUtil { private int width = 100; private int height = 40; private int result = 0; public int getResult() { return result; } public void setResult(int result) { this.result = result; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } private BufferedImage image = null;// 图像 private String rnds;// 验证码 /* * 取得图片的验证码 */ public String getRnds(){ return rnds; } /* * 取得验证码图片 */ public BufferedImage getImage(){ return this.image; } private VerifyCodeUtil(){ try { image = createImage(); } catch (IOException e) { System.out.println("验证码图片产生出现错误:" + e.toString()); } } /* * 取得ValidationCodeUtil实例 */ public static VerifyCodeUtil Instance(){ return new VerifyCodeUtil(); } private BufferedImage createImage() throws IOException{ BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); Graphics g = image.getGraphics(); createRandom(); drawBackground(g); drawRnds(g,rnds); g.dispose(); return image; } private void drawRnds(Graphics g, String rnds){ g.setColor(new Color(0xFFFFFF)); g.setFont(new Font(null,Font.ITALIC | Font.BOLD, 18)); g.drawString(rnds.charAt(0) + "", 1, width/4-1); g.drawString(rnds.charAt(1) + "", width/4+1, width /4+1); g.drawString(rnds.charAt(2) + "", width/2+1, width /4-1); g.drawString(rnds.charAt(3) + "", width*3/4+1, width /4+1); } /*背景*/ private void drawBackground(Graphics g){ g.setColor(new Color(0x00B5AD)); g.fillRect(0, 0, width, height); //噪点 for(int i = 0; i< 120;i++){ int x = (int)(Math.random() * width); int y = (int)(Math.random() * height); int red = (int)(Math.random() * 256); int green = (int)(Math.random() * 256); int blue = (int)(Math.random() * 256); g.setColor(new Color(red, green, blue)); g.drawOval(x, y, 1, 1); } } /*数字验证码*/ private void createRandom(){ String str = "0123456789"; String str1 = "+-*"; String str2 = "="; char[] rndChars = new char[4]; Random random = new Random(); rndChars[0] = str.charAt(random.nextInt(str.length())); rndChars[1] = str1.charAt(random.nextInt(str1.length())); rndChars[2] = str.charAt(random.nextInt(str.length())); rndChars[3] = str2.charAt(random.nextInt(str2.length())); Character strNumber1 = rndChars[0]; Character strNumber2 = rndChars[2]; Character strIcon = rndChars[1]; int number1 = Integer.parseInt(strNumber1.toString()); int number2 = Integer.parseInt(strNumber2.toString()); if((strIcon.toString()).equals("+")){ result = number1 + number2; }else if((strIcon.toString()).equals("-")){ result = number1 - number2; }else if((strIcon.toString()).equals("*")){ result = number1 * number2; }else{ System.out.println("验证码结果输出错误!"); } rnds = new String(rndChars); } } <file_sep>/src/main/java/com/islizx/model/enums/BlogStatusEnum.java package com.islizx.model.enums; /** * @author lizx * @date 2020-02-06 - 22:00 */ public enum BlogStatusEnum { /** * 已发布 */ PUBLISHED(0), /** * 草稿 */ DRAFT(1), /** * 回收站 */ TRASH(2); private Integer code; BlogStatusEnum(Integer code) { this.code = code; } public Integer getCode() { return code; } } <file_sep>/src/main/java/com/islizx/entity/Log.java package com.islizx.entity; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * @author lizx * @date 2020-02-21 - 14:34 */ @Data public class Log implements Serializable { private static final long serialVersionUID = -7506956161988702794L; private Integer id; /** * 方法操作名称 */ private String name; /** * 日志类型 */ private String logType; /** * 请求路径 */ private String requestUrl; /** * 请求类型 */ private String requestType; /** * 请求参数 */ private String requestParam; /** * 请求用户 */ private String username; /** * ip */ private String ip; /** * ip信息 */ private String ipInfo; /** * 花费时间 */ private Integer costTime; /** * 创建时间 */ private Date createTime; } <file_sep>/src/main/java/com/islizx/interceptor/SecurityInterceptor.java package com.islizx.interceptor; import com.islizx.entity.User; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author lizx * @date 2020-01-31 - 11:06 */ public class SecurityInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception { //这里可以根据session的用户来判断角色的权限,根据权限来转发不同的页面 System.out.println("SecurityInterceptor执行==============="); User loginUser = (User) request.getSession().getAttribute("user"); if(loginUser == null) { request.getSession().setAttribute("msg", "请先进行登录操作!"); response.sendRedirect(request.getContextPath() + "/login"); return false; }else if(loginUser.getStatus()){ request.getSession().setAttribute("msg", "该账号已被冻结,请联系管理员!"); response.sendRedirect(request.getContextPath() + "/login"); return false; } return true; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } } <file_sep>/src/main/java/com/islizx/entity/Slide.java package com.islizx.entity; import lombok.Data; import java.io.Serializable; /** * @author lizx * @date 2020-02-15 - 23:30 */ @Data public class Slide implements Serializable { private static final long serialVersionUID = 290839163059169156L; private Integer id; /** * 幻灯片名称 */ private String slideTitle; /** * 幻灯片链接 */ private String slideUrl; /** * 幻灯片图片地址 */ private String slidePictureUrl; /** * 排序编号 */ private Integer slideSort = 1; /** * 打开方式 */ private String slideTarget; } <file_sep>/README.md # islizxBlog 基于SpringMVC+Spring+MyBatis开发的个人博客网站,使用IDEA工具开发,毕业设计 ## 一、关于项目 1. 该博客是基于SSM实现的个人博客系统,适合初学SSM和个人博客制作的同学学习。主要技术架构包括Maven、SpringMVC、Spring、MyBatis、Thymeleaf、Redis等。前端采用Bootstarp和Semantic UI。 ## 二、使用步骤 1. Fork项目 fork或者下载项目到本地(建议先fork到自己仓库,在通过码云导入仓库下载,实测下载速度可以)。完整项目源码,可以使用IDEA导入。数据库文件请先创建数据库,然后以运行sql文件方式导入 2. 导入数据库 新建数据库**blog**,导入数据库blog.sql。注意,数据库的编码和排序规则是utf-8和utf-8_general_ci。数据库默认用户名 root,密码 <PASSWORD> 3. 启动redis服务,并在redis.properties配置你的redis 4. 修改项目中的数据库连接信息 修改 db.properties 文件,该文件很容易找到,在 src/main/resources 中。里面有 MySQL 数据库连接信息,请确保已安装和启动 MySQL。注意修改数据库地址、表名、用户名和密码。 5. db.properties 文件中databasePath表示每周日进行数据库备份的路径,可自行修改 6. 后台sql文件中管理员账户为admin,密码为:<PASSWORD> ## 三、使用注意 1. 开发工具的选择 请使用 IntelliJ IDEA, 尽量不要用 Eclipse/MyEclipse。后者可能要折腾一会儿 2. 确保你安装了 Maven(如果maven加载pom报错,发现不是自己配置的maven,请到setting中修改成自己的maven仓库) 3. 本项目有使用到redis,所以运行项目前先启动redis服务,并在redis.properties配置你的redis 4. 请给你的IDE安装Lombok插件 实体类中多次使用到 @Data 注解,请确保你的 IDE 安装了 Lombok 插件,否则找不到 getter/setter 方法 5. 数据库乱码,在MySQL安装路径,比如(E:\MySQL\MySQL Server 5.5)下找到my.ini文件进入编辑,修改这两处地方为utf8,默认是拉丁文 ```xml character-set-server=utf8 default-character-set=utf8 ``` 6. 本项目使用到的mail服务可在mail.properties中配置,不配置的话不影响整体,只是使用不了邮件服务。 7. 本项目原本使用的是阿里云oss服务,现已修改成图片上传到本地服务器,如果需要可以在db.properties中进行阿里云配置 ## 二、效果预览 1. 预览地址:https://islizx.cn 2. 前台效果图就不展示了,可前往网站浏览 3. 介绍几张后台的页面 1. 后台首页 DashBoard ![](https://islizx.oss-cn-hangzhou.aliyuncs.com/images/2020/5/20200508_152653_627.png) 2. 文章列表 ![](https://islizx.oss-cn-hangzhou.aliyuncs.com/images/2020/5/20200508_153043_486.png) 3. 编辑文章(MarkDown编辑器) ![](https://islizx.oss-cn-hangzhou.aliyuncs.com/images/2020/5/20200508_153149_326.png) 4. 文章类型管理 ![](https://islizx.oss-cn-hangzhou.aliyuncs.com/images/2020/5/20200508_153226_333.png) 5. 页面管理(可以自定义页面,申请友链和留言板即为自定义页面) ![](https://islizx.oss-cn-hangzhou.aliyuncs.com/images/2020/5/20200508_153303_554.png) ![](https://islizx.oss-cn-hangzhou.aliyuncs.com/images/2020/5/20200508_153303_580.png) 6. 公告管理 ![](https://islizx.oss-cn-hangzhou.aliyuncs.com/images/2020/5/20200508_153345_67.png) 7. 附件管理(点击附件可以查看详细信息以及删除操作) ![](https://islizx.oss-cn-hangzhou.aliyuncs.com/images/2020/5/20200508_153429_108.png) ![](https://islizx.oss-cn-hangzhou.aliyuncs.com/images/2020/5/20200508_153517_792.png) 8. 评论管理(管理员回复回收站和待审核的评论后直接通过审核并发送邮件给评论者) ![](https://islizx.oss-cn-hangzhou.aliyuncs.com/images/2020/5/20200508_153604_8.png) 9. 轮播图管理(即首页的轮播图,轮播图可另外链接到其它页面,比如文章或公告) ![](https://islizx.oss-cn-hangzhou.aliyuncs.com/images/2020/5/20200508_153633_214.png) 10. 小工具管理(即首页右侧的bar) ![](https://islizx.oss-cn-hangzhou.aliyuncs.com/images/2020/5/20200508_153656_373.png) 11. 友链管理 ![](https://islizx.oss-cn-hangzhou.aliyuncs.com/images/2020/5/20200508_153720_571.png) 12. 日志管理 ![]( https://islizx.oss-cn-hangzhou.aliyuncs.com/images/2020/5/20200508_153744_66.png) ## 五、下载地址 ​ GitHub地址:https://github.com/isLizx/islizxBlog (如果可以帮忙点一次Star和Fork) <file_sep>/src/main/java/com/islizx/mapper/TypeMapper.java package com.islizx.mapper; import com.islizx.entity.Attachment; import com.islizx.entity.Type; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.HashMap; import java.util.List; /** * @author lizx * @date 2020-02-01 - 12:58 */ @Mapper public interface TypeMapper { /** * 添加 * * @param type 分类 * @return 影响行数 */ int insert(Type type); /** * 更新 * * @param type 分类 * @return 影响行数 */ int update(Type type); /** * 根据分类id获得分类信息 * * @param id ID * @return 分类 */ Type getTypeById(Integer id); /** * 删除分类 * * @param id 分类ID */ int deleteType(Integer id); /** * 查询分类总数 * * @return 数量 */ Integer countType(); /** * 获得分类列表 * * @return 列表 */ List<Type> listType(); /** * 根据标签名获取标签 * * @param name 名称 * @return 分类 */ Type getTypeByName(String name); /** * 获取该分类下所有文章总数 * @param id * @return */ Integer getBlogCountWithTypeId(Integer id); /** * 获取该分类下所有文章总数 其那台 * @param id * @return */ Integer getBlogCountWithTypeIdAtHome(Integer id); } <file_sep>/src/test/java/test.java import io.github.biezhi.ome.OhMyEmail; import io.github.biezhi.ome.SendMailException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.text.SimpleDateFormat; import java.util.Date; /** * @author lizx * @date 2020-02-07 - 22:48 */ public class test { // 该邮箱修改为你需要测试的邮箱地址 private static final String TO_EMAIL = "<EMAIL>"; //@Before public void before() { // 配置,一次即可 OhMyEmail.config(OhMyEmail.SMTP_QQ(false), "2967007822<EMAIL>", "osognegihhwfdgde"); } @Test public void testSendText() throws SendMailException { OhMyEmail.subject("这是一封测试TEXT邮件") .from("小姐姐的邮箱") .to(TO_EMAIL) .text("信件内容") .send(); Assert.assertTrue(true); } @Test public void test1(){ String objectName = "https://islizx.oss-cn-hangzhou.aliyuncs.com/images/2020/3/20200312_131644_983.jpg"; Integer urlPrefixLength = "https://islizx.oss-cn-hangzhou.aliyuncs.com".length(); objectName = objectName.substring(urlPrefixLength+1, objectName.length()); System.out.println(objectName); } } <file_sep>/src/main/java/com/islizx/controller/home/HomeCommentController.java package com.islizx.controller.home; import cn.hutool.extra.servlet.ServletUtil; import cn.hutool.http.HtmlUtil; import com.github.pagehelper.PageInfo; import com.islizx.entity.Blog; import com.islizx.entity.Comment; import com.islizx.entity.User; import com.islizx.model.dto.LizxConst; import com.islizx.model.enums.*; import com.islizx.service.BlogService; import com.islizx.service.CommentService; import com.islizx.service.MailService; import com.islizx.service.UserService; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * @author lizx * @date 2020-02-18 - 16:19 */ @Controller @RequestMapping("/comments") public class HomeCommentController { @Autowired private CommentService commentService; @Autowired private UserService userService; @Autowired private MailService mailService; @Value("/images/otherUserAvatar.jpg") private String avatar; @Autowired private BlogService blogService; @RequestMapping(value = "/{blogId}", method = RequestMethod.GET) public String comments(@PathVariable Integer blogId, Model model, HttpSession session, @RequestParam(value = "size", defaultValue = "10") Integer pageSize, @RequestParam(value = "page", defaultValue = "1") Integer pageIndex) { PageInfo pageInfo = commentService.getListCommentByBlogId(BlogStatusEnum.PUBLISHED.getCode(),CommentStatusEnum.PUBLISHED.getCode(),null, pageIndex, pageSize,blogId); model.addAttribute("pageInfo", pageInfo); Blog blog = blogService.getBlogByPublishedAndId(BlogStatusEnum.PUBLISHED.getCode(),null, blogId); model.addAttribute("blog", blog); String msg = (String) session.getAttribute("msg"); if (msg != null && !msg.equals("")) { model.addAttribute("msg", msg); session.removeAttribute("msg"); } return "home/blog :: commentDiv"; } @RequestMapping(method = RequestMethod.POST) public String post(Comment comment, HttpSession session, HttpServletRequest request, Model model,@RequestParam(value = "verifyCode")String verifyCode) { if(verifyCode==null || verifyCode.equals("")){ session.setAttribute("msg", "请输入验证码"); return "redirect:/comments/" + comment.getBlogId(); } else if(!verifyCode.equals(request.getSession().getAttribute("verifyCode"))){ session.setAttribute("msg", "验证码错误"); return "redirect:/comments/" + comment.getBlogId(); } boolean isAdminToAdmin = true; //1.判断字数,应该小于1000字 if (comment != null && comment.getContent() != null && comment.getContent().length() > 1000) { session.setAttribute("msg", "评论字数太长,请删减或者分条发送!"); return "redirect:/comments/" + comment.getBlogId(); } //2.检查文章是否存在 Comment lastComment = null; Blog blog = blogService.getBlogByPublishedAndId(BlogStatusEnum.PUBLISHED.getCode(),null, comment.getBlogId()); if (blog == null) { session.setAttribute("msg", "文章不存在!"); return "redirect:/comments/" + comment.getBlogId(); } //3.判断是评论还是回复 //回复评论 if (comment.getParentCommentId() > 0) { lastComment = commentService.getById(BlogStatusEnum.PUBLISHED.getCode(), CommentStatusEnum.PUBLISHED.getCode(),null, comment.getParentCommentId()); if (lastComment == null) { session.setAttribute("msg", "回复的评论不存在!"); return "redirect:/comments/" + comment.getBlogId(); } } //将评论内容的字符专为安全字符 comment.setContent(HtmlUtil.escape(comment.getContent())); //4.判断是否登录 //如果已登录 User loginUser = (User) session.getAttribute("user"); if (loginUser != null) { comment.setAvatar(loginUser.getAvatar()); comment.setAdminComment(true); comment.setEmail(loginUser.getEmail()); comment.setNickname(loginUser.getNickname()); isAdminToAdmin = false; } //匿名评论 else { comment.setEmail(HtmlUtil.escape(comment.getEmail()).toLowerCase()); comment.setNickname(HtmlUtil.escape(comment.getNickname())); comment.setAdminComment(false); comment.setAvatar(avatar); } //5.保存分类信息 if (comment.isAdminComment()) { comment.setPass(CommentStatusEnum.PUBLISHED.getCode()); } else { comment.setPass(CommentStatusEnum.CHECKING.getCode()); } String ip = ServletUtil.getClientIP(request); comment.setIp(ip); commentService.insertComment(comment); if(comment.isAdminComment()){ session.setAttribute("msg", "评论成功."); }else{ session.setAttribute("msg", "你的评论已经提交,待管理员审核之后可显示."); } blog.setUser(userService.getUserById(blog.getUserId())); if(isAdminToAdmin){ // 通知管理员有新的回复,如果是管理员评论,则不发邮件 new EmailToAdmin(comment, lastComment, blog).start(); } return "redirect:/comments/" + comment.getBlogId(); } /** * 发送邮件通知管理员 */ class EmailToAdmin extends Thread { private Comment comment; private Comment lastComment; private Blog blog; private EmailToAdmin(Comment comment, Comment lastComment, Blog blog) { this.comment = comment; this.lastComment = lastComment; this.blog = blog; } @Override public void run() { //发送通知给管理员 if (StringUtils.equals(LizxConst.OPTIONS.get(BlogPropertiesEnum.SMTP_EMAIL_ENABLE.getProp()), TrueFalseEnum.TRUE.getValue()) && StringUtils.equals(LizxConst.OPTIONS.get(BlogPropertiesEnum.NEW_COMMENT_NOTICE.getProp()), TrueFalseEnum.TRUE.getValue())) { Map<String, Object> map = new HashMap<>(8); if (blog.getPostType()==PostTypeEnum.POST_TYPE_POST.getCode()) { map.put("pageUrl", LizxConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp()) + "/article/" + blog.getId() + ".html"); } else if (blog.getPostType()==PostTypeEnum.POST_TYPE_NOTICE.getCode()) { map.put("pageUrl", LizxConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp()) + "/notice/" + blog.getId()); } else { map.put("pageUrl", LizxConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp()) + "/p/" + blog.getUrl()); } // 页面名 map.put("pageTitle", LizxConst.OPTIONS.get(BlogPropertiesEnum.BLOG_TITLE.getProp()) + " (新评论通知)"); // 本站网址 map.put("webUrl", LizxConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp())); // 本站名 map.put("webTitle", LizxConst.OPTIONS.get(BlogPropertiesEnum.BLOG_TITLE.getProp())); // 新评论 map.put("comment", comment); // 旧评论 map.put("lastComment", lastComment); // 被评文章 map.put("blog", blog); mailService.sendTemplateMail( blog.getUser().getEmail(), LizxConst.OPTIONS.get(BlogPropertiesEnum.BLOG_TITLE.getProp()) + "(新评论通知)", map, "common/mail_template/mail_new.html"); } } } } <file_sep>/src/main/java/com/islizx/entity/Widget.java package com.islizx.entity; import lombok.Data; import java.io.Serializable; /** * @author lizx * @date 2020-02-16 - 11:01 */ @Data public class Widget implements Serializable { private static final long serialVersionUID = -3390800332821558875L; private Integer id; /** * 小工具标题 */ private String widgetTitle; /** * 小工具内容 */ private String widgetContent; /** * 是否显示(1是,0否) */ private Integer isDisplay = 1; /** * 位置 */ private Integer widgetType; } <file_sep>/src/main/java/com/islizx/service/impl/SlideServiceImpl.java package com.islizx.service.impl; import com.islizx.entity.Slide; import com.islizx.mapper.SlideMapper; import com.islizx.service.SlideService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @author lizx * @date 2020-02-15 - 23:38 */ @Service public class SlideServiceImpl implements SlideService { @Autowired(required = false) SlideMapper slideMapper; @Override public List<Slide> findAll() { return slideMapper.findAll(); } @Override public Slide insertOrUpdate(Slide slide) { if(slide.getId() == null || slide.getId() == 0){ slideMapper.insert(slide); }else{ slideMapper.update(slide); } return slide; } @Override public Slide get(Integer id) { return slideMapper.getSlideById(id); } @Override public Integer delete(Integer id) { return slideMapper.deleteSlide(id); } } <file_sep>/src/main/java/com/islizx/entity/Page.java package com.islizx.entity; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * @author lizx * @date 2020-01-30 - 12:23 */ @Data public class Page implements Serializable { private static final long serialVersionUID = -5448031440554277281L; private Integer id; private String key; private String title; private String content; private Date createTime; private Date updateTime; private Integer viewCount; private Integer commentCount; private Integer status; } <file_sep>/src/main/java/com/islizx/controller/admin/CommentController.java package com.islizx.controller.admin; import cn.hutool.core.lang.Validator; import cn.hutool.extra.servlet.ServletUtil; import com.github.pagehelper.PageInfo; import com.islizx.config.annotation.SystemLog; import com.islizx.entity.*; import com.islizx.model.dto.LizxConst; import com.islizx.model.dto.Msg; import com.islizx.model.enums.*; import com.islizx.service.BlogService; import com.islizx.service.CommentService; import com.islizx.service.MailService; import com.islizx.vo.CommentQuery; import com.sun.org.apache.xpath.internal.operations.Bool; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.util.*; /** * @author lizx * @date 2020-02-14 - 15:26 */ @Controller @Slf4j @RequestMapping("/admin") public class CommentController { @Autowired private CommentService commentService; @Autowired private BlogService blogService; @Autowired private MailService mailService; /** * 评论人相关信息 */ public static final String COMMENT_AUTHOR_IP = "ip"; public static final String COMMENT_AUTHOR = "nickname"; public static final String COMMENT_EMAIL = "email"; public static final String COMMENT_CONTENT = "content"; @RequestMapping("/comments/getpublishedsize") @ResponseBody public Msg getpublishedsize() { // 三种评论类型个数 Integer publish = commentService.countCommentByPass(CommentStatusEnum.PUBLISHED.getCode()); Integer draft = commentService.countCommentByPass(CommentStatusEnum.CHECKING.getCode()); Integer trash = commentService.countCommentByPass(CommentStatusEnum.RECYCLE.getCode()); return Msg.success().add("publish", publish).add("draft", draft).add("trash", trash); } /** * 后台评论列表显示 * * @return modelAndView */ @RequestMapping(value = "/comments", method = RequestMethod.GET) public String index(@RequestParam(required = false, defaultValue = "1") Integer pageIndex, @RequestParam(required = false, defaultValue = "15") Integer pageSize, @RequestParam(required = false, defaultValue = "1") Integer pass, HttpSession session, Model model) { // 三种文章类型个数 Integer publish = commentService.countCommentByPass(CommentStatusEnum.PUBLISHED.getCode()); Integer draft = commentService.countCommentByPass(CommentStatusEnum.CHECKING.getCode()); Integer trash = commentService.countCommentByPass(CommentStatusEnum.RECYCLE.getCode()); HashMap<String, Object> criteria = new HashMap<>(1); criteria.put("pass", pass); PageInfo<Comment> commentPageInfo = commentService.pageComment(pageIndex, pageSize, criteria); model.addAttribute("pageInfo", commentPageInfo); model.addAttribute("publish", publish); model.addAttribute("draft", draft); model.addAttribute("trash", trash); model.addAttribute("pass", pass); String msg = (String) session.getAttribute("msg"); if (msg != null && !msg.equals("")) { model.addAttribute("msg", msg); session.removeAttribute("msg"); } return "admin/comment/comments"; } /** * 分页条件查询 * * @param pageIndex 页数 * @param pageSize * @param commentQuery * @param model * @return */ @RequestMapping("/comments/search") public String search(@RequestParam(required = false, defaultValue = "1") Integer pageIndex, @RequestParam(required = false, defaultValue = "15") Integer pageSize, CommentQuery commentQuery, Model model) { HashMap<String, Object> criteria = new HashMap<>(); String keywords = commentQuery.getKeywords(); Integer pass = commentQuery.getPass(); String sort = commentQuery.getSort(); String order = commentQuery.getOrder(); String searchType = commentQuery.getSearchType(); if (!StringUtils.isBlank(keywords)) { if (COMMENT_CONTENT.equals(searchType)) { criteria.put("content", keywords); } else if (COMMENT_AUTHOR.equals(searchType)) { criteria.put("nickname", keywords); } else if (COMMENT_EMAIL.equals(searchType)) { criteria.put("email", keywords); } else if (COMMENT_AUTHOR_IP.equals(searchType)) { criteria.put("ip", keywords); } } if (pass != null) { criteria.put("pass", pass); } else { criteria.put("pass", 1); } if (sort != null && !StringUtils.isBlank(sort)) criteria.put("sort", sort); if (order != null && !StringUtils.isBlank(order)) criteria.put("order", order); PageInfo<Comment> commentPageInfo = commentService.pageComment(pageIndex, pageSize, criteria); model.addAttribute("pageInfo", commentPageInfo); return "admin/comment/comments :: commentList"; } /** * 将评论改变为发布状态 * 评论状态有两种:待审核1,回收站2 * 对待审核转发布的,发邮件 * * @param commentId 评论编号 * @return 重定向到/admin/comment */ @ResponseBody @RequestMapping(value = "/comments/revert", method = RequestMethod.PUT) @SystemLog(description = "回滚评论", type = LogTypeEnum.OPERATION) public Msg moveToPublish(@RequestParam("id") Integer commentId, HttpSession session) { User loginUser = (User) session.getAttribute("user"); //评论 Comment comment = commentService.getById(null,null,null,commentId); Blog blog = blogService.getBlogByPublishedAndId(null, null,comment.getBlogId()); Comment result = commentService.updateCommentPass(commentId, CommentStatusEnum.PUBLISHED.getCode()); // 判断是不是子评论,如果是,也对被回复人发邮件 if(result.getParentCommentId() != null && result.getParentCommentId() > 0){ //被回复的评论 Comment lastComment = commentService.getById(null,null, null,comment.getParentCommentId()); //邮件通知 new EmailToAuthor(result, lastComment, blog).start(); } //判断是否启用邮件服务 new NoticeToAuthor(result, blog, result.getPass()).start(); return Msg.success().add("msg", "评论已发布!"); } /** * 删除评论 * * @param commentId commentId * @return string 重定向到/admin/comment */ @RequestMapping(value = "/comments/delete", method = RequestMethod.DELETE) @ResponseBody @SystemLog(description = "删除评论", type = LogTypeEnum.OPERATION) public Msg moveToAway(@RequestParam("id") Integer commentId) { //评论 Comment comment = commentService.getById(null,null, null, commentId); if (Objects.equals(comment.getPass(), CommentStatusEnum.RECYCLE.getCode())) { commentService.deleteComment(commentId); return Msg.success().add("msg", "评论已彻底删除"); } else { commentService.updateCommentPass(commentId, CommentStatusEnum.RECYCLE.getCode()); return Msg.success().add("msg", "评论仍入回收站"); } } /** * 管理员回复评论,并通过评论 * * @param commentId 被回复的评论 * @param commentContent 回复的内容 * @return 重定向到/admin/comment */ @RequestMapping(value = "/comments/reply") @ResponseBody @SystemLog(description = "回复评论", type = LogTypeEnum.OPERATION) public Msg replyComment(@RequestParam("id") Integer commentId, @RequestParam("commentContent") String commentContent, HttpServletRequest request, HttpSession session) { //博主信息 User loginUser = (User) session.getAttribute("user"); //被回复的评论 Comment lastComment = commentService.getById(null,null, null,commentId); if (lastComment == null) { return Msg.fail().add("msg", "回复失败,评论不存在"); } Blog blog = blogService.getBlogByPublishedAndId(null, null, lastComment.getBlogId()); if (blog == null) { return Msg.fail().add("msg", "回复失败,文章不存在"); } //修改被回复的评论的状态 if (Objects.equals(lastComment.getPass(), CommentStatusEnum.CHECKING.getCode())) { /*lastComment.setPass(CommentStatusEnum.PUBLISHED.getCode()); commentService.insertOrUpdate(lastComment);*/ commentService.updateCommentPass(lastComment.getId(), CommentStatusEnum.PUBLISHED.getCode()); } //保存评论 Comment comment = new Comment(); comment.setBlogId(lastComment.getBlogId()); comment.setNickname(loginUser.getNickname()); comment.setEmail(loginUser.getEmail()); comment.setIp(ServletUtil.getClientIP(request)); comment.setAvatar(loginUser.getAvatar()); comment.setContent(commentContent); comment.setParentCommentId(commentId); comment.setPass(CommentStatusEnum.PUBLISHED.getCode()); comment.setAdminComment(true); comment.setCreateTime(new Date()); commentService.insertComment(comment); //邮件通知 new EmailToAuthor(comment, lastComment, blog).start(); return Msg.success().add("msg", "回复成功!"); } /** * 批量删除 * * @param del_idstr 评论ID列表 * @return */ @RequestMapping(value = "/comments/batchDelete") @ResponseBody @SystemLog(description = "批量删除评论", type = LogTypeEnum.OPERATION) public Msg batchDelete(@RequestParam("del_idstr") String del_idstr) { List<Integer> ids = new ArrayList<>(); if(del_idstr.contains("-")){ String[] str_ids = del_idstr.split("-"); for(String string:str_ids){ ids.add(Integer.parseInt(string)); } }else{ // 单个删除 Integer id = Integer.parseInt(del_idstr); ids.add(id); } //Integer loginUserId = ((User)session.getAttribute("user")).getId(); //批量操作 //1、防止恶意操作 if (ids == null || ids.size() == 0 || ids.size() >= 100) { return Msg.fail().add("msg", "参数不合法!"); } //2、检查用户权限 //文章作者才可以删除 List<Comment> commentList = commentService.findByBatchIds(ids); /*for (Comment comment : commentList) { if (!Objects.equals(comment.getUserId(), loginUserId) && !Objects.equals(comment.getAcceptUserId(), loginUserId)) { return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.common.permission-denied")); } }*/ //3、如果当前状态为回收站,则删除;否则,移到回收站 for (Comment comment : commentList) { if (Objects.equals(comment.getPass(), CommentStatusEnum.RECYCLE.getCode())) { commentService.deleteComment(comment.getId()); } else { commentService.updateCommentPass(comment.getId(), CommentStatusEnum.RECYCLE.getCode()); } } return Msg.success().add("msg", "删除成功!"); } /** * 异步发送邮件回复给评论者 */ class EmailToAuthor extends Thread { private Comment comment; private Comment lastComment; private Blog blog; private EmailToAuthor(Comment comment, Comment lastComment, Blog blog) { this.comment = comment; this.lastComment = lastComment; this.blog = blog; } @Override public void run() { if (StringUtils.equals(LizxConst.OPTIONS.get(BlogPropertiesEnum.SMTP_EMAIL_ENABLE.getProp()), TrueFalseEnum.TRUE.getValue()) && StringUtils.equals(LizxConst.OPTIONS.get(BlogPropertiesEnum.COMMENT_REPLY_NOTICE.getProp()), TrueFalseEnum.TRUE.getValue())) { if (Validator.isEmail(lastComment.getEmail())) { Map<String, Object> map = new HashMap<>(8); if (blog.getPostType()==PostTypeEnum.POST_TYPE_POST.getCode()) { map.put("pageUrl", LizxConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp()) + "/article/" + blog.getId() + ".html"); } else if (blog.getPostType()==PostTypeEnum.POST_TYPE_NOTICE.getCode()) { map.put("pageUrl", LizxConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp()) + "/notice/" + blog.getId()); } else { map.put("pageUrl", LizxConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp()) + "/p/" + blog.getUrl()); } map.put("comment", comment); map.put("lastComment", lastComment); map.put("blog", blog); // 页面名 map.put("pageTitle", LizxConst.OPTIONS.get(BlogPropertiesEnum.BLOG_TITLE.getProp()) + " (评论回复通知)"); map.put("webUrl", LizxConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp())); // 本站名 map.put("webTitle", LizxConst.OPTIONS.get(BlogPropertiesEnum.BLOG_TITLE.getProp())); mailService.sendTemplateMail( lastComment.getEmail(), LizxConst.OPTIONS.get(BlogPropertiesEnum.BLOG_TITLE.getProp()) + "(评论回复通知)", map, "common/mail_template/mail_reply.html"); } } } } /** * 异步通知评论者审核通过 */ class NoticeToAuthor extends Thread { private Comment comment; private Blog blog; private Integer status; private NoticeToAuthor(Comment comment, Blog blog, Integer status) { this.comment = comment; this.blog = blog; this.status = status; } @Override public void run() { if (StringUtils.equals(LizxConst.OPTIONS.get(BlogPropertiesEnum.SMTP_EMAIL_ENABLE.getProp()), TrueFalseEnum.TRUE.getValue()) && StringUtils.equals(LizxConst.OPTIONS.get(BlogPropertiesEnum.COMMENT_REPLY_NOTICE.getProp()), TrueFalseEnum.TRUE.getValue())) { try { //待审核的评论变成已通过,发邮件 if (status == 1 && Validator.isEmail(comment.getEmail())) { Map<String, Object> map = new HashMap<>(6); if (blog.getPostType()==PostTypeEnum.POST_TYPE_POST.getCode()) { map.put("pageUrl", LizxConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp()) + "/article/" + blog.getId() + ".html"); } else if (blog.getPostType()==PostTypeEnum.POST_TYPE_NOTICE.getCode()) { map.put("pageUrl", LizxConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp()) + "/notice/" + blog.getId()); } else { map.put("pageUrl", LizxConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp()) + "/p/" + blog.getUrl()); } map.put("comment", comment); map.put("blog", blog); // 页面名 map.put("pageTitle", LizxConst.OPTIONS.get(BlogPropertiesEnum.BLOG_TITLE.getProp()) + " (评论审核通知)"); // 本站网址 map.put("webUrl", LizxConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp())); // 本站名 map.put("webTitle", LizxConst.OPTIONS.get(BlogPropertiesEnum.BLOG_TITLE.getProp())); mailService.sendTemplateMail( comment.getEmail(), LizxConst.OPTIONS.get(BlogPropertiesEnum.BLOG_TITLE.getProp()) + " (评论审核通知)", map, "common/mail_template/mail_passed.html"); } } catch (Exception e) { e.printStackTrace(); } } } } } <file_sep>/src/main/java/com/islizx/util/OssUtil.java package com.islizx.util; import cn.hutool.core.date.DateTime; import com.aliyun.oss.OSSClient; import com.aliyun.oss.model.*; import com.islizx.model.dto.FileUploadResult; import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import java.io.*; import java.util.List; /** * @author lizx * @date 2020-03-11 - 22:13 */ @Component public class OssUtil { private static String ENDPOINT = null; private static String ACCESSKEYID = null; private static String ACCESSKEYSECRET = null; private static String BUCKETNAME = null; private static String URLPREFIX = null; private OSSClient client = null; private ObjectMetadata meta = null; // 允许上传的格式 private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".gif", ".png"}; static{ try { ENDPOINT = ConfigManager.getProperty("aliyun.endpoint"); ACCESSKEYID = ConfigManager.getProperty("aliyun.accessKeyId"); ACCESSKEYSECRET = ConfigManager.getProperty("aliyun.accessKeySecret"); BUCKETNAME = ConfigManager.getProperty("aliyun.bucketName"); URLPREFIX = ConfigManager.getProperty("aliyun.urlPrefix"); } catch (java.lang.Exception e) { e.printStackTrace(); } } public void init(){ // 初始化一个OSSClient client = new OSSClient(ENDPOINT,ACCESSKEYID, ACCESSKEYSECRET); meta = new ObjectMetadata(); } /** * 文件上传 * @param uploadFile * @return */ public FileUploadResult upload(MultipartFile uploadFile) { init(); // 校验图片格式 boolean isLegal = false; for (String type : IMAGE_TYPE) { if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(), type)) { isLegal = true; break; } } //封装Result对象,并且将文件的byte数组放置到result对象中 FileUploadResult fileUploadResult = new FileUploadResult(); if (!isLegal) { fileUploadResult.setStatus("error"); return fileUploadResult; } //文件新路径 String fileName = uploadFile.getOriginalFilename(); String filePath = getFilePath(fileName); // 上传到阿里云 try { client.putObject(BUCKETNAME, filePath, new ByteArrayInputStream(uploadFile.getBytes())); } catch (Exception e) { e.printStackTrace(); //上传失败 fileUploadResult.setStatus("error"); return fileUploadResult; } finally { client.shutdown(); } fileUploadResult.setStatus("done"); fileUploadResult.setResponse("success"); fileUploadResult.setName(URLPREFIX + filePath); fileUploadResult.setUid(String.valueOf(System.currentTimeMillis())); return fileUploadResult; } /** * 生成路径以及文件名 例如://images/2019/08/15564277465972939.jpg * * @param sourceFileName * @return */ private String getFilePath(String sourceFileName) { DateTime dateTime = new DateTime(); return "images/" + dateTime.toString("yyyy") + "/" + dateTime.toString("MM") + "/" + System.currentTimeMillis() + RandomUtils.nextInt(100, 9999) + "." + StringUtils.substringAfterLast(sourceFileName, "."); } /** * 查看文件列表 * * @return */ public List<OSSObjectSummary> list() { init(); // 设置最大个数。 final int maxKeys = 200; // 列举文件。 ObjectListing objectListing = client.listObjects(new ListObjectsRequest(BUCKETNAME).withMaxKeys(maxKeys)); List<OSSObjectSummary> sums = objectListing.getObjectSummaries(); client.shutdown(); return sums; } /** * 删除文件 * * @param objectName * @return */ public FileUploadResult delete(String objectName) { init(); // 根据BucketName,objectName删除文件 Integer urlPrefixLength = URLPREFIX.length(); objectName = objectName.substring(urlPrefixLength+1, objectName.length()); client.deleteObject(BUCKETNAME, objectName); FileUploadResult fileUploadResult = new FileUploadResult(); fileUploadResult.setName(objectName); fileUploadResult.setStatus("removed"); fileUploadResult.setResponse("success"); client.shutdown(); return fileUploadResult; } /** * 下载文件 * * @param os * @param objectName * @throws IOException */ public void exportOssFile(OutputStream os, String objectName) throws IOException { init(); // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。 OSSObject ossObject = client.getObject(BUCKETNAME, objectName); // 读取文件内容。 BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent()); BufferedOutputStream out = new BufferedOutputStream(os); byte[] buffer = new byte[1024]; int lenght = 0; while ((lenght = in.read(buffer)) != -1) { out.write(buffer, 0, lenght); } if (out != null) { out.flush(); out.close(); } if (in != null) { in.close(); } } } <file_sep>/src/main/java/com/islizx/controller/home/HomeIndexController.java package com.islizx.controller.home; import com.github.pagehelper.PageInfo; import com.islizx.entity.*; import com.islizx.model.dto.CountDTO; import com.islizx.model.dto.Msg; import com.islizx.model.enums.BlogStatusEnum; import com.islizx.model.enums.PostTypeEnum; import com.islizx.model.enums.WidgetTypeEnum; import com.islizx.service.*; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.List; import java.util.Objects; import java.util.concurrent.TimeUnit; /** * @author lizx * @date 2020-02-16 - 20:26 */ @Controller public class HomeIndexController { @Autowired private BlogService blogService; @Autowired private SlideService slideService; @Autowired private WidgetService widgetService; @Autowired private TypeService typeService; @Autowired private TagService tagService; @Autowired private RedisTemplate redisTemplate; /** * 请求首页 * * @param model model * @return 模板路径 */ @RequestMapping(value = "/", method = RequestMethod.GET) public String index(Model model, @RequestParam(value = "size", defaultValue = "15") Integer pageSize, @RequestParam(value = "sort", defaultValue = "createTime") String sort, @RequestParam(value = "order", defaultValue = "desc") String order) { //调用方法渲染首页 return this.index(model, 1, pageSize, sort, order); } /** * 首页分页 * * @param model model * @return 模板路径/themes/{theme}/index */ @RequestMapping(value = "/page/{pageNumber}", method = RequestMethod.GET) public String index(Model model, @PathVariable(value = "pageNumber") Integer pageNumber, @RequestParam(value = "size", defaultValue = "15") Integer pageSize, @RequestParam(value = "sort", defaultValue = "createTime") String sort, @RequestParam(value = "order", defaultValue = "desc") String order) { //文章分页排序 HashMap<String, Object> blogCriteria = new HashMap<>(1); blogCriteria.put("sort", sort); blogCriteria.put("order", order); blogCriteria.put("published", BlogStatusEnum.PUBLISHED.getCode()); blogCriteria.put("postType", PostTypeEnum.POST_TYPE_POST.getCode()); PageInfo<Blog> blogPageInfo = blogService.pageBlog(pageNumber, pageSize, blogCriteria); model.addAttribute("pageInfo", blogPageInfo); //2.首页的公告列表 HashMap<String, Object> noticeCriteria = new HashMap<>(1); noticeCriteria.put("postType", PostTypeEnum.POST_TYPE_NOTICE.getCode()); noticeCriteria.put("published", BlogStatusEnum.PUBLISHED.getCode()); PageInfo<Blog> noticePageInfo = blogService.pageBlog(0, pageSize, noticeCriteria); model.addAttribute("noticePageInfo", noticePageInfo); //3.幻灯片 // List<Slide> slides = slideService.findAll(); // model.addAttribute("slideList", slides); //4.侧边栏和底部栏组件 //前台主要小工具 List<Widget> postWidgets = widgetService.findWidgetByType(WidgetTypeEnum.POST_DETAIL_SIDEBAR_WIDGET.getCode()); model.addAttribute("postWidgets", postWidgets); CountDTO countDTO = null; countDTO = (CountDTO) redisTemplate.opsForValue().get("index_countDTO"); if(countDTO == null){ //redis缓存中无数据,从数据库中查询,并放入redis缓存中,设置生存时间为1小时 System.out.println("从数据库中取网站数据"); countDTO = blogService.getAllCount(); redisTemplate.opsForValue().set("index_countDTO", countDTO, 1, TimeUnit.HOURS); } else { System.out.println("从redis缓存中取网站数据"); } //统计 model.addAttribute("allCount", countDTO); //文章排名 model.addAttribute("blogViews", blogService.listBlogByViewCount(5)); //分类 List<Type> types = typeService.listTypeWithCount(); model.addAttribute("types", types); //标签 List<Tag> tags = tagService.listTagWithCount(null); model.addAttribute("tags", tags); return "home/index"; } /** * 请求首页 * * @param model model * @return 模板路径 */ @RequestMapping(value = "/search", method = RequestMethod.POST) public String search(Model model, @RequestParam String query, @RequestParam(value = "size", defaultValue = "15") Integer pageSize, @RequestParam(value = "pageIndex", defaultValue = "0") Integer pageIndex, @RequestParam(value = "sort", defaultValue = "createTime") String sort, @RequestParam(value = "order", defaultValue = "desc") String order) { //调用方法渲染首页 return this.search(query, model, pageSize, pageIndex, sort, order); } /** * 分页搜索 * @param query * @param model * @param pageSize * @param pageIndex * @param sort * @param order * @return */ @RequestMapping(value = "/search/{pageIndex}", method = RequestMethod.GET) public String search(@RequestParam String query, Model model, @RequestParam(value = "size", defaultValue = "15") Integer pageSize, @PathVariable(value = "pageIndex") Integer pageIndex, @RequestParam(value = "sort", defaultValue = "createTime") String sort, @RequestParam(value = "order", defaultValue = "desc") String order) { HashMap<String, Object> blogCriteria = new HashMap<>(1); blogCriteria.put("sort", sort); blogCriteria.put("order", order); blogCriteria.put("published", BlogStatusEnum.PUBLISHED.getCode()); blogCriteria.put("postType", PostTypeEnum.POST_TYPE_POST.getCode()); blogCriteria.put("title", query); PageInfo<Blog> blogPageInfo = blogService.pageBlog(pageIndex, pageSize, blogCriteria); model.addAttribute("blogPageInfo", blogPageInfo); model.addAttribute("query", query); return "home/search"; } /** * 判断页面,文章,公告 * @param postUrl * @return */ @RequestMapping(value = {"/{postUrl}.html", "post/{postUrl}"}, method = RequestMethod.GET) public String blog(@PathVariable String postUrl) { Boolean isNumeric = StringUtils.isNumeric(postUrl); Blog post; if (isNumeric) { post = blogService.getBlogByPublishedAndId(BlogStatusEnum.PUBLISHED.getCode(),null, Integer.valueOf(postUrl)); if (post == null) { post = blogService.getBlogByUrl(postUrl, null); } } else { post = blogService.getBlogByUrl(postUrl, PostTypeEnum.POST_TYPE_POST.getCode()); } //文章不存在404 if (null == post) { return "error/404"; } //文章存在但是未发布 if (!post.getPublished().equals(BlogStatusEnum.PUBLISHED.getCode())) { return "error/404"; } // 如果是页面 if (Objects.equals(post.getPostType(), PostTypeEnum.POST_TYPE_PAGE.getCode())) { return "redirect:/p/" + post.getUrl(); } // 如果是公告 else if (Objects.equals(post.getPostType(), PostTypeEnum.POST_TYPE_NOTICE.getCode())) { return "redirect:/notice/" + post.getUrl(); } return "forward:/article/" + post.getId(); } /** * 底部footer组件 * * @param model * @return */ @RequestMapping(value = "/footer", method = RequestMethod.GET) public String footerWidgets(Model model) { List<Widget> footerWidgets = null; footerWidgets = (List<Widget>) redisTemplate.opsForValue().get("footerWidgets"); if(footerWidgets == null){ System.out.println("从数据库中读取底部footer组件"); footerWidgets = widgetService.findWidgetByType(WidgetTypeEnum.FOOTER_WIDGET.getCode()); redisTemplate.opsForValue().set("footerWidgets", footerWidgets, 1, TimeUnit.HOURS); }else{ System.out.println("从redis中读取底部footer组件"); } model.addAttribute("footerWidgets", footerWidgets); return "home/_fragments :: widgetList"; } /** * 顶部自定义页面 * * @param model * @return */ @RequestMapping(value = "/header") public String headerPage(Model model,@RequestParam Integer m) { PageInfo<Blog> pagePageInfo = null; pagePageInfo = (PageInfo<Blog>) redisTemplate.opsForValue().get("pagePageInfo"); if(pagePageInfo == null){ System.out.println("从数据库中读取顶部自定义页面"); HashMap<String, Object> pageCriteria = new HashMap<>(1); pageCriteria.put("postType", PostTypeEnum.POST_TYPE_PAGE.getCode()); pagePageInfo = blogService.pageBlog(0, 15, pageCriteria); redisTemplate.opsForValue().set("pagePageInfo", pagePageInfo, 1, TimeUnit.HOURS); }else{ System.out.println("从redis中读取顶部自定义页面"); } model.addAttribute("pagePageInfo", pagePageInfo); model.addAttribute("n", m); return "home/_fragments :: header"; } /** * 渲染幻灯片 * @return */ @RequestMapping(value = "/getSlideListbyJson") @ResponseBody public Msg getSliesByJson(){ List<Slide> slides = slideService.findAll(); return Msg.success().add("slides", slides); } } <file_sep>/src/test/java/RedisTest.java import com.islizx.service.IViewService; import com.islizx.util.OssUtil; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * @author lizx * @date 2020-03-11 - 11:39 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:spring/spring-*.xml") public class RedisTest { @Autowired RedisTemplate redisTemplate; @Autowired IViewService iViewService; @Autowired OssUtil ossUtil; @Test public void test1() throws Exception{ String strUrl = "F:\\1.jpg"; File file = new File(strUrl); InputStream inputStream = new FileInputStream(file); MultipartFile multipartFile = new MockMultipartFile(file.getName(), inputStream); ossUtil.upload(multipartFile); } }
8be9a1d8339bce35db56d9ecc79986ece02f64f8
[ "JavaScript", "Java", "Markdown" ]
36
Java
Yeeget31/islizxBlog
eb9aff6b754a3622f1896199fb5a33aa27d85c23
28acd5636163dd19f029967a0e10e55f9fac3466
refs/heads/master
<file_sep>package pack.words.grouping; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import java.lang.reflect.Array; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; /** * Unit test for simple App. */ public class AppTest { @Test public void test1() { String input = "sapog sarai arbuz bolt boks birja"; String expected = "{b=[birja, boks, bolt], s=[sapog, sarai]}"; assertEquals(new SortedWordGroup(input).toString(), expected); } @Test public void test2() { String input = "арбуз болт бокс биржа"; String expected = "{б=[биржа, бокс, болт]}"; assertEquals(new SortedWordGroup(input).toString(), expected); } @Test public void test3() { String input = "сапог сарай арбуз болт бокс биржа"; String expected = "{б=[биржа, бокс, болт], с=[сапог, сарай]}"; assertEquals(new SortedWordGroup(input).toString(), expected); } @Test public void test4() { String input = ""; String expected = "{}"; assertEquals(new SortedWordGroup(input).toString(), expected); } @Test public void test5() { String input = null; String expected = "{}"; assertEquals(new SortedWordGroup(input).toString(), expected); } @Test public void test6() { String input = "СаПоГ саРАЙ арбуз БОЛТ Бокс бИРЖА"; String expected = "{б=[биржа, бокс, болт], с=[сапог, сарай]}"; assertEquals(new SortedWordGroup(input).toString(), expected); } @Test public void test7() { String inputString = "сапог +++ ' ' 58935735 сарай ||||| арбуз _ ~@$ $@$ 2323болт бокс биржа"; String expected = "{'=[', '], б=[биржа, бокс], с=[сапог, сарай]}"; assertEquals(new SortedWordGroup(inputString).toString(), expected); } @Test public void test8() { String inputString = "сапог сарай арбуз болт бокс биржа table duck deer"; String expected = "{d=[deer, duck], б=[биржа, бокс, болт], с=[сапог, сарай]}"; assertEquals(new SortedWordGroup(inputString).toString(), expected); } } <file_sep>package pack.words.grouping; import java.util.Collections; import java.util.List; public class SortingUtils { public static void sortWordsList(List<String> words){ Collections.sort(words, (a, b) -> { if (a.length() == b.length()) return a.compareTo(b); else return b.length() - a.length(); }); } }
c453e99d468b2f0c907eb6e643501e0308811126
[ "Java" ]
2
Java
alinaT95/WordsGrouping
86e86dee4152fff9d51a8c221489f71eeb09b57e
f2ca80f19f2abf02f81d65b0d434722fd5df1f66
refs/heads/master
<file_sep>local frame = CreateFrame("Frame") frame:RegisterEvent("CHAT_MSG_RAID") frame:RegisterEvent("CHAT_MSG_GUILD") frame:RegisterEvent("CHAT_MSG_RAID_LEADER") local gpValues = { ["Ring of Binding"] = " -- Need: 24 - Greed: 6" ,["Crimson Shocker"] = " -- Need: 36 - Greed: 9" ,["Flamewalker Legplates"] = " -- Need: 36 - Greed: 9" ,["Shadowstrike"] = " -- Need: 36 - Greed: 9" ,["Core Forged Greaves"] = " -- Need: 36 - Greed: 9" ,["Fireguard Shoulders"] = " -- Need: 36 - Greed: 9" ,["Fireproof Cloak"] = " -- Need: 36 - Greed: 9" ,["Choker of Enlightenment"] = " -- Need: 72 - Greed: 18" ,["Helm of the Lifegiver"] = " -- Need: 72 - Greed: 18" ,["Manastorm Leggings"] = " -- Need: 72 - Greed: 18" ,["Ring of Spell Power"] = " -- Need: 72 - Greed: 18 -- Priority: Mages then Warlocks" ,["Wristguards of Stability"] = " -- Need: 72 - Greed: 18" ,["Seal of the Archmagus"] = " -- Need: 72 - Greed: 18" ,["Cenarion Bracers"] = " -- Need: 72 - Greed: 18" ,["Cenarion Belt"] = " -- Need: 72 - Greed: 18" ,["Giantstalker Bracers"] = " -- Need: 72 - Greed: 18" ,["Giantstalker Belt"] = " -- Need: 72 - Greed: 18" ,["Arcanist Bindings"] = " -- Need: 72 - Greed: 18" ,["Arcanist Belt"] = " -- Need: 72 - Greed: 18" ,["Vambraces of Prophecy"] = " -- Need: 72 - Greed: 18" ,["Girdle of Prophecy"] = " -- Need: 72 - Greed: 18" ,["Nightslayer Bracelets"] = " -- Need: 72 - Greed: 18" ,["Nightslayer Belt"] = " -- Need: 72 - Greed: 18" ,["Felheart Bracers"] = " -- Need: 72 - Greed: 18" ,["Felheart Raiment"] = " -- Need: 72 - Greed: 18" ,["Bracers of Might"] = " -- Need: 72 - Greed: 18" ,["Belt of Might"] = " -- Need: 72 - Greed: 18" ,["Lawbringer Bracers"] = " -- Need: 72 - Greed: 18" ,["Lawbringer Belt"] = " -- Need: 72 - Greed: 18" ,["Ancient Cornerstone Grimoire"] = " -- Need: 72 - Greed: 18" ,["Magma Tempered Boots"] = " -- Need: 72 - Greed: 18" ,["Aged Core Leather Gloves"] = " -- Need: 108 - Greed: 27 -- Priority: Rogues then Druids" ,["Earthshaker"] = " -- Need: 108 - Greed: 27" ,["Fire Runed Grimoire"] = " -- Need: 108 - Greed: 27" ,["Obsidian Edged Blade"] = " -- Need: 108 - Greed: 27" ,["Sabatons of the Flamewalker"] = " -- Need: 108 - Greed: 27" ,["Gutgore Ripper"] = " -- Need: 108 - Greed: 27" ,["Finkle's Lava Dredger"] = " -- Need: 108 - Greed: 27" ,["Essence of the Pure Flame"] = " -- Need: 108 - Greed: 27" ,["Shard of the Flame"] = " -- Need: 108 - Greed: 27" ,["Cenarion Helmet"] = " -- Need: 108 - Greed: 27" ,["Cenarion Shoulders"] = " -- Need: 108 - Greed: 27" ,["Cenarion Gloves"] = " -- Need: 108 - Greed: 27" ,["Cenarion Leggings"] = " -- Need: 108 - Greed: 27" ,["Cenarion Boots"] = " -- Need: 108 - Greed: 27" ,["Giantstalker Helmet"] = " -- Need: 108 - Greed: 27" ,["Giantstalker Shoulders"] = " -- Need: 108 - Greed: 27" ,["Giantstalker Gloves"] = " -- Need: 108 - Greed: 27" ,["Giantstalker Leggings"] = " -- Need: 108 - Greed: 27" ,["Giantstalker Boots"] = " -- Need: 108 - Greed: 27" ,["Arcanist Crown"] = " -- Need: 108 - Greed: 27" ,["Arcanist Mantle"] = " -- Need: 108 - Greed: 27" ,["Arcanist Gloves"] = " -- Need: 108 - Greed: 27" ,["Arcanist Leggings"] = " -- Need: 108 - Greed: 27" ,["Arcanist Boots"] = " -- Need: 108 - Greed: 27" ,["Circlet of Prophecy"] = " -- Need: 108 - Greed: 27" ,["Mantle of Prophecy"] = " -- Need: 108 - Greed: 27" ,["Gloves of Prophecy"] = " -- Need: 108 - Greed: 27" ,["Pants of Prophecy"] = " -- Need: 108 - Greed: 27" ,["Boots of Prophecy"] = " -- Need: 108 - Greed: 27" ,["Nightslayer Cover"] = " -- Need: 108 - Greed: 27" ,["Nightslayer Shoulderpads"] = " -- Need: 108 - Greed: 27" ,["Nightslayer Gloves"] = " -- Need: 108 - Greed: 27" ,["Nightslayer Pants"] = " -- Need: 108 - Greed: 27" ,["Nightslayer Boots"] = " -- Need: 108 - Greed: 27" ,["Felheart Horns"] = " -- Need: 108 - Greed: 27" ,["Felheart Shoulderpads"] = " -- Need: 108 - Greed: 27" ,["Felheart Gloves"] = " -- Need: 108 - Greed: 27" ,["Felheart Pants"] = " -- Need: 108 - Greed: 27" ,["Felheart Slippers"] = " -- Need: 108 - Greed: 27" ,["Helm of Might"] = " -- Need: 108 - Greed: 27" ,["Pauldrons of Might"] = " -- Need: 108 - Greed: 27" ,["Gauntlets of Might"] = " -- Need: 108 - Greed: 27" ,["Legplates of Might"] = " -- Need: 108 - Greed: 27" ,["Sabatons of Might"] = " -- Need: 108 - Greed: 27" ,["<NAME>"] = " -- Need: 108 - Greed: 27" ,["<NAME>"] = " -- Need: 108 - Greed: 27" ,["<NAME>"] = " -- Need: 108 - Greed: 27" ,["<NAME>"] = " -- Need: 108 - Greed: 27" ,["<NAME>"] = " -- Need: 108 - Greed: 27" ,["Flameguard Gauntlets"] = " -- Need: 126 - Greed: 31.5" ,["Sorcerous Dagger"] = " -- Need: 144 - Greed: 36" ,["Eskhandar's Right Claw"] = " -- Need: 144 - Greed: 36" ,["Gloves of the Hypnotic Flame"] = " -- Need: 144 - Greed: 36" ,["Sash of Whispered Secrets"] = " -- Need: 144 - Greed: 36" ,["Dragon's Blood Cape"] = " -- Need: 144 - Greed: 36" ,["Malistar's Defender"] = " -- Need: 144 - Greed: 36" ,["Cenarion Vestments"] = " -- Need: 144 - Greed: 36" ,["Giantstalker's Breastplate"] = " -- Need: 144 - Greed: 36" ,["Arcanist Robe"] = " -- Need: 144 - Greed: 36" ,["Robes of Prophecy"] = " -- Need: 144 - Greed: 36" ,["Nightslayer Chestpiece"] = " -- Need: 144 - Greed: 36" ,["<NAME>"] = " -- Need: 144 - Greed: 36" ,["Breastplate of Might"] = " -- Need: 144 - Greed: 36" ,["Lawbringer Chestguard"] = " -- Need: 144 - Greed: 36" ,["Bindings of the Windseeker"] = " -- Need: 180" ,["Deep Earth Spaulders"] = " -- Need: 180 - Greed: 45" ,["Cloak of the Shrouded Mists"] = " -- Need: 180 - Greed: 45 -- Prioirty: Hunters/Tanks" ,["Spinal Reaper"] = " -- Need: 180 - Greed: 45" ,["Sapphiron Drape"] = " -- Need: 180 - Greed: 45" ,["Aurastone Hammer"] = " -- Need: 198 - Greed: 49.5 -- Priority: Druids" ,["Blastershot Launcher"] = " -- Need: 198 - Greed: 49.5" ,["Bonereaver's Edge"] = " -- Need: 198 - Greed: 49.5" ,["Brutality Blade"] = " -- Need: 216 - Greed: 54 -- Prioirty: Warriors/Rogues" ,["Drillborer Disk"] = " -- Need: 216 - Greed: 54" ,["Staff of Dominance"] = " -- Need: 216 - Greed: 54" ,["Band of Sulfuras"] = " -- Need: 216 - Greed: 54" ,["Vis'kag the Bloodletter"] = " -- Need: 216 - Greed: 54 -- Prioirty: Warriors/Rogues" ,["Stormrage Cover"] = " -- Need: 240 - Greed: 60" ,["Dragonstalker's Helm"] = " -- Need: 240 - Greed: 60" ,["Netherwind Crown"] = " -- Need: 240 - Greed: 60" ,["Halo of Transcendence"] = " -- Need: 240 - Greed: 60" ,["Bloodfang Hood"] = " -- Need: 240 - Greed: 60" ,["Nemesis Skullcap"] = " -- Need: 240 - Greed: 60" ,["Helm of Wrath"] = " -- Need: 240 - Greed: 60" ,["Judgement Crown"] = " -- Need: 240 - Greed: 60" ,["Mana Igniting Cord"] = " -- Need: 252 - Greed: 63" ,["Azuresong Mageblade"] = " -- Need: 252 - Greed: 63 -- Prioirty: Mages/Warlocks/Paladins" ,["Cauterizing Band"] = " -- Need: 252 - Greed: 63 -- Priority: Priest/Druid" ,["Wristguards of True Flight"] = " -- Need: 252 - Greed: 63 -- Priority: Tanks" ,["Heavy Dark Iron Ring"] = " -- Need: 270 - Greed: 67.5" ,["Core Hound Tooth"] = " -- Need: 288 - Greed: 72 -- Priority: Rogues then Hunters" ,["Deathbringer"] = " -- Need: 288 - Greed: 72" ,["Head of Onyxia"] = " -- Need: 288 - Greed: 72 -- Priority: Warriors then Rogues/Hunters" ,["Stormrage Legguards"] = " -- Need: 288 - Greed: 72" ,["Dragonstalker Legguards"] = " -- Need: 288 - Greed: 72" ,["Netherwind Pants"] = " -- Need: 288 - Greed: 72" ,["Leggings of Transcendence"] = " -- Need: 288 - Greed: 72" ,["Bloodfang Pants"] = " -- Need: 288 - Greed: 72" ,["Nemesis Leggings"] = " -- Need: 288 - Greed: 72" ,["Legplates of Wrath"] = " -- Need: 288 - Greed: 72" ,["Judgement Legplates"] = " -- Need: 288 - Greed: 72" ,["Shard of the Scale"] = " -- Need: 312 - Greed: 78 -- Priority: Priest/Paladin/Druid" ,["Ancient Petrified Leaf"] = " -- Need: 324 -- Note: Mature Black Dragon Sinew included in GP" ,["The Eye of Divinity"] = " -- Need: 324" ,["Mature Black Dragon Sinew"] = " -- Need: 324 -- Note: Ancient Petrified Leaf included in GP" ,["Medallion of Steadfast Might"] = " -- Need: 324 - Greed: 81" ,["Quick Strike Ring"] = " -- Need: 324 - Greed: 81" ,["Talisman of Ephemeral Power"] = " -- Need: 324 - Greed: 81 -- Priority: Warlocks then Mages" ,["Wild Growth Spaulders"] = " -- Need: 324 - Greed: 81 -- Priority: Druids then Paladins" ,["Eye of Sulfuras"] = " -- Need: 360 - Greed: 90" ,["Striker's Mark"] = " -- Need: 360 - Greed: 90 -- Priority: Warriors and Rogues" ,["Crown of Destruction"] = " -- Need: 360 - Greed: 90" ,["Perdition's Blade"] = " -- Need: 360 - Greed: 90 -- Priority: Rogues and Prot Warriors" ,["Robe of Volatile Power"] = " -- Need: 378 - Greed: 94.5" ,["Salamander Scale Pants"] = " -- Need: 378 - Greed: 94.5 -- Priority: Paladins and Druids" ,["Choker of the Firelord"] = " -- Need: 378 - Greed: 94.5 -- Priority: Mages and Warlocks" ,["Band of Accuria"] = " -- Need: 432 - Greed: 108 -- Priority: Rogues and Tanks" ,["Onslaught Girdle"] = " -- Need: 432 - Greed: 108" } function OnEvent(frame, event, ...) local msg = ...; if(not(msg:lower():sub(1,3) == "!gp")) then return end return ChatEvent(event, msg, select(2, ...)) end function ChatEvent(event, text, player, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, presenceID) local channel if (event == "CHAT_MSG_RAID") or (event == "CHAT_MSG_RAID_LEADER") then channel = "RAID" end if (event == "CHAT_MSG_GUILD") then channel = "GUILD" end local items = GetItems(text) for i = 1, #items, 2 do local count = items[i] local link = items[i+1] ChatThrottleLib:SendChatMessage("NORMAL", "TyrantEPGP", link, channel, nil, "TyrantEPGP") end end function GetItems(str) local itemList = {} for i = #itemList, 1, -1 do itemList[i] = nil end for number, link, color, item, name in str:gmatch("(%d*)%s*(|?c?(%x*)|Hitem:([^|]+)|h%[(.-)%]|h|?r?)") do table.insert(itemList, tonumber(number) or 1) table.insert(itemList, link .. gpValues[name]) end return itemList end frame:SetScript("OnEvent", OnEvent)<file_sep># tyrantepgp Simple addon to show GP values for phase 1 of classic wow. ## Usage ### !gp [itemlink]
3a65735ed5b5734e560423027caa077bfd65c628
[ "Markdown", "Lua" ]
2
Lua
ScottSlatton/tyrantepgp
8f2b1262de274919cbbbf868550b0f22e0fa1b96
7ce1e8e297c9bad4af420db9691ace2008ba2ac3
refs/heads/master
<repo_name>xlxmht/legistify<file_sep>/legistify/application/config/email.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /* | ------------------------------------------------------------------------- | Email Settings | ------------------------------------------------------------------------- | | */ $config['useragent'] = 'legistify'; $config['protocol'] = 'smtp'; $config['smtp_host'] = 'smtp.gmail.com'; $config['smtp_port'] = '465'; $config['smtp_user'] = '<EMAIL>'; $config['smtp_pass'] = '<PASSWORD>'; $config['smtp_crypto'] = 'ssl'; $config['newline'] = "\r\n"; $config['mailtype'] = "text"; $config['validate'] = FALSE; $config['priority'] = "3"; $config['charset'] = "iso-8859-1"; /* End of file email.php */ /* Location: ./application/config/email.php */ //'<EMAIL>'; //'UTLjharnet@15';<file_sep>/legistify/application/modules/__inc/scripts.php <!-- jQuery 2.1.4 --> <script src="<?php echo base_url(); ?>assets/js/jQuery-2.1.4.min.js"></script> <!-- Bootstrap 3.3.2 JS --> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js" type="text/javascript"></script> <!-- AdminLTE App --> <script src="<?php echo base_url(); ?>assets/js/app.min.js" type="text/javascript"></script><file_sep>/legistify/application/language/english/user_lang.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); // Login / Logout $lang['login_successful'] = 'Logged In Successfully'; $lang['login_unsuccessful'] = 'Incorrect Login'; $lang['login_unsuccessful_not_active'] = 'Account is inactive'; $lang['login_timeout'] = 'Temporarily Locked Out. Try again later.'; $lang['logout_successful'] = 'Logged Out Successfully'; $lang['query_successful'] = 'Query Submitted Successfully'; $lang['query_unsuccessful'] = 'Unbale to Submit Query'; $lang['update_query_successful'] = 'Query Updated Successfully'; $lang['update_query_unsuccessful'] = 'Unable to Update Query'; <file_sep>/legistify/application/modules/user/views/query_form.php <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Legistify | Query Form</title> <?php $this->load->view('../../__inc/head'); ?> </head> <body class="register-page"> <div class="register-box"> <div class="register-logo"> <a href="#"><b>Legistify</b>Query</a> </div> <div class="register-box-body"> <p class="login-box-msg">Query for legal documents</p> <?php echo ($errors) ? '<div class="alert alert-danger">'.$errors.'</div>' : '' ?> <?php echo ($message) ? '<div class="alert alert-info">'.$message.'</div>' : '' ?> <?php $attributes = array('id' => 'queryform'); echo form_open("user/user_query",$attributes);?> <div class="form-group"> <label for="email">Email</label> <input type="email" name="email" class="form-control" placeholder="Email"/> <?php echo form_error('email'); ?> </div> <div class="form-group"> <label for="document">Regarding Document</label> <?php $js = 'class="form-control"'; echo form_dropdown('document',$doc_list,0,$js); ?> <?php echo form_error('document'); ?> </div> <div class="form-group"> <label for="document">Query Details</label> <textarea class="form-control" name="details" rows="3" cols="3" placeholder="Enter the details"/></textarea> <?php echo form_error('details'); ?> </div> <div class="row"> <div class="col-xs-6"> <?php $attributes = 'class="btn btn-warning btn-block btn-flat"'; echo anchor('user/login', 'Login Form',$attributes)?> </div> <div class="col-xs-6"> <?php $js = 'class="btn btn-primary btn-block btn-flat"'; echo form_submit('submit', 'Submit Query',$js);?> </div><!-- /.col --> </div> </form> </div><!-- /.form-box --> </div><!-- /.register-box --> <?php $this->load->view('../../__inc/scripts'); ?> </body> </html><file_sep>/legistify/application/modules/user/models/user_model.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class User_model extends CI_Model { /** * message (uses lang file) * * @var string **/ protected $messages; /** * error message (uses lang file) * * @var string **/ protected $errors; public function __construct() { parent::__construct(); $this->load->database(); $this->lang->load('user'); //using delimiters $this->message_start_delimiter = '<p class="text-black">'; $this->message_end_delimiter = '</p>'; $this->error_start_delimiter = '<p class="text-red">'; $this->error_end_delimiter = '</p>'; } public function get_documents() { $query = $this->db->get('document_master'); $row[0] = 'Select Document'; if ($query->num_rows() > 0) { foreach ($query->result() as $res) { $row[$res->id] = $res->name; } return $row; } return $row; } public function get_user_querylist($id = '') { if (empty($id)) { $this->db->select('B.name as doc,A.*') ->from('queries as A') ->join('document_master as B', 'B.id = A.document_id') ->where('A.email_send',0) ->order_by('A.time','ASC'); $query = $this->db->get(); if ($query->num_rows() > 0) { return $query->result_array(); } return FALSE; }else{ $this->db->select('B.name as doc,A.*') ->from('queries as A') ->join('document_master as B', 'B.id = A.document_id') ->where(array('A.email_send' => 0 , 'A.id' => $id)) ->limit(1); $query = $this->db->get(); if ($query->num_rows() == 1) { return $query->row(); } return FALSE; } } public function login($identity, $password) { if (empty($identity) || empty($password)) { $this->set_error('login_unsuccessful'); return FALSE; } $query = $this->db->select('id,username') ->get_where('users',array('username' => $identity , 'password' => $password)); if ($query->num_rows() == 1) { $this->set_session($query->row()); $this->set_message('login_successful'); return TRUE; } $this->set_error('login_unsuccessful'); return FALSE; } public function save_document_query($email,$doc,$details) { if (empty($email) || empty($doc) || empty($details)) { $this->set_error('query_unsuccessful'); return FALSE; } $save_data = array( 'document_id' => $doc, 'email' => $email, 'message' => $details, 'time' => date('Y-m-d H:m:s') ); $this->db->insert('queries', $save_data); if ($this->db->insert_id()) { $this->set_message('query_successful'); return TRUE; } $this->set_error('query_unsuccessful'); return FALSE; } public function update_document_query($id,$response) { if (empty($id) || empty($response)) { $this->set_error('update_query_unsuccessful'); return FALSE; } $save_data = array( 'response_message' => $response, 'email_send' => 1 ); $updated_query_db = $this->db->update('queries', $save_data,array('id' => $id)); if ($updated_query_db) { $this->set_message('update_query_successful'); }else{ $this->set_error('update_query_unsuccessful'); } return $updated_query_db; } protected function set_session($user) { $session_data = array( 'id' => $user->id, 'username' => $user->username ); $this->session->set_userdata($session_data); return TRUE; } /** * logged_in * * @return bool **/ public function logged_in() { return (bool) $this->session->userdata('id'); } /** * logout * * @return void **/ public function logout() { $this->session->unset_userdata( array('id' => '', 'username' => '') ); //Destroy the session $this->session->sess_destroy(); //Recreate the session if (substr(CI_VERSION, 0, 1) == '2') { $this->session->sess_create(); } else { $this->session->sess_regenerate(TRUE); } $this->set_message('logout_successful'); return TRUE; } /** * set_error * * Set an error message * * @return void **/ public function set_error($error) { $this->errors[] = $error; return $error; } /** * errors * * Get the error message * * @return void **/ public function errors() { $_output = ''; foreach ($this->errors as $error) { $errorLang = $this->lang->line($error) ? $this->lang->line($error) : '##' . $error . '##'; $_output .= $this->error_start_delimiter . $errorLang . $this->error_end_delimiter; } return $_output; } /** * set_message * * Set a message * * @return void **/ public function set_message($message) { $this->messages[] = $message; return $message; } /** * messages * * Get the messages * * @return void **/ public function messages() { $_output = ''; foreach ($this->messages as $message) { $messageLang = $this->lang->line($message) ? $this->lang->line($message) : '##' . $message . '##'; $_output .= $this->message_start_delimiter . $messageLang . $this->message_end_delimiter; } return $_output; } }<file_sep>/legistify/application/modules/user/views/blank.php <!-- For Listing User Query Details --> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Legistify | Dashboard</title> <!-- include head --> <?php $this->load->view('../../__inc/head'); ?> <?php echo link_tag('assets/css/datatables/jquery.dataTables.css'); ?> </head> <body class="skin-blue sidebar-mini"> <!-- Site wrapper --> <div class="wrapper"> <header class="main-header"> <!-- include header --> <?php $this->load->view('../../__inc/header'); ?> </header> <!-- =============================================== --> <!-- include Left sidebar --> <?php $this->load->view('../../__inc/side_nav_bar'); ?> <!-- =============================================== --> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> User Query Details <small>List of user queries</small> </h1> <ol class="breadcrumb"> <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li> <li class="active">Queries</li> </ol> </section> <!-- Main content --> <section class="content"> <!-- Default box --> <?php echo ($this->session->flashdata('message')) ? '<div class="alert alert-info">'.$this->session->flashdata('message').'</div>' : '' ?> <div class="box"> <div class="box-body"> <table id="printview" class="display table table-bordered table-condensed"> <thead> <tr> <th>Query Document</th> <th>Message Details</th> <th>Email</th> <th>Date & Time</th> <th>Action</th> </tr> </thead> </table> </div><!-- /.box-body --> </div><!-- /.box --> </section><!-- /.content --> </div><!-- /.content-wrapper --> <!-- include footer --> <?php $this->load->view('../../__inc/footer'); ?> </div><!-- ./wrapper --> <!-- include script --> <?php $this->load->view('../../__inc/scripts'); ?> <script src="<?php echo base_url(); ?>assets/js/datatable/jquery.dataTables.js"></script> <script type="text/javascript"> 'use strict'; $(document).ready(function(){ var oTable = $('#printview').DataTable( { dom: 'T<"clear">lfrtip', "paging": false, "ordering": false, "filter": false, "info": false }); var test_token = '<?php echo $this->security->get_csrf_hash(); ?>'; var ajax_get_docs = function() { $.ajax({ url: "user/ajax_get_querylist", type: "POST", //The type which you want to use: GET/POST data: {csrf_test_name:test_token}, dataType: "json", //Return data type (what we expect). success: function(j) { if (j.valid === "true") { oTable.clear(); var msg = j.qdata; console.log(j.qdata); for (var i = 0; i < msg.length; i++) { var up_link = '<a class="btn btn-primary btn-xs" href="<?php echo base_url("user/update_querylist")."/" ?>'+msg[i].id+'">Edit</a>'; oTable.row.add([msg[i].doc,msg[i].message,msg[i].email,msg[i].time,up_link]).draw(); } }else{ oTable.clear(); oTable.draw(); } }, error: function(e){ console.log(e.responseText); } }); } ajax_get_docs(); }); </script> </body> </html><file_sep>/legistify/application/modules/__inc/head.php <meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'> <!-- Bootstrap 3.3.4 --> <?php echo link_tag('assets/css/bootstrap.min.css'); ?> <!-- Font Awesome Icons --> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" /> <!-- Ionicons --> <link href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css" /> <!-- Theme style --> <?php echo link_tag('assets/css/AdminLTE.min.css'); ?> <!-- AdminLTE Skins. Choose a skin from the css/skins --> <?php echo link_tag('assets/css/skins/skin-blue.min.css'); ?> <file_sep>/README.txt ##-- Instruction to run the application --## 1. First import the database "legistify" resides in "legistify/legistify.sql". 2. All files are in "legistify/application/modules". 3. Email id to send the answer from lawyer to user is: Email: <EMAIL> Pass: <PASSWORD> 4. There is a login form for lawyer where he will see all the queries posted by different users: username is set to "admin" password is set to "<PASSWORD>" 5. Type the response in the texarea provided, browse the file to upload attachment with .docx and hit "Update & send Email" 6. Query will be deleted(not from database but from front end) as soon as lawyer provide answers to the user. 7. That's all...!!<file_sep>/legistify/application/core/MY_Controller.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class MY_Controller extends CI_Controller { function __construct() { parent::__construct(); $this->ci =& get_instance(); $this->load->helper(array('url','form','html')); $this->load->library('form_validation'); $this->ci->load->library('session'); $this->output->set_header('Last-Modified:'.gmdate('D, d M Y H:i:s').'GMT'); $this->output->set_header('Cache-Control: no-store, no-cache, must-revalidate'); $this->output->set_header('Cache-Control: post-check=0, pre-check=0',false); $this->output->set_header('Pragma: no-cache'); } } // END Controller class /* End of file MY_Controller.php */ /* Location: ./system/core/MY_Controller.php */<file_sep>/legistify/application/modules/user/controllers/user.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class User extends MY_Controller { public function __construct() { parent::__construct(); $this->form_validation->set_error_delimiters('<p class="text-black">', '</p>'); //$this->form_validation->set_message_delimiters('<p class="text-aqua">', '</p>'); $this->load->model('user_model'); } public function index() { if (!$this->user_model->logged_in()) { redirect('user/user_query','refresh'); } else{ $this->load->view('blank'); } } public function ajax_get_querylist() { //check if its an ajax request, exit if not if(!$this->input->is_ajax_request()) { die("request should be ajax"); } $result = $this->user_model->get_user_querylist(); if ($result) { $res = array("valid"=>"true", "qdata" => $result); echo json_encode($res); } else{ $res = array("valid"=>"false"); echo json_encode($res); } } /** Function for Admin's login **/ public function login() { //validate form input $this->form_validation->set_rules('identity', 'Identity', 'required|xss_clean|max_length[30]'); $this->form_validation->set_rules('password', '<PASSWORD>', '<PASSWORD>'); if ($this->form_validation->run() == true) { if ($this->user_model->login($this->input->post('identity'), $this->input->post('password'))) { //if the login is successful //redirect them back to the home page $this->session->set_flashdata('message', $this->user_model->messages()); redirect('user/index', 'refresh'); } else { //if the login was un-successful //redirect them back to the login page $this->session->set_flashdata('errors', $this->user_model->errors()); redirect('user/login', 'refresh'); } } else { //the user is not logging in so display the login page //set the flash data error message if there is one $this->data['errors'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('errors'); $this->data['message'] = $this->session->flashdata('message'); $this->load->view('login',$this->data); } } public function check_docs($str) { if (!$str) { $this->form_validation->set_message('check_docs', 'The %s field is required'); return FALSE; } else { return TRUE; } } public function user_query() { $this->data['title'] = 'Query Form'; //validate form input $this->form_validation->set_rules('email', 'Email', 'required|xss_clean|valid_email|max_length[30]'); $this->form_validation->set_rules('document', 'Document', 'required|xss_clean|callback_check_docs'); $this->form_validation->set_rules('details', 'Details', 'required|xss_clean|max_length[150]'); if ($this->form_validation->run() == true) { if ($this->user_model->save_document_query($this->input->post('email'), $this->input->post('document'),$this->input->post('details'))) { $this->session->set_flashdata('message', $this->user_model->messages()); redirect('user/user_query', 'refresh'); } else { $this->session->set_flashdata('errors', $this->user_model->errors()); redirect('user/user_query', 'refresh'); } } else { $this->data['errors'] = $this->session->flashdata('errors'); $this->data['message'] = $this->session->flashdata('message'); $this->data['doc_list'] = $this->user_model->get_documents(); $this->load->view('query_form',$this->data); } } public function update_querylist($id) { if (!$this->user_model->logged_in() || !$id) { redirect('user/index','refresh'); }elseif (!$this->user_model->get_user_querylist(trim($id))) { redirect('user/index','refresh'); } $config['upload_path'] = './uploads/'; $config['allowed_types'] = 'doc|docx'; $config['overwrite'] = true; $config['max_size'] = '3072'; $config['max_width'] = '1024'; $config['max_height'] = '768'; $this->load->library('upload', $config); $this->data['query_info'] = $this->user_model->get_user_querylist(trim($id)); //validate form input $this->form_validation->set_rules('answer', 'Answer', 'required|xss_clean|max_length[100]'); if ($this->form_validation->run() == true && $this->upload->do_upload()) { if ($this->_send_email($this->data['query_info']->email,$this->data['query_info']->message,$this->input->post('answer'),$this->upload->data()['full_path'])) { //if message sent successfully //update queries data if($this->user_model->update_document_query($this->data['query_info']->id,$this->input->post('answer'))) { $this->session->set_flashdata('message', $this->user_model->messages()); redirect('user/index', 'refresh'); } else{ $this->session->set_flashdata('errors', $this->user_model->errors()); redirect(uri_string(), 'refresh'); } } else { //redirect them back to the login page $this->session->set_flashdata('errors', $this->user_model->errors()); redirect(uri_string(), 'refresh'); } }else{ //the user is not logging in so display the login page //set the flash data error message if there is one $this->data['errors'] = ($this->upload->display_errors()) ? $this->upload->display_errors() : $this->session->flashdata('errors'); $this->data['message'] = $this->session->flashdata('message'); $this->load->view('edit',$this->data); } } protected function _send_email($to, $msg, $response_msg, $attachment){ if (!$this->user_model->logged_in() || empty($to)) { redirect('user/index','refresh'); } $this->load->library('email'); $this->email->clear(TRUE); $this->email->from($this->email->smtp_user); $this->email->to($to); $this->email->subject('Legistify - Query Support'); $body = $this->email->email_body($msg, $response_msg); $this->email->message($body); $this->email->attach($attachment); $result = $this->email->send(); if($result){ $this->session->set_flashdata('message','e-mail sent successfully to your given email address'); return TRUE; }else{ $this->session->set_flashdata('errors','Unable to sent e-mail'); return FALSE; } } public function logout() { //log the user out $logout = $this->user_model->logout(); //redirect them to the login page $this->session->set_flashdata('message', $this->user_model->messages()); redirect('user/login', 'refresh'); } } /* End of file welcome.php */ /* Location: ./application/controllers/welcome.php */<file_sep>/legistify/application/modules/user/views/login.php <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Legistify | Log in</title> <?php $this->load->view('../../__inc/head'); ?> </head> <body class="login-page"> <div class="login-box"> <div class="login-logo"> <a href="#"><b>Legistify</b>Login</a> </div><!-- /.login-logo --> <div class="login-box-body"> <p class="login-box-msg">Sign in to start your session</p> <?php echo ($errors) ? '<div class="alert alert-danger">'.$errors.'</div>' : '' ?> <?php echo ($message) ? '<div class="alert alert-info">'.$message.'</div>' : '' ?> <?php $attributes = array('id' => 'loginform'); echo form_open("user/login",$attributes);?> <div class="form-group has-feedback"> <input type="text" name="identity" class="form-control" placeholder="Username"/> <span class="glyphicon glyphicon-envelope form-control-feedback"></span> </div> <div class="form-group has-feedback"> <input type="<PASSWORD>" name="password" class="form-control" placeholder="<PASSWORD>"/> <span class="glyphicon glyphicon-lock form-control-feedback"></span> </div> <div class="row"> <div class="col-xs-6"> <?php $js = 'class="btn btn-primary btn-block btn-flat"'; echo form_submit('submit', 'Sign In',$js);?> </div><!-- /.col --> <div class="col-xs-6"> <?php $attributes = 'class="btn btn-warning btn-block btn-flat"'; echo anchor('user/user_query', 'Query Form',$attributes)?> </div> </div> <?php form_close(); ?> </div><!-- /.login-box-body --> </div><!-- /.login-box --> <?php $this->load->view('../../__inc/scripts'); ?> </body> </html><file_sep>/legistify/application/modules/user/views/edit.php <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Legistify | Dashboard</title> <!-- include head --> <?php $this->load->view('../../__inc/head'); ?> <?php echo link_tag('assets/css/datatables/jquery.dataTables.css'); ?> </head> <body class="skin-blue sidebar-mini"> <!-- Site wrapper --> <div class="wrapper"> <header class="main-header"> <!-- include header --> <?php $this->load->view('../../__inc/header'); ?> </header> <!-- =============================================== --> <!-- include Left sidebar --> <?php $this->load->view('../../__inc/side_nav_bar'); ?> <!-- =============================================== --> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> Update Query Details <small>Updation of user queries</small> </h1> <ol class="breadcrumb"> <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li> <li class="active">Queries</li> </ol> </section> <!-- Main content --> <section class="content"> <!-- Default box --> <?php echo ($message) ? '<div class="alert alert-info">'.$message.'</div>' : '' ?> <?php echo ($errors) ? '<div class="alert alert-danger">'.$errors.'</div>' : '' ?> <?php $attributes = 'role="form"'; echo form_open_multipart(uri_string(),$attributes);?> <div class="box"> <div class="box-body"> <div class="row"> <div class="col-lg-6"> <div class="form-group"> <label for="doc">Query Regarding</label> <input type="text" value="<?php echo $query_info->doc ?>" class="form-control" readonly> </div> <div class="form-group"> <label for="email">Email</label> <input type="text" value="<?php echo $query_info->email ?>" class="form-control" readonly> </div> <div class="form-group"> <label for="time">Submission Date & Time</label> <input type="text" value="<?php echo $query_info->time ?>" class="form-control" readonly> </div> <div class="form-group"> <label for="message">Message Details</label> <textarea type="text" rows="3" cols="3" class="form-control" readonly><?php echo $query_info->message ?></textarea> </div> </div> <div class="col-lg-6"> <div class="form-group"> <label for="answer">Response Message</label> <textarea type="text" name="answer" rows="3" cols="3" class="form-control"></textarea> <?php echo form_error('answer'); ?> </div> <div class="form-group"> <label>Response Upload</label> <input type="file" name="userfile" id="userfile" required/> <span class="text-red"><br /> * Allowed file size is 3MB and file type is doc.</span> </div> </div> </div> </div><!-- /.box-body --> <div class="box-footer"> <?php $js = 'class="btn btn-primary"'; echo form_submit('submit', 'Update & Send Email',$js);?> <?php $attributes = 'class="btn bg-olive"'; echo anchor('user/index', 'Back',$attributes)?> </div> </div><!-- /.box --> <?php echo form_close();?> </section><!-- /.content --> </div><!-- /.content-wrapper --> <!-- include footer --> <?php $this->load->view('../../__inc/footer'); ?> </div><!-- ./wrapper --> <!-- include script --> <?php $this->load->view('../../__inc/scripts'); ?> <script src="<?php echo base_url(); ?>assets/js/datatable/jquery.dataTables.js"></script> <script type="text/javascript"> 'use strict'; $(document).ready(function(){ var oTable = $('#printview').DataTable( { dom: 'T<"clear">lfrtip', "paging": false, "ordering": false, "filter": false, "info": false }); var test_token = '<?php echo $this->security->get_csrf_hash(); ?>'; var ajax_get_docs = function() { $.ajax({ url: "user/ajax_get_querylist", type: "POST", //The type which you want to use: GET/POST data: {csrf_test_name:test_token}, dataType: "json", //Return data type (what we expect). success: function(j) { if (j.valid === "true") { oTable.clear(); var msg = j.qdata; console.log(j.qdata); for (var i = 0; i < msg.length; i++) { var up_link = '<a class="btn btn-primary btn-xs" href="<?php echo base_url("user/update_querylist")."/" ?>'+msg[i].id+'">Edit</a>'; oTable.row.add([msg[i].doc,msg[i].message,msg[i].email,msg[i].time,up_link]).draw(); } }else{ oTable.clear(); oTable.draw(); } }, error: function(e){ console.log(e.responseText); } }); } ajax_get_docs(); }); </script> </body> </html>
c9976478fd717e208a0e849c52aaf1196a34176e
[ "Text", "PHP" ]
12
PHP
xlxmht/legistify
23ebfb3e9521643022c98d1be44d810c65fba9ac
2de2781abbe72cc659b10ae42b8b67f89d971b24
refs/heads/master
<file_sep>import React from 'react'; import ReactDOM from 'react-dom'; import { connect } from 'react-redux'; import { WidthProvider, Responsive } from 'react-grid-layout'; import _ from 'lodash'; import styled from 'styled-components'; import Draggable from './Draggable'; import Droppable from './Droppable'; import CardForm from '../components/divlab_components/CardForm'; import HeaderForm from '../components/divlab_components/HeaderForm'; import HeadshotForm from '../components/divlab_components/HeadshotForm'; import ParagraphForm from '../components/divlab_components/ParagraphForm'; import SidewaysCardForm from '../components/divlab_components/SidewaysCardForm'; import { addAPage, getAllPages, editAPage, deleteAPage, } from '../store/pageReducer'; import { setHTML, regexer } from '../utils/utils'; import { Button, Icon, Menu, Segment, Sidebar, Confirm, } from 'semantic-ui-react'; const ResponsiveReactGridLayout = WidthProvider(Responsive); const Item = styled.div` color: #555; padding: 8px; border-radius: 3px; `; const droppableStyle1 = { backgroundColor: '#555', display: 'flex', flexDirection: 'column', justifyContent: 'center', minWidth: '250px', minHeight: '500px', margin: '32px', }; class divlabTwo extends React.PureComponent { static defaultProps = { className: 'layout', cols: { lg: 120, md: 100, sm: 60, xs: 40, xxs: 20 }, rowHeight: 2, }; constructor(props) { super(props); this.state = { visible: false, items: [], newCounter: 0, components: [], usedComponents: [], html: '', open: false, title: '', toggled: false, }; this.onAddItem = this.onAddItem.bind(this); this.onBreakpointChange = this.onBreakpointChange.bind(this); this.reactDomRender = this.reactDomRender.bind(this); } //Opens and closes the delete modal show = () => this.setState({ open: true }); handleConfirm = () => { this.setState({ open: false }); this.props.deleteAPage( this.props.auth.auth.uid, this.props.match.params.id ); }; handleCancel = () => this.setState({ open: false }); handleHideClick = () => this.setState({ visible: false }); handleShowClick = () => this.setState({ visible: true }); handleSidebarHide = () => this.setState({ visible: false }); componentDidMount() { this.props.auth.auth.uid && this.props.getAllPages(this.props.auth.auth.uid); if (this.props.pages.length && this.props.match.params.id) { const newState = JSON.parse( this.props.pages.find(doc => doc.id === `${this.props.match.params.id}`) .data.pageData ); this.setState({ ...newState.canvas, html: newState.html }); setTimeout(() => { this.reactDomRender(this.state); }, 10); } } save = async () => { const { items, visible, newCounter } = this.state; const html = setHTML(); await this.setState({ html }); if (this.props.match.params.id) { this.props.editAPage( this.props.auth.auth.uid, this.props.match.params.id, JSON.stringify({ canvas: { items, visible, newCounter, components: [], usedComponents: [], title: this.state.title, }, html, }) ); } else { await this.props.addAPage( this.props.auth.auth.uid, JSON.stringify({ canvas: { items, visible, newCounter, components: [], usedComponents: [], }, html, }) ); } }; reactDomRender(state) { let data = regexer(state.html); if (data) { let counter = 0; for (let i = 0; i < data.length; i++) { let curEl = data[i]; if ( curEl === 'HeadshotComponent' || curEl === 'ParagraphComponent' || 'CardComponent' || 'SidewaysCardComponent' || 'HeaderComponent' ) { switch (curEl) { case 'HeadshotComponent': let temp = document.getElementById(`n${counter}`); while (!temp) { counter++; temp = document.getElementById(`n${counter}`); } let newDiv = document.createElement('div'); newDiv.id = `newDiv${counter}`; temp.style.padding = '8px'; temp.appendChild(newDiv); ReactDOM.render( <HeadshotForm info={{ imageUrl: data[i + 1], id: `image${i}`, edit: false, }} />, document.getElementById(`newDiv${counter}`) ); counter++; break; case 'ParagraphComponent': let temp2 = document.getElementById(`n${counter}`); while (!temp2) { counter++; temp2 = document.getElementById(`n${counter}`); } let newDiv2 = document.createElement('div'); newDiv2.id = `newDiv${counter}`; temp2.style.padding = '8px'; temp2.appendChild(newDiv2); ReactDOM.render( <ParagraphForm info={{ content: data[i + 1], id: `paragraph${i}`, edit: false, }} />, document.getElementById(`newDiv${counter}`) ); counter++; break; case 'CardComponent': let temp3 = document.getElementById(`n${counter}`); while (!temp3) { counter++; temp3 = document.getElementById(`n${counter}`); } let newDiv3 = document.createElement('div'); newDiv3.id = `newDiv${counter}`; temp3.style.padding = '8px'; temp3.appendChild(newDiv3); ReactDOM.render( <CardForm info={{ imageUrl: data[i + 1], name: data[i + 2], caption: data[i + 3], description: data[i + 4], footer: data[i + 5], id: `paragraph${i}`, edit: false, }} />, document.getElementById(`newDiv${counter}`) ); counter++; break; case 'HeaderComponent': let temp4 = document.getElementById(`n${counter}`); while (!temp4) { counter++; temp4 = document.getElementById(`n${counter}`); } let newDiv4 = document.createElement('div'); newDiv4.id = `newDiv${counter}`; temp4.style.padding = '8px'; temp4.appendChild(newDiv4); ReactDOM.render( <HeaderForm info={{ backgroundUrl: data[i + 1], title: data[i + 2], navlinks: '', id: `paragraph${i}`, edit: false, }} />, document.getElementById(`newDiv${counter}`) ); counter++; break; case 'SidewaysCardComponent': let temp5 = document.getElementById(`n${counter}`); while (!temp5) { counter++; temp5 = document.getElementById(`n${counter}`); } let newDiv5 = document.createElement('div'); newDiv5.id = `newDiv${counter}`; temp5.style.padding = '8px'; temp5.appendChild(newDiv5); ReactDOM.render( <SidewaysCardForm info={{ imageUrl: data[i + 1], name: data[i + 2], caption: data[i + 3], description: data[i + 4], id: `paragraph${i}`, edit: false, }} />, document.getElementById(`newDiv${counter}`) ); counter++; break; default: break; } } } } } createElement(el) { const removeStyle = { position: 'absolute', right: '2px', top: 0, cursor: 'pointer', }; const i = el.add ? '+' : el.i; return ( <div style={{ border: '1px solid red', overflow: 'hidden' }} key={i} data-grid={el} id={i} > {el.add ? ( <span className="add text" onClick={this.onAddItem} title="You can add an item by clicking here, too." > Add + </span> ) : ( <span className="text" /> )} <span name="X" className="remove" style={removeStyle} onClick={this.onRemoveItem.bind(this, i)} > x </span> </div> ); } onAddItem() { /*eslint no-console: 0*/ this.setState({ // Add a new item. It must have a unique key! items: this.state.items.concat({ i: 'n' + this.state.newCounter, x: (this.state.items.length * 2) % (this.state.cols || 120), // y: Infinity, // puts it at the bottom y: 1, w: 20, h: 20, }), // Increment the counter to ensure key is always unique. newCounter: this.state.newCounter + 1, }); } // We're using the cols coming back from this to calculate where to add new items. onBreakpointChange(breakpoint, cols) { this.setState({ breakpoint: breakpoint, cols: cols, }); } onLayoutChange = items => { this.setState({ items }); }; onRemoveItem(i) { this.setState({ items: _.reject(this.state.items, { i: i }) }); } removeClass = () => { const divs = document.querySelectorAll('.react-resizable'); divs.forEach(item => { item.classList.remove('react-resizable'); }); }; render() { const { visible } = this.state; return ( <div> <Button.Group> <Button disabled={visible} onClick={this.handleShowClick}> Show Components </Button> <Button disabled={!visible} onClick={this.handleHideClick}> Hide Components </Button> </Button.Group> <div className="myProjects" style={{ marginTop: '20px' }}> <p>{this.state.title}</p> </div> <Sidebar.Pushable as={Segment} style={{ backgroundColor: 'rgb(253,208,0)' }} > <Sidebar as={Menu} animation="overlay" icon="labeled" inverted onHide={this.handleSidebarHide} vertical visible={visible} width="wide" > <Menu.Item as="a"> <Icon name="home" /> Home </Menu.Item> <Menu.Item as="a" onClick={() => { this.setState({ components: [...this.state.components, <CardForm />], visible: false, }); }} > <Icon name="address card" /> Card </Menu.Item> <Menu.Item as="a" onClick={() => { this.setState({ components: [...this.state.components, <SidewaysCardForm />], visible: false, }); }} > <Icon name="address card" /> Sideways Card </Menu.Item> <Menu.Item as="a" onClick={() => { this.setState({ components: [...this.state.components, <HeaderForm />], visible: false, }); }} > <Icon name="header" /> Header </Menu.Item> <Menu.Item as="a" onClick={() => { this.setState({ components: [...this.state.components, <HeadshotForm />], visible: false, }); }} > <Icon name="image" /> Image </Menu.Item> <Menu.Item as="a" onClick={() => { this.setState({ components: [...this.state.components, <ParagraphForm />], visible: false, }); }} > <Icon name="paragraph" /> Paragraph </Menu.Item> </Sidebar> <Sidebar.Pusher dimmed={visible}> <Segment basic> <div style={{ marginBottom: '10px' }}> <Button onClick={() => { const imgs = document.querySelectorAll( '.react-resizable-handle-se' ); const editButtonsOn = document.querySelectorAll( '.edit-button-on' ); const editButtonsOff = document.querySelectorAll( '.edit-button-off' ); const divs = document.querySelectorAll('.react-grid-item'); const xs = document.getElementsByName('X'); editButtonsOn.forEach(item => { if (item.classList.contains('edit-button-on')) { item.classList.replace( 'edit-button-on', 'edit-button-off' ); } }); editButtonsOff.forEach(item => { if (item.classList.contains('edit-button-off')) { item.classList.replace( 'edit-button-off', 'edit-button-on' ); } }); imgs.forEach(i => { if (i.classList.contains('react-resizable-handle')) { i.classList.remove('react-resizable-handle'); } else { i.classList.add('react-resizable-handle'); } }); xs.forEach(x => { if (x.textContent === 'x') { x.textContent = ''; } else { x.textContent = 'x'; } }); divs.forEach(div => { if (div.style.border) { div.style.border = null; } else { div.style.border = '1px solid red'; } }); this.setState({toggled: !this.state.toggled}) }} > <Icon name="eye" /> Toggle Preview </Button> <Button onClick={this.onAddItem} disabled={this.state.toggled}> <Icon name="plus square" /> Add New Container </Button> <Button onClick={this.save}> <Icon name="save" /> Save </Button> <Button disabled={!this.state.toggled} onClick={() => { // let html = document.querySelector('html').innerHTML; // html = '<html>\n' + html + '\n</html>'; let head = document.querySelector('head').innerHTML; let canvas = document.querySelector('.react-grid-layout') .innerHTML; let html = '<html>\n' + head + '<body style="background-color: white;">\n' + '<div style="width: 1200px; margin: auto;">' + canvas + '</div>' + '</body>\n' + '\n</html>'; // console.log(canvas); let download = document.createElement('a'); download.style.display = 'none'; download.setAttribute( 'href', 'data:text/html;charset=utf-8,' + encodeURIComponent(html) ); download.setAttribute('download', 'index'); document.body.appendChild(download); download.click(); document.body.removeChild(download); }} > <Icon name="download" /> Export </Button> <Button onClick={this.show} inverted color='red'> <Icon name="trash alternate" /> Delete Project </Button> <Confirm open={this.state.open} content="Are you sure you want to delete this project?" onCancel={this.handleCancel} onConfirm={this.handleConfirm} /> </div> {/* Styling for centering grid here */} <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'center', }} > <div> <Droppable style={ this.state.components.length ? droppableStyle1 : null } > {this.state.components.map((item, idx) => { if (!this.state.usedComponents.includes(item)) { this.state.usedComponents.push(item); } return ( <Draggable id={String(Math.floor(Math.random() * 100000000))} key={idx} > <Item>{item}</Item> </Draggable> ); })} </Droppable> </div> <div> <Droppable> <ResponsiveReactGridLayout onLayoutChange={this.onLayoutChange} style={{ width: '1200px', minHeight: '1000px', backgroundColor: 'white', }} {...this.props} > {_.map(this.state.items, el => { return this.createElement(el); })} </ResponsiveReactGridLayout> </Droppable> </div> </div> </Segment> </Sidebar.Pusher> </Sidebar.Pushable> </div> ); } } const mapStateToProps = state => { return { auth: state.firebase, profile: state.firebase.profile, pages: state.pages, }; }; const mapDispatchToProps = dispatch => { return { editAPage: (userId, pageId, pageContent) => { dispatch(editAPage(userId, pageId, pageContent)); }, addAPage: (userId, pageContent) => { dispatch(addAPage(userId, pageContent)); }, getAllPages: user => { dispatch(getAllPages(user)); }, deleteAPage: (userId, pageId) => { dispatch(deleteAPage(userId, pageId)); }, }; }; export default connect( mapStateToProps, mapDispatchToProps )(divlabTwo); <file_sep>import React from 'react'; import { Link } from 'react-router-dom'; import { connect } from 'react-redux'; import { signOut } from '../store/authReducer'; import { Modal, Dropdown } from 'semantic-ui-react'; import Carousel from 'semantic-ui-carousel-react'; class Navbar extends React.Component { constructor(props) { super(props); this.state = { open: false, }; this.profileItems = [ { key: 'newProject', text: 'NEW PROJECT', onClick: () => { const newProject = document.querySelector('#newProject'); newProject.click(); }, }, { key: 'projects', text: 'PROJECTS', onClick: () => { const allProjects = document.querySelector('#allProjects'); allProjects.click(); }, }, { key: 'signout', text: 'SIGN OUT', onClick: this.props.signOut, }, ]; } render() { const elements = [ { render: () => { return ( <div> <center> <h2> After logging in, add a container or two to your canvas... </h2> </center> <br /> <iframe title="intro" src="https://giphy.com/embed/Qz4snoMQSPhXDikptH" width="800" height="410" frameBorder="0" class="giphy-embed" allowFullScreen ></iframe> <center> <h4> You can add, resize, move, and delete these containers as you wish. </h4> </center> </div> ); }, }, { render: () => { return ( <div> <center> <h2> Click "Show Comopnents" to choose which elements to add to your canvas. </h2> </center> <br /> <iframe title="another" src="https://giphy.com/embed/lPLOsVCKifFC19EImy" width="800" height="410" frameBorder="0" class="giphy-embed" allowFullScreen ></iframe> <center> <h4> After adding a component, fill out the form and click preview to see your element in action! </h4> </center> </div> ); }, }, { render: () => { return ( <div> <center> <h2> When you're happy with the way everything looks, save it to your projects page. </h2> </center> <br /> <iframe title="anotherrr" src="https://giphy.com/embed/hs1cB6r8dTkjPt3fGt" width="800" height="410" frameBorder="0" class="giphy-embed" allowFullScreen ></iframe> <center> <h4> Don't worry! You can always go back and edit your page later. PRO TIP: You can see what your page will look like live by toggling the preview button on and off! </h4> </center> </div> ); }, }, { render: () => { return ( <div> <center> <h2> Once your happy with your site, export it as an HTML file. </h2> </center> <br /> <iframe title="outro" src="https://giphy.com/embed/fxNXJQzuevhG04Hz3N" width="800" height="410" frameBorder="0" class="giphy-embed" allowFullScreen ></iframe> <center> <h4> Launch the download using your favorite Text Editor or directly in your web browser of choice, and see your site in action! </h4> </center> </div> ); }, }, { render: () => { return ( <div> <center> <h2> If you'd like, you can add navigation links to your header! </h2> </center> <br /> <iframe title="outro" src="https://giphy.com/embed/QzAdOIkZ9G0svTin0X" width="800" height="410" frameBorder="0" class="giphy-embed" allowFullScreen ></iframe> <center> <h4> To do this, change the div ID of the component you want the link to navigate to, and add that link to the 'navbars' section of the header in the format DivId1, DivId1 || DivId2, DivId2 || etc.... NOTE: Adding navlinks can only be done immediately before exporting. All navlinks will be cleared upon exit from that specific working space. </h4> </center> </div> ); }, }, ]; return ( <div id="navbar"> {this.props.auth.auth.uid ? ( <nav> <div> <Link id="mainHeader" className="navlink" to="/home"> {'<divlab />'} </Link> </div> <div> <Modal trigger={<Link className="navlink">TOUR</Link>}> <Modal.Header> <center>How to use {'<divlab />'}</center> </Modal.Header> <Modal.Content> <Carousel elements={elements} showNextPrev={true} showIndicators={false} /> </Modal.Content> </Modal> <Link id="newProject" className="navlink" to="/divlab" style={{ display: 'none' }} > NEW PROJECT </Link> <a id="allProjects" href="/projects" className="navlink" style={{ display: 'none' }} > {this.props.profile.initials} </a> <Link id="about" className="navlink" to="/about"> ABOUT </Link> <Dropdown className="navlink" text={this.props.profile.initials} floating labeled > <Dropdown.Menu> {this.profileItems.map(option => ( <Dropdown.Item key={option.key} {...option} /> ))} </Dropdown.Menu> </Dropdown> </div> </nav> ) : ( <nav> <div> <Link id="mainHeader" className="navlink" to="/home"> {'<divlab />'} </Link> </div> <div> <Modal trigger={<Link className="navlink">TOUR</Link>}> <Modal.Header>How to use {'<divlab />'}</Modal.Header> <Modal.Content> <Carousel elements={elements} showNextPrev={true} showIndicators={false} /> </Modal.Content> </Modal> <Link className="navlink" to="/divlab"> TRY IT </Link> <Link id="about" className="navlink" to="/about"> ABOUT </Link> <Link className="navlink" to="/signIn"> SIGN IN </Link> </div> </nav> )} </div> ); } } /** * CONTAINER */ const mapStateToProps = state => { return { auth: state.firebase, profile: state.firebase.profile, }; }; const mapDispatchToProps = dispatch => { return { signOut: () => { dispatch(signOut()); }, }; }; export default connect( mapStateToProps, mapDispatchToProps )(Navbar); /** * PROP TYPES */ <file_sep>import React from 'react'; export default function HeadshotComponent(props) { let { imageUrl } = props.info; // let divStyle = { // height: '100%', // width: '100%', // margin: '0px', // display: 'block' // }; return imageUrl.length ? ( <div className="divStyle" name="HeadshotComponent"> <span dangerouslySetInnerHTML={{ __html: '<!-- HeadshotSrcStart -->' }} /> <img alt="" src={imageUrl} /> <span dangerouslySetInnerHTML={{ __html: '<!-- HeadshotSrcEnd -->' }} /> </div> ) : ( <img alt="" src="images/HeadshotExample.png" /> ); } <file_sep>import history from '../history'; //inital state const initState = { authError: null, }; //constants const LOGIN_ERROR = 'LOGIN_ERROR'; const LOGIN_SUCCESS = 'LOGIN_SUCCESS'; const SIGN_OUT_SUCCESS = 'SIGN_OUT_SUCCESS'; const SIGN_UP_SUCCESS = 'SIGN_UP_SUCCESS'; const SIGN_UP_ERROR = 'SIGN_UP_ERROR'; //actions const loginError = error => ({ type: LOGIN_ERROR, error }); const loginSuccess = () => ({ type: LOGIN_SUCCESS }); const signOutSuccess = () => ({ type: SIGN_OUT_SUCCESS }); const signUpSuccess = () => ({ type: SIGN_UP_SUCCESS }); const signUpError = err => ({ type: SIGN_UP_ERROR, err }); //THUNKS export const signIn = credentials => async ( dispatch, getState, { getFirebase, getFirestore } ) => { try { const firebase = await getFirebase(); //this is the call that gets us access to firebase: await firebase .auth() .signInWithEmailAndPassword(credentials.email, credentials.password); dispatch(loginSuccess()); history.push('/projects'); } catch (err) { dispatch(loginError(err)); console.error(err); } }; export const signOut = () => async ( dispatch, getState, { getFirebase, getFirestore } ) => { try { const firebase = await getFirebase(); await firebase.auth().signOut(); dispatch(signOutSuccess()); history.push('/'); } catch (err) { console.error(err); } }; export const signUp = newUser => async ( dispatch, getState, { getFirebase, getFirestore } ) => { try { const firebase = await getFirebase(); const firestore = await getFirestore(); const response = await firebase .auth() .createUserWithEmailAndPassword(newUser.email, newUser.password); await firestore .collection('users') .doc(response.user.uid) .set({ firstName: newUser.firstName, lastName: newUser.lastName, initials: `<${newUser.firstName[0]}${newUser.lastName[0]} />`, }); dispatch(signUpSuccess()); history.push('/'); } catch (err) { dispatch(signUpError(err)); console.error(err); } }; //Reducer const authReducer = (state = initState, action) => { switch (action.type) { case LOGIN_ERROR: console.log('login error'); return { ...state, authError: 'Login failed. Please check your credentials and try again.', }; case LOGIN_SUCCESS: console.log('Login successful'); return { ...state, authError: null }; case SIGN_OUT_SUCCESS: console.log('Sign Out Success!'); return state; case SIGN_UP_SUCCESS: console.log('Sign Up Success!'); return { ...state, authError: null }; case SIGN_UP_ERROR: console.log('Sign Up Failed'); return { ...state, authError: action.err.message }; default: return state; } }; export default authReducer; <file_sep>import firebase from 'firebase/app'; import 'firebase/firestore'; import 'firebase/auth'; // Initialize Firebase var firebaseConfig = { apiKey: '<KEY>', authDomain: 'divlab.firebaseapp.com', databaseURL: 'https://divlab.firebaseio.com', projectId: 'divlab', storageBucket: 'divlab.appspot.com', messagingSenderId: '919221202248', appId: '1:919221202248:web:ffb4df2748747841', }; firebase.initializeApp(firebaseConfig); firebase.firestore(); export default firebase; <file_sep>import React from 'react'; export default function Paragraph(props) { let divStyle = { color: 'black', height: '100%', width: '100%', textAlign: 'left' }; const { content, id } = props.info; return content.length || id.length ? ( <div style={divStyle} id={id} name="ParagraphComponent"> <p dangerouslySetInnerHTML={{ __html: '<!-- ParagraphContentStart -->' }} /> <p>{content}</p> <p dangerouslySetInnerHTML={{ __html: '<!-- ParagraphContentEnd -->' }} /> </div> ) : ( <img alt="" src="images/ParagraphExample.png" /> ); } <file_sep># DivLab DivLab is full-stack web application for mocking up and building web applications. Divlab offers a sleek user interface and a great user experience with drag-and-drop integration. Users can quickly get started designing their projects without signing up. If users would like to save their progress and come back at a later time to edit their work, they can sign up and save their progress. Users are able to create multiple projects and go back to working on them any time. Once you are finished, users are able to export an HTML file with their project to their computer and view it on the browser. Visit [DivLab](https://divlab.herokuapp.com) to try us out! ## Table of Contents - [DivLab](#DivLab) - [Table of Contents](#Table-of-Contents) - [Download](#Download) - [Team](#Team) - [<NAME>](#Zachary-Resnick) - [<NAME>](#Joonho-Han) - [<NAME>](#Elliot-Gonzalez) - [Tech Stack](#Tech-Stack) - [React](#React) - [Redux](#Redux) - [Firebase](#Firebase) - [Firestore](#Firestore) - [HTML5 Drag and Drop](#HTML5-Drag-and-Drop) - [React-Grid-Layout](#React-Grid-Layout) - [Semantic UI React](#Semantic-UI-React) - [Tutorial](#Tutorial) - [Examples](#Examples) - [Available Scripts](#Available-Scripts) ## Download Step by step guide for downloading repo: ``` cd <directory you want to download to> git clone https://github.com/bowserdnd/divlab.git cd divlab npm install npm start Go to http://localhost:3000 to use DivLab! ``` ## Team ### `<NAME>` Github: https://github.com/ZResnick LinkedIn: https://www.linkedin.com/in/zachresnick1/ ### `<NAME>` Github: https://github.com/joonhojhan LinkedIn: https://www.linkedin.com/in/joonhojhan/ ### `<NAME>` Github: https://github.com/elliotgonzalez123 LinkedIn: https://www.linkedin.com/in/elliot-gonzalez-4b18534a/ ## Tech Stack Technologies used in this project: ### `React` https://reactjs.org/ - React is a JavaScript library for building user interfaces. - React will efficiently update and render only the components that need to be rerendered. - React is component-based and allows for each component to manage their own state. ### `Redux` https://redux.js.org/ - Redux is an open-source JavaScript library for state management. - Redux works together with React and Firestore to build complex user interfaces and retrieve data from the database, while easily managing state. ### `Firebase` https://firebase.google.com/ - Firebase is a mobile and web application development platform that offers a variety of services to help develop high-quality apps. - Firebase Authentication is used to allow users to sign in and keep their data unique. ### `Firestore` https://firebase.google.com/docs/firestore/ - Firestore is a flexible, scalable database for mobile, web, and server development from Firebase and Google Cloud Platform. - Firestore is a NoSQL database where data is stored in documents, and these documents are stored in collections. - Firestore keeps data in sync and keeps data up to date. ### `HTML5 Drag and Drop` https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API - HTML5 Drag and Drop interfaces enable applications to use drag-and-drop features in browsers. - By specifying draggable and droppable elements, users can easily select a draggable element and move it to a droppable element. - HTML5 Drag and Drop is used to move components into containers in the workspace. ### `React-Grid-Layout` https://github.com/STRML/react-grid-layout - React-Grid-Layout is a grid layout system for React. - React-Grid-Layout is responsive and supports breakpoints. Breakpoint layouts can be provided by the user or autogenerated. - React-Grid-Layout allows users to drag and resize containers in the workspace. ### `Semantic UI React` https://react.semantic-ui.com/ - Semantic UI React is the React integration for Semantic UI. - Semantic UI is a modern front-end development framework. Is offers a sleek and subtle design that provides a lightweight user experience. ## Tutorial After logging in, add a container or two to your canvas... You can add, resize, move, and delete these containers as you wish. ![tutorial1](https://media.giphy.com/media/Qz4snoMQSPhXDikptH/giphy.gif) Click "Show Comopnents" to choose which elements to add to your canvas. After adding a component, fill out the form and click preview to see your element in action! ![tutorial2](https://media.giphy.com/media/lPLOsVCKifFC19EImy/giphy.gif) When you're happy with the way everything looks, save it to your projects page. Don't worry! You can always go back and edit your page later. PRO TIP: You can see what your page will look like live by toggling the preview button on and off! ![tutorial3](https://media.giphy.com/media/hs1cB6r8dTkjPt3fGt/giphy.gif) Once your happy with your site, export it as an HTML file. Launch the download using your favorite Text Editor or directly in your web browser of choice, and see your site in action! ![tutorial4](https://media.giphy.com/media/fxNXJQzuevhG04Hz3N/giphy.gif) If you'd like, you can add navigation links to yoiur header! To do this, change the div ID of the component you want the link to navigate to, and add that link to the 'navbars' section of the header in the format DivId1, DivId1 || DivId2, DivId2 || etc.... NOTE: Adding navlinks can only be done immediately before exporting. All navlinks will be cleared upon exit from that specific working space. ![tutorial5](https://media.giphy.com/media/QzAdOIkZ9G0svTin0X/giphy.gif) ## Examples ![example2](https://github.com/bowserdnd/divlab/blob/master/public/images/example2.png) ![example1](https://github.com/bowserdnd/divlab/blob/master/public/images/example1.png) ## Available Scripts In the project directory, you can run: ### `npm start` Runs the app in the development mode.<br> Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.<br> You will also see any lint errors in the console. <!-- ### `npm test` Launches the test runner in the interactive watch mode.<br> See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. --> ### `npm run build` Builds the app for production to the `build` folder.<br> It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.<br> Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. <!-- ### `npm run eject` **Note: this is a one-way operation. Once you `eject`, you can’t go back!** If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). ### Code Splitting This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting ### Analyzing the Bundle Size This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size ### Making a Progressive Web App This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app ### Advanced Configuration This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration ### Deployment This section has moved here: https://facebook.github.io/create-react-app/docs/deployment ### `npm run build` fails to minify This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify --> <file_sep>import React from 'react'; import { Card, Image } from 'semantic-ui-react'; const CardComponent = props => { const { name, description, footer, caption, imageUrl } = props.info; return name.length || description.length || footer.length || caption.length || imageUrl.length ? ( <Card name="CardComponent"> <span dangerouslySetInnerHTML={{ __html: '<!-- CardImgStart -->' }} /> <Image src={imageUrl} wrapped ui={false} /> <span dangerouslySetInnerHTML={{ __html: '<!-- CardImgEnd -->' }} /> <Card.Content> <span dangerouslySetInnerHTML={{ __html: '<!-- CardHeaderStart -->' }} /> <Card.Header>{name}</Card.Header> <span dangerouslySetInnerHTML={{ __html: '<!-- CardHeaderEnd -->' }} /> <Card.Meta> <span dangerouslySetInnerHTML={{ __html: '<!-- CardCaptionStart -->' }} /> <span className="date">{caption}</span> <span dangerouslySetInnerHTML={{ __html: '<!-- CardCaptionEnd -->' }} /> </Card.Meta> <span dangerouslySetInnerHTML={{ __html: '<!-- CardDescriptionStart -->' }} /> <Card.Description>{description}</Card.Description> <span dangerouslySetInnerHTML={{ __html: '<!-- CardDescriptionEnd -->' }} /> </Card.Content> <span dangerouslySetInnerHTML={{ __html: '<!-- CardFooterStart -->' }} /> <Card.Content extra>{footer}</Card.Content> <span dangerouslySetInnerHTML={{ __html: '<!-- CardFooterEnd -->' }} /> </Card> ) : ( <div> <Image alt="" src="images/CardExample.png" /> </div> ); }; export default CardComponent;
b76bec8b6769de5c5af7440c2b9851a9c9052926
[ "JavaScript", "Markdown" ]
8
JavaScript
frontend210/divlab
856df6b6c9d28e5664907f0db591ba48a6786aca
48f9900d97fe908cee940ec13851a1c0521eb9df
refs/heads/master
<repo_name>Ruby-J/ruby-j.github.io<file_sep>/js/effect.js var i = 1; var textBox = document.getElementById("textbox"); var arrowDown = document.getElementById("arrow-down"); var arrowDownS = document.getElementById("arrow-down-shade"); /* Fade in/out textbox effect - NOTE: FIX*/ var myopacity = 0; function fadeInTransition() { if (myopacity<1) { myopacity += .05; setTimeout(function(){fadeInTransition()},100); } textBox.style.opacity = myopacity; } function fadeOutTransition() { if (myopacity>0) { myopacity -= .05; setTimeout(function(){fadeOutTransition()},100); } textBox.style.opacity = myopacity; } function hideTextBox() { textBox.style.display = "none"; arrowDown.style.display = "none"; arrowDownS.style.display = "none"; } fadeInTransition(); document.addEventListener('DOMContentLoaded',function(event){ var dataText = [ "Hey! You over there!", "If you're here, then that means you have nothing to do, right?", "Want to try something out? It won't hurt, I promise!", "Well first of all, who are you?", ""]; document.getElementById("textbox").addEventListener("click", advanceDialog); function advanceDialog() { //document.getElementById("textbox").style.color: "#F00"; if (arrowDown.style.display == "") { indexText += 1; StartTextAnimation(indexText); } } // keeps calling itself until the text is finished function typeWriter(text, i, fnCallback) { arrowDown.style.display = "none"; arrowDownS.style.display = "none"; // check if text isn't finished yet if (i < (text.length)) { // add next character to h1 textBox.innerHTML = text.substring(0, i+1) +'<span id="caret"></span>'; //for the cursor at end effect // wait for a while and call this function again for next character setTimeout(function() { typeWriter(text, i + 1, fnCallback) }, 50); } // text finished, call callback if there is a callback function else if (typeof fnCallback == 'function') { // call callback after timeout arrowDown.style.display=""; arrowDownS.style.display = ""; } } // start a typewriter animation for a text in the dataText array function StartTextAnimation(i) { // check if dataText[i] exists if (i < dataText[i].length) { // text exists! start typewriter animation typeWriter(dataText[i], 0, function(){ // after callback (and whole text has been animated), start next text StartTextAnimation(i + 1); }); } else if (dataText[i] == "") { fadeOutTransition(); setTimeout(hideTextBox, 2000); } } //starttextanimation StartTextAnimation(indexText); }); //typeWriter <file_sep>/js/function.js var love = 0; var flag_0001 = 0; var loveBar = document.getElementById('love-bar'); var generatorsButton = document.getElementById('generatorsButton'); var indexText = 0; /* var 'i' in the functions */ function makeLove(num) { if (num == 1) { love += 1 * level; } else { love += num; } document.getElementById("love_count").innerHTML = love.toFixed(1); } var generators = 0; var generatorCost; function computeGeneratorCost() { generatorCost = Math.floor(10 * Math.pow(1.1, generators)); } computeGeneratorCost(); var level = 1; var levelUpLove = 100; function computeLevelUpLove() { levelUpLove = Math.floor (100 * Math.pow (1.5, level)); } function updateLevel() { document.getElementById('level').innerHTML = level; } function buygenerator() { var generatorCost = Math.floor(10 * Math.pow(1.1,generators)); if(love >= generatorCost) { generators += 1; love -= generatorCost; document.getElementById('generators').innerHTML = generators; document.getElementById('love_count').innerHTML = love.toFixed(1); } var nextCost = Math.floor(10 * Math.pow(1.1,generators)); document.getElementById('generatorCost').innerHTML = nextCost; } function updateLoveBar(love) { var widthStr = (love * 100 / levelUpLove) + "%"; loveBar.style.width = widthStr; if (love >= levelUpLove) { love -= levelUpLove; level += 1; updateLevel(); computeLevelUpLove(); } } function checkBuyable() { computeGeneratorCost(); if (love >= generatorCost) { generatorsButton.disabled = false; } else if (love < generatorCost) { generatorsButton.disabled = true; } } function save() { var savefile = { love: love, generators: generators, level: level, indexText: indexText, flag_0001: flag_0001}; localStorage.setItem("savefile",JSON.stringify(savefile)); //ga('send', 'event', 'My Game', 'Save'); } window.setInterval(function(){ makeLove(generators*0.05); updateLoveBar(love); checkBuyable(); document.getElementById('toNextLvl').innerHTML = (levelUpLove - love).toFixed(1); }, 100); window.setInterval(function(){ save(); console.log("Autosaved!"); }, 30000); /* 60000 = 60s = 1 min */ function load() { var savegame = JSON.parse(localStorage.getItem("savefile")); if (typeof savegame.love !== "undefined") love = savegame.love; if (typeof savegame.generators !== "undefined") generators = savegame.generators; if (typeof savegame.level !== "undefined") level = savegame.level; if (typeof savegame.indexText !== "undefined") indexText = savegame.indexText; if (typeof savegame.flag_0001 !== "undefined") flag_0001 = savegame.flag_0001; computeGeneratorCost(); document.getElementById('generators').innerHTML = generators; document.getElementById('generatorCost').innerHTML = generatorCost; computeLevelUpLove(); updateLevel(); } load(); <file_sep>/js/event.js var divHate; function cacheDOMElements() { divHate = document.getElementById("divHate"); } cacheDOMElements(); if (flag_0001 === 0){ divHate.style.display = "none"; } else { divHate.style.display = ""; } <file_sep>/README.md # ruby-j.github.io <NAME>'s website and portfolio hosted on github.io.
6c49a9404236e0425c3a8ae98e08ce7b29ba1230
[ "JavaScript", "Markdown" ]
4
JavaScript
Ruby-J/ruby-j.github.io
3ff2146c051fb837839fc8e67ee3f451b4dd9398
b66fa02498fcbf62ef7da6f99b0a48f1ed93a28e
refs/heads/master
<file_sep>di-arena ======== This is a configurable tournament runner for Robocode (http://robocode.sourceforge.net/). <file_sep>#!/usr/bin/env python3 import sqlite3 import re import json import csv import sys from datetime import datetime class DBRecord: ''' instances of this class resemble a database record ''' def __init__(self, db_rec): for col in db_rec.keys(): setattr(self,col,db_rec[col]) def __str__(self): non_internal = re.compile(r'^[^_]') return '[{0} {1}]'.format( self.__class__.__name__, ' '.join( [ '{0}({1})'.format(attr,getattr(self,attr)) for attr in filter(non_internal.match,vars(self).keys()) ]), ) class Battle(DBRecord): def __init__(self, record, db): self.db = db self._robots = [] # <Robot> super().__init__(record) def addCompetitor( self, robot ): self._robots.append(robot) def getProperties( self ): return json.loads(self.Properties) def competitors( self ): ''' This returns a list of BattleData.Robot. ''' return self._robots def __str__(self): return '{0}\n {1}'.format( super().__str__(), '\n '.join(list(map(str,self._robots))), ) class Robot(DBRecord): def __init__(self, record, db): self.db = db super().__init__(record) class BattleDB: def __init__( self, db_file ): self.db_file = db_file self.conn = None self._debug = False def __del__( self ): if self.conn: self.conn.close() def __str__( self ): return '[BattleDB file({0})]'.format( self.db_file, ) def execute( self, *args ): if self._debug: print('[SQLITE3.EXECUTE]\n query: {0}\n params: {1}'.format(args[0],args[1])) return self.conn.execute(*args) def debug( self, state=None ): if state is None: self._debug = not self._debug else: self._debug = state print('Debug: {0}'.format(self._debug)) def connect( self ): if self.conn is not None: return self.conn = sqlite3.connect(self.db_file, # autocommit isolation_level = None) self.conn.row_factory = sqlite3.Row self.conn.execute(''' CREATE TABLE IF NOT EXISTS Robots ( RobotID INTEGER PRIMARY KEY, Name TEXT, LastUpdated Text ); ''') # State: scheduled,running,finished # Started/Finish: ISO timestamps # Obsolete: boolean self.conn.execute(''' CREATE TABLE IF NOT EXISTS Battles ( BattleID INTEGER PRIMARY KEY, Priority INTEGER, State TEXT, Started TEXT, Finished TEXT, Properties TEXT, Winner INTEGER, Obsolete INTEGER ); ''') # Score: -1 means no results # Results: stringified dict of properties self.conn.execute(''' CREATE TABLE IF NOT EXISTS BattleRobots ( BattleID INTEGER, RobotID INTEGER, RobotUpdated TEXT, Score INTEGER, Results TEXT, PRIMARY KEY(BattleID,RobotID) ); ''') # # Robots # def UpdateRobot( self, lastUpdated=None, name=None, id=None ): self.connect() if lastUpdated is None: lastUpdated = datetime.now().strftime('%Y-%m-%dT%H:%M:%S') elif lastUpdated.__class__ == datetime: lastUpdated = lastUpdated.strftime('%Y-%m-%dT%H:%M:%S') if id is None: if name is None: raise ValueError('UpdateRobot() cannot create new robot without a name') # ensure that names are unique error = None try: orig = self.GetRobot(name=name) error = ValueError('UpdateRobot() cannot create new robot with duplicate name ({0}): {1}'.format(name,orig)) except: # good pass else: # we couldn't throw this exception within the try clause raise error # new robot insert = self.conn.execute(''' INSERT INTO Robots (Name,LastUpdated) VALUES (?,?) ''', [name,lastUpdated]) return self.GetRobot(id=insert.lastrowid) else: # updated robot self.conn.execute(''' UPDATE Robots SET LastUpdated=? WHERE RobotID=? ''', [lastUpdated,id]) return self.GetRobot(id=id) def GetRobots( self ): self.connect() return [ Robot(record,self) for record in self.conn.execute('SELECT * FROM Robots').fetchall() ] def GetRobot( self, name=None, id=None ): if name is None and id is None: raise ValueError('GetRobot() called with neither name or id') self.connect() if id is not None: for record in self.conn.execute(''' SELECT * FROM Robots WHERE RobotID=? ; ''',[id]): return Robot(record,self) raise KeyError("GetRobot() no robot with ID '{0}' found".format(id)) if name is not None: for record in self.conn.execute(''' SELECT * FROM Robots WHERE Name=? ; ''',[name]): return Robot(record,self) raise KeyError("GetRobot() no robot with name '{0}' found".format(name)) def dump( self, ofile=sys.stdout, otype='json' ): ''' Dump the database contents. ''' self.connect() o_csv = csv.writer(ofile) for table in ['Robots','Battles','BattleRobots']: print('\n\nTABLE: {0}'.format(table),file=ofile) emitHeader = True for row in self.conn.execute('SELECT * FROM {0}'.format(table)): if otype == 'csv': if emitHeader: o_csv.writerow(row.keys()) emitHeader = False o_csv.writerow([row[k] for k in row.keys()]) elif otype == 'json': print(json.dumps({ k:row[k] for k in row.keys()}, sort_keys=True, indent=4), file=ofile) # # Battles # defaultProperties = { 'robocode.battleField.width':800, 'robocode.battleField.height':600, 'robocode.battle.numRounds':10, 'robocode.battle.gunCoolingRate':0.1, 'robocode.battle.rules.inactivityTime':450, 'robocode.battle.hideEnemyNames':True, } def getProperties( self ): return BattleDB.defaultProperties def ObsolesceBattles( self ): ''' Check each of the finished battles to see if any of the competitors has since been updated. ''' self.connect() self.conn.execute(''' UPDATE Battles SET Obsolete=1 WHERE BattleID IN ( SELECT BattleRobots.BattleID FROM BattleRobots INNER JOIN Robots ON BattleRobots.RobotID=Robots.RobotID WHERE Robots.LastUpdated > BattleRobots.RobotUpdated AND BattleRobots.RobotUpdated <> '' ) AND Obsolete=0 AND State='finished' ''',[]) def GetRobotFinishedBattles( self, robot, obsolete=False ): ''' (set obsolete to None to prevent selection by Obsolete) ''' return self.GetRobotBattles(robot,state=['finished'],obsolete=obsolete) def GetRobotRunningBattles( self, robot ): ''' ''' return self.GetRobotBattles(robot,state=['running'],obsolete=None) def GetRobotScheduledBattles( self, robot ): ''' ''' return self.GetRobotBattles(robot,state=['scheduled'],obsolete=None) def GetRobotObsoleteBattles( self, robot ): ''' ''' return self.GetRobotBattles(robot,obsolete=True) def GetRobotBattles( self, robot, state=None, obsolete=None ): ''' Return a list of BattleData.Battle objects for which <robot> is a competitor. ''' self.connect() if state is None: # don't select by state state = [] if robot.__class__ != Robot: # assume <robot> is the ID robot = self.GetRobot(id=robot) conditions = [ 'BattleID IN ( SELECT BattleID FROM BattleRobots WHERE RobotID=? )' ] parameters = [ robot.RobotID ] for s in state: conditions.append('State=?') parameters.append(s) if obsolete is not None: conditions.append('Obsolete={0}'.format( 1 if obsolete else 0 )) return [ self.GetBattle(record['BattleID']) for record in self.execute(''' SELECT BattleID FROM Battles WHERE {0} '''.format(' AND '.join(conditions)),parameters) ] # def GetBattleBetween( self, comps, obsolete=False ): # ''' # set obsolete to None in order not to use Obsolete as a selection criteria # ''' # joins = [] # conds = [] # for cmp_id in range(len(comps)): # if cmp_id == 0: # joins.append('INNER JOIN BattleRobots AS BR0 ON Battles.BattleID=BR0.BattleID') # else: # joins.append( # 'INNER JOIN BattleRobots AS BR{c_id} ON BR{p_id}.BattleID=BR{c_id}.BattleID'.format( # c_id = cmp_id, # p_id = cmp_id-1, # )) # conds.append('BR{0}.RobotID=?',cmp_id) # params.append(comps[cmp_id].RobotID) # return [ # GetBattle(record['BattleID'] # for record in self.execute(''' # SELECT BattleID # FROM Battles # {joins} # WHERE {conds} # '''.format( # joins = ' '.join(joins), # conds = ' AND '.join(conds), # ),params) # ] def GetRunningBattles(self): return self.GetBattles(State='running') def GetScheduledBattles(self): return self.GetBattles(State='scheduled') def GetFinishedBattles(self, nonObsolete=True): if nonObsolete: return self.GetBattles(State='finished',Obsolete=0) else: return self.GetBattles(State='finished') def GetObsoleteBattles(self): return self.GetBattles(Obsolete=1) def GetBattles( self, *sql_conditions, **conditions ): self.connect() # Construct the SQL query. query = ''' SELECT BattleID FROM Battles ''' params = [] if len(sql_conditions) + len(conditions) > 0: conds = list(sql_conditions) + \ list(map(lambda f:'{0}=?'.format(f),conditions.keys())) query += 'WHERE {0}'.format( ' AND '.join(conds) ) params = [ str(v) for v in conditions.values() ] if self._debug: print('Query: {0}\nParams: {1}'.format(query,params)) #DEBUG return [ self.GetBattle(record['BattleID']) for record in self.conn.execute(query,params) ] def GetBattle( self, id ): ''' Query and return the battle matching the specified ID from the DB. This method is the only one that adds the battle's competitors. Anything that returns a BattleData.Battle should use this. ''' self.connect() if id.__class__ == Battle: id = id.BattleID battle = None for record in self.conn.execute(''' SELECT * FROM Battles WHERE BattleID=? ; ''',[id]): battle = Battle(record,self) break else: raise KeyError("GetBattle() no Battle with ID '{0}' found".format(id)) for record in self.conn.execute(''' SELECT * FROM BattleRobots WHERE BattleID=? ; ''',[id]): battle.addCompetitor(self.GetRobot(id=record['RobotID'])) return battle def ScheduleBattle( self, competitors, properties=None ): if properties is None: properties = self.__class__.defaultProperties self.connect; # Create the battle insert = self.conn.execute(''' INSERT INTO Battles (State,Priority,Started,Finished,Properties,Winner,Obsolete) VALUES ('scheduled',-1,'','',?,-1,0) ; ''',[json.dumps(properties)]) battle_obj = self.GetBattle(insert.lastrowid) for robot in competitors: # allow ID's or Robots if robot.__class__ != Robot: robotID = robot robot = self.GetRobot(id=robotID) else: robotID = robot.RobotID self.conn.execute(''' INSERT INTO BattleRobots (BattleID,RobotID,RobotUpdated,Score,Results) VALUES (?,?,'',-1,'') ; ''',[battle_obj.BattleID,robot.RobotID]) return self.GetBattle(battle_obj.BattleID) class BattleAlreadyFinished(Exception): def __init__(self,battle): self.battle = battle def __str__(self): return 'The battle is already finished: {0}'.format(battle) class BattleAlreadyStarted(Exception): def __init__(self,battle): self.battle = battle def __str__(self): return 'The battle is already started: {0}'.format(battle) class BattleNotStarted(Exception): def __init__(self,battle): self.battle = battle def __str__(self): return 'The battle has not been started: {0}'.format(battle) def MarkBattleRunning( self, battle ): self.connect() # validate/normalize <battle> if battle.__class__ == Battle: # replace it with current data battle = self.GetBattle(battle.BattleID) else: # assume it's a BattleID battle = self.GetBattle(battle) # Verify that it isn't already running or finished if battle.Finished: raise BattleDB.BattleAlreadyFinished(battle) if battle.Started: raise BattleDB.BattleAlreadyStarted(battle) # Change the Battle.State self.conn.execute(''' UPDATE Battles SET State='running', Started=? WHERE BattleID=? ''',[ datetime.now().strftime('%Y-%m-%dT%H:%M:%S'), battle.BattleID ]) # Update the BattleRobot.RobotUpdated self.conn.execute(''' UPDATE BattleRobots SET RobotUpdated=( SELECT LastUpdated FROM Robots WHERE RobotID=BattleRobots.RobotID ) WHERE BattleID=? ''',[battle.BattleID]) def BattleCompleted( self, battle, battleData, resultData ): ''' <battle> is a BattleData.Battle object or a BattleID battleData is a dict of battle data ''' self.connect() # validate/normalize <battle> if battle.__class__ == Battle: # replace it with current data battle = self.GetBattle(battle.BattleID) else: # assume it's a BattleID battle = self.GetBattle(battle) # Verify that it isn't already running or finished if battle.Finished: raise BattleDB.BattleAlreadyFinished(battle) if battle.State != 'running': raise BattleDB.BattleNotStarted(battle) winner = None for robot in battle.competitors(): if robot.Name == battleData['Winner']: winner = robot.RobotID if winner is None: raise ValueError('No winner found ({0})'.format(battleData['Winner'])) # Change the Battle.State self.conn.execute(''' UPDATE Battles SET State='finished', Started=?, Finished=?, Winner=?, Properties=? WHERE BattleID=? ''',[battleData['Started'], battleData['Finished'], winner, battleData['Properties'], # these should be definitive battle.BattleID]) # Update the BattleRobot.RobotUpdated for robot in battle.competitors(): self.conn.execute(''' UPDATE BattleRobots SET Score=?, Results=? WHERE BattleID=? AND RobotID=? ''',[ resultData[robot.Name]['Score'], resultData[robot.Name]['Results'], battle.BattleID, robot.RobotID ]) <file_sep>#!/usr/bin/env python3 from BattleData import BattleDB from datetime import datetime import Robocode import random import os import os.path db_file = 't_battle_db.sqlite3' # always start clean if os.path.isfile(db_file): os.remove(db_file) bdata = BattleDB(db_file) for i in range(10): id = random.randint(0,59) name = 'nonex.TestRobot.{0:02d}'.format(id) bdata.UpdateRobot( lastUpdated = '2014-10-20T09:30:{0:02d}'.format(id), name = name, ) robots = bdata.GetRobots() # schedule a few battles battleCount = 5 for i in range(battleCount): comps = random.sample(robots,2) print('\n'.join(list(map(str,comps)))) battle = bdata.ScheduleBattle(comps) print(battle) # get all battles print('\n\n\n[TEST] GetBattles()...') all_battles = bdata.GetBattles() assert len(all_battles) == battleCount, \ 'GetBattles() returns incorrect number of battles: {0}!={1}\n{2}'.format( len(all_battles), all_battles, '\n'.join(list(map(str,all_battles)))) print('[TEST] Get all battles: OK') # mark one as running run_battle = random.choice(all_battles) bdata.MarkBattleRunning(run_battle) print("[RUNNING] {0}".format(run_battle)) running_battles = bdata.GetRunningBattles() assert len(running_battles) == 1, \ 'GetBattles(State=\'running\') returns incorrect number of battles: {0}!={1}\n{2}'.format( len(running_battles), running_battles, '\n'.join(list(map(str,running_battles)))) print('\n\n\n[TEST_RESULTS] OK') <file_sep>#!/usr/bin/env python3 import sys sys.path.append('..') import Robocode import os.path di_arena = os.path.abspath(os.path.realpath(os.path.join(os.path.dirname(__file__),'..','..','arena'))) robo_dir = os.path.abspath(os.path.realpath(os.path.join(os.path.dirname(__file__),'..','..','robocode'))) robo = Robocode.Robocode(di_arena,robo_dir) print(robo) print("\n\nName:") robot = robo.robot( name = 'jubjub_robofab.RandomRunner' ) print(robot) robot = robo.robot( name = 'sample.Crazy' ) print(robot) print("\n\nDescriptor:") robot = robo.robot(descriptor = os.path.join(robo.robots, 'jubjub_robofab', 'RandomRunner.robot')) print(robot) robot = robo.robot(descriptor = os.path.join(robo.robots, 'sample', 'Crazy.robot')) print(robot) print('\n\n[TEST_OK]') <file_sep>#!/usr/bin/env python3 ''' Attempt to schedule a number of battles, mark some as running, and complete others. The goal is to leave the database in a state to test some of the more complicated queries. ''' import sys sys.path.append('..') from Scheduler import Scheduler from BattleData import BattleDB import Robocode import random import argparse import os import os.path def build_cmdline(): parser = argparse.ArgumentParser() parser.add_argument('--seed',type=int,default=random.randint(0,1<<63-1)) parser.add_argument('--db',type=str,default='t_sched_db.sqlite3') return parser def init_robots( battledb, robocode ): robots = [ 'jubjub_robofab.RandomRunner', 'sample.Crazy', 'sample.Fire', 'sample.VelociRobot', 'sample.Tracker', ] for robotName in robots: robot = robo.robot( name = robotName ) battledb.UpdateRobot( name = robot.name, lastUpdated = robot.lastUpdated ) robots = battledb.GetRobots() return robots, { r.RobotID:r for r in robots } def main_objects( db_file ): # typical battledb = BattleDB(db_file) scheduler = Scheduler(db_file,None) di_arena = os.path.abspath(os.path.realpath(os.path.join(os.path.dirname(__file__),'..','..','arena'))) robo_dir = os.path.abspath(os.path.realpath(os.path.join(os.path.dirname(__file__),'..','..','robocode'))) robocode = Robocode.Robocode(di_arena,robo_dir) return robocode,battledb,scheduler def battleid( battle ): return battle.BattleID def comp_ids( comps ): return [ c.RobotID for c in comps ] def abbrBattles( sched_battles ): ''' sched_battles is a sequence of (<Robot>,<Robot>) ''' return [ '{0}-{1}'.format(min(a,b),max(a,b)) for a,b in sorted(list(map(comp_ids,sched_battles))) ] if __name__ == '__main__': cmdline = build_cmdline().parse_args() print("[RANDOM_SEED] {0}".format(cmdline.seed)) random.seed(cmdline.seed) print("[DATABASE] {0}".format(cmdline.db)) if os.path.isfile(cmdline.db): os.remove(cmdline.db) robo,bdata,sched = main_objects(cmdline.db) robots, d_robots = init_robots(bdata,robo) all_battles = list(sched.allBattles()) assert len(all_battles) == 10, 'Incorrect number of battles: {0}'.format(len(all_battles)) print(str(abbrBattles(all_battles))) necessary = list(sched.necessaryBattles()) assert len(all_battles) == len(necessary), \ 'Mismatch: all battles should be necessary\n All: {all}\n Necessary: {necc}'.format( all = abbrBattles(all_battles), necc = abbrBattles(necessary), ) # Run some random ones. num_torun = 3 to_run = random.sample(all_battles,num_torun) for comps in to_run: pass <file_sep>#!/usr/bin/env python3 import argparse import sqlite3 import sys import csv import json def build_cmdline(): parser = argparse.ArgumentParser( 'Run an arbitrary query against a SQLite3 database' ) parser.add_argument( 'db', type=str, help='the database to run the query against', ) parser.add_argument( '--query', '-q', type=str, required=True, help='the query to execute', ) outtype_group = parser.add_mutually_exclusive_group() outtype_group.add_argument( '--csv', action='store_const', const='csv', ) outtype_group.add_argument( '--json', action='store_const', const='json', ) return parser if __name__ == '__main__': cmdline = build_cmdline().parse_args() output_type = 'csv' if cmdline.csv: output_type = cmdline.csv elif cmdline.json: output_type = cmdline.json print('Output Type: {0}'.format(output_type),file=sys.stderr) print('DB: {0}\nQuery: {1}\n'.format(cmdline.db,cmdline.query,file=sys.stderr)) db = sqlite3.connect(cmdline.db) db.row_factory = sqlite3.Row header = None csv_out = None count = 0 if output_type == 'csv': csv_out = csv.writer(sys.stdout) for record in db.execute(cmdline.query): count += 1 if output_type == 'csv': if header is None: header = record.keys() csv_out.writerow(header) csv_out.writerow([record[k] for k in header]) elif output_type == 'json': print(json.dumps({k:record[k] for k in record.keys()}, indent=4, sort_keys=True)) else: raise Exception('Unknown output type {0}'.format(output_type)) print('\n{0} records returned.'.format(count),file=sys.stderr) <file_sep>#!/usr/bin/env python3 import sys sys.path.append('..') import sqlite3 from cpuinfo import cpuinfo # py-cpuinfo import socket import argparse import os,os.path,sys import itertools,random,re from datetime import datetime from BattleData import BattleDB import Robocode from BattleRunner import BattleRunner def build_cmdline(): parser = argparse.ArgumentParser( 'performance profiling of multiprocessing battles') parser.add_argument( '--db', type=str, default='performance.results.sqlite3', help='the database in which to record all information', ) parser.add_argument( '--output-directory', '-o', type=str, default='perf_output', help='the directory where output files should be stored', ) parser.add_argument( '--runs', '-r', type=int, default=30, help='the number of desired runs for each combination', ) parser.add_argument( '--max','-m', type=int, default=10, help='the maximum multiplier of the number of # workers to calculate the # battles', ) return parser class PerfDB: def __init__(self, db_file, desired_runs, max_multiplier=10): self.db_file = db_file self.desired_runs = desired_runs self.mmax = max_multiplier self.initDB() def initDB(self): self.conn = sqlite3.connect(self.db_file, # autocommit isolation_level = None) self.conn.row_factory = sqlite3.Row self.conn.execute(''' CREATE TABLE IF NOT EXISTS Runs ( RunID INTEGER PRIMARY KEY, CPUInfo TEXT, CPUCount INTEGER, Hostname TEXT, Workers INTEGER, BattleMultiplier INTEGER, RunStarted TEXT, RunFinished TEXT, DBFile TEXT ); ''') def nextRun( self ): ''' Decide which run should take place next. Return a (#workers,#battles,run #) tuple. ''' # See which combinations have the fewest runs. # If there are some, choose one of those at random. # Otherwise, choose a possible combination at random. this_cpu = cpuinfo.get_cpu_info()['brand'] max_cpu = int(cpuinfo.get_cpu_info()['count'] * 1.5) comb = tuple(itertools.product(range(1,max_cpu+1), range(1,self.mmax+1))) already_run = { '{0:04d}_{1:04d}'.format(w,m):0 for w,m in comb } #print(str(already_run)) for record in self.conn.execute(''' SELECT Workers,BattleMultiplier,COUNT(RunID) FROM Runs WHERE CPUInfo=? GROUP BY Workers,BattleMultiplier ''',[this_cpu]): #print('{0}'.format({ k:record[k] for k in record.keys()})) already_run['{0:04d}_{1:04d}'.format( record['Workers'],record['BattleMultiplier'])] = \ record['COUNT(RunID)'] #print(str(already_run)) fewest_runs = min(already_run.values()) if fewest_runs == self.desired_runs: raise StopIteration() need_run = tuple(filter(lambda k: already_run[k] == fewest_runs, already_run.keys())) # Choose a random scenario with fewer runs. if len(need_run) > 0: c = random.choice(need_run) return tuple(map(int,re.split(r'_',c))) + (fewest_runs+1,) # Otherwise, choose a random run. # c = random.choose(already_run.keys()) # return tuple(map(int,re.split(r'_',c))) + (fewest_runs+1,) def commitRun( self, run_data ): ''' Save the run data into the database. ''' cpu_info = cpuinfo.get_cpu_info() result = self.conn.execute(''' INSERT INTO Runs (CPUInfo,CPUCount,Hostname,Workers,BattleMultiplier, RunStarted,RunFinished,DBFile) VALUES (?,?,?,?,?,?,?,?) ''',[ cpu_info['brand'], cpu_info['count'], socket.gethostname(), run_data['Workers'], run_data['BattleMultiplier'], run_data['RunStarted'], run_data['RunFinished'], run_data['DBFile'], ]) def runScenario( num_workers, battle_mult, scen_db_file, perf_db ): num_battles = num_workers * battle_mult print('[SCENARIO] workers({workers}) battles({battles}) {db}'.format( workers = num_workers, battles = num_battles, db = scen_db_file, )) # This file is a scratch file. Delete it if it exists. if os.path.isdir(scen_db_file): os.remove(scen_db_file) battledb = BattleDB(scen_db_file) di_arena = os.path.abspath(os.path.realpath(os.path.join(os.path.dirname(__file__),'..','..','arena'))) robo_dir = os.path.abspath(os.path.realpath(os.path.join(os.path.dirname(__file__),'..','..','robocode'))) robo = Robocode.Robocode(di_arena,robo_dir) runner = BattleRunner(battledb,robo,num_workers) runner.start() # # Import/create the robots # robots = [ 'jubjub_robofab.RandomRunner', 'sample.Crazy', 'sample.Fire', 'sample.VelociRobot', 'sample.Tracker', 'sample.RamFire', 'sample.SittingDuck', 'sample.SpinBot', 'sample.TrackFire', 'sample.Walls', ] for robotName in robots: robot = robo.robot( name = robotName ) battledb.UpdateRobot( name = robot.name, lastUpdated = robot.lastUpdated ) robots = battledb.GetRobots() all_battles = list(itertools.combinations(battledb.GetRobots(),2)) # BattleData.Battle battles = [ battledb.ScheduleBattle(random.choice(all_battles)) for i in range(num_battles) ] # Robocode.Battle robo_battles = [ robo.battle(b.BattleID, list(map(lambda c:c.Name,b.competitors())), battledb.getProperties()) for b in battles ] # Run the battles. for battle in robo_battles: runner.submit(battle) runner.finish() # Record the run data. for rec in battledb.execute('SELECT MIN(Started) AS begin, MAX(Finished) as end FROM Battles'): start = datetime.strptime(rec['begin'],'%Y-%m-%dT%H:%M:%S') finish = datetime.strptime(rec['end'],'%Y-%m-%dT%H:%M:%S') elapsed = finish-start perf_db.commitRun({ 'Workers' : num_workers, 'BattleMultiplier' : battle_mult, 'RunStarted' : rec['begin'], 'RunFinished' : rec['end'], 'DBFile' : scen_db_file, }) print('[ELAPSED] {battles},{workers},{elapsed},{start},{finish}'.format( battles = len(battles), workers = workers, elapsed = elapsed.total_seconds(), start = start, finish = finish, )) if __name__ == '__main__': cmdline = build_cmdline().parse_args() db = PerfDB(cmdline.db, cmdline.runs, cmdline.max) print("Performance Test ({0})\nDesired Runs: {1}\nMax Multiplier: {2}".format(cmdline.db,cmdline.runs,cmdline.max)) if not os.path.isdir(cmdline.output_directory): os.makedirs(cmdline.output_directory) while True: try: workers,battle_mult,runIndex = db.nextRun() outdb = os.path.join(cmdline.output_directory, 'w{workers:04d}_m{mult:04d}_i{index:03d}.{hostname}.sqlite3'.format( workers = workers, mult = battle_mult, index = runIndex, hostname = socket.gethostname())) runScenario(workers,battle_mult,outdb,db) except StopIteration: # finished with all necessary scenarios. print("Finished with all desired runs.") break <file_sep>#!/usr/bin/env python3 import sys sys.path.append('..') from BattleRunner import BattleRunner from BattleData import BattleDB from datetime import datetime import time import Robocode import os, os.path import itertools import argparse import random def name( obj ): return obj.Name if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--workers',type=int,default=8) parser.add_argument('--battles',type=int,default=60) cmdline = parser.parse_args() workers = cmdline.workers num_battles =cmdline.battles db_file = 't_battlerunner.sqlite3' # always start clean if os.path.isfile(db_file): os.remove(db_file) bdata = BattleDB(db_file) di_arena = os.path.abspath(os.path.realpath(os.path.join(os.path.dirname(__file__),'..','..','arena'))) robo_dir = os.path.abspath(os.path.realpath(os.path.join(os.path.dirname(__file__),'..','..','robocode'))) robo = Robocode.Robocode(di_arena,robo_dir) runner = BattleRunner(bdata,robo,workers) runner.start() # # Import/create the robots # robots = [ 'jubjub_robofab.RandomRunner', 'sample.Crazy', 'sample.Fire', 'sample.VelociRobot', 'sample.Tracker', 'sample.RamFire', 'sample.SittingDuck', 'sample.SpinBot', 'sample.TrackFire', 'sample.Walls', ] for robotName in robots: robot = robo.robot( name = robotName ) bdata.UpdateRobot( name = robot.name, lastUpdated = robot.lastUpdated ) robots = bdata.GetRobots() d_robots = { r.RobotID:r for r in robots } all_battles = list(itertools.combinations(bdata.GetRobots(),2)) battles = [ # bdata.ScheduleBattle(comps) # for comps in all_battles bdata.ScheduleBattle(random.choice(all_battles)) for i in range(num_battles) ] d_battles = { b.BattleID:b for b in battles } print('Battles: {0}'.format(' '.join(['{0}:{1}'.format(b.BattleID, '-'.join([str(r.RobotID) for r in b.competitors()])) for b in d_battles.values()]))) robo_battles = [ robo.battle(b.BattleID,list(map(name,b.competitors())),bdata.getProperties()) for b in battles ] startTime = datetime.now() for battle in robo_battles: runner.submit(battle) runner.finish() print("[TIME] {0} battles ({2} workers) took {1}".format(len(battles),datetime.now()-startTime,workers)) # Attempt to get better performance numbers. for rec in bdata.execute('SELECT MIN(Started) AS begin, MAX(Finished) as end FROM Battles'): start = datetime.strptime(rec['begin'],'%Y-%m-%dT%H:%M:%S') finish = datetime.strptime(rec['end'],'%Y-%m-%dT%H:%M:%S') elapsed = finish-start print('[ELAPSED] {battles},{workers},{elapsed},{start},{finish}'.format( battles = len(battles), workers = workers, elapsed = elapsed.total_seconds(), start = start, finish = finish, )) <file_sep>#!/usr/bin/env python3 import sys sys.path.append('..') import Robocode import os.path di_arena = os.path.abspath(os.path.realpath(os.path.join(os.path.dirname(__file__),'..','..','arena'))) robo_dir = os.path.abspath(os.path.realpath(os.path.join(os.path.dirname(__file__),'..','..','robocode'))) robo = Robocode.Robocode(di_arena,robo_dir) print(robo) result = robo.result('test.result') print(result) <file_sep>#!/usr/bin/env python3 import sys sys.path.append('..') from BattleData import BattleDB import argparse parser = argparse.ArgumentParser() parser.add_argument('--csv',action='store_true') parser.add_argument('--json',action='store_true') parser.add_argument('db',type=str) cmdline = parser.parse_args() bdata = BattleDB(cmdline.db) if cmdline.json: bdata.dump(otype='json') else: bdata.dump(otype='csv') <file_sep>#!/usr/bin/env python3 ''' Monitor the robots directory and keep track of updated robots. Each robot is "described" by a text file name <name>.robot, which contains a list of binary dependencies. If any of these are updated, the robot is re-entered in the tournament. ''' from BattleData import BattleDB import re import os import os.path import time from datetime import datetime class _RobotDescr: def __init__( self, robotFile ): self.rfile = robotFile self.name = os.path.basename(os.path.splitext(self.rfile)[0]) rdir = os.path.dirname(self.rfile) with open(robotFile) as robotIn: self.deps = [ os.path.join(rdir,dep.strip()) for dep in robotIn ] self.lastUpdated = max([ os.stat(dep).st_mtime for dep in self.deps ]) def __str__(self): return '[{cls} File({rfile}) Name({name}) lastUpdated({updated})]\n {deps}'.format( cls = self.__class__, rfile = self.rfile, name = self.name, updated = datetime.fromtimestamp(self.lastUpdated), deps = '\n '.join([os.path.basename(dep) for dep in self.deps ]), ) class CompetitorMonitor: def __init__( self, robotDB ): self.db_file = robotDB def monitor( self, robotPath ): self.db = BattleDB(self.db_file) self.path = robotPath descr = re.compile(r'\.robot$',re.I) while True: for robot in [ _RobotDescr(os.path.join(self.path,rfile)) for rfile in filter(descr.search,os.listdir(self.path))]: print(robot) time.sleep(10) <file_sep>#!/usr/bin/env python3 from BattleData import * import argparse def build_cmdline(): parser = argparse.ArgumentParser( 'Add/Update robots in the database' ) <file_sep>#!/usr/bin/env python3 import multiprocessing from queue import Empty import subprocess import Robocode import os, os.path from datetime import datetime import sys import time # This class knows about Robocode and the Database. def recommendedWorkers(): cpus = multiprocessing.cpu_count() if cpus > 12: return cpus-2 elif cpus > 6: return cpus-1 else: return cpus def BattleWorker( robocode, battledb, job_q, result_q ): print('[{who}] Started:\n {db}\n {robo}'.format( who = multiprocessing.current_process().name, db = battledb, robo = robocode ), file=sys.stderr) try: while True: battle = job_q.get() if battle.__class__ != Robocode.Battle: # sentinel: no more jobs print('[{0}] EndOfWork!'.format( multiprocessing.current_process().name, ), file=sys.stderr) break start_time = datetime.now() try: battledb.MarkBattleRunning(battle.id) print('[{who}] Running battle {id} between: {comps}'.format( who = multiprocessing.current_process().name, id = battle.id, comps = ' '.join(battle.competitors), ), file=sys.stderr) battle.run() print('[{who}] Finished: {id}'.format( who = multiprocessing.current_process().name, id = battle.id, ), file=sys.stderr) except subprocess.CalledProcessError as e: print('[{who}] Battle invocation fails: {exc}\n{output}'.format( who = multiprocessing.current_process().name, exc = e.cmd, output = e.output, ), file=sys.stderr) if not battle.error: # Only record the data if the battle succeeded. battledb.BattleCompleted(battle.id, battle.dbData(), battle.result.dbData()) elapsed = datetime.now() - start_time result_q.put(battle.id) except Exception as e: print('[{who}] Exception: {exc}'.format( who = multiprocessing.current_process().name, exc = e, ), file=sys.stderr) raise e print('[{0}] Finished!'.format( multiprocessing.current_process().name, ), file=sys.stderr) class BattleRunner: def __init__( self, battledb, robocode, maxWorkers=None ): self.battledb = battledb self.robocode = robocode self.job_q = multiprocessing.JoinableQueue() self.result_q = multiprocessing.JoinableQueue() self.workers = maxWorkers if maxWorkers is not None else recommendedWorkers() self.job_count = 0 def start( self ): # Start the workers. self.pool = [ multiprocessing.Process( target = BattleWorker, args=(self.robocode, self.battledb, self.job_q, self.result_q) ) for i in range(self.workers) ] for p in self.pool: p.start() def finish( self ): print('[{0}] Sending EndOfWork signals'.format( multiprocessing.current_process().name, ), file=sys.stderr) for p in self.pool: self.job_q.put(0) # Consume everything in the result_q while self.job_count > 0: battleid = self.result_q.get() self.job_count -= 1 for p in self.pool: p.join() def submit( self, battle ): print('[{0}] Submitting battle #{1} '.format( multiprocessing.current_process().name, battle.id, ), file=sys.stderr) self.job_q.put(battle) self.job_count += 1 def running(self): ''' check to see if any of the workers are still running ''' for p in self.pool: if p.is_alive(): return True return False def getResults(self): ''' check to see if there are any results ''' results = [] try: results.append(self.result_q.get_nowait()) except Empty: pass return results <file_sep>#!/usr/bin/env python3 ''' Attempt to schedule a number of battles, mark some as running, and complete others. The goal is to leave the database in a state to test some of the more complicated queries. ''' import sys sys.path.append('..') from BattleData import BattleDB from datetime import datetime import Robocode import random import os import os.path def bdump(d,prefix='\n '): return prefix.join(list(map(str,[ b.BattleID for b in d.values() ]))) def query_test( battledb, robocode, k_battles, k_r_battles, scheduled, running, finished_nonobs, finished, obsolete ): # scheduled got_scheduled = battledb.GetScheduledBattles() d_got_scheduled = { b.BattleID:b for b in got_scheduled } assert comp(d_got_scheduled,scheduled), \ 'Mismatch: scheduled battles\n Got:\n {got}\n Expected:\n {exp}'.format( got = bdump(d_got_scheduled), exp = bdump(scheduled), ) # running got_running = battledb.GetRunningBattles() d_got_running = { b.BattleID:b for b in got_running } assert comp(d_got_running,running), \ 'Mismatch: running battles\n Got:\n {got}\n Expected:\n {exp}'.format( got = bdump(d_got_running), exp = bdump(running), ) # finished, non-obsolete got_finished_nonobs = battledb.GetFinishedBattles(nonObsolete=True) d_got_finished_nonobs = { b.BattleID:b for b in got_finished_nonobs } assert comp(d_got_finished_nonobs,finished_nonobs), \ 'Mismatch: finished, non-obsolete battles\n Got:\n {got}\n Expected:\n {exp}'.format( got = bdump(d_got_finished_nonobs), exp = bdump(finished_nonobs), ) # finished got_finished = battledb.GetFinishedBattles(nonObsolete = False) d_got_finished = { b.BattleID:b for b in got_finished } assert comp(d_got_finished,finished), \ 'Mismatch: finished battles\n Got:\n {got}\n Expected:\n {exp}'.format( got = bdump(d_got_finished), exp = bdump(running), ) # obsolete got_obsolete = battledb.GetObsoleteBattles() d_got_obsolete = { b.BattleID:b for b in got_obsolete } assert comp(d_got_obsolete,obsolete), \ 'Mismatch: obsolete battles\n Got:\n {got}\n Expected:\n {exp}'.format( got = bdump(d_got_obsolete), exp = bdump(running), ) def comp( a, b ): ''' Perform a comparison of keys (only) between the two dicts. ''' return set(a.keys()) == set(b.keys()) def diff( from_dict, del_dict ): ''' Return a shallow copy of from_dict with the items in del_dict removed. ''' ret = from_dict.copy() for k in del_dict.keys(): try: del(ret[k]) except KeyError: pass return ret def combine( a, b ): ''' Return a shallow copy of from_dict with the items in del_dict added. ''' ret = a.copy() for k,v in b.items(): ret[k] = v return ret db_file = 't_obs.sqlite3' # always start clean if os.path.isfile(db_file): os.remove(db_file) bdata = BattleDB(db_file) di_arena = os.path.abspath(os.path.realpath(os.path.join(os.path.dirname(__file__),'..','..','arena'))) robo_dir = os.path.abspath(os.path.realpath(os.path.join(os.path.dirname(__file__),'..','..','robocode'))) robo = Robocode.Robocode(di_arena,robo_dir) robots = [ 'jubjub_robofab.RandomRunner', 'sample.Crazy', 'sample.Fire', 'sample.VelociRobot', 'sample.Tracker', ] for robotName in robots: robot = robo.robot( name = robotName ) bdata.UpdateRobot( name = robot.name, lastUpdated = robot.lastUpdated ) robots = bdata.GetRobots() battles = [ bdata.ScheduleBattle((robots[0],robots[1])), bdata.ScheduleBattle((robots[2],robots[3])), bdata.ScheduleBattle((robots[4],robots[0])), ] d_battles = { b.BattleID:b for b in battles } robot_battles = { r.RobotID:[ b.BattleID for b in filter(lambda b: r.RobotID in [_r.RobotID for _r in b.competitors()], d_battles.values()) ] for r in robots } r_battles = { b.BattleID : robo.battle(b.BattleID, [c.Name for c in b.competitors()], b.getProperties()) for b in battles } # Query for scheduled, running, finished, and obsolete battles. query_test( bdata, robo, d_battles, r_battles, scheduled = d_battles, running = {}, finished_nonobs = {}, finished = {}, obsolete = {}, ) marked_only = { battles[b].BattleID:battles[b] for b in (1,) } torun = { battles[b].BattleID:battles[b] for b in (0,2) } # Choose a robot from one run battle to obsolesce. robot_to_obs = robots[1] to_obs = { battles[b].BattleID:battles[b] for b in (0,) } print("Mark Only: {0}".format(list(marked_only.keys()))) print("To Run: {0}".format(list(torun.keys()))) print("To Obs ({0}): {1}".format(robot_to_obs.RobotID,list(to_obs.keys()))) print('\nMarking battles...') for battle in marked_only.values(): bdata.MarkBattleRunning(battle) # Query for scheduled, running, finished, and obsolete battles. query_test( bdata, robo, d_battles, r_battles, scheduled = diff(d_battles,marked_only), running = marked_only, finished_nonobs = {}, finished = {}, obsolete = {}, ) print('\nRunning battles...') for battle in torun.values(): bdata.MarkBattleRunning(battle) # Query for scheduled, running, finished, and obsolete battles. query_test( bdata, robo, d_battles, r_battles, scheduled = diff(diff(d_battles,marked_only),torun), running = combine(marked_only,torun), finished_nonobs = {}, finished = {}, obsolete = {}, ) for battle in torun.values(): r_battle = r_battles[battle.BattleID] r_battle.run() print('.',end='') sys.stdout.flush() bdata.BattleCompleted(battle, r_battle.dbData(), r_battle.result.dbData()) print() # Query for scheduled, running, finished, and obsolete battles. query_test( bdata, robo, d_battles, r_battles, scheduled = diff(diff(d_battles,marked_only),torun), running = marked_only, finished_nonobs = torun, finished = torun, obsolete = {}, ) print('\n\nObsolescing battles for ({0}): {1}'.format(robot_to_obs.RobotID,list(to_obs.keys()))) print('Robot:\n{0}'.format(robot_to_obs)) bdata.UpdateRobot(lastUpdated=datetime.now(),id=robot_to_obs.RobotID) bdata.ObsolesceBattles() # Query for scheduled, running, finished, and obsolete battles. query_test( bdata, robo, d_battles, r_battles, scheduled = diff(diff(d_battles,marked_only),torun), running = marked_only, finished_nonobs = diff(torun,to_obs), finished = torun, obsolete = to_obs, ) print("\nAll queries return expected values.") <file_sep>#!/usr/bin/env python3 import RobotMonitor monitor = RobotMonitor.CompetitorMonitor('monitor.sqlite') monitor.monitor('robots') <file_sep>#!/usr/bin/env python3 import sys,os,os.path,shutil,traceback import subprocess import re import zipfile def detectJava( exe, version_re ): try: output = subprocess.check_output([exe,'-version'], stderr = subprocess.STDOUT) m = version_re.search(output.decode('utf-8')) if m is None: print('Cannot discern {0} version from output\n\'{1}\''.format( exe,output), file=sys.stderr) return False ver = m.group(1) print('{0} version {1}'.format(exe,ver)) javaPath = shutil.which(exe) if javaPath is None: # This really shouldn't happen. print('Cannot discern path to {0} executable.'.format(exe), file=sys.stderr) return False print('{0}: {1}'.format(exe,javaPath)) class JavaInfo: def __init__(self,path,version): self.path,self.version = path,version return JavaInfo(javaPath,ver) except FileNotFoundError: print('{0} is not in the PATH.'.format(exe), file=sys.stderr) return False except Exception as e: print('{0} detection failed: {1}'.format(exe,e), file=sys.stderr) raise e def installRobocode( javaPath ): print("Installing Robocode...") installDir = os.path.join(os.path.dirname(__file__),'..','robocode') if os.path.isdir(installDir): try: shutil.rmtree(installDir) except Exception as e: print('Error removing existing Robocode install dir: {0}'.format(e), file = sys.stderr) traceback.print_exc() return False installerDir = os.path.join(os.path.dirname(__file__),'..','install') installer_re = re.compile(r'^robocode.*-setup.jar$',re.I) for installer in sorted(filter(installer_re.search, os.listdir(installerDir)),reverse=True): print("Installing '{0}' to '{1}'".format(os.path.basename(installer), installDir)) try: archive = zipfile.ZipFile(os.path.join(installerDir,installer)) archive.extractall(path=installDir) return installDir except Exception as e: print('Error installing/extracting Robocode:\n', file=sys.stderr) traceback.print_exc() return False def copySampleRobots(roboDir,arenaDir): print("Copying sample robots into the arena...") sampleSrc = os.path.join(roboDir,'robots','sample') sampleDst = os.path.join(arenaDir,'robots','sample') if os.path.isdir(sampleDst): shutil.rmtree(sampleDst) return shutil.copytree(sampleSrc,sampleDst) def configureArena( roboDir ): arenaDir = os.path.abspath(os.path.realpath(os.path.join(os.path.dirname(__file__),'..','arena'))) for subdir in ('robots','battles','recordings','results'): path = os.path.join(arenaDir,subdir) if not os.path.isdir(path): print(' {0}'.format(subdir)) os.makedirs(path) if not copySampleRobots(roboDir,arenaDir): return False return arenaDir if __name__ == '__main__': # create any necessary directories # detect java # install robocode # copy the sample robots javaInfo = detectJava('java',re.compile(r'java version "([^"]+)"',re.I)) if not javaInfo: sys.exit(1) javacInfo = detectJava('javac',re.compile(r'javac (\S+)',re.I)) if not javacInfo: sys.exit(1) roboDir = installRobocode(javaInfo.path) if not roboDir: sys.exit(1) arenaDir = configureArena(roboDir) if not arenaDir: sys.exit(1) <file_sep>#!/usr/bin/env python3 ''' This is an interface into Robocode and its data. It knows nothing about any other classes. ''' import os import os.path import csv import json import re import sys from datetime import datetime import subprocess class Robocode: def __init__( self, arena_dir, robocode_dir, robots = 'robots', battles = 'battles', results = 'results', recordings = 'recordings', lib = 'libs', ): self.robocodeDir = robocode_dir self.arenaDir = arena_dir for prop,param in (('robots',robots), ('battles',battles), ('results',results), ('recordings',recordings)): if os.path.isdir(param): setattr(self,prop,param) else: setattr(self,prop,os.path.join(self.arenaDir,param)) self.lib = os.path.join(self.robocodeDir,lib) def __str__(self): return '[Robocode dir({robo_dir}) {nonstd}]'.format( robo_dir = self.robocodeDir, nonstd = ' '.join( [ '{0}({1})'.format(d,getattr(self,d)) for d in filter(lambda d:os.path.abspath(getattr(self,d)) != os.path.abspath(os.path.join(self.robocodeDir,d)), ('robots','battles','results','recordings','lib')) ]), ) def result( self, result_base ): ''' Read the contents of a results file. ''' if os.path.isfile(result_base): return Result(result_base) # Otherwise, assume it's in the system dir. return Result(os.path.join(self.results,result_base)) def robot( self, name=None, descriptor=None ): ''' Search the robot directory for the given robot. ''' if name is not None: return Robot(name,self.robots) elif descriptor is not None: # path to a descriptor file namePart = os.path.splitext(os.path.relpath(descriptor,self.robots))[0] return Robot('.'.join(namePart.split(os.sep)),self.robots) def battle( self, id, competitors, properties ): return Battle(self,id,competitors,properties) # # Robocode.RobotDescr # class RobotDescr: def __init__( self, robotFile ): self.rfile = robotFile self.name = os.path.basename(os.path.splitext(self.rfile)[0]) rdir = os.path.dirname(self.rfile) with open(robotFile) as robotIn: self.deps = [ dep.strip() for dep in robotIn ] self.deps = [ os.path.join(rdir,dep) for dep in self.deps if dep ] self.lastUpdated = \ datetime.fromtimestamp(max([ os.stat(dep).st_mtime for dep in self.deps ])) def __str__(self): return '[{cls} File({rfile}) Name({name}) lastUpdated({updated})]\n {deps}'.format( cls = self.__class__.__name__, rfile = self.rfile, name = self.name, updated = self.lastUpdated, deps = '\n '.join([os.path.basename(dep) for dep in self.deps ]), ) # # Robocode.Robot # class Robot: def __init__(self,robotBase,robotRoot): ''' robotBase is just a "name" (no extension, no dirs) ''' pieces = robotBase.split('.') # dirs in Java naming # look for .jar (not recursively) jar = os.path.join(robotRoot,robotBase+'.jar') jclass = os.path.join(robotRoot,*pieces)+'.class' if os.path.isfile(jar): self.path = jar ext = '.jar' elif os.path.isfile(jclass): self.path = jclass ext = '.class' else: raise FileNotFoundError(robotBase) self.name = robotBase self.descriptor = RobotDescr(os.path.splitext(self.path)[0] + '.robot') #print(str(self.descriptor)) # robocode.repository/src/main/java/net/sf/robocode/repository if ( ext == '.class' and not ( pieces[0] == 'tested' or pieces[0] == 'sample' ) ): self.development = True else: self.development = False self.lastUpdated = self.descriptor.lastUpdated def battleName( self ): return '{0}{1}'.format( self.name, '*' if self.development else '', ) def __str__(self): return '[Robot name({name}) develP({devel}) updated({updated}) path({path})]\n {deps}'.format( name = self.name, devel = self.development, updated = self.lastUpdated.strftime('%Y-%m-%dT%H:%M:%S'), path = self.path, deps = '\n '.join(self.descriptor.deps), ) # # Robocode.Result # class Result: _score = re.compile(r'^\s*(\d+)\s*\(\d+%\)\s*$') _place = re.compile(r'^(\d+)(?:st|nd|rd|th): .*$') _name = re.compile(r'^[^:]+: (.*)\*?$') _rounds = re.compile(r'Results for (\d+) round(?:s)?',re.I) def __init__( self, in_file ): self.robots = [] self.winner = '' self.rounds = 0 with open(in_file,'rt') as in_tab_file: meta_head = in_tab_file.readline() self.rounds = int(re.sub(Result._rounds,r'\1',meta_head)) header = re.split(r'\s*\t\s*',in_tab_file.readline()) in_tab = csv.DictReader( in_tab_file, fieldnames = header, delimiter = '\t' ) for row in in_tab: data = { k:row[k] for k in row.keys() } del(data['']) # strip the empty column data['_Score'] = re.sub(Result._score,r'\1',data['Total Score']) data['_Place'] = int(re.sub(Result._place,r'\1',data['Robot Name'])) # remove the 'devel' marker, if it exists data['_Name'] = re.sub(Result._name,r'\1',data['Robot Name']).rstrip('*') if data['_Place'] == 1: # remove the 'devel' marker, if it exists self.winner = data['_Name'].rstrip('*') self.robots.append(data) def __str__(self): return '[Result rounds({rounds}) winner({winner})]\n {robots}'.format( rounds = self.rounds, winner = self.winner, robots = '\n '.join(list(map(str,self.robots))), ) def dbData(self): ''' an interface between this object and the database Each DB field is a key in the returned dict. ''' # This is highly dependent on the DB schema. # BattleID INTEGER, # RobotID INTEGER, # RobotUpdated TEXT, # Score INTEGER, # Results TEXT, # PRIMARY KEY(BattleID,RobotID) return { r_data['_Name']: { 'Score' : r_data['_Score'], 'Results' : json.dumps(r_data, sort_keys=True), } for r_data in self.robots } # # Robocode.Battle # class Battle: robotProp = 'robocode.battle.selectedRobots' notOther = ( 'id', 'properties', 'competitors' ) def __init__( self, robocode, id, competitors, properties, **kwargs ): self.robocode = robocode # parent object (class Robocode) self.id = id self.competitors = competitors # robot names self.properties = properties self.battleFile = None # allow overriding def __str__( self ): return '[{cls} BattleID({id})]\n Properties:\n {props}\n Competitors:\n {comps}\n Other:\n {other}'.format( cls = self.__class__.__name__, id = self.id, comps = '\n '.join(self.competitors), props = '\n '.join([ '{0}={1}'.format(k,v) for k,v in self.properties.items() ]), other = '\n '.join( [ '{0}: {1}'.format(attr,getattr(self,attr)) for attr in filter(lambda p: p not in Battle.notOther, vars(self)) ]) ) def run( self ): ''' Run the battle. ''' self.createBattleFile() self.resultFile = os.path.join(self.robocode.results, '{0}.result'.format(self.id)) self.recordFile = os.path.join(self.robocode.recordings, '{0}.br'.format(self.id)) command = [ 'java', '-Xmx512M', # memory # This doesn't like quotes. I believe it tries to detect if it's an absolute # path or not, prepending the CWD if not. '-DROBOTPATH={0}'.format(self.robocode.robots), #'-DPARALLEL=true', # attempt parallelism '-cp', os.path.join(self.robocode.lib,'robocode.jar'), 'robocode.Robocode', '-cwd', self.robocode.robocodeDir, '-battle', self.battleFile, '-results', self.resultFile, '-record', self.recordFile, '-nodisplay', '-nosound', ] try: self.started = datetime.now() self.output = subprocess.check_output( command, stderr = subprocess.STDOUT, timeout = 60, ) self.finished = datetime.now() self.runTime = self.finished-self.started matches = re.search(r"Can't find '([^']+)\*?'", self.output.decode('ascii'),re.I) if matches: print("Missing Robot: {0}".format(matches.group(1)), file=sys.stderr) raise subprocess.CalledProcessError( 0, cmd=command, output=self.output) self.error = False self.result = self.robocode.result(self.resultFile) except subprocess.TimeoutExpired as e: # A timeout should not consider a valid battle run. self.runTime = datetime.now()-self.started self.finished = None self.error = True except subprocess.CalledProcessError as e: self.finished = datetime.now() self.runTime = self.finished-self.started self.error = True print('Battle returns error:\n{0}'.format(e.output.decode('ascii'))) raise e def createBattleFile( self ): self.battleFile = os.path.join(self.robocode.battles, '{0}.battle'.format(self.id)) with open(self.battleFile,'wt') as out_battle: for prop,value in self.properties.items(): print('{0}={1}'.format(prop,value), file=out_battle) # Competitors print('{0}={1}'.format( Battle.robotProp, ','.join([ Robot(r,self.robocode.robots).battleName() for r in self.competitors ]), ), file=out_battle) def dbData( self ): ''' an interface between this object and the database Each DB field is a key in the returned dict. ''' # This is highly dependent on the DB schema. # BattleID INTEGER PRIMARY KEY, # Priority INTEGER, # State TEXT, # Started TEXT, # Finished TEXT, # Properties TEXT, # Winner INTEGER, # Obsolete INTEGER return { 'BattleID' : self.id, 'Started' : self.started.strftime('%Y-%m-%dT%H:%M:%S'), 'Finished' : self.finished.strftime('%Y-%m-%dT%H:%M:%S'), 'Properties' : json.dumps(self.properties,sort_keys=True), 'Winner' : self.result.winner, } <file_sep>#!/usr/bin/env python3 import BattleData import itertools # Strategy: # 1. Get a list of all robots. # 2. For each entry in the job queue: # A. Decide which battles are the most important. # Score the robots # - number of scheduled battles # - not currently playing # - fewest non-obsolete battles # B. Choose a robot needing battles # C. Choose an opponent. # D. Schedule the battle. class Scheduler: def __init__( self, db_file, runner, **propertyOverrides ): self.db_file = db_file self.runner = runner self.battledb = BattleData.BattleDB(self.db_file) def necessaryBattles( self ): alreadyCompleted = self.battledb.GetFinishedBattles(nonObsolete=True) for comps in self.allBattles(): self.battledb.GetBattleBetween(comps) return filter(lambda b: b.BattleID not in alreadyCompleted, self.allBattles()) def allBattles( self ): return itertools.combinations(self.battledb.GetRobots(),2) def ScheduleBattle( comps ): return self.battledb.ScheduleBattle(comps) # property overrides <file_sep>#!/usr/bin/env python3 ''' Reporting tools. 1. List running battles. 2. List results by robot. 3. List leaderboard. ''' <file_sep>#!/usr/bin/env python3 from BattleData import * if __name__ == '__main__': bdb = BattleDB('test1.sqlite3') bdb.connect() <file_sep>#!/usr/bin/env python3 from BattleData import BattleDB from datetime import datetime bdata = BattleDB('t_robot_db.sqlite3') for i_id in range(3,10): stamp = datetime(2014,10,7,9,0,0) name = 'nonex.TestRobot' + str(i_id) try: i_robot = bdata.GetRobot(name=name) # robot exists print('Robot {0} exists: {1}'.format(name,i_robot)) except: print('New Robot') i_robot = bdata.UpdateRobot( lastUpdated = stamp.strftime('%Y-%m-%dT%H:%M:%S'), name = name, ) print(i_robot) print("updating robot") stamp = datetime.now() i_robot = bdata.UpdateRobot( lastUpdated = stamp.strftime('%Y-%m-%dT%H:%M:%S'), id = i_robot.RobotID, ) print(i_robot) print('\nAll Robots:\n {0}'.format('\n '.join(list(map(str,bdata.GetRobots()))))) print('\n\n[TEST_OK]') <file_sep>#!/usr/bin/env python3 import sys sys.path.append('..') from BattleData import BattleDB from datetime import datetime import Robocode import random import os import os.path db_file = 't_battle2_db.sqlite3' # always start clean if os.path.isfile(db_file): os.remove(db_file) bdata = BattleDB(db_file) arena_dir = os.path.realpath(os.path.join(os.path.dirname(__file__),'..','..','arena')) robocode_dir = os.path.realpath(os.path.join(os.path.dirname(__file__),'..','..','robocode')) robo = Robocode.Robocode(arena_dir,robocode_dir) print(robo) robots = [ 'jubjub_robofab.RandomRunner', 'sample.Crazy', 'sample.Fire', ] for robotName in robots: robot = robo.robot( name = robotName ) bdata.UpdateRobot( name = robot.name, lastUpdated = robot.lastUpdated ) robots = bdata.GetRobots() comps = random.sample(robots,2) battle = bdata.ScheduleBattle(comps) print('DB Object:\n{0}\n'.format(battle)) r_battle = robo.battle(battle.BattleID, [c.Name for c in comps], battle.getProperties()) print('Robocode Object:\n{0}\n'.format(r_battle)) print("\nPreparing to run battle...") bdata.MarkBattleRunning(battle) print(bdata.GetBattle(battle)) print("\nRunning battle...") try: r_battle.run() except Exception as e: print(e.cmd) print(e.output) print("finished") print(r_battle) print(r_battle.result) print('\nbattleDBData:\n {0}'.format('\n '.join([ '{0}: {1}'.format(k,v) for k,v in r_battle.dbData().items() ]))) print('\nresultDBData:\n {0}'.format('\n '.join([ '{0}: {1}'.format(k,v) for k,v in r_battle.result.dbData().items() ]))) print("\nCompleting battle...") bdata.BattleCompleted(battle, r_battle.dbData(), r_battle.result.dbData()) print(bdata.GetBattle(battle))
7d72587c1930f756dee71c2e1500a34ec84d094b
[ "Markdown", "Python" ]
22
Markdown
mojomojomojo/di-arena
3ef0ee2a9c0358bec98653f09942ae9cc35a48d4
0ecb38d411dd11940a504f23d34552304c8d0f08
refs/heads/master
<repo_name>SylNeves/Iocastelogin<file_sep>/build.xml <project name="iocaste-login" default="compile"> <property name="targetdir-pages" value="${basedir}/bin/pages"/> <property name="targetdir-web" value="${basedir}/bin/WEB-INF"/> <property name="targetdir-classes" value="${basedir}/bin-classes"/> <property name="targetdir-common" value="${basedir}/bin-common"/> <property name="builddir" value="${basedir}/build"/> <target name="clean"> <delete dir="${builddir}"/> </target> <target name="compile" depends="clean"> <copy todir="${builddir}/WEB-INF"> <fileset dir="${targetdir-web}"/> </copy> <copy todir="${builddir}/WEB-INF/classes"> <fileset dir="${targetdir-classes}"/> </copy> <copy todir="${builddir}"> <fileset dir="${targetdir-pages}"/> </copy> <copy todir="${builddir}/WEB-INF/lib/" file="../iocaste/iocaste-common.jar"/> <war basedir="${builddir}" destfile="${basedir}/${ant.project.name}.war"/> <delete dir="${builddir}"/> </target> </project><file_sep>/WEB-INF/classes/org/iocaste/login/LoginServlet.java package org.iocaste.login; import org.iocaste.protocol.ClientServlet; import org.iocaste.protocol.Iocaste; public class LoginServlet extends ClientServlet { private static final long serialVersionUID = 1946889529842250472L; @Override protected void init(Iocaste iocaste) throws Exception { String usuario = getValue("usuario").toUpperCase(); String senha = getValue("<PASSWORD>"); if (iocaste.login(usuario, senha)== true) { redirect("/iocaste-session/pagina1.html"); } else { redirect("erro.html"); } } }
d21d63bf237763fa6cd9c3f934e8fb32bb12835c
[ "Java", "Ant Build System" ]
2
Ant Build System
SylNeves/Iocastelogin
c076d24706cdbf98978ccfc4cca62f10a3a44c4f
ecd6adcdb563830331cd01e76e72a76898c174ba
refs/heads/master
<file_sep>## PHP import CSV to mysql <file_sep><?php //load the database configuration file include 'db/dbConfig.php'; if(!empty($_GET['status'])){ switch($_GET['status']){ case 'succ': $statusMsgClass = 'alert-success'; $statusMsg = 'Truck data has been inserted successfully.'; break; case 'err': $statusMsgClass = 'alert-danger'; $statusMsg = 'Some problem occurred, please try again.'; break; case 'invalid_file': $statusMsgClass = 'alert-danger'; $statusMsg = 'Please upload a valid CSV file.'; break; default: $statusMsgClass = ''; $statusMsg = ''; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Truck Data CSV Import</title> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container" style="margin-top: 30px;"> <?php if(!empty($statusMsg)){ echo '<div class="alert '.$statusMsgClass.'">'.$statusMsg.'</div>'; } ?> <div class="panel panel-info"> <div class="panel-heading"> Trucks </div> <div class="panel-body"> <form action="db/importData.php" method="post" enctype="multipart/form-data" id="importFrm" style="margin-bottom: 20px;"> <div class="row"> <div class="col-sm-6"> <label for="file">CSV file</label> <div class="input-group"> <input type="file" name="file" class="form-control" placeholder="CSV file" /> <span class="input-group-btn"> <input type="submit" class="btn btn-primary" name="importSubmit" value="IMPORT"> </span> </div> </div> <div class="col-sm-3 col-sm-offset-3"> <?php if (isset($_GET['ajax'])) { echo $_GET['myString']; } else { ?> <button id="exportData" name="export" class="btn btn-default" type="button"> Export <?php echo $table; ?> data CSV </button> <pre id="data"></pre> <?php } ?> </div> </div> </form> <table class="table table-bordered"> <thead> <tr> <th>Year</th> <th>Cab</th> <th>Engine</th> <th>Wheel Base</th> <th>Drive Train</th> <th>FGAWR</th> <th>GVWR</th> <th>Rear Wheel</th> <th>Bed</th> <th>Trim Pkg</th> <th>Headlamp</th> <th>Plow Model</th> <th>Subframe</th> <th>Mount Kit</th> <th>Center Member</th> <th>Note 1</th> <!-- <th>Note 2</th> --> <!-- <th>Note 3</th> <th>Note 4</th> <th>Note 5</th> <th>Note 6</th> <th>Note 7</th> <th>Note 8</th> <th>Note 9</th> <th>Note 10</th> --> </tr> </thead> <tbody> <?php // get records from database $query = $conn->query("SELECT * FROM TRUCKS ORDER BY id DESC"); if ($query->num_rows > 0) { while($row = $query->fetch_assoc()){ ?> <tr> <td><?php echo $row['year']; ?></td> <td><?php echo $row['cab']; ?></td> <td><?php echo $row['engine']; ?></td> <td><?php echo $row['wheel_base']; ?></td> <td><?php echo $row['drive_train']; ?></td> <td><?php echo $row['fgawr']; ?></td> <td><?php echo $row['gvwr']; ?></td> <td><?php echo $row['rear_wheel']; ?></td> <td><?php echo $row['bed']; ?></td> <td><?php echo $row['trim_pkg']; ?></td> <td><?php echo $row['headlamp']; ?></td> <td><?php echo $row['plow_model']; ?></td> <td><?php echo $row['subframe']; ?></td> <td><?php echo $row['mount_kit']; ?></td> <td><?php echo $row['center_member']; ?></td> <td><?php echo $row['note_1']; ?></td> <?php /* <td><?php echo $row['note 2']; ?></td> <td><?php echo $row['note 3']; ?></td> <td><?php echo $row['note 4']; ?></td> <td><?php echo $row['note 5']; ?></td> <td><?php echo $row['note 6']; ?></td> <td><?php echo $row['note 7']; ?></td> <td><?php echo $row['note 8']; ?></td> <td><?php echo $row['note 9']; ?></td> <td><?php echo $row['note 10']; ?></td> */ ?> </tr> <?php } } else { ?> <tr><td colspan="5">No trucks(s) found.....</td></tr> <?php } ?> </tbody> </table> </div> </div> </div> <script type="text/javascript"> var scriptString = 'THIS IS MY JS STRING'; $('#exportData').click(function(){ $.ajax({ method: 'post', url: 'db/exportData.php', // data: { // 'myString': scriptString, // 'ajax': true // }, success: function(data) { $('#data').text(data); console.log('CSV exported!') } }); }); </script> </body> </html> <file_sep><?php //load the database configuration file include 'dbConfig.php'; if(isset($_POST['importSubmit'])){ //validate whether uploaded file is a csv file $csvMimes = array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain'); if( !empty($_FILES['file']['name']) && in_array($_FILES['file']['type'], $csvMimes) ){ if(is_uploaded_file($_FILES['file']['tmp_name'])){ //open uploaded csv file with read only mode $csvFile = fopen($_FILES['file']['tmp_name'], 'r'); //skip first line fgetcsv($csvFile); // parse data from csv file line by line while(($line = fgetcsv($csvFile)) !== FALSE){ $year = $line[0]; $cab = $line[1]; $engine = $line[2]; $wheel_base = $line[3]; $drive_train = $line[4]; $fgawr = $line[5]; $gvwr = $line[6]; $rear_wheel = $line[7]; $bed = $line[8]; $trim_pkg = $line[9]; $headlamp = $line[10]; $plow_model = addslashes($line[11]); $subframe = addslashes($line[12]); $mount_kit = addslashes($line[13]); $center_member = addslashes($line[14]); $note_1 = addslashes($line[15]); $note_2 = addslashes($line[16]); $note_3 = addslashes($line[17]); $note_4 = addslashes($line[18]); $note_5 = addslashes($line[19]); $note_6 = addslashes($line[20]); $note_7 = addslashes($line[21]); $note_8 = addslashes($line[22]); $note_9 = addslashes($line[23]); $note_10 = addslashes($line[24]); // check whether truck already exists in database with same email // $prevQuery = "SELECT id FROM $table WHERE cab = '". $line[1] ."'"; // $prevResult = $conn->query($prevQuery); // if ($prevResult->num_rows > 0) { // //update truck data // $conn->query("UPDATE $table SET name = '".$line[0]."', phone = '".$line[2]."', created = '".$line[3]."', modified = '".$line[3]."', status = '".$line[4]."' WHERE email = '".$line[1]."'"); // echo "update truck data"; // die(); // } else { //insert truck data into database $conn->query("INSERT INTO $table (year, cab, engine, wheel_base, drive_train, fgawr, gvwr, rear_wheel, bed, trim_pkg, headlamp, plow_model, subframe, mount_kit, center_member, note_1, note_2, note_3, note_4, note_5, note_6, note_7, note_8, note_9, note_10) VALUES ('$year', '$cab', '$engine', '$wheel_base', '$drive_train', '$fgawr', '$gvwr', '$rear_wheel', '$bed', '$trim_pkg', '$headlamp', '$plow_model', '$subframe', '$mount_kit', '$center_member', '$note_1', '$note_2', '$note_3', '$note_4', '$note_5', '$note_6', '$note_7', '$note_8', '$note_9', '$note_10')"); // } } //close opened csv file fclose($csvFile); $qstring = '?status=succ'; } else { $qstring = '?status=err'; } } else { $qstring = '?status=invalid_file'; } } //redirect to the listing page header("Location: ../index.php" . $qstring); <file_sep><?php include 'dbConfig.php'; header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename=data.csv'); // $output = fopen("php://output", "w"); $output = fopen("truckdata_export.csv", "w"); fputcsv($output, array('year', 'cab', 'engine', 'wheel_base', 'drive_train', 'fgawr', 'gvwr', 'rear_wheel', 'bed', 'trim_pkg', 'headlamp', 'plow_model', 'subframe', 'mount_kit', 'center_member', 'note_1', 'note_2', 'note_3', 'note_4', 'note_5', 'note_6', 'note_7', 'note_8', 'note_9', 'note_10')); $query = "SELECT * from TRUCKS"; //ORDER BY emp_id DESC"; $result = mysqli_query($conn, $query); while($row = mysqli_fetch_assoc($result)) { fputcsv($output, $row); } fclose($output); ?>
a816182d437c5f09a04749f1c13a8e14fd3445db
[ "Markdown", "PHP" ]
4
Markdown
8ctopotamus/php-csv-mysqli
c6914189ae6aab6e35d3777ec0d3d60fc0e5eb9e
e901e20083f04a7d33d755434f0adde63630cdde
refs/heads/master
<repo_name>sravenscraft/b3-interior<file_sep>/readme.txt b3-interior This is the git repository for the B3 interior page development. <file_sep>/js/nav-hover.js <script> $('ul.nav li li').hover( function() { $(this).find('ul.multilevel-linkul-0').stop(true, true).delay(50).fadeIn(250);}, function() { $(this).find('ul.multilevel-linkul-0').stop(true, true).delay(50).fadeOut(100); }); </script>
9cf0ffc03ed39da19f8e2f02fc2db04dead25ced
[ "JavaScript", "Text" ]
2
Text
sravenscraft/b3-interior
a08c0650d04d59673aa4d6eacc4bd211b1d1b9cb
190194ed91710241e866a24bc7d28681fd73cd3d
refs/heads/master
<repo_name>guilhermeeuzebio/agenda-do-busao<file_sep>/app/src/main/java/coletivo/com/agenda/Calendario.java package coletivo.com.agenda; import android.provider.CalendarContract; /** * Created by root on 16/06/17. */ public class Calendario { } <file_sep>/app/src/main/java/coletivo/com/agenda/MainActivity.java package coletivo.com.agenda; import android.app.PendingIntent; import android.content.Intent; import android.provider.CalendarContract; import android.provider.SyncStateContract; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.Calendar; import WebService.Data; import WebService.RetornoWSTempoReal; import WebService.RetornoWSTempoRealConverter; import WebService.WebServiceMarechal; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import static coletivo.com.agenda.R.layout.activity_maps; public class MainActivity extends AppCompatActivity { private EditText txtLinha; private Data[] dados; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(RetornoWSTempoReal.class, new RetornoWSTempoRealConverter()); Gson gson = gsonBuilder.create(); Retrofit retrofit = new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create(gson)) .baseUrl(WebServiceMarechal.URL_WEBSERVICE_MARECHAL) .build(); final WebServiceMarechal service = retrofit.create(WebServiceMarechal.class); final Call<RetornoWSTempoReal> request = service.getTempoReal(); request.enqueue(new Callback<RetornoWSTempoReal>() { @Override public void onResponse(Call<RetornoWSTempoReal> call, Response<RetornoWSTempoReal> response) { dados = response.body().getData(); } @Override public void onFailure(Call<RetornoWSTempoReal> call, Throwable t) { Log.d(Constants.PACKAGE_NAME, "falha ao recuperar webservice" + t.getLocalizedMessage()); t.printStackTrace(); } }); txtLinha = (EditText) findViewById(R.id.txtLinha); } public void agenda(){ Calendar beginTime = Calendar.getInstance(); beginTime.set(2017,6,17,6,30); Calendar endTime = Calendar.getInstance(); endTime.set(2017,6,17,6,30); Intent intent = new Intent(Intent.ACTION_INSERT) .setData(CalendarContract.Events.CONTENT_URI) .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis()) .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime.getTimeInMillis()) .putExtra(CalendarContract.Events.TITLE, "Linha 355.1") .putExtra(CalendarContract.Events.EVENT_LOCATION, "Parada de onibus") .putExtra(CalendarContract.Events.AVAILABILITY, CalendarContract.Events.AVAILABILITY_FREE); startActivity(intent); } public void entrar(View view){ setContentView(R.layout.pesquisa_linha); } public void agendar(View view){ setContentView(R.layout.config_agenda); } public void calendario(View view){ agenda(); } public void pesquisar(View view) { //esta parando o APP for (Data d : dados) { if (d!=null) if (d.getDataHora().equals(txtLinha)) { // TextView horario = (TextView)findViewById(R.id.horarios); // horario.setText(d.getDataHora()); } } } public void mapa (View view){ Intent it = new Intent(this,MapsActivity.class); startActivity(it); } } <file_sep>/app/src/main/java/com/agenda/Linha.java package com.agenda; import java.util.List; import retrofit2.Call; /** * Created by root on 15/06/17. */ public class Linha { public List<Data> DATA; } <file_sep>/app/src/main/java/WebService/Data.java package WebService; /** * Created by rogerio on 6/15/17. */ public class Data { private String dataHora; private String ordem; private String linha; private double latitude; private double longitude; private int velocidade; public String getDataHora() { return dataHora; } public String getOrdem() { return ordem; } public void setOrdem(String ordem) { this.ordem = ordem; } public String getLinha() { return linha; } public void setLinha(String linha) { this.linha = linha; } public void setDataHora(String dataHora) { this.dataHora = dataHora; } public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } public int getVelocidade() { return velocidade; } public void setVelocidade(int velocidade) { this.velocidade = velocidade; } }<file_sep>/app/src/main/java/coletivo/com/agenda/Constants.java package coletivo.com.agenda; /** * Created by root on 15/06/17. */ public class Constants { public static final String PACKAGE_NAME = "coletivo.com.agenda"; }
c884a1c976625a3f9de01bb3fa92c3052493210f
[ "Java" ]
5
Java
guilhermeeuzebio/agenda-do-busao
7baf22e3cd3708c5c69ab6870b339f2a88072a7a
3f23d9415d8f9cf779f25d79bb3951c6cb881d41
refs/heads/master
<repo_name>yurenxj1982/JohnXu-python-practice<file_sep>/practice-from-ProgrammingProjectList/practice_002/port-scan.py #! /usr/bin/env python3 # -*- coding: utf-8 -*- r''' 项目来源自https://github.com/jobbole/ProgrammingProjectList.git 题目: 端口扫描器 $ python3 port-scan.py -h usage: port-scan.py [-h] [-a ADDRESS] [-s START_PORT] [-e END_PORT] scan which ports listening optional arguments: -h, --help show this help message and exit -a ADDRESS, --address ADDRESS address -s START_PORT, --start-port START_PORT scan start port -e END_PORT, --end-port END_PORT scan end port ''' import argparse import asyncio import socket from concurrent.futures import ThreadPoolExecutor import time now = lambda : time.time() def test_connect(address, port): r''' Corroutine func to test address:port can connect ''' ret = False with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: try: s.connect((address, port)) ret = True except OSError as err: ret = False return (address, port, ret) def scan_machine(address, start, end, concurrents=100): r''' scan machine ''' with ThreadPoolExecutor(max_workers=concurrents) as executor: tasks = [] loop = asyncio.get_event_loop() for port in range(start, end): future = loop.run_in_executor(executor, test_connect, address, port) task = asyncio.ensure_future(future) tasks.append(task) tasks_future = asyncio.wait(tasks) finished_futures, _ = loop.run_until_complete(tasks_future) loop.close() return sorted([future.result() for future in finished_futures]) if __name__ == "__main__": parser = argparse.ArgumentParser(description="scan which ports listening") parser.add_argument("-a", "--address", type=str, help="address") parser.add_argument("-s", "--start-port", type=int, help="scan start port") parser.add_argument("-e", "--end-port", type=int, help="scan end port") params = parser.parse_args() address, start, end = params.address, params.start_port, params.end_port + 1 start_time = now() results = scan_machine(address, start, end) use_time = now() - start_time for address, port, result in results: if result: print("{}:{} opend".format(address, port)) print("use {}s".format(use_time)) <file_sep>/practice-from-ProgrammingProjectList/practice_001/revert-string.py #! /usr/bin/env python3 # -*- coding: utf-8 -*- r''' 项目来源自https://github.com/jobbole/ProgrammingProjectList.git 题目:逆转字符串 使用方法: revert-string [-h|--help] string ''' import argparse if __name__ == "__main__": parser = argparse.ArgumentParser(description='Revert the string') parser.add_argument('string', metavar='string', type=str, help='the string will be reverted') namespace = parser.parse_args() print(namespace.string[-1::-1]) <file_sep>/practice_001-poker_dealer/poker-dealer.py #! /usr/bin/env python3 # -*- coding: utf-8 -*- r''' 这是一个随机发牌程序的练习 问题描述: 1) 程序的使用方法: $ poker-dealer [-h | --help] [-p|--players players] [--without-joker] -p --players how many player, default is 4 --with[out]-joker enable joker, default is --with-joker -h show this 目的: 熟悉随机函数 熟悉Enum的使用 熟悉命令行getopt操作 ''' from enum import Enum import random def usage(name): ''' print usage ''' helpstr = '''usage: {0} [-h | --help] [-p|--players players] [--without-joker] -p --players how many player, default is 4 --without-joker without joker -h --help show this '''.format(name) print(helpstr) Pointer = Enum( 'Pointer', ['Joker', 'A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'], module=__name__ ) Color = Enum( 'Color', ['Black', 'Color', 'Spade', 'Heart', 'Diamond', 'Club'], module=__name__ ) class PokerCard(object): r''' Poker Card ''' def __init__(self, pointer, color): self.pointer = pointer self.color = color def __repr__(self): return "{0}:{1}".format(self.color.name, self.pointer.name) class PokerFactory(object): r''' The Poker Factory ''' def __init__(self, enable_joker=True): r''' PokerFactory __init__ ''' self.cards = [PokerCard(x, y) for x in list(Pointer)[1:] for y in list(Color)[2:]] if enable_joker: self.cards += [PokerCard(Pointer.Joker, Color.Black), PokerCard(Pointer.Joker, Color.Color)] def getPoker(self): r''' get a poker copy ''' return self.cards[:] def deal(cards, player_counts=4): r''' deal function ''' players = {} for i in range(player_counts): players['Player_{0}'.format(i + 1)] = [] player_index = 0 while cards: card = cards.pop(random.randrange(len(cards))) players['Player_{0}'.format(player_index + 1)].append(card) player_index = (player_index + 1) % player_counts return players if __name__ == '__main__': import sys import os import getopt dirname, filename = os.path.split(sys.argv[0]) try: opts, args = getopt.getopt( sys.argv[1:], "hp:", ["help", "players=", "without-joker"]) except getopt.GetoptError as err: print(err) usage(filename) sys.exit(2) params = { 'players': 4, 'with-joker': True } for o, a in opts: if o in ('-h', '--help'): usage(filename) sys.exit() elif o in ('-p', '--players'): params['players'] = int(a) elif o == '--without-joker': params['with-joker'] = False pokerFactory = PokerFactory(params['with-joker']) players_cards = deal(cards=pokerFactory.getPoker(), player_counts=params['players']) for player, cards in players_cards.items(): print(player, "has {0} cards".format(len(cards)), ":", cards, end='\n\n') <file_sep>/practice-from-ProgrammingProjectList/practice_001/README.md # 练习1: 逆转字符串 输入字符串, 将其逆转输出 ## 使用方法: ``` shell revert-string [-h | --help] string ``` ## 分析 在python3中, 字符串可以使用切片操作。逆转字符串相当于对字符串使用[-1::-1]。 ## 练习目标 1. 熟悉字符串切片操作 1. 熟悉argparse, 使用argparse操作命令行参数 ## 实现 参见文件[revert-string.py](./revert-string.py) <file_sep>/practice-from-ProgrammingProjectList/README.md # 说明 这些练习的题目来自[有了这个列表,程序员不愁没练手的小项目了](https://github.com/jobbole/ProgrammingProjectList.git) # 目录 <file_sep>/practice-from-ProgrammingProjectList/practice_002/README.md # 练习2: 端口扫描器 输入某个ip地址和端口区间,程序会逐个尝试区间内的端口,如果能成功连接的话就将该端口标记为open。 ## 使用方法: ``` shell $ python3 port-scan.py -h usage: port-scan.py [-h] [-a ADDRESS] [-s START_PORT] [-e END_PORT] scan which ports listening optional arguments: -h, --help show this help message and exit -a ADDRESS, --address ADDRESS address -s START_PORT, --start-port START_PORT scan start port -e END_PORT, --end-port END_PORT scan end port ``` ## 分析 1. socket 连接操作判断对方端口是否处在监听状态 2. 使用asyncio.eventloop进行并发操作 ## 练习目标 1. 熟悉socket connect 1. 熟悉asyncio eventloop ## 实现 参见[port-scan.py](./port-scan.py) <file_sep>/practice_002-image_to_text/image-to-text.py #! /usr/bin/env python3 # -*- coding: utf-8 -*- r''' 这是一个图片转字符画的练习 问题描述: 1) 程序的使用方法: $ image-to-text [-h | --help] [--scale scale] [--char-set "char_set"] image -h show this --scale scale to scale px --char-set the transform character set default is "$@B%8&WM#*oahkbdpqwm ZO0QLCJUYXzcvunxrjft/\|()1{} []?-_+~<>i!lI;:,\"^`'." image image file 目的: 熟悉pillow(PIL)库 ''' from PIL import Image def usage(name): ''' print usage ''' helpstr = '''usage: {0} [-h | --help] [--scale scale] [--char-set "char_set"] image... -h --help show this --scale scale to scale px --char-set the transform character set default is " $@B%8&WM#*oahkbdpqwm ZO0QLCJUYXzcvunxrjft/\\|()1{} []?-_+~<>i!lI;:,\"^`'." image... image files '''.format(name) print(helpstr) class TextImageConvertor(object): r''' TextImageConvertor ''' def __init__(self): self._scale = -1 self._gray_str = " $@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\"^`'." self._r_coeffficient = 0.229 self._g_coeffficient = 0.587 self._b_coeffficient = 0.114 @property def scale(self): ''' scale ''' return self._scale @scale.setter def scale(self, scale): self._scale = scale @property def gray_string(self): ''' gray string ''' return self._gray_str @gray_string.setter def gray_string(self, string): self._gray_str = string def _convert_L(self, L): r''' trans gray L to char ''' return self._gray_str[int(L / 256 * len(self._gray_str))] def _rgba_to_L(self, r, g, b, alpha=256): r''' trans rgba to level ''' if alpha == 0: return 0 gray = self._r_coeffficient * r + self._g_coeffficient * g + self._b_coeffficient * b return gray def _convert(self, image, pixel_convert_l_func): buf = [] width, height = image.size for y in range(height): for x in range(width): data = image.getpixel((x, y)) pixel_l = pixel_convert_l_func(data) buf.append(self._convert_L(pixel_l)) buf.append('\n') return buf def convert(self, image): r''' convert image to string ''' buf = [] op_im = image.copy() if self._scale > 0: op_im.thumbnail((self._scale, self._scale)) if op_im.mode == "RGBA": buf = self._convert(op_im, lambda rgba: self._rgba_to_L(rgba[0], rgba[1], rgba[2], rgba[3])) elif op_im.mode == "RGB": buf = self._convert(op_im, lambda rgb: self._rgba_to_L(rgb[0], rgb[1], rgb[2])) elif op_im.mode == "LA": buf = self._convert(op_im, lambda la: la[0]) elif op_im.mode == "L": buf = self._convert(op_im, lambda l: l[0]) else: pass return "".join(buf) if __name__ == '__main__': import sys import os import getopt dirname, filename = os.path.split(sys.argv[0]) try: opts, args = getopt.getopt( sys.argv[1:], "h", ["help", "char-set=", "scale="]) except getopt.GetoptError as err: print(err) usage(filename) sys.exit(2) textConvertor = TextImageConvertor() for o, a in opts: if o in ('-h', '--help'): usage(filename) sys.exit() elif o == '--char-set': textConvertor.gray_string = a elif o == '--scale': textConvertor.scale = int(a) for image_file in args: with Image.open(image_file) as im: print(textConvertor.convert(im))
236e5355fc619713915289ac1b5b1f520dc7bf1e
[ "Markdown", "Python" ]
7
Python
yurenxj1982/JohnXu-python-practice
13bf9d266f239e4ca7ffec35a86a1b663a5dcf9f
91053af4160d6af5aa8de3de57daa77e5da8644d
refs/heads/master
<file_sep>package com.ybj.file.parse.core.post; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; import com.ybj.file.config.element.BaseParseFileInfo; import com.ybj.file.config.element.ColumnHead; import com.ybj.file.config.element.ToParseTemplate; import com.ybj.file.model.parse.ColumnEntry; import com.ybj.file.model.parse.ParsedRow; import com.ybj.file.parse.core.ParseException; import com.ybj.file.parse.core.Reader; import com.ybj.file.parse.core.ReaderFactory; import com.ybj.file.parse.core.exception.IllegalHeadException; import com.ybj.file.parse.core.exception.RowHandleException; import com.ybj.file.parse.core.post.infs.PostRowHandler; import com.ybj.file.parse.message.CellParseMessage; import com.ybj.file.parse.message.ParseContext; import com.ybj.file.parse.message.RowParseMessage; public class FileParseExtractor implements ParseStartHandler { protected Map<Integer, String> columnFieldMap = new HashMap<Integer, String>(); protected Map<Integer, String> columnTitleMap = new HashMap<Integer, String>(); private PostRowHandler postHandler; public FileParseExtractor(PostRowHandler postHandler) { this.postHandler = postHandler; } @Override public void startParse(BaseParseFileInfo baseFileInfo) throws ParseException { Reader reader = ReaderFactory.getReader(baseFileInfo.getFileName()); if (reader == null) { throw new ParseException("不支持的文件类型,请选择正确的模板导入。"); } reader.read(baseFileInfo, null); } /** * 后续可以引入对接参数,如某个Handler的对接上面是1,下路对接是3,则处理链上面只能是1结束的,处理链下端的只能是3开始的。 */ @Override public void processOne(ParsedRow parsedRow, ParseContext parseContext) throws RowHandleException { ToParseTemplate toParseTemplate = parsedRow.getCurTemplate(); int curRow = parsedRow.getRowIndex(); int headRow = toParseTemplate.getHeadRow(); int startContentRow = toParseTemplate.getStartContent(); // 为了兼容xml提取,xml提取rowIndex = -1,不会反在此返回 if (curRow >= 0 && curRow < headRow) { return; } // 为了兼容xml提取,xml提取rowIndex = -1,xml提取不进行表头提取,直接进行内容读取 if (curRow == headRow) { RowParseMessage rowMsg = validateRow(parsedRow, parseContext); if (rowMsg.isHasError()) { throw new IllegalHeadException(rowMsg); } readHead(parsedRow, parseContext); // 如果表头是最后一行,说明是一个只有表头的空表 if (parsedRow.isLastRow()) { CellParseMessage error = new CellParseMessage("导入的文件中没有可以解析的数据。", parsedRow.getSheetIndex(), parsedRow.getRowIndex()); rowMsg.add(error); rowMsg.setHasError(true); throw new IllegalHeadException(rowMsg); } return; } if (curRow >= startContentRow) { extractContent(parsedRow, parseContext); } } private RowParseMessage validateRow(ParsedRow dataRow, ParseContext parseContext) { ToParseTemplate toParseTemplate = dataRow.getCurTemplate(); RowParseMessage headParseMessage = parseContext.getHeadParseMessage(); if (toParseTemplate.getHeadRow() < 0) { headParseMessage.setRowMsg("找不到对应的表头"); headParseMessage.setHasError(true); return headParseMessage; } if (toParseTemplate.getHeadRow() == dataRow.getRowIndex()) { List<String> keyHeads = toParseTemplate.getToParseHead().getColumnHeads().stream() .filter(ColumnHead::isRequired).map(ColumnHead::getTitleName).collect(Collectors.toList()); List<String> allDataHeads = dataRow.getCells().stream().map(ColumnEntry::getValue) .collect(Collectors.toList()); for (String keyHead : keyHeads) { if (!allDataHeads.contains(keyHead)) { CellParseMessage error = new CellParseMessage("表头:“" + keyHead + "”必须包含。", dataRow.getSheetIndex(), dataRow.getRowIndex()); headParseMessage.add(error); headParseMessage.setHasError(true); } } } return headParseMessage; } /** * 表头提取 * * @param parsedRow * @return */ protected RowParseMessage readHead(ParsedRow parsedRow, ParseContext parseContext) { columnFieldMap.clear(); columnTitleMap.clear(); List<ColumnEntry> titles = parsedRow.getCells(); if (titles.isEmpty()) { System.out.println("没有可以解析的列,请检查表头或者更换模板类型为不识别表头解析。"); return null; } ToParseTemplate toParseTemplate = parsedRow.getCurTemplate(); List<String> templateHeads = toParseTemplate.getToParseHead().getColumnHeads().stream() .map(ColumnHead::getTitleName).collect(Collectors.toList()); for (ColumnEntry titleEntry : parsedRow.getCells()) { if (templateHeads.contains(titleEntry.getValue())) { columnFieldMap.put(titleEntry.getKey(), toParseTemplate.getFieldName(titleEntry.getValue())); columnTitleMap.put(titleEntry.getKey(), titleEntry.getValue()); } } if (columnFieldMap.isEmpty()) { System.out.println("Sheet:" + parsedRow.getSheetIndex()); System.out.println("模板与Excel表头不匹配,没有满足条件的列可以解析"); return null; } parseContext.clearColumnFieldMap(); parseContext.putAllColumnFieldMap(columnFieldMap); return null; } private void extractContent(ParsedRow parsedRow, ParseContext parseContext) { Iterator<ColumnEntry> iter = parsedRow.getCells().iterator(); // 删除没有配置表头的列,根据表头和列的对应关系补齐Titile和Field while (iter.hasNext()) { ColumnEntry contentEntry = iter.next(); Integer columnIndex = contentEntry.getKey(); if (columnIndex == null)// xml提取没有列序号-列名称关系,直接跳过,避免在下一步数据被删除 { continue; } if (columnFieldMap.get(columnIndex) == null) { iter.remove(); } else { contentEntry.setTitle(columnTitleMap.get(columnIndex)); contentEntry.setField(columnFieldMap.get(columnIndex)); } } //当前行从Excel解析得到的列数据中包含的列序号集合 List<Integer> curRowColumnIds = parsedRow.getCells().stream().map(ColumnEntry::getKey) .collect(Collectors.toList()); for (Entry<Integer, String> entry : columnFieldMap.entrySet()) { // 没有找到对应列的数据,则增加一个为空的数据 // 补全cell为空的列 if (!curRowColumnIds.contains(entry.getKey())) { ColumnEntry ce = new ColumnEntry(entry.getKey(), null); ce.setTitle(columnTitleMap.get(entry.getKey())); ce.setField(entry.getValue()); parsedRow.getCells().add(entry.getKey(),ce); } } /* * if(parsedRow.isEmpty()) { return; } */ postHandler.processOne(parsedRow, parseContext); } @Override public PostRowHandler next(PostRowHandler next) { this.postHandler = next; return this.postHandler; } @Override public PostRowHandler next() { return this.postHandler; } } <file_sep>package com.ybj.file.parse.regist.validator.enumeration; import java.util.Arrays; import com.ybj.file.config.element.init.ParserBeanFactoryRegister; import com.ybj.file.parse.regist.validator.SingleCellValidator; import com.ybj.file.parse.regist.validator.ValidatorExpression; import com.ybj.file.parse.regist.validator.enumeration.datasource.EnumDataSource; import com.ybj.file.parse.regist.validator.factory.ValidatorFactory; public class EnumCellValidatorFactory implements ValidatorFactory { public static final String REGIST_KEY = EnumValidator.REGIST_KEY; @Override public SingleCellValidator newValidator(ValidatorExpression ve) { try { EnumValidator enumValidator = new EnumValidator(); String[] params = ve.getParams(); String enumDataSourceType = params[0]; EnumDataSource dataSource = ParserBeanFactoryRegister.get(EnumDataSource.class, enumDataSourceType); enumValidator.putAll(dataSource.getKeyvalueMap(Arrays.copyOfRange(params, 1, params.length))); return enumValidator; } catch (Exception e) { throw new RuntimeException("枚举表达式异常:" + ve.getExpression(), e); } } @Override public String getRegistKey() { return REGIST_KEY; } } <file_sep>Excel导入框架使用说明 | 责任人 | 修改日期 | 版本变更记录 | | ------ | --------- | -------------------------------------------------------- | | 颜本军 | 2019/5/17 | 初始化 | ## 概要 框架命名Eiuse,后续文档称呼为Eiuse。框架定位是简化Java语言对Excel文件、xml文件导入编程操作,提供Java SDK包和Springboot Starter 两种jar包直接集成到我们需要的项目中。 ### 一、引入工具包或者源码 1、非SpringBoot项目,POM 引入 Java SDK ```xml <groupId>com.cmiot</groupId> <artifactId>FileParseSDK</artifactId> <version>0.0.1-SNAPSHOT</version> ``` 2、SpringBoot项目,POM引入SpringBoot Starter ```xml <groupId>com.cmiot</groupId> <artifactId>spring-boot-FileParse-starter</artifactId> <version>0.0.1-SNAPSHOT</version> ``` 3、将源码集成到Lion框架中(使用最新版的spring-boot-mng-starter) ### 二、简单的示例 模板配置通过xml文件配置,默认使用类路径下的 *fileParseContext.xml* 作为模板配置文件。 示例,假如在你的系统中需要提供一个人员信息导入接口,导入如下图的人员信息Excel文件 ![待导入Excel](C:\Users\yanbenjun\AppData\Roaming\Typora\typora-user-images\1557220026366.png) 1、配置模板,需要导入的列 ```xml <?xml version="1.0" encoding="UTF-8"?> <fileParse xmlns="http://www.yanbenjun.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.yanbenjun.com fileParse.xsd"> <!-- *解析系统,集成到业务系统中,让业务系统能够方便的让开发整合excel、csv、xml数据解析功能到业务系统; *可以灵活的配置不同的模板、或者竟可能多的包络系统已知属性,形成一个通用模板; *具体用什么model装数据、存储到什么数据库、可以配置到xml里写死(适合固定模板的解析);也可以不用配置,等用户上传 *完文件后,让用户确认文件类型或者将类型写入到Excel自动识别(和业务有关),类型可以知道数据存储的java模型和具体入库 *数据库。 --> <parseSystem name="powerMng"> <!-- 通用列配置 --> <columns> </columns> <!-- 通用sheet模板配置 --> <templates> </templates> <!-- 通用解析文件配置 --> <files> </files> <!-- 解析点,具体的业务系统,哪里需要解析文件,只需要在请求中传入该解析点ID,就可以自动根据解析点的配置,自动解析入库 --> <parsePoint id="20190507"> <!-- 唯一ID --> <toParseFile name="test" mode="single"> <toParseTemplate name="test" sheetIndex="0" handler="com.cmiot.mng.file.test.MyRowHandler"> <columnHead titleName="姓名" fieldName="name" required="true" type="string" validator="notnull"/> <columnHead titleName="年龄" fieldName="age" required="true" type="integer" /> <columnHead titleName="性别" fieldName="sex" required="true" type="string" validator="notnull"/> <columnHead titleName="所属岗位" fieldName="job" required="true" type="string" validator="notnull"/> <columnHead titleName="测试字段1" fieldName="testField1" required="false" type="string"/> </toParseTemplate> </toParseFile> </parsePoint> </parseSystem> </fileParse> ``` 2、写自己的行处理器,完成自己的业务(如写入数据库、缓存、或者输出到控制台) ```java public class MyRowHandler extends TeminationPostRowHandler//继承框架提供的基础行处理器 { /** * 实现自己的业务逻辑 */ @Override public void processOne(ParsedRow parsedRow, ParseContext parseContext) throws RowHandleException { if (parseContext.getCurRowMsg().isHasError()) {//处理当前行的校验错误 System.out.println(parsedRow.getCells()); System.out.println(parseContext.getCurRowMsg().getCellParseMsgs()); } else {//处理没有行校验错误的数据 System.out.println(parsedRow.getModelRow());//正常解析的数据以Map形式提供 // OR INSERT DB System.out.println(parseContext.getCurRowMsg().getCellParseMsgs());//处理该列错误 } } } ``` 3、提供Restful接口 ```java //@Restful public void import(String filename, InputStream ins) { try { //获取该导入入口对应的解析点parser FileParser fp = FileParserFactory.getFileParser(filename, ins, 20190507L); ParseContext context = fp.getContext();//解析上下文,可以通过此上下文把自己的参数传递到你自己的Handler,也可以获取到Handler中返回的信息,如解析错误信息 context.putAll(packet.formData); fp.parse(); } catch (Exception e) { //TODO } } ``` 这样通过以上三步,我们的一个基本的人员信息导入接口就算完成了。 ## 模板配置 ### 一、标签说明 #### 1、 parseSystem parseSystem对应我们的应用系统,一个应用系统下有一个唯一的xml配置文件和parseSystem,可以给parseSystem命名。parseSystem下的属性和节电如下列表 | 属性or子节点 | 描述 | 类型 | 限制条件 | | ------ | --------- | ---- | --------------- | | name | 系统名称 | 属性 | string | | columns | 公共列配置 | 子节点 | multi | | templates | 公共Sheet模板配置 | 子节点 | multi | | files | 公共文件模板配置 | 子节点 | multi | | parsePoint | 解析点 | 子节点 | multi | #### 2、 parsePoint parsePoint对应我们的应用系统中的导入接口,对应前台的一个导入http请求。 | 属性or子节点 | 描述 | 类型 | 限制条件 | 备注 | | ------ | --------- | ---- | --------------- | --- | | id | 解析点唯一标识 | 属性 | Long | must | | toParseFile | 文件模板 | 子节点 | multi | 与refFile二者必须至少有一个 | | refFile | 引用公共的toParseFile | 子节点 | multi | 与toParseFile二者必须至少有一个 | 说明: 1)、当parsePoint下有多个toParseFile,代表该导入接口支持多文件模板解析,解析系统能够自动识别用户上传的文件,根据文件里的label(对应toParseFile的属性name)自动识别该上传文件解析使用的toParseFile文件模板。 2)、当parsePoint下只有一个toParseFile,代表该导入接口支持toParseFile匹配文件模板的解析,用户上传的文件无需要label,解析系统会自动识别所有上传的文件为toParseFile文件模板类型的导入文件。 #### 3、toParseFile toParseFile对应我们需要解析的文件模板,注意这里是文件模板,不是文件本身。 | 属性or子节点 | 描述 | 类型 | 限制条件 | 备注 | | ------ | --------- | ---- | --------------- | --- | | name | 文件模板名称 | 属性 | String | must | | mode | 文件模板Sheet页数量 | 子节点 | enum | 文件模板下sheet模板的数量 | | toParseTemplate | Sheet模板 | 子节点 | multi | 与refTemplate二者必须至少有一个 | | refTemplate | 引用公共的toParseTemplate | 子节点 | multi | 与toParseTemplate二者必须至少有一个 | #### 4、toParseTemplate toParseTemplate对应我们真正解析的文件内容模板(如Excel的sheet页模板)。 | 属性or子节点 | 描述 | 类型 | 限制条件 | 备注 | | ------ | --------- | ---- | --------------- | --- | | name | sheet模板名称 | 属性 | String | optional | | sheetIndex | 需要解析的sheet页序号 | 属性 | number | must(default=0) | | headRow | 表头所在行 | 属性 | number | must(default=0) | | contentStartRow | 内容开始行 | 属性 | number | must(default=1) | | handler | 用户自己的行处理器 | 属性 | string | must(用户自定义处理框架解析的行记录,需要继承框架提供的基类TeminationPostRowHandler) | | validator | (sheet)模型校验器 | 属性 | string(validatorExpressions) | 框架内置了联合主键校验器 | | columnHead | 列表头 | 子节点 | multi | 与refColumn二者必须至少有一个 | | refColumn | (sheet)模型校验器 | 子节点 | multi | 与columnHead二者必须至少有一个 | #### 5、columnHead columnHead对应我们sheet页表头属性。 | 属性or子节点 | 描述 | 类型 | 限制条件 | 备注 | | ---- | --------------- | ---- | --- | ----- | | id | 列ID | 属性 | number | optional,在公共columns下使用时必填 | | titleName | 模板表头列名称(Excel表头列) | 属性 | string | must | | fieldName | 列属性对应的Java域名 | 属性 | string | must | | required | 列是否必须包含 | 属性 | boolean | must(default=false)(true=必须包含,false=可选列,有则解析,没则不解析) | | type | 列属性类型 | 属性 | string | 支持string,int,double,boolean(default=string) | | validator | 列属性校验器 | 属性 | string(validatorExpressions) | 框架内置了多种校验器 | | horizontalMerger | 属性垂直合并器 | 属性 | string | 垂直合并器向系统注册的key,通过key获取java垂直合并器,功能待完善,不建议使用 | | xmlExtendInfo | xml数据提取使用,xml列位置信息 | 属性 | string | 功能待完善,不建议使用 | #### 6、其它 files、templates、columns分别作为toParseFile、toParseTemplate、columnHead的公共配置容器,公共配置可以重复使用。在可以使用的地方通过refFile、refTemplate、refColumn标签引用公共容器里已经配置好的对象。 ### 二、进阶使用 #### 1、传递解析参数和解析结果 ParseContext,解析上下文可以帮助我们在解析开始前设置自己需要向后续解析处理时需要用到的参数,另一方面,也可以将解析的结果传递到解析完毕后,例如解析格式错误信息,需要在解析完毕后传递给解析调用方。 ```java //@Restful public List<String> import(String filename, InputStream ins) { try { //获取该导入入口对应的解析点parser FileParser fp = FileParserFactory.getFileParser(filename, ins, 20190507L); ParseContext context = fp.getContext();//解析开始前,通过FileParser获取到ParseContext对象 Object params = "ybj"//你需要传递的参数; context.put("user", params);//添加你需要传递的参数 fp.parse();//开始解析 List<String> errorMsgs = (List<String>)parseContext.get("errorMsgs");// 解析完毕获取解析中的错误信息 return errorMsgs;//错误信息返回给前台 } catch (Exception e) { //TODO } } ``` ```java public class MyRowHandler extends TeminationPostRowHandler//继承框架提供的基础行处理器 { private List<String> errorMsgs = new ArrayList<>(); /** * 实现自己的业务逻辑 */ @Override public void processOne(ParsedRow parsedRow, ParseContext parseContext) throws RowHandleException { //TODO 你自己的业务处理逻辑 errorMsgs.add(getErrorMsg(parsedRow, parseContext)) if(parsedRow.isLastRow()){ //TODO 你自己的业务处理逻辑 //放入所有解析异常信息,可以在解析完毕后通过key获取你传递的值 parseContext.put("errorMsgs",errorMsgs); } } private String getErrorMsg(ParsedRow parsedRow, ParseContext parseContext) { //TODO 获取解析异常信息 return "获取解析异常信息"; } } ``` #### 2、最终后置行数据处理器-TeminationPostRowHandler ##### a、xml中配置的位置 用户继承实现自己的TeminationPostRowHandler,在xml中的toParseTemplate标签的属性handler指定用户实现的类全名,如下所示 ```xml <toParseTemplate name="test" sheetIndex="0" handler="com.cmiot.mng.file.test.MyRowHandler"> ... </toParseTemplate> ``` ##### b、实现 ```java public class MyRowHandler extends TeminationPostRowHandler { @Override public void processOne(ParsedRow parsedRow, ParseContext parseContext) throws RowHandleException { //TODO 你自己的业务处理逻辑 } } ``` #### 3、校验器 说明:不同校验器可以用|分隔,联合使用,如notnull|integer,如下表示同时校验所属岗位列不能为空且填入的值必须为整数类型。 ```xml <columnHead titleName="所属岗位" fieldName="job" required="true" type="string" validator="notnull|integer"/> ``` ##### NoneValidator(无校验) | 关键字 | 校验位置 | 作用 | 使用说明 | | ---- | --------------- | ---- | --- | | none | 列 | 不校验 | 无 | ##### NotNullValidator (非空校验器) | 关键字 | 校验位置 | 作用 | 使用说明 | | ---- | --------------- | ---- | --- | | notnull | 列 | 属性非空校验 | 无 | ##### BooleanValidator (布尔校验器) | 关键字 | 校验位置 | 作用 | 使用说明 | | ---- | --------------- | ---- | --- | | boolean | 列 | 布尔校验 | 无 | ##### IntegerValidator (整数校验器) | 关键字 | 校验位置 | 作用 | 使用说明 | | ---- | --------------- | ---- | --- | | integer | 列 | 整数校验 | 无 | ##### DoubleValidator (小数校验器) | 关键字 | 校验位置 | 作用 | 使用说明 | | ---- | --------------- | ---- | --- | | double | 列 | 小数校验 | 无 | ##### EnumValidator (枚举校验器) | 关键字 | 校验位置 | 作用 | 使用说明 | | ---- | --------------- | ---- | --- | | enum(expression,[key1,value1,key2,value2,...]) | 列 | 枚举校验 | 当第一个参数=expression时,直接将key,value依次写入表达式 | | enum(enumclass,[classOrBean]) | 列 | 枚举校验 | 当第一个参数=enumclass时,classOrBean表示:实现了接口EnumEntry的枚举类全名 | | enum(query,[classOrBean]) | 列 | 枚举校验 | 当第一个参数=query时,classOrBean表示:用户自己实现继承了DbEnumDataSource抽象类的自定义数据库枚举源 | ###### A. expression ```xml <columnHead titleName="所属岗位" fieldName="job" required="true" type="string" validator="enum(expression, Java,0,JavaScript,1)"/> ``` ###### B. enumclass ```xml <columnHead titleName="所属岗位" fieldName="job" required="true" type="string" validator="enum(enumclass, com.ybj.file.test.MyEnumType)"/> ``` ```java public enum MyEnumType implements EnumEntry { JAVA("Java", 0), JAVASCRIPT("JavaScript", 1); private String fdKey; private Object fdValue; private MyEnumType(String fdKey, Object fdValue) { this.fdKey = fdKey; this.fdValue = fdValue; } @Override public String getFdKey() { // TODO Auto-generated method stub return this.fdKey; } @Override public Object getFdValue() { // TODO Auto-generated method stub return this.fdValue; } } ``` ###### C. query ```xml <columnHead titleName="所属岗位" fieldName="job" required="true" type="string" validator="enum(query, com.ybj.file.test.MyEnumDataSource)"/> ``` ```java public class RoomNameEnumDataSource extends DbEnumDataSource { /** * 获取形如[{"fdKey":enumKey,"fdValue":enumValue},{...}]的list * * @param args * @return */ @Override public List<Map<String, Object>> queryDataList(String... args) { // TODO 查询数据 return new ArrayList<>(); } } ``` ##### UniqueValidator (唯一行校验器) | 关键字 | 校验位置 | 作用 | 使用说明 | | ---- | --------------- | ---- | ----- | | unique([classOrBean],[key1,key2,...]) | sheet | 主键or联合主键唯一性校验 | classOrBean表示:用户自己继承UniqueValidator实现的唯一校验器;key1,key2等表示需要联合校验的列属性 | 使用示例: ```xml <toParseTemplate name="airConditioner" sheetIndex="1" handler="com.ybj.file.test.MyRowHandler" validator="unique(com.ybj.file.test.MyUniqueValidator, ac_brand)"> ... </toParseTemplate> ``` ```java public class MyUniqueValidator extends CacheUniqueValidator { public MyUniqueValidator() { super(); } @Override public List<Map<String, Object>> queryExistValues() { //TODO QUERY FROM DATABASE List<Map<String, Object>> list = new ArrayList<>(); Map<String, Object> map = new HashMap<>(); map.put("ac_brand", "美的"); return list; } } ```<file_sep>package com.ybj.file.parse.message; public class Location { private int fileId = -1; private int sheetId = -1; private int rowId = -1; private int columnId = -1; public Location() { } public Location(int sheetId) { this.sheetId = sheetId; } public Location(int sheetId,int rowId) { this.sheetId = sheetId; this.rowId = rowId; } public Location(int sheetId,int rowId, int columnId) { this.sheetId = sheetId; this.rowId = rowId; this.columnId = columnId; } public int getFileId() { return fileId; } public void setFileId(int fileId) { this.fileId = fileId; } public int getSheetId() { return sheetId; } public void setSheetId(int sheetId) { this.sheetId = sheetId; } public int getRowId() { return rowId; } public void setRowId(int rowId) { this.rowId = rowId; } public int getColumnId() { return columnId; } public void setColumnId(int columnId) { this.columnId = columnId; } public String toString() { return "Location: ["+fileId+","+sheetId+","+rowId+", "+columnId+"]"; } } <file_sep>package com.ybj.file.parse.regist; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public abstract class AbstractRegister implements Register { protected static final Map<String, ICanRegist> CONTAINER = new ConcurrentHashMap<>(); @Override public final boolean regist(ICanRegist t) { return CONTAINER.putIfAbsent(t.getRegistKey() + "_" + this.getClass().getName(), t) == null ? true : false; } public ICanRegist getObject(String registKey) { return CONTAINER.get(registKey + "_" + this.getClass().getName()); } @Override public boolean regist(String key, ICanRegist t) { return CONTAINER.putIfAbsent(key + "_" + this.getClass().getName(), t) == null ? true : false; } } <file_sep>package com.ybj.file.parse.regist.validator.factory; import java.util.List; import com.ybj.file.parse.regist.validator.UniqueValidator; public class JavaUniqueValidatorFactory implements UniqueValidatorBuilder { @Override public UniqueValidator build(String clazzOrBean, List<String> unionKeys) { try { Class<? extends UniqueValidator> clazz = Class.forName(clazzOrBean).asSubclass(UniqueValidator.class); return clazz.getConstructor(List.class).newInstance(unionKeys); } catch (Exception e) { throw new RuntimeException("唯一校验器表达式错误,请确保类全名或者构造函数的正确。"); } } @Override public String getFactoryType() { return "java"; } } <file_sep>package com.ybj.file.parse.core; import com.ybj.file.parse.core.excel.XlsReader; import com.ybj.file.parse.core.excel.XlsxReader; import com.ybj.file.parse.core.xml.XmlReader; public class ReaderFactory { public static Reader getReader(String fileName) { if (fileName.endsWith(".xlsx")) { return new XlsxReader(); } else if (fileName.endsWith(".xls")) { return new XlsReader(); } else if (fileName.endsWith(".xml")) { return new XmlReader(); } return null; } } <file_sep>package com.ybj.file.parse.regist.validator; import org.apache.commons.lang.StringUtils; import com.ybj.file.parse.regist.ICanRegist; import com.ybj.file.parse.regist.TypeHandleException; import com.ybj.file.parse.regist.convertor.IntegerConverter; import com.ybj.file.util.NumberUtils; public class IntegerValidator implements SingleCellValidator, ICanRegist { public static final String REGIST_KEY = IntegerConverter.REGIST_KEY; @Override public String getRegistKey() { return REGIST_KEY; } /** * @param 需要校验的值 * @return 是否有错 true=有错 */ @Override public boolean validate(String value) { try { getTypeValue(value); } catch (TypeHandleException e) { return true; } return false; } @Override public String getErrorMsg() { return "非整数类型"; } @Override public Integer getTypeValue(String originalValue) { if (StringUtils.isEmpty(originalValue)) { return null; } try { Integer result = Integer.parseInt(NumberUtils.trimZeroAndDot(originalValue.trim())); return result; } catch (NumberFormatException e) { TypeHandleException tce = new TypeHandleException("非整数类型"); throw tce; } } @Override public String getSimpleName() { return REGIST_KEY; } @Override public Object getParam() { return null; } } <file_sep>package com.ybj.file.parse.core.post.must; import java.util.List; import com.ybj.file.config.element.ToParseTemplate; import com.ybj.file.model.parse.ColumnEntry; import com.ybj.file.model.parse.ParsedRow; import com.ybj.file.parse.core.exception.RowHandleException; import com.ybj.file.parse.core.post.MidPostRowHandler; import com.ybj.file.parse.core.post.infs.PostRowHandler; import com.ybj.file.parse.message.CellParseMessage; import com.ybj.file.parse.message.ParseContext; import com.ybj.file.parse.message.RowParseMessage; import com.ybj.file.parse.regist.validator.SingleCellValidator; /** * 单字段校验,用于除FileParseExtractor所有PostHandler的最前端 * * @author yanbenjun * */ public class TypeValidateHandler extends MidPostRowHandler { public TypeValidateHandler() { super(); } public TypeValidateHandler(PostRowHandler next) { super(next); } @Override public void processOne(ParsedRow parsedRow, ParseContext parseContext) throws RowHandleException { int sheetIndex = parsedRow.getSheetIndex(); int rowIndex = parsedRow.getRowIndex(); ToParseTemplate toParseTemplate = parsedRow.getCurTemplate(); List<ColumnEntry> cells = parsedRow.getCells(); RowParseMessage rowParseMessage = parseContext.getCurRowMsg(); //校验单个Cell for (int i = 0; i < cells.size(); i++) { ColumnEntry ce = cells.get(i); String field = ce.getField(); String cellValue = ce.getValue(); List<SingleCellValidator> cellValidators = toParseTemplate.getSingleCellValidator(field); for (SingleCellValidator validator : cellValidators) { if (validator.validate(cellValue)) { CellParseMessage cellMsg = new CellParseMessage(); cellMsg.setSheetId(sheetIndex); cellMsg.setRowId(rowIndex); cellMsg.setColumnId(ce.getKey()); cellMsg.setField(field); cellMsg.setTitle(ce.getTitle()); cellMsg.setCellOriginValue(cellValue); cellMsg.setMsgType(validator.getSimpleName()); cellMsg.setMsg(validator.getErrorMsg()); rowParseMessage.add(cellMsg); break; } // 校验通过的行,设置转换后的值 ce.setModelValue(validator.getTypeValue(cellValue)); } } // 下一个处理 next.processOne(parsedRow, parseContext); } } <file_sep>package com.ybj.file.parse.regist; public class TypeHandleException extends RuntimeException { /** * */ private static final long serialVersionUID = -5914172343263818526L; private String errorInfo; private String messageKey; public TypeHandleException(String errorInfo) { this.errorInfo = errorInfo; } public String getErrorInfo() { return errorInfo; } public void setErrorInfo(String errorInfo) { this.errorInfo = errorInfo; } public String getMessageKey() { return messageKey; } public void setMessageKey(String messageKey) { this.messageKey = messageKey; } } <file_sep>package com.ybj.file.config.element.init; /** * 实现此工厂类,可以实现对xml配置的handler不同解析方式获取终止后置处理器 * @author Administrator * */ public interface ParserBeanFactory { public Class<?> getFactoryClass(); public String getFactoryType(); } <file_sep>package com.ybj.file.parse.core.exception; public class RowHandleException extends RuntimeException { /** * */ private static final long serialVersionUID = 5650335059003735314L; public RowHandleException() { } public RowHandleException(Exception e) { super(e); } } <file_sep>package com.ybj.file.model; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.ybj.file.config.element.ColumnHead; public class ToParseHead { /** 需要解析的列 */ private List<ColumnHead> columnHeads = new ArrayList<ColumnHead>(); private Map<String, ColumnHead> headMap = new HashMap<String, ColumnHead>(); public ToParseHead() { } public ToParseHead(List<ColumnHead> columnHeads) { addAll(columnHeads); } public ColumnHead getByFieldName(String fieldName) { return this.headMap.get(fieldName); } public void add(ColumnHead columnHead) { this.columnHeads.add(columnHead); this.headMap.put(columnHead.getFieldName(), columnHead); } public void addAll(List<ColumnHead> columnHeads) { this.columnHeads.addAll(columnHeads); for(ColumnHead ch : columnHeads) { this.headMap.put(ch.getFieldName(), ch); } } public List<ColumnHead> getColumnHeads() { return columnHeads; } public String toString() { return "需要解析的表头:" + this.columnHeads.toString(); } } <file_sep>package com.ybj.file.parse.core; public abstract class AbstractReader implements Reader { } <file_sep>package com.ybj.file.export; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Workbook; public class XlsExcelWriter extends ExcelWriter { @Override protected Workbook createWorkbook(int flushSize) { return new HSSFWorkbook(); } @Override protected int getMaxSheetSize() { return 65536; } } <file_sep>package com.ybj.file.parse.core.post.must; import java.util.List; import java.util.stream.Collectors; import com.ybj.file.config.element.ToParseTemplate; import com.ybj.file.model.parse.ColumnEntry; import com.ybj.file.model.parse.ParsedRow; import com.ybj.file.parse.core.exception.RowHandleException; import com.ybj.file.parse.core.post.MidPostRowHandler; import com.ybj.file.parse.core.post.infs.PostRowHandler; import com.ybj.file.parse.message.CellParseMessage; import com.ybj.file.parse.message.MultiCellsParseMessage; import com.ybj.file.parse.message.ParseContext; import com.ybj.file.parse.message.RowParseMessage; import com.ybj.file.parse.regist.validator.MultiCellValidator; public class MultiCellsValidatorHandler extends MidPostRowHandler { public MultiCellsValidatorHandler() { super(); } public MultiCellsValidatorHandler(PostRowHandler next) { super(next); } @Override public void processOne(ParsedRow parsedRow, ParseContext parseContext) throws RowHandleException { int sheetIndex = parsedRow.getSheetIndex(); int rowIndex = parsedRow.getRowIndex(); ToParseTemplate toParseTemplate = parsedRow.getCurTemplate(); RowParseMessage rowParseMessage = parseContext.getCurRowMsg(); List<String> hasErrorFields = rowParseMessage.getCellParseMsgs().stream().map(CellParseMessage::getField) .collect(Collectors.toList()); // 校验行,如多个Cell联合主键 List<MultiCellValidator> multiCellValidators = toParseTemplate.getMultiCellValidators(); for (MultiCellValidator multiCellValidator : multiCellValidators) { // 联合校验的字段已经在前面有单元格错误了,则不进行校验(因为经过Convertor转换后的 值已经不是原始值)。 if (!hasErrorFields.removeAll(multiCellValidator.getUnionKeys())) { if (multiCellValidator.validate(parsedRow.getModelRow())) { MultiCellsParseMessage cellsMsg = new MultiCellsParseMessage(); cellsMsg.setSheetId(sheetIndex); cellsMsg.setRowId(rowIndex); List<String> unionKeys = multiCellValidator.getUnionKeys(); cellsMsg.setFields(unionKeys); cellsMsg.setTitles(getUnionTitles(parsedRow, unionKeys)); cellsMsg.setCellOriginValues(getUnionOriginValues(parsedRow, unionKeys)); cellsMsg.setMsgType(multiCellValidator.getSimpleName()); cellsMsg.setMsg(multiCellValidator.getErrorMsg()); rowParseMessage.addMulti(cellsMsg); break; } } } // 下一个处理 next.processOne(parsedRow, parseContext); } private List<String> getUnionTitles(ParsedRow parsedRow, List<String> unionKeys) { return parsedRow.getCells().stream().filter(item -> { return unionKeys.contains(item.getField()); }).collect(Collectors.toList()).stream().map(ColumnEntry::getTitle).collect(Collectors.toList()); } private List<String> getUnionOriginValues(ParsedRow parsedRow, List<String> unionKeys) { return parsedRow.getCells().stream().filter(item -> { return unionKeys.contains(item.getField()); }).collect(Collectors.toList()).stream().map(ColumnEntry::getValue).collect(Collectors.toList()); } } <file_sep>package com.ybj.file.parse.regist.validator; import com.ybj.file.parse.regist.ICanRegist; public class NoneValidator implements SingleCellValidator, ICanRegist { public static final String REGIST_KEY = "none"; @Override public String getRegistKey() { return REGIST_KEY; } @Override public boolean validate(String value) { return false; } @Override public String getErrorMsg() { return null; } @Override public Object getTypeValue(String originalValue) { return originalValue; } @Override public String getSimpleName() { return REGIST_KEY; } @Override public Object getParam() { return null; } } <file_sep>package com.ybj.file.parse.message; import java.util.HashMap; import java.util.Map; public class ParseContext { private Map<String, Object> context = new HashMap<>(); private RowParseMessage curRowMsg = new RowParseMessage(); private RowParseMessage headParseMessage = new RowParseMessage(); private Map<Integer, String> columnFieldMap = new HashMap<>(); public String getString(String key) { return (String) context.get(key); } public Integer getInt(String key) { return (Integer) context.get(key); } public Object getObject(String key) { return context.get(key); } public void put(String key, Object value) { context.put(key, value); } public void putAll(Map<String, Object> params) { context.putAll(params); } public void createRowMessage() { curRowMsg = new RowParseMessage(); } public RowParseMessage getHeadParseMessage() { return headParseMessage; } public RowParseMessage getCurRowMsg() { return curRowMsg; } public Map<Integer, String> getColumnFieldMap() { return columnFieldMap; } public void putAllColumnFieldMap(Map<Integer, String> columnFieldMap) { this.columnFieldMap.putAll(columnFieldMap); } public void clearColumnFieldMap() { this.columnFieldMap.clear(); } } <file_sep>package com.ybj.file.config; import com.ybj.file.config.element.ParseSystem; import com.ybj.file.config.element.ToParseFile; /** * 模板配置上下文 * * @author Administrator * */ public class ParseSystemContext { private ParseSystem parseSystem = ParseSystem.singleton(); public ParseSystemContext(String configFile) { parseSystem.load("", configFile); } /** * 获取系统中指定解析点的第fileIndex个文件模板 * * @param parsePointId * 解析点id * @param fileIndex * 文件模板序列号 * @return 文件模板 */ public ToParseFile getFileTemplate(Long parsePointId, int fileIndex) { return parseSystem.getParsePoint(parsePointId).getToParseFile(fileIndex); } /** * 获取系统中指定解析点的第fileIndex个文件模板 * * @param parsePointId * 解析点id * @param fileTemplateName * 文件模板名称 * @return 文件模板,如果在指定解析点下找不到该名称的模板,返回空 */ public ToParseFile getFileTemplate(Long parsePointId, String fileTemplateName) { return parseSystem.getParsePoint(parsePointId).getToParseFile(fileTemplateName); } } <file_sep>package com.ybj.file.parse.regist.validator; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.ybj.file.util.MapUtils; public abstract class CacheUniqueValidator extends UniqueValidator { /** * 该Field已经存在的值的集合,包括数据库中和已解析的 */ private List<Map<String, Object>> existValues = new ArrayList<>(); public CacheUniqueValidator(List<String> unionKeys) { super(unionKeys); } public abstract List<Map<String, Object>> queryExistValues(); @Override public boolean validate(Map<String, Object> checkingColumns) { for (Map<String, Object> existValue : existValues) { if (MapUtils.equals(checkingColumns, existValue)) { return true; } } existValues.add(checkingColumns); return false; } @Override public void before() { existValues.addAll(queryExistValues()); } } <file_sep>package com.ybj.file.export; import java.io.OutputStream; import java.util.List; import java.util.Map; import com.ybj.file.export.templates.SheetWriteTemplate; /** * 导出工具类 * 方法中带xlsx的导出xlsx文件 * 带xls的导出xls文件 * * @author yanbenjun * */ public class ExcelExportUtils { /** * 1.向輸出數據流中寫入Excel數據 * 2、默認寫到第一個Sheet頁,表頭在第一行,數據從第二行開始 * 3、一次性写入 * 4、表头从数据中提取,但只显示数据(只适用一次性写入所有的数据的情况) * * @param outputStream * 輸出流 * @param dataList * 一次性寫入的數據 */ public static void exportXlsxWithoutHead(OutputStream outputStream, List<Map<String, Object>> dataList) { new XlsxExcelWriter().writeWithoutHead(outputStream, dataList); } /** * 1.向輸出數據流中寫入Excel數據 * 2、默認寫到第一個Sheet頁,表頭在第一行,數據從第二行開始 * 3、一次性写入 * 4、表头从数据中提取,但只显示数据(只适用一次性写入所有的数据的情况) * * @param outputStream * 輸出流 * @param dataList * 一次性寫入的數據 */ public static void exportXlsWithoutHead(OutputStream outputStream, List<Map<String, Object>> dataList) { new XlsExcelWriter().writeWithoutHead(outputStream, dataList); } /** * 1.向輸出數據流中寫入Excel數據 * 2、默認寫到第一個Sheet頁,表頭在第一行,數據從第二行開始 * 3、一次性写入 * * @param outputStream * 輸出流 * @param header * 表頭 * @param dataList * 一次性寫入的數據 */ public static void exportXlsx(OutputStream outputStream, Map<String, String> header, List<Map<String, Object>> dataList) { new XlsxExcelWriter().write(outputStream, header, dataList); } /** * 1.向輸出數據流中寫入Excel數據 * 2、默認寫到第一個Sheet頁,表頭在第一行,數據從第二行開始 * 3、一次性写入 * * @param outputStream * 輸出流 * @param header * 表頭 * @param dataList * 一次性寫入的數據 */ public static void exportXls(OutputStream outputStream, Map<String, String> header, List<Map<String, Object>> dataList) { new XlsExcelWriter().write(outputStream, header, dataList); } /** * 1.向輸出數據流中寫入Excel數據 * 2、默認寫到第一個Sheet頁,表頭在第一行,數據從第二行開始 * 3、数据分批次写入Excel,每一批次的数据通过PageDataQuery查询 * * @param outputStream * 輸出流 * @param header * 表頭 * @param pageDataQuery * 分頁查詢接口數據接口對象 */ public static void exportXlsx(OutputStream outputStream, Map<String, String> header, PageDataQuery pageDataQuery) { new XlsxExcelWriter().write(outputStream, header, pageDataQuery); } /** * 1.向輸出數據流中寫入Excel數據 * 2、默認寫到第一個Sheet頁,表頭在第一行,數據從第二行開始 * 3、数据分批次写入Excel,每一批次的数据通过PageDataQuery查询 * * @param outputStream * 輸出流 * @param header * 表頭 * @param pageDataQuery * 分頁查詢接口數據接口對象 */ public static void exportXls(OutputStream outputStream, Map<String, String> header, PageDataQuery pageDataQuery) { new XlsExcelWriter().write(outputStream, header, pageDataQuery); } /** * 1.向輸出數據流中寫入Excel數據 * 2、多sheet頁數據寫入,根據sheetWriteTemplate中定義的格式寫入 * * @param outputStream * 輸出流 * @param sheetWriteTemplates * 多sheet對應的一些配置 */ public static void exportXlsx(OutputStream outputStream, List<SheetWriteTemplate> sheetWriteTemplates) { new XlsxExcelWriter().write(outputStream, sheetWriteTemplates); } /** * 1.向輸出數據流中寫入Excel數據 * 2、多sheet頁數據寫入,根據sheetWriteTemplate中定義的格式寫入 * * @param outputStream * 輸出流 * @param sheetWriteTemplates * 多sheet對應的一些配置 */ public static void exportXls(OutputStream outputStream, List<SheetWriteTemplate> sheetWriteTemplates) { new XlsExcelWriter().write(outputStream, sheetWriteTemplates); } } <file_sep>package com.ybj.file.parse.regist; public class ToParserFileTypeRegister extends AbstractRegister { private ToParserFileTypeRegister() { } public static ToParserFileTypeRegister singletonInstance() { return InnerInstanceClass.instance; } private static class InnerInstanceClass { private static final ToParserFileTypeRegister instance = new ToParserFileTypeRegister(); } } <file_sep>package com.ybj.file.config.element; import java.io.InputStream; import com.ybj.file.parse.message.ParseContext; import lombok.Getter; import lombok.Setter; /** * 需要解析的的文件信息 * 包括文件全路径、文件解析对应的文件模板:toParseFile * @author Administrator * */ @Getter @Setter public class BaseParseFileInfo { private String fileName; private InputStream inputStream; private ParseContext parseContext = new ParseContext(); private ToParseFile toParseFile; } <file_sep>package com.ybj.file.parse.regist.merger.horizontal; import com.ybj.file.parse.regist.ICanRegist; import com.ybj.file.parse.regist.TypeHandleException; public interface TypeHorizontalMerger<T> extends ICanRegist { public T merge(Object... values) throws TypeHandleException; } <file_sep>package com.ybj.file.parse.regist.validator.factory; import com.ybj.file.parse.regist.validator.RegexValidator; import com.ybj.file.parse.regist.validator.SingleCellValidator; import com.ybj.file.parse.regist.validator.ValidatorExpression; public class RegexCellValidatorFactory implements ValidatorFactory { public static final String REGIST_KEY = RegexValidator.REGIST_KEY; @Override public SingleCellValidator newValidator(ValidatorExpression ve) { try { RegexValidator regexValidator = new RegexValidator(); regexValidator.setRegPattern(ve.getParams()[0]); return regexValidator; } catch (Exception e) { throw new RuntimeException("正则校验器表达式异常", e); } } @Override public String getRegistKey() { return REGIST_KEY; } } <file_sep>package com.ybj.file.parse.message; public abstract class ParseMessage implements IParseMessage { protected boolean hasError; public boolean isHasError() { return hasError; } public void setHasError(boolean hasError) { this.hasError = hasError; } } <file_sep>package com.ybj.file.config.element; public class TagConstants { public static final String FILE_PARSE = "fileParse"; public static final String PARSE_SYSTEM = "parseSystem"; public static final String COLUMNS = "columns"; public static final String TEMPLATES = "templates"; public static final String FILES = "files"; public static final String PARSE_POINT = "parsePoint"; public static final String TO_PARSE_FILE = "toParseFile"; public static final String REF_FILE = "refFile"; public static final String TO_PARSE_TEMPLATE = "toParseFile"; public static final String REF_TEMPLATE = "refTemplate"; public static final String COLUMN_HEAD = "toParseFile"; public static final String REF_COLUMN = "refColumn"; } <file_sep>package com.ybj.file.model.parse; import com.alibaba.fastjson.JSON; /** * 行数据 的 属性值信息 * @author Administrator * */ public class ColumnEntry { /** * xlsx,xls 第key列 */ private Integer key; /** * 数据属性名称-view使用 */ private String title; /** * 数据属性名称-Model使用 */ private String field; /** * 数据属性值 */ private String value; /** * 转换成Java类型 的属性值 */ private Object modelValue; public ColumnEntry(int column, String lastContents) { this.key = column; this.value = lastContents; } public ColumnEntry(String title, String lastContents) { this.title = title; this.value = lastContents; } public Integer getKey() { return key; } public String getValue() { return value; } public String setValue(String value) { return this.value = value; } public String toString() { return JSON.toJSONString(this); } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Object getModelValue() { return modelValue; } public void setModelValue(Object modelValue) { this.modelValue = modelValue; } public String getField() { return field; } public void setField(String field) { this.field = field; } } <file_sep>package com.ybj.file.config.element; public class AttributeContants { public static final String ID = "id"; public static final String NAME = "name"; public static final String REF = "ref"; public static final String TITLE_NAME = "titleName"; public static final String FIELD_NAME = "fieldName"; public static final String TYPE = "type"; public static final String REQUIRED = "required"; public static final String HORIZONTALMERGER = "horizontalMerger"; } <file_sep>package com.ybj.file.parse.core.post.infs; import com.ybj.file.config.element.BaseParseFileInfo; import com.ybj.file.parse.core.ParseException; /** * 解析開始的地方 * @author Administrator * */ public interface ParseStarter { public void startParse(BaseParseFileInfo baseFileInfo) throws ParseException; } <file_sep>package com.ybj.file.config.element; import java.util.HashMap; import java.util.List; import java.util.Map; @XmlElement(name="files") public class Files extends XElement { @XmlElement(name="toParseFile",subElement=ToParseFile.class) private Map<String, ToParseFile> toParseFileMap = new HashMap<String,ToParseFile>(); @Override public void add(XElement xe) { add((ToParseFile)xe); } public void add(ToParseFile toParseFile) { ToParseFile tpf = toParseFileMap.putIfAbsent(toParseFile.getName(), toParseFile); if(tpf != null) { throw new RuntimeException("重复的全局带解析模板文件," + tpf); } } public void addAll(List<ToParseFile> toParseFiles) { for(ToParseFile tpf : toParseFiles) { add(tpf); } } public ToParseFile get(String name) { return toParseFileMap.get(name); } public String toString() { return this.toParseFileMap.toString(); } @Override public void clear() { toParseFileMap.clear(); } } <file_sep>package com.ybj.file.parse.regist.merger.horizontal; import java.util.stream.Stream; import com.ybj.file.parse.regist.TypeHandleException; import com.ybj.file.parse.regist.merger.vertical.TypeVerticalMerger; public class IntegerAddMerger implements TypeHorizontalMerger<Integer>,TypeVerticalMerger<Integer> { public static final String REGIST_KEY = "integeradd"; @Override public Integer merge(Object... values) throws TypeHandleException { return Stream.of(values).filter(v -> v != null).count() == 0 ? null : Stream.of(values).filter(v -> v != null).mapToInt(v -> ((Integer)v)).sum(); } @Override public String getRegistKey() { return REGIST_KEY; } } <file_sep>package com.ybj.file.parse.regist.validator.factory; import java.util.List; import com.ybj.file.config.element.init.ParserBeanFactory; import com.ybj.file.parse.regist.validator.UniqueValidator; public interface UniqueValidatorBuilder extends ParserBeanFactory { @Override public default Class<?> getFactoryClass() { return UniqueValidatorFactory.class; } public UniqueValidator build(String clazzOrBean, List<String> unionKeys); } <file_sep>package com.ybj.file.parse.message; import java.util.ArrayList; import java.util.List; public class RowParseMessage extends ParseMessage { private int rowIndex; private String rowMsg; private List<CellParseMessage> cellParseMsgs = new ArrayList<>(); private List<MultiCellsParseMessage> multiCellsParseMsgs = new ArrayList<>(); public RowParseMessage() { } public RowParseMessage(int rowIndex) { this.rowIndex = rowIndex; } @Override public boolean isHasError() { return !cellParseMsgs.isEmpty() || super.isHasError(); } public int getRowIndex() { return rowIndex; } public void setRowIndex(int rowIndex) { this.rowIndex = rowIndex; } public List<CellParseMessage> getCellParseMsgs() { return cellParseMsgs; } public void add(CellParseMessage em) { cellParseMsgs.add(em); } public void addAll(List<CellParseMessage> ems) { cellParseMsgs.addAll(ems); } public void addMulti(MultiCellsParseMessage em) { multiCellsParseMsgs.add(em); } public void addMultiAll(List<MultiCellsParseMessage> ems) { multiCellsParseMsgs.addAll(ems); } @Override public boolean breakOut() { return false; } public String getRowMsg() { return rowMsg; } public void setRowMsg(String rowMsg) { this.rowMsg = rowMsg; } } <file_sep>package com.ybj.file.parse.core; public class ParseException extends Exception { private String error; /** * */ private static final long serialVersionUID = 6801037286673562840L; public ParseException() { } public ParseException(String error) { super(error); this.error = error; } public ParseException(Exception e) { super(e); } public String getError() { return this.error; } } <file_sep>package com.ybj.file.parse.regist.validator; import org.apache.commons.lang.StringUtils; import com.ybj.file.parse.regist.ICanRegist; import com.ybj.file.parse.regist.TypeHandleException; import com.ybj.file.parse.regist.convertor.DoubleConverter; public class DoubleValidator implements SingleCellValidator, ICanRegist { public static final String REGIST_KEY = DoubleConverter.REGIST_KEY; @Override public String getRegistKey() { return REGIST_KEY; } /** * @param 需要校验的值 * @return 是否有错 true=有错 */ @Override public boolean validate(String value) { try { getTypeValue(value); } catch (TypeHandleException e) { return true; } return false; } @Override public String getErrorMsg() { return "非数字类型"; } @Override public Double getTypeValue(String originalValue) { if (StringUtils.isEmpty(originalValue)) { return null; } try { Double result = Double.parseDouble(originalValue.trim()); return result; } catch (NumberFormatException e) { TypeHandleException tce = new TypeHandleException("非小数类型"); throw tce; } } @Override public String getSimpleName() { return REGIST_KEY; } @Override public Object getParam() { return null; } } <file_sep>package com.ybj.file.parse.core.exception; /** * 在进行数据处理时,需要跳出当前File处理时使用 * @author Administrator * */ public class FileBreakoutException extends RowHandleException { /** * */ private static final long serialVersionUID = -1583732573497130107L; public FileBreakoutException() { } public FileBreakoutException(Exception e) { super(e); } } <file_sep>package com.ybj.file.parse.regist.validator; import org.apache.commons.lang.StringUtils; import com.ybj.file.parse.regist.ICanRegist; public class NotNullValidator implements SingleCellValidator, ICanRegist { public static final String REGIST_KEY = "notnull"; @Override public String getRegistKey() { return REGIST_KEY; } /** * @param 需要校验的值 * @return 是否有错 true=有错 */ @Override public boolean validate(String value) { return StringUtils.isBlank(value); } @Override public String getErrorMsg() { return "非空字段不能为空"; } @Override public Object getTypeValue(String originValue) { return originValue; } @Override public String getSimpleName() { return REGIST_KEY; } @Override public Object getParam() { return null; } } <file_sep>package com.ybj.file.model; public class ToParsePackage { } <file_sep>package com.ybj.file.parse.regist.validator; import java.util.ArrayList; import java.util.List; public abstract class UniqueValidator implements MultiCellValidator { public static final String REGIST_KEY = "unique"; private List<String> unionKeys = new ArrayList<>(); public UniqueValidator() { } public UniqueValidator(List<String> unionKeys) { this.unionKeys.addAll(unionKeys); } @Override public String getSimpleName() { return REGIST_KEY; } @Override public List<String> getUnionKeys() { return this.unionKeys; } @Override public String getErrorMsg() { // TODO Auto-generated method stub return "重复的数据"; } public void addUnionKeys(List<String> unionKeys) { this.unionKeys.addAll(unionKeys); } } <file_sep>package com.ybj.file.parse.regist.merger.vertical; import com.ybj.file.parse.regist.ICanRegist; public interface TypeVerticalMerger<T> extends ICanRegist { public T merge(Object... objects); } <file_sep>package com.ybj.file.parse.message; import java.util.List; import lombok.Getter; import lombok.Setter; import lombok.ToString; @Getter @Setter @ToString public class MultiCellsParseMessage extends Location implements IParseMessage { private String msg; private List<String> cellOriginValues; private List<String> fields; private List<String> titles; private String msgType; public MultiCellsParseMessage() { } public MultiCellsParseMessage(String msg) { this.msg = msg; } public MultiCellsParseMessage(String msg, int sheetId) { this(msg, sheetId, -1); } public MultiCellsParseMessage(String msg, int sheetId, int rowId) { this(msg, sheetId, rowId, -1); } public MultiCellsParseMessage(String msg, int sheetId, int rowId, int columnId) { super(sheetId, rowId, columnId); this.msg = msg; } @Override public boolean breakOut() { return false; } @Override public boolean isHasError() { return false; } } <file_sep>package com.ybj.file.parse.core.post.may; import com.ybj.file.model.parse.ParsedRow; import com.ybj.file.parse.core.exception.RowHandleException; import com.ybj.file.parse.core.post.MidPostRowHandler; import com.ybj.file.parse.core.post.infs.PostRowHandler; import com.ybj.file.parse.message.ParseContext; public class ExcludeFiltHandler extends MidPostRowHandler { public ExcludeFiltHandler() { super(); } public ExcludeFiltHandler(PostRowHandler next) { super(next); } @Override public void processOne(ParsedRow parsedRow, ParseContext parseContext) throws RowHandleException { if(parsedRow.isEmpty()) { return; } next.processOne(parsedRow, parseContext); //TODO 具体的业务可以通过继承该类,复写该方法实现 } } <file_sep>package com.ybj.file.parse.core.post.must; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.stream.Collectors; import com.ybj.file.config.element.ToParseTemplate; import com.ybj.file.model.parse.ColumnEntry; import com.ybj.file.model.parse.ParsedRow; import com.ybj.file.parse.core.exception.RowHandleException; import com.ybj.file.parse.core.post.MidPostRowHandler; import com.ybj.file.parse.core.post.infs.PostRowHandler; import com.ybj.file.parse.message.ParseContext; import com.ybj.file.parse.regist.merger.horizontal.TypeHorizontalMerger; /** * 相同列关键词(表头)的内容合并处理器 * @author Administrator * */ public class SameTitleMergeHandler extends MidPostRowHandler { public SameTitleMergeHandler() { super(); } public SameTitleMergeHandler(PostRowHandler next) { super(next); } @Override public void processOne(ParsedRow parsedRow, ParseContext parseContext) throws RowHandleException { ToParseTemplate toParseTemplate = parsedRow.getCurTemplate(); List<ColumnEntry> cells = parsedRow.getCells(); Map<String,List<ColumnEntry>> map = new HashMap<String, List<ColumnEntry>>(); for(int i=0; i< cells.size(); i++) { ColumnEntry ce = cells.get(i); if(map.get(ce.getField()) == null) { map.put(ce.getField(), new ArrayList<ColumnEntry>()); } map.get(ce.getField()).add(ce); } Map<String, Object> mergeMap = new HashMap<String, Object>(); for(Entry<String, List<ColumnEntry>> entry : map.entrySet()) { String field = entry.getKey(); List<ColumnEntry> ces = entry.getValue(); TypeHorizontalMerger<?> typeMerger = toParseTemplate.getTypeHorizontalMerger(field); List<Object> values = ces.stream().map(ColumnEntry::getModelValue).collect(Collectors.toList()); Object obj = typeMerger.merge(values.toArray()); mergeMap.put(field, obj); } //去重title,并将合并后的值设置进去 Iterator<ColumnEntry> iter = cells.iterator(); Set<String> hasSet = new HashSet<String>(); while(iter.hasNext()) { ColumnEntry ce = iter.next(); String field = ce.getField(); ce.setModelValue(mergeMap.get(field)); if(hasSet.contains(field)) { iter.remove(); } else { hasSet.add(field); } } next.processOne(parsedRow, parseContext); } } <file_sep>package com.ybj.file.parse.core.post.may; import com.ybj.file.model.parse.ParsedRow; import com.ybj.file.parse.core.exception.RowHandleException; import com.ybj.file.parse.core.post.TeminationPostRowHandler; import com.ybj.file.parse.message.ParseContext; public class NormalPrinter implements TeminationPostRowHandler { @Override public void processOne(ParsedRow parsedRow, ParseContext parseContext) throws RowHandleException { if (parseContext.getCurRowMsg().isHasError()) { System.out.println(parseContext.getCurRowMsg().getCellParseMsgs()); } System.out.println("modelRow:" + parsedRow.getModelRow()); } } <file_sep>package com.ybj.file.config.element.init; import com.ybj.file.config.ParseConfigurationException; import com.ybj.file.parse.core.post.TeminationPostRowHandler; public interface TeminationPostRowHandlerFactory extends ParserBeanFactory { public default Class<?> getFactoryClass() { return TeminationPostRowHandlerFactory.class; } public TeminationPostRowHandler build(String beanKey) throws ParseConfigurationException; } <file_sep>package com.ybj.file.parse.regist.validator.enumeration.datasource; import java.util.Map; import com.ybj.file.config.element.init.ParserBeanFactory; public interface EnumDataSource extends ParserBeanFactory { @Override public default Class<?> getFactoryClass() { return EnumDataSource.class; } public Map<String, Object> getKeyvalueMap(String... params); } <file_sep>package com.ybj.file.parse.regist.validator.factory; import com.ybj.file.parse.regist.validator.MaxLengthValidator; import com.ybj.file.parse.regist.validator.SingleCellValidator; import com.ybj.file.parse.regist.validator.ValidatorExpression; public class MaxLengthCellValidatorFactory implements ValidatorFactory { public static final String REGIST_KEY = MaxLengthValidator.REGIST_KEY; @Override public SingleCellValidator newValidator(ValidatorExpression ve) { try { MaxLengthValidator validator = new MaxLengthValidator(); String[] params = ve.getParams(); validator.setValue(Integer.parseInt(params[0])); return validator; } catch (Exception e) { throw new RuntimeException("数字校验表达式异常", e); } } @Override public String getRegistKey() { return REGIST_KEY; } } <file_sep>package com.ybj.file.parse.regist.merger.horizontal; import java.util.ArrayList; import java.util.List; import com.ybj.file.parse.regist.merger.vertical.TypeVerticalMerger; public class StringListCollectMerger implements TypeVerticalMerger<List<String>>, TypeHorizontalMerger<List<String>> { public static final String REGIST_KEY = "stringlist"; @Override public String getRegistKey() { return REGIST_KEY; } @Override public List<String> merge(Object... objects) { List<String> result = new ArrayList<>(); for (Object obj : objects) { if (obj == null) { result.add(null); } else if (obj instanceof String) { result.add((String) obj); } else { throw new RuntimeException("水平合并时数据类型错误"); } } return result; } } <file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.yanbenjun</groupId> <artifactId>FileParseSDK</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <spring-boot.version>2.0.5.RELEASE</spring-boot.version> <java.compiler.version>1.8</java.compiler.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion> </properties> <dependencies> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/dom4j/dom4j --> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>${spring-boot.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <!-- 要将源码放上去,需要加入这个插件 --> <plugin> <artifactId>maven-source-plugin</artifactId> <configuration> <attach>true</attach> </configuration> <executions> <execution> <phase>compile</phase> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project><file_sep>package com.ybj.file.parse; import com.ybj.file.parse.core.ParseException; public interface Parser { public void parse() throws ParseException; } <file_sep>package com.ybj.file.config.element.init; import com.ybj.file.config.ParseConfigurationException; import com.ybj.file.parse.core.post.TeminationPostRowHandler; /** * 类全名生成处后置处理器生成工厂 * @author Administrator * */ public class JavaTeminationPostRowHandlerFactory implements TeminationPostRowHandlerFactory { @Override public TeminationPostRowHandler build(String handlerStr) throws ParseConfigurationException { try { Class<?> cl = Class.forName(handlerStr); Class<? extends TeminationPostRowHandler> handlerClazz = cl.asSubclass(TeminationPostRowHandler.class); TeminationPostRowHandler teminationHandler = handlerClazz.newInstance(); return teminationHandler; } catch (ClassCastException | ClassNotFoundException | InstantiationException | IllegalAccessException e) { throw new ParseConfigurationException(e); } } @Override public String getFactoryType() { return "java"; } } <file_sep>package com.ybj.file.parse.core.post.infs; import com.ybj.file.model.parse.ParsedRow; import com.ybj.file.parse.core.exception.RowHandleException; import com.ybj.file.parse.message.ParseContext; /** * 文件解析行信息后处理器 * @author Administrator * */ public interface PostRowHandler { /** * 当前行处理器需要进行的处理,具体处理类实现 * @param parsedRow * @param parseMessage * @throws RowHandleException */ public void processOne(ParsedRow parsedRow, ParseContext parseContext) throws RowHandleException; /** * 设置下一个行处理器,并返回该处理器 * @param next 需要设置的行处理器 * @return 行处理器 */ public PostRowHandler next(PostRowHandler next); /** * 返回下一个行处理器 * @return */ public PostRowHandler next(); } <file_sep>package com.ybj.file.parse.regist; public interface Register { public boolean regist(ICanRegist t); public boolean regist(String key, ICanRegist t); } <file_sep>package com.ybj.file.parse.core.post.may; import java.util.ArrayList; import java.util.List; import com.ybj.file.model.parse.ParsedRow; import com.ybj.file.parse.core.exception.RowHandleException; import com.ybj.file.parse.core.post.MidPostRowHandler; import com.ybj.file.parse.message.ParseContext; import com.ybj.file.parse.message.ParseMessage; /** * 缓存行数据 * @author Administrator * */ public class CacheHandler extends MidPostRowHandler { private List<ParsedRow> rowCache = new ArrayList<>(); private List<ParseMessage> messages = new ArrayList<>(); @Override public void processOne(ParsedRow parsedRow, ParseContext parseContext) throws RowHandleException { rowCache.add(parsedRow); messages.add(parseContext.getCurRowMsg()); } public List<ParsedRow> getRowCache() { return rowCache; } public List<ParseMessage> getMessages() { return messages; } } <file_sep>package com.ybj.file.parse; import com.ybj.file.config.element.BaseParseFileInfo; import com.ybj.file.parse.core.ParseException; import com.ybj.file.parse.core.post.FileParseExtractor; import com.ybj.file.parse.message.ParseContext; public class FileParser implements Parser { private BaseParseFileInfo baseFileInfo; public FileParser(BaseParseFileInfo baseFileInfo) { this.baseFileInfo = baseFileInfo; } public ParseContext getContext() { return baseFileInfo.getParseContext(); } @Override public void parse() throws ParseException { new FileParseExtractor(null).startParse(baseFileInfo); } } <file_sep>package com.ybj.file.parse.regist.convertor; import org.apache.commons.lang.StringUtils; import com.ybj.file.parse.regist.TypeHandleException; public class IntegerConverter implements TypeConvertor<Integer> { public static final String REGIST_KEY = "integer"; @Override public Integer getTypeValue(String value) throws TypeHandleException { if(StringUtils.isEmpty(value)) { return null; } try { Integer result = Integer.parseInt(trimZeroAndDot(value.trim())); return result; } catch (NumberFormatException e) { TypeHandleException tce = new TypeHandleException("非整数类型"); throw tce; } } /** * 使用java正则表达式去掉多余的.与0 * @param s * @return */ private static String trimZeroAndDot(String s){ if(s.indexOf(".") > 0){ s = s.replaceAll("0+?$", "");//去掉多余的0 s = s.replaceAll("[.]$", "");//如最后一位是.则去掉 } return s; } public static IntegerConverter singleton() { return IntegerConverterBuilder.singleton; } private static class IntegerConverterBuilder { private static final IntegerConverter singleton = new IntegerConverter(); } @Override public String getRegistKey() { return REGIST_KEY; } } <file_sep>package com.ybj.file.parse.regist; import com.ybj.file.parse.regist.merger.horizontal.DoubleAddMerger; import com.ybj.file.parse.regist.merger.horizontal.IntegerAddMerger; import com.ybj.file.parse.regist.merger.horizontal.StringJoinMerger; import com.ybj.file.parse.regist.merger.horizontal.StringListCollectMerger; import com.ybj.file.parse.regist.merger.horizontal.TypeHorizontalMerger; public class TypeHorizontalMergerRegister extends AbstractRegister { public TypeHorizontalMerger<?> getTypeHorizontalMerger(String typeName) { ICanRegist cr = super.getObject(typeName.trim()); if(cr == null) { throw new RuntimeException("没有注册与类型:“" + typeName + "”对应的类型转换器"); } return (TypeHorizontalMerger<?>)cr; } public static TypeHorizontalMergerRegister singleton() { return TypeHorizontalMergerRegisterBuilder.singleton; } private static class TypeHorizontalMergerRegisterBuilder { private static final TypeHorizontalMergerRegister singleton = new TypeHorizontalMergerRegister(); static { singleton.regist(new StringJoinMerger()); singleton.regist(new IntegerAddMerger()); singleton.regist(new DoubleAddMerger()); singleton.regist(new StringListCollectMerger()); } } } <file_sep>package com.ybj.file.config.element; import java.lang.annotation.ElementType; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Repeatable(XmlElements.class) @Target({ElementType.TYPE,ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface XmlElement { String name(); Class<?> subElement() default XElement.class; } <file_sep>package com.ybj.file.parse.regist.merger.vertical; import java.util.stream.Stream; public class FirstNoneEmptyMerger implements TypeVerticalMerger<Object> { public static final String REGIST_KEY = "firstnoneempty"; @Override public String getRegistKey() { return REGIST_KEY; } @Override public Object merge(Object... objects) { return Stream.of(objects).filter(obj->obj!=null).findFirst().orElse(null); } } <file_sep>package com.ybj.file.export; import java.io.IOException; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.VerticalAlignment; import org.apache.poi.ss.usermodel.Workbook; import com.ybj.file.export.templates.SheetWriteTemplate; public abstract class ExcelWriter { private static int dataFlushSize = 1000; private Log log = LogFactory.getLog(ExcelWriter.class); /** * 1.向輸出數據流中寫入Excel數據 * 2、默認寫到第一個Sheet頁,表頭在第一行,數據從第二行開始 * 3、一次性写入 * 4、表头从数据中提取,但只显示数据(只适用一次性写入所有的数据的情况) * * @param outputStream * 輸出流 * @param dataList * 一次性寫入的數據 */ public void writeWithoutHead(OutputStream outputStream, List<Map<String, Object>> dataList) { SheetWriteTemplate sheetWriteTemplate = new SheetWriteTemplate(); sheetWriteTemplate.addAll(findHeaderFromDataList(dataList)); sheetWriteTemplate.setPageDataQuery((pageNum) -> { return pageNum == 0 ? dataList : Collections.emptyList(); }); sheetWriteTemplate.setDataStartIndex(0); write(outputStream, Stream.of(sheetWriteTemplate).collect(Collectors.toList())); } private Map<String, String> findHeaderFromDataList(List<Map<String, Object>> dataList) { Map<String, String> header = new LinkedHashMap<>(); for (Map<String, Object> data : dataList) { for (String entry : data.keySet()) { header.put(entry, entry); } } return header; } /** * 1.向輸出數據流中寫入Excel數據 * 2、默認寫到第一個Sheet頁,表頭在第一行,數據從第二行開始 * 3、一次性写入 * * @param outputStream * 輸出流 * @param header * 表頭 * @param dataList * 一次性寫入的數據 */ public void write(OutputStream outputStream, Map<String, String> header, List<Map<String, Object>> dataList) { SheetWriteTemplate sheetWriteTemplate = new SheetWriteTemplate(); sheetWriteTemplate.addAll(header); sheetWriteTemplate.setPageDataQuery((pageNum) -> { return pageNum == 0 ? dataList : Collections.emptyList(); }); write(outputStream, Stream.of(sheetWriteTemplate).collect(Collectors.toList())); } /** * 1.向輸出數據流中寫入Excel數據 * 2、默認寫到第一個Sheet頁,表頭在第一行,數據從第二行開始 * 3、数据分批次写入Excel,每一批次的数据通过PageDataQuery查询 * @param outputStream 輸出流 * @param header 表頭 * @param pageDataQuery 分頁查詢接口數據接口對象 */ public void write(OutputStream outputStream, Map<String, String> header, PageDataQuery pageDataQuery) { SheetWriteTemplate sheetWriteTemplate = new SheetWriteTemplate(); sheetWriteTemplate.addAll(header); write(outputStream, Stream.of(sheetWriteTemplate).collect(Collectors.toList())); } /** * 1.向輸出數據流中寫入Excel數據 * 2、多sheet頁數據寫入,根據sheetWriteTemplate中定義的格式寫入 * * @param outputStream 輸出流 * @param sheetWriteTemplates 多sheet對應的一些配置 */ public void write(OutputStream outputStream, List<SheetWriteTemplate> sheetWriteTemplates) { try (Workbook workbook = createWorkbook(dataFlushSize)) { for (int i = 0; i < sheetWriteTemplates.size(); i++) { SheetWriteTemplate curTemplate = sheetWriteTemplates.get(i); Sheet curSheet = workbook.createSheet((i + 1) + "." + curTemplate.getSheetName()); write(curSheet, curTemplate); } workbook.write(outputStream); } catch (IOException e) { log.debug("Write workbook to outputstream error.", e); } } /** * 写入表头,并且返回每一列表头的长度Map * * @param sheet * @param header * @param cellStyle * @return */ private Map<Integer, Integer> writeHead(Sheet sheet, Map<String, String> header, CellStyle cellStyle) { // 用于计算每一列的最长宽度,当结束写入sheet时,设置列宽 Map<Integer, Integer> columnMaxLengthMap = new HashMap<>(); Row headRow = sheet.createRow(0); int i = 0; // 标题列数 for (Map.Entry<String, String> entry : header.entrySet()) { columnMaxLengthMap.put(i, entry.getValue().getBytes().length); Cell cell = headRow.createCell(i++); cell.setCellStyle(cellStyle); cell.setCellValue(entry.getValue()); } return columnMaxLengthMap; } private CellStyle createCellStyleFromWorkbook(Workbook workbook) { // 创建单元格,并设置值表头 设置表头居中 CellStyle styleMain = workbook.createCellStyle(); // 水平居中 styleMain.setAlignment(HorizontalAlignment.CENTER); // 垂直居中 styleMain.setVerticalAlignment(VerticalAlignment.CENTER); return styleMain; } private void write(Sheet sheet, SheetWriteTemplate sheetWriteTemplate) { Workbook workbook = sheet.getWorkbook(); // 产生表格标题行 sheet.setVerticallyCenter(true); // 创建单元格,并设置值表头 设置表头居中 CellStyle styleMain = createCellStyleFromWorkbook(workbook); // 寫表頭 Map<String, String> header = sheetWriteTemplate.getHeader(); if (header.isEmpty()) { log.warn("表头为空,放弃写入Excel。"); return; } Map<Integer, Integer> columnMaxLengthMap = writeHead(sheet, header, styleMain); PageDataQuery pageDataQuery = sheetWriteTemplate.getPageDataQuery(); if (pageDataQuery == null) { throw new RuntimeException("缺少数据查询对象, PageDataQuery"); } int pageNum = 0; int offset = 0; int curRowIndex = sheetWriteTemplate.getDataStartIndex(); List<Map<String, Object>> dataList = null; do { // 注意循環條件,寫pageDataQuery查詢方法時一定要有結束時為空的結果 dataList = pageDataQuery.query(pageNum++); if (dataList != null && dataList.size() > 0) { for (int i=0; i<dataList.size(); i++) { Map<String, Object> rowData = dataList.get(i); if (curRowIndex >= getMaxSheetSize()) {// 数据超过当前sheet所能承载的极限,新建sheet存储数据 // 先设置上个sheet的各个列的宽度 setColumnSize(sheet, columnMaxLengthMap); // 开始下一个sheet sheet = workbook.createSheet(sheetWriteTemplate.getSheetName() + (++offset)); curRowIndex = sheetWriteTemplate.getDataStartIndex(); columnMaxLengthMap = writeHead(sheet, header, styleMain); } Row row = sheet.createRow(curRowIndex++); int colIndex = 0; for (Map.Entry<String, String> headerEntry : header.entrySet()) { if (rowData.containsKey(headerEntry.getKey())) { Object cellValue = rowData.get(headerEntry.getKey()); // 设置该列最大宽度 if (cellValue != null) { int curRowColumnLength = cellValue.toString().getBytes().length; if (columnMaxLengthMap.get(colIndex) < curRowColumnLength) { columnMaxLengthMap.put(colIndex, curRowColumnLength); } } Cell cell = row.createCell(colIndex++); cell.setCellStyle(styleMain); setCellValue(cell, cellValue); } } } } } while (dataList != null && dataList.size() > 0); setColumnSize(sheet, columnMaxLengthMap); } /** * 自适应宽度(中文支持) * * @param sheet * @param size */ private static void setColumnSize(Sheet sheet, Map<Integer, Integer> columnMaxLengthMap) { for (Map.Entry<Integer, Integer> entry : columnMaxLengthMap.entrySet()) { sheet.setColumnWidth(entry.getKey(), entry.getValue() * 256); } } private void setCellValue(Cell cell, Object value) { if (value instanceof String) { cell.setCellValue((String) value); } else if (value instanceof Integer) { int intValue = (Integer) value; cell.setCellValue(intValue); } else if (value instanceof Float) { float fValue = (Float) value; cell.setCellValue(fValue); } else if (value instanceof Double) { double dValue = (Double) value; cell.setCellValue(dValue); } else if (value instanceof Long) { long longValue = (Long) value; cell.setCellValue(longValue); } else if (value instanceof Boolean) { boolean bValue = (Boolean) value; cell.setCellValue(bValue); } else if (value instanceof Date) { Date date = (Date) value; SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss"); cell.setCellValue(sdf.format(date)); } else { // 其它数据类型都当作字符串简单处理 cell.setCellValue(value == null ? "" : value.toString()); } } protected abstract Workbook createWorkbook(int flushSize); protected abstract int getMaxSheetSize(); } <file_sep>package com.ybj.file.export; import java.util.List; import java.util.Map; public interface PageDataQuery { public List<Map<String, Object>> query(int pageNum); } <file_sep>package com.ybj.file.config.element.xml; import org.xml.sax.Attributes; import com.alibaba.fastjson.JSON; import com.ybj.file.parse.core.xml.XmlPath; public class XmlPositionInfo { /** * 相对row路径的子路径 */ private XmlPath xmlPath = new XmlPath(); /** * 路径方向(父目录、子目录) */ private int pathDirect; /** * 属性key的位置,0表示取标签,1表示取标签的属性=attrName的属性,2表示取标签的属性=attrName且属性值=attrValue;3表示取标签内容 * 一般来说就0,1,2有意义 */ private int keyPath; /** * 属性Value的位置,0表示取标签,1表示取标签的属性=attrName的属性,2表示取标签的属性=attrName的属性值;3表示取标签内容 * 一般来说就2和3有意义 */ private int valuePath; private String attrName = ""; private String attrValue = ""; /** * 匹配当前标签是否有符合当前key位置的key,有则返回key值 * @param tagName * @param attrs * @return */ public String findKey(String tagName, Attributes attrs) { int keyPathType = keyPath; if (keyPathType == 0) { return tagName; } else if (keyPathType == 1) { for (int i = 0; i < attrs.getLength(); i++) { if (attrs.getQName(i).equalsIgnoreCase(attrName)) { return this.attrName; } } } else if (keyPathType == 2) { for (int i = 0; i < attrs.getLength(); i++) { if (attrs.getQName(i).equalsIgnoreCase(attrName) && attrs.getValue(i).equalsIgnoreCase(attrValue)) { return this.attrValue; } } } return null; } /** * 匹配当前标签下是否有符合当前值位置信息,有则返回该值 * @param name * @param attrs * @return */ public String findValue(String name, Attributes attrs) { int valuePathType = valuePath; if (valuePathType == 0) { return name; } else if (valuePathType == 1) { return null; } else if (valuePathType == 2) { for (int i = 0; i < attrs.getLength(); i++) { if (attrs.getQName(i).equalsIgnoreCase(attrName)) { return attrs.getValue(i); } } } return null; } public XmlPath getXmlPath() { return xmlPath; } public void setXmlPath(XmlPath xmlPath) { this.xmlPath = xmlPath; } public int getPathDirect() { return pathDirect; } public void setPathDirect(int pathDirect) { this.pathDirect = pathDirect; } public int getKeyPath() { return keyPath; } public void setKeyPath(int keyPath) { this.keyPath = keyPath; } public int getValuePath() { return valuePath; } public void setValuePath(int valuePath) { this.valuePath = valuePath; } public String getAttrName() { return attrName; } public void setAttrName(String attrName) { this.attrName = attrName; } public String getAttrValue() { return attrValue; } public void setAttrValue(String attrValue) { this.attrValue = attrValue; } public String toString() { return JSON.toJSONString(this); } public static XmlPositionInfo parse(String jsonStr) { return JSON.parseObject(jsonStr, XmlPositionInfo.class); } public static String getExampleJson() { XmlPositionInfo xpxc = new XmlPositionInfo(); XmlPath xmlPath = new XmlPath(); xmlPath.addLast("simpleData"); xpxc.setXmlPath(xmlPath); xpxc.setPathDirect(1); xpxc.setKeyPath(2); xpxc.setValuePath(3); xpxc.setAttrName("name"); xpxc.setAttrValue("ASDL"); return xpxc.toString(); } public static void main(String[] args) { String json = getExampleJson(); System.out.println(json); } } <file_sep>package com.ybj.file.config; public interface BeforeTemplateParseIntializable { public void before(); } <file_sep>package com.ybj.file.parse.regist; import com.ybj.file.parse.regist.merger.horizontal.DoubleAddMerger; import com.ybj.file.parse.regist.merger.horizontal.IntegerAddMerger; import com.ybj.file.parse.regist.merger.horizontal.StringJoinMerger; import com.ybj.file.parse.regist.merger.vertical.FirstNoneEmptyMerger; import com.ybj.file.parse.regist.merger.vertical.ListCollectionMerger; import com.ybj.file.parse.regist.merger.vertical.TypeVerticalMerger; public class TypeVerticalMergerRegister extends AbstractRegister { public TypeVerticalMerger<?> getTypeVerticalMerger(String typeName) { ICanRegist cr = super.getObject(typeName.trim()); if(cr == null) { throw new RuntimeException("没有注册与类型:“" + typeName + "”对应的类型转换器"); } return (TypeVerticalMerger<?>)cr; } public static TypeVerticalMergerRegister singleton() { return TypeVerticalMergerRegisterBuilder.singleton; } private static class TypeVerticalMergerRegisterBuilder { private static final TypeVerticalMergerRegister singleton = new TypeVerticalMergerRegister(); static { singleton.regist(new StringJoinMerger()); singleton.regist(new IntegerAddMerger()); singleton.regist(new DoubleAddMerger()); singleton.regist(new ListCollectionMerger()); singleton.regist(new FirstNoneEmptyMerger()); } } }
7b970ce83559560b70853e14ba44a877f9694b80
[ "Markdown", "Java", "Maven POM" ]
65
Java
yanbenjun/FileParseSDK
046cf986b9b783f509441836dea46107af662535
f4501ef93697b3f78b41340926a1454b13733e52
refs/heads/master
<repo_name>antonioadv08/lab-express-cinema<file_sep>/starter_code/bin/seeds.js const mongoose = require ('mongoose') const Movies = require ('./../models/Movies') const moviesJSON = require ('./movies.json') mongoose .connect('mongodb://localhost/cinema', {useNewUrlParser: true}) .then(x => { console.log(`Connected to Mongo! Database name: "${x.connections[0].name}"`) }) .catch(err => { console.error('Error connecting to mongo', err) }); Movies.deleteMany() .then(moviesDeleted => { return Movies.create(moviesJSON) }) .then(moviesCreated => { console.log('Movies created') process.exit(0) })<file_sep>/starter_code/routes/movies.js const express = require ('express') const moviesRouter = express.Router() const mongoose = require ('mongoose') const Movies = require ('./../models/Movies') mongoose .connect('mongodb://localhost/cinema', {useNewUrlParser: true}) .then(x => { console.log(`Connected to Mongo! Database name: "${x.connections[0].name}"`) }) .catch(err => { console.error('Error connecting to mongo', err) }); moviesRouter.get('/', (req, res) => { Movies.find() .then(listOfMovies => { res.render('movies', {listOfMovies}) }) }) module.exports = moviesRouter;<file_sep>/starter_code/routes/movie.js const movieRouter = require ('express').Router() const Movies = require ('./../models/Movies') const mongoose = require ('mongoose') mongoose .connect('mongodb://localhost/cinema', {useNewUrlParser: true}) .then(x => { console.log(`Connected to Mongo! Database name: "${x.connections[0].name}"`) }) .catch(err => { console.error('Error connecting to mongo', err) }); movieRouter.get('/:movieID', (req, res) => { Movies.findById(req.params.movieID) .then(movieFound => { res.render('movie', {movieFound}) }) }) module.exports = movieRouter
c2b36dbf34c73bda5e5bc6c63630569650534048
[ "JavaScript" ]
3
JavaScript
antonioadv08/lab-express-cinema
d96b0c7a61ed894d242efe6e15c76214fa9e690e
8c775068e25f3820ffe6956eec54f5562b7c67c9
refs/heads/master
<file_sep>class City { constructor(name = '', coordi = '') { this.name = name; this.coordi = coordi; this.coordiMap = new Map(); } coordiDraw() { this.coordiMap.set('Tel Aviv,IL', [32.08, 34.78]); this.coordiMap.set('New York,US', [40.73, -73.99]); this.coordiMap.set('Paris,FR', [48.86, 2.35]); this.coordiMap.set('Barcelona,ES', [41.38, 2.18]); this.coordiMap.set('Toronto,CA', [43.65, -79.39]); this.coordiMap.set('Los Angeles,US', [34.05, -118.24]); this.coordiMap.set('Sydney,AU', [-33.85, 151.22]); this.coordiMap.set('Tokyo,JP', [35.68, 139.76]); this.coordiMap.set('London,UK', [51.51, -0.13]); this.coordiMap.set('Rome,IT', [12.48, 41.89]); this.coordiMap.forEach( (coordinates) => { const marker = L.marker(coordinates).addTo(mymap); this.coordiMap.set(coordinates, marker); }) } getCoordiMap() { return this.coordiMap; } setChosenCoordi() { switch (this.name) { case 'Tel Aviv,IL': this.coordi = this.coordiMap.get('Tel Aviv,IL'); break; case 'New York,US': this.coordi = this.coordiMap.get('New York,US'); break; case 'Paris,FR': this.coordi = this.coordiMap.get('Paris,FR'); break; case 'Barcelona,ES': this.coordi = this.coordiMap.get('Barcelona,ES'); break; case 'Toronto,CA': this.coordi = this.coordiMap.get('Toronto,CA'); break; case 'Los Angeles,US': this.coordi = this.coordiMap.get('Los Angeles,US'); break; case 'Sydney,AU': this.coordi = this.coordiMap.get('Sydney,AU'); break; case 'Tokyo,JP': this.coordi = this.coordiMap.get('Tokyo,JP'); break; case 'London,UK': this.coordi = this.coordiMap.get('London,UK'); break; case 'Rome,IT': this.coordi = this.coordiMap.get('Rome,IT'); break; } this.setChosen(); } setChosen() { const redIcon = L.icon({ iconUrl: "https://maps.gstatic.com/mapfiles/api-3/images/spotlight-poi2_hdpi.png", }); const blueIcon = L.icon({ iconUrl: "https://unpkg.com/leaflet@1.3.1/dist/images/marker-icon.png", }); this.coordiMap.forEach((marker, coordinates ) => { if(typeof coordinates === 'object'){ marker.setIcon(blueIcon); } }) const chosenMarker= this.coordiMap.get(this.coordi); chosenMarker.setIcon(redIcon); mymap.setView(this.coordi, 7); } }<file_sep>let apiAccess = {}; let init = {}; let mymap = L.map('mapid').setView([0, 0], 2); const ACCESS_TOKEN = '<KEY>'; const KEY = 'e76868e4617fa9179c42aa2672b286b5'; const elms = document.querySelectorAll('button') for (let i = 0; i < elms.length - 1; i++) { elms[i].addEventListener('click', () => { sendCity(elms[i].value); }) } L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', { attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' + 'Imagery © <a href="http://mapbox.com">Mapbox</a>', maxZoom: 18, id: 'mapbox.streets', accessToken: ACCESS_TOKEN }).addTo(mymap); const coordiInitMap = new City(); coordiInitMap.coordiDraw(); function sendCity(myCity) { apiReq(myCity); setViewCoordi(myCity); } function setViewCoordi(myCity) { const coordi = new City(myCity); coordi.coordiMap = coordiInitMap.getCoordiMap(); coordi.setChosenCoordi(); } function apiReq(myCity) { const requestURL = `http://api.openweathermap.org/data/2.5/weather?q=${myCity}&units=metric&appid=${KEY}`; $.ajax({ url: requestURL, type: "GET", dataType: "json", success: (data) => { apiAccess = data; initWeather(); displayWeather(); } }); } function initWeather() { init = new Weather(); init.setInit(apiAccess); } function displayWeather() { init.print(); } function zoomOut() { mymap.setView([0, 0], 2); }
4eea14bf09e1cc6e6fdd5057243511461f3332a9
[ "JavaScript" ]
2
JavaScript
shahafWebiks/WeatherMap
2129c9de43b4d02c9caf38579f707be5b10c8563
1da08c33ddefa8ecdd7284394c7b0f5fc13ccfba
refs/heads/master
<file_sep>#!/bin/bash # global bash script function first () { echo "Hello" } function second () { echo "World" } function third () { echo "!" } function fourth () { echo " And so on." } function fifth () { echo "One more time." }<file_sep># Test-Submodule-Global A repository to test submodule functionality. Create Submodule: - navigate into project folder - git submodule add URL_TO_GIT_REPOSITORY FILE_PATH_OF_SUBMODULE Show status of submodule f.i. the branch where it referenced to: - navigate into project folder - git submodule status Update Submodule: - navigate into sub-module folder - git pull If reference is discaraged: - navigate into sub-module folder - git checkout master
0f383352d5ca47edf728e8b56164ed4c8ed8a416
[ "Markdown", "Shell" ]
2
Shell
Git-Creativist/Test-Submodule-Global
d9df0964dfbec213130555d8061aae9f8bf26c8c
2dbbbed41760485c0e74fab18d8d5b9735e35129
refs/heads/master
<file_sep>import pandas as pd import numpy as np from sklearn.pipeline import Pipeline from sklearn.preprocessing import Imputer from sklearn.ensemble import RandomForestClassifier from sklearn.grid_search import GridSearchCV df = pd.read_csv('../data/train.csv') df = df.drop(['Name','Ticket','Cabin'], axis=1) df.head(2) from scipy.stats import mode df['Embarked'] = df['Embarked'].fillna(mode(df['Embarked'])[0][0]) df['Gender'] = df['Sex'].map({'female':0, 'male':1}).astype(int) df = pd.concat([df,pd.get_dummies(df['Embarked'], prefix='Embarked')], axis=1) df = df.drop(['Sex','Embarked'], axis=1) age_mean = df['Age'].mean() age_median = df['Age'].median() train_data = df.values imputer = Imputer(missing_values='NaN') classifier = RandomForestClassifier(n_estimators=100) pipeline = Pipeline([ ('imp', imputer), ('clf', classifier), ]) parameter_grid = { 'imp__strategy': ['mean', 'median'], 'clf__max_features': [0.5, 1], 'clf__max_depth': [5, None], } grid_search = GridSearchCV(pipeline, parameter_grid, cv=5, verbose=3) grid_search.fit(train_data[0:,2:], train_data[0:,1]) print sorted(grid_search.grid_scores_, key=lambda x: x.mean_validation_score) print grid_search.best_score_ print grid_search.best_params_ df['Age'] = df['Age'].fillna(age_mean) train_data = df.values model = RandomForestClassifier(n_estimators = 100, max_features=0.5, max_depth=5) model = model.fit(train_data[0:,2:],train_data[0:,1]) df_test = pd.read_csv('../data/test.csv') df_test = df_test.drop(['Name','Ticket','Cabin'], axis=1) df_test['Age'] = df_test['Age'].fillna(age_mean) fare_means = df.pivot_table('Fare', index='Pclass', aggfunc='mean') df_test['Fare'] = df_test[['Fare','Pclass']].apply(lambda x: fare_means[x['Pclass']] if pd.isnull(x['Fare']) else x['Fare'], axis=1) df_test['Gender'] = df_test['Sex'].map({'female':0, 'male':1}).astype(int) df_test = pd.concat([df_test, pd.get_dummies(df_test['Embarked'], prefix='Embarked')], axis=1) df_test = df_test.drop(['Sex','Embarked'], axis=1) test_data = df_test.values output = model.predict(test_data[:,1:]) results = np.c_[test_data[:,0].astype(int), output.astype(int)] df_result = pd.DataFrame(results, columns = ['PassengerId', 'Survived']) print df_result
90675563eb99c8598c224fe93219a47de399929e
[ "Python" ]
1
Python
MittalShruti/KaggleTitanic
c93a4c773b8fe25a3ac37c698f92a774144f0a71
930ea063176fd84aa6b8dd3cde6f703ff4bbafd2
refs/heads/master
<file_sep>package 郑迪; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class TestHttpRequest { public static void main(String[] args) throws Exception { // JSONObject postag=new JSONObject(); // postag.put("operator", "and"); // postag.put("analyzer", "whitespace"); // postag.put("type", "phrase"); // postag.put("slop", 0); // String query="dog"; // postag.put("query", query); // JSONObject Match = new JSONObject(); // Match.put("postag", postag); // JSONObject Query = new JSONObject(); // Query.put("match", Match); // /** // * 为什么一个Query要写这么复杂 // */ // JSONObject HttpQuery=new JSONObject(); // JSONArray Fields = new JSONArray(); // Fields.put(""); // HttpQuery.put("fields", Fields); // HttpQuery.put("size", 0); // HttpQuery.put("query", Query); // System.out.println(HttpQuery.toString()); // /** // * 查询黑名单 // */ // String blackReturn=HttpRequest.doPost(HttpQuery.toString(), // "http://10.110.6.43:9200/essay/_search"); // System.out.println(blackReturn); // /** // * 查询白名单 // */ // String whiteReturn=HttpRequest.doPost(HttpQuery.toString(), // "http://10.110.6.43:9200/pigai/_search"); // System.out.println(whiteReturn); // JSONObject BlackJs = new JSONObject(blackReturn); // JSONObject WhiteJs = new JSONObject(whiteReturn); // String blackNum = BlackJs.optJSONObject("hits").opt("total").toString(); // String whiteNum = WhiteJs.optJSONObject("hits").opt("total").toString(); // System.out.println(blackNum+" "+whiteNum); getBlack(", a better"); getWhite(", better"); } public static int getBlack(String query) throws Exception{ JSONObject postag=new JSONObject(); postag.put("operator", "and"); postag.put("analyzer", "whitespace"); postag.put("type", "phrase"); postag.put("slop", 0); postag.put("query", query); JSONObject Match = new JSONObject(); Match.put("postag", postag); JSONObject Query = new JSONObject(); Query.put("match", Match); JSONObject HttpQuery=new JSONObject(); JSONArray Fields = new JSONArray(); Fields.put(""); HttpQuery.put("fields", Fields); HttpQuery.put("size", 0); HttpQuery.put("query", Query); String blackReturn=HttpRequest.doPost(HttpQuery.toString(), "http://10.110.6.43:9200/essay/_search"); JSONObject BlackJs = new JSONObject(blackReturn); String blackNum = BlackJs.optJSONObject("hits").opt("total").toString(); int bNum=Integer.parseInt(blackNum); System.out.println(bNum); return bNum; } public static int getWhite(String query) throws Exception{ JSONObject postag=new JSONObject(); postag.put("operator", "and"); postag.put("analyzer", "whitespace"); postag.put("type", "phrase"); postag.put("slop", 0); postag.put("query", query); JSONObject Match = new JSONObject(); Match.put("postag", postag); JSONObject Query = new JSONObject(); Query.put("match", Match); JSONObject HttpQuery=new JSONObject(); JSONArray Fields = new JSONArray(); Fields.put(""); HttpQuery.put("fields", Fields); HttpQuery.put("size", 0); HttpQuery.put("query", Query); /** * 以上全是封装json,感觉有点太麻烦了 */ String whiteReturn=HttpRequest.doPost(HttpQuery.toString(), "http://10.110.6.43:9200/pigai/_search"); JSONObject WhiteJs = new JSONObject(whiteReturn); String whiteNum = WhiteJs.optJSONObject("hits").opt("total").toString(); int wNum=Integer.parseInt(whiteNum); System.out.println(wNum); return wNum; } } <file_sep>import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import edu.stanford.nlp.trees.Tree; public class n_gram { public static void main(String args[]) { // args[0] = "C:\\Users\\zhdi\\clue_a.n5.snt.tree"; // args[1] = "3"; String[] Files = new String[args.length - 1]; // { // "/home/cikuu/limaolin/clue_snt_each650w_tree/clue_a.n5.snt.tree", // "/home/cikuu/limaolin/clue_snt_each650w_tree/clue_b.n5.snt.tree", // "/home/cikuu/limaolin/clue_snt_each650w_tree/clue_c.n5.snt.tree", // "/home/cikuu/limaolin/clue_snt_each650w_tree/clue_d.n5.snt.tree", // "/home/cikuu/limaolin/clue_snt_each650w_tree/clue_e.n5.snt.tree", // "/home/cikuu/limaolin/clue_snt_each650w_tree/clue_f.n5.snt.tree", // "/home/cikuu/limaolin/clue_snt_each650w_tree/clue_g.n5.snt.tree", // "/home/cikuu/limaolin/clue_snt_each650w_tree/clue_h.n5.snt.tree", // "/home/cikuu/limaolin/clue_snt_each650w_tree/clue_i.n5.snt.tree", // "/home/cikuu/limaolin/clue_snt_each650w_tree/clue_j.n5.snt.tree", // "/home/cikuu/limaolin/clue_snt_each650w_tree/clue_k.n5.snt.tree", // "/home/cikuu/limaolin/clue_snt_each650w_tree/clue_l.n5.snt.tree", // "/home/cikuu/limaolin/clue_snt_each650w_tree/clue_m.n5.snt.tree", // "/home/cikuu/limaolin/clue_snt_each650w_tree/clue_n.n5.snt.tree", // "/home/cikuu/limaolin/clue_snt_each650w_tree/clue_o.n5.snt.tree", // "/home/cikuu/limaolin/clue_snt_each650w_tree/clue_p.n5.snt.tree", // "/home/cikuu/limaolin/clue_snt_each650w_tree/clue_q.n5.snt.tree", // "/home/cikuu/limaolin/clue_snt_each650w_tree/clue_r.n5.snt.tree", // "/home/cikuu/limaolin/clue_snt_each650w_tree/clue_s.n5.snt.tree", // "/home/cikuu/limaolin/clue_snt_each650w_tree/clue_t.n5.snt.tree", // "/home/cikuu/limaolin/clue_snt_each650w_tree/clue_u.n5.snt.tree", // "/home/cikuu/limaolin/clue_snt_each650w_tree/clue_v.n5.snt.tree", // "/home/cikuu/limaolin/clue_snt_each650w_tree/clue_w.n5.snt.tree", // "/home/cikuu/limaolin/clue_snt_each650w_tree/clue_x.n5.snt.tree", // "/home/cikuu/limaolin/clue_snt_each650w_tree/clue_y.n5.snt.tree", // "/home/cikuu/limaolin/clue_snt_each650w_tree/clue_z.n5.snt.tree" // "C:\\Users\\zhdi\\test1.txt", // "C:\\Users\\zhdi\\clue_a.n5.snt.tree" // }; for (int i = 0; i < Files.length; i++) { Files[i] = args[i].toString(); } int n = (int) args[args.length - 1].charAt(0) - 48; System.out.println(n); for (int i = 0; i < Files.length; i++) { String FileName = Files[i]; String WriteFileName = Files[i] + "." + n + "gram"; File file = new File(FileName); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); FileWriter writer = new FileWriter(WriteFileName); String tempString = null; while ((tempString = reader.readLine()) != null) { try { Tree t = Tree.valueOf(tempString); if (t == null) { System.out.println(tempString); continue; } TreeDependency.NGram(t, writer, n); } catch (Exception e1) { continue; } }// while() reader.close(); writer.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } }// try-catch }// for(Files[]) }// main }
34c298dea343ea6e798e31a90db33cea53234d76
[ "Java" ]
2
Java
y111x/yyxTest
85e5938441e9978ac00869231e5a28352d6b1bc9
e556fbf17385a76feea9c71b26c37bae038e2ca8
refs/heads/master
<repo_name>ESalmeronRV/TheDiceeGame<file_sep>/index.js // function printRandomNumber1(){ // document.getElementById("randomNumberTest").innerHTML = randomNumber1; // } function printRandomDiceImg() { var randomNumber1 = Math.floor(1 + Math.random() * 6); var randomNumber2 = Math.floor(1 + Math.random() * 6); // document.getElementById("randomNumberTest").innerHTML = randomNumber1; if (randomNumber1 == 1) { document.getElementById("dicePlayer1ID").src = "images/dice1.png"; } else if (randomNumber1 == 2) { document.getElementById("dicePlayer1ID").src = "images/dice2.png"; } else if (randomNumber1 == 3) { document.getElementById("dicePlayer1ID").src = "images/dice3.png"; } else if (randomNumber1 == 4) { document.getElementById("dicePlayer1ID").src = "images/dice4.png"; } else if (randomNumber1 == 5) { document.getElementById("dicePlayer1ID").src = "images/dice5.png"; } else if (randomNumber1 == 6) { document.getElementById("dicePlayer1ID").src = "images/dice6.png"; } if (randomNumber2 == 1) { document.getElementById("dicePlayer2ID").src = "images/dice1.png"; } else if (randomNumber2 == 2) { document.getElementById("dicePlayer2ID").src = "images/dice2.png"; } else if (randomNumber1 == 3) { document.getElementById("dicePlayer2ID").src = "images/dice3.png"; } else if (randomNumber2 == 4) { document.getElementById("dicePlayer2ID").src = "images/dice4.png"; } else if (randomNumber2 == 5) { document.getElementById("dicePlayer2ID").src = "images/dice5.png"; } else if (randomNumber2 == 6) { document.getElementById("dicePlayer2ID").src = "images/dice6.png"; } if(randomNumber1>randomNumber2){ document.getElementById("result").innerHTML = "Player 1 Wins!"; } else if (randomNumber1<randomNumber2){ document.getElementById("result").innerHTML = "Player 2 Wins!"; } else{ document.getElementById("result").innerHTML = "Draw!"; } }
6c6c3307cb679cd36e1e31a10bd5400f981256c5
[ "JavaScript" ]
1
JavaScript
ESalmeronRV/TheDiceeGame
c77156bcc2ff6d9eba13f3313c7990add51b5c2b
27493da73d6a78fa462dffc2c543b576e4350fe3
refs/heads/master
<repo_name>caisimongit/Framework.Mayiboy.ExcelHelper<file_sep>/Framework.Mayiboy.ExcelHelper/TableColumnAttribute.cs using System; namespace Framework.Mayiboy.ExcelHelper { /// <summary> /// Table的标题 /// </summary> public sealed class TableColumnAttribute : Attribute { /// <summary> /// /// </summary> /// <param name="columnName"></param> public TableColumnAttribute(params string[] columnName) { this.ColumnName = columnName; } /// <summary> /// Table 标题集合 /// </summary> public string[] ColumnName { get; private set; } } }<file_sep>/Framework.Mayiboy.ExcelHelper/ExcelHelper.cs using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using NPOI.HPSF; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; namespace Framework.Mayiboy.ExcelHelper { public class ExcelHelper { #region 将DataSet导入到Excel的MemoryStream /// <summary> /// 将DataSet导入到Excel格式的内存中 /// </summary> /// <param name="dsSource">数据表集合</param> /// <param name="lastAuthor">最后修改者</param> /// <param name="sheetSize">工作表大小</param> /// <param name="company">所属公司</param> /// <param name="isAutoCellWidth">自动识别单元格宽度</param> /// <returns></returns> public static MemoryStream Export(DataSet dsSource, string lastAuthor, int sheetSize = 65535, string company = "蚂蚁男孩", bool isAutoCellWidth = true) { var book = FillWorkbook(dsSource, lastAuthor, sheetSize, company); MemoryStream ms = new MemoryStream(); book.Write(ms); ms.Seek(0, SeekOrigin.Begin); return ms; } #endregion #region 将DataTable导出到Excel的MemoryStream /// <summary> /// DataTable导出到Excel格式的MemoryStream /// </summary> /// <param name="dtSource">数据表</param> /// <param name="lastAuthor">作者</param> /// <param name="sheetSize">工作表大小</param> /// <param name="company">所属公司</param> /// <param name="isAutoCellWidth">自动识别单元格宽度</param> /// <remarks> /// 如果DataTable行数大于设置的SheetSize则将数据分割成多个Sheet /// </remarks> /// <returns></returns> public static MemoryStream Export(DataTable dtSource, string lastAuthor, int sheetSize = 65535, string company = "蚂蚁男孩", bool isAutoCellWidth = true) { HSSFWorkbook workbook = new HSSFWorkbook(); List<ISheet> sheetlist = new List<ISheet>(); #region 分割sheet var sheetnum = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(dtSource.Rows.Count) / sheetSize)); for (int i = 0; i < sheetnum; i++) { var sheetname = (i == 0 ? dtSource.TableName : dtSource.TableName + i); var sheet = string.IsNullOrEmpty(sheetname) ? workbook.CreateSheet() : workbook.CreateSheet(sheetname); sheetlist.Add(sheet); } #endregion #region 文档属性信息 DocumentSummaryInformation information = PropertySetFactory.CreateDocumentSummaryInformation(); information.Company = company; workbook.DocumentSummaryInformation = information; SummaryInformation information2 = PropertySetFactory.CreateSummaryInformation(); information2.Author = company; information2.ApplicationName = company; information2.LastAuthor = lastAuthor; information2.Comments = lastAuthor; information2.Title = company; information2.Subject = company + "的单表格"; information2.CreateDateTime = DateTime.Now; workbook.SummaryInformation = information2; #endregion #region 设置每个列宽度 int[] numArray = new int[dtSource.Columns.Count]; foreach (DataColumn column in dtSource.Columns) { var realColName = GetRealColName(column.ColumnName); numArray[column.Ordinal] = Encoding.GetEncoding(0x3a8).GetBytes(realColName).Length; } if (isAutoCellWidth) { for (int i = 0; i < dtSource.Rows.Count; i++) { for (int j = 0; j < dtSource.Columns.Count; j++) { int length = Encoding.GetEncoding(0x3a8).GetBytes(dtSource.Rows[i][j].ToString()).Length; if (length > numArray[j]) { numArray[j] = length; } } } } #endregion #region 表头样式 ICellStyle style = workbook.CreateCellStyle(); style.Alignment = HorizontalAlignment.Center; IFont font = workbook.CreateFont(); font.FontHeightInPoints = 10; font.Boldweight = 700; style.SetFont(font); #endregion #region 填充标题 foreach (var t in sheetlist) { var row = t.CreateRow(0); foreach (DataColumn column in dtSource.Columns) { var realColName = GetRealColName(column.ColumnName); row.CreateCell(column.Ordinal).SetCellValue(realColName); row.GetCell(column.Ordinal).CellStyle = style; int w = numArray[column.Ordinal] + 1; if (w > 0xff) { w = 0xff; } t.SetColumnWidth(column.Ordinal, w * 0x100); } } #endregion #region 单元格数据格式 List<ICellStyle> cellstylelist = new List<ICellStyle>(); for (int i = 0; i < dtSource.Columns.Count; i++) { string format = GetFormat(dtSource.Columns[i].ColumnName); if (string.IsNullOrEmpty(format)) { cellstylelist.Add(null); } else { ICellStyle item = workbook.CreateCellStyle(); item.DataFormat = workbook.CreateDataFormat().GetFormat(format); cellstylelist.Add(item); } } ICellStyle cellstyledatetime = workbook.CreateCellStyle(); cellstyledatetime.DataFormat = workbook.CreateDataFormat().GetFormat("yyyy-MM-dd HH:mm:ss"); #endregion for (int i = 0; i < sheetlist.Count; i++) { var rownum = 1;//从第2行填充数据 int startnum = i * sheetSize; int endnum = (((i + 1) * sheetSize) > dtSource.Rows.Count) ? dtSource.Rows.Count : ((i + 1) * sheetSize); for (int k = startnum; k < endnum; k++) { DataRow datarow = dtSource.Rows[k]; IRow row = sheetlist[i].CreateRow(rownum); for (int j = 0; j < dtSource.Columns.Count; j++) { DateTime minValue; ICell cell = row.CreateCell(dtSource.Columns[j].Ordinal); string value = (datarow[dtSource.Columns[j]] == null) ? string.Empty : datarow[dtSource.Columns[j]].ToString().Trim(); if (string.IsNullOrEmpty(value)) { goto SetCellNoV; } switch (dtSource.Columns[j].DataType.ToString()) { case "System.TimeSpan": case "System.Guid": case "System.String": { cell.SetCellValue(value); continue; } case "System.DateTime": { DateTime.TryParse(value, out minValue); cell.CellStyle = cellstylelist[j] ?? cellstyledatetime; cell.SetCellValue(minValue); continue; } case "System.Boolean": { bool result = false; bool.TryParse(value, out result); cell.SetCellValue(result); continue; } case "System.Int16": case "System.Int32": case "System.Int64": case "System.Byte": { int num10 = 0; int.TryParse(value, out num10); cell.SetCellValue((double)num10); if (cellstylelist[j] != null) { cell.CellStyle = cellstylelist[j]; } continue; } case "System.Decimal": case "System.Double": { double num11 = 0.0; double.TryParse(value, out num11); cell.SetCellValue(num11); if (cellstylelist[j] != null) { cell.CellStyle = cellstylelist[j]; } continue; } case "System.DBNull": { cell.SetCellValue(""); continue; } case "System.Byte[]": { byte[] bs = (byte[])datarow[dtSource.Columns[j]]; cell.SetCellValue(ToHexIs0X(bs)); continue; } default: goto SetCellNoV; } SetCellNoV: cell.SetCellValue(""); } rownum++; } } MemoryStream stream = new MemoryStream(); workbook.Write(stream); stream.Seek(0, SeekOrigin.Begin); return stream; } #endregion #region 将列表导入到Excel中 /// <summary> /// 将列表导入到Excel中 /// </summary> /// <typeparam name="T">类型</typeparam> /// <param name="list">列表</param> /// <param name="lastAuthor">最修改者</param> /// <param name="sheetSize">工作表大小</param> /// <param name="company">所属公司</param> /// <returns></returns> public static MemoryStream Export<T>(List<T> list, string lastAuthor, int sheetSize = 65000, string company = "蚂蚁男孩") { var table = ConvertToDataTable<T>(list); return Export(table, lastAuthor, sheetSize, company); } #endregion #region xls导入DataSet /// <summary> /// xls导入DataSet /// </summary> /// <param name="stream">Excel文档流</param> /// <returns></returns> public static DataSet Import(Stream stream) { DataSet ds = new DataSet(); var workbook = WorkbookFactory.Create(stream); var evaluator = WorkbookFactory.CreateFormulaEvaluator(workbook); for (int i = 0; i < workbook.NumberOfSheets; i++) { ISheet sheet = workbook.GetSheetAt(i); if (sheet != null) { DataTable table = new DataTable(sheet.SheetName); IEnumerator rowEnumerator = sheet.GetRowEnumerator(); //添加列头 if (rowEnumerator.MoveNext()) { var current = (IRow)rowEnumerator.Current; foreach (ICell cell in current) { table.Columns.Add(cell.StringCellValue.Trim()); } } //添加值 while (rowEnumerator.MoveNext()) { var current = (IRow)rowEnumerator.Current; DataRow tbrow = table.NewRow(); for (int j = 0; j < table.Columns.Count; j++) { ICell cell = current.GetCell(j); if (cell == null) { tbrow[j] = null; } else { switch (cell.CellType) { case CellType.Numeric: { if (DateUtil.IsCellDateFormatted(cell)) { tbrow[j] = cell.DateCellValue; } else { tbrow[j] = cell.NumericCellValue; } } break; case CellType.Blank: { tbrow[j] = ""; } break; case CellType.Formula: { tbrow[j] = evaluator.Evaluate(cell).StringValue; } break; default: tbrow[j] = cell.StringCellValue; break; } } } table.Rows.Add(tbrow); } ds.Tables.Add(table); } } return ds; } #endregion #region 将List列表转化为DataTable /// <summary> /// 将List列表转化为DataTable /// </summary> /// <typeparam name="T">类型</typeparam> /// <param name="list">数据列表</param> /// <returns></returns> public static DataTable ConvertToDataTable<T>(List<T> list) { Type type = typeof(T); using (DataTable table = new DataTable()) { TableColumnAttribute customAttribute; string str; PropertyInfo[] properties = type.GetProperties(); foreach (PropertyInfo info in properties) { if (info.GetCustomAttribute<TableColumnAttribute>() != null) { var propertyType = info.PropertyType; var type3 = Nullable.GetUnderlyingType(propertyType) ?? propertyType; customAttribute = info.GetCustomAttribute<TableColumnAttribute>(); str = customAttribute.ColumnName[0]; table.Columns.Add(str, type3); } } foreach (var t in list) { DataRow row2 = table.NewRow(); foreach (PropertyInfo info in properties) { customAttribute = info.GetCustomAttribute<TableColumnAttribute>(); if (customAttribute != null) { str = customAttribute.ColumnName[0]; row2[str] = info.GetValue(t, null) ?? DBNull.Value; } } table.Rows.Add(row2); } return table; } } #endregion #region 将Table列表转化为List /// <summary> /// 将Table列表转化为List /// </summary> /// <typeparam name="T">实体类型</typeparam> /// <param name="table">数据列表</param> /// <returns></returns> public static List<T> ConvertToList<T>(DataTable table) { List<T> list = new List<T>(); for (int i = 0; i < table.Rows.Count; i++) { list.Add(CreateItem<T>(table.Rows[i])); } return list; } #endregion #region Private Method /// <summary> /// 将DataSet转换为WorkBook表格 /// </summary> /// <param name="dsSource">数据表集合</param> /// <param name="lastAuthor">最后修改者</param> /// <param name="sheetSize">工作表大小</param> /// <param name="company">所属公司</param> /// <param name="isAutoCellWidth">自动识别单元格宽度</param> /// <returns></returns> private static HSSFWorkbook FillWorkbook(DataSet dsSource, string lastAuthor, int sheetSize, string company = "蚂蚁男孩", bool isAutoCellWidth = true) { HSSFWorkbook workbook = new HSSFWorkbook(); #region 文档属性信息 DocumentSummaryInformation dsinformation = PropertySetFactory.CreateDocumentSummaryInformation(); dsinformation.Company = company; workbook.DocumentSummaryInformation = dsinformation; SummaryInformation siinformation = PropertySetFactory.CreateSummaryInformation(); siinformation.Author = company; siinformation.ApplicationName = company; siinformation.LastAuthor = lastAuthor; siinformation.Comments = lastAuthor; siinformation.Title = company; siinformation.Subject = company + "的单表格"; siinformation.CreateDateTime = DateTime.Now; workbook.SummaryInformation = siinformation; #endregion #region 表头样式 ICellStyle cellstyle = workbook.CreateCellStyle(); cellstyle.Alignment = HorizontalAlignment.Center; IFont font = workbook.CreateFont(); font.FontHeightInPoints = 10; font.Boldweight = 700; cellstyle.SetFont(font); #endregion if (dsSource != null && dsSource.Tables.Count > 0) { for (int q = 0; q < dsSource.Tables.Count; q++) { var dtSource = dsSource.Tables[q]; ISheet sheet = workbook.CreateSheet(dtSource.TableName); FillSheet(workbook, sheet, dtSource, sheetSize, cellstyle, isAutoCellWidth); } } return workbook; } /// <summary> /// 填充Sheet /// <param name="workbook">工作表格</param> /// <param name="sheet">Sheet</param> /// <param name="dtSource">表格</param> /// <param name="cellstyle">高亮样式</param> /// <param name="isAutoCellWidth">自动识别单元格宽度</param> /// </summary> private static void FillSheet(HSSFWorkbook workbook, ISheet sheet, DataTable dtSource, int sheetSize, ICellStyle cellstyle, bool isAutoCellWidth) { #region 设置每个列宽度 int[] numArray = new int[dtSource.Columns.Count]; foreach (DataColumn column in dtSource.Columns) { var realColName = GetRealColName(column.ColumnName); numArray[column.Ordinal] = Encoding.GetEncoding(0x3a8).GetBytes(realColName).Length; } if (isAutoCellWidth) { for (int i = 0; i < dtSource.Rows.Count; i++) { for (int j = 0; j < dtSource.Columns.Count; j++) { int length = Encoding.GetEncoding(0x3a8).GetBytes(dtSource.Rows[i][j].ToString()).Length; if (length > numArray[j]) { numArray[j] = length; } } } } #endregion #region 填充标题 var headrow = sheet.CreateRow(0); foreach (DataColumn column in dtSource.Columns) { var realColName = GetRealColName(column.ColumnName); headrow.CreateCell(column.Ordinal).SetCellValue(realColName); headrow.GetCell(column.Ordinal).CellStyle = cellstyle; int w = numArray[column.Ordinal] + 1; if (w > 0xff) { w = 0xff; } sheet.SetColumnWidth(column.Ordinal, w * 0x100); } #endregion #region 单元格数据格式 List<ICellStyle> cellstylelist = new List<ICellStyle>(); for (int i = 0; i < dtSource.Columns.Count; i++) { string format = GetFormat(dtSource.Columns[i].ColumnName); if (string.IsNullOrEmpty(format)) { cellstylelist.Add(null); } else { ICellStyle item = workbook.CreateCellStyle(); item.DataFormat = workbook.CreateDataFormat().GetFormat(format); cellstylelist.Add(item); } } ICellStyle cellstyledatetime = workbook.CreateCellStyle(); cellstyledatetime.DataFormat = workbook.CreateDataFormat().GetFormat("yyyy-MM-dd HH:mm:ss"); #endregion var rownum = 1;//从第2行Excel表格填充数据 #region 填充数据列表 int total = dtSource.Rows.Count > sheetSize ? sheetSize : dtSource.Rows.Count; for (int k = 0; k < total; k++) { DataRow datarow = dtSource.Rows[k]; IRow row = sheet.CreateRow(rownum); for (int j = 0; j < dtSource.Columns.Count; j++) { ICell cell = row.CreateCell(dtSource.Columns[j].Ordinal); string value = (datarow[dtSource.Columns[j]] == null) ? string.Empty : datarow[dtSource.Columns[j]].ToString().Trim(); if (string.IsNullOrEmpty(value)) { goto SetCellNoV; } switch (dtSource.Columns[j].DataType.ToString()) { case "System.TimeSpan": case "System.Guid": case "System.String": { cell.SetCellValue(value); continue; } case "System.DateTime": { DateTime minValue; DateTime.TryParse(value, out minValue); cell.CellStyle = cellstylelist[j] ?? cellstyledatetime; cell.SetCellValue(minValue); continue; } case "System.Boolean": { bool result = false; bool.TryParse(value, out result); cell.SetCellValue(result); continue; } case "System.Int16": case "System.Int32": case "System.Int64": case "System.Byte": { int num10 = 0; int.TryParse(value, out num10); cell.SetCellValue((double)num10); if (cellstylelist[j] != null) { cell.CellStyle = cellstylelist[j]; } continue; } case "System.Decimal": case "System.Double": { double num11 = 0.0; double.TryParse(value, out num11); cell.SetCellValue(num11); if (cellstylelist[j] != null) { cell.CellStyle = cellstylelist[j]; } continue; } case "System.DBNull": { cell.SetCellValue(""); continue; } case "System.Byte[]": { byte[] bs = (byte[])datarow[dtSource.Columns[j]]; cell.SetCellValue(ToHexIs0X(bs)); continue; } default: goto SetCellNoV; } SetCellNoV: cell.SetCellValue(""); } rownum++; } #endregion } /// <summary> /// /// </summary> /// <param name="oriName"></param> /// <returns></returns> private static string GetRealColName(string oriName) { if (string.IsNullOrEmpty(oriName)) { return oriName; } int index = oriName.IndexOf("@$@", StringComparison.Ordinal); if (index == -1) { return oriName; } return oriName.Substring(0, index); } /// <summary> /// /// </summary> /// <param name="oriName"></param> /// <returns></returns> private static string GetFormat(string oriName) { if (string.IsNullOrEmpty(oriName)) { return null; } int index = oriName.IndexOf("@$@", StringComparison.Ordinal); if (index == -1) { return null; } return oriName.Substring(index + "@$@".Length).Trim(); } /// <summary> /// 获取Table一行数据并转换为实体 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="row"></param> /// <returns></returns> private static T CreateItem<T>(DataRow row) { var type = typeof(T); T obj = Activator.CreateInstance<T>(); var infolist = type.GetProperties().Where(e => e.GetCustomAttribute<TableColumnAttribute>() != null && e.GetCustomAttribute<TableColumnAttribute>().ColumnName.Length > 0).ToList(); foreach (DataColumn column in row.Table.Columns) { var info = infolist.FirstOrDefault(e => e.GetCustomAttribute<TableColumnAttribute>().ColumnName.Contains(column.ColumnName)); if (info != null) { var value = ChangeType(row[column.ColumnName], info.PropertyType); if (info.CanWrite) { info.SetValue(obj, value, null); } } } return obj; } /// <summary> /// /// </summary> /// <param name="value"></param> /// <param name="conversion"></param> /// <returns></returns> private static object ChangeType(object value, Type conversion) { var t = conversion; if (value == DBNull.Value) { return null; } if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) { if (value == DBNull.Value) { return null; } t = Nullable.GetUnderlyingType(t); } else if (conversion == typeof(string)) { return Convert.ChangeType(value.ToString(), t, null); } //处理不规范时间字符串 if (value is string && t == typeof(DateTime)) { value = ToDateTime(value.ToString()); } return Convert.ChangeType(value, t, null); } /// <summary> /// String to DateTime(字符串 转换成 时间) /// </summary> /// <param name="s">String</param> /// <param name="def">Default</param> /// <returns>Byte</returns> private static DateTime ToDateTime(string s, DateTime def = default(DateTime)) { //时间字符串格式 yyyyMMdd if (s.Length == 8 && Regex.IsMatch(s, "^[0-9]{4}[0-9]{2}[0-9]{2}$", RegexOptions.IgnoreCase)) { return new DateTime(int.Parse(s.Substring(0, 4)), int.Parse(s.Substring(4, 2)), int.Parse(s.Substring(6, 2))); } DateTime result; return DateTime.TryParse(s, out result) ? result : def; } /// <summary> /// 转化为16进制 /// </summary> /// <param name="bytes"></param> /// <returns></returns> public static string ToHexIs0X(byte[] bytes) { string hexString = string.Empty; if (bytes != null) { StringBuilder strB = new StringBuilder(); for (int i = 0; i < bytes.Length; i++) { strB.Append(bytes[i].ToString("X2")); } hexString = strB.ToString(); } return string.IsNullOrEmpty(hexString) ? hexString : "0x" + hexString; } #endregion } } <file_sep>/TestConsole/OrderExcelModel.cs using Framework.Mayiboy.ExcelHelper; namespace TestConsole { public class OrderExcelModel { /// <summary> /// 订单Id /// </summary> [TableColumn("订单主键Id")] public int Id { get; set; } /// <summary> /// 订单号 /// </summary> [TableColumnAttribute("订单号")] public string OrderNumber { get; set; } /// <summary> /// 订单金额 /// </summary> [TableColumnAttribute("订单金额", "金额")] public decimal OrderAmount { get; set; } /// <summary> /// 订单类型 /// </summary> [TableColumnAttribute("订单类型")] public string OrderType { get; set; } /// <summary> /// 订单来源 /// </summary> [TableColumnAttribute("订单来源")] public int Source { get; set; } } }<file_sep>/README.md # Framework.Mayiboy.ExcelHelper<file_sep>/TestConsole/Program.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Framework.Mayiboy.ExcelHelper; using Framework.Mayiboy.Utility; namespace TestConsole { class Program { static void Main(string[] args) { List<OrderExcelModel> list = new List<OrderExcelModel>(); list.Add(new OrderExcelModel { Id = 1, OrderNumber = DateTime.Now.ToString("ACyyyyMMddHHmmssfff"), OrderAmount = 888.88M, OrderType = "电子商品", Source = 1 }); #region 写入到文件 using (MemoryStream ms = ExcelHelper.Export(list, "蚂蚁男孩")) { using (FileStream fs = new FileStream("mayiboy.xls", FileMode.Create)) { byte[] buff = ms.ToArray(); fs.Write(buff, 0, buff.Length); fs.Close(); ms.Close(); } } #endregion #region 读取Excel文件 var filestream = File.OpenRead("mayiboy.xls"); var dataset = ExcelHelper.Import(filestream); var table = dataset.Tables[0]; var list2 = ExcelHelper.ConvertToList<OrderExcelModel>(table); #endregion list2.ForEach(e => { Console.WriteLine(e.ToJson()); }); Console.WriteLine("ok"); Console.ReadKey(); } } }
5b7ea0b81c0fac76bedee934023045db2d0532fb
[ "Markdown", "C#" ]
5
C#
caisimongit/Framework.Mayiboy.ExcelHelper
0171f146799ed3c81d44687a7e77bec7f966e84b
c9b27a33daf7b6b6a90a830ec21ae4518aa45532
refs/heads/main
<repo_name>AASTHA2005/c36<file_sep>/sketch.js var gamestate=0; var playercount; var database; var form,player,game; var allPlayers; var car1,car2,car3,car4,cars; var car1img,car2img,car3img,car4img,track,ground; function preload(){ track=loadImage("sprites/track.jpg") car1img=loadImage("sprites/car1.png") car2img=loadImage("sprites/car2.png") car3img=loadImage("sprites/car3.png") car4img=loadImage("sprites/car4.png") ground=loadImage("sprites/ground.png") } function setup(){ createCanvas(displayWidth-20,displayHeight-30); database=firebase.database(); game=new Game() game.getstate() game.start(); } function draw(){ background("white"); if(playercount===4) { game.update(1) } if(gamestate===1){ clear(); game.play(); } if(gamestate===2){ game.end(); } // drawSprites() }
9f01dc5b32405e1f7471a6aa20bd7d3f3e20682d
[ "JavaScript" ]
1
JavaScript
AASTHA2005/c36
ad67a3037442ada7765c75a5db196e16f6061ffa
b33a4f6f9264d835e3e55761bca68a2711a10077
refs/heads/master
<repo_name>recycode/backend<file_sep>/heroku/recycode.rb require 'rubygems' require 'sinatra' require 'mongo' require 'json/ext' include Mongo COLLECTION = 'recycode' DROPOFF = 'drop-off' configure do if ENV['MONGOHQ_URL'] conn = Mongo::Connection.from_uri(ENV['MONGOHQ_URL']) uri = URI.parse(ENV['MONGOHQ_URL']) set :mongo_connection, conn set :mongo_db, conn.db(uri.path.gsub(/^\//, '')) else conn = MongoClient.new("localhost", 27017) set :mongo_connection, conn set :mongo_db, conn.db('test') end coll = settings.mongo_db[DROPOFF] coll.create_index([['loc', Mongo::GEO2DSPHERE]]) end get '/collections/?' do settings.mongo_db.collection_names end helpers do def object_id val BSON::ObjectId.from_string(val) end def document_by_id id id = object_id(id) if String === id settings.mongo_db[COLLECTION].find_one(:_id => id).to_json end def document_by_barcode barcode settings.mongo_db[COLLECTION].find_one(:barcode => barcode).to_json end end get '/documents/?' do content_type :json settings.mongo_db[COLLECTION].find.to_a.to_json end # find a document by its ID get '/document/:id/?' do content_type :json document_by_id(params[:id]).to_json end post '/new_document/?' do content_type :json new_id = settings.mongo_db[COLLECTION].insert params document_by_id(new_id).to_json end put '/update/:id/?' do content_type :json id = object_id(params[:id]) # settings.mongo_db['test'].update(:_id => id, params) document_by_id(id).to_json end put '/update_name/:id/?' do content_type :json id = object_id(params[:id]) name = params[:name] # settings.mongo_db['test'].update(:_id => id, {"$set" => {:name => name}}) document_by_id(id).to_json end # delete the specified document and return success delete '/remove/:id' do content_type :json settings.mongo_db[COLLECTION].remove(:_id => object_id(params[:id])) {:success => true}.to_json end ### RECYCODE PRODUCT API get '/' do "Recycode2" end post '/product/add' do content_type :json new_id = settings.mongo_db[COLLECTION].insert params document_by_id(new_id).to_json end get '/product/:barcode' do content_type :json #document_by_barcode(params[:barcode]).to_json document_by_barcode(params[:barcode]) end post '/product/img/:barcode' do grid = Mongo::GridFileSystem.new(settings.mongo_db) grid.open("#{params[:barcode]}", 'w') do |f| f.write(request.env["rack.input"].read) end {:success => true}.to_json end get '/product/img/:barcode' do raw = "" grid = Mongo::GridFileSystem.new(settings.mongo_db) grid.open("#{params[:barcode]}", 'r') do |f| raw = f.read end content_type 'image/jpeg' raw end ### RECYCODE GEO API post '/place' do d = JSON.parse(request.env["rack.input"].string) settings.mongo_db[DROPOFF].insert(d) {:success => true}.to_json end get '/places' do places = Array.new settings.mongo_db[DROPOFF].find.each {|row| places.push(row) } places.to_json end get '/places/near' do lat = params[:lat].to_f lng = params[:lng].to_f dst = params[:dist].to_i places = Array.new op ={"loc" => {"$near" => { "$geometry" => {"type" => "Point", "coordinates" => [lng, lat]},"$maxDistance" => dst}}} settings.mongo_db[DROPOFF].find(op).each {|row| places.push(row) } places.to_json end delete '/place/remove/:id' do content_type :json settings.mongo_db[DROPOFF].remove(:_id => object_id(params[:id])) {:success => true}.to_json end<file_sep>/heroku/Gemfile ### Gemfile ### source "https://rubygems.org" ruby "2.1.0" gem 'sinatra' gem 'mongo' gem 'bson_ext'
4c2a21f979502b7518917db94db344d01ff6300a
[ "Ruby" ]
2
Ruby
recycode/backend
3f5cf152c87aa12f8b132bf7556859af61862c4f
2e8cb405231814281f9cede72d981b411415c604
refs/heads/master
<repo_name>priyanka4491/GlobalSF<file_sep>/src/aura/TestReviewChart/TestReviewChartController.js ({ doInit : function(component, event, helper) { var page = component.get("v.page") || 1; helper.getAllProgram(component,event,helper, page); }, pageChange: function(component,event,helper) { var page; var direction; page = component.get("v.page") || 1; direction = event.getParam("direction"); page = direction === "previous" ? (page - 1) : (page + 1); console.log('page---' +page); helper.getAllProgram(component,event,helper,page); } })<file_sep>/src/aura/Frontier_ProgramPlanning_SelectedProduct/Frontier_ProgramPlanning_SelectedProductController.js ({ doInit : function(component, event, helper) { var appEvent = $A.get("e.c:Frontier_ProgramPlanningSelectProduct"); var selectProduct = component.get("v.selectedProducts"); console.log("Selected" +selectProduct); appEvent.setParams({"selectedProducts" : selectProduct}); appEvent.fire(); } })<file_sep>/src/aura/Frontier_AccountDashborad_DealerList/Frontier_AccountDashborad_DealerListHelper.js ({ getdealerdetails : function(component,event,helper,page) { var action = component.get("c.getDealersList"); var crop = component.get("v.crop"); var season = component.get("v.season"); var visit = component.find("visit").get("v.value"); action.setParams({ pageNumber :page, pageSize : component.get("v.pageSize"), crop : crop, season : season, accType : component.get("v.accType"), visit : (visit=='None'?'null':visit) }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ var retResponse =JSON.parse(response.getReturnValue()); if(retResponse.length > 0){ component.set("v.total",retResponse[0].Count); component.set("v.pages",Math.ceil((retResponse[0].Count)/component.get("v.pageSize"))); component.set("v.page",page); } else if(retResponse.length == 0){ component.set("v.total",0); component.set("v.pages",1); component.set("v.page",1); } component.set("v.accountsList", retResponse); } else{ console.log('Error'); } }); $A.enqueueAction(action); } })<file_sep>/src/aura/Frontier_GrowerAccount_TopProducts/Frontier_GrowerAccount_TopProductsHelper.js ({ getTopProducts : function(component, event) { console.log("Inside doinit"); var action = component.get("c.topProducts"); action.setCallback(this, function(response) { var topProdcutsValue = response.getReturnValue(); console.log("topProdcutsValue" + topProdcutsValue); component.set("v.topProducts",topProdcutsValue); if (response.getState() === "SUCCESS") { console.log("Success"); } else if (response.getState() === "ERROR") { $A.log("Errors", response.getError()); } }); $A.enqueueAction(action); } })<file_sep>/src/aura/Test_Calendar_Using_JQ/Test_Calendar_Using_JQController.js ({ loadCalender : function(component, event, helper) { $('#mycalendar').monthly({ mode: 'event', //jsonUrl: 'events.json', dataType: 'json', //xmlUrl: 'events.xml', events:{"monthly": [{id:1,name:"Sales Visit & Proposal",startdate:"2017-2-8",enddate:"2017-2-8",starttime:"12:00",endtime:"2:00", color:"rgba(0, 255, 0, 0.498039215686275)",url:""}, {id:2,name:"Field Check",startdate:"2017-2-12",enddate:"2017-2-12",starttime:"11:00",endtime:"12:00", color:"rgba(102, 204, 255, 1)",url:""}]} }); }, addNewTouchPoint : function(component, event, helper){ console.log("I ma in lightining..."); } })<file_sep>/src/aura/Frontier_SalesRep_Performance/Frontier_SalesRep_PerformanceController.js ({ loadChart : function(component,event){ console.log('Inside chart'); var bchart = "myChart"; //var bchart = 'myChart'+'0012C000002MJjfQAG'; console.log("Inside chart load" + bchart); var data = { labels: ['778,923 YTD Volume'], datasets: [ { type : "horizontalBar", backgroundColor: "#32CD32", data: [100] }, { type : "horizontalBar", backgroundColor: "rgb(237, 168, 49)", data: [100] } ]}; var options = { responsive : true, maintainAspectRatio: false, curvature: 0.5, overlayBars: true, bezierCurve : false, animation:false, tooltip:false, scaleLabel:{ display:false }, legend:{ display: false }, scales: { xAxes: [{ display:false, stacked: true, gridLines: { display:false }, barPercentage : 0.2 }], yAxes: [{ stacked: true, display:false, gridLines: { display:false, color: "#fff" }, display: true, barPercentage : 0.5, ticks: { // minimum will be 0, unless there is a lower value. suggestedMin: 0, // minimum value will be 0. beginAtZero: true } }] }, animation: { duration: 0, onComplete: function () { var self = this, chartInstance = this.chart, ctx = chartInstance.ctx; ctx.font = '10px Arial'; ctx.textAlign = "center"; ctx.fillStyle = "White"; Chart.helpers.each(self.data.datasets.forEach((dataset, datasetIndex) => { var meta = self.getDatasetMeta(datasetIndex), total = 0, //total values to compute fraction labelxy = [], offset = Math.PI / 2, //start sector from top radius, centerx, centery, lastend = 0; //prev arc's end line: starting with 0 for (var val of dataset.data) { total += val; } Chart.helpers.each(meta.data.forEach((element, index) => { radius = element._model.outerRadius; centerx = element._model.x; centery = element._model.y; var thispart = dataset.data[index], arcsector = Math.PI * (2 * thispart / total); if (element.hasValue() && dataset.data[index] > 0) { labelxy.push(lastend + arcsector / 2 + Math.PI + offset); } else { labelxy.push(-1); } lastend += arcsector; }), self) var lradius = radius * 3 / 4; for (var idx in labelxy) { if (labelxy[idx] === -1) continue; var langle = labelxy[idx], dx = centerx + lradius * Math.cos(langle), dy = centery + lradius * Math.sin(langle), val = Math.round(dataset.data[idx] / total * 100); //ctx.fillText(self.data.labels[idx],dx, dy); wrapText(ctx,self.data.labels[idx],dx,dy,8,3); console.log('dx=>'+dx); console.log('dy=>'+dy); //ctx.fillText(dataset.data[idx], dx, dy); } }), self); function wrapText(context, text, x, y, maxWidth, lineHeight) { var cars = text.split("\n"); for (var ii = 0; ii < cars.length; ii++) { var line = ""; var words = cars[ii].split(" "); for (var n = 0; n < words.length; n++) { var testLine = line + words[n] + " "; var metrics = context.measureText(testLine); var testWidth = metrics.width; if (testWidth > maxWidth) { context.fillText(line, x, y); line = words[n] + " "; y += lineHeight; } else { line = testLine; } } context.fillText(line, x, y); y += lineHeight; } } } } }; var el = document.getElementById(bchart); //var el = component.find(bchart); var ctx = el.getContext("2d"); //ctx.canvas.width=600; ctx.canvas.height=60; //console.log(ctx.canvas.width + "Width"); //var lineBar = document.getElementById("line-bar").getContext("2d"); var myBarChart1 = new Chart(ctx, { type: 'horizontalBar', data: data, options: options }); //var myLineBarChart = new Chart(lineBar).LineBar(data); } });<file_sep>/src/aura/Frontier_SalesRep_ProgramDetails/Frontier_SalesRep_ProgramDetailsHelper.js ({ programEventListHelper : function(component,event,page,isPageChange,isInitialize) { var progId = component.get("v.progId"); var accId =component.get("v.accountId"); var acctTarget = component.get("v.accountTarget"); var action = component.get("c.getProgramAccounts"); console.log('Program Id' + progId); var triggeredField = null; if(!isInitialize){ if(event.currentTarget && event.currentTarget.id != null){ console.log('Inside Helper Target' + event.currentTarget.id); var sortfield=component.get("v.SortByField." +event.currentTarget.id); console.log('&&&&&&&&&&&&&'+sortfield); triggeredField = component.get("v.SortByField."+event.currentTarget.id); // triggeredField =event.currentTarget.id; component.set("v.triggeredField",triggeredField); console.log('Triggered Field'+triggeredField); } else if(isPageChange && component.get("v.triggeredField") != ""){ triggeredField = component.get("v.triggeredField"); } } var growerFlag = component.get("v.growerFlag"); var daccId = component.get("v.dealeraccId"); console.log('daccId' + daccId + ' ' + growerFlag); if(daccId == undefined || daccId ==''){ daccId = null; } console.log('Triggered Field'+triggeredField); action.setParams({ programId : progId, pageSize : component.get("v.pageSize"), pageNumber : page, triggeredField : triggeredField, isInitialize : isInitialize, isPageChange : isPageChange, growerFlag : growerFlag, daccId : daccId, accountTarget : acctTarget }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ var programEventlist = []; var accountList = []; component.set("v.page",page); var retResponse = response.getReturnValue(); console.log("retResponse"+ retResponse); component.set("v.total",JSON.parse(retResponse[0])); component.set("v.pages",Math.ceil((JSON.parse(retResponse[0]))/component.get("v.pageSize"))); programEventlist = JSON.parse(retResponse[1]); accountList = JSON.parse(retResponse[2]); component.set("v.accountProgramList", programEventlist); component.set("v.accountList",accountList); component.set("v.SortByField", JSON.parse(retResponse[3])); console.log("accProductList" + JSON.stringify(retResponse[4])) component.set("v.accountProductList", JSON.parse(retResponse[4])); }else if (state === "ERROR"){ console.log('Error'); } }); $A.enqueueAction(action); }, cancelPgm : function(component,event,reason){ var pgmAccId = component.get("v.cancelUniqueId"); console.log('pgmAcc' + pgmAccId); //var programId = (pgmAccId.split('/')[0]); //var accId = (pgmAccId.split('/')[1]); var accPgmId = (pgmAccId.split('/')[0]); var status = (pgmAccId.split('/')[1]); console.log( accPgmId + ' ' + status); var action = component.get("c.getCancelPgm"); action.setParams({ status : status, accPgmId : accPgmId, reason : reason }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ console.log('Success'); var comp = 'MyPrograms'; var myEvent = $A.get("e.c:Frontier_RefreshProgramChart"); myEvent.setParams({ "compName":comp }); myEvent.fire(); } else if(state === 'ERROR'){ console.log('Error'); } }); $A.enqueueAction(action); }, completePgm : function(component,event){ console.log('Inside complete'); var pgmAccId = event.currentTarget.id; console.log('pgmAcc' + pgmAccId); //var programId = (pgmAccId.split('/')[0]); //var accId = (pgmAccId.split('/')[1]); var accPgmId = (pgmAccId.split('/')[0]); var status = (pgmAccId.split('/')[1]); console.log( accPgmId + ' ' + status); var action = component.get("c.getCompletePgm"); action.setParams({ status : status, accPgmId : accPgmId }); action.setCallback(this,function(response){ var state = response.getState(); var message; if(state === 'SUCCESS'){ console.log('Success'); var popUpFlag = response.getReturnValue(); console.log('popUpFlag' + popUpFlag); if(popUpFlag=='Allow'){ message='Program Completed'; this.showPopUpAllow(component,event,message); } if(popUpFlag=='Not Allow'){ message='Program Not Completed'; this.showPopUpntAllow(component,event,message); } var comp = 'MyPrograms'; var myEvent = $A.get("e.c:Frontier_RefreshProgramChart"); myEvent.setParams({ "compName":comp }); myEvent.fire(); } else if (state === "ERROR"){ console.log('Error'); } }); $A.enqueueAction(action); }, cancelSelectedActivity : function(component,event){ //var uniqueId = event.currentTarget.id; var taskId = event.currentTarget.id; var accountId = component.get("v.accountId"); var programId = component.get("v.programId"); var action = component.get("c.getCancelActy"); action.setParams({ accountId : accountId, programId : programId, taskId : taskId }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ console.log('Success'); } else if (state === "ERROR"){ console.log('Error'); } }); $A.enqueueAction(action); }, navigateToActivityDetail : function(component, event, helper){ var handlerName,roleDesc,accId,pgmId,accComId,myprogramDetails; console.log('event.target.id' + event.target.id); if(event.target.id){ handlerName = event.target.id.split(',')[0]; roleDesc = event.target.id.split(',')[1]; accId = event.target.id.split(',')[2]; pgmId = event.target.id.split(',')[3]; accComId = event.target.id.split(',')[4]; } if(roleDesc){ if(roleDesc === 'Partner'){ myprogramDetails = handlerName+'-'+roleDesc+'-'+accId+'-'+pgmId+'-'+accComId; var url = '/one/one.app#/n/Dealer_List?myprogramDetails='+myprogramDetails; var viewRecord = document.getElementById(event.target.id); viewRecord.setAttribute("href", url); } if(roleDesc === 'Customer'){ myprogramDetails = handlerName+'-'+roleDesc+'-'+accId+'-'+pgmId+'-'+accComId; var url = '/one/one.app#/n/Grower_List?myprogramDetails='+myprogramDetails; var viewRecord = document.getElementById(event.target.id); viewRecord.setAttribute("href", url); } } }, getAllPrograms : function(component,event,helper) { console.log('********account'+component.get("v.accountId")); var programId =component.get("v.programId"); var action = component.get("c.getMyPrograms"); action.setParams({ programId : programId, }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ var retResponse = (JSON.parse(response.getReturnValue())); console.log("retResponse"+ JSON.stringify(retResponse)); component.set("v.programList", retResponse); component.set("v.loadchart1" , true); component.set("v.loadchart2" , true); component.set("v.loadchart3" , true); }else if (state === "ERROR"){ console.log('Error'); } }); $A.enqueueAction(action); }, showPopUpAllow: function(component,event,message){ console.log("Inside showPop" + message); $A.createComponent("c:Frontier_PopUp", {Message : message }, function(newComp){ console.log('pop'); var comp = component.find("allowpopcomplete"); comp.set("v.body",newComp); }); }, showPopUpntAllow: function(component,event,message){ console.log("Inside showPop" + message); $A.createComponent("c:Frontier_PopUp", {Message : message }, function(newComp){ console.log('pop'); var comp = component.find("notallowpopcomplete"); comp.set("v.body",newComp); }); }, addAccountPrograms: function(component, event){ var programId =component.get("v.progId"), lookupaccountId =component.get("v.accountsId"); var action = component.get("c.addAccountProgram"); action.setParams({ lookupaccountId : lookupaccountId, ProgramId : programId }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ //var retResponse = (JSON.parse(response.getReturnValue())); //console.log("responeObject" +retResponse); var myEvent = $A.get("e.c:Frontier_SelectedProgramEvent"); var pgmId = component.get("v.progId"); var acctTarget = component.get("v.accountTarget"); myEvent.setParams({ "programId": pgmId, "dealerId": '', "accountTarget": acctTarget }); console.log("progId" + event.target.value); myEvent.fire(); }else if (state === "ERROR"){ console.log('Error'); } }); $A.enqueueAction(action); }, closePopup : function(component, event){ var model = component.find('addnewaccount'); $A.util.removeClass(model, 'slds-show'); $A.util.addClass(model, 'slds-hide'); var backDrop = component.find('addCancelbackgrnd'); $A.util.removeClass(backDrop, 'slds-show'); $A.util.addClass(backDrop, 'slds-hide'); } })<file_sep>/src/aura/Frontier_SalesRep_ProgramDetail_Master/Frontier_SalesRep_ProgramDetail_MasterHelper.js ({ programEventListHelper : function(component,event,page,isPageChange,isInitialize) { var programId = component.get("v.programId"); var accId =component.get("v.accountId"); var action = component.get("c.getMyProgramAccounts"); var groweAcc = component.get("v.growerAcc"); if(groweAcc == 'undefined' || groweAcc=='' || groweAcc==null){ groweAcc = null; } console.log('groweAcc' + groweAcc); console.log('Program Id' + programId); var triggeredField = null; if(!isInitialize){ if(event.currentTarget && event.currentTarget.id != null){ console.log('Inside Helper Target' + event.currentTarget.id); var sortfield=component.get("v.SortByField." +event.currentTarget.id); console.log('Sort Field'+sortfield); triggeredField = component.get("v.SortByField."+event.currentTarget.id); // triggeredField =event.currentTarget.id; component.set("v.triggeredField",triggeredField); console.log('Triggered Field'+triggeredField); } else if(isPageChange && component.get("v.triggeredField") != ""){ triggeredField = component.get("v.triggeredField"); } } action.setParams({ programId : programId, pageSize : component.get("v.pageSize"), pageNumber : page, triggeredField : triggeredField, isInitialize : isInitialize, isPageChange : isPageChange, }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ var programEventlist = []; component.set("v.page",page); var retResponse = response.getReturnValue(); console.log("retResponse"+ retResponse); component.set("v.total",JSON.parse(retResponse[0])); component.set("v.pages",Math.ceil((JSON.parse(retResponse[0]))/component.get("v.pageSize"))); programEventlist = JSON.parse(retResponse[1]); component.set("v.accountProgramList", programEventlist); component.set("v.SortByField", JSON.parse(retResponse[2])); }else if (state === "ERROR"){ console.log('Error'); } }); $A.enqueueAction(action); }, cancelSelectedActivity : function(component,event){ //var uniqueId = event.currentTarget.id; var taskId = event.currentTarget.id; var accountId = component.get("v.accountId"); var programId = component.get("v.programId"); var action = component.get("c.getCancelActy"); action.setParams({ accountId : accountId, programId : programId, taskId : taskId }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ console.log('Success'); } else if (state === "ERROR"){ console.log('Error'); } }); $A.enqueueAction(action); }, navigateToUpdateTouchPointDetail : function(component,event) { console.log("c:Frontier_GrowerAccount_UpdateTouchPoint"); var currentDateId = event.currentTarget.id; var accId =component.get("v.accountId"); var programId =component.get("v.programId"); console.log('currentDateId' + currentDateId); $A.createComponent( "c:Frontier_GrowerAccount_UpdateTouchPoint", { currentDateId: currentDateId, accountId:accId, newUpdateStatus:'update', programId:programId }, function(newCmp){ var cmp = component.find("AccountDetail"); cmp.set("v.body", []); cmp.set("v.body", newCmp); } ); }, getAllPrograms : function(component,event,helper) { var programId =component.get("v.programId"); var dealerId; var isMyProgram; console.log('programId' +programId); var dealerId = component.get("v.growerAcc"); console.log('dealerId' +dealerId); if(dealerId != null){ isMyProgram = 'false'; component.set("v.dealerId",dealerId); console.log('dealerId' +dealerId + isMyProgram); } if(dealerId == 'undefined' || dealerId =='' || dealerId == null){ dealerId = null; isMyProgram = 'true'; } var isAllDealer = 'false'; var action = component.get("c.getMyProgramsChart"); action.setParams({ programId : programId, dealerId:dealerId, isAllDealer:isAllDealer, isMyProgram:isMyProgram }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ var retResponse = (JSON.parse(response.getReturnValue())); console.log("retResponse"+ JSON.stringify(retResponse)); component.set("v.programList", retResponse); component.set("v.loadchart1" , true); component.set("v.loadchart2" , true); component.set("v.loadchart3" , true); component.set("v.loadchart4" , true); // var inputsel = component.find("sellingSeason"); var cropsel = component.find("cropDetails"); var opts=[]; var crops=[]; for(var i=0;i< retResponse.sellingSeasontypes.length;i++){ opts.push({"class": "optionClass", label: retResponse.sellingSeasontypes[i], value:retResponse.sellingSeasontypes[i]}); } for(var i=0;i< retResponse.croptypes.length;i++){ crops.push({"class": "optionClass", label: retResponse.croptypes[i], value:retResponse.croptypes[i]}); } // inputsel.set("v.options",opts); cropsel.set("v.options",crops); var Acquire = retResponse.acquirecount; var Develop = retResponse.developcount; var LightTouch = retResponse.ltcount; var Retain = retResponse.retaincount; console.log('Acquire' + Acquire + 'Develop' + Develop + 'LightTouch' +LightTouch +'Retain'+Retain); $A.createComponent( "c:Frontier_ProgramPlanning_Radl", { acqcount:Acquire, dcount :Develop, lcount :LightTouch, rcount :Retain }, function(newCmp){ var cmp = component.find("radlDiv1"); //cmp.set("v.body", []); cmp.set("v.body", newCmp); } ); }else if (state === "ERROR"){ console.log('Error'); } }); $A.enqueueAction(action); }, getSeason : function(component, event, helpe) { var seasonVal = '2017 Safra'; var selectedSeason = component.find("selectedSeason").get("v.value"); if(selectedSeason != null) { seasonVal = selectedSeason; } console.log('Inside Grower Profile'); var selectedGrower = component.get("v.growerId"); var action = component.get("c.getSeasonData"); action.setParams({ season :seasonVal }); action.setCallback(this, function(response) { if (response.getState() === "SUCCESS") { var seasonDetailsJson = JSON.parse(response.getReturnValue()); console.log('growerAccountDetailJson' + seasonDetailsJson); console.log('growerAccountDetailJson.growerSeason' + seasonDetailsJson.growerSeason); component.set("v.seasonList",seasonDetailsJson); console.log('seasonDetailsJson.growerSeason' + seasonDetailsJson.growerSeason); //this.getSeasonDetails(component,event,helper); } else if (response.getState() === "ERROR") { $A.log("Errors", response.getError()); console.log("Errors", response.getError()); } }); $A.enqueueAction(action); } })<file_sep>/src/aura/Frontier_AccountDetailApp/Frontier_AccountDetailAppController.js ({ doInit : function(component, event, helper){ var myOpts = []; myOpts.push({'label':'All','value':'All'}); myOpts.push({'label':'One','value':'One'}); myOpts.push({'label':'Two','value':'Two'}); component.set("v.myOptions",myOpts); $A.createComponent( "c:MultiSelect", { "aura:id":"my-multi-select", options:component.get("v.myOptions"), selectChange:component.getReference("c.handleSelectChangeEvent"), selectedItems:"" }, function(newCmp){ var cmp = component.find("mul-select"); cmp.set("v.body", newCmp); } ); }, showSpinner : function(component, event, helper){ var spinner = component.find('spinner'); $A.util.removeClass(spinner, "xc-hidden"); }, hideSpinner : function(component, event, helper){ var spinner = component.find('spinner'); $A.util.addClass(spinner, "xc-hidden"); }, handleSelectChangeEvent: function(component, event, helper) { var items = component.get("v.items"); items = event.getParam("values"); component.set("v.items", items); } })<file_sep>/src/aura/Frontier_Touch_Plng_Pgm/Frontier_Touch_Plng_PgmController.js ({ addPgm : function(component,event){ document.getElementById("newSectionId").style.display = "block"; document.getElementById("backSectionId").style.display = "block"; //component.set("v.depntPicValue" , ''); var action = component.get("c.getPicklistValue"); //var programsel = component.find("programName"); var programs=[]; var depProg = ['None']; var result; var value= 'None'; action.setCallback(this, function(a){ var state = a.getState(); result = a.getReturnValue(); for(var i=0;i< result.length;i++){ programs.push({"class": "optionClass", label: result[i], value: result[i]}); } //programsel.set("v.options",programs); component.set("v.picValue" , result); component.set("v.depntPicValue" , depProg); component.set("v.selectedCntrlValue", ''); component.set("v.highlghtDepValue", ''); }); $A.enqueueAction(action); }, addNonPgm : function(component,event){ document.getElementById("newSectionnonId").style.display = "block"; document.getElementById("backSectionnonId").style.display = "block"; var action = component.get("c.getNonPicklistValue"); var nonprograms=[]; var result; action.setCallback(this, function(a){ var state = a.getState(); result = a.getReturnValue(); //programsel.set("v.options",programs); component.set("v.nonActivityValue" , result); component.set("v.nonProgram" , 'Non-Program'); component.set("v.selectedNonactv", ''); }); $A.enqueueAction(action); }, selectChangeHandler : function(component,event){ var controlPick = event.currentTarget.id; var previousValue; console.log('controlPick' + controlPick); //var controlPick = component.find("programName").get("v.value"); var action = component.get("c.getDependentValue"); var activitysel = component.find("activityName"); var activities=[]; var result; action.setParams({ Controlvalue: controlPick }); action.setCallback(this, function(a){ var state = a.getState(); result = a.getReturnValue(); for(var i=0;i< result.length;i++){ activities.push({"class": "optionClass", label: result[i], value: result[i]}); } component.set("v.depntPicValue" , result); if(controlPick != previousValue){ component.set("v.highlghtDepValue", ''); } component.set("v.selectedCntrlValue", controlPick); previousValue = component.get("v.selectedCntrlValue"); }); $A.enqueueAction(action); }, selectNonactiv : function(component,event){ var nonActiveValue = event.currentTarget.id; component.set("v.selectedNonactv", nonActiveValue); }, selectDependent : function(component,event){ //var controlField = component.get("v.selectedCntrlValue"); var selectedDepValue = event.currentTarget.id; component.set("v.highlghtDepValue", selectedDepValue); }, getDone : function(){ document.getElementById("newSectionId").style.display = "none"; document.getElementById("backSectionId").style.display = "none"; }, getnonPgmDone : function(){ document.getElementById("newSectionnonId").style.display = "none"; document.getElementById("backSectionnonId").style.display = "none"; }, clearData : function(component,event){ var action = component.get("c.getPicklistValue"); //var programsel = component.find("programName"); // component.set("v.depntPicValue" , ''); //var programs=[]; var result; //var value= "None"; action.setCallback(this, function(a){ var state = a.getState(); result = a.getReturnValue(); /* for(var i=0;i< result.length;i++){ programs.push({"class": "optionClass", label: result[i], value: result[i]}); }*/ //programsel.set("v.options",programs); component.set("v.picValue" , result); component.set("v.depntPicValue" , 'None'); component.set("v.selectedCntrlValue", ''); component.set("v.highlghtDepValue", ''); }); $A.enqueueAction(action); }, addPgmActivity : function(component,event){ var pgmValue = component.get("v.highlghtDepValue"); var activityValue= component.get("v.selectedCntrlValue"); if(pgmValue && activityValue != null){ component.set("v.addProgramValue" , pgmValue + ' - '+activityValue); document.getElementById("newSectionId").style.display = "none"; document.getElementById("backSectionId").style.display = "none"; } }, addnonPgmActivity : function(component,event){ var nonActive = component.get("v.selectedNonactv"); var nonPgm = component.get("v.nonProgram"); if(nonActive && nonPgm != null){ component.set("v.addProgramValue" , nonActive + ' - '+nonPgm); document.getElementById("newSectionnonId").style.display = "none"; document.getElementById("backSectionnonId").style.display = "none"; } } })<file_sep>/src/aura/Frontier_LocationBasedActivities/Frontier_LocationBasedActivitiesHelper.js ({ getTasks : function(component) { /*if(navigator.geolocation){ navigator.geolocation.getCurrentPosition(function(position){ console.log(position.coords.longitude); component.set("v.comLat",position.coords.latitude); component.set("v.comLong",position.coords.longitude); }); }*/ var action = component.get("c.getMyLocationRecords"); action.setParams({ lati : component.get("v.comLat"), longi: component.get("v.comLong") }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ $A.createComponent("c:Frontier_GoogleMapComponent", { "aura:id" : "test", "Tasks" : response.getReturnValue(), "currentLongitude": component.get("v.comLong"), "currentLatitude": component.get("v.comLat") }, function(task){ var comp = component.find("map"); comp.set("v.body",task); console.log('Frontier_GoogleMapComponent'); } ); component.set("v.TaskRecords",response.getReturnValue()); //component.set("v.TaskRecords",component.get("v.responseRecord")); } }); $A.enqueueAction(action); } })<file_sep>/src/aura/Frontier_AccountDetails/Frontier_AccountDetailsHelper.js ({ getAccounts:function(cmp){ console.log('accountDetailResponse=>'+cmp.get("v.accountDetailResponse")); cmp.set("v.accountDetail",JSON.parse(cmp.get("v.accountDetailResponse"))); console.log('accId=>'+ cmp.get("v.accId")); console.log('accCommunicationId=>'+ cmp.get("v.accCommunicationId")); var action = cmp.get("c.getAccountDetails"); action.setParams({ accId : cmp.get("v.accId"),accCommunicationId : cmp.get("v.accCommunicationId"),result : cmp.get("v.accountDetailResponse")}); // Create a callback that is executed after // the server-side action returns action.setCallback(this, function(response){ var state = response.getState(); if (state === "SUCCESS"){ console.log('accountResponse=>'+response.getReturnValue()); var salesDetailJson = JSON.parse(response.getReturnValue()); cmp.set("v.account", salesDetailJson); } else if (state === "ERROR"){ var errors = response.getError(); if (errors){ if (errors[0] && errors[0].message){ console.log("Error message: "+errors[0].message); } } else{ console.log("Unknown error"); } } }); $A.enqueueAction(action); } });<file_sep>/src/aura/Frontier_Pgm_Plang_Review/Frontier_Pgm_Plang_ReviewHelper.js ({ getAllProgram : function(component, event, helper, page) { var program = component.get("v.programName"); var page = page || 1; var pageSize=component.get("v.pageSize"); var progIds = component.get("v.programIdSet"); var action = component.get("c.getPrograms"); action.setParams({ pageNumber : page, pageSize : component.get("v.pageSize") }); console.log('Get All Programs'); action.setCallback(this, function(response) { var state = response.getState(); if(state == 'SUCCESS'){ var pgmList = []; var pgmIdset =[]; var pgmId =[]; component.set("v.page",page); var programList = response.getReturnValue(); component.set("v.pages",Math.ceil((JSON.parse(programList[0]))/component.get("v.pageSize"))); component.set("v.total",JSON.parse(programList[0])); console.log('programList' + programList); pgmList = JSON.parse(programList[1]); pgmId= JSON.parse(programList[2]); component.set("v.programDetails", pgmList); console.log('pgmList' +JSON.stringify(pgmList)); for(var i=0;i<pgmId.length;i++){ pgmIdset.push(pgmId[i]); } console.log('pgmIdset' +pgmIdset); component.set("v.programIdSet",pgmIdset); console.log('ProgramIdSet' + component.get("v.programIdSet")); /* $A.createComponent( "c:Frontier_ProgramPlanning_Radl", { }, function(radl){ var radlcmp = component.find("radlDiv"); //cmp.set("v.body", []); radlcmp.set("v.body", radl); } );*/ } else if (state === "ERROR"){ console.log('Error'); } }); $A.enqueueAction(action); }, submitProgram :function(component,event,helper){ console.log('Inside submit helper'); var action = component.get("c.submitProgram"); action.setParams({ programIds : JSON.stringify(component.get("v.programIdSet")) }); action.setCallback(this, function(response) { var state = response.getState(); if(state == 'SUCCESS'){ this.showPopUp(component,event,'Submitted Successfully'); // alert('THE CHANGES HAS BEEN SAVED SUCCESSFULLY !!'); } else if (state === "ERROR"){ console.log('Error'); } }); $A.enqueueAction(action); }, showPopUp: function(component,event,message){ component.set("v.isSubmitted",true); console.log("Inside showPop" + message); $A.createComponent("c:Frontier_PopUp", {Message : message, ComponentName : 'Frontier_Pgm_Plang_Review' }, function(newComp){ console.log('pop'); var comp = component.find("userpopup"); if(comp != undefined){ comp.set("v.body",newComp); } }); } , /* handleSubmitProgramAction : function(component,event,helper){ console.log('Event Handled'); component.set("v.isSubmitted",true); var isSubmitted = component.get("v.isSubmitted"); if (component.isValid() && isSubmitted) { $A.createComponent( "c:Frontier_ProgramPlanning", { }, function(newCmp){ var cmp = component.find("programDetail"); cmp.set("v.body", []); cmp.set("v.body", newCmp); } ); } */ } })<file_sep>/src/aura/Frontier_AccountTracking_Table/Frontier_AccountTracking_TableHelper.js ({ getsObjectRecords : function(component,page1, productID, sortFieldName) { var page = page1 || 1; console.log(JSON.stringify(component.get("v.Trackingtabledetails"))); var action = component.get("c.getAccounts"); console.log("sort" + sortFieldName); console.log("productID" + productID); action.setParams({ result : component.get("v.Trackingtabledetails"), pageNumber : page, pageSize : component.get("v.pageSize"), ProductId : productID, sortFieldName: sortFieldName }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ var retResponse = response.getReturnValue(); console.log('Success'); }else if (state === "ERROR") { console.log('Error'); } }); $A.enqueueAction(action); } });<file_sep>/src/aura/Frontier_AccountDetailViewComponent/Frontier_AccountDetailViewComponentHelper.js ({ getAccountDetailResponse : function(component){ try { var action = component.get("c.getAccDetails"); //Pass the Sap ID to server side so that the response would be obtained based on the sap Id console.log('component.get("v.sapId")=>'+component.get("v.sapId")); console.log('component.get("v.accCommunicationId")=>'+component.get("v.accCommunicationId")); action.setParams({"sapId": component.get("v.sapId")}); action.setCallback(this, function(response){ var state = response.getState(); if (state === "SUCCESS" && !(response.getReturnValue() === 'CalloutError')){ console.log('accId================>'+response.getReturnValue()); $A.createComponent( "c:Frontier_AccountDetails", { "accId": component.get("v.accId"), "accCommunicationId": component.get("v.accCommunicationId"), "accountDetailResponse":response.getReturnValue() }, function(newCmp){ //Render the sales order dashboard component to the parent container var cmp = component.find("AccountDetailSection"); cmp.set("v.body", newCmp); } ); $A.createComponent( "c:FrontierSalesOrderDashboard", { "SalesDetailResponse": response.getReturnValue(), "accId": component.get("v.accId") }, function(newCmp){ //Render the sales order dashboard component to the parent container var cmp = component.find("SalesOrderDashboard"); cmp.set("v.body", newCmp); } ); } else if(response.getReturnValue() === 'CalloutError'){ console.log('CalloutError'); } else{ console.log('Call Back Error'); } }); $A.enqueueAction(action); } catch(e){ console.log('Exception Occured'+e); } } });<file_sep>/src/aura/Frontier_AllDealers_GrowerPrograms_MasterComponent/Frontier_AllDealers_GrowerPrograms_MasterComponentHelper.js ({ getAllPrograms : function(component,event,helper) { var action = component.get("c.getMyPrograms"); var acctDetails = component.get("v.growerAcc"); console.log('acctDetails' +acctDetails); var isMyProgram = 'false'; var dealerId = null; var isAllDealer ='true'; var ProgramId = null; action.setParams({ ProgramId :ProgramId, dealerId : dealerId, isAllDealer:isAllDealer, isMyProgram :isMyProgram }); //var inputsel = component.find("sellingSeason"); var opts=[]; action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ var retResponse = (JSON.parse(response.getReturnValue())); console.log("retResponse"+ JSON.stringify(retResponse)); component.set("v.programList", retResponse); component.set("v.loadchart1" , true); component.set("v.loadchart2" , true); component.set("v.loadchart3" , true); /* for(var i=0;i< retResponse.sellingSeasontypes.length;i++){ opts.push({"class": "optionClass", label: retResponse.sellingSeasontypes[i], value:retResponse.sellingSeasontypes[i]}); } inputsel.set("v.options",opts);*/ var Acquire = retResponse.acquireCount; var Develop = retResponse.developCount; var LightTouch = retResponse.lightTouchCount; var Retain = retResponse.retainCount; console.log('Acquire' + Acquire + 'Develop' + Develop + 'LightTouch' +LightTouch +'Retain'+Retain); $A.createComponent( "c:Frontier_ProgramPlanning_Radl", { acqcount:Acquire, dcount :Develop, lcount :LightTouch, rcount :Retain }, function(newCmp){ var cmp = component.find("radlDiv"); //cmp.set("v.body", []); cmp.set("v.body", newCmp); } ); /* $A.createComponent( "c:Frontier_Pgm_Planning_BudgetChart", { "available" : '5', "allocated" : '7', "consumed" :'8' , "identifier" : '1' }, function(newCmp){ var cmp = component.find("loadchart1"); //cmp.set("v.body", []); cmp.set("v.body", newCmp); } );*/ /* $A.createComponent( "c:Frontier_ProgramPlanning_Radl", { }, function(newCmp){ var cmp = component.find("radlDiv"); //cmp.set("v.body", []); cmp.set("v.body", newCmp); } ); $A.createComponent( "c:Frontier_ProgramPlanning_Radl", { }, function(newCmp){ var cmp = component.find("radlDiv"); //cmp.set("v.body", []); cmp.set("v.body", newCmp); } ); */ }else if (state === "ERROR"){ console.log('Error'); } }); $A.enqueueAction(action); }, navigateToProgramDetails:function(component,event,helper){ var programId = event.getParam("programId"); console.log('My Programs' + programId); $A.createComponent("c:Frontier_AllDealers_SalesRep_ProgramDetail_Master", { programId: programId }, function(program){ console.log('Program Details'); var comp = component.find("programDetail"); comp.set("v.body",program); } ); } })<file_sep>/src/aura/Frontier_ProgramPlanning_Radl/Frontier_ProgramPlanning_RadlController.js ({ doInit : function(component, event, helper) { /* console.log('Inside graph doinit'); helper.loadRADLgraph(component, event);*/ } })<file_sep>/src/aura/Frontier_SelectedProgramList/Frontier_SelectedProgramListController.js ({ doInit : function(component, event, helper) { component.set("v.isInitialize",true); component.set("v.highlightPanel",'background:#D3D3D3;width:100%;text-align: initial;'); console.log('isInitialize'+component.get("v.isInitialize")); console.log('component.get("v.programList")'+component.get("v.programList")); component.set("v.isInitialLoad",false); helper.applyPaginationToTable(component,event,component.get("v.programList")); }, highlightProgram : function(component, event, helper) { var progId; var isInitialLoad = component.get("v.isInitialLoad"); if(event.target != undefined){ progId = event.target.id; var myEvent = $A.get("e.c:Frontier_SelectedProgramEvent"); myEvent.setParams({"progId": progId}); myEvent.fire(); console.log('clicked from child'+event.target.id); component.set("v.isInitialize",false); } else{ console.log('Last Event from Child'+event.getParam("programId")); progId = event.getParam("programId"); } component.set("v.progId",progId); if(!isInitialLoad){ component.set("v.isInitialLoad",true); } // var triggeredProgram = document.getElementById(progId); // $A.util.addClass(document.getElementById(progId), 'changeMe'); /* if(component.get("v.btnPrevious") != null){ var prevTriggeredProgram = document.getElementById(component.get("v.btnPrevious")); $A.util.removeClass(prevTriggeredProgram,'changeMe'); } component.set("v.btnPrevious",event.target.id);*/ /* if(component.get("v.isInitialLoad")){ }*/ }, tableChange: function(component,event,helper) { var cmpName = event.getParam("compName"); console.log('cmpName' + cmpName); if(cmpName == 'ProgramList'){ //component.set("v.isInitialize",false); helper.applyPaginationToTable(component,event,component.get("v.programList")); } } })<file_sep>/src/aura/Frontier_AllDealers_SalesRep_ProgramDetails/Frontier_AllDealers_SalesRep_ProgramDetailsController.js ({ doInit : function(component, event, helper) { var page = component.get("v.page") || 1; var ispageChange = false; var isInitialize = true; component.set("v.usersInitialLoad",true); helper.programListHelper(component,event,page,ispageChange,isInitialize); //helper.getAllPrograms(component,event,helper); }, pageChange: function(component,event,helper) { var cmpName = event.getParam("compName"); console.log('cmpName' + cmpName); if(cmpName == 'AllGrowerAccountList'){ var page = component.get("v.page") || 1; var direction = event.getParam("direction"); page = direction === "previous" ? (page - 1) : (page + 1); var ispageChange = true; var isInitialize = false; component.set("v.usersInitialLoad",false); helper.programListHelper(component,event,page,ispageChange,isInitialize); } }, sortDirection : function(component,event,helper){ if(event.currentTarget.id != '' && component.get("v.prevId") != '' && component.get("v.prevId") != event.currentTarget.id){ component.set("v.SortBy"+component.get("v.prevId"),"onMouseOut"); } var page = component.get("v.page") || 1; console.log("Event Target"+event.currentTarget.id) if(event.currentTarget.id != ''){ component.set("v.SortBy"+event.currentTarget.id,"onClick"); } var ispageChange = false; var isInitialize = false; component.set("v.prevId",event.currentTarget.id); component.set("v.usersInitialLoad",false); helper.programListHelper(component,event,page,ispageChange,isInitialize); }, updateTouchPointNavigation: function(component,event,helper){ helper.navigateToUpdateTouchPointDetail(component, event); }, cancelProgram : function(component,event,helper){ //console.log('Inside cancel' + document.getElementById("newCancel").style.display); var uniqueID = event.currentTarget.id; component.set("v.cancelUniqueId" , uniqueID); console.log(component.get("v.programId")); document.getElementById("newCancel").style.display = "block"; document.getElementById("cancelbackgrnd").style.display = "block"; }, showModalBox : function(component,event,helper){ document.getElementById("newCancel").style.display = "none"; document.getElementById("cancelbackgrnd").style.display = "none"; component.find("comments").set("v.value", ' '); }, cancelPgmReason : function(component,event,helper){ document.getElementById("newCancel").style.display = "none"; document.getElementById("cancelbackgrnd").style.display = "none"; var reason = component.find("comments").get("v.value"); console.log("reason" + reason); component.find("comments").set("v.value", ' '); helper.cancelPgm(component,event,reason); var page = component.get("v.page") || 1; var ispageChange = false; var isInitialize = true; console.log("ispageChange out" + ispageChange); if (ispageChange == undefined){ console.log("ispageChange" + ispageChange); } component.set("v.usersInitialLoad",true); helper.programListHelper(component,event,page,ispageChange,isInitialize); }, completePgm : function(component,event,helper){ helper.completePgm(component,event); }, cancelActivity : function(component,event,helper){ helper.cancelSelectedActivity(component,event); var page = component.get("v.page") || 1; var ispageChange = false; var isInitialize = true; component.set("v.usersInitialLoad",true); helper.programListHelper(component,event,page,ispageChange,isInitialize); }, programDetailRedirect: function(component,event,helper){ var uniqueId = event.target.id; component.set("v.accountwithProgram",uniqueId); helper.navigateToActivityDetail(component, event,helper); } });<file_sep>/src/aura/Frontier_Truncatetext/Frontier_TruncatetextController.js ({ onload : function(component, event, helper) { if( navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i) ){ component.set("v.isMobile",true); } else { component.set("v.isMobile",false); } var fullString = component.get("v.inputText"); var sublength = component.get("v.truncateLength"); var subString=""; if((component.get("v.identifyEvtList")) == 'frmEvntList'){ if(component.get("v.isMobile") && fullString.length > 10){ console.log('fullString' + fullString); subString = fullString.substring(0,sublength); console.log( 'subString' + subString); component.set("v.truncatedText",subString); } else if(fullString.length > 40){ subString = fullString.substring(0,sublength); console.log(subString + 'subString'); component.set("v.truncatedText",subString); } else { component.set("v.truncatedText",fullString); } } else{ if(component.get("v.isMobile") && fullString.length > 40){ console.log('fullString' + fullString); subString = fullString.substring(0,sublength); console.log( 'subString' + subString); component.set("v.truncatedText",subString); } else if(fullString.length > 150){ subString = fullString.substring(0,sublength); console.log(subString + 'subString'); component.set("v.truncatedText",subString); } else { component.set("v.truncatedText",fullString); } } } })<file_sep>/src/aura/Frontier_DealerDetail_Profile/Frontier_DealerDetail_ProfileController.js ({ doInit : function(component, event, helper) { helper.dealerProfile(component, event, helper); }, fetchSeasonData : function(component, event, helper) { helper.dealerProfile(component, event, helper); }, //Mobile View toggleCrops : function(cmp,event,helper){ var targetObjId=event.target.id; if(targetObjId === ''){ targetObjId = event.target.parentElement.id; if(targetObjId === '' || (targetObjId.length === 0)){ targetObjId = event.target.parentElement.parentElement.id; if(targetObjId === '' || (targetObjId.length === 0)){ targetObjId = event.target.parentElement.parentElement.parentElement.id; if(targetObjId === '' || (targetObjId.length === 0)){ targetObjId = event.target.parentElement.parentElement.parentElement.parentElement.id; if(targetObjId === '' || (targetObjId.length === 0)){ targetObjId = event.target.parentElement.parentElement.parentElement.parentElement.parentElement.id; } } } } } if(!document.getElementById('panel-'+targetObjId).classList.contains("slidedown")){ /*$A.util.addClass(cmp.find('slidedown'+targetObjId), 'slds-hide'); $A.util.removeClass(cmp.find('slidedown'+targetObjId), 'slds-show'); $A.util.addClass(cmp.find('slideup'+targetObjId), 'slds-show') $A.util.removeClass(cmp.find('slideup'+targetObjId), 'slds-hide')*/ document.getElementById(targetObjId).childNodes[0].classList = 'slds-hide'; document.getElementById(targetObjId).childNodes[1].classList = 'slds-show'; document.getElementById('panel-'+targetObjId).classList = 'slidedown'; var panel = document.getElementById('paneldiv-'+targetObjId); if (panel.style.maxHeight){ panel.style.maxHeight = null; } else { panel.style.maxHeight ="100px"; //panel.scrollHeight panel.style.padding = '3%'; } } else{ /*$A.util.addClass(cmp.find('slidedown'+targetObjId), 'slds-show'); $A.util.removeClass(cmp.find('slidedown'+targetObjId), 'slds-hide'); $A.util.addClass(cmp.find('slideup'+targetObjId), 'slds-hide'); $A.util.removeClass(cmp.find('slideup'+targetObjId), 'slds-show');*/ document.getElementById('panel-'+targetObjId).classList = 'slideup'; document.getElementById(targetObjId).childNodes[0].classList = 'slds-show'; document.getElementById(targetObjId).childNodes[1].classList = 'slds-hide'; //document.getElementById('slidedown'+targetObjId).classList = 'slds-show'; //document.getElementById('slideup'+targetObjId).classList = 'slds-hide'; } }, navigateToGrowerList : function(component,event,helper){ var cmpEvent = component.getEvent("redirectToGrowerList"); cmpEvent.setParams({ "accountId" : component.get("v.dealerId"), }); cmpEvent.fire(); }, navigateToProgramPlanning:function(component,event,helper){ var appEvent = $A.get("e.c:Frontier_DealerDetailEvent"); appEvent.setParams({ "dealerId" : component.get("v.dealerId") }); appEvent.fire(); }, /* groweraccNavigation : function(component,event,helper){ $A.createComponent("c:Frontier_GrowerAccountList", {label : ""}, function(GrowerList){ console.log('AccountList'); var comp = component.find("growerList"); comp.set("v.body",GrowerList); } }*/ })<file_sep>/src/aura/Frontier_User_LoginReport/Frontier_User_LoginReportHelper.js ({ getsLogRecords : function(component, event,page, helper,pageChange) { var isExport = component.get("v.isExport"); var page = page || 1; var pageSize=component.get("v.pageSize"); console.log(pageSize + 'pageSize'); console.log(page + 'page'); var logViewList = '';//component.find("LogView").get("v.value"); var action = component.get("c.getLoggedDetails"); if(!pageChange){ var monthOpt = [ { class: "optionClass", label: "Jan", value: "1"}, { class: "optionClass", label: "Feb", value: "2"}, { class: "optionClass", label: "Mar", value: "3"}, { class: "optionClass", label: "Apr", value: "4"}, { class: "optionClass", label: "May", value: "5"}, { class: "optionClass", label: "Jun", value: "6"}, { class: "optionClass", label: "Jul", value: "7"}, { class: "optionClass", label: "Aug", value: "8"}, { class: "optionClass", label: "Sep", value: "9"}, { class: "optionClass", label: "Oct", value: "10"}, { class: "optionClass", label: "Nov", value: "11"}, { class: "optionClass", label: "Dec", value: "12"} ]; component.find("MonthSort").set("v.options",monthOpt); } action.setParams({ pageNumber : page, pageSize : component.get("v.pageSize"), logviews : logViewList, isExport : isExport, MonthOrCountrySort : component.get("v.monthOrCountrySort"), selectedMonthOrCountry : component.get("v.selectedMonthOrCountry"), selectedMonthOrCountryField : component.get("v.selectedMonthOrCountryField") }); action.setCallback(this,function(response){ var state = response.getState(); if (state === "SUCCESS"){ var message = "E-Mail has been sent"; console.log('Response=>'+response.getReturnValue()); var logDetailJson =JSON.parse(response.getReturnValue()); if(logDetailJson.length > 0){ var i; console.log(logDetailJson[0].Count + 'Total'); var Countryopt=[]; if(!pageChange){ for (i = 0; i < logDetailJson[0].countrySet.length; i++) { var optionValue={}; optionValue.class="optionClass"; optionValue.label = logDetailJson[0].countrySet[i]; optionValue.value= logDetailJson[0].countrySet[i]; Countryopt.push(optionValue); } component.find("CountrySort").set("v.options",Countryopt); } component.set("v.total",logDetailJson[0].Count); component.set("v.pages",Math.ceil((logDetailJson[0].Count)/component.get("v.pageSize"))); component.set("v.page",page); } else if(logDetailJson.length == 0){ component.set("v.total",0); component.set("v.pages",1); component.set("v.page",1); } if(isExport){ this.showPopUp(component,event,message); } component.set("v.isExport",false); component.set("v.logs", logDetailJson); } else if (state === "ERROR"){ var errors = response.getError(); if (errors){ if (errors[0] && errors[0].message){ console.log("Error message: "+errors[0].message); } } else{ console.log("Unknown error"); } } }); $A.enqueueAction(action); }, showPopUp: function(component,event,message){ console.log("Inside showPop" + message); $A.createComponent("c:Frontier_PopUp", {Message : message }, function(newComp){ console.log('pop'); var comp = component.find("userpopup"); comp.set("v.body",newComp); }); }, monthORCountrySort: function(component, event,page) { console.log("Month Selected=>"+component.get("v.selectedMonthOrCountry")); var isExport = component.get("v.isExport"); var countrySorting = component.get("v.selectedMonthOrCountry").split('/') var action = component.get("c.getSortByMonthORCounty"); action.setParams({ MonthORCountry : component.get("v.selectedMonthOrCountry"), MonthORCountryField : component.get("v.selectedMonthOrCountryField"), isExport : isExport }); action.setCallback(this,function(response){ if(response.getState() === 'SUCCESS'){ var message = "E-Mail has been sent"; var logDetailJson =JSON.parse(response.getReturnValue()); console.log('Response Sort=>'+response.getReturnValue()); if(logDetailJson.length > 0){ console.log(logDetailJson[0].Count + 'Total'); var Countryopt=[];var i; if(countrySorting.length === 2){ for (i = 0; i < logDetailJson[0].countrySet.length; i++) { var optionValue={}; optionValue.class="optionClass"; optionValue.label = logDetailJson[0].countrySet[i]; optionValue.value= logDetailJson[0].countrySet[i]; if(countrySorting[1] != ''){ if(countrySorting[1].split(';').includes(logDetailJson[0].countrySet[i])){ optionValue.selected= "true" } } Countryopt.push(optionValue); } component.find("CountrySort").set("v.options",Countryopt); } component.set("v.total",logDetailJson[0].Count); component.set("v.pages",Math.ceil((logDetailJson[0].Count)/component.get("v.pageSize"))); component.set("v.page",page); } else if(logDetailJson.length == 0){ component.set("v.total",0); component.set("v.pages",1); component.set("v.page",1); } if(isExport){ this.showPopUp(component,event,message); } component.set("v.isExport",false); component.set("v.logs", logDetailJson); } }); $A.enqueueAction(action); } })<file_sep>/src/aura/Frontier_OpportunitySalesComponent/Frontier_OpportunitySalesComponentController.js ({ loadChart: function(component, event, helper) { var data = { labels: ["2PY", "PY", "CY"], datasets: [ { label : "Sales", type : "bar", fillColor: "rgba(220,220,220,0.5)", //backgroundColor: 'rgba(0, 157, 217, 1)', backgroundColor: "#5ba361", borderColor: '#71B37C', //hoverBackgroundColor: 'rgba(0, 157, 217, 1)', hoverBackgroundColor: "#5ba361", hoverBorderColor: '#71B37C', data: [200, 170, 180] } ]}; var options = {responsive : true, barValueSpacing: 1, overlayBars: true, bezierCurve : false, legend: { display: true, position : 'right', labels: { fontColor: 'black' } }, scales: { xAxes: [{ gridLines: { display:false } }], yAxes: [{ gridLines: { display:false } }] } }; var el = component.find("chart").getElement(); var ctx = el.getContext("2d"); var myBarChart = new Chart(ctx, { type: 'bar', data: data, options: options }); window.onresize=function() { myBarChart.resize(); } } })<file_sep>/src/aura/Frontier_DealerDetail_Collapsible/Frontier_DealerDetail_CollapsibleController.js ({ toggle : function(component, event, helper) { var toggleGrowerAccounts = component.find("GrowerAccounts"); var accordionChange = component.find("accordionSection"); $A.util.toggleClass(toggleGrowerAccounts, "toggle"); $A.util.toggleClass(accordionChange, 'slds-is-close'); $A.util.toggleClass(accordionChange, 'slds-is-open'); }, doInit :function(component, event, helper){ var myOpts = []; myOpts.push({'label':'All','value':'All'}); myOpts.push({'label':'One','value':'One'}); myOpts.push({'label':'Two','value':'Two'}); component.set("v.myOptions",myOpts); } })<file_sep>/src/aura/Frontier_DealerAccount_Sales_Master/Frontier_DealerAccount_Sales_MasterController.js ({ doInit : function(component, event, helper) { console.log('Inside dealer chart'); helper.dealerSalesDetails(component,event,helper); }, changeUnits : function(component,event,helper){ helper.dealerSalesDetails(component,event,helper); } })<file_sep>/src/aura/Frontier_AllDealers_SalesRep_ProgramDetails/Frontier_AllDealers_SalesRep_ProgramDetailsHelper.js ({ programListHelper : function(component,event,page,isPageChange,isInitialize) { var programId = component.get("v.programId"); var accId =component.get("v.accountId"); var action = component.get("c.getPgmAccounts"); console.log('Program Id' + programId); var triggeredField = null; if(!isInitialize){ if(event.currentTarget && event.currentTarget.id != null){ console.log('Inside Helper Target' + event.currentTarget.id); var sortfield=component.get("v.SortByField." + event.currentTarget.id); console.log('&&&&&&&&&&&&&'+sortfield); triggeredField = component.get("v.SortByField."+event.currentTarget.id); // triggeredField =event.currentTarget.id; component.set("v.triggeredField",sortfield); console.log('Triggered Field'+triggeredField); } else if(isPageChange && component.get("v.triggeredField") != ""){ triggeredField = component.get("v.triggeredField"); } } console.log(programId+component.get("v.pageSize")+page+triggeredField+isInitialize+isPageChange); action.setParams({ programId : programId, pageSize : component.get("v.pageSize"), pageNumber : page, triggeredField : triggeredField, isInitialize : isInitialize, isPageChange : isPageChange }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ var programEventlist = []; var accountList = []; component.set("v.page",page); var retResponse = response.getReturnValue(); console.log("retResponse"+ retResponse); component.set("v.total",JSON.parse(retResponse[0])); component.set("v.pages",Math.ceil((JSON.parse(retResponse[0]))/component.get("v.pageSize"))); programEventlist = JSON.parse(retResponse[1]); accountList = JSON.parse(retResponse[2]); component.set("v.accountProgramList", programEventlist); component.set("v.accountList",accountList); component.set("v.SortByField", JSON.parse(retResponse[3])); component.set("v.accountProductList", JSON.parse(retResponse[4])); }else if (state === "ERROR"){ console.log('Error'); } }); $A.enqueueAction(action); }, cancelPgm : function(component,event,reason){ var pgmAccId = component.get("v.cancelUniqueId"); console.log('pgmAcc' + pgmAccId); //var programId = (pgmAccId.split('/')[0]); //var accId = (pgmAccId.split('/')[1]); var accPgmId = (pgmAccId.split('/')[0]); var status = (pgmAccId.split('/')[1]); console.log( accPgmId + ' ' + status); var action = component.get("c.getCancelPgm"); action.setParams({ status : status, accPgmId : accPgmId, reason : reason }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ console.log('Success'); var comp = 'AllDealers'; var myEvent = $A.get("e.c:Frontier_RefreshProgramChart"); myEvent.setParams({ "compName":comp }); myEvent.fire(); } else if(state === 'ERROR'){ console.log('Error'); } }); $A.enqueueAction(action); }, completePgm : function(component,event){ console.log('Inside complete'); var pgmAccId = event.currentTarget.id; console.log('pgmAcc' + pgmAccId); //var programId = (pgmAccId.split('/')[0]); //var accId = (pgmAccId.split('/')[1]); var accPgmId = (pgmAccId.split('/')[0]); var status = (pgmAccId.split('/')[1]); console.log( accPgmId + ' ' + status); var action = component.get("c.getCompletePgm"); action.setParams({ status : status, accPgmId : accPgmId }); action.setCallback(this,function(response){ var state = response.getState(); var message; if(state === 'SUCCESS'){ console.log('Success'); var popUpFlag = response.getReturnValue(); console.log('popUpFlag' + popUpFlag); if(popUpFlag=='Allow'){ message='Program Completed'; this.showPopUpAllow(component,event,message); } if(popUpFlag=='Not Allow'){ message='Program Not Completed'; this.showPopUpntAllow(component,event,message); } var comp = 'AllDealers'; var myEvent = $A.get("e.c:Frontier_RefreshProgramChart"); myEvent.setParams({ "compName":comp }); myEvent.fire(); } else if (state === "ERROR"){ console.log('Error'); } }); $A.enqueueAction(action); }, cancelSelectedActivity : function(component,event){ //var uniqueId = event.currentTarget.id; var taskId = event.currentTarget.id; var accountId = component.get("v.accountId"); var programId = component.get("v.programId"); var action = component.get("c.getCancelActy"); action.setParams({ accountId : accountId, programId : programId, taskId : taskId }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ console.log('Success'); } else if (state === "ERROR"){ console.log('Error'); } }); $A.enqueueAction(action); }, navigateToActivityDetail : function(component, event, helper){ var handlerName,roleDesc,accId,pgmId,accComId,myprogramDetails; if(event.target.id){ handlerName = event.target.id.split(',')[0]; roleDesc = event.target.id.split(',')[1]; accId = event.target.id.split(',')[2]; pgmId = event.target.id.split(',')[3]; accComId = event.target.id.split(',')[4]; } if(roleDesc){ if(roleDesc === 'Partner'){ myprogramDetails = handlerName+'-'+roleDesc+'-'+accId+'-'+pgmId+'-'+accComId; var url = '/one/one.app#/n/Dealer_List?myprogramDetails='+myprogramDetails; var viewRecord = document.getElementById(event.target.id); viewRecord.setAttribute("href", url); } if(roleDesc === 'Customer'){ myprogramDetails = handlerName+'-'+roleDesc+'-'+accId+'-'+pgmId+'-'+accComId; var url = '/one/one.app#/n/Grower_List?myprogramDetails='+myprogramDetails; var viewRecord = document.getElementById(event.target.id); viewRecord.setAttribute("href", url); } } } })<file_sep>/src/aura/Frontier_DealersGrowersList/Frontier_DealersGrowersListHelper.js ({ findGrowerAccounts : function(component, page1, searchKey, event, helper, isInitialize) { // get the current record id var page = page1 || 1; var currentrecordId = component.get("v.recordId"); var action = component.get("c.getAccounts"); action.setStorable(); action.setParams({ "searchKey": searchKey, pageSize : component.get("v.pageSize"), pageNumber : page, accId : currentrecordId }); action.setCallback(this, function(response) { if (action.getState() === "SUCCESS") { var accountDetailJson = response.getReturnValue(); component.set("v.page",page); component.set("v.pages",Math.ceil((JSON.parse(accountDetailJson[0]))/component.get("v.pageSize"))); component.set("v.total",JSON.parse(accountDetailJson[0])); console.log('accountDetailJson' + JSON.parse(accountDetailJson[1])); component.set("v.programs", JSON.parse(accountDetailJson[2])); //helper.setProgramDropdownOptions(component,event,helper); component.set("v.accountsList",JSON.parse(accountDetailJson[1])); component.set("v.corpsAvailable", JSON.parse(accountDetailJson[3])); } else if (response.getState() === "ERROR") { component.set("v.isCallBackError",false); component.set("v.ServerError",response); $A.log("Errors", response.getError()); var errors = action.getError(); if (errors) { if (errors[0] && errors[0].message) { cmp.set("v.Exception", errors[0].message); } } } }); $A.enqueueAction(action); }, setProgramDropdownOptions : function(component,event,helper){ var programs = component.get("v.programs"); var opt; var options = []; if(programs){ for(var i in programs){ opt = [{'label':'','value':'','selected':false}] opt.label = programs[i].Id; opt.value = programs[i].Name; options.push(opt); } } if(options && options.length > 0){ component.set("v.programDropdown",options) } } })<file_sep>/src/aura/Frontier_GrowerAccount_PreviousTouchPoints/Frontier_GrowerAccount_PreviousTouchPointsHelper.js ({ TouchPointRecord : function(component){ // var accountID = component.get("v.accId"); var accountID = '<KEY>' ; var action = component.get("c.getRecentTouchPoints"); action.setParams({ "accId" :accountID }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ component.set("v.touchpoints",response.getReturnValue()); }else if(state === 'ERROR'){ console.log('Error'); } }); $A.enqueueAction(action); } });<file_sep>/src/aura/Frontier_Programs_Activities/Frontier_Programs_ActivitiesController.js ({ doInit : function(component, event, helper) { var partameters = component.get("v.growerAcc"); console.log("partameters:" +partameters); helper.getProgramEventListHelper(component, event, helper); }, loadCaroselDom : function(component, event, helper){ var parameters = event.getParam("modalParameters"); component.set("v.modelProgramId",parameters.split(',')[3]); component.set("v.modelProgramStatus",parameters.split(',')[5]); if(event.getParam("isPopup")){ if(parameters.split(',')[4] === 'completeProgramlink'){ component.set("v.popupName", 'Complete Program') } if(parameters.split(',')[4] === 'cancelProgramlink'){ component.set("v.popupName", 'Cancel Program') } var model = component.find('newCancel'); $A.util.removeClass(model, 'slds-hide'); $A.util.addClass(model, 'slds-show'); var backDrop = component.find('cancelbackgrnd'); $A.util.removeClass(backDrop, 'slds-hide'); $A.util.addClass(backDrop, 'slds-show'); }else{ var count = event.getParam("programCount"); component.set("v.programCount",count); } }, closeModal :function (component, event, helper){ var model = component.find('newCancel'); $A.util.removeClass(model, 'slds-show'); $A.util.addClass(model, 'slds-hide'); var backDrop = component.find('cancelbackgrnd'); $A.util.removeClass(backDrop, 'slds-show'); $A.util.addClass(backDrop, 'slds-hide'); }, updateProgramStatus : function(component, event, helper){ var model = component.find('newCancel'); $A.util.removeClass(model, 'slds-show'); $A.util.addClass(model, 'slds-hide'); var backDrop = component.find('cancelbackgrnd'); $A.util.removeClass(backDrop, 'slds-show'); $A.util.addClass(backDrop, 'slds-hide'); var reason = component.find("comments").get("v.value"); console.log("reason" + reason); component.find("comments").set("v.value", ' '); helper.updatePgmStatus(component, event, helper,reason); } }<file_sep>/src/aura/Frontier_SelectedProgramList/Frontier_SelectedProgramListHelper.js ({ applyPaginationToTable : function(component,event,totalRecords){ //component.set("v.isProgramChange",false); console.log('Inside helper Pagination' +totalRecords); var page; var direction; page = component.get("v.currentPage") || 1; direction = event.getParam("direction"); if(direction === "previous"){ page = page - 1; } else if(direction === "next"){ page = page + 1; } // var totalRecords = component.get("v.accountSelectedList"); var pageSize = component.get("v.tablePageSize"); component.set("v.totalRecords",totalRecords.length); component.set("v.Noofpages",Math.ceil((totalRecords.length)/pageSize)); var noOfRecordsToSkip = (page-1)*pageSize; var programs = []; for(var i = noOfRecordsToSkip; i < noOfRecordsToSkip + pageSize && i < totalRecords.length;i++){ programs.push(totalRecords[i]); } component.set("v.currentPage",page); component.set("v.programListAfterSkip",programs); } })<file_sep>/src/aura/Frontier_SalesRep_ProgramDetails/Frontier_SalesRep_ProgramDetailsController.js ({ doInit : function(component, event, helper) { var progId = component.get("v.progId"); console.log('Program Id' + progId); var page = component.get("v.page") || 1; var ispageChange = false; var isInitialize = true; component.set("v.usersInitialLoad",true); helper.programEventListHelper(component,event,page,ispageChange,isInitialize); //helper.getAllPrograms(component,event,helper); }, pageChange: function(component,event,helper) { var cmpName = event.getParam("compName"); console.log('cmpName' + cmpName); if(cmpName == 'SalesRepAccountList'){ var page = component.get("v.page") || 1; var direction = event.getParam("direction"); page = direction === "previous" ? (page - 1) : (page + 1); var ispageChange = true; var isInitialize = false; component.set("v.usersInitialLoad",false); helper.programEventListHelper(component,event,page,ispageChange,isInitialize); } }, sortDirection : function(component,event,helper){ if(event.currentTarget.id != '' && component.get("v.prevId") != '' && component.get("v.prevId") != event.currentTarget.id){ component.set("v.SortBy"+component.get("v.prevId"),"onMouseOut"); } var page = component.get("v.page") || 1; console.log("Event Target"+event.currentTarget.id) if(event.currentTarget.id != ''){ component.set("v.SortBy"+event.currentTarget.id,"onClick"); } var ispageChange = false; var isInitialize = false; component.set("v.prevId",event.currentTarget.id); component.set("v.usersInitialLoad",false); helper.programEventListHelper(component,event,page,ispageChange,isInitialize); }, updateTouchPointNavigation: function(component,event,helper){ helper.navigateToUpdateTouchPointDetail(component, event); }, cancelProgram : function(component,event,helper){ //console.log('Inside cancel' + document.getElementById("newCancel").style.display); var uniqueID = event.currentTarget.id; component.set("v.cancelUniqueId" , uniqueID); console.log(component.get("v.programId")); document.getElementById("newCancelPgm").style.display = "block"; document.getElementById("cancelbackgrndPgm").style.display = "block"; }, showModalBox : function(component,event,helper){ document.getElementById("newCancelPgm").style.display = "none"; document.getElementById("cancelbackgrndPgm").style.display = "none"; component.find("comments").set("v.value", ' '); }, cancelPgmReason : function(component,event,helper){ document.getElementById("newCancelPgm").style.display = "none"; document.getElementById("cancelbackgrndPgm").style.display = "none"; var reason = component.find("comments").get("v.value"); console.log("reason" + reason); component.find("comments").set("v.value", ' '); helper.cancelPgm(component,event,reason); var page = component.get("v.page") || 1; var ispageChange = false; var isInitialize = true; console.log("ispageChange out" + ispageChange); if (ispageChange == undefined){ console.log("ispageChange" + ispageChange); } component.set("v.usersInitialLoad",true); helper.programEventListHelper(component,event,page,ispageChange,isInitialize); }, completePgm : function(component,event,helper){ helper.completePgm(component,event); }, cancelActivity : function(component,event,helper){ helper.cancelSelectedActivity(component,event); var page = component.get("v.page") || 1; var ispageChange = false; var isInitialize = true; component.set("v.usersInitialLoad",true); helper.programEventListHelper(component,event,page,ispageChange,isInitialize); }, programDetailRedirect: function(component,event,helper){ var uniqueId = event.target.id; component.set("v.accountwithProgram",uniqueId); helper.navigateToActivityDetail(component, event,helper); }, closeModal :function (component, event, helper){ helper.closePopup(component, event); }, showAddNewAccount:function(component, event, helper){ var model = component.find('addnewaccount'); $A.util.removeClass(model, 'slds-hide'); $A.util.addClass(model, 'slds-show'); var backDrop = component.find('addCancelbackgrnd'); $A.util.removeClass(backDrop, 'slds-hide'); $A.util.addClass(backDrop, 'slds-show'); $('#lookup').removeClass("slds-hide").addClass("slds-show"); $('#addButton').removeClass("slds-hide").addClass("slds-show"); $('#okButton').removeClass("slds-show").addClass("slds-hide"); $('#cancelButton').removeClass("slds-show").addClass("slds-hide"); $('#confirmContent').removeClass("slds-show").addClass("slds-hide"); $('.twitter-typeahead').removeAttr("style"); if(component.get("v.accountsId") === 'null'){ $('#addButton').attr('disabled',true); }else{ $('#addButton').attr('disabled',false); } }, setAccountsId : function(component, event, helper){ component.set("v.accountsId",component.get("v.accountsId")); if(component.get("v.accountsId") === 'null'){ $('#addButton').attr('disabled',true); }else{ $('#addButton').attr('disabled',false); } }, addAccount: function(component, event, helper){ $('#lookup').removeClass("slds-show").addClass("slds-hide"); $('#addButton').removeClass("slds-show").addClass("slds-hide"); $('#okButton').removeClass("slds-hide").addClass("slds-show"); $('#cancelButton').removeClass("slds-hide").addClass("slds-show"); $('#confirmContent').removeClass("slds-hide").addClass("slds-show"); }, onokayButton : function(component, event, helper){ helper.addAccountPrograms(component, event); }, onCancelButton : function(component, event, helper){ helper.closePopup(component, event); } });<file_sep>/src/aura/Frontier_Gen_AccountSales/Frontier_Gen_AccountSalesController.js ({ doInit : function(component, event, helper) { helper.getAccountSales(component, event, helper, true); }, callupdateCYTarget : function(component, event, helper){ helper.updateCYTarget(component, event, helper); } })<file_sep>/src/aura/Frontier_VisitListReport/Frontier_VisitListReportHelper.js ({ getsEventRecords : function(component, event,page, helper,isInitialize) { var isExport = component.get("v.isExport"); var page = page || 1; var pageSize=component.get("v.pageSize"); console.log(pageSize + 'pageSize'); console.log(page + 'page'); var sortByType = component.find("sortByType").get("v.value"); var sortByRADL = component.find("sortByRADL").get("v.value"); var sortByMonth= component.find("MonthSort").get("v.value"); //var sortByCountry = component.find("CountrySort").get("v.value"); console.log('sortByRADL' + sortByRADL); console.log('sortByMonth' + sortByMonth); //console.log('sortByCountry' + sortByCountry); //var eventList = component.find("eventList").get("v.value"); var action = component.get("c.getVisitDetails"); action.setParams({ pageNumber : page, pageSize : component.get("v.pageSize"), sortByType : sortByType, sortByRADL : sortByRADL, sortByMonth : String(sortByMonth), //sortByCountry : String(sortByCountry), isExport : isExport }); action.setCallback(this,function(response){ var state = response.getState(); if (state === "SUCCESS"){ var message = "E-Mail has been sent"; console.log('Response=>'+response.getReturnValue().length); var resp = response.getReturnValue(); var visitDetailJson =JSON.parse(response.getReturnValue()); console.log('parsed json'+visitDetailJson.length) if(visitDetailJson.length > 0){ console.log(visitDetailJson[0].Count + 'Total'); component.set("v.total",visitDetailJson[0].Count); component.set("v.pages",Math.ceil((visitDetailJson[0].Count)/component.get("v.pageSize"))); component.set("v.page",page); } else if(visitDetailJson.length == 0){ component.set("v.total",0); component.set("v.pages",1); component.set("v.page",1); } if(isExport){ this.showPopUp(component,event,message); } component.set("v.isExport",false); component.set("v.visits", visitDetailJson); } else if (state === "ERROR"){ var errors = response.getError(); if (errors){ if (errors[0] && errors[0].message){ console.log("Error message: "+errors[0].message); } } else{ console.log("Unknown error"); } } }); $A.enqueueAction(action); }, showPopUp: function(component,event,message){ console.log("Inside showPop" + message); $A.createComponent("c:Frontier_PopUp", {Message : message }, function(newComp){ console.log('pop'); var comp = component.find("visitreportpopup"); comp.set("v.body",newComp); }); } })<file_sep>/src/aura/Frontier_AccountDashboard/Frontier_AccountDashboardHelper.js ({ getLastData : function(component, nDay) { var action = component.get("c.getLastData"); action.setParams({ "nDay": nDay }); action.setCallback(this, function(a) { var perRadlClass = JSON.parse(a.getReturnValue()); component.set("v.Accountdevelopavg", perRadlClass.develop); component.set("v.Accountacquireavg", perRadlClass.aquire); component.set("v.Accountretainavg", perRadlClass.retain); component.set("v.Accountlighttouchavg", perRadlClass.lighttouch); }); $A.enqueueAction(action); } });<file_sep>/src/aura/Frontier_TestGrowerAccount_FarmSize/Frontier_TestGrowerAccount_FarmSizeRenderer.js ({ /* afterRender: function(component, helper) { console.log('rerender'); var itemNode = document.getElementById('myDoughnutChart'); itemNode.parentNode.removeChild(itemNode); document.getElementById('chartDivDoughnut').innerHTML = '<canvas id="myDoughnutChart" class="myChartLarge canvasPosition"></canvas>'; return this.superAfterRender(); }, rerender : function(cmp, helper){ var itemNode = document.getElementById('myDoughnutChart'); itemNode.parentNode.removeChild(itemNode); document.getElementById('chartDivDoughnut').innerHTML = '<canvas id="myDoughnutChart" class="myChartLarge canvasPosition"></canvas>'; return this.superRerender(); }*/ unrender: function () { var itemNode = document.getElementById('myDoughnutChart'); itemNode.parentNode.removeChild(itemNode); return this.superUnrender(); } })<file_sep>/src/aura/Frontier_GrowerTouchpointsbyMonth_Chart/Frontier_GrowerTouchpointsbyMonth_ChartHelper.js ({ loadTouchpoint : function(component, event){ console.log('-----Touchpointchart-----' ); var crop = component.get("v.crop"); var season = component.get("v.season"); var action = component.get("c.getTouchpointbyMonth"); action.setParams({ crop : crop, season : season, accType : 'Customer' }); var months = []; var develop = []; var acquire = []; var retain = []; var light = []; var developcount = []; var acquirecount = []; var retaincount = []; var lightcount = []; action.setCallback(this, function(response) { if (response.getState() === "SUCCESS") { console.log('Success'); var touchpointByMonth = (JSON.parse(response.getReturnValue())); //var tPointbyMonth = JSON.stringify(touchpointByMonth); for(var key in touchpointByMonth.touchpermontcount){ console.log('key' + key ); months.push(key); for(var key1 in touchpointByMonth.touchpermontcount[key]){ console.log('key1' + key1); console.log('touchpointByMonth.touchpermontcount[key]' + touchpointByMonth.touchpermontcount[key]); if(!touchpointByMonth.touchpermontcount[key][key1].hasOwnProperty('Develop')){ console.log('Inside Develop'); developcount.push(0); } if(!touchpointByMonth.touchpermontcount[key][key1].hasOwnProperty('Acquire')){ console.log('Inside Acquire'); acquirecount.push(0); } if(!touchpointByMonth.touchpermontcount[key][key1].hasOwnProperty('Retain')){ console.log('Inside Retain'); retaincount.push(0); } if(!touchpointByMonth.touchpermontcount[key][key1].hasOwnProperty('Light Touch')){ console.log('Inside Light'); lightcount.push(0); } for(var key2 in touchpointByMonth.touchpermontcount[key][key1]){ console.log('key 2' + key2); if(key2 == 'Develop'){ console.log('key2' ); develop.push(key2); developcount.push(touchpointByMonth.touchpermontcount[key][key1][key2]); console.log('key2' + touchpointByMonth.touchpermontcount[key][key1][key2]); component.set("v.developcount",developcount); console.log('check dev count' + component.get("v.developcount")); } /* if(key2 != 'Develop'){ //develop.push(key2); developcount.push(0); console.log('develop'+ developcount); //component.set("v.developcount",developcount); //console.log('check dev count' + component.get("v.developcount")); }*/ if(key2 == 'Acquire'){ acquire.push(key2); acquirecount.push(touchpointByMonth.touchpermontcount[key][key1][key2]); } /* if(key2 != 'Acquire'){ //acquire.push(key2); acquirecount.push(0); } */ if(key2 == 'Retain'){ retain.push(key2); retaincount.push(touchpointByMonth.touchpermontcount[key][key1][key2]); } /* if(key2 != 'Retain'){ //retain.push(key2); retaincount.push(0); } */ if(key2 == 'Light Touch'){ light.push(key2); lightcount.push(touchpointByMonth.touchpermontcount[key][key1][key2]); } /* if(key2 != 'Light Touch'){ //light.push(key2); lightcount.push(0); } */ } } } component.set("v.develop" , develop); component.set("v.developcount" , developcount); console.log('check dev ' + component.get("v.developcount")); component.set("v.acquire" , acquire); component.set("v.acquirecount" , acquirecount); console.log('check acq ' + component.get("v.acquirecount")); component.set("v.retain" , retain); component.set("v.retaincount" , retaincount); console.log('check retain' + component.get("v.retaincount")); component.set("v.light" , light); component.set("v.lightcount" , lightcount); console.log('check light' + component.get("v.lightcount")); } else if (response.getState() === "ERROR") { console.log('Errors', response.getError()); } var data = { //labels: salesDetailJson.Labels, labels:months, //labels:["March","June","July"], datasets: [ { label : "Develop", type : "bar", backgroundColor: "rgb(17, 135, 48)", hoverBackgroundColor: "rgba(50,90,100,1)", borderWidth: 1, //data: [develop] data:component.get("v.developcount") // data: salesDetailJson.orderData }, { label : "Acquire", type : "bar", backgroundColor: "rgb(237, 168, 49)", hoverBackgroundColor: "rgba(140,85,100,1)", borderWidth: 1, //data: [acquire] data:component.get("v.acquirecount") //data: salesDetailJson.orderData }, { label : "Retain", type : "bar", backgroundColor: "rgb(252, 208, 171)", hoverBackgroundColor: "rgba(46,185,235,1)", borderWidth: 1, //data: [retaincount] data:component.get("v.retaincount") //data: salesDetailJson.orderData }, { label : "Light Touch", type : "bar", backgroundColor: "rgb(127, 205, 239)", hoverBackgroundColor: "rgba(46,185,235,1)", borderWidth: 1, data:component.get("v.lightcount") //data: [lightcount] //data: salesDetailJson.orderData } ]}; var options = { responsive : true, curvature: 0.5, overlayBars: true, bezierCurve : false, legend:{ display:false }, legend: { display:true, position:'bottom', labels: { fontColor: 'black' } }, scaleLabel:{ display:false }, tooltips: { enabled:true, }, scales: { xAxes: [{ gridLines: { display:false }, categoryPercentage :0.2, barPercentage : 2.5, stacked : true }], yAxes: [{ gridLines: { display:true, color: "#ccc", }, display: true, categoryPercentage :0.4, barPercentage : 2.5, //barThickness : 20, ticks: { // minimum will be 0, unless there is a lower value. suggestedMin: 0, // minimum value will be 0. beginAtZero: true }, stacked : true }] } }; var el = document.getElementById("myChartGrowertouchpoint"); var ctx = el.getContext("2d"); ctx.canvas.height=400; ctx.canvas.width=1300; var myBarChart1 = new Chart(ctx, { type: 'bar', data: data, options: options }); /*window.onresize=function() { myBarChart1.resize(); };*/ }); $A.enqueueAction(action); } });<file_sep>/src/aura/FR_CMP_Touch_Point_Screen/FR_CMP_Touch_Point_ScreenController.js ({ doInit : function(component){ var today = new Date(); component.set('v.today', today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate()); var action = component.get("c.getActivityDetail"); action.setParams({ "accId" :component.get("v.accId") }); var inputsel = component.find("touchPointType"); /*Commented by <NAME> var contactSelectList = component.find("contactList");*/ var reasonSelectList = component.find("touchPointReason"); var opts=[]; var contacts = []; var reasonval =[]; var result; action.setCallback(this, function(a){ result = JSON.parse(a.getReturnValue()); for(var i=0;i< result.Tasktypes.length;i++){ opts.push({"class": "optionClass", label: result.Tasktypes[i], value: result.Tasktypes[i]}); } console.log('**************'+component.get("v.accId")); if(result.contactList.length > 0){ contacts.push({"class": "optionClass", label: "-- None --", value: "None"}); for(var j=0;j< result.contactList.length;j++){ contacts.push({"class": "optionClass", label: result.contactList[j].Name, value: result.contactList[j].Id}); } /*Commented by priyanka contactSelectList.set("v.options",contacts); */ } else{ contacts.push({"class": "optionClass", label: "-- None --", value: "None"}); /*Commented by priyanka contactSelectList.set("v.options",contacts); */ } for(var k=0;k< result.VisitReason.length;k++){ reasonval.push({"class": "optionClass", label: result.VisitReason[k], value: result.VisitReason[k]}); } reasonSelectList.set("v.options",reasonval); inputsel.set("v.options",opts); }); $A.enqueueAction(action); }, createRecord : function (component, event, helper){ var newTouchPoint = component.get("v.newTouchpoint"); var accountId = component.get("v.accId"); console.log(accountId); console.log('**************'+component.get("v.accId")); helper.createTouchRecord(component,newTouchPoint, accountId); }, showModalBox : function(){ console.log('Page Refresh'); document.getElementById("backGroundSecId").style.display = "none"; document.getElementById("newAccountSecId").style.display = "none"; } });<file_sep>/src/aura/Frontier_User_LoginReport/Frontier_User_LoginReportController.js ({ doInit : function(component, event, helper) { var pageChange = false; var page = component.get("v.page") || 1; component.set("v.monthOrCountrySort",false); component.set("v.selectedMonthOrCountry",''); helper.getsLogRecords(component,event,page,helper,pageChange); }, pageChange: function(component,event,helper) { var pageChange = true; var page = component.get("v.page") || 1; var direction = event.getParam("direction"); page = direction === "previous" ? (page - 1) : (page + 1); console.log("Page direction" + page); helper.getsLogRecords(component,event,page,helper,pageChange); }, VisitsList:function(component,event,helper){ var page = 1; var pageChange = false; component.set("v.monthOrCountrySort",false); component.set("v.selectedMonthOrCountry",''); helper.getsLogRecords(component,event,page,helper,pageChange); }, exportData:function(component,event,helper){ component.set("v.isExport",true); var page = 1; if(!component.get("v.monthOrCountrySort")){ helper.getsLogRecords(component, event,page); } else{ helper.monthORCountrySort(component, event,page); } }, SortByMonth:function(cmp,event,helper){ var page =1; cmp.set("v.monthOrCountrySort",true); cmp.set("v.selectedMonthOrCountry",cmp.find("MonthSort").get("v.value")+'/'+cmp.find("CountrySort").get("v.value")); cmp.set("v.selectedMonthOrCountryField","CALENDAR_MONTH(LoginTime)=/CountryIso="); helper.monthORCountrySort(cmp,event,page); }, SortByCountry:function(cmp,event,helper){ var page =1; cmp.set("v.monthOrCountrySort",true); cmp.set("v.selectedMonthOrCountry",cmp.find("MonthSort").get("v.value")+'/'+cmp.find("CountrySort").get("v.value")); cmp.set("v.selectedMonthOrCountryField","CALENDAR_MONTH(LoginTime)=/CountryIso="); helper.monthORCountrySort(cmp,event,page); } })<file_sep>/src/aura/Frontier_TestGrowerAccount_FarmSize/Frontier_TestGrowerAccount_FarmSizeHelper.js ({ loadFormSizeChartData : function(component,fiscalyr,uom) { $A.util.addClass(component.find('tableDiv'),'tableDiv'); if( $A.get("$Browser.isIPhone")){ $A.util.removeClass(component.find("tableThTr"),'tableThTrAndroid'); $A.util.addClass(component.find("tableThTr"),'tableThTrIphone'); } else if($A.get("$Browser.isAndroid")){ $A.util.removeClass(component.find("tableThTr"),'tableThTrIphone'); $A.util.addClass(component.find("tableThTr"),'tableThTrAndroid'); } var errorMsg = $A.get("$Label.Update_Farming_Area_Alert"); console.log("Error msg" , errorMsg); //component.set("v.errorMsg",'**********Please update Total Area for Current FY**********'); var data = { labels: [corn, soya, others ], datasets: [ { data: [50,40,10], backgroundColor: [ "rgba(254, 102, 0, 1)", "rgba(0, 127, 0, 1)", "rgba(127, 127, 127, 1)" ], hoverBackgroundColor: [ "rgba(254, 102, 0, 1)", "rgba(0, 127, 0, 1)", "rgba(127, 127, 127, 1)" ] }] }; var options = { segmentShowStroke: false, responsive : true, animateRotate: true, animateScale: false, cutoutPercentage: 80, legend: { display : false }, tooltips: { callbacks : { label : function(tooltipItem, data) { var label = (data.labels[tooltipItem.index]) label = label.substring(label.indexOf("|")+1,label.indexOf(":")); var data = data.datasets[0].data[tooltipItem.index]+'%'; console.log(label.substring(label.indexOf("|")+1,label.indexOf(":"))); return label+': '+data; }, } } } var el = document.getElementById("myDoughnutChart"); //var el = component.find(bchart); var ctx = el.getContext("2d"); ctx.canvas.width=2; ctx.canvas.height=2; var myBarChart1 = new Chart(document.getElementById("myDoughnutChart").getContext("2d"), { type: 'doughnut', data: data, options:options }); document.getElementById('chartLegend').innerHTML = myBarChart1.generateLegend() +'<span style="padding-left:30px">Total :' +1000+'</span>'; $A.util.addClass(component.find('chartLegend'),'chart-legend'); } })<file_sep>/src/aura/Frontier_AccountDetailViewComponent/Frontier_AccountDetailViewComponentController.js ({ doInit : function(component, event, helper) { helper.getAccountDetailResponse(component,event); var formFactor = $A.get("$Browser.formFactor"); var accountGrid = component.find("accountGrid"); if(formFactor === 'PHONE'){ $A.util.addClass(accountGrid, 'slds-wrap'); $A.util.removeClass(component.find("touchPoint"), 'slds-p-horizontal--small'); $A.util.removeClass(component.find("recentTouchPoint"), 'slds-p-horizontal--small'); } else { $A.util.removeClass(accountGrid, 'slds-wrap'); } } });<file_sep>/src/aura/Frontier_TouchpointbyTypeChart/Frontier_TouchpointbyTypeChartHelper.js ({ loadTouchType : function(component, event){ var action = component.get("c.getTouchpointTypebyRADL"); action.setParams({ // crop : component.get("v.crop"), season : component.get("v.season"), accType : component.get("v.accType") }); var developtypecount = []; var acqtypecount = []; var retaintypecount = []; var lighttypecount = []; var touchType = ['Total','E-mail','Visit','Call','Event']; action.setCallback(this, function(response) { if (response.getState() === "SUCCESS") { var touchpointByVisit = (JSON.parse(response.getReturnValue())); //touchType= touchpointByVisit.typeSet; component.set("v.touchtype",touchType); if(!touchpointByVisit.totalTouchMap.hasOwnProperty('Develop')){ developtypecount.push(0); } if(!touchpointByVisit.totalTouchMap.hasOwnProperty('Acquire')){ acqtypecount.push(0); } if(!touchpointByVisit.totalTouchMap.hasOwnProperty('Retain')){ retaintypecount.push(0); } if(!touchpointByVisit.totalTouchMap.hasOwnProperty('Light Touch')){ lighttypecount.push(0); } for(var key in touchpointByVisit.totalTouchMap){ if(key == 'Develop'){ developtypecount.push(touchpointByVisit.totalTouchMap[key]); } if(key == 'Acquire'){ acqtypecount.push(touchpointByVisit.totalTouchMap[key]); } if(key == 'Retain'){ retaintypecount.push(touchpointByVisit.totalTouchMap[key]); } if(key == 'Light Touch'){ lighttypecount.push(touchpointByVisit.totalTouchMap[key]); } } if(!touchpointByVisit.emailTouchMap.hasOwnProperty('Develop')){ developtypecount.push(0); } if(!touchpointByVisit.emailTouchMap.hasOwnProperty('Acquire')){ acqtypecount.push(0); } if(!touchpointByVisit.emailTouchMap.hasOwnProperty('Retain')){ retaintypecount.push(0); } if(!touchpointByVisit.emailTouchMap.hasOwnProperty('Light Touch')){ lighttypecount.push(0); } for(var key in touchpointByVisit.emailTouchMap){ if(key == 'Develop'){ developtypecount.push(touchpointByVisit.emailTouchMap[key]); } if(key == 'Acquire'){ acqtypecount.push(touchpointByVisit.emailTouchMap[key]); } if(key == 'Retain'){ retaintypecount.push(touchpointByVisit.emailTouchMap[key]); } if(key == 'Light Touch'){ lighttypecount.push(touchpointByVisit.emailTouchMap[key]); } } if(!touchpointByVisit.visitTouchMap.hasOwnProperty('Develop')){ developtypecount.push(0); } if(!touchpointByVisit.visitTouchMap.hasOwnProperty('Acquire')){ acqtypecount.push(0); } if(!touchpointByVisit.visitTouchMap.hasOwnProperty('Retain')){ retaintypecount.push(0); } if(!touchpointByVisit.visitTouchMap.hasOwnProperty('Light Touch')){ lighttypecount.push(0); } for(var key in touchpointByVisit.visitTouchMap){ if(key == 'Develop'){ developtypecount.push(touchpointByVisit.visitTouchMap[key]); } if(key == 'Acquire'){ acqtypecount.push(touchpointByVisit.visitTouchMap[key]); } if(key == 'Retain'){ retaintypecount.push(touchpointByVisit.visitTouchMap[key]); } if(key == 'Light Touch'){ lighttypecount.push(touchpointByVisit.visitTouchMap[key]); } } if(!touchpointByVisit.chatTouchMap.hasOwnProperty('Develop')){ developtypecount.push(0); } if(!touchpointByVisit.chatTouchMap.hasOwnProperty('Acquire')){ acqtypecount.push(0); } if(!touchpointByVisit.chatTouchMap.hasOwnProperty('Retain')){ retaintypecount.push(0); } if(!touchpointByVisit.chatTouchMap.hasOwnProperty('Light Touch')){ lighttypecount.push(0); } for(var key in touchpointByVisit.chatTouchMap){ if(key == 'Develop'){ developtypecount.push(touchpointByVisit.chatTouchMap[key]); } if(key == 'Acquire'){ acqtypecount.push(touchpointByVisit.chatTouchMap[key]); } if(key == 'Retain'){ retaintypecount.push(touchpointByVisit.chatTouchMap[key]); } if(key == 'Light Touch'){ lighttypecount.push(touchpointByVisit.chatTouchMap[key]); } } if(!touchpointByVisit.callTouchMap.hasOwnProperty('Develop')){ developtypecount.push(0); } if(!touchpointByVisit.callTouchMap.hasOwnProperty('Acquire')){ acqtypecount.push(0); } if(!touchpointByVisit.callTouchMap.hasOwnProperty('Retain')){ retaintypecount.push(0); } if(!touchpointByVisit.callTouchMap.hasOwnProperty('Light Touch')){ lighttypecount.push(0); } for(var key in touchpointByVisit.callTouchMap){ if(key == 'Develop'){ developtypecount.push(touchpointByVisit.callTouchMap[key]); } if(key == 'Acquire'){ acqtypecount.push(touchpointByVisit.callTouchMap[key]); } if(key == 'Retain'){ retaintypecount.push(touchpointByVisit.callTouchMap[key]); } if(key == 'Light Touch'){ lighttypecount.push(touchpointByVisit.callTouchMap[key]); } } component.set("v.dtypecount",developtypecount); component.set("v.acqtypecount",acqtypecount); component.set("v.rtypecount",retaintypecount); component.set("v.ltypecount",lighttypecount); } else if (response.getState() === "ERROR") { console.log('Errors', response.getError()); } var data = { //labels: salesDetailJson.Labels, //labels:["Total","Visit"], labels:component.get("v.touchtype"), datasets: [ { label : "Develop", type : "bar", backgroundColor: "rgb(17, 135, 48)", hoverBackgroundColor: "rgba(50,90,100,1)", borderWidth: 1, data:component.get("v.dtypecount") }, { label : "Acquire", type : "bar", backgroundColor: "rgb(237, 168, 49)", hoverBackgroundColor: "rgba(140,85,100,1)", borderWidth: 1, data:component.get("v.acqtypecount") }, { label : "Retain", type : "bar", backgroundColor: "rgb(252, 208, 171)", hoverBackgroundColor: "rgba(46,185,235,1)", borderWidth: 1, data:component.get("v.rtypecount") }, { label : "Light Touch", type : "bar", backgroundColor: "rgb(127, 205, 239)", hoverBackgroundColor: "rgba(46,185,235,1)", borderWidth: 1, data:component.get("v.ltypecount") } ]}; var options = { responsive : true, curvature: 0.5, overlayBars: true, bezierCurve : false, legend: { display:true, position:'bottom', labels: { fontColor: 'black' } }, scaleLabel:{ display:false }, hover: { mode: true, animationDuration: 0 }, tooltips: { enabled:true, }, scales: { xAxes: [{ gridLines: { display:false }, categoryPercentage :0.5, barPercentage : 1.5, stacked : true }], yAxes: [{ gridLines: { display:true, color: "#ccc", }, display: true, ticks: { // minimum will be 0, unless there is a lower value. suggestedMin: 0, // minimum value will be 0. beginAtZero: true }, stacked : true }] } }; var el = document.getElementById("myChart"); var ctx = el.getContext("2d"); ctx.canvas.height=400; ctx.canvas.width=1300; var myBarChart1 = new Chart(ctx, { type: 'bar', data: data, options: options }); window.onresize=function() { myBarChart1.resize(); }; }); $A.enqueueAction(action); } });<file_sep>/src/aura/Frontier_Touchpoint_Planning_Calender/Frontier_Touchpoint_Planning_CalenderHelper.js ({ redirectTonewTouchpoint : function(component, event, ids, date, actionStatus,isreadOnly){ var parsedDate; if(date){ parsedDate = date.format(); } /*$A.createComponent("c:Frontier_GrowerAccount_UpdateTouchPoint", { "clickdate":date, "newUpdateStatus":actionStatus, "growerAcc": ids, "isFromCalendar":true, "isReadOnly":isreadOnly }, function(touchPoint){ var comp = component.find("calenderBody"); comp.set("v.body",touchPoint); });*/ //var comp = component.find("calenderBody"); //comp.set("v.body",[]); //this.removejscssfile(component,event,'Momentjs.js','js'); var evt = $A.get("e.force:navigateToComponent"); evt.setParams({ componentDef : "c:Frontier_GrowerAccount_UpdateTouchPoint", componentAttributes: { clickdate:parsedDate, newUpdateStatus:actionStatus, growerAcc: ids, isFromCalendar:true, isReadOnly:isreadOnly, isLoaded:true } }); evt.fire(); //var compEvent = component.getEvent("masterCalendarEvent"); //compEvent.fire(); }, loadCalendarData : function(component, event, helper){ var action = component.get("c.getAllTouchPoints"); action.setCallback(this, function(response) { if (response.getState() === "SUCCESS") { var touchPointList = JSON.parse(response.getReturnValue()); var eventsources = helper.convertToCalendarFormat(component, event, helper,touchPointList); helper.loadDatatoCalendar(component, event, helper,eventsources); } else if (response.getState() === "ERROR") { $A.log("Errors", response.getError()); } }); $A.enqueueAction(action); }, convertToCalendarFormat : function(component,event,helper,touchPointList){ var eventSources = []; var eventsArray; console.log('touchPointList=>'+JSON.stringify(touchPointList)); $.map(touchPointList, function(value, key){ eventsArray=[]; var objevent; var titleText = ''; for(var i in value){ objevent = {"id":'',"title":'',"start":'',"color":'',"textColor":'',"isReadOnly":false}; objevent.id = value[i].Program_SFID__c+'/'+value[i].WhatId+','+','+'/'+value[i].Program_Activity_SFID__c+'/'+value[i].TouchPoint_SFID__c+'/'+value[i].TouchPoint_SFID__r.Date__c+'/'+''; if(value[i].TouchPoint_SFID__r.Name){ titleText = '<b>'+value[i].TouchPoint_SFID__r.Name+'</b>'; } for(var j in value){ titleText = titleText + '<br>' + (value[j].Subject?value[j].Subject:''); } objevent.title = titleText; var startDate = value[i].TouchPoint_SFID__r.Date__c; var format = 'YYYY/MM/DD HH:mm:ss ZZ'; var zone = $A.get("$Locale.timezone"); var parsedDate = moment(startDate, format).tz(zone).format(format); console.log("StartDate!!!" + startDate); if(!$A.util.isUndefinedOrNull(parsedDate)){ objevent.start = parsedDate; } if(value[i].TouchPoint_SFID__r.TouchPoint_Status__c === 'Scheduled'){ objevent.color = '#66ccff'; } else if(value[i].TouchPoint_SFID__r.TouchPoint_Status__c === 'Cancelled'){ objevent.color = 'rgba(255, 0, 0, 0.498039215686275)'; objevent.isReadOnly = true; } else if (value[i].TouchPoint_SFID__r.TouchPoint_Status__c === 'Completed'){ objevent.color = '#00ff00'; objevent.isReadOnly = true; } objevent.textColor = '#000000'; if(objevent.title && objevent.start){ eventsArray.push(objevent); break; } } eventSources.push({events:eventsArray}); }); return eventSources; }, loadDatatoCalendar :function(component,event,helper,eventSources){ $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title,\n,month,agendaWeek,agendaDay' }, timezone:'UTC', editable : true, eventStartEditable : true, defaultView: 'month', eventSources: eventSources, dayClick: function(date, allDay, jsEvent, view){ var ids = ''+'/'+'0012C00000AsKGzQAN'+','+'a0g2C000000UynxQAC'+'/'; var isPastDated = $(this).hasClass("fc-other-month fc-past"); var isFutureDated = $(this).hasClass("fc-other-month fc-future"); if(!isPastDated && !isFutureDated){ helper.redirectTonewTouchpoint(component, event, ids, date,'New',false); } }, eventClick: function(calEvent, jsEvent, view) { var spinner = component.find('spinner'); $A.util.removeClass(spinner, "xc-hidden"); var actionStatus = 'update'; if(calEvent.isReadOnly){ actionStatus = 'view'; } helper.redirectTonewTouchpoint(component,event,calEvent.id,'',actionStatus,calEvent.isReadOnly); }, eventRender: function(event, element, view) { if (view.name === 'month') { element.find('span.fc-title').html(element.find('span.fc-title').text()); } else if (view.name === 'agendaWeek' || view.name === 'agendaDay') { element.find('div.fc-title').html(element.find('div.fc-title').text()); } } }); }, removejscssfile :function(component, event, filename, filetype){ var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist from var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for var allsuspects=document.getElementsByTagName(targetelement) for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1) allsuspects[i].parentNode.removeChild(allsuspects[i]) //remove element by calling parentNode.removeChild() } } })<file_sep>/src/aura/Frontier_AssociatedProducts/Frontier_AssociatedProductsRenderer.js ({ rerender : function (component,helper) { } })<file_sep>/src/aura/Frontier_AccountByRadlChart/Frontier_AccountByRadlChartController.js ({ loadAccdashboard : function(component, event, helper){ helper.loadAccDashData(component, event); } })<file_sep>/src/aura/Frontier_FollowUpReport/Frontier_FollowUpReportController.js ({ doInit : function(component, event, helper) { console.log("hjghgj"); var page = component.get("v.page") || 1; var ispageChange = false; var isInitialize = true; helper.getsTaskObjectRecords(component,event,helper,page,ispageChange,isInitialize,component.get("v.taskId")); }, FollowUpList:function(component,event,helper){ //var page = component.get("v.page") || 1; var page = 1; var ispageChange = false; var isInitialize = true; if(component.get("v.prevId") != ''){ component.set("v.SortBy"+component.get("v.prevId"),"onMouseOut"); } helper.getsTaskObjectRecords(component,event,helper,page,ispageChange,isInitialize,''); }, pageChange: function(component,event,helper) { var page = component.get("v.page") || 1; var direction = event.getParam("direction"); page = direction === "previous" ? (page - 1) : (page + 1); var ispageChange = true; var isInitialize = false; helper.getsTaskObjectRecords(component,event,helper,page,ispageChange,isInitialize,''); }, /* showIcon : function(component,event){ if(event.target.id != null && component.get("v.SortBy"+event.target.id) != 'onClick'){ component.set("v.SortBy"+event.target.id,"onHover"); } }, hideIcon : function(component,event){ if(event.target.id != null && component.get("v.SortBy"+event.target.id) != 'onClick'){ component.set("v.SortBy"+event.target.id,"onMouseOut"); } }, */ sortDirection : function(component,event,helper){ var previousId; if(event.target.id != '' && component.get("v.prevId") != '' && component.get("v.prevId") != event.target.id){ console.log('Before'+component.get("v.SortBy"+component.get("v.prevId"))); component.set("v.SortBy"+component.get("v.prevId"),"onMouseOut"); console.log('After'+component.get("v.SortBy"+component.get("v.prevId"))); } var page = component.get("v.page") || 1; if(event.target.id != ''){ component.set("v.SortBy"+event.target.id,"onClick"); } var ispageChange = false; var isInitialize = false; component.set("v.prevId",event.target.id); helper.getsTaskObjectRecords(component,event,helper,page,ispageChange,isInitialize); } })<file_sep>/src/aura/Frontier_DealerDetail_Profile/Frontier_DealerDetail_ProfileHelper.js ({ dealerProfile : function(component, event, helpe) { var seasonVal = '2017 Safra'; var selectedSeason = component.find("selectedSeason").get("v.value"); if(selectedSeason != null) { seasonVal = selectedSeason; } var selecteddealer = component.get("v.dealerId"); var action = component.get("c.dealerAccountDetails"); console.log('selecteddealer'+selecteddealer+'action'+action+'seasonVal'+seasonVal); action.setParams({ dealerAccount : component.get("v.dealerId"), dealerAccComm : component.get("v.accCommId"), season :seasonVal }); action.setCallback(this, function(response) { if (response.getState() === "SUCCESS") { var dealerAccountDetailJson = JSON.parse(response.getReturnValue()); console.log('Inside Profile' +JSON.stringify(dealerAccountDetailJson )); component.set("v.dealerProfileDetails",dealerAccountDetailJson); //this.getSeasonDetails(component,event,helper); } else if (response.getState() === "ERROR") { $A.log("Errors", response.getError()); component.set("v.isCallBackError",false); } }); $A.enqueueAction(action); } });<file_sep>/src/aura/Frontier_SalesRep_KPI_Chart/Frontier_SalesRep_KPI_ChartController.js ({ /*doInit : function(component, event, helper) { var data = [0,25,50,75,100]; component.set("v.CropData",data); var labels = ['2017','2018','2019','2010']; component.set("v.label",labels); component.set("v.KPIMeasure","Sales Order By Crop"); },*/ loadChart: function(component, event, helper) { helper.loadChartData(component, event, helper); } })<file_sep>/src/aura/Frontier_SalesRep_Programs/Frontier_SalesRep_ProgramsHelper.js ({ listProgram : function(component,event,helper,page,ispageChange,isInitialize) { console.log('Inside list program'); var triggeredField = null; if(!isInitialize){ console.log('event.target.id' + event.currentTarget.id); if(event.target && event.currentTarget.id != null){ console.log("v.SortByField."+event.currentTarget.id); triggeredField = component.get("v.SortByField."+event.currentTarget.id); //triggeredField = component.get("v.SortByField.ProgramName"); console.log('Triggered Field get'+ triggeredField); component.set("v.triggeredField",triggeredField); console.log('Triggered Field'+"v.SortByField."+event.currentTarget.id); } else if(ispageChange && component.get("v.triggeredField") != ""){ triggeredField = component.get("v.triggeredField"); } } var action = component.get("c.getProgramList"); var page = page || 1; var pageSize=component.get("v.pageSize"); //console.log(eventList + 'eventList'); var dealerAccount = (component.get("v.growerAcc")).split(',')[0]; console.log('dealerAccount' + dealerAccount); action.setParams({ accId : dealerAccount, pageNumber : page, pageSize : component.get("v.pageSize"), triggeredField : triggeredField, isInitialize : isInitialize, isPageChange : ispageChange }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ console.log('Success'); var programlist=[]; var programlistresponse = response.getReturnValue(); component.set("v.pages",Math.ceil((JSON.parse(programlistresponse[0]))/component.get("v.pageSize"))); component.set("v.total",JSON.parse(programlistresponse[0])); programlist = JSON.parse(programlistresponse[1]); component.set("v.programList" , programlist); console.log('programlist' , programlist); component.set("v.SortByField", JSON.parse(programlistresponse[2])); } else if (state === "ERROR"){ console.log('Error'); } }); $A.enqueueAction(action); }, navigateToProgramDetail : function(component,event) { console.log("c:Frontier_GrowerAccount_ProgramEventsList"); var uniqueId = event.currentTarget.id; var programId = (uniqueId.split('/')[0]); var accountId = (uniqueId.split('/')[1]); console.log(programId+accountId); $A.createComponent( "c:Frontier_GrowerAccount_ProgramEventsList", { "growerAcc": component.get("v.growerAcc"), programId: programId, accountId:accountId }, function(newCmp){ var cmp = component.find("ProgramDetail"); //cmp.set("v.body", []); cmp.set("v.body", newCmp); } ); }, cancelPgm : function(component,event,reason){ var pgmAccId = component.get("v.programId"); console.log('pgmAcc' + pgmAccId); //var programId = (pgmAccId.split('/')[0]); //var accId = (pgmAccId.split('/')[1]); var accPgmId = (pgmAccId.split('/')[0]); var status = (pgmAccId.split('/')[1]); console.log( accPgmId + ' ' + status); var action = component.get("c.getCancelPgm"); action.setParams({ status : status, accPgmId : accPgmId, reason : reason }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ console.log('Success'); } else if(state === 'ERROR'){ console.log('Error'); } }); $A.enqueueAction(action); }, navigateToProfileDetails :function(component,event) { var action = component.get("c.getProgramProfileDetails"); var growerAccDetail = component.get("v.growerAcc"); var growerAccId = growerAccDetail.split(',')[0]; var groweraccCommId = growerAccDetail.split(',')[2]; if(component.get("v.role") === 'Partner'){ $A.createComponent("c:Frontier_DealerDetail_Profile", { "dealerId" : growerAccId, "accCommId": groweraccCommId }, function(newCmp){ //Render the sales order dashboard component to the parent container var cmp = component.find("profileDetails"); cmp.set("v.body", newCmp); } ); } else{ action.setCallback(this,function(response){ var state = response.getState(); if (state === "SUCCESS" && !(response.getReturnValue() === 'CalloutError')){ //component.set("v.GrowerDetails" ,response.getReturnValue()); $A.createComponent( "c:Frontier_GrowerProfileDetails", { "GrowerDetailResponse": response.getReturnValue(), "growerId":growerAccId, "accCommId":groweraccCommId }, function(newCmp){ //Render the sales order dashboard component to the parent container var cmp = component.find("profileDetails"); cmp.set("v.body", newCmp); } ); } }); $A.enqueueAction(action); } } })<file_sep>/src/aura/Frontier_ProgramPlanning_Accountlist/Frontier_ProgramPlanning_AccountlistController.js ({ doInit:function(component,event,helper){ var accountList = component.get("v.accountList"); var account = component.get("v.account"); console.log('account'+account); console.log('accountList'+accountList); var radlKey = (component.get("v.radlKey") == undefined ? 'None': component.get("v.radlKey")) ; var searchKey = (component.get("v.searchKey") == undefined || component.get("v.searchKey") == null ? '' : component.get("v.searchKey")); if(accountList != null && accountList.length > 0){ for(var i = 0;i<accountList.length;i++){ if(account != undefined && account.Id == accountList[i].Id && ((radlKey != undefined && (radlKey != 'None' || radlKey != null) && radlKey == account.serviceLevelDesc)?true:((radlKey == undefined || radlKey == 'None' || radlKey == null) && searchKey != '' ? true :(searchKey == '' && radlKey == 'None'?true:false))) ){ /* if(account != undefined && account.Id == accountList[i].Id){ var isSelectAccount = false; var accName = String(account.Name).toLowerCase(); var searchText = searchKey.toLowerCase(); if((radlKey != undefined && (radlKey != 'None' || radlKey != null) && radlKey == account.serviceLevelDesc) && searchKey != '' && searchText == accName){ isSelectAccount = true; } else if((radlKey == 'None' || radlKey == null) && (searchKey != '' && searchText == accName)){ console.log('Matched'); isSelectAccount = true; } else if((searchKey == '') && (radlKey != undefined && (radlKey != 'None' || radlKey != null) && radlKey == account.serviceLevelDesc)){ isSelectAccount = true; } else if(searchKey == '' && (radlKey == 'None' || radlKey == null || radlKey == undefined)){ isSelectAccount = true; } if(isSelectAccount){ component.set("v.account",accountList[i]); break; } }*/ component.set("v.account",accountList[i]); break; } } } }, onCheck : function(component, event, helper) { var account = component.get("v.account"); helper.selectAccount(component, event, helper,account.isSelected,account.accId); }, selectAllAccounts : function(component, event, helper) { console.log('Select All'); var filteredAccountList = event.getParam("filteredAccountList"); var account = component.get("v.account"); var accountToSelect = {}; accountToSelect = JSON.stringify(account); console.log('**********accountToSelect'+accountToSelect); var isAllSelected = event.getParam("isAllSelected"); console.log('**********isAllSelected'+isAllSelected+'filteredAccountList'+JSON.stringify(filteredAccountList)); if(isAllSelected && filteredAccountList.length > 0){ for(var i = 0; i < filteredAccountList.length; i++){ console.log('**********filteredAccountList[i].Id == account.Id'+filteredAccountList[i].Id == account.Id); if(!account.isSelected && filteredAccountList[i].Id == account.Id){ helper.enableAccount(component,accountToSelect,'isSelected',false,true,true); helper.selectAccount(component, event, helper,true,account.accId); break; } } } else if(!isAllSelected && filteredAccountList.length > 0){ for(var i = 0; i < filteredAccountList.length; i++){ if(account.isSelected && filteredAccountList[i].Id == account.Id){ helper.enableAccount(component,accountToSelect,'isSelected',false,true,false); helper.selectAccount(component, event, helper,false,account.accId); break; } } } } })<file_sep>/src/aura/Frontier_DealerDetail_MasterComponent/Frontier_DealerDetail_MasterComponentHelper.js ({ navigateToDealerDetails : function(component,event) { var dealerAccDetail = component.get("v.growerAcc"); var dealerAccId = dealerAccDetail.split(',')[0]; var dealeraccCommId = dealerAccDetail.split(',')[2]; var action = component.get("c.getGrowerAccs"); /*action.setCallback(this, function(response){ var state = response.getState(); if (state === "SUCCESS" && !(response.getReturnValue() === 'CalloutError')){ component.set("v.GrowerDetails" ,response.getReturnValue()); console.log('Response------------>' + response.getReturnValue()); $A.createComponent("c:Frontier_DealerDetail_Profile", { "dealerAccId" : dealerAccId, "dealerAccCmmId" : dealeraccCommId }, function(newCmp){ //Render the sales order dashboard component to the parent container alert(); var cmp = component.find("DealerProfileSection"); cmp.set("v.body", newCmp); } ); } }); $A.enqueueAction(action);*/ $A.createComponent("c:Frontier_DealerDetail_Profile", { "dealerId" : (component.get("v.growerAcc")).split(',')[0], "accCommId" : (component.get("v.growerAcc")).split(',')[2] }, function(newCmp){ //Render the sales order dashboard component to the parent container var cmp = component.find("DealerProfileSection"); cmp.set("v.body", newCmp); } ); }, toGrowerCount : function(component,event){ component.set("v.setHeader" , false); $A.createComponent("c:Frontier_GrowerAccountList", {label : ""}, function(GrowerList){ var comp = component.find("growerList"); comp.set("v.body",GrowerList); } ); }, getGrowerCount : function(component,event){ var action = component.get("c.getGrowerCount"); action.setParams({ dealerId : (component.get("v.growerAcc")).split(',')[0] }); action.setCallback(this, function(response){ var state = response.getState(); if(state === "SUCCESS"){ component.set("v.growerCount",response.getReturnValue()); } }) $A.enqueueAction(action); } })<file_sep>/src/aura/Frontier_GrowerAccount_RecordTouchPoint/Frontier_GrowerAccount_RecordTouchPointHelper.js ({ createTouchRecord : function(component, touch, accountId){ console.log("Inside Helper"); var fieldDate = component.find("date"); var fieldDateValue = fieldDate.get("v.value"); console.log(fieldDateValue + "fieldDateValue"); var validItem; if ($A.util.isEmpty(fieldDateValue)){ validItem = false; fieldDate.set("v.errors", [{message:"Value can't be blank."}]); } else{ validItem = true; fieldDate.set("v.errors", null); } if(validItem){ this.upsertTouchPoint(component, touch, accountId, function(a) { var touches = component.get("v.touchpoints"); touches.push(a.getReturnValue()); if(a.getState() === "SUCCESS"){ var message = "visitrecord"; /* var comments = component.get("v.comments"); console.log(message); console.log('comments' + comments);*/ //component.set("v.message" , message); console.log("message" + message); //component.find("notes").set("v.value",""); component.find("touchPointType").set("v.value",""); component.find("date").set("v.value",""); //component.set("v.message", message); var appEvent = $A.get("e.c:Frontier_TouchPointCount"); appEvent.setParams({"message" : "" }); appEvent.fire(); this.showPopUp(component,event,accountId,message); } component.set("v.touchpoints", touches); component.set("v.newTouchpoint",{'sobjectType': 'Event', 'ActivityDateTime': null, 'Description': '', 'Type': 'Call'}); }); } }, upsertTouchPoint : function(component, touch, acId, callback){ // Commented By Priyanka var contactId = component.find("contactList").get("v.value"); //var contactId = 'None'; //var notes = component.find("notes").get("v.value"); var touchPointType = component.find("touchPointType").get("v.value"); var dateVal = component.find("date").get("v.value"); var action = component.get("c.insertTouchPoint"); // component.set("v.comments",notes); action.setParams({ "notes" : '', "touchPointType" :touchPointType, "StartDate": dateVal, "accuID": acId, "contactId" : contactId }); if (callback) { action.setCallback(this, callback); } $A.enqueueAction(action); }, showPopUp: function(component,event,accId,message){ console.log("Inside showPop" + message); console.log("Inside showPop" + accId); //console.log("Inside showPop" + comments); $A.createComponent("c:Frontier_PopUp", {Message : message, accId : accId }, function(newComp){ console.log('pop'); var comp = component.find("visitpopup"); comp.set("v.body",newComp); } ); } });<file_sep>/src/aura/Frontier_GrowerAccount_Sales/Frontier_GrowerAccount_SalesRenderer.js ({ /*render: function(component, helper) { console.log('rerender'); $A.get('e.force:refreshView').fire(); return this.superRender(); }*/ })<file_sep>/src/aura/Frontier_DealerAccount_Sales_Master/Frontier_DealerAccount_Sales_MasterHelper.js ({ dealerSalesDetails : function(component,event,helper) { //var UOM = component.find("sortByType").get("v.value"); var growerAccSalesJson; console.log('Dealer id' +dealerAccId); console.log('UOM'+UOM); var UOM = 'Units'; var dealerAccId=component.get("v.dealerid").split(',')[0]; console.log('dealerAccId' + dealerAccId); var action = component.get("c.getdealerSalesDetails"); action.setParams({ dealerAccId :dealerAccId, UOM:UOM }); action.setCallback(this, function(response) { if (response.getState() === "SUCCESS") { console.log('Success'); growerAccSalesJson = (JSON.parse(response.getReturnValue())); console.log('growerAccSalesJson' + JSON.stringify(growerAccSalesJson)); component.set("v.growerSalesFarm",growerAccSalesJson); var growerSalesFarmCrop = []; for(var key in growerAccSalesJson.cropMap){ console.log('Inside Map'); growerSalesFarmCrop.push(key); } console.log('growerSalesFarmCrop' +growerSalesFarmCrop.sort()); component.set("v.growerSalesFarmCrop", growerSalesFarmCrop.sort()); if(growerSalesFarmCrop != null && growerSalesFarmCrop.length > 0){ component.set("v.latestCrop",growerSalesFarmCrop[growerSalesFarmCrop.length -1]); } component.set("v.loadchart1" , true); component.set("v.loadchart2" , true); component.set("v.loadchart3" , true); var crops = []; var conts = growerAccSalesJson.cropPercentage; for ( key in conts ) { crops.push({value:conts[key], key:key}); } component.set("v.crops", crops); } else if (response.getState() === "ERROR") { $A.log("Errors", response.getError()); console.log("Errors", response.getError()); } }); $A.enqueueAction(action); } });<file_sep>/src/aura/Frontier_ProgramPlanning_Radl/Frontier_ProgramPlanning_RadlHelper.js ({ loadRADLgraph : function(component,event) { /*console.log('Inside graph' + component.get("v.fromCmp")); var programId; var developradlCount =[]; var acqradlCount =[]; var retainradlCount =[]; var lightradlCount =[]; if(component.get("v.fromCmp") == 'myPrograms'){ programId = null; console.log('programId' + programId); } if(component.get("v.programId") != '' || component.get("v.programId") != undefined ){ programId = component.get("v.programId"); console.log('programId' + programId); } var action = component.get("c.getGraphdata"); action.setParams({ programId : programId, dealerId : component.get("v.dealerId") }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ console.log('Success'); var accPgmRADL = (JSON.parse(response.getReturnValue())); for(var key in accPgmRADL.accPgmRadlMap){ console.log('key' + key ); if(key == 'Develop'){ component.set("v.dcount",accPgmRADL.accPgmRadlMap[key]); } if(key == 'Acquire'){ component.set("v.acqcount",accPgmRADL.accPgmRadlMap[key]); } if(key == 'Retain'){ component.set("v.rcount",accPgmRADL.accPgmRadlMap[key]); } if(key == 'Light Touch'){ component.set("v.lcount",accPgmRADL.accPgmRadlMap[key]); } } } else{ console.log('Error'); } }); $A.enqueueAction(action); */ } })<file_sep>/src/aura/Frontier_GrowerTouchpointsbyMonth_Chart/Frontier_GrowerTouchpointsbyMonth_ChartController.js ({ loadtouchpointdata : function(component, event, helper){ helper.loadTouchpoint(component, event); } })<file_sep>/src/aura/Frontier_FollowUpReport/Frontier_FollowUpReportHelper.js ({ getsTaskObjectRecords : function(component,event,helper,page,isPageChange,isInitialize,taskId) { //var fieldName = (event.target ? (event.target.id != null ?component.get("v.SortByField."+event.target.id):""):""); var triggeredField = null; if(!isInitialize){ if(event.target && event.target.id != null){ triggeredField = component.get("v.SortByField."+event.target.id); component.set("v.triggeredField",triggeredField); console.log('Triggered Field'+triggeredField); } else if(isPageChange && component.get("v.triggeredField") != ""){ triggeredField = component.get("v.triggeredField"); } } var followupList = component.find("followupList").get("v.value"); var action = component.get("c.findActivities"); console.log('*****************'+page); console.log('triggeredField'+triggeredField); var page = page || 1; var pageSize=component.get("v.pageSize"); console.log(followupList + 'followupList'); action.setParams({ pageNumber : page, pageSize : component.get("v.pageSize"), followupList : followupList, triggeredField : triggeredField, isInitialize : isInitialize, isPageChange : isPageChange, taskId : taskId }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ var followuplist = []; //component.set("v.latestRecords",response.getReturnValue()); var retResponse = response.getReturnValue(); console.log("retResponse"+ retResponse); followuplist = JSON.parse(retResponse[1]); if(retResponse.length > 0){ component.set("v.page",page); component.set("v.total",JSON.parse(retResponse[0])); component.set("v.pages",Math.ceil((JSON.parse(retResponse[0]))/component.get("v.pageSize"))); console.log("followuplist length "+ followuplist.length); component.set("v.FollowUpDataList", followuplist); component.set("v.SortByField", JSON.parse(retResponse[2])); console.log('Sort Order'+retResponse[2]) } else if(retResponse.length == 0){ component.set("v.FollowUpDataList", followuplist); component.set("v.page",1); component.set("v.total",0); component.set("v.pages",1); } } else if (state === "ERROR"){ console.log('Error'); } }); $A.enqueueAction(action); } })<file_sep>/src/aura/Frontier_ProgramPlanning/Frontier_ProgramPlanningController.js ({ doInit:function(component,event,helper){ var searchKey = ''; var radlKey = 'None'; var page = component.get("v.page") || 1; helper.helperchangeProgram(component,event,helper,true); helper.getAllAccounts(component,page,searchKey,radlKey,true,false); }, pageChange: function(component, event, helper) { var cmpName = event.getParam("compName"); console.log('cmpName' + cmpName); if(cmpName == 'ProgramplanAccountList'){ var page; var direction; var radlKey; var searchKey = component.get("v.searchString"); radlKey = component.get("v.radlKey"); if(searchKey == undefined){ searchKey=''; } if(radlKey == undefined ) { radlKey='None'; } page = component.get("v.page") || 1; direction = event.getParam("direction"); page = direction === "previous" ? (page - 1) : (page + 1); //radlKey = component.find("searchByRADL").get("v.value"); var isSelectedAccount = false; if(component.get("v.accountSelectedList") != '' && (radlKey == 'None' ||searchKey == '')){ isSelectedAccount = true; } /* else if(component.get("v.deletedAccountIds") != null){ isSelectedAccount = true; }*/ if(component.get("v.isAllSelected")){ component.set("v.isAllSelected",true); //helper.checkAllAccounts(component,event,helper); } helper.getAllAccounts(component,page,searchKey,radlKey,false,isSelectedAccount); } }, tableChange: function(component,event,helper) { var cmpName = event.getParam("compName"); console.log('cmpName' + cmpName); if(cmpName == 'ProgramAccount'){ var isEventFired = true; helper.applyPaginationToTable(component,event,component.get("v.accountSelectedList"),isEventFired); } }, searchKey: function(component, event){ var myEvent = $A.get("e.c:Frontier_AccountSearchkey"); myEvent.setParams({"searchKey": event.target.value}); myEvent.fire(); }, sortKey: function(component,event){ var sortEvent = $A.get("e.c:Frontier_AccountSortkey"); var selectCmp = component.find("searchByRADL").get("v.value"); console.log("Selected" +selectCmp); sortEvent.setParams({"sortbyValue": selectCmp}); sortEvent.fire(); }, searchKeyChange: function(component, event,helper){ var searchKey,radlKey; var page = 1; searchKey = event.getParam("searchKey"); var isEmptySearch = false; radlKey = event.getParam("sortbyValue"); console.log('searchKey----' +searchKey+'radlKey----'+radlKey+'component.get("v.searchString")'+component.get("v.searchString")); if(searchKey != undefined){ component.set("v.searchString",searchKey); console.log('searchKey Available' +searchKey); } else if(component.get("v.searchString") != null || component.get("v.searchString") != undefined || component.get("v.searchString") != ''){ searchKey = component.get("v.searchString"); console.log('searchKey Retained' +searchKey) } else if(searchKey == undefined || component.get("v.searchString") == null || searchKey == '' || searchKey == null || component.get("v.searchString") == '' || component.get("v.searchString") == undefined){ if(component.get("v.searchText") == undefined || component.get("v.searchText") == null || component.get("v.searchText") == ''){ searchKey = ''; component.set("v.searchString",''); isEmptySearch = true; console.log('No searchKey' +searchKey) } } //radlKey = component.find("searchByRADL").get("v.value"); // console.log('radlKey-----'+radlKey); if(radlKey != undefined || radlKey != null){ component.set("v.radlKey",radlKey); } else if(component.get("v.radlKey") != null){ radlKey = component.get("v.radlKey"); console.log('Radl Key Retain----++' +searchKey) } else if(radlKey == undefined || radlKey == '' || component.get("v.radlKey") == null || radlKey == null){ radlKey = 'None'; if(component.find("searchByRADL") == undefined){ radlKey = component.set("v.radlKey",'None'); } } console.log('searchKey'+searchKey+'radlKey'+radlKey); var isSelectedAccount = false; if((component.get("v.accountSelectedList") != '') && ((radlKey == 'None' && searchKey != '') || (radlKey != 'None' && searchKey == '') || (radlKey != 'None' && searchKey != '') || (radlKey == 'None' && searchKey == ''))){ console.log('Inside selected' + radlKey+searchKey); isSelectedAccount = true; } console.log('searchKey--------------'+searchKey+'component.get("v.searchString")'+component.get("v.searchString")); helper.getAllAccounts(component,page,searchKey,radlKey,false,isSelectedAccount); }, assignProgramToAccount:function(component,event,helper){ helper.associateProgramToAccounts(component,event,helper); helper.ProgramDetailCount(component,event,helper); }, addPgm : function(component){ document.getElementById("newProgramSectionId").style.display = "block"; document.getElementById("backGroundSectionId").style.display = "block"; }, getDone : function(component,event,helper){ document.getElementById("newProgramSectionId").style.display = "none"; document.getElementById("backGroundSectionId").style.display = "none"; component.set("v.addRadl",true); var searchKey; var page = 1; searchKey = (component.get("v.prevRadl") != null && component.get("v.addRadl") ? component.get("v.prevRadl") : ''); var isSelectedAccount = false; if(component.get("v.accountSelectedList") != null){ isSelectedAccount = true; } var radlKey = component.find("searchByRADL").get("v.value"); helper.getAllAccounts(component,page,searchKey,radlKey,false,isSelectedAccount); // component.set("v.clear",false); }, clearData : function(component,event,helper){ document.getElementById("newProgramSectionId").style.display = "none"; document.getElementById("backGroundSectionId").style.display = "none"; document.getElementById(component.get("v.prevRadl")).style=''; component.set("v.searchString",''); component.set("v.prevRadl",""); component.set("v.addRadl",false); var page = 1; var searchKey = (component.get("v.prevRadl") != null && component.get("v.addRadl") ? component.get("v.prevRadl") : ''); var isSelectedAccount = false; if(component.get("v.accountSelectedList") != null){ isSelectedAccount = true; } var radlKey = component.find("searchByRADL").get("v.value"); helper.getAllAccounts(component,page,searchKey,radlKey,false,isSelectedAccount); //component.set("v.clear",true); }, changeprogram:function(component,event,helper){ component.set("v.associatedProducts",null); component.set("v.accountSelectedList",null); component.set("v.isProgramChange",true); helper.helperchangeProgram(component,event,helper,false); component.set("v.progId",event.getParam("progId")); var searchKey = ''; var page = 1; var radlKey = 'None'; helper.getAllAccounts(component,page,searchKey,radlKey,false,false); }, onCheck:function(component,event,helper){ component.set("v.isProductSelected",false); helper.accountListTable(component,event,helper); }, reviewProgram:function(component,event,helper){ var progId = event.target.id; var header = component.find("headerSection"); console.log('progId'+progId); if (component.isValid()) { $A.createComponent( "c:Frontier_Review_MasterComponent", { progId : progId, dealerId : component.get("v.dealerId"), associatedProducts : component.get("v.associatedProducts"), selectedProducts : component.get("v.selectedProducts") }, function(newCmp){ var cmp = component.find("programBlock"); cmp.set("v.body",[]); cmp.set("v.body", newCmp); } );} }, handleSubmitAction : function(component,event,helper) { helper.handleSubmitProgramAction(component,event,helper); }, selectRadl:function(component,event,helper){ component.set("v.addRadl",false); if(component.get("v.prevRadl") != ''){ var radl = component.get("v.prevRadl"); document.getElementById(radl).style = 'color:grey'; } component.set("v.searchString",event.target.id); component.set("v.prevRadl",event.target.id); document.getElementById(event.target.id).style='color:black;font-weight:bold'; }, selectProduct : function(component,event){ if(component.get("v.dealerId") == null){ document.getElementById("newProgramSectionId1").style.display = "block"; document.getElementById("backGroundSectionId1").style.display = "block"; } else{ document.getElementById(component.get("v.dealerId")+"newProgramSectionId1").style.display = "block"; document.getElementById(component.get("v.dealerId")+"backGroundSectionId1").style.display = "block"; } }, addProduct : function(component,event){ component.find("productCode").set("v.value",'None'); component.find("ChargeType").set("v.value",'None'); component.set("v.productQty",null); component.set("v.triggeredAccountId",event.target.id); component.set("v.isProductSelected",false); if((component.get("v.dealerId")) == ''){ document.getElementById("newProgramSectionId1").style.display = "block"; document.getElementById("backGroundSectionId1").style.display = "block"; } else{ document.getElementById(component.get("v.dealerId")+"newProgramSectionId1").style.display = "block"; document.getElementById(component.get("v.dealerId")+"backGroundSectionId1").style.display = "block"; } }, productSelection : function(component,event,helper){ var prodcode = component.find("productCode"); var chargeType = component.find("ChargeType"); var Qty = component.find("Qty"); var isError = false; if (prodcode.get("v.value") == 'None') { isError = true; prodcode.set("v.errors", [{message:"Select the product code "}]); } else if (chargeType.get("v.value") == 'None') { isError = true; chargeType.set("v.errors", [{message:"Select the charge type "}]); } else if (Qty.get("v.value") == null) { isError = true; Qty.set("v.errors", [{message:"Select the Quantity"}]); } else { isError = false; prodcode.set("v.errors", null); chargeType.set("v.errors",null); Qty.set("v.errors",null); } if(!isError){ if(component.get("v.dealerId") == ''){ document.getElementById("newProgramSectionId1").style.display = "none"; document.getElementById("backGroundSectionId1").style.display = "none"; } else{ document.getElementById(component.get("v.dealerId")+"newProgramSectionId1").style.display = "none"; document.getElementById(component.get("v.dealerId")+"backGroundSectionId1").style.display = "none"; } var productWrap; var productPrice = component.find("Price").get("v.value") != 'None' ? component.find("Price").get("v.value") : null; var productCode = component.find("productCode").get("v.value") != 'None' ? component.find("productCode").get("v.value") : null; productWrap = '{"Qty":'+(component.get("v.productQty") != null ? component.get("v.productQty") : null)+',"ProductCode":"'+((productCode != null && productCode != 'None') ? productCode.split(':')[0]:null)+'","productId":"'+((productCode != null && productCode != 'None') ? productCode.split(':')[1]:null)+'","price":'+((productPrice != null && productPrice != 'None') ? productPrice.split(':')[0]:null)+',"chargeType":"'+(component.find("ChargeType").get("v.value") != 'None' ? component.find("ChargeType").get("v.value") : null)+'","accountId":null}'; console.log('Product Wrapppppppppppppp'+productWrap); component.set("v.AccountProductWrapper",JSON.parse(productWrap)); component.set("v.isProductSelected",true); helper.manipulateProduct(component,event,helper); } }, clearSelection : function(component,event,helper){ /* var prodLength = component.get("v.productList") || 1; var selectedProducts = component.get("v.selectedProducts"); var accountId = component.get("v.triggeredAccountId"); if(selectedProducts != null && selectedProducts.length > 0){ for(var i = 0; i < selectedProducts.length;i++){ if(accountId == selectedProducts[i].accountId){ selectedProducts.splice(i, prodLength.length); } } } component.set("v.selectedProducts",selectedProducts);*/ if(component.get("v.dealerId") == ''){ document.getElementById("newProgramSectionId1").style.display = "none"; document.getElementById("backGroundSectionId1").style.display = "none"; } else{ document.getElementById(component.get("v.dealerId")+"newProgramSectionId1").style.display = "none"; document.getElementById(component.get("v.dealerId")+"backGroundSectionId1").style.display = "none"; } }, removeAccount : function(component,event,helper){ console.log('event.target.id' +event.target.id); if(event.target.id != undefined){ helper.detachAccountFromProgram(component,event,helper,event.target.id); var searchKey = ''; var page = component.get("v.page") || 1; var radlKey = 'None'; var notProgramSaved = component.get("v.notProgramSaved"); if(notProgramSaved){ // helper.showPopUp(component,event,'Please Save'); } else{ helper.getAllAccounts(component,page,searchKey,radlKey,true,false); } helper.ProgramDetailCount(component,event,helper); } }, selectAllAccounts : function(component,event,helper){ var accountSelectedList = component.get("v.accountSelectedList"); var filteredAccountList = component.get("v.filteredAccountList"); var accountList; if(component.get("v.isAllSelected")){ console.log(component.get("v.tempAccountSelectedList")+component.get("v.tempAccountList")); if(component.get("v.tempAccountSelectedList") == '' || component.get("v.tempAccountSelectedList") == null){ if(accountSelectedList != null){ component.set("v.tempAccountSelectedList",accountSelectedList); } } if(component.get("v.tempAccountList") == '' || component.get("v.tempAccountList") == null){ accountList = component.get("v.accounts") component.set("v.tempAccountList",accountList); } var selectedList = []; // selectedList.push(accountSelectedList); if((accountSelectedList != null || accountSelectedList != undefined || accountSelectedList != '') && accountSelectedList.length > 0) { for(var j = 0;j<accountSelectedList.length;j++){ selectedList.push(accountSelectedList[j]); } } var currentIndex; if(filteredAccountList != null && filteredAccountList.length > 0){ for(var i = 0;i<filteredAccountList.length;i++){ currentIndex = null; if((accountSelectedList != null || accountSelectedList != undefined || accountSelectedList != '') && accountSelectedList.length > 0){ for(var j = 0;j<accountSelectedList.length;j++){ if (filteredAccountList[i].accId == accountSelectedList[j].accId) { currentIndex = i; continue; } } if(currentIndex == null){ filteredAccountList[i]['isSelected'] = true; selectedList.push(filteredAccountList[i]); } } else{ selectedList.push(filteredAccountList[i]); } } } if((selectedList != null || selectedList != undefined || selectList != '') && selectedList.length > 0){ //console.log('selectedList'+selectedList); //selectedList.push(accountSelectedList); component.set("v.accountSelectedList",selectedList); } component.set("v.accounts",filteredAccountList); if(accountSelectedList == undefined || accountSelectedList == null || accountSelectedList == ''){ component.set("v.accountSelectedList",filteredAccountList); } } else if(component.get("v.isAllSelected") == false){ accountSelectedList = component.get("v.tempAccountSelectedList"); accountList = component.get("v.tempAccountList"); component.set("v.accountSelectedList",accountSelectedList); if(accountList){ component.set("v.accounts",accountList); } console.log("accountIteration" + component.get("v.accounts")); } if(accountSelectedList != null){ helper.applyPaginationToTable(component,event,component.get("v.accountSelectedList"),false); } //helper.checkAllAccounts(component,event,helper); }, associateProductToAccount : function(component,event,helper){ selectedProducts = event.getParam("selectedProducts"); console.log('selectedProducts'+selectedProducts.length); if(selectedProducts != null && selectedProducts.length > 0){ component.set("v.selectedProducts",event.getParam("selectedProducts")); component.set("v.isProductSelected",false); } console.log("Event Handled"); }, showProgramScreen : function(component,event,helper){ var progId = event.getParam("progId"); $A.createComponent( "c:Frontier_ProgramPlanning", { progId : progId }, function(newCmp){ var cmp = component.find("programBlock"); cmp.set("v.body", []); cmp.set("v.body", newCmp); } ); } })<file_sep>/src/aura/Frontier_GrowerAccountDashboard_Master/Frontier_GrowerAccountDashboard_MasterController.js ({ doInit : function(component, event, helper) { var crop='Corn'; var season='SUMMER'; helper.getPicklistValues(component,event); helper.getchartdetails(component,event,crop,season); }, changeseasonCrop : function(component,event,helper){ var crop= component.find("cropDetailsGrower").get("v.value"); var season=component.find("sellingSeasonGrower").get("v.value"); helper.getchartdetails(component,event,crop,season); } })<file_sep>/src/aura/Frontier_Grower_Sales/Frontier_Grower_SalesHelper.js ({ loadChartData : function(component){ var data = { //labels: salesDetailJson.Labels, labels:["Corn", "Soy", "Cotton"], datasets: [ { label : "PY Sales", type : "horizontalBar", backgroundColor: "rgb(17, 135, 48)", hoverBackgroundColor: "rgba(50,90,100,1)", data: (component.get("v.CropData") == 'General' || component.get("v.CropData") == 'Corn'?[30000, 40000, 10000]:[40000, 30000, 20000]) // data: salesDetailJson.orderData }, { label : "Other Monsanto Brand/License sales", type : "horizontalBar", backgroundColor: "rgb(237, 168, 49)", hoverBackgroundColor: "rgba(140,85,100,1)", data: (component.get("v.CropData") == 'General' || component.get("v.CropData") == 'Corn'? [40000,10000,20000]:[30000,20000,10000]), //data: salesDetailJson.orderData }, { label : "Opportunity", type : "horizontalBar", backgroundColor: "rgb(201, 197, 191)", hoverBackgroundColor: "rgba(46,185,235,1)", data: (component.get("v.CropData") == 'General' || component.get("v.CropData") == 'Corn'?[1000,20000,1000]:[2000,10000,2000]) //data: salesDetailJson.orderData } ]}; var options = { responsive : true, curvature: 0.5, overlayBars: true, bezierCurve : false, animation:false, legend: { display:true, position:'bottom', labels: { fontColor: 'black' } }, scaleLabel:{ display:false }, scales: { xAxes: [{ gridLines: { display:false }, barPercentage : 25, stacked : true }], yAxes: [{ gridLines: { display:false, color: "#fff", }, display: true, barPercentage : 25, //barThickness : 20, ticks: { // minimum will be 0, unless there is a lower value. suggestedMin: 0, // minimum value will be 0. beginAtZero: true }, stacked : true }] } }; var el = document.getElementById("myChart"); var ctx = el.getContext("2d"); var myBarChart1 = new Chart(ctx, { type: 'horizontalBar', data: data, options: options }); window.onresize=function() { myBarChart1.resize(); }; } });<file_sep>/src/aura/Frontier_EventList/Frontier_EventListController.js ({ doInit : function(component, event, helper) { var page = component.get("v.page") || 1; var ispageChange = false; var isInitialize = true; component.set("v.usersInitialLoad",true); helper.getsEventObjectRecords(component,event,helper,page,ispageChange,isInitialize,''); }, VisitsList:function(component,event,helper){ var page=1; var ispageChange = false; var isInitialize = false; if(component.get("v.prevId") != ''){ component.set("v.SortBy"+component.get("v.prevId"),"onMouseOut"); } component.set("v.usersInitialLoad",false); helper.getsEventObjectRecords(component,event,helper,page,ispageChange,isInitialize,component.find('createdUser').get("v.value")); }, pageChange: function(component,event,helper) { var page = component.get("v.page") || 1; var direction = event.getParam("direction"); page = direction === "previous" ? (page - 1) : (page + 1); var ispageChange = true; var isInitialize = false; component.set("v.usersInitialLoad",false); helper.getsEventObjectRecords(component,event,helper,page,ispageChange,isInitialize,component.find('createdUser').get("v.value")); }, /* showIcon : function(component,event){ if(event.target.id != null && component.get("v.SortBy"+event.target.id) != "onClick"){ component.set("v.SortBy"+event.target.id,"onHover"); } }, hideIcon : function(component,event){ if(event.target.id != null && component.get("v.SortBy"+event.target.id) != "onClick"){ component.set("v.SortBy"+event.target.id,"onMouseOut"); } },*/ sortDirection : function(component,event,helper){ if(event.target.id != '' && component.get("v.prevId") != '' && component.get("v.prevId") != event.target.id){ component.set("v.SortBy"+component.get("v.prevId"),"onMouseOut"); } var page = component.get("v.page") || 1; console.log("Event Target"+event.target.id) if(event.target.id != ''){ component.set("v.SortBy"+event.target.id,"onClick"); } var ispageChange = false; var isInitialize = false; component.set("v.prevId",event.target.id); component.set("v.usersInitialLoad",false); helper.getsEventObjectRecords(component,event,helper,page,ispageChange,isInitialize,component.find('createdUser').get("v.value")); }, exportData:function(component,event,helper){ component.set("v.isExport",true); var page = component.get("v.page"); var ispageChange = true; var isInitialize = false; component.set("v.usersInitialLoad",false); helper.getsEventObjectRecords(component,event,helper,page,ispageChange,isInitialize,component.find('createdUser').get("v.value")); }, VisitFilterList:function(component,event,helper){ var page = component.get("v.page"); var ispageChange = true; var isInitialize = false; component.set("v.usersInitialLoad",false); helper.getsEventObjectRecords(component,event,helper,page,ispageChange,isInitialize,component.find('createdUser').get("v.value")); }, filerByCreatedUser : function(component,event,helper){ component.set("v.userId",component.find('createdUser').get("v.value")); console.log('createdUser=>'+component.find('createdUser').get("v.value")); component.set("v.createdByUserIds",component.find('createdUser').get("v.value")); var page = component.get("v.page") || 1; var ispageChange = true; var isInitialize = false; component.set("v.usersInitialLoad",false); helper.getsEventObjectRecords(component,event,helper,page,ispageChange,isInitialize,component.find('createdUser').get("v.value")); }, filerByTeam : function(component,event,helper){ component.set("v.territoryId",component.find('TeamSort').get("v.value")); console.log('createdUser=>'+component.find('TeamSort').get("v.value")); var page = component.get("v.page") || 1; var ispageChange = true; var isInitialize = false; component.set("v.usersInitialLoad",false); helper.getsEventObjectRecords(component,event,helper,page,ispageChange,isInitialize,component.find('createdUser').get("v.value")); }, clearSearchValues : function(component, event, helper) { component.find("sortByRADLList").set("v.value",""); component.find("createdUser").set("v.value",""); component.find("MonthSort").set("v.value",""); component.find("TeamSort").set("v.value",""); component.set("v.triggeredField",""); var page = component.get("v.page") || 1; var ispageChange = false; var isInitialize = false; helper.getsEventObjectRecords(component,event,helper,page,ispageChange,isInitialize,''); }, toggleShowLess: function(component, event){ console.log('Previous Id'+component.get("v.PrevIndex")); var prevId = (component.get("v.PrevIndex") != "" ? component.get("v.PrevIndex") : ""); var replaceText = ''; console.log('event.target.id' + event.target.id); if(event.target.id.includes("showeventId")){ replaceText='showeventId'; } else if(event.target.id.includes("lesseventId")){ replaceText='lesseventId'; } var prevtoggleId = prevId.replace(replaceText,''); var thisId = event.target.id; var thisElement = document.getElementById(thisId); var thisValue = thisElement.innerHTML; var prevElement = document.getElementById(prevId); var prevValue =""; if(prevElement !== null && prevElement !== '' && prevElement !== 'undefined'){ prevValue = prevElement.innerHTML; } var showmoreId = 'showmore'+event.target.id.replace(replaceText,''); var showmoreElement = document.getElementById(showmoreId); var showlessId = 'showless'+event.target.id.replace(replaceText,''); var showlessElement = document.getElementById(showlessId); console.log(thisValue); if(thisValue === "" || thisValue === 'undefined' || thisValue.toUpperCase() === 'SHOW MORE'){ if(prevId !== '' && prevId !== 'undefined' && prevValue.toUpperCase() === 'SHOW LESS'){ prevElement.innerHTML = 'Show More'; $A.util.removeClass(document.getElementById('showless'+prevtoggleId),'slds-show'); $A.util.addClass(document.getElementById('showless'+prevtoggleId),'slds-hide'); $A.util.removeClass(document.getElementById('showmore'+prevtoggleId),'slds-hide'); $A.util.addClass(document.getElementById('showmore'+prevtoggleId),'slds-show'); } thisElement.innerHTML = 'show Less'; document.getElementById(event.target.id.replace('showeventId','lesseventId')).innerHTML = 'Show Less'; $A.util.removeClass(showlessElement,'slds-hide'); $A.util.addClass(showlessElement,'slds-show'); $A.util.removeClass(showmoreElement,'slds-show'); $A.util.addClass(showmoreElement,'slds-hide'); } else{ thisElement.innerHTML = 'show More'; document.getElementById(event.target.id.replace('lesseventId','showeventId')).innerHTML = 'Show More'; $A.util.removeClass(showlessElement,'slds-show'); $A.util.addClass(showlessElement,'slds-hide'); $A.util.removeClass(showmoreElement,'slds-hide'); $A.util.addClass(showmoreElement,'slds-show'); } console.log('********************'+thisId); component.set("v.PrevIndex",thisId); console.log(component.get("v.PrevIndex")); }, });<file_sep>/src/aura/Frontier_AccountDetails/Frontier_AccountDetailsController.js ({ doInit : function(cmp, event,helper){ helper.getAccounts(cmp, event); }, showModal : function(){ document.getElementById("backGroundSectionId").style.display = "block"; document.getElementById("newAccountSectionId").style.display = "block"; var appEvent = $A.get("e.c:Frontier_ActivityRefresh"); appEvent.fire(); }, handleTouchPoints:function(cmp,event,helper){ helper.getAccounts(cmp,event); } });<file_sep>/src/aura/FR_CMP_RecentTouchPoints/FR_CMP_RecentTouchPointsController.js ({ doInit : function(component,event,helper){ helper.TouchPointRecord(component); }, handleTouchPoints : function(component,event,helper){ helper.TouchPointRecord(component); }, showModal : function(){ document.getElementById("backGroundSectionId").style.display = "block"; document.getElementById("newAccountSectionId").style.display = "block"; var appEvent = $A.get("e.c:Frontier_ActivityRefresh"); appEvent.fire(); }, navigateToReport : function () { var urlEvent = $A.get("e.force:navigateToURL"); urlEvent.setParams({ "url": $A.get("$Label.c.VisitReportUrl") }); urlEvent.fire(); } });<file_sep>/src/aura/Frontier_Pgm_Plang_Review/Frontier_Pgm_Plang_ReviewController.js ({ doInit : function(component, event, helper) { var page = component.get("v.page") || 1; component.set("v.isSubmitted",false); console.log('Get Programs on Do init'); helper.getAllProgram(component,event,helper, page); }, reviewPageChange: function(component,event,helper) { var cmpName = event.getParam("compName"); console.log('cmpName' + cmpName); if(cmpName == 'PgmPlngReview'){ var page; var direction; page = component.get("v.page") || 1; direction = event.getParam("direction"); page = direction === "previous" ? (page - 1) : (page + 1); console.log('page---' +page); helper.getAllProgram(component,event,helper,page); } }, backToProgramPlanning : function(component, event, helper) { var programEvent = $A.get("e.c:Frontier_ProgramPlanningEvent"); programEvent.setParams({"progId": component.get("v.progId") }).fire(); /* $A.createComponent( "c:Frontier_ProgramPlanning", { progId : component.get("v.progId") }, function(newCmp){ var cmp = component.find("programDetail"); cmp.set("v.body", []); cmp.set("v.body", newCmp); } );*/ }, submitProgramPlanning : function(component, event, helper) { console.log('Inside submit Controller'); helper.submitProgram(component,event,helper); }, /* handleSubmitAction : function(component,event,helper) { helper.handleSubmitProgramAction(component,event,helper); },*/ handleAccountLoad : function(component,event,helper){ var pgmId = event.getParam("programId"); component.set("v.loadProgramId",pgmId); } })<file_sep>/src/aura/Frontier_GrowerAccount_Program/Frontier_GrowerAccount_ProgramController.js ({ doInit : function(component, event, helper) { var acctDetails = component.get("v.growerAcc"), acctId = acctDetails.split(',')[0], acctProgramId = acctDetails.split(',')[3]; console.log('ProgramList=>'+JSON.stringify(component.get("v.growerAcc"))); var page = component.get("v.page") || 1; var ispageChange = false; var isInitialize = true; console.log("ispageChange out" + ispageChange); if (ispageChange == undefined){ console.log("ispageChange" + ispageChange); } component.set("v.usersInitialLoad",true); helper.navigateToProfileDetails(component, event); helper.listProgram(component,event,helper,page,ispageChange,isInitialize); if(acctId && acctProgramId){ helper.navigateToProgramDetail(component, event, acctId, acctProgramId); } }, refreshProgramList : function(component,event,helper){ console.log('Inside refresh list'); var page = component.get("v.page") || 1; var ispageChange = false; var isInitialize = true; console.log("ispageChange out" + ispageChange); if (ispageChange == undefined){ console.log("ispageChange" + ispageChange); } component.set("v.usersInitialLoad",true); helper.navigateToProfileDetails(component, event); helper.listProgram(component,event,helper,page,ispageChange,isInitialize); }, programPageChange: function(component,event,helper) { var cmpName = event.getParam("compName"); console.log('cmpName' + cmpName); if(cmpName == 'Programs'){ console.log('Page' + component.get("v.page")); var page = component.get("v.page") || 1; var direction = event.getParam("direction"); console.log('direction' + direction); page = direction === "previous" ? (page - 1) : (page + 1); var ispageChange = true; var isInitialize = false; //component.set("v.usersInitialLoad",false); console.log('Page' + page); helper.listProgram(component,event,helper,page,ispageChange,isInitialize); } }, sortDirection : function(component,event,helper){ if(event.currentTarget.id != '' && component.get("v.prevId") != '' && component.get("v.prevId") != event.currentTarget.id){ component.set("v.SortBy"+component.get("v.prevId"),"onMouseOut"); } var page = component.get("v.page") || 1; console.log("Event Target"+event.target.id) console.log("Current target" + event.currentTarget.id); if(event.currentTarget.id != ''){ component.set("v.SortBy"+event.currentTarget.id,"onClick"); } var ispageChange = false; var isInitialize = false; component.set("v.prevId",event.currentTarget.id); component.set("v.usersInitialLoad",false); helper.listProgram(component,event,helper,page,ispageChange,isInitialize); }, pgmEventNavigation: function(component,event,helper){ helper.navigateToProgramDetail(component, event); }, cancelProgram : function(component,event,helper){ //console.log('Inside cancel' + document.getElementById("newCancel").style.display); console.log('Inside cancel'); component.set("v.programId" , event.currentTarget.id); console.log('cancel' + component.get("v.programId")); document.getElementById("newCancel").style.display = "block"; document.getElementById("cancelbackgrnd").style.display = "block"; // var cancelEvent = $A.get("e.c:Frontier_CancelEvent"); //cancelEvent.fire(); //document.getElementById("newCancel").style.display = "block"; //document.getElementById("cancelbackgrnd").style.display = "block"; /* helper.cancelPgm(component,event); var page = component.get("v.page") || 1; var ispageChange = false; var isInitialize = true; console.log("ispageChange out" + ispageChange); if (ispageChange == undefined){ console.log("ispageChange" + ispageChange); } component.set("v.usersInitialLoad",true); helper.listProgram(component,event,helper,page,ispageChange,isInitialize); */ }, showModalBox : function(component,event,helper){ document.getElementById("newCancel").style.display = "none"; document.getElementById("cancelbackgrnd").style.display = "none"; component.find("comments").set("v.value", ' '); }, cancelPgmReason : function(component,event,helper){ document.getElementById("newCancel").style.display = "none"; document.getElementById("cancelbackgrnd").style.display = "none"; var reason = component.find("comments").get("v.value"); console.log("reason" + reason); //component.find("comments").set("v.value", ' '); helper.cancelPgm(component,event,reason); var page = component.get("v.page") || 1; var ispageChange = false; var isInitialize = true; console.log("ispageChange out" + ispageChange); if (ispageChange == undefined){ console.log("ispageChange" + ispageChange); } component.set("v.usersInitialLoad",true); helper.listProgram(component,event,helper,page,ispageChange,isInitialize); }, completePgm : function(component,event,helper){ helper.completePgm(component,event); /* var reason = ''; console.log('Inside complete ' + reason); helper.cancelPgm(component,event,reason); var page = component.get("v.page") || 1; var ispageChange = false; var isInitialize = true; console.log("ispageChange out" + ispageChange); if (ispageChange == undefined){ console.log("ispageChange" + ispageChange); } component.set("v.usersInitialLoad",true); helper.listProgram(component,event,helper,page,ispageChange,isInitialize); */ } })<file_sep>/src/aura/Frontier_Gen_Communication/Frontier_Gen_CommunicationController.js ({ doInit : function(component, event, helper) { helper.findCommunication(component, event, helper, true); } })<file_sep>/src/aura/Frontier_GrowerAccountByRadlChart/Frontier_GrowerAccountByRadlChartHelper.js ({ loadAccDashData : function(component, event){ console.log('-----Acccount coverage chart-----' ); var action = component.get("c.getAccountRadl"); action.setParams({ crop : component.get("v.crop"), season : component.get("v.season"), accType : 'Customer' }); var developAccCount = []; var acqAccCount = []; var retainAccCount = []; var lightAccCount = []; var accCoverageLbl = []; action.setCallback(this, function(response) { if (response.getState() === "SUCCESS") { console.log('Success'); var accCoverageRADL = (JSON.parse(response.getReturnValue())); accCoverageLbl= accCoverageRADL.accRADLLblSet; component.set("v.accCoverageLbl",accCoverageLbl); console.log('type' + component.get("v.accCoverageLbl")); //console.log('check value' + accCoverageRADL.accountRadlMap.hasOwnProperty('Retain')); if(!accCoverageRADL.accountRadlMap.hasOwnProperty('Develop')){ console.log('Inside Develop'); developAccCount.push(0); } if(!accCoverageRADL.accountRadlMap.hasOwnProperty('Acquire')){ console.log('Inside Retain'); acqAccCount.push(0); } if(!accCoverageRADL.accountRadlMap.hasOwnProperty('Retain')){ console.log('Inside Retain'); retainAccCount.push(0); console.log('Inside retain 0' + retainAccCount); } if(!accCoverageRADL.accountRadlMap.hasOwnProperty('Light Touch')){ console.log('Inside Retain'); lightAccCount.push(0); } for(var key in accCoverageRADL.accountRadlMap){ console.log('key' + key ); if(key == 'Develop'){ developAccCount.push(accCoverageRADL.accountRadlMap[key]); console.log('Develop1'+ developAccCount); } if(key == 'Acquire'){ acqAccCount.push(accCoverageRADL.accountRadlMap[key]); } if(key == 'Retain'){ retainAccCount.push(accCoverageRADL.accountRadlMap[key]); console.log('Inside retain' + retainAccCount); } if(key == 'Light Touch'){ lightAccCount.push(accCoverageRADL.accountRadlMap[key]); } } if(!accCoverageRADL.accPgmRadlMap.hasOwnProperty('Develop')){ console.log('Inside Develop'); developAccCount.push(0); } if(!accCoverageRADL.accPgmRadlMap.hasOwnProperty('Acquire')){ console.log('Inside Retain'); acqAccCount.push(0); } if(!accCoverageRADL.accPgmRadlMap.hasOwnProperty('Retain')){ console.log('Inside Retain'); retainAccCount.push(0); } if(!accCoverageRADL.accPgmRadlMap.hasOwnProperty('Light Touch')){ console.log('Inside Retain'); lightAccCount.push(0); } for(var key in accCoverageRADL.accPgmRadlMap){ console.log('key' + key ); if(key == 'Develop'){ developAccCount.push(accCoverageRADL.accPgmRadlMap[key]); console.log('Develop2'+ developAccCount); } if(key == 'Acquire'){ acqAccCount.push(accCoverageRADL.accPgmRadlMap[key]); } if(key == 'Retain'){ retainAccCount.push(accCoverageRADL.accPgmRadlMap[key]); } if(key == 'Light Touch'){ lightAccCount.push(accCoverageRADL.accPgmRadlMap[key]); } } if(!accCoverageRADL.accTouchRadlMap.hasOwnProperty('Develop')){ console.log('Inside Develop'); developAccCount.push(0); } if(!accCoverageRADL.accTouchRadlMap.hasOwnProperty('Acquire')){ console.log('Inside Retain'); acqAccCount.push(0); } if(!accCoverageRADL.accTouchRadlMap.hasOwnProperty('Retain')){ console.log('Inside Retain'); retainAccCount.push(0); } if(!accCoverageRADL.accTouchRadlMap.hasOwnProperty('Light Touch')){ console.log('Inside Retain'); lightAccCount.push(0); } for(var key in accCoverageRADL.accTouchRadlMap){ console.log('key' + key ); if(key == 'Develop'){ developAccCount.push(accCoverageRADL.accTouchRadlMap[key]); console.log('Develop3'+ developAccCount); } if(key == 'Acquire'){ acqAccCount.push(accCoverageRADL.accTouchRadlMap[key]); } if(key == 'Retain'){ retainAccCount.push(accCoverageRADL.accTouchRadlMap[key]); } if(key == 'Light Touch'){ lightAccCount.push(accCoverageRADL.accTouchRadlMap[key]); } } if(!accCoverageRADL.accRadlCoverMap.hasOwnProperty('Develop')){ console.log('Inside Develop'); developAccCount.push(0); } if(!accCoverageRADL.accRadlCoverMap.hasOwnProperty('Acquire')){ console.log('Inside Retain'); acqAccCount.push(0); } if(!accCoverageRADL.accRadlCoverMap.hasOwnProperty('Retain')){ console.log('Inside Retain'); retainAccCount.push(0); } if(!accCoverageRADL.accRadlCoverMap.hasOwnProperty('Light Touch')){ console.log('Inside Retain'); lightAccCount.push(0); } for(var key in accCoverageRADL.accRadlCoverMap){ console.log('key' + key ); if(key == 'Develop'){ developAccCount.push(accCoverageRADL.accRadlCoverMap[key]); console.log('Develop3'+ developAccCount); } if(key == 'Acquire'){ acqAccCount.push(accCoverageRADL.accRadlCoverMap[key]); } if(key == 'Retain'){ retainAccCount.push(accCoverageRADL.accRadlCoverMap[key]); } if(key == 'Light Touch'){ lightAccCount.push(accCoverageRADL.accRadlCoverMap[key]); } } if(!accCoverageRADL.TouchpointcountRadlMap.hasOwnProperty('Develop')){ console.log('Inside Develop'); developAccCount.push(0); } if(!accCoverageRADL.TouchpointcountRadlMap.hasOwnProperty('Acquire')){ console.log('Inside Retain'); acqAccCount.push(0); } if(!accCoverageRADL.TouchpointcountRadlMap.hasOwnProperty('Retain')){ console.log('Inside Retain'); retainAccCount.push(0); } if(!accCoverageRADL.TouchpointcountRadlMap.hasOwnProperty('Light Touch')){ console.log('Inside Retain'); lightAccCount.push(0); } for(var key in accCoverageRADL.TouchpointcountRadlMap){ console.log('key' + key ); if(key == 'Develop'){ developAccCount.push(accCoverageRADL.TouchpointcountRadlMap[key]); console.log('Develop4'+ developAccCount); } if(key == 'Acquire'){ acqAccCount.push(accCoverageRADL.TouchpointcountRadlMap[key]); } if(key == 'Retain'){ retainAccCount.push(accCoverageRADL.TouchpointcountRadlMap[key]); } if(key == 'Light Touch'){ lightAccCount.push(accCoverageRADL.TouchpointcountRadlMap[key]); } } if(!accCoverageRADL.avgVisitRadlMap.hasOwnProperty('Develop')){ console.log('Inside Develop'); developAccCount.push(0); } if(!accCoverageRADL.avgVisitRadlMap.hasOwnProperty('Acquire')){ console.log('Inside Retain'); acqAccCount.push(0); } if(!accCoverageRADL.avgVisitRadlMap.hasOwnProperty('Retain')){ console.log('Inside Retain'); retainAccCount.push(0); } if(!accCoverageRADL.avgVisitRadlMap.hasOwnProperty('Light Touch')){ console.log('Inside Retain'); lightAccCount.push(0); } for(var key in accCoverageRADL.avgVisitRadlMap){ console.log('key' + key ); if(key == 'Develop'){ developAccCount.push(accCoverageRADL.avgVisitRadlMap[key]); console.log('Develop6'+ developAccCount); } if(key == 'Acquire'){ acqAccCount.push(accCoverageRADL.avgVisitRadlMap[key]); } if(key == 'Retain'){ retainAccCount.push(accCoverageRADL.avgVisitRadlMap[key]); } if(key == 'Light Touch'){ lightAccCount.push(accCoverageRADL.avgVisitRadlMap[key]); } } component.set("v.dtypecount",developAccCount); component.set("v.acqtypecount",acqAccCount); component.set("v.rtypecount",retainAccCount); component.set("v.ltypecount",lightAccCount); /* console.log('Dev' + component.get("v.dtypecount")); console.log('Acq' + component.get("v.acqtypecount")); console.log('Ret' + component.get("v.rtypecount")); console.log('Light' + component.get("v.ltypecount"));*/ } else if (response.getState() === "ERROR") { console.log('Errors', response.getError()); } var data = { //labels: salesDetailJson.Labels, //labels:["Total","Visit"], labels:component.get("v.accCoverageLbl"), datasets: [ { label : "Develop", backgroundColor: "rgb(17, 135, 48)", hoverBackgroundColor: "rgba(50,90,100,1)", data:component.get("v.dtypecount") // data: salesDetailJson.orderData }, { label : "Acquire", backgroundColor: "rgb(237, 168, 49)", hoverBackgroundColor: "rgba(140,85,100,1)", //data: [acquire] data:component.get("v.acqtypecount") //data: salesDetailJson.orderData }, { label : "Retain", backgroundColor: "rgb(252, 208, 171)", hoverBackgroundColor: "rgba(46,185,235,1)", data:component.get("v.rtypecount") //data: salesDetailJson.orderData }, { label : "Light Touch", backgroundColor: "rgb(127, 205, 239)", hoverBackgroundColor: "rgba(46,185,235,1)", data:component.get("v.ltypecount") } ]}; var options = { responsive : true, curvature: 0.5, overlayBars: true, bezierCurve : false, legend: { display:true, position:'bottom', labels: { fontColor: 'black' } }, scaleLabel:{ display:false }, tooltips: { enabled:true, }, scales: { xAxes: [{ gridLines: { display:false }, barPercentage : 1.5, categoryPercentage :0.5, stacked : true }], yAxes: [{ gridLines: { display:true }, display: true, //categoryPercentage :0.4, //barPercentage : 1.0, //barThickness : 20, ticks: { suggestedMin: 0, // minimum value will be 0. beginAtZero: true }, stacked : true }, ] } }; var el = document.getElementById("myChartGroweraccountRADL"); var ctx = el.getContext("2d"); ctx.canvas.height=400; ctx.canvas.width=1300; var myBarChart1 = new Chart(ctx, { type: 'bar', data: data, options: options }); window.onresize=function() { myBarChart1.resize(); }; }); $A.enqueueAction(action); } });<file_sep>/src/aura/Frontier_Account_AddressInformation/Frontier_Account_AddressInformationController.js ({ doInit : function(component, event, helper) { helper.getAddressdetails(component, event); } })<file_sep>/src/aura/Frontier_Activities_List/Frontier_Activities_ListController.js ({ doInit : function(component,event,helper) { var formFactor = $A.get("$Browser.formFactor"); if(formFactor === 'PHONE'){ component.set("v.isMobileDevice",true); } else { component.set("v.isMobileDevice",false); } var productID = component.get("v.childProductId"); console.log(productID); console.log('doInit'); var page = component.get("v.page") || 1; var flag = false; helper.getsObjectRecords(component,event,page,productID,flag); }, pageChange: function(component,event,helper) { var page = component.get("v.page") || 1; var productID = component.get("v.childProductId"); var direction = event.getParam("direction"); var flag = true; page = direction === "previous" ? (page - 1) : (page + 1); component.set("v.collapsibleId",''); helper.getsObjectRecords(component,event,page,productID,flag); }, showModalBox : function(component){ document.getElementById("searchText").value = ''; /*Commented By Priyanka document.getElementById("searchContact").value = ''; */ console.log('inside showModal'); component.find("searchType").set("v.value","None"); component.find("fromDate").set("v.value",""); component.find("toDate").set("v.value",""); document.getElementById("backGroundSectionId").style.display = "none"; document.getElementById("newAccountSectionId").style.display = "none"; }, searchVisitsBy:function(component,event,helper){ var productID = component.get("v.childProductId"); var flag = true; console.log(productID); console.log('searchVisits'); var page = 1; component.set("v.collapsibleId",''); helper.getsObjectRecords(component,event,page, productID,flag); }, toggleEvent: function(component, event){ console.log('Previous Id'+component.get("v.PrevIndex")); var prevId = (component.get("v.PrevIndex") != "" ? component.get("v.PrevIndex") : ""); var replaceText = ''; if(event.target.id.includes("showeventId")){ replaceText='showeventId'; } else if(event.target.id.includes("lesseventId")){ replaceText='lesseventId'; } var prevtoggleId = prevId.replace(replaceText,''); var thisId = event.target.id; var thisElement = document.getElementById(thisId); var thisValue = thisElement.innerHTML; var prevElement = document.getElementById(prevId); var prevValue =""; if(prevElement !== null && prevElement !== '' && prevElement !== 'undefined'){ prevValue = prevElement.innerHTML; } var showmoreId = 'showmore'+event.target.id.replace(replaceText,''); var showmoreElement = document.getElementById(showmoreId); var showlessId = 'showless'+event.target.id.replace(replaceText,''); var showlessElement = document.getElementById(showlessId); console.log(thisValue); if(thisValue === "" || thisValue === 'undefined' || thisValue.toUpperCase() === 'SHOW MORE'){ if(prevId !== '' && prevId !== 'undefined' && prevValue.toUpperCase() === 'SHOW LESS'){ prevElement.innerHTML = 'Show More'; $A.util.removeClass(document.getElementById('showless'+prevtoggleId),'slds-show'); $A.util.addClass(document.getElementById('showless'+prevtoggleId),'slds-hide'); $A.util.removeClass(document.getElementById('showmore'+prevtoggleId),'slds-hide'); $A.util.addClass(document.getElementById('showmore'+prevtoggleId),'slds-show'); } thisElement.innerHTML = 'show Less'; document.getElementById(event.target.id.replace('showeventId','lesseventId')).innerHTML = 'Show Less'; $A.util.removeClass(showlessElement,'slds-hide'); $A.util.addClass(showlessElement,'slds-show'); $A.util.removeClass(showmoreElement,'slds-show'); $A.util.addClass(showmoreElement,'slds-hide'); } else{ thisElement.innerHTML = 'show More'; document.getElementById(event.target.id.replace('lesseventId','showeventId')).innerHTML = 'Show More'; $A.util.removeClass(showlessElement,'slds-show'); $A.util.addClass(showlessElement,'slds-hide'); $A.util.removeClass(showmoreElement,'slds-hide'); $A.util.addClass(showmoreElement,'slds-show'); } console.log('********************'+thisId); component.set("v.PrevIndex",thisId); console.log(component.get("v.PrevIndex")); }, //Chartih added for handle activies on Modal handleTouchPoints:function(component, event, helper){ var productID = component.get("v.childProductId"); console.log(productID); console.log('doInit'); var page = component.get("v.page") || 1; var flag = false; helper.getsObjectRecords(component,event,page,productID,flag); }, clearSearchValues : function(component, event, helper) { document.getElementById("searchText").value = ''; component.find("searchType").set("v.value","None"); component.find("fromDate").set("v.value",""); component.find("toDate").set("v.value",""); var productID = component.get("v.childProductId"); var page = 1; var flag = false; helper.getsObjectRecords(component,event,page,productID,flag); } });<file_sep>/src/aura/Frontier_ManagerDashboard/Frontier_ManagerDashboardController.js ({ loadChartDetail : function(component, event, helper){ helper.loadChart(component,event); }, })<file_sep>/src/aura/Frontier_VisitReport/Frontier_VisitReportController.js ({ doInit : function (component, event, helper) { helper.navigateToReport(component,event,helper); } })<file_sep>/src/aura/Frontier_Touchpoint_Planning_Calender/Frontier_Touchpoint_Planning_CalenderRenderer.js ({ unrender : function(){ this.superUnrender(); /* var ids = ''+'/'+'0012C00000AsKGzQAN'+','+'a0g2C000000UynxQAC'+'/'; var evt = $A.get("e.force:navigateToComponent"); evt.setParams({ componentDef : "c:Frontier_GrowerAccount_UpdateTouchPoint", componentAttributes: { "clickdate":'2017-05-10', "newUpdateStatus":'new', "growerAcc": ids, "isFromCalendar":true, "isReadOnly":false } }); evt.fire();*/ } // Your renderer method overrides go here })<file_sep>/src/aura/Frontier_GrowerAccountTracking_Table/Frontier_GrowerAccountTracking_TableController.js ({ doInit : function(component, event, helper) { var productID = component.get("v.childProductId"); var page = component.get("v.page") || 1; console.log("checking"+productID); helper.getsObjectRecords(component,page, productID); }, pageChange: function(component, event, helper) { var page = component.get("v.page") || 1; var productID = component.get("v.childProductId"); var direction = event.getParam("direction"); page = direction === "previous" ? (page - 1) : (page + 1); helper.getsObjectRecords(component,page, productID); }, navigatetoAccount: function(component, event){ console.log("Hello=>"+event.target.id); var accId = event.target.id; var cmpEvent = component.getEvent("AccountNavigationEvent"); cmpEvent.setParams({"accId" : accId.split(',')[0],"sapId" :accId.split(',')[1]}); cmpEvent.fire(); console.log("Finished"); } });<file_sep>/src/aura/Frontier_GrowerAccountTracking_Table/Frontier_GrowerAccountTracking_TableHelper.js ({ getsObjectRecords : function(component,page1, productID) { var page = page1 || 1; console.log('page' + page); var action = component.get("c.getGrowerRecords"); var fields = component.get("v.fields"); var sortFieldName = ""; console.log('sortFieldName' + component.get("v.object")); console.log('sortFieldName' + component.get("v.pageSize")); action.setParams({ ObjectName : component.get("v.object"), fieldstoget : fields.join(), pageNumber : page, pageSize : component.get("v.pageSize"), ProductId : productID }); action.setCallback(this,function(response){ var state = response.getState(); console.log("State" + state); if(state === 'SUCCESS'){ var retRecords=[]; console.log("State" + state); console.log('retRecords=>'+ response.getReturnValue()); retRecords = response.getReturnValue(); //component.set("v.accountrec", retRecords); component.set("v.accountrec", retRecords); }else if (state === "ERROR") { console.log('Error'); } }); $A.enqueueAction(action); } });<file_sep>/src/aura/Frontier_GrowerAccountDashboard_Master/Frontier_GrowerAccountDashboard_MasterHelper.js ({ getPicklistValues : function(component,event) { var action = component.get("c.getMyProgramsChart"); var programId = null; var dealerId = null; action.setParams({ programId :programId, dealerId : dealerId }); var inputsel = component.find("sellingSeasonGrower"); var cropsel = component.find("cropDetailsGrower"); var opts=[]; var crops=[]; action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ var retResponse = (JSON.parse(response.getReturnValue())); console.log("retResponse"+ JSON.stringify(retResponse)); for(var i=0;i< retResponse.sellingSeasontypes.length;i++){ opts.push({"class": "optionClass", label: retResponse.sellingSeasontypes[i], value:retResponse.sellingSeasontypes[i]}); } for(var i=0;i< retResponse.croptypes.length;i++){ crops.push({"class": "optionClass", label: retResponse.croptypes[i], value:retResponse.croptypes[i]}); } inputsel.set("v.options",opts); cropsel.set("v.options",crops); } }); $A.enqueueAction(action); }, getchartdetails : function(component,event,crop,season){ $A.createComponent( "c:Frontier_GrowerAccountByRadlChart", { "crop" : crop, "season" : season }, function(newCmp){ var cmp = component.find("accountCoverageRADLGrower"); cmp.set("v.body", []); cmp.set("v.body", newCmp); } ); $A.createComponent( "c:Frontier_GrowerTouchpointsbyMonth_Chart", { "crop" : crop, "season" : season }, function(newCmp){ var cmp = component.find("touchpointByMonthChartGrower"); cmp.set("v.body", []); cmp.set("v.body", newCmp); } ); $A.createComponent( "c:Frontier_GrowerTouchpointbyTypeChart", { "crop" : crop, "season" : season }, function(newCmp){ var cmp = component.find("touchpointByTypeChartGrower"); cmp.set("v.body", []); cmp.set("v.body", newCmp); } ); $A.createComponent( "c:Frontier_GrowerAccountDashboard_GrowerList", { "crop" : crop, "season" : season }, function(newCmp){ var cmp = component.find("growerList"); cmp.set("v.body", []); cmp.set("v.body", newCmp); } ); } })<file_sep>/src/aura/Frontier_TouchpointsbyMonth_Chart/Frontier_TouchpointsbyMonth_ChartHelper.js ({ getpicklistvalues:function(component, event){ var action = component.get("c.getTouchpointTypeValues"); var inputsel = component.find("touchpointbytype"); var opts=[]; var results = []; action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ var retResponse = response.getReturnValue(); //results.push(retResponse); for(var i=0;i< retResponse.length;i++){ opts.push({"class": "optionClass", label: retResponse[i], value:retResponse[i]}); } inputsel.set("v.options",opts); //cropsel.set("v.options",crops); } }); $A.enqueueAction(action); }, loadTouchpoint : function(component, event,touchpointType){ var season = component.get("v.season"); var action = component.get("c.getTouchpointbyMonth"); action.setParams({ touchpointType : touchpointType, season : component.get("v.season"), accType : component.get("v.accType") }); var months = []; var develop = []; var acquire = []; var retain = []; var light = []; var developcount = []; var acquirecount = []; var retaincount = []; var lightcount = []; var checkNull = false; action.setCallback(this, function(response) { if (response.getState() === "SUCCESS") { var touchpointByMonth = (JSON.parse(response.getReturnValue())); for(var key in touchpointByMonth.touchpermontcount){ months.push(key); for(var key1 in touchpointByMonth.touchpermontcount[key]){ if(!touchpointByMonth.touchpermontcount[key][key1].hasOwnProperty('Develop')){ developcount.push(0); checkNull = true; } if(!touchpointByMonth.touchpermontcount[key][key1].hasOwnProperty('Acquire')){ acquirecount.push(0); checkNull = true; } if(!touchpointByMonth.touchpermontcount[key][key1].hasOwnProperty('Retain')){ retaincount.push(0); checkNull = true; } if(!touchpointByMonth.touchpermontcount[key][key1].hasOwnProperty('Light Touch')){ lightcount.push(0); checkNull = true; } for(var key2 in touchpointByMonth.touchpermontcount[key][key1]){ if(key2 == 'Develop'){ develop.push(key2); developcount.push(touchpointByMonth.touchpermontcount[key][key1][key2]); component.set("v.developcount",developcount); checkNull = false; } if(key2 == 'Acquire'){ acquire.push(key2); acquirecount.push(touchpointByMonth.touchpermontcount[key][key1][key2]); checkNull = false; } if(key2 == 'Retain'){ retain.push(key2); retaincount.push(touchpointByMonth.touchpermontcount[key][key1][key2]); checkNull = false; } if(key2 == 'Light Touch'){ light.push(key2); lightcount.push(touchpointByMonth.touchpermontcount[key][key1][key2]); checkNull = false; } } } } component.set("v.develop" , develop); component.set("v.developcount" , developcount); component.set("v.acquire" , acquire); component.set("v.acquirecount" , acquirecount); component.set("v.retain" , retain); component.set("v.retaincount" , retaincount); component.set("v.light" , light); component.set("v.lightcount" , lightcount); } else if (response.getState() === "ERROR") { console.log('Errors', response.getError()); } var data = { labels:months, datasets: [ { label : "Develop", type : "bar", backgroundColor: "rgb(17, 135, 48)", hoverBackgroundColor: "rgba(50,90,100,1)", borderWidth: 1, data:component.get("v.developcount") }, { label : "Acquire", type : "bar", backgroundColor: "rgb(237, 168, 49)", hoverBackgroundColor: "rgba(140,85,100,1)", borderWidth: 1, data:component.get("v.acquirecount") }, { label : "Retain", type : "bar", backgroundColor: "rgb(252, 208, 171)", hoverBackgroundColor: "rgba(46,185,235,1)", borderWidth: 1, data:component.get("v.retaincount") }, { label : "Light Touch", type : "bar", backgroundColor: "rgb(127, 205, 239)", hoverBackgroundColor: "rgba(46,185,235,1)", borderWidth: 1, data:component.get("v.lightcount") } ]}; var options = { responsive : true, curvature: 0.5, overlayBars: true, bezierCurve : false, legend:{ display:false }, legend: { display:true, position:'bottom', labels: { fontColor: 'black' } }, scaleLabel:{ display:false }, tooltips: { enabled:true, }, scales: { xAxes: [{ gridLines: { display:false }, categoryPercentage :0.1, barPercentage : 0.5, stacked : true }], yAxes: [{ gridLines: { display:true, color: "#ccc", }, display: true, //categoryPercentage :0.4, //barPercentage : 0.5, //barThickness : 20, ticks: { // minimum will be 0, unless there is a lower value. suggestedMin: 0, // minimum value will be 0. beginAtZero: true }, stacked : true }] } }; var el = document.getElementById("myCharttouchpoint"); var ctx = el.getContext("2d"); ctx.canvas.height=400; ctx.canvas.width=1300; var myBarChart1 = new Chart(ctx, { type: 'bar', data: data, options: options }); //= touchpointByMonth.touchpermontcount.length; var touchpointMapLength=Object.keys(touchpointByMonth.touchpermontcount).length; if(touchpointMapLength > 0){ document.getElementById("myCharttouchpoint").style.display = "block"; } else{ document.getElementById("myCharttouchpoint").style.display = "none"; } }); $A.enqueueAction(action); } });<file_sep>/src/aura/Frontier_RadlCoveragechart/Frontier_RadlCoveragechartHelper.js ({ loadAccDashData : function(component, event){ var action = component.get("c.getRadlCoverage"); action.setParams({ //crop : component.get("v.crop"), season : component.get("v.season"), accType : component.get("v.accType") }); var developAccCount = []; var acqAccCount = []; var retainAccCount = []; var lightAccCount = []; var accCoverageLbl = []; action.setCallback(this, function(response) { if (response.getState() === "SUCCESS") { var accCoverageRADL = (JSON.parse(response.getReturnValue())); //accCoverageLbl= accCoverageRADL.accRADLLblSet; //component.set("v.accCoverageLbl",accCoverageLbl); if(component.get("v.accType") == 'Partner'){ if(!accCoverageRADL.accRadldealerOppMap.hasOwnProperty('Develop')){ developAccCount.push(0); } if(!accCoverageRADL.accRadldealerOppMap.hasOwnProperty('Acquire')){ acqAccCount.push(0); } if(!accCoverageRADL.accRadldealerOppMap.hasOwnProperty('Retain')){ retainAccCount.push(0); } if(!accCoverageRADL.accRadldealerOppMap.hasOwnProperty('Light Touch')){ lightAccCount.push(0); } for(var key in accCoverageRADL.accRadldealerOppMap){ if(key == 'Develop'){ developAccCount.push(accCoverageRADL.accRadldealerOppMap[key]); } if(key == 'Acquire'){ acqAccCount.push(accCoverageRADL.accRadldealerOppMap[key]); } if(key == 'Retain'){ retainAccCount.push(accCoverageRADL.accRadldealerOppMap[key]); } if(key == 'Light Touch'){ lightAccCount.push(accCoverageRADL.accRadldealerOppMap[key]); } } } else if(component.get("v.accType") == 'Customer'){ if(!accCoverageRADL.accRadlgrowOppMap.hasOwnProperty('Develop')){ developAccCount.push(0); } if(!accCoverageRADL.accRadlgrowOppMap.hasOwnProperty('Acquire')){ acqAccCount.push(0); } if(!accCoverageRADL.accRadlgrowOppMap.hasOwnProperty('Retain')){ retainAccCount.push(0); } if(!accCoverageRADL.accRadlgrowOppMap.hasOwnProperty('Light Touch')){ lightAccCount.push(0); } for(var key in accCoverageRADL.accRadlgrowOppMap){ if(key == 'Develop'){ developAccCount.push(accCoverageRADL.accRadlgrowOppMap[key]); } if(key == 'Acquire'){ acqAccCount.push(accCoverageRADL.accRadlgrowOppMap[key]); } if(key == 'Retain'){ retainAccCount.push(accCoverageRADL.accRadlgrowOppMap[key]); } if(key == 'Light Touch'){ lightAccCount.push(accCoverageRADL.accRadlgrowOppMap[key]); } } } else if(component.get("v.accType") == 'All Accounts'){ if(!accCoverageRADL.allaccRadlOppMap.hasOwnProperty('Develop')){ developAccCount.push(0); } if(!accCoverageRADL.allaccRadlOppMap.hasOwnProperty('Acquire')){ acqAccCount.push(0); } if(!accCoverageRADL.allaccRadlOppMap.hasOwnProperty('Retain')){ retainAccCount.push(0); } if(!accCoverageRADL.allaccRadlOppMap.hasOwnProperty('Light Touch')){ lightAccCount.push(0); } for(var key in accCoverageRADL.allaccRadlOppMap){ if(key == 'Develop'){ developAccCount.push(accCoverageRADL.allaccRadlOppMap[key]); } if(key == 'Acquire'){ acqAccCount.push(accCoverageRADL.allaccRadlOppMap[key]); } if(key == 'Retain'){ retainAccCount.push(accCoverageRADL.allaccRadlOppMap[key]); } if(key == 'Light Touch'){ lightAccCount.push(accCoverageRADL.allaccRadlOppMap[key]); } } } } else if (response.getState() === "ERROR") { console.log('Errors', response.getError()); } var data = { //labels: salesDetailJson.Labels, //labels:["Total","Visit"], labels:["RADL Coverage"], datasets: [ { label : "Develop", backgroundColor: "rgb(17, 135, 48)", hoverBackgroundColor: "rgba(50,90,100,1)", data:developAccCount // data: salesDetailJson.orderData }, { label : "Acquire", backgroundColor: "rgb(237, 168, 49)", hoverBackgroundColor: "rgba(140,85,100,1)", //data: [acquire] data:acqAccCount //data: salesDetailJson.orderData }, { label : "Retain", backgroundColor: "rgb(252, 208, 171)", hoverBackgroundColor: "rgba(46,185,235,1)", data:retainAccCount //data: salesDetailJson.orderData }, { label : "Light Touch", backgroundColor: "rgb(127, 205, 239)", hoverBackgroundColor: "rgba(46,185,235,1)", data:lightAccCount } ]}; var options = { responsive : true, curvature: 0.5, overlayBars: true, bezierCurve : false, legend: { display:false, position:'bottom', labels: { fontColor: 'black' } }, scaleLabel:{ display:false }, hover: { mode: true, animationDuration: 0 }, tooltips: { callbacks: { label: function(tooltipItem, data) { var datasetLabel = data.datasets[tooltipItem.datasetIndex].data; return data.datasets[tooltipItem.datasetIndex].label +':'+ ' '+datasetLabel + '% '; } } }, scales: { xAxes: [{ gridLines: { display:false }, barPercentage : 0.7, categoryPercentage :0.5, stacked : false }], yAxes: [{ gridLines: { display:true }, display: true, scaleShowLabels: false, //barPercentage : 0.5, //categoryPercentage :0.4, //barThickness : 20, ticks: { suggestedMin: 0, fontColor: "#ffffff", // minimum value will be 0. beginAtZero: true, steps: 10, stepValue: 10, max: 100 }, stacked : false }, ] } }; //var accountchartbyRADL = 'myChartaccountRADL'+component.get("v.season")+component.get("v.crop"); var el = document.getElementById("myChartRADLaccount"); var ctx = el.getContext("2d"); ctx.canvas.height=63; ctx.canvas.width=100; var myBarChart1 = new Chart(ctx, { type: 'bar', data: data, options: options }); window.onresize=function() { myBarChart1.resize(); }; }); $A.enqueueAction(action); } });<file_sep>/src/aura/Frontier_Carosel_Activities/Frontier_Carosel_ActivitiesController.js ({ doInit : function(component, event, helper) { helper.getProgramEventListHelper(component, event, helper); }, backToTouchpoint : function(component, event, helper){ helper.redirectToselectedActivity(component, event, helper); }, cancelActivity : function(component, event, helper){ var acctDetails = event.getSource().getLocalId(), acctId = acctDetails.split(',')[0], acctProgramId = acctDetails.split(',')[3], acctProgramActivityId = acctDetails.split(',')[6]; helper.cancelSelectedActivity(component, event, helper, acctId, acctProgramId, acctProgramActivityId); }, completeProgram :function(component, event, helper){ var cmpEvent = component.getEvent("loadCarosel"); cmpEvent.setParams({ "activityCount":component.get("v.activityCount"), "isPopup" :true, "modalParameters":event.getSource().getLocalId() }); cmpEvent.fire(); console.log("complete Program"); }, closeModal :function (component, event, helper){ var model = component.find('addnewActivity'); $A.util.removeClass(model, 'slds-show'); $A.util.addClass(model, 'slds-hide'); var backDrop = component.find('addCancelbackgrnd'); $A.util.removeClass(backDrop, 'slds-show'); $A.util.addClass(backDrop, 'slds-hide'); }, showAddNewActivity:function(component, event, helper){ var model = component.find('addnewActivity'); $A.util.removeClass(model, 'slds-hide'); $A.util.addClass(model, 'slds-show'); var backDrop = component.find('addCancelbackgrnd'); $A.util.removeClass(backDrop, 'slds-hide'); $A.util.addClass(backDrop, 'slds-show'); var selectedActivity = component.get("v.selectedAtivityMap"); var opts = []; var previousValue = '', optObj; if(selectedActivity){ for(var i in selectedActivity){ if(!(selectedActivity[i].Status === 'Not Scheduled') && !(previousValue === selectedActivity[i].Subject)){ optObj={class:"",label:"",value:""}; optObj.class = "optionClass"; optObj.label = selectedActivity[i].Subject; optObj.value = selectedActivity[i].Id; opts.push(optObj); previousValue = selectedActivity[i].Subject; } } } component.find("addinputSelect").set("v.options", opts); }, copyTask:function(component, event, helper){ var selectedTaskId = component.find("addinputSelect").get("v.value"); var action = component.get("c.cloneTask"); action.setParams({ taskId : selectedTaskId, }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ var retResponse = response.getReturnValue(); var clonedTask = JSON.parse(retResponse); $('#tableRPA'+component.get("v.PgmListId") +'> tbody:last-child').append('<tr class="tablerow"><td>'+replaceEmptyString(clonedTask.Subject) +'</td><td>'+replaceEmptyString(clonedTask.Status)+'</td><td>'+replaceEmptyString(clonedTask.Phase__c)+'</td></tr>'); console.log('state' +state); } function replaceEmptyString(value){ if(!value && value === undefined && value !== 0){ return ''; } else{ return value; } } var model = component.find('addnewActivity'); $A.util.removeClass(model, 'slds-show'); $A.util.addClass(model, 'slds-hide'); var backDrop = component.find('addCancelbackgrnd'); $A.util.removeClass(backDrop, 'slds-show'); $A.util.addClass(backDrop, 'slds-hide'); }); $A.enqueueAction(action); console.log("selectedTaskId" +selectedTaskId); }, saveComments : function(component, event, helper){ var uniqueIds = event.getSource().getLocalId(); var actAccId = uniqueIds.split(',')[0]; var activityId = uniqueIds.split(',')[6]; var textAreaValue = document.getElementById('textArea'+uniqueIds.split(',')[3]).value; console.log("I am in saveComments" + textAreaValue); helper.saveActivityComments(component, event, helper, actAccId, activityId, textAreaValue); } })<file_sep>/src/aura/Frontier_Salesrep_Coverage_Area/Frontier_Salesrep_Coverage_AreaHelper.js ({ getAccounts : function(component) { var action = component.get("c.getCoverageAreaLocationRecords"); action.setParams({ lati : component.get("v.comLat"), longi: component.get("v.comLong") }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ $A.createComponent("c:Frontier_GoogleMapComponent", { "aura:id" : "test", "coverageTasks" : response.getReturnValue(), "currentLongitude": component.get("v.comLong"), "currentLatitude": component.get("v.comLat") }, function(task){ console.log('Inside Dynamic creation'); var comp = component.find("map"); comp.set("v.body",task); console.log('Frontier_GoogleMapComponent'); } ); component.set("v.TaskRecords",response.getReturnValue()); //component.set("v.TaskRecords",component.get("v.responseRecord")); } }); $A.enqueueAction(action); } })<file_sep>/src/aura/Frontier_ProgramPlanning/Frontier_ProgramPlanningRenderer.js ({ rerender : function(cmp, helper){ // $A.get('e.force:refreshView').fire(); this.superRerender(); // do custom rerendering here } })<file_sep>/src/aura/Frontier_Gen_AccountSales/Frontier_Gen_AccountSalesHelper.js ({ getAccountSales : function(component, event, helper, isInitialize) { // get the current record id debugger; var currentrecordId = component.get("v.recordId"); var action = component.get("c.getAccountSalesDetails"); action.setStorable(); action.setParams({ recordId : currentrecordId, accountType : "Dealer" }); action.setCallback(this, function(response) { if (action.getState() === "SUCCESS") { var accountsSalesDetailsJson = JSON.parse(response.getReturnValue()); console.log('accountsSalesDetailsJson' + JSON.stringify(accountsSalesDetailsJson)); component.set("v.accountSalesDetails",accountsSalesDetailsJson); //this.getSeasonDetails(component,event,helper); } else if (response.getState() === "ERROR") { component.set("v.isCallBackError",false); component.set("v.ServerError",response); $A.log("Errors", response.getError()); console.log("Errors", response.getError()); } }); $A.enqueueAction(action); }, updateCYTarget : function (component, event, helper){ var CYTargetValue = component.find('CYTargetValue').get('v.value'); var action = component.get("c.updateCYTarget"); action.setParams({ CYTarget : CYTargetValue }); action.setCallback(this, function(response) { if (action.getState() === "SUCCESS") { alert("update success"); //var accountsSalesDetailsJson = JSON.parse(response.getReturnValue()); //console.log('accountsSalesDetailsJson' + JSON.stringify(accountsSalesDetailsJson)); //component.set("v.accountSalesDetails",accountsSalesDetailsJson); //this.getSeasonDetails(component,event,helper); } else if (response.getState() === "ERROR") { component.set("v.isCallBackError",false); component.set("v.ServerError",response); $A.log("Errors", response.getError()); console.log("Errors", response.getError()); } }); $A.enqueueAction(action); } })<file_sep>/src/aura/MultiSelect/MultiSelectHelper.js ({ setInfoText: function(component, values) { if (values.length == 0) { component.set("v.infoText", "Select an option..."); } if (values.length == 1) { component.set("v.infoText", values[0]); } else if (values.length > 1) { component.set("v.infoText", values.length + " options selected"); } }, getSelectedValues: function(component){ var options = component.get("v.options_"); var values = []; options.forEach(function(element) { if (element.selected) { values.push(element.value); } }); return values; }, getSelectedLabels: function(component){ var options = component.get("v.options_"); var labels = []; options.forEach(function(element) { if (element.selected) { labels.push(element.label); } }); return labels; }, setProgramDropdownOptions : function(component,event,helper){ var accId = component.get("v.accId"); var programs = component.get("v.programs"); var opt; var options = []; if(programs){ for(var i in programs){ opt = [{'label':'','value':'','selected':false}] opt.label = programs[i].Name; opt.value = accId +"-"+ programs[i].Id; options.push(opt); } } if(options && options.length > 0){ component.set("v.options",options) } }, despatchSelectChangeEvent: function(component,values,currentId){ var compEvent = component.getEvent("selectChangeEvent"); compEvent.setParams({ "values": values,"selectedId":currentId}); compEvent.fire(); } })<file_sep>/src/aura/Frontier_ProgramPlanning_Programlist/Frontier_ProgramPlanning_ProgramlistController.js ({ doInit : function(component, event, helper) { console.log('Inside Do Init'); var page = component.get("v.page") || 1; helper.programList(component,event,helper,page); }, pageChange: function(component,event,helper) { var cmpName = event.getParam("compName"); console.log('cmpName' + cmpName); if(cmpName == 'ProgramsList'){ var page = component.get("v.page") || 1; var direction = event.getParam("direction"); page = direction === "previous" ? (page - 1) : (page + 1); helper.programList(component,event,helper,page); } }, programNavigation : function(component,event,helper){ var myEvent = $A.get("e.c:Frontier_SelectedProgramEvent"); var evt = event.currentTarget.id; console.log('evt'+evt); myEvent.setParams({ "programId": evt.split(',')[0], "dealerId": evt.split(',')[1], "accountTarget": evt.split(',')[2] }); console.log("progId" + evt); myEvent.fire(); } })<file_sep>/src/aura/Frontier_DynamicAruaIdMarkup/Frontier_DynamicAruaIdMarkupController.js ({ clickMe : function(component, event, helper){ var elem = component.find('mulselect0012C00000ArlIfQAJ'); var elem1 = component.find('mulselect0012C00000AsKHJQA3'); } })<file_sep>/src/aura/Frontier_GrowersDealerList/Frontier_GrowersDealerListHelper.js ({ getDealerAccount : function(component,event,page1,searchKey) { var page = page1 || 1; var acId = component.get("v.accountId"); var action = component.get("c.getDealerAccounts"); console.log("================= Inside getDealerAccount" + searchKey); console.log("================= Inside page" + page); action.setParams({ "searchKey": searchKey, pageNumber : page, pageSize : component.get("v.pageSize"), accId : acId }); action.setCallback(this, function(response) { var accounts = []; component.set("v.page",page); var accountList = response.getReturnValue(); component.set("v.pages",Math.ceil((JSON.parse(accountList[0]))/component.get("v.pageSize"))); component.set("v.total",JSON.parse(accountList[0])); accounts = JSON.parse(accountList[1]); console.log("Account search employee" + accounts); component.set("v.accounts", accounts); }); $A.enqueueAction(action); }, toGrowerCount : function(component,event){ var uniqueId = event.target.id; console.log('accountId,Sap Id,Accmu'+uniqueId); var accountId = uniqueId.split(',')[0]; $A.createComponent("c:Frontier_GrowerAccountList", { accountId: accountId }, function(GrowerList){ console.log('AccountList'); var comp = component.find("GrowerAccount"); comp.set("v.body",GrowerList); } ); }, navigateToAccountDetail : function(component,event) { console.log("c:Frontier_GrowerAccount_Overview"); var uniqueId = event.target.id; console.log('accountId,Sap Id,Accmu'+uniqueId); var accountId = uniqueId.split(',')[0]; var sapId= uniqueId.split(',')[1]; var accCommunicationId = uniqueId.split(',')[2]; /*$A.createComponent( "c:Frontier_AccountDetailViewComponent", { accId: accountId, sapId: sapId, accCommunicationId: accCommunicationId }, function(newCmp){ var cmp = component.find("AccountDetail"); cmp.set("v.body", []); cmp.set("v.body", newCmp); } );*/ $A.createComponent( "c:Frontier_GrowerAccount_Overview", { "growerAcc" : uniqueId, "role" : component.get("v.accounts")[0].roleDesc, "heading" :'dealer' }, function(newCmp){ var cmp = component.find("GrowerAccount"); cmp.set("v.body", []); cmp.set("v.body", newCmp); } ); }, sortbyRadl: function(component,page1,sortbyValue) { var page = page1 || 1; console.log("Inside sort helper"); console.log("Inside sort page" + page); var action = component.get("c.sortBy"); action.setParams({ "sortbyValue": sortbyValue, pageNumber : page, pageSize : component.get("v.pageSize"), accId : component.get("v.accountId") }); action.setCallback(this, function(response) { var accounts = []; component.set("v.page",page); var accountList = response.getReturnValue(); component.set("v.pages",Math.ceil((JSON.parse(accountList[0]))/component.get("v.pageSize"))); component.set("v.total",JSON.parse(accountList[0])); accounts = JSON.parse(accountList[1]); console.log("Dealer Account=>" + accounts); component.set("v.accounts", accounts); }); $A.enqueueAction(action); }, })<file_sep>/src/aura/GenerateDyanamicAuraId/GenerateDyanamicAuraIdController.js ({ doInit : function(component, event, helper) { var uniqueId = component.get("v.uniqueId"); console.log("uniqueAuraId:" + uniqueId); $A.createComponent( "c:Frontier_DynamicAruaIdMarkup", { "aura:id":uniqueId, }, function(newCmp){ var cmp = component.find('root'); cmp.set("v.body", newCmp); } ); var elem = component.find(uniqueId); } })<file_sep>/src/aura/Frontier_TouchpointChild/Frontier_TouchpointChildController.js ({ doInit : function(component, event, helper) { var key= component.get("v.key"); var Tmap = component.get("v.taskMap"); var taskList = []; var tasks = []; var task; console.log("Taskssssssssssss Map=====================>"+Tmap); console.log("keyyyyyyyyyyyy=====================>"+key); //tasks.push(Tmap[key]); for(var key1 in Tmap){ if(key1 == key){ taskList.push(Tmap[key1]); } } //tasklist.push(map[key]); component.set("v.tasks",taskList); var tasklist=component.get("v.tasks"); console.log("Taskssssssssssss List=====================>"+ JSON.stringify(tasklist)); var programs = []; var programActivities =[]; var date =[]; var type=[]; var status=[]; var redirectParameter=''; for(var i=0;i<tasklist.length;i++){ for(var j=0;j<tasklist[i].length;j++){ console.log(tasklist[i][j].Program_SFID__r.Name); programs.push(tasklist[i][j].Program_SFID__r.Name); programActivities.push(tasklist[i][j].Program_Activity_SFID__r.Name); date.push(tasklist[i][j].TouchPoint_SFID__r.Date__c); type.push(tasklist[i][j].TouchPoint_SFID__r.TouchPointTypes__c); status.push(tasklist[i][j].TouchPoint_SFID__r.TouchPoint_Status__c); redirectParameter = tasklist[i][j].Program_SFID__c +'/'+ component.get("v.growerAcc")+'/'+tasklist[i][j].Program_Activity_SFID__c+'/'+tasklist[i][j].TouchPoint_SFID__c+'/'+tasklist[i][j].TouchPoint_SFID__r.Date__c+'/'+'c:Frontier_GrowerAcc_Touchpoint'; } } component.set("v.Programs",programs); component.set("v.ProgramActivities",programActivities); component.set("v.TouchpointDate",date); component.set("v.TouchpointStatus",status); component.set("v.TouchpointType",type); component.set("v.redirectString",redirectParameter) console.log('Program Name' +component.get("v.Programs")+component.get("v.ProgramActivities")+component.get("v.TouchpointDate")); console.log('Program Name------' +component.get("v.TouchpointStatus")+component.get("v.TouchpointType")); }, navigateToTouchpointEventFire : function(cmp,event,helper){ var compEvent = cmp.getEvent("navigateToTouchpointList"); compEvent.setParams( { touchPointRedirect : cmp.get("v.redirectString"), touchPointStatus : document.getElementById(event.target.parentNode.id).parentNode.parentNode.childNodes[4].innerHTML } ); compEvent.fire(); } })<file_sep>/src/aura/Frontier_GrowerAccount_Sales_Master/Frontier_GrowerAccount_Sales_MasterController.js ({ doInit : function(component, event, helper) { helper.growerSalesDetails(component,event,helper); }, changeUnits : function(component,event,helper){ helper.growerSalesDetails(component,event,helper); } })<file_sep>/src/aura/Frontier_SalesRep_ProgramDetail_Master/Frontier_SalesRep_ProgramDetail_MasterController.js ({ doInit : function(component, event, helper) { var page = component.get("v.page") || 1; var ispageChange = false; var isInitialize = true; //var dealerId = component.get("v.dealerId"); helper.programEventListHelper(component,event,page,ispageChange,isInitialize); helper.getAllPrograms(component,event,helper); }, pageChange: function(component,event,helper) { var page = component.get("v.page") || 1; var direction = event.getParam("direction"); page = direction === "previous" ? (page - 1) : (page + 1); var ispageChange = true; var isInitialize = false; component.set("v.usersInitialLoad",false); helper.programEventListHelper(component,event,page,ispageChange,isInitialize); }, sortDirection : function(component,event,helper){ if(event.currentTarget.id != '' && component.get("v.prevId") != '' && component.get("v.prevId") != event.currentTarget.id){ component.set("v.SortBy"+component.get("v.prevId"),"onMouseOut"); } var page = 1; console.log("Event Target"+event.currentTarget.id) if(event.currentTarget.id != ''){ component.set("v.SortBy"+event.currentTarget.id,"onClick"); } var ispageChange = false; var isInitialize = false; component.set("v.prevId",event.currentTarget.id); component.set("v.usersInitialLoad",false); helper.programEventListHelper(component,event,page,ispageChange,isInitialize); }, updateTouchPointNavigation: function(component,event,helper){ helper.navigateToUpdateTouchPointDetail(component, event); }, cancelActivity : function(component,event,helper){ console.log('cancel'); helper.cancelSelectedActivity(component,event); var page = component.get("v.page") || 1; var ispageChange = false; var isInitialize = true; component.set("v.usersInitialLoad",true); helper.programEventListHelper(component,event,page,ispageChange,isInitialize); }, refreshProgram : function(component,event,helper){ var cmpName = event.getParam("compName"); console.log('cmpName' + cmpName); if(cmpName == 'MyPrograms'){ console.log('Inside refresh Event'); component.set("v.loadchart1" , false); component.set("v.loadchart2" , false); component.set("v.loadchart3" , false); component.set("v.loadchart4" , false); helper.getAllPrograms(component,event,helper); } }, navigateToTouchPoints : function(component,event,helper){ var cmpEvent = component.getEvent("redirectToDealerDetail"); var accId = component.get("v.accountId"); var programId = component.get("v.programId"); var accCommId = component.get("v.growerAcc").split(',')[2]; var programEventId = event.target.id; cmpEvent.setParams({ "accIdSapIdAccCommId" :accId +","+","+accCommId+","+programId+","+programEventId, "tabScopeNo" : '4', "componentName":"c:Frontier_Programs_Activities" }); cmpEvent.fire(); }, fetchSeasonData : function(component, event, helper) { helper.getSeason(component, event, helper); } });<file_sep>/src/aura/Frontier_GrowerAccount_FarmSize/Frontier_GrowerAccount_FarmSizeController.js ({ loadFormSizeChart : function(component, event, helper) { var fiscalyr = null; var uom = null; var seasonkey = null; component.set("v.seasonKey",seasonkey); helper.loadFormSizeChartData(component,fiscalyr,uom); }, update : function(component, event, helper){ if(component.isValid()){ component.destroy(); } }, changeChart : function(component, event, helper){ var fiscalyr; var uom; //var prevId = component.get("v.prevID"); //var prevfiscalId = component.get("v.prevfiscalID"); //var seasonkey; uom = component.find("UOM").get("v.value"); fiscalyr = component.find("FiscalYear").get("v.value"); //console.log('event.target.id' + event.target.id); console.log('fiscalyr' + fiscalyr); console.log('uom' + uom); /* if(prevId === '' && event.target.id == 'hectares'){ $A.util.toggleClass(document.getElementById('acres'), 'buttonColor'); $A.util.toggleClass(document.getElementById('hectares'), 'buttonColor'); } if(prevId != '' && prevId != event.target.id && (event.target.id === 'acres' || event.target.id === 'hectares')){ $A.util.toggleClass(document.getElementById('acres'), 'buttonColor'); $A.util.toggleClass(document.getElementById('hectares'), 'buttonColor'); } if(prevfiscalId == '' && event.target.id == 'FY16'){ $A.util.toggleClass(document.getElementById('FY17'), 'buttonColor'); $A.util.toggleClass(document.getElementById('FY16'), 'buttonColor'); } if(prevfiscalId == '' && event.target.id == 'FY15'){ $A.util.toggleClass(document.getElementById('FY17'), 'buttonColor'); $A.util.toggleClass(document.getElementById('FY15'), 'buttonColor'); } if(prevfiscalId != '' && prevfiscalId != event.target.id && (event.target.id == 'FY17' || event.target.id == 'FY16' || event.target.id == 'FY15')){ if(prevfiscalId == 'FY17'){ $A.util.toggleClass(document.getElementById('FY17'), 'buttonColor'); } else if(prevfiscalId == 'FY16'){ $A.util.toggleClass(document.getElementById('FY16'), 'buttonColor'); } else{ $A.util.toggleClass(document.getElementById('FY15'), 'buttonColor'); } $A.util.toggleClass(document.getElementById(event.target.id), 'buttonColor'); } var itemNode = document.getElementById('myDoughnutChart'); itemNode.parentNode.removeChild(itemNode); document.getElementById('chartDivDoughnut').innerHTML = '<canvas id="myDoughnutChart" class="myChartLarge canvasPosition"></canvas>'; if(prevId === '' && (event.target.id === 'acres' || event.target.id === 'hectares')){ uom = event.target.id; console.log('Inside uom' + uom); } else if(prevId != '' && (event.target.id === 'acres' || event.target.id === 'hectares')){ uom = event.target.id; console.log('Inside uom 1' + uom); } else if(prevId != '' && (event.target.id === 'FY16' || event.target.id ==='FY17' || event.target.id ==='FY15')){ uom = prevId; } if(prevfiscalId === '' && (event.target.id === 'FY16' || event.target.id ==='FY17' || event.target.id ==='FY15')){ fiscalyr = event.target.id; } else if(prevfiscalId != '' && (prevfiscalId != event.target.id) && (event.target.id === 'FY16' || event.target.id ==='FY17' || event.target.id ==='FY15')){ fiscalyr = event.target.id; } else if(prevfiscalId != '' && (event.target.id === 'acres' || event.target.id === 'hectares')){ fiscalyr = prevfiscalId; } else if(prevfiscalId === '' && (event.target.id === 'acres' || event.target.id === 'hectares')){ fiscalyr = null; } if(event.target.id === 'FY16' || event.target.id === 'FY17' || event.target.id === 'FY15'){ component.set("v.prevfiscalID",event.target.id); } else if(prevfiscalId === '' && (event.target.id === 'acres' || event.target.id === 'hectares')){ component.set("v.prevfiscalID",'FY17'); } if(event.target.id === 'acres' || event.target.id === 'hectares'){ component.set("v.prevID",event.target.id); } console.log('fiscalyr' + fiscalyr + ' '+ 'uom' + uom);*/ helper.loadFormSizeChartData(component,fiscalyr,uom); }, updCurrentYrArea : function(component,event,helper){ helper.updCurrentFYArea(component,event); } })<file_sep>/src/aura/Frontier_AllDealers_ProgramPlanning_ProgramList/Frontier_AllDealers_ProgramPlanning_ProgramListController.js ({ doInit : function(component, event, helper) { var page = component.get("v.page") || 1; helper.programList(component,event,helper,page); }, pageChange: function(component,event,helper) { var cmpName = event.getParam("compName"); console.log('cmpName' + cmpName); if(cmpName == 'AllDealerProgramsList'){ var page = component.get("v.page") || 1; var direction = event.getParam("direction"); page = direction === "previous" ? (page - 1) : (page + 1); helper.programList(component,event,helper,page); } }, programNavigation : function(component,event,helper){ var myEvent = $A.get("e.c:Frontier_SelectedProgramEvent"); var programId = event.target.id; myEvent.setParams({ "programId": programId }); console.log("progId" + event.target.value); myEvent.fire(); } })<file_sep>/src/aura/Frontier_Programs_Activities/Frontier_Programs_ActivitiesHelper.js ({ getProgramEventListHelper : function(component, event,helper) { var acctDetails = component.get("v.growerAcc"), acctId = acctDetails.split(',')[0], acctProgramId = acctDetails.split(',')[3], acctProgramActivityId = acctDetails.split(',')[4]; component.set("v.selectedProgramId",acctProgramId); var action = component.get("c.getProgramsTasksByTask"); // action.setParams({ acctId : acctId, programId : acctProgramId, taskId : acctProgramActivityId }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ var programEventlist = []; var retResponse = response.getReturnValue(); programEventlist = JSON.parse(retResponse); console.log("json stringfiy:::" + JSON.stringify(retResponse)); component.set("v.programEventList", programEventlist); component.set("v.programList",programEventlist.accountProgramList); component.set("v.programIdActivityMap",programEventlist.activityMap); var aMap = component.get("v.programIdActivityMap"); var listofPrograms = Object.keys(aMap).map( function(key){ return{ key: key, value : aMap[key] } }); component.set("v.selectedAtivityMap",listofPrograms); //component.set("v.selectedTaskName",programEventlist.selectedName); console.log("v.programEventList from PA" + programEventlist); } else if(state === "ERROR"){ console.log('Error'); } }); $A.enqueueAction(action); }, updatePgmStatus : function(component, event,helper,reason){ var PgmId = component.get("v.modelProgramId"); var pgmList = component.get("v.programList"); var accPgmId; for(var i in pgmList){ if(pgmList[i].Program__c === PgmId) { accPgmId = pgmList[i].Id; break; } } var status = component.get("v.modelProgramStatus"); if(component.get("v.popupName") === 'Complete Program'){ status = 'Completed'; } if(component.get("v.popupName") === 'Cancel Program'){ status = 'Cancelled' } console.log( accPgmId + ' ' + status); var action = component.get("c.getCancelPgm"); action.setParams({ status : status, accPgmId : accPgmId, reason : reason }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ var updatedStatus = document.getElementById('pgmStatus'+component.get("v.modelProgramId")); updatedStatus.innerHTML = ((component.get("v.popupName") === 'Complete Program')?'Completed':'Cancelled'); if((component.get("v.popupName") === 'Complete Program') || (component.get("v.popupName") === 'Cancel Program')){ var comElem = $('#parentcompleteProgramlink' + component.get("v.modelProgramId")); var cancelElem = $('#parentcancelProgramlink' + component.get("v.modelProgramId")); comElem.css("display","none"); comElem.next().css("display","none"); cancelElem.css("display","none"); } console.log('Success'); } else if(state === 'ERROR'){ console.log('Error'); } }); $A.enqueueAction(action); } })<file_sep>/src/aura/Frontier_Dealer_GrowerProgram_Chart/Frontier_Dealer_GrowerProgram_ChartHelper.js ({ loadPgmChart : function(component,event,helper) { console.log('Inside chartHelp Dealer Grower'); var allocated =component.get("v.allocated"); var available =component.get("v.available"); var consumed = component.get("v.consumed"); console.log(allocated + ' ' + available+''+consumed); var dataSet=[]; var labels=[]; var dealeruniquechart; dealeruniquechart = 'dealeruniquechart'+component.get("v.identifier"); console.log(dealeruniquechart + 'dealeruniquechart'); var el = document.getElementById(dealeruniquechart); console.log(el + 'el'); var context = el.getContext('2d'); if((component.get("v.identifier")) == 1){ console.log('identifier 1'); dataSet = [component.get("v.allocated"),component.get("v.available"), component.get("v.consumed")]; //labels = [component.get("v.allocated"),component.get("v.available")]; labels =['Allocated','Available', 'Consumed']; var centext = "Budget"; console.log(dataSet + 'dataset1'); console.log(labels + 'labels1'); } else if((component.get("v.identifier")) == 2){ console.log('identifier 2'); dataSet = [component.get("v.cancelled"),component.get("v.completed"),component.get("v.notStarted"),component.get("v.inExecution")]; //labels = [component.get("v.cancelled"),component.get("v.completed"),component.get("v.notStarted"),component.get("v.inExecution")]; labels =['Cancelled','Completed','Not Started','In Execution']; var centext = "Execution"; console.log(dataSet + 'dataset2'); console.log(labels + 'labels2'); } else if((component.get("v.identifier") == 3)){ console.log('identifier 3'); dataSet = [component.get("v.planned"),component.get("v.postPlanned")]; //labels = [component.get("v.planned"),component.get("v.postPlanned")]; labels =['Planned','Post Planned']; var centext = "Planning"; console.log(dataSet + 'dataset'); } else if((component.get("v.identifier") == 4)){ console.log('identifier 4'); dataSet = [component.get("v.product1"),component.get("v.product2"),component.get("v.product3")]; //labels = [component.get("v.product1"),component.get("v.product2"),component.get("v.product3")]; labels =['Product1','Product2','Product3']; var centext = 'Accts. using\nProd.'; console.log(dataSet + 'dataset'); } else if((component.get("v.identifier") == 6)){ console.log('identifier 6'); dataSet = [component.get("v.product1"),component.get("v.product2"),component.get("v.product3")]; //labels = [component.get("v.product1"),component.get("v.product2"),component.get("v.product3")]; labels =['Product1','Product2','Product3']; var centext = 'Accts. using\nProd.'; console.log(dataSet + 'dataset'); } else{ dataSet = [component.get("v.product1"),component.get("v.product2"),component.get("v.product3")]; //labels = [component.get("v.product1"),component.get("v.product2"),component.get("v.product3")]; labels =['Product1','Product2','Product3']; var centext = 'Accts. using\nProd.'; console.log(dataSet + 'dataset'); } var data = { //labels: ['Product 1<br /><span style="Padding-left:24%;">Programs:'+component.get("v.program1")+'</span>','Product 2 <br /><span style="Padding-left:24%"> Programs:'+component.get("v.program2")+'</span>','Product 3 <br /> <span style="Padding-left:24%"> Programs:'+component.get("v.program3")+'</span>'], labels: labels, //labels: ['Product 1','Product 2','Product 3'], datasets: [ { data: dataSet, backgroundColor: [ "#f5f5f5", "#D3D3D3", "#3299CC", "#FFCC00" ] }] }; var options = { showAllTooltips: false, segmentShowStroke: false, responsive : true, animateRotate: true, animateScale: false, //cutoutPercentage: 80, legend: { display : false, position:'right' }, hover: { onHover: null, mode: 'single', animationDuration:0 }, animation: { duration: 0, onComplete: function () { var self = this, chartInstance = this.chart, ctx = chartInstance.ctx; ctx.font = '10px Arial'; ctx.textAlign = "center"; var width = this.chart.width; var height = this.chart.height; var x = this.chart.canvas.clientWidth / 2; var y = this.chart.canvas.clientHeight / 2; //fill center chart color var identity = component.get("v.identifier"); if((component.get("v.identifier")) != 6 && identity.length == 1){ ctx.beginPath(); this.chart.ctx.arc(x,y,40,0,2*Math.PI); ctx.fillStyle = '#ffffff'; ctx.fill(); } //render text in the middle of the chart var textX = width / 2, textY = height / 2; console.log('text' + textX + ' ' + textY); ctx.fillStyle ='black'; ctx.textBaseline = "middle"; if(centext.includes("\n")){ var lines = centext.split('\n'); for (var i = 0; i<lines.length; i++){ if(i == 1){ textY = textY + 10; } ctx.fillText(lines[i], textX, textY); } }else{ ctx.fillText(centext, textX, textY); } // ctx.fillText(centext, textX, textY); Chart.helpers.each(self.data.datasets.forEach((dataset, datasetIndex) => { var meta = self.getDatasetMeta(datasetIndex), total = 0, //total values to compute fraction labelxy = [], offset = Math.PI / 2, //start sector from top radius, centerx, centery, lastend = 0; //prev arc's end line: starting with 0 for (var val of dataset.data) { total += val; } Chart.helpers.each(meta.data.forEach((element, index) => { radius = element._model.outerRadius; centerx = element._model.x; centery = element._model.y; var thispart = dataset.data[index], arcsector = Math.PI * (2 * thispart / total); if (element.hasValue() && dataset.data[index] > 0) { labelxy.push(lastend + arcsector / 2 + Math.PI + offset); } else { labelxy.push(-1); } lastend += arcsector; }), self) var lradius = radius * 3 / 4; for (var idx in labelxy) { if (labelxy[idx] === -1) continue; var langle = labelxy[idx], dx = centerx + lradius * Math.cos(langle), dy = centery + lradius * Math.sin(langle), val = Math.round(dataset.data[idx] / total * 100); //ctx.fillText(self.data.labels[idx],dx, dy); wrapText(ctx,dataset.data[idx],dx,dy,8,3); } // centrText(ctx,textcentr,textX,textY); }), self); function wrapText(context, text, x, y, maxWidth, lineHeight) { var line=" "; line = text; context.fillStyle='black'; context.fillText(line, x, y); } } }, tooltips: { enabled:false, } } var canvas = document.getElementById(dealeruniquechart); //var canvas = component.find("dealerchart2"); // var canvas = component.find('chart'+component.get("v.identifier")); console.log(canvas + 'el'); var ctx = canvas.getContext('2d'); console.log(ctx + 'ctx'); ctx.canvas.width=300; ctx.canvas.height=100; var pgmDChart = new Chart(ctx, { type: 'doughnut', data: data, options:options }); var dealerprogramlegendId; dealerprogramlegendId = 'dealeruniquechartlegend' + component.get("v.identifier"); console.log('dealerprogramlegendId' + dealerprogramlegendId); document.getElementById(dealerprogramlegendId).innerHTML = pgmDChart.generateLegend(); $A.util.addClass(component.find(dealerprogramlegendId),'chart-lgnd'); } })<file_sep>/src/aura/Frontier_Dealer_GrowerProgram_Chart/Frontier_Dealer_GrowerProgram_ChartRenderer.js ({ afterRender : function(component, helper){ /* var identifier = component.get("v.identifier"); if (document.getElementById('chart'+identifier) != null) { var canvas = document.getElementById('chart'+identifier); console.log(canvas+'********'); var att = document.createAttribute("aura:id"); // Create a "class" attribute att.value = 'chart'+identifier; // Set the value of the class attribute canvas.setAttributeNode(att); } else{ console.log('Null Exists========'); } this.superAfterRender();*/ } })<file_sep>/src/aura/FrontierSalesOrderDashboard/FrontierSalesOrderDashboardHelper.js ({ loadChartData : function(component){ if(component.isValid()){ Console.log(JSON.stringify(component.get("v.SalesDetailResponse"))); var action = component.get("c.AccountDetails"); action.setParams({ CropType : component.get("v.CropData"), result : component.get("v.SalesDetailResponse"), accId : component.get("v.accId") }); action.setCallback(this, function(response) { if (response.getState() === "SUCCESS") { var salesDetailJson = JSON.parse(response.getReturnValue()); component.set("v.SalesOrder",salesDetailJson); } else if (response.getState() === "ERROR") { $A.log("Errors", response.getError()); } var data = { labels: salesDetailJson.Labels, datasets: [ { label : "Sales", type : "bar", fillColor: "rgba(220,220,220,0.5)", backgroundColor: 'rgba(38, 95, 43, 1)', borderColor: '#71B37C', hoverBackgroundColor: 'rgba(38, 95, 43, 1)', hoverBorderColor: '#71B37C', data: salesDetailJson.orderData } ]}; var options = { responsive : true, barValueSpacing: 1, overlayBars: true, bezierCurve : false, animation:false, legend: { display:true, position:'right', labels: { fontColor: 'black' } }, scales: { xAxes: [{ gridLines: { display:false } }], yAxes: [{ gridLines: { display:false }, display: true, ticks: { // minimum will be 0, unless there is a lower value. suggestedMin: 0, // minimum value will be 0. beginAtZero: true } }] } }; var el = document.getElementById("myChart"); var ctx = el.getContext("2d"); var myBarChart1 = new Chart(ctx, { type: 'bar', data: data, options: options }); window.onresize=function() { myBarChart1.resize(); }; }); $A.enqueueAction(action); } } });<file_sep>/src/aura/Frontier_TestGrowerAccount_FarmSize/Frontier_TestGrowerAccount_FarmSizeController.js ({ loadFormSizeChart : function(component, event, helper) { var fiscalyr = null; var uom = null; helper.loadFormSizeChartData(component,fiscalyr,uom); }, update : function(component, event, helper){ if(component.isValid()){ component.destroy(); } }, changeChart : function(component, event, helper){ var fiscalyr; var uom; var prevId = component.get("v.prevID"); var prevfiscalId = component.get("v.prevfiscalID"); console.log('event.target.id' + event.target.id); console.log('prevfiscalId' + prevfiscalId); console.log('prevId' + prevId); if(prevId === '' && event.target.id == 'hectares'){ $A.util.toggleClass(document.getElementById('acres'), 'buttonColor'); $A.util.toggleClass(document.getElementById('hectares'), 'buttonColor'); } if(prevId != '' && prevId != event.target.id && (event.target.id === 'acres' || event.target.id === 'hectares')){ $A.util.toggleClass(document.getElementById('acres'), 'buttonColor'); $A.util.toggleClass(document.getElementById('hectares'), 'buttonColor'); } if(prevfiscalId == '' && event.target.id == 'FY15'){ $A.util.toggleClass(document.getElementById('FY16'), 'buttonColor'); $A.util.toggleClass(document.getElementById('FY15'), 'buttonColor'); } if(prevfiscalId != '' && prevfiscalId != event.target.id && (event.target.id == 'FY16' || event.target.id == 'FY15')){ $A.util.toggleClass(document.getElementById('FY16'), 'buttonColor'); $A.util.toggleClass(document.getElementById('FY15'), 'buttonColor'); } var itemNode = document.getElementById('myDoughnutChart'); itemNode.parentNode.removeChild(itemNode); document.getElementById('chartDivDoughnut').innerHTML = '<canvas id="myDoughnutChart" class="myChartLarge canvasPosition"></canvas>'; if(prevId === '' && (event.target.id === 'acres' || event.target.id === 'hectares')){ uom = event.target.id; console.log('Inside uom' + uom); } else if(prevId != '' && (event.target.id === 'acres' || event.target.id === 'hectares')){ uom = event.target.id; console.log('Inside uom 1' + uom); } else if(prevId != '' && (event.target.id === 'FY15' || event.target.id ==='FY16')){ uom = prevId; } if(prevfiscalId === '' && (event.target.id === 'FY15' || event.target.id ==='FY16')){ fiscalyr = event.target.id; } else if(prevfiscalId != '' && (prevfiscalId != event.target.id) && (event.target.id === 'FY15' || event.target.id ==='FY16')){ fiscalyr = event.target.id; } else if(prevfiscalId != '' && (event.target.id === 'acres' || event.target.id === 'hectares')){ fiscalyr = prevfiscalId; } else if(prevfiscalId === '' && (event.target.id === 'acres' || event.target.id === 'hectares')){ fiscalyr = null; } if(event.target.id === 'FY15' || event.target.id === 'FY16'){ component.set("v.prevfiscalID",event.target.id); } else if(prevfiscalId === '' && (event.target.id === 'acres' || event.target.id === 'hectares')){ component.set("v.prevfiscalID",'FY16'); } if(event.target.id === 'acres' || event.target.id === 'hectares'){ component.set("v.prevID",event.target.id); } console.log('fiscalyr' + fiscalyr + ' '+ 'uom' + uom); helper.loadFormSizeChartData(component,fiscalyr,uom); }, })<file_sep>/src/aura/Frontier_Account_AddressInformation/Frontier_Account_AddressInformationHelper.js ({ getAddressdetails : function(component, event) { var acccomId = component.get("v.accComId"); var acctId = component.get("v.accountId"); var action = component.get("c.getAccountCommunicationDetails"); action.setParams({ accId : acctId, accComId : acccomId, }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ var retResponse = JSON.parse(response.getReturnValue()); console.log("accountCommResult::" + retResponse); component.set("v.acctDetails",JSON.parse(retResponse[0])); component.set("v.accountCommList",JSON.parse(retResponse[1])); } else{ console.log("Error Occured"); } }); $A.enqueueAction(action); } })<file_sep>/src/aura/Frontier_GrowerAccount_PreviousTouchPoints/Frontier_GrowerAccount_PreviousTouchPointsController.js ({ doInit : function(component,event,helper){ helper.TouchPointRecord(component); }, handleTouchPoints : function(component,event,helper){ helper.TouchPointRecord(component); }, /* showModal : function(){ document.getElementById("backGroundSectionId").style.display = "block"; document.getElementById("newAccountSectionId").style.display = "block"; var appEvent = $A.get("e.c:Frontier_ActivityRefresh"); appEvent.fire(); }*/ });<file_sep>/src/aura/Frontier_Gen_DealerAndGrowerAccountList/Frontier_Gen_DealerAndGrowerAccountListController.js ({ doinit : function(component, event, helper) { var action = component.get("c.getAccounts"); action.setParams({ "searchKey": '', pageNumber : 1, pageSize : 10 }) action.setCallback(this, function(response) { if(response.getState() === "SUCCESS"){ Component.set('accountList',JSON.parse(response.getReturnValue())); } } } })<file_sep>/src/aura/Frontier_SelectedProgramList/Frontier_SelectedProgramListRenderer.js ({ rerender : function(cmp, helper){ // $A.util.addClass(document.getElementById(cmp.get("v.progId")), 'changeMe'); this.superRerender(); // document.getElementById(cmp.get("v.progId")).style = 'background:#D3D3D3;width:100%;text-align: initial;'; cmp.set("v.highlightPanel",'background:#D3D3D3;width:100%;text-align: initial;'); console.log('After render child'+cmp.get("v.progId")); console.log('After render child Id'+document.getElementById(cmp.get("v.progId"))); // do custom rerendering here } })<file_sep>/src/aura/Frontier_outputShowMoreText/Frontier_outputShowMoreTextController.js ({ doInit : function(component, event, helper) { component.set("v.containerId", component.get("v.containerId")) // body = component.get("v.body"); // component.set("v.body",body); }, toggleEvent: function(component, event, helper){ var parentId = component.get("v.containerId"); var thisId = event.getSource().getLocalId(); console.log(thisId); var thisElement = component.find(thisId); var parentElement = component.find(parentId); var thisValue = thisElement.get("v.value"); console.log(thisValue); if(thisValue.toUpperCase() === 'SHOW MORE'){ component.set("v.toggleValue",'Show Less'); $A.util.toggleClass(parentElement,'full-text'); } else{ component.set("v.toggleValue",'Show More'); $A.util.toggleClass(parentElement,'short-text'); } } })<file_sep>/src/aura/Frontier_GrowerAccount_UpdateTouchPoint/Frontier_GrowerAccount_UpdateTouchPointController.js ({ loadStaticResources : function(component, event, helper){ console.log("Script Loaded"); }, doInit : function(component, event, helper) { helper.helperUpdateTouchPoint(component, event); //alert(component.get('v.accountId')); }, setMultipleAttributeToSelectdyanamically : function(component,event,helper){ if(!(event.target.id).includes('activityOption') && !(event.target.id).includes('nonactivityOption') && event.target.id != ''){ if(!document.getElementById(event.target.id).classList.contains('multiple')){ helper.nonProgramdependentActivate(component, event); document.getElementById(event.target.id).setAttribute("multiple", "true"); document.getElementById(event.target.id).setAttribute("size", "3"); } } }, dependentActivate : function(component,event,helper){ var selectProgramDomId = event.target.id; var i; var activityArray=[]; if(selectProgramDomId === 'program_1'){ component.set("v.activitiesFlag",true); }else{ component.set("v.activitiesFlag",false); } var selectProgram = document.getElementById(event.target.id).value; if(selectProgram !== 'SelectProgram'){ if(component.get("v.programIdActivityMap")[selectProgram] !== 'undefined'){ if(component.get("v.activityType") != '' && component.get("v.activityType") != 'null'){ for(i=0;i<(component.get("v.programIdActivityMap")[selectProgram]).length;i++){ if(component.get("v.programIdActivityMap")[selectProgram][i].Activity_Type__c === component.get("v.activityType")){ activityArray.push(component.get("v.programIdActivityMap")[selectProgram][i]) } } component.set("v.programDependentActivities",activityArray); }else { component.set("v.programDependentActivities",component.get("v.programIdActivityMap")[selectProgram]); } } if(event.target.id != ''){ document.getElementById('programActivites_'+selectProgramDomId.substring(selectProgramDomId.indexOf('_')+1,selectProgramDomId.length)).removeAttribute("disabled"); } } }, nonProgramdependentActivate : function(component,event,helper){ var selectProgramDomId = event.target.id; var i; var activityArray=[]; if(selectProgramDomId === 'nonprogram_1'){ component.set("v.activitiesFlag",true); }else{ component.set("v.activitiesFlag",false); } var selectProgram = document.getElementById(event.target.id).value; if(selectProgram !== 'SelectProgram'){ if(component.get("v.programIdActivityMap")[selectProgram] !== 'undefined'){ if(component.get("v.activityType") != '' && component.get("v.activityType") != 'null'){ for(i=0;i<(component.get("v.programIdActivityMap")[selectProgram]).length;i++){ if(component.get("v.programIdActivityMap")[selectProgram][i].Activity_Type__c === component.get("v.activityType")){ activityArray.push(component.get("v.programIdActivityMap")[selectProgram][i]) } } component.set("v.nonProgramDependentActivities",activityArray); }else { component.set("v.nonProgramDependentActivities",component.get("v.programIdActivityMap")[selectProgram]); } } if(event.target.id != ''){ document.getElementById('nonprogramActivites_'+selectProgramDomId.substring(selectProgramDomId.indexOf('_')+1,selectProgramDomId.length)).removeAttribute("disabled"); } } }, addProgramActivities : function(component,event,helper){ var programDependentsActivities = 'programDependentsActivities'; var programActivityLastId = document.getElementsByClassName('programActivityGrid')[document.getElementsByClassName('programActivityGrid').length-1].id; var totalprogramActivityGrid = parseInt(programActivityLastId.substring(programActivityLastId.length-1,programActivityLastId.length)); //var totalprogramActivityGrid = (document.getElementsByClassName('programActivityGrid')).length; var existingProgramIdsArray = []; var refNode = document.getElementsByClassName('programActivityGrid')[document.getElementsByClassName('programActivityGrid').length-1]; //var refNode = document.getElementsByClassName('programActivityGrid')[0 //var refProgramActivitesTextNode = document.getElementsByClassName("programActivitySelectGrid")[document.getElementsByClassName('programActivityGrid').length-1]; var refProgramActivitesTextNode = document.getElementById('programActivity'+totalprogramActivityGrid) var attr ='programActivity'+(totalprogramActivityGrid+1); var textAttr = 'programAndActivities'+(totalprogramActivityGrid); var i,j; var options=''; var programNotSelected = false; //Checking whether Program selected for before activity //alert(document.getElementById('program_'+(totalprogramActivityGrid-1))); if(document.getElementById('program_'+(totalprogramActivityGrid-1))){ for(i=0;i<document.getElementById('program_'+(totalprogramActivityGrid-1)).options.length;i++){ if(document.getElementById('program_'+(totalprogramActivityGrid-1)).options[i].selected && document.getElementById('program_'+(totalprogramActivityGrid-1)).options[i].value === 'SelectProgram'){ programNotSelected = true; } } } if(programNotSelected){ alert('Please Select a Program before adding a new Program Activities') }else{ //Eliminating already selected Programs in select option for new program activity for(j=1;j<totalprogramActivityGrid;j++){ if(document.getElementById('program_'+j)){ for(i=0;i<document.getElementById('program_'+j).options.length;i++){ if(document.getElementById('program_'+j).options[i].value !== 'SelectProgram'){ if(document.getElementById('program_'+j).options[i].selected && !existingProgramIdsArray.includes(document.getElementById('program_'+j).options[i].value)){ existingProgramIdsArray.push(document.getElementById('program_'+j).options[i].value); } } } } } var activitySelect = document.createElement('select'); var activitySelectOption = document.createElement('option'); var programActivity = document.createElement('div'); programActivity.setAttribute("class","slds-grid programActivitySelectGrid"); var ProgramDiv = document.createElement('div'); ProgramDiv.setAttribute("class","slds-p-horizontal--small slds-size--6-of-12 slds-small-size--6-of-12 slds-medium-size--6-of-12 slds-large-size--6-of-12"); programActivity.appendChild(ProgramDiv); var ProgramDivPar = document.createElement('p'); ProgramDivPar.setAttribute("class","vAlign"); ProgramDiv.appendChild(ProgramDivPar); var programSelect = document.createElement('select'); programSelect.setAttribute("id","program_"+totalprogramActivityGrid); // programSelect.setAttribute("onchange","dependentActivate"); programSelect.onchange = function(events) { console.log(events.target.id); var currentSelectedProgramId = events.target.id helper.dependentActivities(component,events); //clearing the Current Select Option Before loading dependent activity option document.getElementById('programActivites_'+currentSelectedProgramId.substring(currentSelectedProgramId.indexOf('_')+1,currentSelectedProgramId.length)).innerHTML = ''; // enabling the picklist document.getElementById('programActivites_'+currentSelectedProgramId.substring(currentSelectedProgramId.indexOf('_')+1,currentSelectedProgramId.length)).removeAttribute("disabled"); //Adding Program Dependent Activities var activitySelectedsOption = document.createElement('option'); activitySelectedsOption.value = 'SelectActivity'; activitySelectedsOption.text = 'Select Activity'; //programSelect.add(programSelectOption); document.getElementById('programActivites_'+currentSelectedProgramId.substring(currentSelectedProgramId.indexOf('_')+1,currentSelectedProgramId.length)).add(activitySelectedsOption); //alert(component.get("v.programDependentsActivities")); if(typeof component.get("v."+programDependentsActivities) !== 'undefined'){ for(i=0;i<component.get("v."+programDependentsActivities).length;i++){ if(component.get("v.activityType") === component.get("v."+programDependentsActivities)[i].Activity_Type__c ){ var activitySelectedOption = document.createElement('option'); activitySelectedOption.value = component.get('v.programDependentsActivities')[i].Id; activitySelectedOption.text = component.get('v.programDependentsActivities')[i].Name; activitySelectedOption.className = 'option'; //programSelect.add(programSelectOption); document.getElementById('programActivites_'+currentSelectedProgramId.substring(currentSelectedProgramId.indexOf('_')+1,currentSelectedProgramId.length)).add(activitySelectedOption); } } } } var programSelectOption = document.createElement('option'); programSelectOption.value = 'SelectProgram'; programSelectOption.text = 'Select Program'; //programSelectOption.selected = 'true'; programSelect.add(programSelectOption); //Adding Program Picklist values for(i=0;i<component.get('v.programList').length;i++){ var programSelectOption = document.createElement('option'); programSelectOption.value = component.get('v.programList')[i].Program_SFID__c; programSelectOption.text = component.get('v.programList')[i].Program_SFID__r.Name; if(existingProgramIdsArray.includes(component.get('v.programList')[i].Program_SFID__c)){ programSelectOption.disabled = true; } for(j=0;j<component.get('v.deletedProgramList').length;j++){ if(component.get('v.deletedProgramList')[j] === component.get('v.programList')[i].Program_SFID__c){ programSelectOption.disabled = false; } } //programSelectOption.disabled = existingProgramIdsArray.includes(component.get('v.programList')[i].Program_SFID__c) ? True : False ; programSelect.add(programSelectOption); } ProgramDivPar.appendChild(programSelect); var ActivityDiv = document.createElement('div'); ActivityDiv.setAttribute("class","slds-p-horizontal--small slds-size--6-of-12 slds-small-size--6-of-12 slds-medium-size--6-of-12 slds-large-size--6-of-12"); programActivity.appendChild(ActivityDiv); var ActivityDivPar = document.createElement('p'); ActivityDivPar.setAttribute("class","vAlign"); ActivityDiv.appendChild(ActivityDivPar); activitySelect.setAttribute("id","programActivites_"+totalprogramActivityGrid); // programSelect.setAttribute("onchange","dependentActivate"); activitySelect.onclick = function(eventss) { console.log('event'); helper.setMultipleAttributeToSelectdynamically(component,eventss); } activitySelectOption.value = 'SelectActivity'; activitySelectOption.text = 'Select Activity'; activitySelect.add(activitySelectOption); activitySelect.setAttribute("disabled","true"); ActivityDivPar.appendChild(activitySelect); //refNode.parentNode.insertBefore(programActivity,refNode.nextSibling); //document.getElementById('programAndActivities'+totalprogramActivityGrid).innerHTML = ''; document.getElementById('programActivity'+totalprogramActivityGrid).appendChild(programActivity) var el = document.createElement("div") el.setAttribute("id",attr); el.setAttribute("class","programActivityGrid"); refNode.parentNode.insertBefore(el,refNode.nextSibling); var e2 = document.createElement("div") e2.setAttribute("id",textAttr); refProgramActivitesTextNode.appendChild(e2); } }, addNonProgramActivities : function(component,event,helper){ var programDependentsActivities = 'programDependentsActivities'; var programActivityLastId = document.getElementsByClassName('nonprogramActivityGrid')[document.getElementsByClassName('nonprogramActivityGrid').length-1].id; var totalprogramActivityGrid = parseInt(programActivityLastId.substring(programActivityLastId.length-1,programActivityLastId.length)); //var totalprogramActivityGrid = (document.getElementsByClassName('nonprogramActivityGrid')).length; var existingProgramIdsArray = []; var refNode = document.getElementsByClassName('nonprogramActivityGrid')[document.getElementsByClassName('nonprogramActivityGrid').length-1]; //var refNode = document.getElementsByClassName('nonprogramActivityGrid')[0 //var refProgramActivitesTextNode = document.getElementsByClassName("programActivitySelectGrid")[document.getElementsByClassName('nonprogramActivityGrid').length-1]; var refProgramActivitesTextNode = document.getElementById('nonprogramActivity'+totalprogramActivityGrid) var attr ='nonprogramActivity'+(totalprogramActivityGrid+1); var textAttr = 'nonprogramAndActivities'+(totalprogramActivityGrid); var i,j; var options=''; var programNotSelected = false; //Checking whether Program selected for before activity if(document.getElementById('nonprogram_'+(totalprogramActivityGrid-1))){ for(i=0;i<document.getElementById('nonprogram_'+(totalprogramActivityGrid-1)).options.length;i++){ if(document.getElementById('nonprogram_'+(totalprogramActivityGrid-1)).options[i].selected && document.getElementById('nonprogram_'+(totalprogramActivityGrid-1)).options[i].value === 'SelectProgram'){ programNotSelected = true; } } } if(programNotSelected){ alert('Please Select a Non-Program before adding a new Non-Program Activities') }else{ //Eliminating already selected Programs in select option for new program activity for(j=1;j<totalprogramActivityGrid;j++){ if(document.getElementById('nonprogram_'+j)){ for(i=0;i<document.getElementById('nonprogram_'+j).options.length;i++){ if(document.getElementById('nonprogram_'+j).options[i].value !== 'SelectProgram'){ if(document.getElementById('nonprogram_'+j).options[i].selected && !existingProgramIdsArray.includes(document.getElementById('nonprogram_'+j).options[i].value)){ existingProgramIdsArray.push(document.getElementById('nonprogram_'+j).options[i].value); } } } } } var activitySelect = document.createElement('select'); var activitySelectOption = document.createElement('option'); var programActivity = document.createElement('div'); programActivity.setAttribute("class","slds-grid nonprogramActivitySelectGrid"); var ProgramDiv = document.createElement('div'); ProgramDiv.setAttribute("class","slds-p-horizontal--small slds-size--6-of-12 slds-small-size--6-of-12 slds-medium-size--6-of-12 slds-large-size--6-of-12"); programActivity.appendChild(ProgramDiv); var ProgramDivPar = document.createElement('p'); ProgramDivPar.setAttribute("class","vAlign"); ProgramDiv.appendChild(ProgramDivPar); var programSelect = document.createElement('select'); programSelect.setAttribute("id","nonprogram_"+totalprogramActivityGrid); // programSelect.setAttribute("onchange","dependentActivate"); programSelect.onchange = function(events) { console.log(events.target.id); var currentSelectedProgramId = events.target.id helper.dependentActivities(component,events); //clearing the Current Select Option Before loading dependent activity option document.getElementById('nonprogramActivites_'+currentSelectedProgramId.substring(currentSelectedProgramId.indexOf('_')+1,currentSelectedProgramId.length)).innerHTML = ''; // enabling the picklist document.getElementById('nonprogramActivites_'+currentSelectedProgramId.substring(currentSelectedProgramId.indexOf('_')+1,currentSelectedProgramId.length)).removeAttribute("disabled"); //Adding Program Dependent Activities var activitySelectedsOption = document.createElement('option'); activitySelectedsOption.value = 'SelectActivity'; activitySelectedsOption.text = 'Select Activity'; //programSelect.add(programSelectOption); document.getElementById('nonprogramActivites_'+currentSelectedProgramId.substring(currentSelectedProgramId.indexOf('_')+1,currentSelectedProgramId.length)).add(activitySelectedsOption); //alert(component.get("v.programDependentsActivities")); if(typeof component.get("v."+programDependentsActivities) !== 'undefined'){ for(i=0;i<component.get("v."+programDependentsActivities).length;i++){ var activitySelectedOption = document.createElement('option'); activitySelectedOption.value = component.get('v.programDependentsActivities')[i].Id; activitySelectedOption.text = component.get('v.programDependentsActivities')[i].Name; activitySelectedOption.className = 'option'; //programSelect.add(programSelectOption); document.getElementById('nonprogramActivites_'+currentSelectedProgramId.substring(currentSelectedProgramId.indexOf('_')+1,currentSelectedProgramId.length)).add(activitySelectedOption); } } } var programSelectOption = document.createElement('option'); programSelectOption.value = 'SelectProgram'; programSelectOption.text = 'Select Program'; programSelectOption.selected = 'true'; programSelect.add(programSelectOption); //Adding Non-Program Picklist values for(i=0;i<component.get('v.nonProgramList').length;i++){ var programSelectOption = document.createElement('option'); programSelectOption.value = component.get('v.nonProgramList')[i].Id; programSelectOption.text = component.get('v.nonProgramList')[i].Name; if(existingProgramIdsArray.includes(component.get('v.nonProgramList')[i].Id)){ programSelectOption.disabled = true; } for(j=0;j<component.get('v.deletedNonProgramList').length;j++){ if(component.get('v.deletedNonProgramList')[j] === component.get('v.nonProgramList')[i].Id){ programSelectOption.disabled = false; } } //programSelectOption.disabled = existingProgramIdsArray.includes(component.get('v.programList')[i].Program_SFID__c) ? True : False ; programSelect.add(programSelectOption); } ProgramDivPar.appendChild(programSelect); var ActivityDiv = document.createElement('div'); ActivityDiv.setAttribute("class","slds-p-horizontal--small slds-size--6-of-12 slds-small-size--6-of-12 slds-medium-size--6-of-12 slds-large-size--6-of-12"); programActivity.appendChild(ActivityDiv); var ActivityDivPar = document.createElement('p'); ActivityDivPar.setAttribute("class","vAlign"); ActivityDiv.appendChild(ActivityDivPar); activitySelect.setAttribute("id","nonprogramActivites_"+totalprogramActivityGrid); // programSelect.setAttribute("onchange","dependentActivate"); activitySelect.onclick = function(eventss) { console.log('event'); helper.setMultipleAttributeToSelectdynamically(component,eventss); } activitySelectOption.value = 'SelectActivity'; activitySelectOption.text = 'Select Activity'; activitySelect.add(activitySelectOption); activitySelect.setAttribute("disabled","true"); ActivityDivPar.appendChild(activitySelect); //refNode.parentNode.insertBefore(programActivity,refNode.nextSibling); //document.getElementById('nonprogramAndActivities1'+totalprogramActivityGrid).innerHTML = ''; document.getElementById('nonprogramActivity'+totalprogramActivityGrid).appendChild(programActivity) var el = document.createElement("div") el.setAttribute("id",attr); el.setAttribute("class","nonprogramActivityGrid"); refNode.parentNode.insertBefore(el,refNode.nextSibling); var e2 = document.createElement("div") e2.setAttribute("id",textAttr); refProgramActivitesTextNode.appendChild(e2); } }, toGrowerList : function(component,event){ if(event.target.id){ var cmpEvent = component.getEvent("redirectToGrowerList"); cmpEvent.setParams({ "accountId" : event.target.id, }); cmpEvent.fire(); } else{ var growersEvent = component.getEvent("redirectToGrowers"); growersEvent.setParams({ "accountId" : event.target.id, }); growersEvent.fire(); } }, toDealerList : function(component,event){ var dealersEvent = component.getEvent("redirectToDelaerList"); dealersEvent.setParams({ "accountId" : event.target.id, }); dealersEvent.fire(); }, loadCalendar : function(component,event){ /*var calEvent = $A.get("e.c:Frontier_Touchpoint_Planning_Calendar_Event"); calEvent.setParams({ "handlerName" :'calendar' }); calEvent.fire();*/ localStorage.setItem("justOnce", "false"); var urlEvent = $A.get("e.force:navigateToURL"); urlEvent.setParams({ "url": "/one/one.app#/n/Sales_Rep_Touchpoint_Calendar" }); urlEvent.fire(); }, saveTouchPoint : function(component,event,helper){ helper.setProgramAndActivityValues(component,event,'Not Scheduled'); }, scheduleTouchPoint : function(component,event,helper){ helper.setProgramAndActivityValues(component,event,'Scheduled'); }, cancelTouchpoint : function(component,event,helper){ //helper.setProgramAndActivityValues(component,event,'Cancelled'); helper.showModel(component,event,'Cancelled'); }, completeTouchpoint : function(component,event,helper){ //helper.setProgramAndActivityValues(component,event,'Completed'); helper.showModel(component,event,'Completed'); }, cancelORCompleteTouchpoint : function(component,event,helper){ console.log(component.get("v.popUpHeader").split(' ')[0]); if(component.get("v.popUpHeader").split(' ')[0] === 'Cancel'){ helper.setProgramAndActivityValues(component,event,'Cancelled'); }else if(component.get("v.popUpHeader").split(' ')[0] === 'Complete'){ helper.setProgramAndActivityValues(component,event,'Completed'); } helper.closeModel(component); }, closePopUp : function(component,event,helper){ //console.log(component.get("v.popUpHeader").split(' ')[0]); //helper.setProgramAndActivityValues(component,event,) helper.closeModel(component); }, selecActivityDelete : function(component,event,helper){ helper.deleteActivity(component,event); }, selectNonActivityDelete : function(component,event,helper){ helper.deleteNonProgramActivity(component,event); }, editProgramActivity :function(component,event,helper){ helper.addActivities(component,event); }, editNonProgramActivity :function(component,event,helper){ helper.addNonProgActivities(component,event); }, deleteProgram : function(component,event,helper){ helper.minusProgram(component,event); }, deleteNonProgram : function(component,event,helper){ helper.minusNonPrograms(component,event); }, deleteNonProgramActivity : function(component,event,helper){ var targetId = event.target.id; document.getElementById('nonActivity'+targetId).remove() }, addNonProgramActivity : function(component,event,helper){ document.getElementById('nonProgramActivityDiv').classList = 'slds-hide'; document.getElementById('nonProgramActivitySelect').classList.remove('slds-hide'); }, cancel : function(component,event,helper){ /*if(component.get("v.growerAcc").split('/').length === 3){ //touchPointId = component.get("v.growerAcc").split('/')[3]; var cmpEvent = component.getEvent("redirectToDealerDetail"); console.log('growId=>'+component.get("v.growerAcc").split('/')[1]); cmpEvent.setParams({ "accIdSapIdAccCommId" : component.get("v.growerAcc").split('/')[1], "tabScopeNo" : '3', "componentName":"c:Frontier_GrowerAccount_ActivitiesList" }); cmpEvent.fire(); }else if(component.get("v.growerAcc").split('/').length === 6){ var cmpEvent = component.getEvent("redirectToDealerDetail"); console.log('growId=>'+component.get("v.growerAcc").split('/')[1]); cmpEvent.setParams({ "accIdSapIdAccCommId" : component.get("v.growerAcc").split('/')[1]+','+component.get("v.growerAcc").split('/')[0], "tabScopeNo" : '3', //"componentName":component.get("v.growerAcc").split('/')[5], "componentName" : 'c:Frontier_GrowerAccount_Program' }); cmpEvent.fire(); }else if(component.get("v.growerAcc").split('/').length === 6){ var cmpEvent = component.getEvent("redirectToDealerDetail"); console.log('growId=>'+component.get("v.growerAcc").split('/')[1]); cmpEvent.setParams({ "accIdSapIdAccCommId" : component.get("v.growerAcc").split('/')[1]+','+component.get("v.growerAcc").split('/')[0], "tabScopeNo" : '3', //"componentName":component.get("v.growerAcc").split('/')[5], "componentName" : 'c:Frontier_GrowerAccount_Program' }); cmpEvent.fire(); }*/ helper.redirectiontoList(component,event); }, selectActivitiesByType : function(component,event,helper){ var selectedActivityId = document.getElementById(event.target.id).value; var selectedActivityIndex = (document.getElementById(event.target.id).parentNode.id).substring((document.getElementById(event.target.id).parentNode.id).indexOf('_')+1,(document.getElementById(event.target.id).parentNode.id).length); var selectedProgramId =''; var i; var activityType=''; //Getting Program Id to retrive the related activites from Activity Map for(i=0;i<document.getElementById('program_'+selectedActivityIndex).length;i++){ if(document.getElementById('program_'+selectedActivityIndex).options[i].selected){ selectedProgramId = document.getElementById('program_'+selectedActivityIndex).options[i].value; } } //Getting selected visit Type for(i=0;i<component.get("v.programIdActivityMap")[selectedProgramId].length;i++){ if(component.get("v.programIdActivityMap")[selectedProgramId][i].Id === selectedActivityId){ activityType = component.get("v.programIdActivityMap")[selectedProgramId][i].Activity_Type__c; } } //Adding related Touchpoint Type options to Program related Activities document.getElementById('programActivites_'+selectedActivityIndex).innerHTML =''; var activitySelectOption = document.createElement('option'); activitySelectOption.value = 'SelectActivity'; activitySelectOption.text = 'Select Activity'; document.getElementById('programActivites_'+selectedActivityIndex).add(activitySelectOption); for(i=0;i<component.get("v.programIdActivityMap")[selectedProgramId].length;i++){ if(component.get("v.programIdActivityMap")[selectedProgramId][i].Activity_Type__c === activityType){ var activitySelectOption = document.createElement('option'); activitySelectOption.value = component.get("v.programIdActivityMap")[selectedProgramId][i].Id; activitySelectOption.text = component.get("v.programIdActivityMap")[selectedProgramId][i].Name; activitySelectOption.className = "option"; if(component.get("v.programIdActivityMap")[selectedProgramId][i].Id === selectedActivityId){ activitySelectOption.selected = "true"; } document.getElementById('programActivites_'+selectedActivityIndex).add(activitySelectOption); } } component.set('v.activityType',activityType); //Setting touchpoint Type picklist value var opts = [ {label:activityType , value: activityType} ]; component.find('touchPointType').set('v.options',opts); }, selectNonActivitiesByType : function(component,event,helper){ var selectedActivityId = document.getElementById(event.target.id).value; var selectedActivityIndex = (document.getElementById(event.target.id).parentNode.id).substring((document.getElementById(event.target.id).parentNode.id).indexOf('_')+1,(document.getElementById(event.target.id).parentNode.id).length); var selectedProgramId =''; var i; var activityType=''; //Getting Program Id to retrive the related activites from Activity Map for(i=0;i<document.getElementById('nonprogram_'+selectedActivityIndex).length;i++){ if(document.getElementById('nonprogram_'+selectedActivityIndex).options[i].selected){ selectedProgramId = document.getElementById('nonprogram_'+selectedActivityIndex).options[i].value; } } //Getting selected visit Type for(i=0;i<component.get("v.programIdActivityMap")[selectedProgramId].length;i++){ if(component.get("v.programIdActivityMap")[selectedProgramId][i].Id === selectedActivityId){ activityType = component.get("v.programIdActivityMap")[selectedProgramId][i].Activity_Type__c; } } //Adding related Touchpoint Type options to Program related Activities document.getElementById('nonprogramActivites_'+selectedActivityIndex).innerHTML =''; var activitySelectOption = document.createElement('option'); activitySelectOption.value = 'SelectActivity'; activitySelectOption.text = 'Select Activity'; document.getElementById('nonprogramActivites_'+selectedActivityIndex).add(activitySelectOption); for(i=0;i<component.get("v.programIdActivityMap")[selectedProgramId].length;i++){ if(component.get("v.programIdActivityMap")[selectedProgramId][i].Activity_Type__c === activityType){ var activitySelectOption = document.createElement('option'); activitySelectOption.value = component.get("v.programIdActivityMap")[selectedProgramId][i].Id; activitySelectOption.text = component.get("v.programIdActivityMap")[selectedProgramId][i].Name; activitySelectOption.className = "option"; if(component.get("v.programIdActivityMap")[selectedProgramId][i].Id === selectedActivityId){ activitySelectOption.selected = "true"; } document.getElementById('nonprogramActivites_'+selectedActivityIndex).add(activitySelectOption); } } component.set('v.activityType',activityType); //Setting touchpoint Type picklist value var opts = [ {label:activityType , value: activityType} ]; component.find('touchPointType').set('v.options',opts); } })<file_sep>/src/aura/Frontier_AccountSearchBar/Frontier_AccountSearchBarController.js ({ searchKeyChange: function(component, event){ var myEvent = $A.get("e.c:Frontier_AccountSearchkey"); myEvent.setParams({"searchKey": event.target.value}); console.log("ist event value" + event.target.value); myEvent.fire(); }, onSingleSelectChange:function(component){ var sortEvent = $A.get("e.c:Frontier_AccountSortBy"); var selectCmp = component.find("InputSelectSingle").get("v.value"); console.log("Selected" +selectCmp); sortEvent.setParams({"sortbyValue": selectCmp}); sortEvent.fire();} });<file_sep>/src/aura/Frontier_Dealer_Grower_ProgramChart/Frontier_Dealer_Grower_ProgramChartController.js ({ loadPgmBudget : function(component, event, helper) { console.log('Inside chart'); helper.loadPgmChart(component,event,helper); } })<file_sep>/src/aura/Frontier_CalenderMasterComponent/Frontier_CalenderMasterComponentController.js ({ doInit : function(component, event, helper) { $A.createComponent("c:Frontier_Touchpoint_Planning_Calender", { }, function(touchPoint){ var comp = component.find("calendarMaster"); comp.set("v.body",touchPoint); }); }, handleCompNavigation : function(component, event, helper){ var urlEvent = $A.get("e.force:navigateToURL"); urlEvent.setParams({ "url": "#/n/Sales_Rep_Touchpoint_Calendar" }); urlEvent.fire(); var ids = ''+'/'+'0012C00000AsKGzQAN'+','+'a0g2C000000UynxQAC'+'/'; $A.createComponent("c:Frontier_GrowerAccount_UpdateTouchPoint", { "clickdate":'2017-05-10', "newUpdateStatus":'new', "growerAcc": ids, "isFromCalendar":true, "isReadOnly":false }, function(touchPoint){ var comp = component.find("calendarMaster"); comp.set("v.body",touchPoint); }); } })<file_sep>/src/aura/Frontier_PopUp/Frontier_PopUpController.js ({ doInit : function(component, event, helper) { var message = component.get("v.Message"); console.log("message init" + message); if(message != null && message =="visitrecord"){ component.set("v.Message", "Visit Recorded"); } else if(message != null && message =="followuprecord") component.set("v.Message", "Follow-Up Scheduled"); else if(message != null && message =="E-Mail has been sent") component.set("v.Message", "E-Mail has been sent"); else if(message != null && message =="Program Completed") component.set("v.Message", "Program is successfully completed"); else if(message != null && message =="Program Not Completed") component.set("v.Message", "Program cannot be completed since related activities are not in completed status"); }, showModalBox : function(component, event, helper){ event.preventDefault(); console.log('Page Refresh123'); $A.util.addClass(component.find("backGroundSecId1"), 'slds-hide'); $A.util.addClass(component.find("newAccountSecId1"), 'slds-hide'); if(component.get("v.Message") == "Program is successfully completed"){ var popEvent = $A.get("e.c:Frontier_RefreshProgram"); //popEvent.setParams({"searchKey": event.target.value}); console.log("ist event value" ); popEvent.fire(); } //document.getElementById("backGroundSecId1").style.display = "none"; // document.getElementById("newAccountSecId1").style.display = "none"; }, hideModalBox : function(component, event, helper){ event.preventDefault(); console.log('hideModalBox'); $A.util.addClass(component.find("backGroundSecId1"), 'slds-hide'); $A.util.addClass(component.find("newAccountSecId1"), 'slds-hide'); console.log('&&&&&&&Hide=='+component.get("v.ComponentName")); var compName = component.get("v.ComponentName"); if(compName == 'Frontier_Pgm_Plang_Review'){ console.log('Event Fired above========'); var popUpEvent = $A.get("e.c:Frontier_PopUpCloseEvent"); popUpEvent.fire(); console.log('Event Fired below========'); } else if(component.get("v.Message") == "Program is successfully completed"){ var popEvent = $A.get("e.c:Frontier_RefreshProgram"); //popEvent.setParams({"searchKey": event.target.value}); console.log("ist event value" ); popEvent.fire(); } //document.getElementById("backGroundSecId1").style.display = "none"; // document.getElementById("newAccountSecId1").style.display = "none"; } })<file_sep>/src/aura/Frontier_GrowerAccount_MasterComponent/Frontier_GrowerAccount_MasterComponentHelper.js ({ navigateToGrowerProfile : function(component,event){ console.log('Inside Helper'); //var action = component.get("c.getGrowerAccFarmingDatas"); var growerAccDetail = component.get("v.growerAcc"); var growerAccId = growerAccDetail.split(',')[0]; var groweraccCommId = growerAccDetail.split(',')[2]; //action.setCallback(this, function(response){ //var state = response.getState(); //if (state === "SUCCESS" && !(response.getReturnValue() === 'CalloutError')){ //component.set("v.GrowerDetails" ,response.getReturnValue()); //console.log('Response------------>' + response.getReturnValue()); $A.createComponent( "c:Frontier_GrowerProfileDetails", { "GrowerDetailResponse": '', "growerId":growerAccId, "accCommId":groweraccCommId }, function(newCmp){ //Render the sales order dashboard component to the parent container var cmp = component.find("GrowerProfileSection"); cmp.set("v.body", newCmp); } ); /* $A.createComponent( "c:Frontier_GrowerAccount_RecordTouchPoint", { "GrowerDetailResponse": response.getReturnValue(), "growerId":growerAccId }, function(newCmp){ //Render the sales order dashboard component to the parent container var cmp = component.find("GrowerRecordTouchPointSection"); cmp.set("v.body", newCmp); } );*/ //} /* else if(response.getReturnValue() === 'CalloutError'){ console.log('CalloutError'); } else{ console.log('Call Back Error'); }*/ //}); // $A.enqueueAction(action); }, navigateToPreviousTouchPoint : function(component,event){ var growerAccDetail = component.get("v.growerAcc"); var growerAccId = growerAccDetail.split(',')[0]; var groweraccCommId = growerAccDetail.split(',')[2]; $A.createComponent("c:Frontier_GrowerAccount_PreviousTouchPoints", {label : "", "growerId":growerAccId }, function(PreviousTouchPoint){ console.log('AccountList'); var comp = component.find("previousTouch"); comp.set("v.body",PreviousTouchPoint); } ); }, navigateToGrowerFarmSize : function(component,event){ var growerAccDetail = component.get("v.growerAcc"); var growerAccId = growerAccDetail.split(',')[0]; var groweraccCommId = growerAccDetail.split(',')[2]; console.log('Frontier_GrowerAccount_FarmSize'); $A.createComponent("c:Frontier_GrowerAccount_FarmSize", { "growerAccId":growerAccId }, function(GrowerFarmSize){ console.log('growerFarmSize'); var comp = component.find("growerFarmSize"); comp.set("v.body",GrowerFarmSize); } ); }, navigateToGrowerAccountSales : function(component,event){ var growerAccDetail = component.get("v.growerAcc"); var growerAccId = growerAccDetail.split(',')[0]; var groweraccCommId = growerAccDetail.split(',')[2]; $A.createComponent("c:Frontier_GrowerAccount_Sales_Master", { "growerAccId":growerAccId }, function(GrowerAccountSales){ console.log('growerSales'); var comp = component.find("growerSales"); comp.set("v.body",GrowerAccountSales); } ); } })<file_sep>/src/aura/Frontier_AccountDashboard_MasterComponent/Frontier_AccountDashboard_MasterComponentController.js ({ doInit : function(component, event, helper) { //var crop='Corn'; var season='SUMMER'; var accType='Partner'; helper.getPicklistValues(component,event,helper); helper.getchartdetails(component,event,helper,season,accType); }, changeseasonCrop : function(component,event,helper){ //var crop= component.find("cropDetails").get("v.value"); var season=component.find("sellingSeason").get("v.value"); var accType =component.find("accType").get("v.value"); helper.getchartdetails(component,event,helper,season,accType); } })<file_sep>/src/aura/Frontier_AccountList/Frontier_AccountListHelper.js ({ searchEmployee : function(component,event, helper, page1,searchKey) { var acId = component.find("v.accountId"); var page = page1 || 1; var action = component.get("c.getAccounts"); console.log("================= Inside searchEmployee" + searchKey); console.log("================= Inside page" + page); action.setParams({ "searchKey": searchKey, pageNumber : page, pageSize : component.get("v.pageSize"), accId : acId }); action.setCallback(this, function(response) { if(response.getState() === "SUCCESS"){ var accounts = []; component.set("v.page",page); var accountList = response.getReturnValue(); component.set("v.pages",Math.ceil((JSON.parse(accountList[0]))/component.get("v.pageSize"))); component.set("v.total",JSON.parse(accountList[0])); accounts = JSON.parse(accountList[1]); console.log("Account search employee" + accounts); component.set("v.accounts", accounts); helper.gotoComponent(component, event, helper); } }); $A.enqueueAction(action); }, navigateToAccountDetail : function(component,event) { console.log("c:Frontier_AccountDetailViewComponent"); var uniqueId = event.target.id; console.log('accountId,Sap Id,Accmu'+uniqueId); var accountId = uniqueId.split(',')[0]; var sapId= uniqueId.split(',')[1]; var accCommunicationId = uniqueId.split(',')[2]; /*$A.createComponent( "c:Frontier_AccountDetailViewComponent", { accId: accountId, sapId: sapId, accCommunicationId: accCommunicationId }, function(newCmp){ var cmp = component.find("AccountDetail"); cmp.set("v.body", []); cmp.set("v.body", newCmp); } );*/ $A.createComponent( "c:Frontier_GrowerAccount_Overview", { "growerAcc" : accountId+','+sapId+','+accCommunicationId, "role" : component.get("v.accounts")[0].roleDesc, "heading" :'dealer', "accountAddressInfo":uniqueId.split(',')[3]+','+uniqueId.split(',')[4] }, function(newCmp){ var cmp = component.find("AccountDetail"); cmp.set("v.body", []); cmp.set("v.body", newCmp); } ); }, sortbyRadl: function(component,page1,sortbyValue) { var page = page1 || 1; console.log("Inside sort helper"); console.log("Inside sort page" + page); var action = component.get("c.sortBy"); action.setParams({ "sortbyValue": sortbyValue, pageNumber : page, pageSize : component.get("v.pageSize") }); action.setCallback(this, function(response) { var accounts = []; component.set("v.page",page); var accountList = response.getReturnValue(); component.set("v.pages",Math.ceil((JSON.parse(accountList[0]))/component.get("v.pageSize"))); component.set("v.total",JSON.parse(accountList[0])); accounts = JSON.parse(accountList[1]); console.log("Account search employee" + accounts); component.set("v.accounts", accounts); }); $A.enqueueAction(action); }, showPopUp: function(component,event,message){ console.log("Inside showPop"); $A.createComponent("c:Frontier_PopUp", {Message : message}, function(newComp){ console.log('pop'); var comp = component.find("followpopup"); comp.set("v.body",newComp); }); }, toGrowerCount : function(component,event){ var uniqueId = event.target.id; console.log('accountId,Sap Id,Accmu'+uniqueId); var accountId = uniqueId.split(',')[0]; $A.createComponent("c:Frontier_GrowerAccountList", { accountId: accountId }, function(GrowerList){ console.log('AccountList'); var comp = component.find("AccountDetail"); comp.set("v.body",GrowerList); } ); }, toGrowerList : function(component,event){ var accountId = event.getParam("accountId"); $A.createComponent("c:Frontier_GrowerAccountList", { accountId: accountId }, function(GrowerList){ console.log('AccountList'); var comp = component.find("AccountDetail"); comp.set("v.body",GrowerList); } ); }, gotoComponent : function(component,event,helper){ var sPageURL,myprogramDetails,accountId,programId,accomId,roleDesc; if(window.location.hash.split('=')){ sPageURL = window.location.hash.split('='); if(sPageURL[1]){ myprogramDetails = sPageURL[1].split('-'); roleDesc = myprogramDetails[1]; accountId = myprogramDetails[2]; programId = myprogramDetails[3]; accomId = myprogramDetails[4]; if(accountId){ $A.createComponent( "c:Frontier_GrowerAccount_Overview", { "growerAcc" : accountId+','+''+','+accomId+','+programId, "role" : myprogramDetails[1], "heading" :'dealer', "handlerName": myprogramDetails[0] }, function(newCmp){ var cmp = component.find("AccountDetail"); cmp.set("v.body", []); cmp.set("v.body", newCmp); } ); } } } } });<file_sep>/src/aura/Frontier_AccountDashboard_MasterComponent/Frontier_AccountDashboard_MasterComponentHelper.js ({ getPicklistValues : function(component,event,helper) { var action = component.get("c.getMyProgramsChart"); var programId = null; var dealerId = null; action.setParams({ programId :programId, dealerId : dealerId, isDashboard : 'True' }); var inputsel = component.find("sellingSeason"); //var cropsel = component.find("cropDetails"); var accSelect = component.find("accType"); var opts=[]; //var crops=[]; var accType=[]; action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ var retResponse = (JSON.parse(response.getReturnValue())); for(var i=0;i< retResponse.sellingSeasontypes.length;i++){ opts.push({"class": "optionClass", label: retResponse.sellingSeasontypes[i], value:retResponse.sellingSeasontypes[i]}); } /* for(var i=0;i< retResponse.croptypes.length;i++){ crops.push({"class": "optionClass", label: retResponse.croptypes[i], value:retResponse.croptypes[i]}); }*/ for(var i=0;i< retResponse.accTypes.length;i++){ accType.push({"class": "optionClass", label: retResponse.accTypes[i], value:(retResponse.accTypes[i] == 'Dealer'?'Partner': (retResponse.accTypes[i] == 'Grower'?'Customer':'All Accounts'))}); } inputsel.set("v.options",opts); //cropsel.set("v.options",crops); accSelect.set("v.options",accType); } }); $A.enqueueAction(action); }, getchartdetails : function(component,event,helper,season,accType){ $A.createComponent( "c:Frontier_AccountByRadlChart", { //"crop" : crop, "season" : season, "accType" : accType }, function(newCmp){ var cmp = component.find("accountRADL"); cmp.set("v.body", []); cmp.set("v.body", newCmp); } ); $A.createComponent( "c:Frontier_RadlCoveragechart", { //"crop" : crop, "season" : season, "accType" : accType }, function(newCmp){ var cmp = component.find("accountRADLCoverage"); cmp.set("v.body", []); cmp.set("v.body", newCmp); } ); $A.createComponent( "c:Frontier_TouchpointsbyMonth_Chart", { //"crop" : crop, "season" : season, "accType" : accType }, function(newCmp){ var cmp = component.find("touchpointByMonthChart"); cmp.set("v.body", []); cmp.set("v.body", newCmp); } ); $A.createComponent( "c:Frontier_TouchpointbyTypeChart", { //"crop" : crop, "season" : season, "accType" : accType }, function(newCmp){ var cmp = component.find("touchpointByTypeChart"); cmp.set("v.body", []); cmp.set("v.body", newCmp); } ); /* $A.createComponent( "c:Frontier_AccountDashborad_DealerList", { "crop" : crop, "season" : season, "accType" : accType }, function(newCmp){ var cmp = component.find("dealerList"); cmp.set("v.body", []); cmp.set("v.body", newCmp); } );*/ } })<file_sep>/src/aura/Frontier_GrowerAccount_Overview/Frontier_GrowerAccount_OverviewController.js ({ doInit : function(component, event, helper){ if(component.get("v.handlerName") === 'activityView'){ helper.navigateToTabComponents(component,event,"c:Frontier_GrowerAccount_Program","tab-scoped-2"); helper.toggleSelectedTabs(component,event,helper,2); }else{ helper.navigateToTabComponents(component,event,"c:Frontier_GrowerAccount_MasterComponent","tab-scoped-1"); } }, toggleTabs : function(component, event, helper) { var accProgramDetails = component.get("v.growerAcc"); var accDet = component.get("v.accountAddressInfo"); console.log("accDet"+accDet); if(accProgramDetails.split(',')[3]){ component.set("v.growerAcc",accProgramDetails.split(',')[0]+','+accProgramDetails.split(',')[1]+','+accProgramDetails.split(',')[2]) } else if(accProgramDetails.split('/')[1]){ component.set("v.growerAcc",accProgramDetails.split('/')[1]) } //alert((event.target.id).substring(0,(event.target.id).indexOf('_'))); //alert((event.target.id).substring((event.target.id).indexOf('___')+3,(event.target.id).lastIndexOf('___'))); var compName =(event.target.id).substring((event.target.id).indexOf('___')+3,(event.target.id).lastIndexOf('___')); var tabScoped = (event.target.id).substring(0,(event.target.id).indexOf('_')); var i; for(i=1;i<=5;i++){ //alert(component.find('tab-scoped-'+i+'_tab')) $A.util.removeClass( component.find('tab-scoped-'+i+'_tab'),'slds-active'); $A.util.removeClass( component.find('tab-scoped-'+i+'_tab'),'active'); $A.util.removeClass( component.find('tab-scoped-'+i),'slds-show'); $A.util.addClass( component.find('tab-scoped-'+i),'slds-hide'); //$A.util.addClass( component.find('tab-scoped-'+i),'slds-show'); $A.util.removeClass( component.find('tab-scoped-'+i+'__item'),'activeFont'); $A.util.addClass( component.find('tab-scoped-'+i+'__item'),'inactiveFont'); } //$A.util.addClass( component.find((event.target.id).substring(0,(event.target.id).indexOf('_'))+'_tab'),'slds-active'); $A.util.removeClass( component.find((event.target.id).substring(0,(event.target.id).indexOf('_'))),'slds-hide'); $A.util.addClass( component.find((event.target.id).substring(0,(event.target.id).indexOf('_'))),'slds-show'); $A.util.removeClass( component.find((event.target.id).substring(0,(event.target.id).indexOf('_'))+'__item'),'inactiveFont'); $A.util.addClass( component.find((event.target.id).substring(0,(event.target.id).indexOf('_'))+'__item'),'activeFont'); $A.util.addClass( component.find((event.target.id).substring(0,(event.target.id).indexOf('_'))+'_tab'),'active'); if(compName !== 'ta'){ helper.navigateToTabComponents(component,event,compName,tabScoped); } }, navigateToDealerDetail : function (component,event,helper) { console.log(event.getParam("businessRole")); if(event.getParam("componentName") === 'c:Frontier_DealerDetail_MasterComponent' && event.getParam("tabScopeNo") === '1' ){ component.set("v.role",event.getParam("businessRole")); } component.set("v.growerAcc",event.getParam("accIdSapIdAccCommId")); helper.navigateToTabComponents(component,event,event.getParam("componentName"),"tab-scoped-"+event.getParam("tabScopeNo")); helper.toggleSelectedTabs(component,event,helper,event.getParam("tabScopeNo")); }, showSpinner : function (component) { var spinner = component.find('spinner'); $A.util.removeClass(spinner, "xc-hidden"); }, hideSpinner : function (component) { var spinner = component.find('spinner'); $A.util.addClass(spinner, "xc-hidden"); }, navigateToProgramPlanning:function(component,event,helper){ var dealerAccDetail = component.get("v.growerAcc"); var dealerAccId = dealerAccDetail.split(',')[0]; $A.createComponent( "c:Frontier_ProgramPlanning", { dealerId : dealerAccId }, function(newCmp){ var cmp = component.find("programBlock"); cmp.set("v.body",[]); cmp.set("v.body", newCmp); } ); }, })<file_sep>/src/aura/Frontier_SalesOrderbyCrop/Frontier_SalesOrderbyCropController.js ({ loadChart: function() { } });<file_sep>/src/aura/Frontier_GrowerAccount_ActivitiesList/Frontier_GrowerAccount_ActivitiesListController.js ({ doInit : function(component, event, helper) { var page = component.get("v.page") || 1; var ispageChange = false; var isInitialize = true; var accComId = component.get("v.growerAcc").split(',')[2] ? component.get("v.growerAcc").split(',')[2] :''; component.set("v.accComId",accComId); helper.createAccountDetailsComp(component, event); helper.getProgramActivitiesList(component,event,page,ispageChange,isInitialize); }, activitiesPageChange: function(component,event,helper) { var cmpName = event.getParam("compName"); console.log('cmpName' +cmpName); if(cmpName == 'ActivitiesList'){ var page = component.get("v.page") || 1; var direction = event.getParam("direction"); page = direction === "previous" ? (page - 1) : (page + 1); var ispageChange = true; var isInitialize = false; helper.getProgramActivitiesList(component,event,page,ispageChange,isInitialize); } }, sortDirection : function(component,event,helper){ if(event.currentTarget.id != '' && component.get("v.prevId") != '' && component.get("v.prevId") != event.currentTarget.id){ component.set("v.SortBy"+component.get("v.prevId"),"onMouseOut"); } var page = 1; console.log("Event Target"+event.currentTarget.id) if(event.currentTarget.id != ''){ component.set("v.SortBy"+event.currentTarget.id,"onClick"); } var ispageChange = false; var isInitialize = false; component.set("v.prevId",event.currentTarget.id); helper.getProgramActivitiesList(component,event,page,ispageChange,isInitialize); }, scheduleTouchpoint : function(component,event,helper){ var i; var programIds=''; var activitiesIds=''; var allActivitySelectedOfSameType=true; var activitySelectedArray = []; //Validating all Activities are selected with same Type for(i=0;i<document.getElementsByClassName('checkboxClass').length;i++){ if(document.getElementsByClassName('checkboxClass')[i].checked){ if(!activitySelectedArray.includes(document.getElementById('ActivityType_'+i).innerHTML)){ if(document.getElementById('ActivityType_'+i).innerHTML === '') { activitySelectedArray.push(document.getElementById('ActivityType_'+i).innerHTML); }else{ activitySelectedArray.push(document.getElementById('ActivityType_'+i).innerHTML); } } } } if(activitySelectedArray.length > 1){ allActivitySelectedOfSameType=false; } if(allActivitySelectedOfSameType) { for(i=0;i<document.getElementsByClassName('checkboxClass').length;i++){ if(document.getElementsByClassName('checkboxClass')[i].checked){ //alert(document.getElementsByClassName('checkboxClass')[i].id); if(!programIds.includes((document.getElementsByClassName('checkboxClass')[i].id).split('/')[0])){ programIds +=','+(document.getElementsByClassName('checkboxClass')[i].id).split('/')[0]; } activitiesIds += ','+(document.getElementsByClassName('checkboxClass')[i].id).split('/')[1]; //alert(activitiesIds); } } programIds = programIds.substring(1,activitiesIds.length); activitiesIds = activitiesIds.substring(1,activitiesIds.length); console.log(programIds+'/'+component.get("v.growerAcc")+'/'+activitiesIds); //alert(activitiesIds); var cmpEvent = component.getEvent("redirectToDealerDetail"); cmpEvent.setParams({ "accIdSapIdAccCommId" : programIds+'/'+component.get("v.growerAcc")+'/'+activitiesIds, "tabScopeNo" : '4', "componentName":"c:Frontier_GrowerAccount_UpdateTouchPoint", "newUpdateStatus":'New' }); cmpEvent.fire(); } else { alert('Please Select All Activities of Same Type') } }, cancelActivity : function(component,event,helper){ console.log('cancel'); helper.cancelSelectedActivity(component,event,helper); var page = component.get("v.page") || 1; var ispageChange = false; var isInitialize = true; component.set("v.usersInitialLoad",true); helper.getProgramActivitiesList(component,event,page,ispageChange,isInitialize); }, cancelTouchpoint : function(component,event,helper){ var i; var activitiesIds=''; for(i=0;i<document.getElementsByClassName('checkboxClass').length;i++){ document.getElementsByClassName('checkboxClass')[i].checked = false; } }, pgmEventNavigation: function(component,event,helper){ helper.navigateToProgramDetail(component,event,helper); }, individualScheduleTouchpoint : function(component,event,helper){ var i; var programIds=''; var activitiesIds=''; //alert(document.getElementsByClassName('checkboxClass')[event.target.id].id) /*if(!programIds.includes((document.getElementsByClassName('checkboxClass')[event.target.id].id).split('/')[0])){ programIds +=','+(document.getElementsByClassName('checkboxClass')[event.target.id].id).split('/')[0]; }*/ activitiesIds = (document.getElementsByClassName('checkboxClass')[event.target.id].id).split('/')[1]; programIds = (document.getElementsByClassName('checkboxClass')[event.target.id].id).split('/')[0]; console.log('programIds=>'+programIds);console.log('activitiesIds=>'+activitiesIds); var cmpEvent = component.getEvent("redirectToDealerDetail"); cmpEvent.setParams({ "accIdSapIdAccCommId" : programIds+'/'+component.get("v.growerAcc")+'/'+activitiesIds, "tabScopeNo" : '4', "componentName":"c:Frontier_GrowerAccount_UpdateTouchPoint", "newUpdateStatus":'New' }); cmpEvent.fire(); } });<file_sep>/src/aura/Frontier_AllDealers_GrowerPrograms_MasterComponent/Frontier_AllDealers_GrowerPrograms_MasterComponentController.js ({ doInit : function(component, event, helper) { helper.getAllPrograms(component,event,helper); }, selectedProgram : function(component,event,helper){ helper.navigateToProgramDetails(component,event,helper); } })<file_sep>/src/aura/Frontier_TouchPointRecord/Frontier_TouchPointRecordHelper.js ({ createTouchRecord : function(component, touch, accountId) { var validItem = true; var fieldDate = component.find("date"); var fieldDateValue = fieldDate.get("v.value"); var validFollowUp; var followUpDate = component.find("followupdate"); var startDateTime = new Date(followUpDate.get("v.value")); startDateTime.setDate(startDateTime.getDate() + 1); var endDateTime = new Date(); if( $A.localizationService.isBefore(startDateTime,endDateTime) && startDateTime != endDateTime) { followUpDate.set("v.errors", [{message:"Follow up date must be future date"}]); validFollowUp = false; console.log('Timezone based Error'+startDateTime+'End date'+endDateTime); } else{ validFollowUp = true; followUpDate.set("v.errors", null); } if ($A.util.isEmpty(fieldDateValue)){ validItem = false; fieldDate.set("v.errors", [{message:"Value can't be blank."}]); } else { fieldDate.set("v.errors", null); } if(validItem && validFollowUp){ this.upsertTouchPoint(component, touch, accountId, function(a) { var touches = component.get("v.touchpoints"); touches.push(a.getReturnValue()); if(a.getState() === "SUCCESS"){ document.getElementById("backGroundId").style.display = "block"; document.getElementById("newAccountId").style.display = "block"; } component.find("followupdate").set("v.value",""); component.set("v.touchpoints", touches); component.set("v.newTouchpoint",{'sobjectType': 'Event', 'ActivityDateTime': null, 'Description': '', 'Type': 'Call', 'Subject' : ''}); }); } }, upsertTouchPoint : function(component, touch, acId, callback) { /* Commented By Priyanka var contactId = component.find("contactList").get("v.value"); */ var contactId = 'None'; var notes = component.find("notes").get("v.value"); var touchPointType = component.find("touchPointType").get("v.value"); var touchPointReason = component.find("touchPointReason").get("v.value"); var dateVal = component.find("date").get("v.value"); var followDate1 = component.find("followupdate").get("v.value");; console.log("followDate" + followDate1); if(followDate1 == ''){ console.log("Inside null"); bfollowDate1 = null; } var action = component.get("c.insertTouchPoint"); action.setParams({ "notes" :notes, "touchPointType" :touchPointType, "touchPointReason" : touchPointReason, "StartDate": dateVal, "recordType" : 'Event Touch Point', "accuID": acId, "contactId" : contactId, "dueDate" : followDate1 }); if (callback) { action.setCallback(this, callback); } $A.enqueueAction(action); } });<file_sep>/src/aura/Frontier_GrowAcc_Touchpoints/Frontier_GrowAcc_TouchpointsHelper.js ({ getProgramActivityTouchpoints : function(component,event,page,isInitialize,index) { //var accountId = component.get("v.accountId"); var accDetail = component.get("v.growerAcc"); var accountId = accDetail.split(',')[0]; console.log('button pressed'+index); console.log('Account Id' + accountId); var action = component.get("c.getProgramActivityTouchpoints"); action.setParams({ pageNumber : page, pageSize : component.get("v.pageSize"), accountId : accountId, filterTask : index }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ var touchpointsList = []; component.set("v.page",page); var retResponse = response.getReturnValue(); console.log("retResponse"+ JSON.stringify(retResponse)); component.set("v.total",JSON.parse(retResponse[0])); component.set("v.pages",Math.ceil((JSON.parse(retResponse[0]))/component.get("v.pageSize"))); touchpointsList = JSON.parse(retResponse[1]); component.set("v.touchpointsList",touchpointsList); console.log('Keyyyyyyyyytouchhh'+component.get("v.touchpointsList")); var touchPointKeys = []; for(var touchpointkey in touchpointsList){ touchPointKeys.push(touchpointkey); } //component.set("v.touchpointKeys",touchPointKeys); console.log('Keyyyyyyyyy'+touchPointKeys); component.set("v.touchpointKeys",touchPointKeys); }else if (state === "ERROR"){ console.log('Error'); } }); $A.enqueueAction(action); }, createAccountDetailsComp : function(component,event){ $A.createComponent( "c:Frontier_Account_AddressInformation", { accountId:component.get("v.growerAcc").split(',')[0]?component.get("v.growerAcc").split(',')[0]:'', accComId: component.get("v.accComId"), }, function(newCmp){ var cmp = component.find("addrssInfo"); cmp.set("v.body", newCmp); } ); } })<file_sep>/src/aura/Frontier_CancelPopup/Frontier_CancelPopupController.js ({ handlecancel : function(component, event, helper) { console.log('I nside handle cancel'); //document.getElementById("newCancel").style.display = "block"; //document.getElementById("cancelbackgrnd").style.display = "block"; } })<file_sep>/src/aura/Frontier_GrowerAccountByRadlChart/Frontier_GrowerAccountByRadlChartController.js ({ loadAccdashboard : function(component, event, helper){ helper.loadAccDashData(component, event); /*console.log('After load'); if((component.get("v.flag")) == true){ console.log('After load true'); helper.groupablebar(component, event); */ } } })<file_sep>/src/aura/Frontier_Carosel_Activities/Frontier_Carosel_ActivitiesHelper.js ({ getProgramEventListHelper : function(component, event, helper) { var acctDetails = component.get("v.growerAcc"), acctId = acctDetails.split(',')[0], acctProgramId = acctDetails.split(',')[3], acctProgramActivityId = acctDetails.split(',')[4]; component.set("v.selectedProgramId",acctProgramId); var action = component.get("c.getProgramsTasksByTask"); action.setParams({ acctId : acctId, programId : acctProgramId, taskId : acctProgramActivityId }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ var programEventlist = []; var retResponse = response.getReturnValue(); programEventlist = JSON.parse(retResponse); console.log("json stringfiy:::" + JSON.stringify(retResponse)); //component.set("v.programEventList", programEventlist); component.set("v.programList",programEventlist.accountProgramList); component.set("v.ativityMap",programEventlist.activityMap); //component.set("v.selectedActivity",programEventlist.selectedName); console.log("v.programEventList from PA" + programEventlist); var PgmListId = component.get("v.PgmListId"); var selectedTask = component.get("v.selectedActivity"); var aMap = component.get("v.ativityMap"); var selaMap =[]; for(var key in aMap){ if(PgmListId && key){ if(key === PgmListId){ selaMap = aMap[PgmListId]; } } } component.set("v.selectedAtivityMap",selaMap); var selectedMap = component.get("v.selectedAtivityMap"); helper.createHTMLForCarosel(component, event, selectedMap, acctProgramActivityId); if(component.get("v.programList").length === component.get("v.programCount")+1){ window.setTimeout( $A.getCallback(function() { if (component.isValid()) { $('.carosel').slick({ dots:true, infinite:false }) } }) ); } } else if(state === "ERROR"){ console.log('Error'); } }); $A.enqueueAction(action); }, createHTMLForCarosel : function(component, event, selectedMap, acctProgramActivityId){ var selectedHtml; var parsedHTML; var _bindHtml; var topSectionMarkup,tableHead,tableRows,tableBottom =''; var buttonDetails =[]; if(selectedMap && selectedMap.length >0){ for(var i in selectedMap){ if(acctProgramActivityId === selectedMap[i].Id && selectedMap[i].Program_SFID__r.Name !== 'Non-Program'){ topSectionMarkup = '<div>'+ '<div class="slds-grid slds-wrap caroselGrid">'+ '<div class="slds-size--1-of-3 slds-medium-size--1-of-3" id='+'parentbackLink'+component.get("v.PgmListId")+'>'+ ''+generateDynamicButton('parentbackLink','backlink','<Back to Activities','c.backToTouchpoint','backlinkClass')+''+ '</div>'+ '<div class="slds-size--1-of-3 slds-medium-size--1-of-3" style="padding-right:5%">'+ '<center>'+ '<span class="headSection">Activitiy&nbsp#&nbsp'+component.get("v.activityCount")+'</span>'+ '<span class="headSection">TouchPoint&nbsp#&nbsp 1</span>'; if(selectedMap[i].TouchPoint_SFID__c){ topSectionMarkup= topSectionMarkup+'<span class="headSection-noraml">'+replaceEmptyString(convertCustomDate(selectedMap[i].TouchPoint_SFID__r.Date__c))+'</span>'; } topSectionMarkup = topSectionMarkup +'</center>'+ '</div>'+ '<div class="slds-size--1-of-3 slds-medium-size--1-of-3">'+ '<p data-aura-rendered-by="17:830;a"><b data-aura-rendered-by="18:830;a">Time :&nbsp;<select class="form-control inputstyle select uiInput uiInputSelect uiInput--default uiInput--select" size="1" aria-describedby="" id="20:830;a" data-aura-rendered-by="31:830;a" data-aura-class="uiInput uiInputSelect uiInput--default uiInput--select" data-interactive-lib-uid="9" style="width:50%">&nbsp;'+ '<option value="" selected="selected" data-aura-rendered-by="24:830;a" class="uiInputSelectOption" data-aura-class="uiInputSelectOption">01:00PM Central US</option></select><!--render facet: 35:830;a--></b></p>'+ '</div>'+ '</div>'+ '<div class="innercaroselGrid">'+ '<div class="slds-grid slds-grid--pull-padded">'+ '<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-2 slds-large-size--1-of-2">'+ '<div class="slds-grid slds-wrap slds-grid--pull-padded">'+ '<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-2 slds-large-size--1-of-2 slds-custom-p-large">'+ '<strong>Activity</strong><br></br>'+ ''+ replaceEmptyString(selectedMap[i].Subject?selectedMap[i].Subject:selectedMap[i].Name) +''+ '</div>'; if(selectedMap[i].TouchPoint_SFID__c && selectedMap[i].Status === 'Scheduled'){ topSectionMarkup = topSectionMarkup +'<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-2 slds-large-size--1-of-2 slds-custom-p-large" id='+'parentcancelactivityLink'+component.get("v.PgmListId")+'>'+ ''+generateDynamicButton('parentcancelactivityLink','cancelactivitylink','Cancel Activity','c.cancelActivity','cancelactivitylinkClass')+''+ '</div>'; }else{ topSectionMarkup = topSectionMarkup +'<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-2 slds-large-size--1-of-2 slds-custom-p-large" id='+'parentcancelactivityLink'+component.get("v.PgmListId")+'>'+ '</div>'; } topSectionMarkup = topSectionMarkup +'<div class="slds-p-horizontal--small slds-size--1-of-2 slds-medium-size--1-of-1 slds-large-size--1-of-1 slds-custom-p-large slds-custom-m-large">'+ '<div class="slds-grid">'+ '<div class="slds-size--1-of-2">'+ '<strong>Comments</strong>'+ '</div>'+ '<div class="slds-size--1-of-2 cus-textarea-save-link" id='+'parentcommentSavelinkLink'+component.get("v.PgmListId")+'>'+ ''+generateDynamicButton('parentcommentSavelinkLink','commentSavelink','Save','c.saveComments','commentSavelinkClass')+''+ '</div>'+ '</div>'+ '<textarea style="width:96%;" class="textarea" rows="5" id='+'textArea'+component.get("v.PgmListId")+'>'+ replaceEmptyString(selectedMap[i].Description) +'</textarea>'+ '</div>'+ '</div>'+ '</div>'+ '<div class="vertical-line" style="height:260px;"></div>'+ '<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-2 slds-large-size--1-of-2">'+ '<div class="slds-grid slds-wrap slds-grid--pull-padded">'+ '<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-2 slds-large-size--1-of-4">'+ '<strong>Program</strong><br></br>'+ ''+ replaceEmptyString(selectedMap[i].Program_SFID__r.Name) +''+ '</div>'+ '<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-2 slds-large-size--1-of-3 custom-comp-cancel">'; if(component.get("v.prgmStatus") !== 'Completed' && component.get("v.prgmStatus") !== 'Cancelled'){ topSectionMarkup = topSectionMarkup +'<span style = "position:relative;right:2%;" id='+'parentcompleteProgramlink'+component.get("v.PgmListId")+'>'+ ''+generateDynamicButton('parentcompleteProgramlink','completeProgramlink','Complete Program','c.completeProgram','completeProgramlinkClass')+''+ '</span>'+ '<span class="slashClass">/</span>' + '<span style = "position:relative;right:8%;" id='+'parentcancelProgramlink'+component.get("v.PgmListId")+'>'+ ''+generateDynamicButton('parentcancelProgramlink','cancelProgramlink','Cancel Program','c.completeProgram','cancelProgramlinkClass')+''+ '</span>'; } topSectionMarkup = topSectionMarkup +'</div>'+ '<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-1 slds-large-size--1-of-1 slds-custom-m-large">'+ '<strong>Program Status</strong><br></br>'+ '<span id='+'pgmStatus'+component.get("v.PgmListId")+'>'+ replaceEmptyString(component.get("v.prgmStatus")) +'</span>'+ '</div>'+ '<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-1 slds-large-size--1-of-1 slds-custom-m-large">'+ '<strong>Program Budget</strong><br></br>'+ ''+ replaceEmptyString(selectedMap[i].Program_SFID__r.Budget__C) +''+ '</div>'+ '</div>'+ '</div>'+ '</div>'+ '</div>'+ '</div>'; //set activity Id component.set("v.generatedActivityId",selectedMap[i].Id); //increment count component.set("v.activityCount",component.get("v.activityCount") +1); var cmpEvent = component.getEvent("loadCarosel"); cmpEvent.setParams({ "activityCount":component.get("v.activityCount"), "isPopup" :false, "modalParameters":'' }); cmpEvent.fire(); break; } if(acctProgramActivityId === selectedMap[i].Id && selectedMap[i].Program_SFID__r.Name === 'Non-Program'){ topSectionMarkup = '<div>'+ '<div class="slds-grid slds-wrap caroselGrid">'+ '<div class="slds-size--1-of-3 slds-medium-size--1-of-3" id='+'parentbackLink'+component.get("v.PgmListId")+'>'+ ''+generateDynamicButton('parentbackLink','backlink','<Back to Activities','c.backToTouchpoint','backlinkClass')+''+ '</div>'+ '<div class="slds-size--1-of-3 slds-medium-size--1-of-3" style="padding-right:5%">'+ '<center>'+ '<span class="headSection">Activitiy&nbsp#&nbsp'+component.get("v.activityCount")+'</span>'+ '<span class="headSection">TouchPoint&nbsp#&nbsp 1</span>'; if(selectedMap[i].TouchPoint_SFID__c){ topSectionMarkup= topSectionMarkup+'<span class="headSection-noraml">'+replaceEmptyString(convertCustomDate(selectedMap[i].TouchPoint_SFID__r.Date__c))+'</span>'; } topSectionMarkup = topSectionMarkup +'</center>'+ '</center>'+ '</div>'+ '<div class="slds-size--1-of-3 slds-medium-size--1-of-3">'+ '<p data-aura-rendered-by="17:830;a"><b data-aura-rendered-by="18:830;a">Time :&nbsp;<select class="form-control inputstyle select uiInput uiInputSelect uiInput--default uiInput--select" size="1" aria-describedby="" id="20:830;a" data-aura-rendered-by="31:830;a" data-aura-class="uiInput uiInputSelect uiInput--default uiInput--select" data-interactive-lib-uid="9" style="width:50%">&nbsp;'+ '<option value="" selected="selected" data-aura-rendered-by="24:830;a" class="uiInputSelectOption" data-aura-class="uiInputSelectOption">01:00PM Central US</option></select><!--render facet: 35:830;a--></b></p>'+ '</div>'+ '</div>'+ '<div class="innercaroselGrid">'+ '<div class="slds-grid slds-grid--pull-padded">'+ '<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-2 slds-large-size--1-of-2">'+ '<div class="slds-grid slds-wrap slds-grid--pull-padded">'+ '<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-2 slds-large-size--1-of-2 slds-custom-p-large">'+ '<strong>Activity</strong><br></br>'+ ''+ replaceEmptyString(selectedMap[i].Subject?selectedMap[i].Subject:selectedMap[i].Name) +''+ '</div>'; if(selectedMap[i].TouchPoint_SFID__c && selectedMap[i].Status === 'Scheduled'){ topSectionMarkup = topSectionMarkup +'<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-2 slds-large-size--1-of-2 slds-custom-p-large" id='+'parentcancelactivityLink'+component.get("v.PgmListId")+'>'+ ''+generateDynamicButton('parentcancelactivityLink','cancelactivitylink','Cancel Activity','c.cancelActivity','cancelactivitylinkClass')+''+ '</div>'; }else{ topSectionMarkup = topSectionMarkup +'<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-2 slds-large-size--1-of-2 slds-custom-p-large" id='+'parentcancelactivityLink'+component.get("v.PgmListId")+'>'+ '</div>'; } topSectionMarkup = topSectionMarkup +'<div class="slds-p-horizontal--small slds-size--1-of-2 slds-medium-size--1-of-1 slds-large-size--1-of-1 slds-custom-p-large slds-custom-m-large">'+ '<div class="slds-grid">'+ '<div class="slds-size--1-of-2">'+ '<strong>Comments</strong>'+ '</div>'+ '<div class="slds-size--1-of-2 cus-textarea-save-link" id='+'parentcommentSavelinkLink'+component.get("v.PgmListId")+'>'+ ''+generateDynamicButton('parentcommentSavelinkLink','commentSavelink','Save','c.saveComments','commentSavelinkClass')+''+ '</div>'+ '</div>'+ '<textarea style="width:96%;" class="textarea" rows="5" id='+'textArea'+component.get("v.PgmListId")+'>'+ replaceEmptyString(selectedMap[i].Description) +'</textarea>'+ '</div>'+ '</div>'+ '</div>'+ '<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-2 slds-large-size--1-of-2">'+ '<div class="slds-grid slds-wrap slds-grid--pull-padded">'+ '<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-2 slds-large-size--1-of-3">'+ '<strong>Program</strong><br></br>'+ ''+ replaceEmptyString(selectedMap[i].Program_SFID__r.Name) +''+ '</div>'+ '</div>'+ '</div>'+ '</div>'+ '</div>'+ '</div>'; //set activity Id component.set("v.generatedActivityId",selectedMap[i].Id); //increment count component.set("v.activityCount",component.get("v.activityCount") +1); var cmpEvent = component.getEvent("loadCarosel"); cmpEvent.setParams({ "activityCount":component.get("v.activityCount"), "isPopup" :false, "modalParameters":'' }); cmpEvent.fire(); break; } } if(!component.get("v.generatedActivityId")){ for(var i in selectedMap){ if(acctProgramActivityId !== selectedMap[i].Id && selectedMap[i].Program_SFID__r.Name !== 'Non-Program'){ topSectionMarkup = '<div>'+ '<div class="slds-grid slds-wrap caroselGrid">'+ '<div class="slds-size--1-of-3 slds-medium-size--1-of-3" id='+'parentbackLink'+component.get("v.PgmListId")+'>'+ ''+generateDynamicButton('parentbackLink','backlink','<Back to Activities','c.backToTouchpoint','backlinkClass')+''+ '</div>'+ '<div class="slds-size--1-of-3 slds-medium-size--1-of-3" style="padding-right:5%">'+ '<center>'+ '<span class="headSection">Activitiy&nbsp#&nbsp'+component.get("v.activityCount")+'</span>'+ '<span class="headSection">TouchPoint&nbsp#&nbsp 1</span>'; if(selectedMap[i].TouchPoint_SFID__c){ topSectionMarkup= topSectionMarkup+'<span class="headSection-noraml">'+replaceEmptyString(convertCustomDate(selectedMap[i].TouchPoint_SFID__r.Date__c))+'</span>'; } topSectionMarkup = topSectionMarkup +'</center>'+ '</center>'+ '</div>'+ '<div class="slds-size--1-of-3 slds-medium-size--1-of-3">'+ '<p data-aura-rendered-by="17:830;a"><b data-aura-rendered-by="18:830;a">Time :&nbsp;<select class="form-control inputstyle select uiInput uiInputSelect uiInput--default uiInput--select" size="1" aria-describedby="" id="20:830;a" data-aura-rendered-by="31:830;a" data-aura-class="uiInput uiInputSelect uiInput--default uiInput--select" data-interactive-lib-uid="9" style="width:50%">&nbsp;'+ '<option value="" selected="selected" data-aura-rendered-by="24:830;a" class="uiInputSelectOption" data-aura-class="uiInputSelectOption">01:00PM Central US</option></select><!--render facet: 35:830;a--></b></p>'+ '</div>'+ '</div>'+ '<div class="innercaroselGrid">'+ '<div class="slds-grid slds-grid--pull-padded">'+ '<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-2 slds-large-size--1-of-2">'+ '<div class="slds-grid slds-wrap slds-grid--pull-padded">'+ '<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-2 slds-large-size--1-of-2 slds-custom-p-large">'+ '<strong>Activity</strong><br></br>'+ ''+ replaceEmptyString(selectedMap[i].Subject?selectedMap[i].Subject:selectedMap[i].Name) +''+ '</div>'; if(selectedMap[i].TouchPoint__c && selectedMap[i].Status === 'Scheduled'){ topSectionMarkup = topSectionMarkup +'<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-2 slds-large-size--1-of-2 slds-custom-p-large" id='+'parentcancelactivityLink'+component.get("v.PgmListId")+'>'+ ''+generateDynamicButton('parentcancelactivityLink','cancelactivitylink','Cancel Activity','c.cancelActivity','cancelactivitylinkClass')+''+ '</div>'; }else{ topSectionMarkup = topSectionMarkup +'<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-2 slds-large-size--1-of-2 slds-custom-p-large" id='+'parentcancelactivityLink'+component.get("v.PgmListId")+'>'+ '</div>'; } topSectionMarkup = topSectionMarkup +'<div class="slds-p-horizontal--small slds-size--1-of-2 slds-medium-size--1-of-1 slds-large-size--1-of-1 slds-custom-p-large slds-custom-m-large">'+ '<div class="slds-grid">'+ '<div class="slds-size--1-of-2 cus-textarea-save-link">'+ '<strong>Comments</strong>'+ '</div>'+ '<div class="slds-size--1-of-2 cus-textarea-save-link" id='+'parentcommentSavelinkLink'+component.get("v.PgmListId")+'>'+ ''+generateDynamicButton('parentcommentSavelinkLink','commentSavelink','Save','c.saveComments','commentSavelinkClass')+''+ '</div>'+ '</div>'+ '<textarea style="width:96%;" class="textarea" rows="5" id='+'textArea'+component.get("v.PgmListId")+'>'+ replaceEmptyString(selectedMap[i].Description) +'</textarea>'+ '</div>'+ '</div>'+ '</div>'+ '<div class="vertical-line" style="height:260px;"></div>'+ '<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-2 slds-large-size--1-of-2">'+ '<div class="slds-grid slds-wrap slds-grid--pull-padded">'+ '<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-2 slds-large-size--1-of-4">'+ '<strong>Program</strong><br></br>'+ ''+ replaceEmptyString(selectedMap[i].Program_SFID__r.Name) +''+ '</div>'+ '<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-2 slds-large-size--1-of-3 custom-comp-cancel">'; if(component.get("v.prgmStatus") !== 'Completed' && component.get("v.prgmStatus") !== 'Cancelled'){ topSectionMarkup = topSectionMarkup +'<span style = "position:relative;right:2%;" id='+'parentcompleteProgramlink'+component.get("v.PgmListId")+'>'+ ''+generateDynamicButton('parentcompleteProgramlink','completeProgramlink','Complete Program','c.completeProgram','completeProgramlinkClass')+''+ '</span>'+ '<span class="slashClass">/</span>' + '<span style = "position:relative;right:8%;" id='+'parentcancelProgramlink'+component.get("v.PgmListId")+'>'+ ''+generateDynamicButton('parentcancelProgramlink','cancelProgramlink','Cancel Program','c.completeProgram','cancelProgramlinkClass')+''+ '</span>'; } topSectionMarkup = topSectionMarkup +'</div>'+ '<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-1 slds-large-size--1-of-1 slds-custom-m-large">'+ '<strong>Program Status</strong><br></br>'+ '<span id='+'pgmStatus'+component.get("v.PgmListId")+'>'+ replaceEmptyString(component.get("v.prgmStatus")) +'</span>'+ '</div>'+ '<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-1 slds-large-size--1-of-1 slds-custom-m-large">'+ '<strong>Program Budget</strong><br></br>'+ ''+ replaceEmptyString(selectedMap[i].Program_SFID__r.Budget__C) +''+ '</div>'+ '</div>'+ '</div>'+ '</div>'+ '</div>'+ '</div>'; //set activity Id component.set("v.generatedActivityId",selectedMap[i].Id); //increment count component.set("v.activityCount",component.get("v.activityCount") +1); var cmpEvent = component.getEvent("loadCarosel"); cmpEvent.setParams({ "activityCount":component.get("v.activityCount"), "isPopup" :false, "modalParameters":'' }); cmpEvent.fire(); break; } if(acctProgramActivityId !== selectedMap[i].Id && selectedMap[i].Program_SFID__r.Name === 'Non-Program'){ topSectionMarkup = '<div>'+ '<div class="slds-grid slds-wrap caroselGrid">'+ '<div class="slds-size--1-of-3 slds-medium-size--1-of-3" id='+'parentbackLink'+component.get("v.PgmListId")+'>'+ ''+generateDynamicButton('parentbackLink','backlink','<Back to Activities','c.backToTouchpoint','backlinkClass')+''+ '</div>'+ '<div class="slds-size--1-of-3 slds-medium-size--1-of-3" style="padding-right:5%">'+ '<center>'+ '<span class="headSection">Activitiy&nbsp#&nbsp'+component.get("v.activityCount")+'</span>'+ '<span class="headSection">TouchPoint&nbsp#&nbsp 1</span>'; if(selectedMap[i].TouchPoint_SFID__c){ topSectionMarkup= topSectionMarkup+'<span class="headSection-noraml">'+replaceEmptyString(convertCustomDate(selectedMap[i].TouchPoint_SFID__r.Date__c))+'</span>'; } topSectionMarkup = topSectionMarkup +'</center>'+ '</center>'+ '</div>'+ '<div class="slds-size--1-of-3 slds-medium-size--1-of-3">'+ '<p data-aura-rendered-by="17:830;a"><b data-aura-rendered-by="18:830;a">Time :&nbsp;<select class="form-control inputstyle select uiInput uiInputSelect uiInput--default uiInput--select" size="1" aria-describedby="" id="20:830;a" data-aura-rendered-by="31:830;a" data-aura-class="uiInput uiInputSelect uiInput--default uiInput--select" data-interactive-lib-uid="9" style="width:50%">&nbsp;'+ '<option value="" selected="selected" data-aura-rendered-by="24:830;a" class="uiInputSelectOption" data-aura-class="uiInputSelectOption">01:00PM Central US</option></select><!--render facet: 35:830;a--></b></p>'+ '</div>'+ '</div>'+ '<div class="innercaroselGrid">'+ '<div class="slds-grid slds-grid--pull-padded">'+ '<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-2 slds-large-size--1-of-2">'+ '<div class="slds-grid slds-wrap slds-grid--pull-padded">'+ '<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-2 slds-large-size--1-of-2 slds-custom-p-large">'+ '<strong>Activity</strong><br></br>'+ ''+ replaceEmptyString(selectedMap[i].Subject?selectedMap[i].Subject:selectedMap[i].Name) +''+ '</div>'; if(selectedMap[i].TouchPoint_SFID__c && selectedMap[i].Status === 'Scheduled'){ topSectionMarkup = topSectionMarkup +'<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-2 slds-large-size--1-of-2 slds-custom-p-large" id='+'parentcancelactivityLink'+component.get("v.PgmListId")+'>'+ ''+generateDynamicButton('parentcancelactivityLink','cancelactivitylink','Cancel Activity','c.cancelActivity','cancelactivitylinkClass')+''+ '</div>'; }else{ topSectionMarkup = topSectionMarkup +'<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-2 slds-large-size--1-of-2 slds-custom-p-large" id='+'parentcancelactivityLink'+component.get("v.PgmListId")+'>'+ '</div>'; } topSectionMarkup = topSectionMarkup + '<div class="slds-p-horizontal--small slds-size--1-of-2 slds-medium-size--1-of-1 slds-large-size--1-of-1 slds-custom-p-large slds-custom-m-large">'+ '<div class="slds-grid">'+ '<div class="slds-size--1-of-2">'+ '<strong>Comments</strong>'+ '</div>'+ '<div class="slds-size--1-of-2 cus-textarea-save-link" id='+'parentcommentSavelinkLink'+component.get("v.PgmListId")+'>'+ ''+generateDynamicButton('parentcommentSavelinkLink','commentSavelink','Save','c.saveComments','commentSavelinkClass')+''+ '</div>'+ '</div>'+ '<textarea style="width:96%;" class="textarea" rows="5" id='+'textArea'+component.get("v.PgmListId")+'>'+ replaceEmptyString(selectedMap[i].Description) +'</textarea>'+ '</div>'+ '</div>'+ '</div>'+ '<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-2 slds-large-size--1-of-2">'+ '<div class="slds-grid slds-wrap slds-grid--pull-padded">'+ '<div class="slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--1-of-2 slds-large-size--1-of-3">'+ '<strong>Program</strong><br></br>'+ ''+ replaceEmptyString(selectedMap[i].Program_SFID__r.Name) +''+ '</div>'+ '</div>'+ '</div>'+ '</div>'+ '</div>'+ '</div>'; //set activity Id component.set("v.generatedActivityId",selectedMap[i].Id); //increment count component.set("v.activityCount",component.get("v.activityCount") +1); var cmpEvent = component.getEvent("loadCarosel"); cmpEvent.setParams({ "activityCount":component.get("v.activityCount"), "isPopup" :false, "modalParameters":'' }); cmpEvent.fire(); break; } } } tableRows=""; for(var j in selectedMap){ if(component.get("v.generatedActivityId") !== selectedMap[j].Id){ tableRows = tableRows + '<tr class="tablerow">'+ '<td>'+ ''+ replaceEmptyString(selectedMap[j].Subject?selectedMap[j].Subject:selectedMap[j].Name) +''+ '</td><td>'+ ''+ replaceEmptyString(selectedMap[j].Status?selectedMap[j].Status:selectedMap[j].Status__c) +''+ '</td><td>'+ ''+ replaceEmptyString(selectedMap[j].Phase__c) +''+ '</td>'+ '</tr>'; } } if(tableRows !== ""){ tableHead = '<div class="slds-grid slds-wrap slds-grid--pull-padded paTable">'+ '<p><strong>Related Program Activities</strong></p><br></br>'+ '<table id="tableRPA'+component.get("v.PgmListId")+'" class="slds-table slds-no-row-hover slds-table--product VisitTable">'+ '<thead>'+ '<tr class="slds-text-custom--label">'+ '<th>'+ '<span><strong>Activity Name</strong></span>'+ '</th>'+ '<th>'+ '<span><strong>Status</strong></span>'+ '</th>'+ '<th>'+ '<div style="text-align:center;">'+ '<span style="float:left;">'+ '<strong>Phase</strong>'+ '</span>'+ '<span><svg class="icon icon--plus" viewBox="0 0 5 5" xmlns="http://www.w3.org/2000/svg"><path d="M2 1 h1 v1 h1 v1 h-1 v1 h-1 v-1 h-1 v-1 h1 z" /></svg></span>'+ '<span id='+'parentaddactivityLink'+component.get("v.PgmListId")+'>'+ ''+generateDynamicButton('parentaddactivityLink','addactivitylink','Add New Activity','c.showAddNewActivity','addactivitylinkClass')+''+ '</span>'+ '</div>'+ '</th>'+ '</tr>'+ '</thead><tbody>'; tableBottom ='</tbody></table></div>'; } if(tableHead && tableRows && tableBottom){ _bindHtml = topSectionMarkup + tableHead + tableRows + tableBottom; } else{ _bindHtml = topSectionMarkup; } if(topSectionMarkup){ if(component.get("v.selectedProgramId") === component.get("v.PgmListId")){ var _bindParent = $("#innerCarosel" +component.get("v.programCount")).append(_bindHtml); $(".carosel").prepend(_bindParent); }else{ $("#innerCarosel" +component.get("v.programCount")).append(_bindHtml); } }else{ $("#innerCarosel" +component.get("v.programCount")).remove(); } }else{ $("#innerCarosel" +component.get("v.programCount")).remove(); } function replaceEmptyString(value){ if(!value && value === undefined && value !== 0){ return ''; } else{ return value; } } function convertCustomDate(date){ var tchDate; if(date){ var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']; var months = ['January','February','March','April','May','June','July','August','September','October','November','December']; tchDate = new Date(date); return days[tchDate.getDay()]+','+months[tchDate.getMonth()]+','+tchDate.getDate()+','+tchDate.getFullYear(); } return tchDate } //Dynamically create ui:button and the append into carosel markup function generateDynamicButton(parentId,butttonId,label,action,markupclass){ buttonDetails.push({pId:parentId,bId:butttonId,label:label,action:action,mclass:markupclass}); return ''; } for(var k in buttonDetails){ var parentElem = document.getElementById(buttonDetails[k].pId+component.get("v.PgmListId")); if(parentElem){ var accountDetails = component.get("v.growerAcc"); $A.createComponent( "ui:button", { "aura:id": accountDetails.split(',')[0]+','+accountDetails.split(',')[1]+','+accountDetails.split(',')[2]+','+component.get("v.PgmListId")+','+buttonDetails[k].bId+','+component.get("v.prgmStatus")+','+component.get("v.generatedActivityId"), "label": buttonDetails[k].label, "press": component.getReference(buttonDetails[k].action) }, function(newButton, status, errorMessage){ if (status === "SUCCESS") { var cmp = component.find(buttonDetails[k].bId) cmp.set("v.body", newButton); } else if (status === "ERROR") { console.log("Error: " + errorMessage); } } ); var backlinkelem = $('.'+buttonDetails[k].mclass + component.get("v.programCount")); $('.'+buttonDetails[k].mclass + component.get("v.programCount")).remove(); $('#'+buttonDetails[k].pId +component.get("v.PgmListId")).append(backlinkelem); } } }, cancelSelectedActivity : function(component, event, helper, acctId, acctProgramId, acctProgramActivityId){ var action = component.get("c.getCancelActy"); action.setParams({ accountId : acctId, programId : acctProgramId, taskId : acctProgramActivityId }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ helper.redirectToselectedActivity(component, event, helper); console.log('Success'); } else if (state === "ERROR"){ console.log('Error'); } }); $A.enqueueAction(action); }, redirectToselectedActivity : function(component, event, helper){ var cmpEvent = component.getEvent("redirectToDealerDetail"); cmpEvent.setParams({ "accIdSapIdAccCommId" : event.getSource().getLocalId(), "tabScopeNo" : '2', "componentName":"c:Frontier_GrowerAccount_Program", }); cmpEvent.fire(); }, saveActivityComments : function (component, event, helper, actAccId, activityId, textAreaValue) { var action = component.get("c.saveActivityComments"); action.setParams({ accountId : actAccId, activityId : activityId, activityComments : textAreaValue }); action.setCallback(this,function(response){ var state = response.getState(); if(state === 'SUCCESS'){ this.showPopUp(component,event,'Your Comments Successfully Updated !!'); console.log('Saved in the backend. Response success.'); } else if (state === "ERROR"){ console.log('Unable to save. Error reported.'); } }); $A.enqueueAction(action); }, showPopUp: function(component,event,message){ $A.createComponent("c:Frontier_PopUp", {Message : message, ComponentName : 'Frontier_Carosel_Activities', customCss : "commentPopup" }, function(newComp){ var comp = component.find("userpopup"); if(comp != undefined){ comp.set("v.body",newComp); } }); $(".cFrontier_PopUp").css("right:50%"); } })
3159cb7d72b397ad4ef400816922778dec936ac1
[ "JavaScript" ]
118
JavaScript
priyanka4491/GlobalSF
92532f3e710dba4a2edc923f5582ecebfbc18ed0
54410d9dd8a91b8655597cdca35858a9ff0b7f88
refs/heads/master
<repo_name>FluxDenisty/ASCII-Enthusiasts-72-hour-2014<file_sep>/README.md ASCII-Enthusiasts-72-hour-2014 ============================== Hopefully a game <file_sep>/Makefile run: Game ./Game Game: main.cc g++ $^ -o $@ <file_sep>/main.cc #include <iostream> #include <vector> #define PL( text ) (cout << text << endl) using namespace std; struct Menu { struct Answer { string text; int num; }; vector<string> list; Answer ask() { vector<string>::iterator it = list.begin(); for (int i = 1; it != list.end(); ++i) { PL(i << ". " << *it); ++it; } Answer answer; while (answer.text == "") { string in; getline(cin, in); try { answer.num = atoi(in.c_str()); } catch(...) { PL("Please enter a number from 1 to " << list.size()); continue; } if (answer.num == 0 || answer.num > list.size()) { PL("Please enter a number from 1 to " << list.size()); continue; } answer.text = list[answer.num - 1]; } return answer; } void add(string s) { list.push_back(s); } void clear() { list.clear(); } }; int main (int argc, char**argv) { PL("Welcome to Text Harvest!"); Menu main_menu; main_menu.add("New Game"); // 1 main_menu.add("Continue"); // 2 main_menu.add("Options"); // 3 main_menu.add("Credits"); // 4 main_menu.add("Quit"); // 5 while (1) { Menu::Answer answer = main_menu.ask(); PL(answer.text); if (answer.num == 5) { break; } } }
92d3e9d7df1c5c449be8bd08bbcff494ec0b8c5c
[ "Markdown", "Makefile", "C++" ]
3
Markdown
FluxDenisty/ASCII-Enthusiasts-72-hour-2014
e765f9a4ec545510e3189c96b086721a504bd0b5
58940e71ef8b3ff8ca963f298efe8f578f6fe350
refs/heads/master
<file_sep>import os ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) # Root directory of the project RAW_DATA_DIRECTORY = '/Downloaded_Data/Raw_Data/' # Raw-scraped data from the Fitbit API PROCESSED_DATA_DIRECTORY = '/Downloaded_Data/Preprocessed_Data/' # Preprocessed up/down sampled data TRAINING_DATA_DIRECTORY = '/Downloaded_Data/Training_Data/' # Training data for the neural network FILE_EXT = '.xlsx' # File format to save/load data CLIENT_ID = '22D56P' # Fitbit API Client ID CLIENT_SECRET = '9aefa27740d00cd57d1b06beb43992ac' # Fitbit API Client Secret START_DATE = '2018-01-30' # '2016-09-28' # Date to start scraping data <file_sep>absl-py==0.6.1 asn1crypto==0.24.0 astor==0.7.1 blinker==1.4 bokeh==1.0.1 certifi==2018.10.15 cffi==1.11.5 chardet==3.0.4 cheroot==6.5.2 CherryPy==18.0.1 contextlib2==0.5.5 cryptography==2.3.1 cycler==0.10.0 fitbit==0.3.0 gast==0.2.0 grpcio==1.12.1 h5py==2.8.0 idna==2.7 jaraco.functools==1.20 Jinja2==2.10 Keras==2.2.4 Keras-Applications==1.0.6 Keras-Preprocessing==1.0.5 kiwisolver==1.0.1 llvmlite==0.25.0 Markdown==3.0.1 MarkupSafe==1.0 matplotlib==3.0.1 mkl-fft==1.0.6 mkl-random==1.0.1 more-itertools==4.3.0 numba==0.40.0 numpy==1.15.4 oauthlib==2.1.0 olefile==0.46 packaging==18.0 pandas==0.23.4 patsy==0.5.1 Pillow==5.3.0 portend==2.3 protobuf==3.6.1 pycparser==2.19 PyJWT==1.6.4 pyOpenSSL==18.0.0 pyparsing==2.3.0 PySocks==1.6.8 python-dateutil==2.7.5 pytz==2018.7 pywin32==223 PyYAML==3.13 repoze.lru==0.7 requests==2.20.0 requests-oauthlib==1.0.0 Routes==2.4.1 scikit-learn==0.20.0 scipy==1.1.0 seaborn==0.9.0 simplejson==3.16.0 six==1.11.0 statsmodels==0.9.0 tempora==1.13 tensorboard==1.12.0 tensorflow==1.12.0 termcolor==1.1.0 tornado==5.1.1 urllib3==1.23 Werkzeug==0.14.1 win-inet-pton==1.0.1 wincertstore==0.2 zc.lockfile==1.3.0<file_sep>import pandas as pd import fitbit import datetime import heart_rate_ai.fitbit_data.fitbit_authentication as Oauth2 from dateutil import parser from enum import Enum from definitions import * from heart_rate_ai.utilities.data_frame_support import * class FitbitActivity(Enum): STEPS = 0 SLEEP = 1 CALORIES = 2 DISTANCE = 3 FLOORS = 4 ELEVATION = 5 HEART = 6 class FitbitDataScraper: def __init__(self): self.server = None self.authorization_client = None self._project_dir = ROOT_DIR def authentication_process(self): self.server = Oauth2.OAuth2Server(CLIENT_ID, CLIENT_SECRET) self.server.browser_authorize() retrieved_access_token = str(self.server.oauth.session.token['access_token']) retrieved_refresh_token = str(self.server.oauth.session.token['refresh_token']) self.authorization_client = fitbit.Fitbit(CLIENT_ID, CLIENT_SECRET, oauth2=True, access_token=retrieved_access_token, refresh_token=retrieved_refresh_token) def _write_data_to_file(self, date, data_frame, activity): filename = self._project_dir + RAW_DATA_DIRECTORY + date.strftime("%Y-%m-%d") + FILE_EXT DataFrameIO.append_df_to_excel(filename, data_frame, activity.name, index=False) @staticmethod def _data_frame_conversion(activity_data, activity): # Ensure data exists before processing if not activity_data['activities-' + activity.name.lower() + '-intraday']: return pd.DataFrame() else: time_list = [] val_list = [] for entry in activity_data['activities-' + activity.name.lower() + '-intraday']['dataset']: val_list.append(entry['value']) time_list.append(entry['time']) return pd.DataFrame({'Time': time_list, activity.name: val_list}) @staticmethod def _sleep_data_frame_conversion(activity_data, activity): # Ensure data exists before processing if not activity_data[activity.name.lower()]: return pd.DataFrame() else: time_list = [] val_list = [] for entry in activity_data[activity.name.lower()][0]['minuteData']: val_list.append(int(entry['value'])) time_list.append(entry['dateTime']) return pd.DataFrame({'Time': time_list, activity.name: val_list}) def scrape_activities(self, date): # Iterate through each activity type for activity in FitbitActivity: # Reflect the current enumerated value into its string equivalent activity_type = 'activities/' + activity.name.lower() # Determine the data detail-level if activity == FitbitActivity.HEART: sampling_interval = '1sec' else: sampling_interval = '1min' # Request the specified activity type from the Fitbit API activity_data_frame = None if activity != FitbitActivity.SLEEP: activity_data = self.authorization_client.intraday_time_series(activity_type, base_date=date, detail_level=sampling_interval) # Process the data into a DataFrame activity_data_frame = FitbitDataScraper._data_frame_conversion(activity_data, activity) else: activity_data = self.authorization_client.get_sleep(date) # Process the data into a DataFrame activity_data_frame = FitbitDataScraper._sleep_data_frame_conversion(activity_data, activity) # Save Data to a file if not activity_data_frame.empty: self._write_data_to_file(date, activity_data_frame, activity) def scrape_activities_over_dates(self, overwrite_old_data): yesterday = datetime.datetime.now() - datetime.timedelta(1) # Use yesterday so we have a full day's data for current_date in FitbitDataScraper._generate_date_range(parser.parse(START_DATE), yesterday): if self._check_if_data_exists(current_date.strftime("%Y-%m-%d")): if overwrite_old_data: print('Overwriting existing data') self._remove_file(current_date.strftime("%Y-%m-%d")) self.scrape_activities(current_date) else: print('Data already exists, overwriting not enabled') else: print('scraping...') self.scrape_activities(current_date) def _check_if_data_exists(self, date): filename = self._project_dir + RAW_DATA_DIRECTORY + date + FILE_EXT does_file_exist = os.path.isfile(filename) return does_file_exist def _remove_file(self, date): filename = self._project_dir + RAW_DATA_DIRECTORY + date + FILE_EXT os.remove(filename) @staticmethod def _generate_date_range(start_date, end_date): return (start_date + datetime.timedelta(days=i) for i in range((end_date - start_date).days + 1)) def main(): data_scraper = FitbitDataScraper() data_scraper.authentication_process() data_scraper.scrape_activities_over_dates(True) if __name__ == '__main__': main() <file_sep>import os import numpy as np import pandas as pd from definitions import * from keras.models import Sequential from keras.layers import LSTM from keras.layers import Dense from math import sqrt from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import LabelEncoder from sklearn.metrics import mean_squared_error from matplotlib import pyplot class ActivityClassifier: def __init__(self): self.combined_preprocessed_data_frame = None self.training_data_frame = None self.scaled_preprocessed_data = None self.training_data_percentage = 0.2 self.model_neurons = 500 self.model_epochs = 200 self.model_batch_size = 128 self.model_layers = 1 self.model_dropout = 0.2 self._categorical_data_scaler = None @staticmethod def initialize_processor(): os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"] = "1" # model will be trained on GPU 1 def load_activity_data(self, date): # Load the scraped data set filename = ROOT_DIR + RAW_DATA_DIRECTORY + date + FILE_EXT activity_data_xls = pd.ExcelFile(filename) heart_data_frame = pd.read_excel(activity_data_xls, 'HEART') step_data_frame = pd.read_excel(activity_data_xls, 'STEPS') distance_data_frame = pd.read_excel(activity_data_xls, 'DISTANCE') calories_data_frame = pd.read_excel(activity_data_xls, 'CALORIES') # Reform the data into an organized dataset heart_data_frame = ActivityClassifier.data_reframing(heart_data_frame, date) step_data_frame = ActivityClassifier.data_reframing(step_data_frame, date) distance_data_frame = ActivityClassifier.data_reframing(distance_data_frame, date) calories_data_frame = ActivityClassifier.data_reframing(calories_data_frame, date) # Concatenate the data into one set frames = [heart_data_frame, step_data_frame, distance_data_frame, calories_data_frame] self.combined_preprocessed_data_frame = pd.concat(frames, axis=1) self.combined_preprocessed_data_frame.to_excel(ROOT_DIR + PROCESSED_DATA_DIRECTORY + date + FILE_EXT) # Load the corresponding training data set filename = ROOT_DIR + TRAINING_DATA_DIRECTORY + date + FILE_EXT activity_data_xls = pd.ExcelFile(filename) self.training_data_frame = pd.read_excel(activity_data_xls, index_col=0) # Convert the Activity label into an encoded value encoder = LabelEncoder() self.training_data_frame['ACTIVITY'] = encoder.fit_transform(self.training_data_frame['ACTIVITY']) @staticmethod def data_reframing(activity_data_frame, date): activity_data_frame['Time'] = date + ' ' + activity_data_frame['Time'] activity_data_frame['Time'] = pd.to_datetime(activity_data_frame['Time'], format='%Y-%m-%d %H:%M:%S') activity_data_frame = activity_data_frame.set_index('Time').resample('1min').mean() return activity_data_frame def condition_data(self): conditioned_data = None frames = [self.combined_preprocessed_data_frame, self.training_data_frame] combined_frames = pd.concat(frames, axis=1) for column in combined_frames: values = combined_frames[column].values values = np.vstack(values) values = np.nan_to_num(values) values = values.astype('float32') if conditioned_data is not None: conditioned_data = np.append(conditioned_data, values, 1) else: conditioned_data = values self._categorical_data_scaler = MinMaxScaler(feature_range=(0, 1)) self.scaled_preprocessed_data = self._categorical_data_scaler.fit_transform(conditioned_data) def model_setup(self): # Define TRAIN and TEST data: # Randomly sample the TRAIN data set, all others go into the TEST data set train_data = None test_data = None current_row = 1 number_of_rows = self.scaled_preprocessed_data.shape[0] random_rows = np.random.randint(number_of_rows, size=int(self.training_data_percentage*number_of_rows)) for sample in self.scaled_preprocessed_data: # Check if current row is in the random sample for the training set if current_row in random_rows: row_data = self.scaled_preprocessed_data[current_row, :] if train_data is not None: train_data = np.vstack((train_data, row_data)) else: train_data = row_data else: if test_data is not None: test_data = np.vstack((test_data, sample)) else: test_data = sample current_row = current_row + 1 # Split into inputs and outputs train_IN = train_data[:, :-1] train_OUT = train_data[:, -1] test_IN = test_data[:, :-1] test_OUT = test_data[:, -1] # Reshape into 3D Format [samples, timesteps, features] train_IN3D = train_IN.reshape((train_IN.shape[0], self.model_layers, train_IN.shape[1])) test_IN3D = test_IN.reshape((test_IN.shape[0], self.model_layers, test_IN.shape[1])) # Design the Network model = Sequential() model.add(LSTM(self.model_neurons, dropout=self.model_dropout, recurrent_dropout=self.model_dropout, input_shape=(train_IN3D.shape[1], train_IN3D.shape[2]))) model.add(Dense(self.model_layers, activation='sigmoid')) model.compile(loss='mae', optimizer='Adadelta') # Fit the Network history = model.fit(train_IN3D, train_OUT, epochs=self.model_epochs, batch_size=self.model_batch_size, validation_data=(test_IN3D, test_OUT), verbose=2, shuffle=True) # plot history pyplot.plot(history.history['loss'], label='train') pyplot.plot(history.history['val_loss'], label='test') pyplot.legend() pyplot.show() # Evaluate Performance: # Predicted Output: test_pred = model.predict(test_IN3D) inv_pred = np.concatenate((test_IN, test_pred), axis=1) inv_pred = self._categorical_data_scaler.inverse_transform(inv_pred) inv_pred = inv_pred[:, 4] # Actual Output: inv_output = np.column_stack((test_IN, test_OUT)) inv_output = self._categorical_data_scaler.inverse_transform(inv_output) inv_output = inv_output[:, 4] # Root-Mean-Square Error rmse = sqrt(mean_squared_error(inv_output, inv_pred)) print('Test RMSE: %.3f' % rmse) # Actual vs Predicted Results pyplot.plot(inv_pred, label='Predicted') pyplot.plot(inv_output, label='Actual') pyplot.legend() pyplot.show() def main(): date = '2018-11-12' ActivityClassifier.initialize_processor() classifier = ActivityClassifier() classifier.load_activity_data(date) classifier.condition_data() classifier.model_setup() print('done') if __name__ == '__main__': main() <file_sep>import numpy as np from timeit import default_timer as timer from numba import vectorize @vectorize(['float32(float32, float32)'], target='cuda') def gpu_pow(a, b): return a ** b @vectorize(['float32(float32, float32)'], target='parallel') def cpu_para_pow(a, b): return a ** b def cpu_pow(a, b, c): for i in range(a.size): c[i] = a[i] ** b[i] def cpu_test(): vec_size = 100000000 a = b = np.array(np.random.sample(vec_size), dtype=np.float32) c = np.zeros(vec_size, dtype=np.float32) start = timer() cpu_pow(a, b, c) duration = timer() - start print(duration) def cpu_para_test(): vec_size = 100000000 a = b = np.array(np.random.sample(vec_size), dtype=np.float32) c = np.zeros(vec_size, dtype=np.float32) start = timer() c = cpu_para_pow(a, b) duration = timer() - start print(duration) def gpu_test(): vec_size = 100000000 a = b = np.array(np.random.sample(vec_size), dtype=np.float32) c = np.zeros(vec_size, dtype=np.float32) start = timer() c = gpu_pow(a, b) duration = timer() - start print(duration) def main(): cpu_para_test() cpu_test() gpu_test() if __name__ == '__main__': main()
225f3b24604ea49c1ebcb8fcde267870d082b423
[ "Python", "Text" ]
5
Python
Purdue-Academic-Projects/AI_Final_Project
e47709db8dcceefb0d1ca8ba46cf3d53a9b9d8d8
d54b5172901740c0e79940e788903a4ce2ba80bd
refs/heads/master
<file_sep><?php namespace App\Repository; use App\Entity\Artwork; use App\Entity\Todo; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; use Symfony\Component\HttpClient\HttpClient; use Symfony\Component\HttpFoundation\Response; class ArtworkRepository { const API_URL = 'https://collectionapi.metmuseum.org/public/collection/v1/'; const MAX_ARTWORK = 2; public function findArtworksByCountry(string $country, $category='Paintings'): array { $client = HttpClient::create(); $country = ucfirst($country); $query = $country; $url = self::API_URL . 'search?geoLocation=' . $country. '&isHighlight=true&medium='. $category.'&q='. $query; $response = $client->request( 'GET', $url ); if($response->getStatusCode() === Response::HTTP_OK) { $apiArtworks = $response->toArray()['objectIDs']; if(!empty($apiArtworks) && count($apiArtworks) >= self::MAX_ARTWORK) { $randowKeys = array_rand($apiArtworks, self::MAX_ARTWORK); foreach ($randowKeys as $key) { $artworkApiId = $apiArtworks[$key]; $artworks[] = $this->findArtwork($artworkApiId); } } } return $artworks ?? []; } public function findArtwork(int $id) :Artwork { $client = HttpClient::create(); $response = $client->request('GET', self::API_URL . 'objects/' . $id); $apiArtwork = $response->toArray(); return new Artwork($apiArtwork); } } <file_sep><?php namespace App\Entity; class Artwork { private $id; private $year; private $image; private $category; private $title; private $country; private $artist; public function __construct(?array $data) { if(!empty($data)) { $this->hydrate($data); } } public function hydrate (array $data) :void { $this->setId($data['objectID']); $this->setYear($data['objectDate']); $this->setImage($data['primaryImageSmall']); $this->setCategory($data['medium']); $this->setTitle($data['title']); $this->setCountry($data['country']); $this->setArtist($data['artistDisplayName']); } /** * @return mixed */ public function getId() { return $this->id; } /** * @param mixed $id */ public function setId($id): void { $this->id = $id; } /** * @return mixed */ public function getYear() { return $this->year; } /** * @param mixed $year */ public function setYear($year): void { $this->year = $year; } /** * @return mixed */ public function getImage() { return $this->image; } /** * @param mixed $image */ public function setImage($image): void { $this->image = $image; } /** * @return mixed */ public function getCategory() { return $this->category; } /** * @param mixed $category */ public function setCategory($category): void { $this->category = $category; } /** * @return mixed */ public function getTitle() { return $this->title; } /** * @param mixed $title */ public function setTitle($title): void { $this->title = $title; } /** * @return mixed */ public function getCountry() { return $this->country; } /** * @param mixed $country */ public function setCountry($country): void { $this->country = $country; } /** * @return mixed */ public function getArtist() { return $this->artist; } /** * @param mixed $artist */ public function setArtist($artist): void { $this->artist = $artist; } } <file_sep><?php namespace App\Repository; use App\Entity\Todo; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; use Symfony\Component\HttpClient\HttpClient; class TodoRepository { const API_URL = 'https://jsonplaceholder.typicode.com/todos/'; private $parameterBag; // recupération du parameter definit dans le fichier services.yaml public function __construct(ParameterBagInterface $parameterBag) { $this->parameterBag = $parameterBag; } public function findTodo(int $id) :Todo { // $key = $this->parameterBag->get('apiWindyKey'); // dump($key); $client = HttpClient::create(); $response = $client->request('GET', self::API_URL .$id); $todoFromApi = $response->toArray(); $todo = new Todo(); $todo->hydrate($todoFromApi); return $todo; } public function findAllTodo() :array { $client = HttpClient::create(); $response = $client->request('GET', self::API_URL); $todosFromApi = $response->toArray(); foreach ($todosFromApi as $todoFromApi) { $todo = new Todo(); $todo->hydrate($todoFromApi); $todos[] = $todo; } return $todos; } } <file_sep><?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass="App\Repository\CountryCocktailRepository") */ class CountryCocktail { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=3) */ private $countryIso; /** * @ORM\Column(type="integer") */ private $cocktailApiId; public function getId(): ?int { return $this->id; } public function getCountryIso(): ?string { return $this->countryIso; } public function setCountryIso(string $countryIso): self { $this->countryIso = $countryIso; return $this; } public function getCocktailApiId(): ?int { return $this->cocktailApiId; } public function setCocktailApiId(int $cocktailApiId): self { $this->cocktailApiId = $cocktailApiId; return $this; } } <file_sep><?php namespace App\Repository; use App\Entity\Cocktail; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; use Symfony\Component\HttpClient\HttpClient; use Symfony\Component\HttpFoundation\Response; class CocktailRepository { const API_URL = 'https://www.thecocktaildb.com/api/json/v1/1/'; public function findCocktail(int $id): ?Cocktail { $client = HttpClient::create(); $response = $client->request('GET', self::API_URL . 'lookup.php?i=' . $id); if($response->getStatusCode() === Response::HTTP_OK) { $apiCocktail = $response->toArray()['drinks'][0] ?? []; if(!empty($apiCocktail)) { $cocktail = new Cocktail($apiCocktail); } } return $cocktail ?? null; } } <file_sep><?php namespace App\Entity; class Webcam { private $id; private $country; private $image; private $place; public function __construct(?array $data) { if(!empty($data)) { $this->hydrate($data); } } public function hydrate (array $data) :void { dump($data); $this->setId($data['id']); $this->setImage($data['image']['current']['preview']); $this->setCountry($data['location']['country']); $this->setPlace($data['location']['city']); } /** * @return mixed */ public function getPlace() { return $this->place; } /** * @param mixed $place */ public function setPlace($place): void { $this->place = $place; } /** * @return mixed */ public function getId() { return $this->id; } /** * @param mixed $id */ public function setId($id): void { $this->id = $id; } /** * @return mixed */ public function getCountry() { return $this->country; } /** * @param mixed $country */ public function setCountry($country): void { $this->country = $country; } /** * @return mixed */ public function getImage() { return $this->image; } /** * @param mixed $image */ public function setImage($image): void { $this->image = $image; } } <file_sep><?php namespace App\Controller; use App\Repository\ArtworkRepository; use App\Repository\CocktailRepository; use App\Repository\CountryCocktailRepository; use App\Repository\TodoRepository; use App\Repository\WebcamRepository; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Intl\Countries; use Symfony\Component\Intl\Intl; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\HttpClient\HttpClient; class HomeController extends AbstractController { /** * @Route("/home/{country}", name="home") * @param string $country * @param ArtworkRepository $artworkRepository * @param CocktailRepository $cocktailRepository * @param WebcamRepository $webcamRepository * @param CountryCocktailRepository $countryCocktailRepository * @return \Symfony\Component\HttpFoundation\Response */ public function index( string $country, ArtworkRepository $artworkRepository, CocktailRepository $cocktailRepository, WebcamRepository $webcamRepository, CountryCocktailRepository $countryCocktailRepository) { $webcam = $webcamRepository->findWebcamByCountry($country); $countryName = Countries::getName($country); $artworks = $artworkRepository->findArtworksByCountry($countryName); $cocktails = $countryCocktailRepository->findByCountryIso($country); if ($cocktails) { $cocktailRand = $cocktails[array_rand($cocktails)]; $cocktail = $cocktailRepository->findCocktail($cocktailRand->getCocktailApiId()); } return $this->render('home/index.html.twig', [ 'artworks' => $artworks ?? [], 'cocktail' => $cocktail ?? null, 'webcam' => $webcam, 'country' => $country, ]); } } <file_sep>am4core.ready(function() { // Themes begin am4core.useTheme(am4themes_dataviz); am4core.useTheme(am4themes_animated); // Themes end var chart = am4core.create("chartdiv", am4maps.MapChart); // Set map definition chart.geodata = am4geodata_worldLow; // Set projection chart.projection = new am4maps.projections.Orthographic(); chart.panBehavior = "rotateLongLat"; chart.deltaLatitude = -20; chart.padding(20,20,20,20); // limits vertical rotation chart.adapter.add("deltaLatitude", function(delatLatitude){ return am4core.math.fitToRange(delatLatitude, -90, 90); }) // Create map polygon series var polygonSeries = chart.series.push(new am4maps.MapPolygonSeries()); // Make map load polygon (like country names) data from GeoJSON polygonSeries.useGeodata = true; // Configure series var polygonTemplate = polygonSeries.mapPolygons.template; polygonTemplate.tooltipText = "{name}"; polygonTemplate.fill = am4core.color("#eecb8f"); polygonTemplate.stroke = am4core.color("#bb9f6f"); polygonTemplate.strokeWidth = 0.5; var graticuleSeries = chart.series.push(new am4maps.GraticuleSeries()); graticuleSeries.mapLines.template.line.stroke = am4core.color("#ffffff"); graticuleSeries.mapLines.template.line.strokeOpacity = 0.08; graticuleSeries.fitExtent = false; chart.backgroundSeries.mapPolygons.template.polygon.fillOpacity = 0.8; chart.backgroundSeries.mapPolygons.template.polygon.fill = am4core.color("#eecb8f"); // Create hover state and set alternative fill color var hs = polygonTemplate.states.create("hover"); hs.properties.fill = chart.colors.getIndex(0).brighten(-0.5); let animation; setTimeout(function(){ animation = chart.animate({property:"deltaLongitude", to:100000}, 20000000); }, 3000) chart.seriesContainer.events.on("down", function(){ if(animation){ animation.stop(); } }) var polygonTemplate = polygonSeries.mapPolygons.template; polygonTemplate.events.on("hit", function(ev) { // zoom to an object ev.target.series.chart.zoomToMapObject(ev.target); // get object info let countryIso = ev.target.dataItem.dataContext.id; document.location.href = '/home/'+countryIso; }); }); // end am4core.ready() <file_sep><?php namespace App\Entity; class Cocktail { private $id; private $name; private $alcoholic; private $glass; private $instructions; private $image; private $ingredients; public function __construct(?array $data) { if(!empty($data)) { $this->hydrate($data); } } public function hydrate (array $data) :void { $this->setId($data['idDrink']); $this->setName($data['strDrink']); $this->setAlcoholic($data['strAlcoholic']); $this->setGlass($data['strGlass']); $this->setInstructions($data['strInstructions']); $this->setImage($data['strDrinkThumb']); for($i=0;$i<15;$i++) { if(!empty($data['strIngredient'.$i])) { $ingredients[] = ['name'=>$data['strIngredient'.$i], 'quantity'=>$data['strMeasure'.$i]]; } } $this->setIngredients($ingredients ?? []); } /** * @return mixed */ public function getId() { return $this->id; } /** * @param mixed $id */ public function setId($id): void { $this->id = $id; } /** * @return mixed */ public function getName() { return $this->name; } /** * @param mixed $name */ public function setName($name): void { $this->name = $name; } /** * @return mixed */ public function getAlcoholic() { return $this->alcoholic; } /** * @param mixed $alcoholic */ public function setAlcoholic($alcoholic): void { $this->alcoholic = $alcoholic; } /** * @return mixed */ public function getGlass() { return $this->glass; } /** * @param mixed $glass */ public function setGlass($glass): void { $this->glass = $glass; } /** * @return mixed */ public function getInstructions() { return $this->instructions; } /** * @param mixed $instructions */ public function setInstructions($instructions): void { $this->instructions = $instructions; } /** * @return mixed */ public function getImage() { return $this->image; } /** * @param mixed $image */ public function setImage($image): void { $this->image = $image; } /** * @return mixed */ public function getIngredients() { return $this->ingredients; } /** * @param mixed $ingredients */ public function setIngredients($ingredients): void { $this->ingredients = $ingredients; } } <file_sep><?php namespace App\Repository; use App\Entity\Artwork; use App\Entity\Cocktail; use App\Entity\Webcam; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; use Symfony\Component\HttpClient\HttpClient; use Symfony\Component\HttpFoundation\Response; class WebcamRepository { const API_URL = 'https://api.windy.com/api/webcams/v2/'; private $parameterBag; // récupération du parameter définit dans le fichier services.yaml public function __construct(ParameterBagInterface $parameterBag) { $this->parameterBag = $parameterBag; } public function findWebcamByCountry(string $country) :?Webcam { $apiWindyKey = $this->parameterBag->get('apiWindyKey'); $client = HttpClient::create(); $response = $client->request('GET', self::API_URL . 'list/country=' . $country . '/category=beach' . "?show=webcams:location,image&key=" . $apiWindyKey); if($response->getStatusCode() === Response::HTTP_OK) { $apiWebcams = $response->toArray()['result']['webcams']; if(!empty($apiWebcams)) { $key = array_rand($apiWebcams); $webcam = new Webcam($apiWebcams[$key]); } } return $webcam ?? null; } } <file_sep><?php namespace App\DataFixtures; use App\Entity\CountryCocktail; use Doctrine\Bundle\FixturesBundle\Fixture; use Doctrine\Persistence\ObjectManager; class CountryCocktailFixtures extends Fixture { public function load(ObjectManager $manager) { // $product = new Product(); // $manager->persist($product); $cocktails = [ "US" => [11008], "MX" => [11007, 13621], "CU" => [11000, 11288], "FR" => [17201, 11003], "IT" => [17215], ]; foreach ($cocktails as $countryIso => $cocktailIds) { foreach ($cocktailIds as $cocktailId) { $countryCocktail = new CountryCocktail(); $countryCocktail->setCountryIso($countryIso); $countryCocktail->setCocktailApiId($cocktailId); $manager->persist($countryCocktail); } } $manager->flush(); } } <file_sep><?php namespace App\Entity; class Todo { private $userId; private $title; private $completed; public function hydrate(array $todo) :void { $this->setTitle($todo['title']); $this->setCompleted($todo['completed']); $this->setUserId($todo['userId']); } /** * @return mixed */ public function getUserId() { return $this->userId; } /** * @param mixed $userId */ public function setUserId($userId): void { $this->userId = $userId; } /** * @return mixed */ public function getTitle() { return $this->title; } /** * @param mixed $title */ public function setTitle($title): void { $this->title = $title; } /** * @return mixed */ public function getCompleted() { return $this->completed; } /** * @param mixed $completed */ public function setCompleted($completed): void { $this->completed = $completed; } }
1bfda19b6df4920e5be20823fe72c20636bfbe37
[ "JavaScript", "PHP" ]
12
PHP
WildCodeSchool/orleans-2003-hackathon1-trainers
14843c7f1c43bf0f352c27add20a8cbc968d4bdf
f80f23d83379c4aa7383b5e3e14aa714f189617d
refs/heads/master
<file_sep>import face_recognition image_of_jim = face_recognition.load_image_file( "./face_recognition/img/known/<NAME>.jpg" ) jim_face_encoding = face_recognition.face_encodings(image_of_jim)[0] unknow_image = face_recognition.load_image_file( "face_recognition//img//unknown//Dumb.jpg" ) unknown_face_encoding = face_recognition.face_encodings(unknow_image)[0] # compare faces results = face_recognition.compare_faces([jim_face_encoding], unknown_face_encoding) if results[0]: print("This is <NAME>") else: print("This is NOT <NAME>") <file_sep>import numpy as np t = np.array([2, 3, 5, 7]) nc = np.array([250, 300, 200, 250]) sc = np.sum(nc) p = nc / sc pa = np.cumsum(p) np.random.seed(0) u = np.random.random(size=100) j = 0 # contador de datos de U di = np.empty(shape=[len(u)]) for x in u: i = 0 # contador de prob while i < len(pa): if x < pa[i]: di[j] = t[i] i = len(pa) else: i = i + 1 j = j + 1 print(di) <file_sep>import numpy as np import cv2 face_cascade = cv2.CascadeClassifier("cascades//data//haarcascade_frontalface_alt2.xml") cap = cv2.VideoCapture(0) while True: # Para capturar frame por frame ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, scaleFactor=1.5, minNeighbors=5) for (x, y, w, h) in faces: print(x, y, w, h) # The region of interes it's the square made of h * w roi_gray = gray[y : y + h, x : x + w] roi_frame = frame[y : y + h, x : x + w] # Recognized? deep learning model predict keras, tensorflow, pytorch, scikit learn img_item = "my_image.png" # Para guardar una imagen en un archivo especificado (nombre y formato,arreglo numpy) cv2.imwrite(img_item, roi_gray) color = (51, 255, 255) # BGR 0-255 and this time its blue stroke = 2 # How thick ists the line of the rectangle end_coord_x = x + w end_coord_y = y + h cv2.rectangle(frame, (x, y), (end_coord_x, end_coord_y), color, stroke) # Para mostrar los frames resultantes cv2.imshow("stiv_camera", frame) if cv2.waitKey(20) & 0xFF == ord("q"): break cap.release() cv2.destroyAllWindows() <file_sep>import face_recognition from PIL import Image, ImageDraw, ImageFont image_of_jona = face_recognition.load_image_file( "./face_recognition/img/known/Jona Kahnwald.png" ) jona_face_encoding = face_recognition.face_encodings(image_of_jona)[0] image_of_hannah = face_recognition.load_image_file( "./face_recognition/img/known/Hannah Kahnwald.png" ) hannah_face_encoding = face_recognition.face_encodings(image_of_hannah)[0] image_of_katharina = face_recognition.load_image_file( "./face_recognition/img/known/Katharina Nielsen.png" ) katharina_face_encoding = face_recognition.face_encodings(image_of_katharina)[0] image_of_noah = face_recognition.load_image_file( "./face_recognition/img/known/Noah.jpg" ) noah_face_encoding = face_recognition.face_encodings(image_of_noah)[0] # Create arrays of encodings and names known_face_encodings = [ jona_face_encoding, hannah_face_encoding, katharina_face_encoding, noah_face_encoding, ] known_face_names = ["<NAME>", "<NAME>", "<NAME>", "Noah"] # Load test image to find faces in test_image = face_recognition.load_image_file( "./face_recognition/img/groups/darl_cast.png" ) # Find faces in test image face_locations = face_recognition.face_locations(test_image) face_encodings = face_recognition.face_encodings(test_image, face_locations) # Convert to PIL format pil_image = Image.fromarray(test_image) # Create a ImageDraw instance draw = ImageDraw.Draw(pil_image) # Change the font size with ImageFont font = ImageFont.truetype("BAUHS93.TTF", 37) # Loop through faces in test image for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings): matches = face_recognition.compare_faces(known_face_encodings, face_encoding) name = "<NAME>" # If match if True in matches: first_match_index = matches.index(True) name = known_face_names[first_match_index] # Draw box draw.rectangle(((left, top), (right, bottom)), outline=(255, 255, 0)) # Draw label text_width, text_height = draw.textsize(name) draw.rectangle( ((left, bottom - text_height - 40), (right, bottom)), fill=(255, 255, 0), outline=(255, 255, 0), ) draw.text((left + 70, bottom - text_height - 35), name, fill=(0, 0, 0), font=font) del draw # Display image pil_image.show() # Save image pil_image.save("face_recog_identified.jpg") <file_sep>import matplotlib.pylab as plt import networkx as nx import numpy as np points_list = [(0, 1), (1, 5), (5, 6), (5, 4), (1, 2), (2, 3), (2, 7)] goal = 7 G = nx.Graph() G.add_edges_from(points_list) pos = nx.spring_layout(G) nx.draw_networkx_nodes(G, pos) nx.draw_networkx_edges(G, pos) nx.draw_networkx_labels(G, pos) plt.show()
77834b4cb32e72f1cb604d9d40f2e4e5055c167f
[ "Python" ]
5
Python
Stiven-Jaramillo/Sample-repo
a012ec16a4e18018477c1d344d1a16d145fc5dcc
d2676d66580bd0dfcd52b3a4ff48c79d2c329ab6
refs/heads/master
<repo_name>rouis08/rouis<file_sep>/call_daq.c /* ----------------------------------------------------------------- * * COMPANY CONFIDENTIAL * INTERNAL USE ONLY * * Copyright (C) 1997 - 2015 Synaptics Incorporated. All right reserved. * * This document contains information that is proprietary to Synaptics * Incorporated. The holder of this document shall treat all information * contained herein as confidential, shall use the information only for its * intended purpose, and shall protect the information in whole or part from * duplication, disclosure to any other party, or dissemination in any media * without the written permission of Synaptics Incorporated. * * Synaptics Incorporated * 1251 McKay Drive * San Jose, CA 95131 * (408) 904-1100 */ #include "mex.h" #include <stdio.h> #include "daq2.h" #ifdef _MSC_VER #define snprintf _snprintf #endif extern mxArray *daqObject; // static data static char errString[1024]; static double getStructFieldValue(const mxArray *s, const char *fieldName); double getStructFieldValue(const mxArray *s, const char *fieldName) { double value; mxArray *field; field = mxGetField(s, 0, fieldName); if (field == NULL || (0 == mxIsNumeric(field) && 0 == mxIsLogical(field))) { snprintf(errString, 1024, "Error reading field %s", fieldName); mexErrMsgIdAndTxt("DAQ2:call_daq:argumentError", errString); } value = mxGetScalar(field); return value; } // DAQ2 API functions void DAQ_startContinuousAcquisition(int16 type) { mxArray *prhs[2]; prhs[0] = daqObject; prhs[1] = mxCreateDoubleScalar(type); if (prhs[1] != NULL) { mexCallMATLAB(0, NULL, 2, prhs, "startContinuousAcquisition"); mxDestroyArray(prhs[1]); } } void DAQ_startSingleAcquisition(int16 type) { mxArray *prhs[2]; prhs[0] = daqObject; prhs[1] = mxCreateDoubleScalar(type); if (prhs[1] != NULL) { mexCallMATLAB(0, NULL, 2, prhs, "startSingleAcquisition"); mxDestroyArray(prhs[1]); } } void DAQ_stopAcquisition() { mxArray *prhs[1]; prhs[0] = daqObject; mexCallMATLAB(0, NULL, 1, prhs, "stopAcquisition"); } DAQFrame_t *DAQ_getFrame(int16 frameType) { mxArray *prhs[2]; mxArray *f; mxArray *buf; double *bufPtr; int buflen; int i; static DAQFrame_t daqFrame; prhs[0] = daqObject; prhs[1] = mxCreateDoubleScalar(frameType); mexCallMATLAB(1, &f, 2, prhs, "getFrame"); // plhs is a DAQFrame struct if (mxIsEmpty(f)) { return NULL; } daqFrame.owner = (uint16) getStructFieldValue(f, "owner"); daqFrame.sequence = (uint16) getStructFieldValue(f, "sequence"); daqFrame.type = (int16) getStructFieldValue(f, "type"); daqFrame.timeStamp = (uint32) getStructFieldValue(f, "timeStamp"); daqFrame.cycles = (uint32) getStructFieldValue(f, "cycles"); daqFrame.length = (uint16) getStructFieldValue(f, "length"); daqFrame.errorFlags.all = (uint16) getStructFieldValue(f, "errorFlags"); buf = mxGetField(f, 0, "buffer"); buflen = (int) mxGetNumberOfElements(buf); if (buflen > DAQ_MAX_OUTPUT_BUFFER_SIZE) { mexErrMsgIdAndTxt("DAQ2:call_daq:argumentError", "DAQ_getFrame() output buffer is too large\n"); } bufPtr = mxGetPr(buf); for (i = 0; i < buflen; i++) { daqFrame.buffer[i] = (uint16) bufPtr[i]; } for (;i < DAQ_MAX_OUTPUT_BUFFER_SIZE; i++) { daqFrame.buffer[i] = 0; } mxDestroyArray(f); return &daqFrame; } void DAQ_releaseFrame(DAQFrame_t *frame) { mxArray *prhs[2]; mxArray *buf; double *bufPtr; int i; char *fields[] = {"owner", "sequence", "type", "timeStamp", "cycles", "length", "errorFlags", "buffer"}; prhs[1] = mxCreateStructMatrix(1, 1, sizeof(fields)/sizeof(fields[0]), fields); mxSetField(prhs[1], 0, "owner", mxCreateDoubleScalar(frame->owner)); mxSetField(prhs[1], 0, "sequence", mxCreateDoubleScalar(frame->sequence)); mxSetField(prhs[1], 0, "type", mxCreateDoubleScalar(frame->type)); mxSetField(prhs[1], 0, "timeStamp", mxCreateDoubleScalar(frame->timeStamp)); mxSetField(prhs[1], 0, "cycles", mxCreateDoubleScalar(frame->cycles)); mxSetField(prhs[1], 0, "length", mxCreateDoubleScalar(frame->length)); mxSetField(prhs[1], 0, "errorFlags", mxCreateDoubleScalar(frame->errorFlags.all)); buf = mxCreateDoubleMatrix(1, frame->length, mxREAL); bufPtr = mxGetPr(buf); for (i = 0; i < frame->length; i++) { *bufPtr++ = frame->buffer[i]; } mxSetField(prhs[1], 0, "buffer", buf); prhs[0] = daqObject; mexCallMATLAB(0, NULL, 2, prhs, "releaseFrame"); mxDestroyArray(prhs[1]); } void DAQ_writeVar(uint16 addr, uint16 val) { mxArray *prhs[3]; prhs[0] = daqObject; prhs[1] = mxCreateDoubleScalar(addr); prhs[2] = mxCreateDoubleScalar(val); mexCallMATLAB(0, NULL, 3, prhs, "writeVar"); mxDestroyArray(prhs[1]); mxDestroyArray(prhs[2]); } void DAQ_writeVars(DAQVarId_t *ids, uint16 *vals, uint16 n) { mxArray *prhs[3]; int i; double *p; prhs[0] = daqObject; prhs[1] = mxCreateNumericMatrix(1, n, mxDOUBLE_CLASS, mxREAL); prhs[2] = mxCreateNumericMatrix(1, n, mxDOUBLE_CLASS, mxREAL); p = mxGetPr(prhs[1]); for (i = 0; i < n; i++) { p[i] = ids[i]; } p = mxGetPr(prhs[2]); for (i = 0; i < n; i++) { p[i] = vals[i]; } mexCallMATLAB(0, NULL, 3, prhs, "writeVars"); mxDestroyArray(prhs[1]); mxDestroyArray(prhs[2]); } void DAQ_writeArray(DAQVarId_t id, uint16 *vals, uint16 n) { mxArray *prhs[3]; int i; double *p; prhs[0] = daqObject; prhs[1] = mxCreateDoubleScalar(id); prhs[2] = mxCreateNumericMatrix(1, n, mxDOUBLE_CLASS, mxREAL); p = mxGetPr(prhs[2]); for (i = 0; i < n; i++) { p[i] = vals[i]; } mexCallMATLAB(0, NULL, 3, prhs, "writeArray"); mxDestroyArray(prhs[1]); mxDestroyArray(prhs[2]); } void DAQ_writeRepeat(DAQVarId_t id, uint16 val, uint16 len) { mxArray *prhs[4]; prhs[0] = daqObject; prhs[1] = mxCreateDoubleScalar(id); prhs[2] = mxCreateDoubleScalar(val); prhs[3] = mxCreateDoubleScalar(len); mexCallMATLAB(0, NULL, 4, prhs, "writeRepeat"); mxDestroyArray(prhs[1]); mxDestroyArray(prhs[2]); mxDestroyArray(prhs[3]); } void DAQ_writeVarAsync(uint16 addr, uint16 val) { mxArray *prhs[3]; prhs[0] = daqObject; prhs[1] = mxCreateDoubleScalar(addr); prhs[2] = mxCreateDoubleScalar(val); mexCallMATLAB(0, NULL, 3, prhs, "writeVarAsync"); mxDestroyArray(prhs[1]); mxDestroyArray(prhs[2]); } uint16 DAQ_readVar(uint16 addr) { mxArray *plhs[1], *prhs[2]; uint16 rv; prhs[0] = daqObject; prhs[1] = mxCreateDoubleScalar(addr); if (prhs[1] != NULL) { // guaranteed never NULL when run from Matlab mexCallMATLAB(1, plhs, 2, prhs, "readVar"); rv = (int16) mxGetScalar(plhs[0]); mxDestroyArray(prhs[1]); mxDestroyArray(plhs[0]); } return rv; } /* FIXME: Wrap getVersion */ <file_sep>/cbc.c #include <string.h> #include <stddef.h> #include "calc2.h" #include "cbc.h" #include "active_frame.h" #define LEN(x) (sizeof(x)/sizeof(x[0])) void getCBCs(DAQVarId_t base, uint16 *cbcs, uint16 len) { uint16 i; uint16 nRegs; uint16 cbcsPerVar; uint16 nBits; uint16 *outPtr = cbcs; uint16 mask = 0; if (IS_T1327) { cbcsPerVar = 4; nBits = 4; mask = 0xF; } else if (IS_TH2411 || IS_TH2432) { cbcsPerVar = 3; nBits = 5; mask = 0x1F; } else if (IS_TD4191) { cbcsPerVar = 3; nBits = 5; mask = 0x1F; } else if(IS_TD4300 || IS_TD4302) { cbcsPerVar = 4; nBits = 4; mask = 0xF; } else if(IS_TD4100) { cbcsPerVar = 4; nBits = 4; mask = 0xF; } nRegs = (len + cbcsPerVar - 1)/cbcsPerVar; for (i = 0; i < nRegs; i++) { uint16 v = DAQ_readVar(base + i); uint16 j; for (j = 0; j < cbcsPerVar && i * cbcsPerVar + j < len; j++) { *outPtr++ = v & mask; v >>= nBits; } } } void setCBCs(DAQVarId_t base, uint16 *cbcs, uint16 len) { uint16 i; uint16 idx; uint16 cbcsPerVar; uint16 nBits; uint16 *inPtr = cbcs; uint16 v; uint16 field; uint16 cbcVals[8]; if (IS_T1327) { cbcsPerVar = 4; nBits = 4; } else if (IS_TH2411 || IS_TH2432) { cbcsPerVar = 3; nBits = 5; } else if (IS_TD4191) { cbcsPerVar = 3; nBits = 5; } else if(IS_TD4300 || IS_TD4302) { cbcsPerVar = 4; nBits = 4; } else if(IS_TD4100) { cbcsPerVar = 4; nBits = 4; } v = 0; field = 0; idx = 0; for (i = 0; i < len; i++) { v += *inPtr++ << (nBits*field++); if (field == cbcsPerVar) { cbcVals[idx++] = v; if (idx == LEN(cbcVals)) { DAQ_writeArray(base, cbcVals, LEN(cbcVals)); base += LEN(cbcVals); idx = 0; } field = 0; v = 0; } } if (field > 0 && field != cbcsPerVar) { cbcVals[idx++] = v; } if (idx > 0) { DAQ_writeArray(base, cbcVals, idx); } } #if CONFIG_LOCAL_CBC_AUTOSCAN #if defined(__T100X_VOID_ALIGNMENT__) && (__T100X_VOID_ALIGNMENT__ == 16) # define OFFSET_16(x, y) offsetof(x, y) #else # define OFFSET_16(x, y) (offsetof(x, y)/sizeof(uint16)) #endif static void addS16ScalarToU16Array(uint16 *dst, uint16 len, int16 scalar) { for (; len > 0; len--) { *dst++ += scalar; } } void findBestCbcs(cbc_servo_command servo_cmd) { DAQFrame_t *df; uint16 lcbcBits = 4; //TODO: Add other DAQ_ReadVar too. #if IS_AFE2430 uint16 TmpCBCpl = 0; uint16 hybridMuxCbcTxPlTmp[MAX_RX] = {0}; uint16 hybridNoMuxCbcTxPlTmp[MAX_TX] = {0}; uint16 absPl = DAQ_readVar(ABS_ABS_PL); uint16 COLS = (DAQ_readVar(NUM_2D_RX_RXSET0)+DAQ_readVar(NUM_2D_RX_RXSET1)); uint16 ROWS ATTR_UNUSED = (DAQ_readVar(NUM_2D_TX_RXSET0)+DAQ_readVar(NUM_2D_TX_RXSET1)); #else // uint16 COLS = DAQ_readVar(NUM_2D_RX); uint16 ROWS ATTR_UNUSED = DAQ_readVar(NUM_2D_TX); #endif #if CONFIG_ACQ_PROX_ABS uint16 proxXCbc[MAX_RX]; uint16 proxYCbc[MAX_TX]; #endif #if CONFIG_HYBRID uint16 hybridXCbc[MAX_RX]; uint16 hybridYCbc[MAX_TX]; #endif uint16 imageCbc[MAX_RX]; uint16 dozeCbc[MAX_RX]; #if CONFIG_BUTTON uint16 hybridButtonCbc[MAX_BUTTONS]; uint16 buttonCbc[MAX_BUTTONS]; uint16 dozeButtonCbc[MAX_BUTTONS]; #endif #if CONFIG_GUARDS_NEED_CBC uint16 proxXGuardCbc[MAX_RX_GUARDS]; uint16 hybridXGuardCbc[MAX_RX_GUARDS]; uint16 proxYGuardCbc[MAX_TX_GUARDS]; uint16 hybridYGuardCbc[MAX_TX_GUARDS]; #endif struct array_t { uint16 servo_enabled; uint16 *cbcs; uint16 len; DAQVarId_t var; uint16 bursts; uint16 offset; uint16 bits; uint16 search_length; uint16 column_length; } arrays[] = { #if CONFIG_PROX { PROX_CBCS_SERVO, proxXCbc, DAQ_readVar(NUM_2D_RX), PROX_X_CBCS, DAQ_readVar(PROX_X_BURSTS), OFFSET_16(activeFrame_t, proxX), 32, 1, 1 }, { PROX_CBCS_SERVO, proxYCbc, DAQ_readVar(NUM_2D_TX), PROX_Y_CBCS, DAQ_readVar(PROX_Y_BURSTS), OFFSET_16(activeFrame_t, proxY), 32, 1, 1 }, #endif #if CONFIG_HYBRID { HYBRID_CBCS_SERVO, hybridXCbc, DAQ_readVar(NUM_2D_RX), HYBRID_X_CBCS, DAQ_readVar(HYBRID_X_BURSTS), OFFSET_16(activeFrame_t, hybridX), 16, 1, 1 }, { HYBRID_CBCS_SERVO, hybridYCbc, DAQ_readVar(NUM_2D_TX), HYBRID_Y_CBCS, DAQ_readVar(HYBRID_Y_BURSTS), OFFSET_16(activeFrame_t, hybridY), 16, 1, 1 }, #endif { DOZE_CBCS_SERVO, dozeCbc, DAQ_readVar(NUM_2D_RX), DOZE_CBCS, DAQ_readVar(DOZE_BURSTS_PER_CLUSTER), 0, 16, 2, MAX_RX + MAX_BUTTONS}, #if CONFIG_BUTTON { HYBRID_BUTTON_CBCS_SERVO, hybridButtonCbc, MAX_BUTTONS, HYBRID_BUTTON_CBCS, DAQ_readVar(BUTTON_ABS_AXIS)? DAQ_readVar(HYBRID_Y_BURSTS) : DAQ_readVar(HYBRID_X_BURSTS), OFFSET_16(activeFrame_t, hybridButtons), 16, 1, 1 }, { BUTTON_CBCS_SERVO, buttonCbc, DAQ_readVar(NUM_BUTTON_RX), BUTTON_CBCS, DAQ_readVar(TRANS_BURSTS_PER_CLUSTER), OFFSET_16(activeFrame_t, buttons), 16, DAQ_readVar(CONCURRENT_BUTTON_ACQUISITION)?DAQ_readVar(TRANS_CLUSTERS):1, MAX_BUTTONS }, { DOZE_CBCS_SERVO, dozeButtonCbc, DAQ_readVar(NUM_BUTTON_RX), DOZE_BUTTON_CBCS, DAQ_readVar(DOZE_BURSTS_PER_CLUSTER), MAX_RX, 16, 2, MAX_RX + MAX_BUTTONS }, #endif #if CONFIG_GUARDS_NEED_CBC { PROX_CBCS_SERVO, proxXGuardCbc, DAQ_readVar(NUM_RX_GUARDS), PROX_RX_GUARD_CBCS, DAQ_readVar(PROX_X_BURSTS), OFFSET_16(activeFrame_t, proxXGuards), 32, 1, 1 }, { HYBRID_CBCS_SERVO, hybridXGuardCbc, DAQ_readVar(NUM_RX_GUARDS), HYBRID_RX_GUARD_CBCS, DAQ_readVar(HYBRID_X_BURSTS), OFFSET_16(activeFrame_t, hybridXGuards), 16, 1, 1 }, { PROX_CBCS_SERVO, proxYGuardCbc, DAQ_readVar(NUM_TX_GUARDS), PROX_TX_GUARD_CBCS, DAQ_readVar(PROX_Y_BURSTS), OFFSET_16(activeFrame_t, proxYGuards), 32, 1, 1 }, { HYBRID_CBCS_SERVO, hybridYGuardCbc, DAQ_readVar(NUM_TX_GUARDS), HYBRID_TX_GUARD_CBCS, DAQ_readVar(HYBRID_Y_BURSTS), OFFSET_16(activeFrame_t, hybridYGuards), 16, 1, 1 }, #endif { TRANS_CBCS_SERVO, imageCbc, DAQ_readVar(NUM_2D_RX), TRANS_CBCS, DAQ_readVar(TRANS_BURSTS_PER_CLUSTER), OFFSET_16(activeFrame_t, image), 16, DAQ_readVar(TRANS_CLUSTERS), MAX_RX }, }; //first element in the struct must be the imagecbcs; second must be trans button cbcs int16 mask; uint16 i, j; if (IS_TH2411 || IS_TH2421) lcbcBits = 5; else if (IS_T1327) lcbcBits = 4; else if (IS_TH2432) lcbcBits = 3; { DAQVarId_t regs[] = {PROX_ENABLED, HYBRID_ENABLED, BUTTONS_ABS_ENABLED, BUTTONS_ENABLED, IMAGE_ENABLED, NOISE_ENABLED}; uint16 vals[] = {servo_cmd & PROX_CBCS_SERVO, servo_cmd & (HYBRID_CBCS_SERVO|HYBRID_BUTTON_CBCS_SERVO), servo_cmd & HYBRID_BUTTON_CBCS_SERVO, servo_cmd & BUTTON_CBCS_SERVO, servo_cmd & TRANS_CBCS_SERVO, 0}; DAQ_writeVars(regs, vals, LEN(regs)); } for (i = 0; i < LEN(arrays); i++) { memset(arrays[i].cbcs, 0, arrays[i].len*sizeof(arrays[i].cbcs[0])); } for (mask = (1 << (lcbcBits-1)); mask > 0; mask >>= 1) { struct array_t *arr = arrays; for (i = 0; i < LEN(arrays); i++, arr++) { if ( servo_cmd & arr->servo_enabled ) { addS16ScalarToU16Array(arr->cbcs, arr->len, mask); setCBCs(arr->var, arr->cbcs, arr->len); } } if( servo_cmd & DOZE_CBCS_SERVO ) { df = DAQ_getFrame(1); } else { df = DAQ_getFrame(0); } arr = arrays; for (i = 0; i < LEN(arrays); i++, arr++) { if ( servo_cmd & arr->servo_enabled ) { if (arr->bits == 32) { uint32 *raw = (uint32 *) &df->buffer[arr->offset]; uint32 threshold = (uint32) 2048*arr->bursts; for (j = 0; j < arr->len; j++) { uint16 k = 0; while(k < arr->search_length) { if (*(raw + k*arr->column_length + j) <= threshold) { arr->cbcs[j] -= mask; break; } k++; } } } else { uint16 *raw = (uint16 *) &df->buffer[arr->offset]; uint16 threshold = 2048*arr->bursts; for (j = 0; j < arr->len; j++) { uint16 k = 0; while(k < arr->search_length) { if (*(raw + k*arr->column_length + j) <= threshold) { arr->cbcs[j] -= mask; break; } k++; } } } } } DAQ_releaseFrame(df); } //set the final CBC servo result { struct array_t *arr = arrays; for (i = 0; i < LEN(arrays); i++, arr++) { if ( servo_cmd & arr->servo_enabled ) { setCBCs(arr->var, arr->cbcs, arr->len); } } } } #endif <file_sep>/cbc.h #ifndef _CBC_H #define _CBC_H #include "daq2.h" #include "calc2.h" typedef enum{ PROX_CBCS_SERVO = 1, HYBRID_CBCS_SERVO = 1<<1, TRANS_CBCS_SERVO = 1<<2, BUTTON_CBCS_SERVO = 1<<3, HYBRID_BUTTON_CBCS_SERVO = 1<<4, DOZE_CBCS_SERVO = 1<<5 } cbc_servo_command; void getCBCs(DAQVarId_t base, uint16 *cbcs, uint16 len); void setCBCs(DAQVarId_t base, uint16 *cbcs, uint16 len); void findBestCbcs(cbc_servo_command servo_cmd); #endif // _CBC_H
b7d8342178676ae5fb56807de060edc2926534eb
[ "C" ]
3
C
rouis08/rouis
0783b728f4486c6e16fc49bcad2cba95666fea1c
aff86144cc4fa0ea8021703a353e141532e6562b
refs/heads/master
<repo_name>jarty13/lab-flask-tdd<file_sep>/tests/pet_factory.py """ Test Factory to make fake objects for testing """ import factory from factory.fuzzy import FuzzyChoice from service.models import Pet class PetFactory(factory.Factory): """ Creates fake pets that you don't have to feed """ class Meta: model = Pet id = factory.Sequence(lambda n: n) name = factory.Faker("first_name") category = FuzzyChoice(choices=["dog", "cat", "bird", "fish"]) available = FuzzyChoice(choices=[True, False]) if __name__ == "__main__": for _ in range(10): pet = PetFactory() print(pet.serialize()) <file_sep>/requirements.txt # Dependencies Flask==1.1.2 Flask-API==1.1 Flask-Log-Request-ID==0.10.1 SQLAlchemy==1.3.23 Flask-SQLAlchemy==2.4.4 psycopg2-binary==2.8.4 # Runtime gunicorn==20.0.2 honcho>=1.0.1 # Code quality pylint==2.4.4 flake8==3.7.9 # Testing factory-boy==2.12.0 nose==1.3.7 pinocchio==0.4.2 httpie==2.3.0 # Code coverage coverage==4.5.4 codecov==2.1.10
b0e93e504bc1e45a4e08b0cbc30a9ada3601b9d2
[ "Python", "Text" ]
2
Python
jarty13/lab-flask-tdd
d943e84a6c2dab6660d55428be56e767fd90bc0f
e54f3212d3804ecb60f5f0227f6fc9c6cb70e2a8
refs/heads/master
<file_sep>notes. mkdir - bloating. nearly 4kb. to strip - printf. possibly remove option -p ? rm : mini_errno is 50 Bytes (!) <file_sep>#if 0 mini_start mini_open mini_errno mini_strerror mini_perror mini_writes mini_ewrites mini_eputs mini_sendfile #LDSCRIPT default LDSCRIPT text_and_bss INCLUDESRC SHRINKELF return #endif #define BLOCKSIZE 4096 void usage(){ writes("cat2 infile [outfile]\n"); exit(1); } void err(const char* f, int e){ ewrites("Couldn't open "); eputs(f); //perror("Got: "); eputs(strerror(e)); exit(e); } int main(int argc, char**argv){ if ( argc==1 || argc>3 || (argv[1][0]=='-' && argv[1][0]=='h') ) usage(); int fd = open( argv[1], O_RDONLY ); if(fd<0){ err(argv[1],errno); } int outfd = STDOUT_FILENO; if ( argc>2 ){ if ( (outfd=open(argv[2],O_WRONLY | O_CREAT ))< 0 ) err(argv[2],errno); } while ( sendfile(outfd,fd,0,BLOCKSIZE) ); if ( errno ){ eputs(strerror(errno)); //perror(errno); exit(errno); } return(0); } <file_sep>/* See LICENSE file for copyright and license details. */ #include <sys/times.h> #include <sys/wait.h> #include <errno.h> #include <stdio.h> #include <unistd.h> #include "util.h" static void usage(void) { eprintf("usage: %s [-p] cmd [arg ...]\n", argv0); } int main(int argc, char *argv[]) { pid_t pid; struct tms tms; /* user and sys times */ clock_t r0, r1; /* real time */ long ticks; /* per second */ int status, savederrno, ret = 0; ARGBEGIN { case 'p': break; default: usage(); } ARGEND if (!argc) usage(); if ((ticks = sysconf(_SC_CLK_TCK)) <= 0) eprintf("sysconf _SC_CLK_TCK:"); if ((r0 = times(&tms)) == (clock_t)-1) eprintf("times:"); switch ((pid = fork())) { case -1: eprintf("fork:"); case 0: execvp(argv[0], argv); savederrno = errno; weprintf("execvp %s:", argv[0]); _exit(126 + (savederrno == ENOENT)); default: break; } waitpid(pid, &status, 0); if ((r1 = times(&tms)) == (clock_t)-1) eprintf("times:"); if (WIFSIGNALED(status)) { fprintf(stderr, "Command terminated by signal %d\n", WTERMSIG(status)); ret = 128 + WTERMSIG(status); } fprintf(stderr, "real %f\nuser %f\nsys %f\n", (r1 - r0) / (double)ticks, tms.tms_cutime / (double)ticks, tms.tms_cstime / (double)ticks); if (WIFEXITED(status)) ret = WEXITSTATUS(status); return ret; } <file_sep>/* See LICENSE file for copyright and license details. */ #include <ctype.h> #include <string.h> #include "../util.h" #define is_odigit(c) ('0' <= c && c <= '7') size_t unescape(char *s) { static const char escapes[256] = { ['"'] = '"', ['\''] = '\'', ['\\'] = '\\', ['a'] = '\a', ['b'] = '\b', ['E'] = 033, ['e'] = 033, ['f'] = '\f', ['n'] = '\n', ['r'] = '\r', ['t'] = '\t', ['v'] = '\v' }; size_t m, q; char *r, *w; for (r = w = s; *r;) { if (*r != '\\') { *w++ = *r++; continue; } r++; if (!*r) { eprintf("null escape sequence\n"); } else if (escapes[(unsigned char)*r]) { *w++ = escapes[(unsigned char)*r++]; } else if (is_odigit(*r)) { for (q = 0, m = 4; m && is_odigit(*r); m--, r++) q = q * 8 + (*r - '0'); *w++ = MIN(q, 255); } else if (*r == 'x' && isxdigit(r[1])) { r++; for (q = 0, m = 2; m && isxdigit(*r); m--, r++) if (isdigit(*r)) q = q * 16 + (*r - '0'); else q = q * 16 + (tolower(*r) - 'a' + 10); *w++ = q; } else { eprintf("invalid escape sequence '\\%c'\n", *r); } } *w = '\0'; return w - s; } <file_sep>/* See LICENSE file for copyright and license details. */ #include <sys/resource.h> #include <errno.h> #include <pwd.h> #include <stdlib.h> #include "util.h" #ifndef PRIO_MIN #define PRIO_MIN -NZERO #endif #ifndef PRIO_MAX #define PRIO_MAX (NZERO-1) #endif static int renice(int which, int who, long adj) { errno = 0; adj += getpriority(which, who); if (errno) { weprintf("getpriority %d:", who); return 0; } adj = MAX(PRIO_MIN, MIN(adj, PRIO_MAX)); if (setpriority(which, who, (int)adj) < 0) { weprintf("setpriority %d:", who); return 0; } return 1; } static void usage(void) { eprintf("usage: %s -n num [-g | -p | -u] id ...\n", argv0); } int main(int argc, char *argv[]) { const char *adj = NULL; long val; int which = PRIO_PROCESS, ret = 0; struct passwd *pw; int who; ARGBEGIN { case 'n': adj = EARGF(usage()); break; case 'g': which = PRIO_PGRP; break; case 'p': which = PRIO_PROCESS; break; case 'u': which = PRIO_USER; break; default: usage(); } ARGEND if (!argc || !adj) usage(); val = estrtonum(adj, PRIO_MIN, PRIO_MAX); for (; *argv; argc--, argv++) { if (which == PRIO_USER) { errno = 0; if (!(pw = getpwnam(*argv))) { if (errno) weprintf("getpwnam %s:", *argv); else weprintf("getpwnam %s: no user found\n", *argv); ret = 1; continue; } who = pw->pw_uid; } else { who = estrtonum(*argv, 1, INT_MAX); } if (!renice(which, who, val)) ret = 1; } return ret; } <file_sep># A template makefile # Set Prog to the program's name # unpack minilib to the "source dir/minilib" # or set a link # copy this makefile into the source dir # done. # Or: download the file minilibcombined.c # have a look in minilib.h, which defines you need # define your switches, and include # minilibcombined.c into one of your sourcefiles. # ifndef PROG PROG=yes true false pwd wc endif # where to build object files (defaults to ./ ) BUILDDIR=build # where should the binares go? BINDIR=./static_x64 # Where minilib is installed, or should be installed to MLIBDIR=minilib # Don't create obj files, include evrything in one gcc run.(yourself) #SINGLERUN=1 # Include everything yourself NOINCLUDE=1 # Include the sources of minilib with the compat headers # (e.g., build the source of printf within the header stdio.h) #INCLUDECOMPATSRC=1 # include only the Text section in the resulting elf output #ONLYTEXT= true false yes # Set the optimization flag (default: -O1) # Be careful with that, -Os as well as -O2 seem to be problematic # Maybe more functions need to be volatile ? # OPTFLAG=-Os # GCC #GCC=gcc # LD #LD=ld # Truncate elf binaries SHRINKELF=1 # Report verbose #VERBOSE=1 # configsettings ending here ifdef BUILDPROG PROG=$(BUILDPROG) include $(MLIBDIR)/Makefile.include else #( This is a recursive makefile and will call itself with this param) ifdef with-minilib include $(MLIBDIR)/Makefile.include endif all: @$(foreach P,$(PROG),$(MAKE) BUILDPROG=$(P) OFILES=libutil && ) true cd static_x64 && make #Compile with minilib or without # Will compile with minilib, if present and found in MLIBDIR default: $(if $(wildcard $(MLIBDIR)/Makefile.include), make with-minilib=1, make native ) # build without minilib # compile with dynamic loading, os native libs native: $(PROG).c $(info call "make getminilib" to fetch and extract the "minilib" and compile $(PROG) static (recommended) ) gcc -o $(PROG) $(PROG).c # we haven't been callen recursive ifndef with-minilib ifndef BUILDDIR BUILDDIR=. endif rebuild: make clean make clean: $(shell rm $(PROG)) $(shell cd $(BUILDDIR) && rm *.o) endif getminilib: $(MLIBDIR)/minilib.h $(MLIBDIR)/minilib.h: $(info get minilib) git clone https://github.com/michael105/minilib.git $(MLIBDIR) || (( (curl https://codeload.github.com/michael105/minilib/zip/master > minilib.zip) || (wget https://codeload.github.com/michael105/minilib/zip/master)) && unzip minilib.zip && mv minilib-master $(MLIBDIR)) make rebuild install: $(PROG) cp $(PROG) /usr/local/bin endif #(ifdef BUILDPROG) <file_sep>/* See LICENSE file for copyright and license details. */ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "../utf.h" int fputrune(const Rune *r, FILE *fp) { char buf[UTFmax]; return fwrite(buf, runetochar(buf, r), 1, fp); } int efputrune(const Rune *r, FILE *fp, const char *file) { int ret; if ((ret = fputrune(r, fp)) < 0) { fprintf(stderr, "fputrune %s: %s\n", file, strerror(errno)); exit(1); } return ret; } <file_sep>/* See LICENSE file for copyright and license details. */ #include <stdio.h> #include <string.h> #include "../text.h" #include "../util.h" int linecmp(struct line *a, struct line *b) { int res = 0; if (!(res = memcmp(a->data, b->data, MIN(a->len, b->len)))) res = a->len - b->len; return res; } <file_sep>#if 0 mini_start LDSCRIPT onlytext INCLUDESRC shrinkelf return #endif int main(void){ return 0; } <file_sep> .PHONY: README.md README.md: cp README.in README.md ls -lho --time-style=long-iso | grep -oE '\s*(\S*\s*){5}$$' >> README.md echo '```'>> README.md <file_sep>//#define mini_INCLUDESRC #include "minilib.h" #include "libutil/concat.c" #include "libutil/writeall.c" #include "libutil/eprintf.c" <file_sep>/* See LICENSE file for copyright and license details. */ #include <ctype.h> #include <errno.h> #include <inttypes.h> #include <stdlib.h> #include <string.h> #include "../util.h" off_t parseoffset(const char *str) { off_t res, scale = 1; char *end; /* strictly check what strtol() usually would let pass */ if (!str || !*str || isspace(*str) || *str == '+' || *str == '-') { weprintf("parseoffset %s: invalid value\n", str); return -1; } errno = 0; res = strtol(str, &end, 0); if (errno) { weprintf("parseoffset %s: invalid value\n", str); return -1; } if (res < 0) { weprintf("parseoffset %s: negative value\n", str); return -1; } /* suffix */ if (*end) { switch (toupper((int)*end)) { case 'B': scale = 512L; break; case 'K': scale = 1024L; break; case 'M': scale = 1024L * 1024L; break; case 'G': scale = 1024L * 1024L * 1024L; break; default: weprintf("parseoffset %s: invalid suffix '%s'\n", str, end); return -1; } } /* prevent overflow */ if (res > (SSIZE_MAX / scale)) { weprintf("parseoffset %s: out of range\n", str); return -1; } return res * scale; } <file_sep>/* See LICENSE file for copyright and license details. */ #include <ctype.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "util.h" static int base = 26, start = 'a'; static int itostr(char *str, int x, int n) { str[n] = '\0'; while (n-- > 0) { str[n] = start + (x % base); x /= base; } return x ? -1 : 0; } static FILE * nextfile(FILE *f, char *buf, int plen, int slen) { static int filecount = 0; if (f) fshut(f, "<file>"); if (itostr(buf + plen, filecount++, slen) < 0) return NULL; if (!(f = fopen(buf, "w"))) eprintf("'%s':", buf); return f; } static void usage(void) { eprintf("usage: %s [-a num] [-b num[k|m|g] | -l num] [-d] " "[file [prefix]]\n", argv0); } int main(int argc, char *argv[]) { FILE *in = stdin, *out = NULL; off_t size = 1000, n; int ret = 0, ch, plen, slen = 2, always = 0; char name[NAME_MAX + 1], *prefix = "x", *file = NULL; ARGBEGIN { case 'a': slen = estrtonum(EARGF(usage()), 0, INT_MAX); break; case 'b': always = 1; if ((size = parseoffset(EARGF(usage()))) < 0) return 1; if (!size) eprintf("size needs to be positive\n"); break; case 'd': base = 10; start = '0'; break; case 'l': always = 0; size = estrtonum(EARGF(usage()), 1, MIN(LLONG_MAX, SSIZE_MAX)); break; default: usage(); } ARGEND if (*argv) file = *argv++; if (*argv) prefix = *argv++; if (*argv) usage(); plen = strlen(prefix); if (plen + slen > NAME_MAX) eprintf("names cannot exceed %d bytes\n", NAME_MAX); estrlcpy(name, prefix, sizeof(name)); if (file && strcmp(file, "-")) { if (!(in = fopen(file, "r"))) eprintf("fopen %s:", file); } n = 0; while ((ch = getc(in)) != EOF) { if (!out || n >= size) { if (!(out = nextfile(out, name, plen, slen))) eprintf("fopen: %s:", name); n = 0; } n += (always || ch == '\n'); putc(ch, out); } ret |= (in != stdin) && fshut(in, "<infile>"); ret |= out && (out != stdout) && fshut(out, "<outfile>"); ret |= fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>"); return ret; } <file_sep>/* See LICENSE file for copyright and license details. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "text.h" #include "utf.h" #include "util.h" typedef struct Range { size_t min, max; struct Range *next; } Range; static Range *list = NULL; static char mode = 0; static char *delim = "\t"; static size_t delimlen = 1; static int nflag = 0; static int sflag = 0; static void insert(Range *r) { Range *l, *p, *t; for (p = NULL, l = list; l; p = l, l = l->next) { if (r->max && r->max + 1 < l->min) { r->next = l; break; } else if (!l->max || r->min < l->max + 2) { l->min = MIN(r->min, l->min); for (p = l, t = l->next; t; p = t, t = t->next) if (r->max && r->max + 1 < t->min) break; l->max = (p->max && r->max) ? MAX(p->max, r->max) : 0; l->next = t; return; } } if (p) p->next = r; else list = r; } static void parselist(char *str) { char *s; size_t n = 1; Range *r; if (!*str) eprintf("empty list\n"); for (s = str; *s; s++) { if (*s == ' ') *s = ','; if (*s == ',') n++; } r = ereallocarray(NULL, n, sizeof(*r)); for (s = str; n; n--, s++) { r->min = (*s == '-') ? 1 : strtoul(s, &s, 10); r->max = (*s == '-') ? strtoul(s + 1, &s, 10) : r->min; r->next = NULL; if (!r->min || (r->max && r->max < r->min) || (*s && *s != ',')) eprintf("bad list value\n"); insert(r++); } } static size_t seek(struct line *s, size_t pos, size_t *prev, size_t count) { size_t n = pos - *prev, i, j; if (mode == 'b') { if (n >= s->len) return s->len; if (nflag) while (n && !UTF8_POINT(s->data[n])) n--; *prev += n; return n; } else if (mode == 'c') { for (n++, i = 0; i < s->len; i++) if (UTF8_POINT(s->data[i]) && !--n) break; } else { for (i = (count < delimlen + 1) ? 0 : delimlen; n && i < s->len; ) { if ((s->len - i) >= delimlen && !memcmp(s->data + i, delim, delimlen)) { if (!--n && count) break; i += delimlen; continue; } for (j = 1; j + i <= s->len && !fullrune(s->data + i, j); j++); i += j; } } *prev = pos; return i; } static void cut(FILE *fp, const char *fname) { Range *r; struct line s; static struct line line; static size_t size; size_t i, n, p; ssize_t len; while ((len = getline(&line.data, &size, fp)) > 0) { line.len = len; if (line.data[line.len - 1] == '\n') line.data[--line.len] = '\0'; if (mode == 'f' && !memmem(line.data, line.len, delim, delimlen)) { if (!sflag) { fwrite(line.data, 1, line.len, stdout); fputc('\n', stdout); } continue; } for (i = 0, p = 1, s = line, r = list; r; r = r->next) { n = seek(&s, r->min, &p, i); s.data += n; s.len -= n; i += (mode == 'f') ? delimlen : 1; if (!s.len) break; if (!r->max) { fwrite(s.data, 1, s.len, stdout); break; } n = seek(&s, r->max + 1, &p, i); i += (mode == 'f') ? delimlen : 1; if (fwrite(s.data, 1, n, stdout) != n) eprintf("fwrite <stdout>:"); s.data += n; s.len -= n; } putchar('\n'); } if (ferror(fp)) eprintf("getline %s:", fname); } static void usage(void) { eprintf("usage: %s -b list [-n] [file ...]\n" " %s -c list [file ...]\n" " %s -f list [-d delim] [-s] [file ...]\n", argv0, argv0, argv0); } int main(int argc, char *argv[]) { FILE *fp; int ret = 0; ARGBEGIN { case 'b': case 'c': case 'f': mode = ARGC(); parselist(EARGF(usage())); break; case 'd': delim = EARGF(usage()); if (!*delim) eprintf("empty delimiter\n"); delimlen = unescape(delim); break; case 'n': nflag = 1; break; case 's': sflag = 1; break; default: usage(); } ARGEND if (!mode) usage(); if (!argc) cut(stdin, "<stdin>"); else { for (; *argv; argc--, argv++) { if (!strcmp(*argv, "-")) { *argv = "<stdin>"; fp = stdin; } else if (!(fp = fopen(*argv, "r"))) { weprintf("fopen %s:", *argv); ret = 1; continue; } cut(fp, *argv); if (fp != stdin && fshut(fp, *argv)) ret = 1; } } ret |= fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>"); return ret; } <file_sep>/* See LICENSE file for copyright and license details. */ #include <libgen.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "util.h" static void usage(void) { eprintf("usage: %s [-dqtu] [-p directory] [template]\n", argv0); } int main(int argc, char *argv[]) { int dflag = 0, pflag = 0, qflag = 0, tflag = 0, uflag = 0, fd; char *template = "tmp.XXXXXXXXXX", *tmpdir = "", *pdir, *p, path[PATH_MAX], tmp[PATH_MAX]; size_t len; ARGBEGIN { case 'd': dflag = 1; break; case 'p': pflag = 1; pdir = EARGF(usage()); break; case 'q': qflag = 1; break; case 't': tflag = 1; break; case 'u': uflag = 1; break; default: usage(); } ARGEND if (argc > 1) usage(); else if (argc == 1) template = argv[0]; if (!argc || pflag || tflag) { if ((p = getenv("TMPDIR"))) tmpdir = p; else if (pflag) tmpdir = pdir; else tmpdir = "/tmp"; } len = estrlcpy(path, tmpdir, sizeof(path)); if (path[0] && path[len - 1] != '/') estrlcat(path, "/", sizeof(path)); estrlcpy(tmp, template, sizeof(tmp)); p = dirname(tmp); if (!(p[0] == '.' && p[1] == '\0')) { if (tflag && !pflag) eprintf("template must not contain directory separators in -t mode\n"); } estrlcat(path, template, sizeof(path)); if (dflag) { if (!mkdtemp(path)) { if (!qflag) eprintf("mkdtemp %s:", path); return 1; } } else { if ((fd = mkstemp(path)) < 0) { if (!qflag) eprintf("mkstemp %s:", path); return 1; } if (close(fd)) eprintf("close %s:", path); } if (uflag) unlink(path); puts(path); efshut(stdout, "<stdout>"); return 0; } <file_sep>/* See LICENSE file for copyright and license details. */ #include <sys/stat.h> #include <stdio.h> #include <string.h> #include "util.h" static unsigned int b64e(unsigned char *b) { unsigned int o, p = b[2] | (b[1] << 8) | (b[0] << 16); const char b64et[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; o = b64et[p & 0x3f]; p >>= 6; o = (o << 8) | b64et[p & 0x3f]; p >>= 6; o = (o << 8) | b64et[p & 0x3f]; p >>= 6; o = (o << 8) | b64et[p & 0x3f]; return o; } static void uuencodeb64(FILE *fp, const char *name, const char *s) { struct stat st; ssize_t n, m = 0; unsigned char buf[45], *pb; unsigned int out[sizeof(buf)/3 + 1], *po; if (fstat(fileno(fp), &st) < 0) eprintf("fstat %s:", s); printf("begin-base64 %o %s\n", st.st_mode & 0777, name); /* write line by line */ while ((n = fread(buf, 1, sizeof(buf), fp))) { /* clear old buffer if converting with non-multiple of 3 */ if (n != sizeof(buf) && (m = n % 3) != 0) { buf[n] = '\0'; /* m == 2 */ if (m == 1) buf[n+1] = '\0'; /* m == 1 */ } for (pb = buf, po = out; pb < buf + n; pb += 3) *po++ = b64e(pb); if (m != 0) { unsigned int mask = 0xffffffff, dest = 0x3d3d3d3d; /* m==2 -> 0x00ffffff; m==1 -> 0x0000ffff */ mask >>= ((3-m) << 3); po[-1] = (po[-1] & mask) | (dest & ~mask); } *po++ = '\n'; fwrite(out, 1, (po - out) * sizeof(unsigned int) - 3, stdout); } if (ferror(fp)) eprintf("'%s' read error:", s); puts("===="); } static void uuencode(FILE *fp, const char *name, const char *s) { struct stat st; unsigned char buf[45], *p; ssize_t n; int ch; if (fstat(fileno(fp), &st) < 0) eprintf("fstat %s:", s); printf("begin %o %s\n", st.st_mode & 0777, name); while ((n = fread(buf, 1, sizeof(buf), fp))) { ch = ' ' + (n & 0x3f); putchar(ch == ' ' ? '`' : ch); for (p = buf; n > 0; n -= 3, p += 3) { if (n < 3) { p[2] = '\0'; if (n < 2) p[1] = '\0'; } ch = ' ' + ((p[0] >> 2) & 0x3f); putchar(ch == ' ' ? '`' : ch); ch = ' ' + (((p[0] << 4) | ((p[1] >> 4) & 0xf)) & 0x3f); putchar(ch == ' ' ? '`' : ch); ch = ' ' + (((p[1] << 2) | ((p[2] >> 6) & 0x3)) & 0x3f); putchar(ch == ' ' ? '`' : ch); ch = ' ' + (p[2] & 0x3f); putchar(ch == ' ' ? '`' : ch); } putchar('\n'); } if (ferror(fp)) eprintf("'%s' read error:", s); printf("%c\nend\n", '`'); } static void usage(void) { eprintf("usage: %s [-m] [file] name\n", argv0); } int main(int argc, char *argv[]) { FILE *fp = NULL; void (*uuencode_f)(FILE *, const char *, const char *) = uuencode; int ret = 0; ARGBEGIN { case 'm': uuencode_f = uuencodeb64; break; default: usage(); } ARGEND if (!argc || argc > 2) usage(); if (argc == 1 || !strcmp(argv[0], "-")) { uuencode_f(stdin, argv[0], "<stdin>"); } else { if (!(fp = fopen(argv[0], "r"))) eprintf("fopen %s:", argv[0]); uuencode_f(fp, argv[1], argv[0]); } ret |= fp && fshut(fp, argv[0]); ret |= fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>"); return ret; } <file_sep>/* See LICENSE file for copyright and license details. */ #include <ctype.h> #include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "queue.h" #include "util.h" struct type { unsigned char format; unsigned int len; TAILQ_ENTRY(type) entry; }; static TAILQ_HEAD(head, type) head = TAILQ_HEAD_INITIALIZER(head); static unsigned char addr_format = 'o'; static off_t skip = 0; static off_t max = -1; static size_t linelen = 1; static int big_endian; static void printaddress(off_t addr) { char fmt[] = "%07j#"; if (addr_format == 'n') { fputc(' ', stdout); } else { fmt[4] = addr_format; printf(fmt, (intmax_t)addr); } } static void printchunk(const unsigned char *s, unsigned char format, size_t len) { long long res, basefac; size_t i; char fmt[] = " %#*ll#"; unsigned char c; const char *namedict[] = { "nul", "soh", "stx", "etx", "eot", "enq", "ack", "bel", "bs", "ht", "nl", "vt", "ff", "cr", "so", "si", "dle", "dc1", "dc2", "dc3", "dc4", "nak", "syn", "etb", "can", "em", "sub", "esc", "fs", "gs", "rs", "us", "sp", }; const char *escdict[] = { ['\0'] = "\\0", ['\a'] = "\\a", ['\b'] = "\\b", ['\t'] = "\\t", ['\n'] = "\\n", ['\v'] = "\\v", ['\f'] = "\\f", ['\r'] = "\\r", }; switch (format) { case 'a': c = *s & ~128; /* clear high bit as required by standard */ if (c < LEN(namedict) || c == 127) { printf(" %3s", (c == 127) ? "del" : namedict[c]); } else { printf(" %3c", c); } break; case 'c': if (strchr("\a\b\t\n\v\f\r\0", *s)) { printf(" %3s", escdict[*s]); } else if (!isprint(*s)) { printf(" %3o", *s); } else { printf(" %3c", *s); } break; default: if (big_endian) { for (res = 0, basefac = 1, i = len; i; i--) { res += s[i - 1] * basefac; basefac <<= 8; } } else { for (res = 0, basefac = 1, i = 0; i < len; i++) { res += s[i] * basefac; basefac <<= 8; } } fmt[2] = big_endian ? '-' : ' '; fmt[6] = format; printf(fmt, (int)(3 * len + len - 1), res); } } static void printline(const unsigned char *line, size_t len, off_t addr) { struct type *t = NULL; size_t i; int first = 1; unsigned char *tmp; if (TAILQ_EMPTY(&head)) goto once; TAILQ_FOREACH(t, &head, entry) { once: if (first) { printaddress(addr); first = 0; } else { printf("%*c", (addr_format == 'n') ? 1 : 7, ' '); } for (i = 0; i < len; i += MIN(len - i, t ? t->len : 4)) { if (len - i < (t ? t->len : 4)) { tmp = ecalloc(t ? t->len : 4, 1); memcpy(tmp, line + i, len - i); printchunk(tmp, t ? t->format : 'o', t ? t->len : 4); free(tmp); } else { printchunk(line + i, t ? t->format : 'o', t ? t->len : 4); } } fputc('\n', stdout); if (TAILQ_EMPTY(&head) || (!len && !first)) break; } } static int od(int fd, char *fname, int last) { static unsigned char *line; static size_t lineoff; static off_t addr; unsigned char buf[BUFSIZ]; size_t i, size = sizeof(buf); ssize_t n; while (skip - addr > 0) { n = read(fd, buf, MIN(skip - addr, sizeof(buf))); if (n < 0) weprintf("read %s:", fname); if (n <= 0) return n; addr += n; } if (!line) line = emalloc(linelen); for (;;) { if (max >= 0) size = MIN(max - (addr - skip), size); if ((n = read(fd, buf, size)) <= 0) break; for (i = 0; i < n; i++, addr++) { line[lineoff++] = buf[i]; if (lineoff == linelen) { printline(line, lineoff, addr - lineoff + 1); lineoff = 0; } } } if (n < 0) { weprintf("read %s:", fname); return n; } if (lineoff && last) printline(line, lineoff, addr - lineoff); if (last) printline((unsigned char *)"", 0, addr); return 0; } static int lcm(unsigned int a, unsigned int b) { unsigned int c, d, e; for (c = a, d = b; c ;) { e = c; c = d % c; d = e; } return a / d * b; } static void addtype(char format, int len) { struct type *t; t = emalloc(sizeof(*t)); t->format = format; t->len = len; TAILQ_INSERT_TAIL(&head, t, entry); } static void usage(void) { eprintf("usage: %s [-bdosvx] [-A addressformat] [-E | -e] [-j skip] " "[-t outputformat] [file ...]\n", argv0); } int main(int argc, char *argv[]) { int fd; struct type *t; int ret = 0, len; char *s; big_endian = (*(uint16_t *)"\0\xff" == 0xff); ARGBEGIN { case 'A': s = EARGF(usage()); if (strlen(s) != 1 || !strchr("doxn", s[0])) usage(); addr_format = s[0]; break; case 'b': addtype('o', 1); break; case 'd': addtype('u', 2); break; case 'E': case 'e': big_endian = (ARGC() == 'E'); break; case 'j': if ((skip = parseoffset(EARGF(usage()))) < 0) usage(); break; case 'N': if ((max = parseoffset(EARGF(usage()))) < 0) usage(); break; case 'o': addtype('o', 2); break; case 's': addtype('d', 2); break; case 't': s = EARGF(usage()); for (; *s; s++) { switch (*s) { case 'a': case 'c': addtype(*s, 1); break; case 'd': case 'o': case 'u': case 'x': /* todo: allow multiple digits */ if (*(s+1) > '0' && *(s+1) <= '9') { len = *(s+1) - '0'; } else { switch (*(s+1)) { case 'C': len = sizeof(char); break; case 'S': len = sizeof(short); break; case 'I': len = sizeof(int); break; case 'L': len = sizeof(long); break; default: len = sizeof(int); } } addtype(*s++, len); break; default: usage(); } } break; case 'v': /* always set - use uniq(1) to handle duplicate lines */ break; case 'x': addtype('x', 2); break; default: usage(); } ARGEND /* line length is lcm of type lengths and >= 16 by doubling */ TAILQ_FOREACH(t, &head, entry) linelen = lcm(linelen, t->len); if (TAILQ_EMPTY(&head)) linelen = 16; while (linelen < 16) linelen *= 2; if (!argc) { if (od(0, "<stdin>", 1) < 0) ret = 1; } else { for (; *argv; argc--, argv++) { if (!strcmp(*argv, "-")) { *argv = "<stdin>"; fd = 0; } else if ((fd = open(*argv, O_RDONLY)) < 0) { weprintf("open %s:", *argv); ret = 1; continue; } if (od(fd, *argv, (!*(argv + 1))) < 0) ret = 1; if (fd != 0) close(fd); } } ret |= fshut(stdout, "<stdout>") | fshut(stderr, "<stderr>"); return ret; } <file_sep>#if 0 mini_start mini_strcmp mini_strlen mini_fprintfs mini_getenv INCLUDESRC shrinkelf LDSCRIPT text_and_bss return #endif int main(int argc, char **argv, char **env ){ char *delimiter = "\n"; int a = 1; if ( argc > 1 ){ if ( argv[1][0] == '-' && argv[1][1] == '0' ){ delimiter = "\0"; a++; } } if ( argc > a ){ fprintfs( stdout, "%s: %s%s", argv[a], getenv(argv[a]), delimiter ); return(0); } for ( int a =0; env[a]; a++ ){ fprintfs(stdout, "%s%s", env[a], delimiter ); } return(0); } <file_sep>#if 0 COMPILE printf itodec eprintf prints open eprints MINIBUF 512 SHRINKELF #STRIPFLAG " " return #endif void crc32_init(uint32_t *crc_table) { uint32_t c,i; unsigned j; *crc_table = 0; for (i = 0x1000000; i > 0xfffff; i+=0x1000000) { // 1 - 256 for little_endian crc_table++; c = i;// << 24; for (j = 8; j; j--) { asm("mark:\n"); asm("add %0,%0\njnc 1f\nxor $0x04c11db7,%0\n1:\n" : "+r"(c) ); // c = c&0x80000000 ? ((c <<1 ) ^ 0x04c11db7) : ( c<<1 ); // c = (c&1) ? ((c >> 1) ^ polynomial) : (c >> 1); // little } *crc_table = c; } } int cksum(int fd, const char *s, uint32_t* crctab){ ssize_t n; size_t len = 0, i; uint32_t ck = 0; unsigned char buf[BUFSIZ]; while ((n = read(fd, buf, BUFSIZ)) > 0){ for (i = 0; i < n; i++) //ck = (ck >> 8) ^ crctab[(ck ^buf[i]) &0xff]; ck = (ck << 8) ^ crctab[(ck >> 24) ^ buf[i]]; len += n; } if (n < 0) { eprints("couldn't read ", s, "\n" ); return(1); } for (i = len; i; i >>= 8) // ck = (ck >> 8) ^ crctab[(ck ^i) &0xff]; ck = (ck << 8) ^ crctab[(ck >> 24) ^ (i & 0xFF)]; printf("%u %u %s\n", ~ck, len,s); return(0); } int main(int argc, char *argv[]){ int fd; int ret = 0; uint32_t crctab[256]; crc32_init(crctab); argv++; do{ if ( *argv==0 || (argv[0][0]=='-' && argv[0][1]==0) ){ ret |= cksum(0, "<stdin>", crctab); } else { if ((fd = open(*argv, O_RDONLY)) < 0) { eprints("Couldn't open ", *argv, "\n"); ret = 1; } else { ret |= cksum(fd, *argv, crctab); close(fd); } } } while ( *argv && *(++argv) ); exit(ret); } <file_sep>/* public domain sha512 implementation based on fips180-3 */ struct sha512 { uint64_t len; /* processed message length */ uint64_t h[8]; /* hash state */ uint8_t buf[128]; /* message block buffer */ }; enum { SHA512_DIGEST_LENGTH = 64 }; /* reset state */ void sha512_init(void *ctx); /* process message */ void sha512_update(void *ctx, const void *m, unsigned long len); /* get message digest */ /* state is ruined after sum, keep a copy if multiple sum is needed */ /* part of the message might be left in s, zero it if secrecy is needed */ void sha512_sum(void *ctx, uint8_t md[SHA512_DIGEST_LENGTH]); <file_sep>/* See LICENSE file for copyright and license details. */ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include "../util.h" double estrtod(const char *s) { char *end; double d; d = strtod(s, &end); if (end == s || *end != '\0') eprintf("%s: not a real number\n", s); return d; } <file_sep>/* See LICENSE file for copyright and license details. */ #include <sys/stat.h> #include <errno.h> #include <fcntl.h> #include <libgen.h> #include <string.h> #include <unistd.h> #include "util.h" static void usage(void) { eprintf("usage: %s [-f] [-L | -P | -s] target [name]\n" " %s [-f] [-L | -P | -s] target ... dir\n", argv0, argv0); } int main(int argc, char *argv[]) { char *targetdir = ".", *target = NULL; int ret = 0, sflag = 0, fflag = 0, dirfd = AT_FDCWD, hastarget = 0, flags = AT_SYMLINK_FOLLOW; struct stat st, tst; ARGBEGIN { case 'f': fflag = 1; break; case 'L': flags |= AT_SYMLINK_FOLLOW; break; case 'P': flags &= ~AT_SYMLINK_FOLLOW; break; case 's': sflag = 1; break; default: usage(); } ARGEND if (!argc) usage(); if (argc > 1) { if (!stat(argv[argc - 1], &st) && S_ISDIR(st.st_mode)) { if ((dirfd = open(argv[argc - 1], O_RDONLY)) < 0) eprintf("open %s:", argv[argc - 1]); targetdir = argv[argc - 1]; if (targetdir[strlen(targetdir) - 1] == '/') targetdir[strlen(targetdir) - 1] = '\0'; } else if (argc == 2) { hastarget = 1; target = argv[argc - 1]; } else { eprintf("%s: not a directory\n", argv[argc - 1]); } argv[argc - 1] = NULL; argc--; } for (; *argv; argc--, argv++) { if (!hastarget) target = basename(*argv); if (!sflag) { if (stat(*argv, &st) < 0) { weprintf("stat %s:", *argv); ret = 1; continue; } else if (fstatat(dirfd, target, &tst, AT_SYMLINK_NOFOLLOW) < 0) { if (errno != ENOENT) { weprintf("fstatat %s %s:", targetdir, target); ret = 1; continue; } } else if (st.st_dev == tst.st_dev && st.st_ino == tst.st_ino) { if (!fflag) { weprintf("%s and %s/%s are the same file\n", *argv, targetdir, target); ret = 1; } continue; } } if (fflag && unlinkat(dirfd, target, 0) < 0 && errno != ENOENT) { weprintf("unlinkat %s %s:", targetdir, target); ret = 1; continue; } if ((sflag ? symlinkat(*argv, dirfd, target) : linkat(AT_FDCWD, *argv, dirfd, target, flags)) < 0) { weprintf("%s %s <- %s/%s:", sflag ? "symlinkat" : "linkat", *argv, targetdir, target); ret = 1; } } return ret; } <file_sep>/* See LICENSE file for copyright and license details. */ #include <unistd.h> #include "../util.h" ssize_t writeall(int fd, const void *buf, size_t len) { const char *p = buf; ssize_t n; while (len) { n = write(fd, p, len); if (n <= 0) return n; p += n; len -= n; } return p - (const char *)buf; } <file_sep>#if 0 mini_start mini_exit mini_writes mini_fwrites mini_atoi mini_fopen mini_fclose mini_getc mini_putc mini_printl mini_prints mini_globals mini_buf 256 #LDSCRIPT onlytext #LDSCRIPT text_and_bss #globals_on_stack shrinkelf INCLUDESRC return #endif /* head - print the first few lines of a file Author: <NAME> */ #define DEFAULT 10 void usage(){ fwrites(STDERR_FILENO,"Usage: head [-n] [file ...]\n"); exit(1); } void do_file(n, f) int n; FILE *f; { int c; /* Print the first 'n' lines of a file. */ while (n) switch (c = getc(f)) { case EOF: return; case '\n': --n; default: putc((char) c, stdout); } } int main(argc, argv) int argc; char *argv[]; { FILE *f; int n, k, nfiles; char *ptr; /* Check for flag. Only flag is -n, to say how many lines to print. */ k = 1; ptr = argv[1]; n = DEFAULT; if (argc > 1 && *ptr++ == '-') { k++; n = atoi(ptr); if (n <= 0) usage(); } nfiles = argc - k; if (nfiles == 0) { /* Print standard input only. */ do_file(n, stdin); exit(0); } /* One or more files have been listed explicitly. */ while (k < argc) { if (nfiles > 1) { writes("==> "); prints(argv[k]); writes(" <==\n"); } f = fopen(argv[k], "r"); if (!f){ writes("head: cannot open "); prints( argv[k]); writes("\n"); } else { do_file(n, f); fclose(f); } k++; if (k < argc) printl(); } exit(0); } <file_sep>/* See LICENSE file for copyright and license details. */ #include <stdint.h> #include <stdlib.h> #include <string.h> #include "utf.h" #include "util.h" static int aflag = 0; static size_t *tablist = NULL; static size_t tablistlen = 8; static size_t parselist(const char *s) { size_t i; char *p, *tmp; tmp = estrdup(s); for (i = 0; (p = strsep(&tmp, " ,")); i++) { if (*p == '\0') eprintf("empty field in tablist\n"); tablist = ereallocarray(tablist, i + 1, sizeof(*tablist)); tablist[i] = estrtonum(p, 1, MIN(LLONG_MAX, SIZE_MAX)); if (i > 0 && tablist[i - 1] >= tablist[i]) eprintf("tablist must be ascending\n"); } tablist = ereallocarray(tablist, i + 1, sizeof(*tablist)); return i; } static void unexpandspan(size_t last, size_t col) { size_t off, i, j; Rune r; if (tablistlen == 1) { i = 0; off = last % tablist[i]; if ((col - last) + off >= tablist[i] && last < col) last -= off; r = '\t'; for (; last + tablist[i] <= col; last += tablist[i]) efputrune(&r, stdout, "<stdout>"); r = ' '; for (; last < col; last++) efputrune(&r, stdout, "<stdout>"); } else { for (i = 0; i < tablistlen; i++) if (col < tablist[i]) break; for (j = 0; j < tablistlen; j++) if (last < tablist[j]) break; r = '\t'; for (; j < i; j++) { efputrune(&r, stdout, "<stdout>"); last = tablist[j]; } r = ' '; for (; last < col; last++) efputrune(&r, stdout, "<stdout>"); } } static void unexpand(const char *file, FILE *fp) { Rune r; size_t last = 0, col = 0, i; int bol = 1; while (efgetrune(&r, fp, file)) { switch (r) { case ' ': if (!bol && !aflag) last++; col++; break; case '\t': if (tablistlen == 1) { if (!bol && !aflag) last += tablist[0] - col % tablist[0]; col += tablist[0] - col % tablist[0]; } else { for (i = 0; i < tablistlen; i++) if (col < tablist[i]) break; if (!bol && !aflag) last = tablist[i]; col = tablist[i]; } break; case '\b': if (bol || aflag) unexpandspan(last, col); col -= (col > 0); last = col; bol = 0; break; case '\n': if (bol || aflag) unexpandspan(last, col); last = col = 0; bol = 1; break; default: if (bol || aflag) unexpandspan(last, col); last = ++col; bol = 0; break; } if ((r != ' ' && r != '\t') || (!aflag && !bol)) efputrune(&r, stdout, "<stdout>"); } if (last < col && (bol || aflag)) unexpandspan(last, col); } static void usage(void) { eprintf("usage: %s [-a] [-t tablist] [file ...]\n", argv0); } int main(int argc, char *argv[]) { FILE *fp; int ret = 0; char *tl = "8"; ARGBEGIN { case 't': tl = EARGF(usage()); if (!*tl) eprintf("tablist cannot be empty\n"); /* Fallthrough: -t implies -a */ case 'a': aflag = 1; break; default: usage(); } ARGEND tablistlen = parselist(tl); if (!argc) { unexpand("<stdin>", stdin); } else { for (; *argv; argc--, argv++) { if (!strcmp(*argv, "-")) { *argv = "<stdin>"; fp = stdin; } else if (!(fp = fopen(*argv, "r"))) { weprintf("fopen %s:", *argv); ret = 1; continue; } unexpand(*argv, fp); if (fp != stdin && fshut(fp, *argv)) ret = 1; } } ret |= fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>"); return ret; } <file_sep>/* public domain md5 implementation based on rfc1321 and libtomcrypt */ #include <stdint.h> #include <string.h> #include "../md5.h" static uint32_t rol(uint32_t n, int k) { return (n << k) | (n >> (32-k)); } #define F(x,y,z) (z ^ (x & (y ^ z))) #define G(x,y,z) (y ^ (z & (y ^ x))) #define H(x,y,z) (x ^ y ^ z) #define I(x,y,z) (y ^ (x | ~z)) #define FF(a,b,c,d,w,s,t) a += F(b,c,d) + w + t; a = rol(a,s) + b #define GG(a,b,c,d,w,s,t) a += G(b,c,d) + w + t; a = rol(a,s) + b #define HH(a,b,c,d,w,s,t) a += H(b,c,d) + w + t; a = rol(a,s) + b #define II(a,b,c,d,w,s,t) a += I(b,c,d) + w + t; a = rol(a,s) + b static const uint32_t tab[64] = { 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 }; static void processblock(struct md5 *s, const uint8_t *buf) { uint32_t i, W[16], a, b, c, d; for (i = 0; i < 16; i++) { W[i] = buf[4*i]; W[i] |= (uint32_t)buf[4*i+1]<<8; W[i] |= (uint32_t)buf[4*i+2]<<16; W[i] |= (uint32_t)buf[4*i+3]<<24; } a = s->h[0]; b = s->h[1]; c = s->h[2]; d = s->h[3]; i = 0; while (i < 16) { FF(a,b,c,d, W[i], 7, tab[i]); i++; FF(d,a,b,c, W[i], 12, tab[i]); i++; FF(c,d,a,b, W[i], 17, tab[i]); i++; FF(b,c,d,a, W[i], 22, tab[i]); i++; } while (i < 32) { GG(a,b,c,d, W[(5*i+1)%16], 5, tab[i]); i++; GG(d,a,b,c, W[(5*i+1)%16], 9, tab[i]); i++; GG(c,d,a,b, W[(5*i+1)%16], 14, tab[i]); i++; GG(b,c,d,a, W[(5*i+1)%16], 20, tab[i]); i++; } while (i < 48) { HH(a,b,c,d, W[(3*i+5)%16], 4, tab[i]); i++; HH(d,a,b,c, W[(3*i+5)%16], 11, tab[i]); i++; HH(c,d,a,b, W[(3*i+5)%16], 16, tab[i]); i++; HH(b,c,d,a, W[(3*i+5)%16], 23, tab[i]); i++; } while (i < 64) { II(a,b,c,d, W[7*i%16], 6, tab[i]); i++; II(d,a,b,c, W[7*i%16], 10, tab[i]); i++; II(c,d,a,b, W[7*i%16], 15, tab[i]); i++; II(b,c,d,a, W[7*i%16], 21, tab[i]); i++; } s->h[0] += a; s->h[1] += b; s->h[2] += c; s->h[3] += d; } static void pad(struct md5 *s) { unsigned r = s->len % 64; s->buf[r++] = 0x80; if (r > 56) { memset(s->buf + r, 0, 64 - r); r = 0; processblock(s, s->buf); } memset(s->buf + r, 0, 56 - r); s->len *= 8; s->buf[56] = s->len; s->buf[57] = s->len >> 8; s->buf[58] = s->len >> 16; s->buf[59] = s->len >> 24; s->buf[60] = s->len >> 32; s->buf[61] = s->len >> 40; s->buf[62] = s->len >> 48; s->buf[63] = s->len >> 56; processblock(s, s->buf); } void md5_init(void *ctx) { struct md5 *s = ctx; s->len = 0; s->h[0] = 0x67452301; s->h[1] = 0xefcdab89; s->h[2] = 0x98badcfe; s->h[3] = 0x10325476; } void md5_sum(void *ctx, uint8_t md[MD5_DIGEST_LENGTH]) { struct md5 *s = ctx; int i; pad(s); for (i = 0; i < 4; i++) { md[4*i] = s->h[i]; md[4*i+1] = s->h[i] >> 8; md[4*i+2] = s->h[i] >> 16; md[4*i+3] = s->h[i] >> 24; } } void md5_update(void *ctx, const void *m, unsigned long len) { struct md5 *s = ctx; const uint8_t *p = m; unsigned r = s->len % 64; s->len += len; if (r) { if (len < 64 - r) { memcpy(s->buf + r, p, len); return; } memcpy(s->buf + r, p, 64 - r); len -= 64 - r; p += 64 - r; processblock(s, s->buf); } for (; len >= 64; len -= 64, p += 64) processblock(s, p); memcpy(s->buf, p, len); } <file_sep>#if 0 mini_start mini_buf 1024 mini_exit mini_vhangup mini_open mini_fopen mini_fread mini_fwrite mini_close mini_fflush mini_ioctl mini_printf mini_fprintf mini_printf mini_strncpy mini_strcmp mini_memset mini_sleep mini_ftell mini_fseek mini_fchmod mini_fchown mini_sigemptyset mini_sigaction mini_isatty mini_vexec LDSCRIPT text_and_bss shrinkelf INCLUDESRC return #endif /* See LICENSE file for copyright and license details. */ // kgetty, for kerberos. Use this for local logins only ! // The ticket cache is kept after the login, // therefore, after the first login, it's possible // to login at other virtual terminals without entering the password again. // // most of this is borrowed from the suckless project. (getty,and login) // Added the code to get kerberos working for authentication // // misc // dropping privilieges to "nobody". // this user should be present on every unix system, // with the uid/gid defined below. // if not dropping privileges, // running ksu as root would su to the given user, // with a wrong or missing password as well. // On the other hand, setting the tty up could // need root rights. // Therefore the code for dropping the user rights. #define uid_nobody 65534 #define gid_nobody 65534 //#define TEST static char *tty = "/dev/tty1"; static char *defaultterm = "linux"; static void usage(void){ printf("usage: kgetty [tty] [term] [cmd] [args...]\n"); exit(0); } void errprintf(const char *msg){ fprintf(stderr,"Error.\n"); fprintf(stderr,msg); exit(1); } void errprintf2(const char *msg1,const char *msg2){ fprintf(stderr,"Error.\n"); fprintf(stderr,msg1); fprintf(stderr,msg2); exit(1); } void warnprintf2(const char *msg1,const char *msg2){ fprintf(stderr,msg1); fprintf(stderr,msg2); fprintf(stderr,"\n"); exit(1); } int main(int argc, char *argv[]){ //struct passwd *pw; char *user; char term[128], logname[LOGIN_NAME_MAX], c; char hostname[HOST_NAME_MAX + 1]; // struct utmp usr; struct sigaction sa; FILE *fp; int fd; unsigned int i = 0; ssize_t n; long pos; uid_t uid; gid_t gid; strncpy(term, defaultterm, sizeof(term)); if (argc > 1) { tty = argv[1]; if (argc > 2) strncpy(term, argv[2], sizeof(term)); } sa.sa_handler = SIG_IGN; sa.sa_flags = 0; sigemptyset(&sa.sa_mask); sigaction(SIGHUP, &sa, NULL); // setenv("TERM", term, 1); setsid(); #ifndef TEST fd = open(tty, O_RDWR); if (fd < 0) errprintf2("open %s:", tty); if (isatty(fd) == 0) errprintf2("%s is not a tty\n", tty); /* steal the controlling terminal if necessary */ /* if (ioctl(fd, TIOCSCTTY, (void *)1) != 0) warnprintf2("TIOCSCTTY: could not set controlling tty\n"); */ vhangup(); close(fd); fd = open(tty, O_RDWR); if (fd < 0) errprintf2("open %s:", tty); dup2(fd, 0); dup2(fd, 1); dup2(fd, 2); if (fchown(fd, 0, 0) < 0) warnprintf2("fchown ", tty); if (fchmod(fd, 0600) < 0) warnprintf2("fchmod ", tty); if (fd > 2) close(fd); #endif sa.sa_handler = SIG_DFL; sa.sa_flags = 0; sigemptyset(&sa.sa_mask); sigaction(SIGHUP, &sa, NULL); /* Clear all utmp entries for this tty */ /* fp = fopen(UTMP_PATH, "r+"); if (fp) { do { pos = ftell(fp); if (fread(&usr, sizeof(usr), 1, fp) != 1) break; if (usr.ut_line[0] == '\0') continue; if (strcmp(usr.ut_line, tty) != 0) continue; memset(&usr, 0, sizeof(usr)); fseek(fp, pos, SEEK_SET); if (fwrite(&usr, sizeof(usr), 1, fp) != 1) break; } while (1); if (ferror(fp)) warnprintf2("I/O error: ", UTMP_PATH); fclose(fp); } */ //if (argc > 2) // return execvp(argv[2], argv + 2); // if (gethostname(hostname, sizeof(hostname)) == 0) // printf("Kerberos@%s - login: ", hostname); // else printf("Kerberos - login: "); fflush(stdout); /* Flush pending input */ ioctl(0, TCFLSH, (void *)0); memset(logname, 0, sizeof(logname)); while (1) { n = read(0, &c, 1); if (n < 0) errprintf("read:"); if (n == 0) return 1; if (i >= sizeof(logname) - 1) errprintf("login name too long\n"); if (c == '\n' || c == '\r') break; logname[i++] = c; } if (logname[0] == '-') errprintf("login name cannot start with '-'\n"); if (logname[0] == '\0') return 1; printf("\n"); // get gid and uid. //pw = getpwnam(&logname); // if (!pw) { //user doesn't exist /* if (errno) eprintf("getpwnam %s:", &logname); else eprintf("who are you?\n");*/ // better don't reveal, this user doesn't seem to exist. misc // hopefully this user doesn't exist. // when - well, there still is the password left to guess. // need to emulate kerberos here, somehow ? // sleep(1); // return(1); // } //pw = getpwnam("krb5-micha"); // pw = getpwnam("nobody"); // if (!pw) { // errprintf("Couldn't get uid of user nobody\n"); // } // uid = pw->pw_uid; // gid = pw->pw_gid; // if (initgroups(&logname, gid) < 0) // errprintf("initgroups:"); if (setgid(gid_nobody) < 0) errprintf("setgid:"); if (setuid(uid_nobody) < 0) errprintf("setuid:"); //printf("exec ksu.\n"); char *envp[] = { envp[0]="KRB5CCNAME=FILE:/tmp/krb_csc", envp[1]=0 }; char *argvpc[] = { argvpc[0]="init", argvpc[1]=&logname, argvpc[2]="-c", argvpc[3]="FILE:/tmp/krb5_csc", 0 }; char *argvp[] = { argvp[0]="klist", argvp[1]="/tmp/krb5_csc", argvp[2]=NULL }; int r = vexec("/usr/bin/klist",argvp,envp); i = 0; while ( r ){ // not authorized yet if ( i++ > 2 ) exit(1); r = vexec("/usr/bin/kinit",argvpc,envp); } return execve("/usr/bin/ksu",argvpc, envp ); //return execlp("/usr/bin/ksu", "ksu", &logname, "-n", &logname, "-k", NULL); //execlp("/usr/bin/id", "id", NULL); //return execlp("/usr/bin/ksu", "ksu", &logname, "-c", "FILE:/home/krb5-micha/.krb5/krb5m", NULL); //return execlp("/usr/bin/ksu", "ksu", &logname, "-k", "-n", "krb5-micha", "-c", "FILE:/tmp/krb5-micha", NULL); //return execlp("/bin/login", "login", "-p", logname, NULL); } <file_sep>/* See LICENSE file for copyright and license details. */ #include <stdio.h> #include "util.h" int main(int argc, char *argv[]) { char **p; argv0 = *argv, argv0 ? (argc--, argv++) : (void *)0; for (p = argv; ; p = (*p && *(p + 1)) ? p + 1 : argv) { fputs(*p ? *p : "y", stdout); putchar((!*p || !*(p + 1)) ? '\n' : ' '); } return 1; /* not reached */ } <file_sep>/* See LICENSE file for copyright and license details. */ #include <sys/stat.h> #include <stdlib.h> #include "util.h" static void usage(void) { eprintf("usage: %s [-m mode] name ...\n", argv0); } int main(int argc, char *argv[]) { mode_t mode = 0, mask; int mflag = 0, ret = 0; ARGBEGIN { case 'm': mflag = 1; mask = getumask(); mode = parsemode(EARGF(usage()), mode, mask); break; default: usage(); } ARGEND if (!argc) usage(); for (; *argv; argc--, argv++) { if (mkfifo(*argv, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH) < 0) { weprintf("mkfifo %s:", *argv); ret = 1; } else if (mflag) { if (chmod(*argv, mode) < 0) { weprintf("chmod %s:", *argv); ret = 1; } } } return ret; } <file_sep>#if 0 mini_start mini_writes mini_usleep LDSCRIPT text_and_bss shrinkelf INCLUDESRC return #endif // misc 2020/07 // Public domain void usage(){ writes("Usage: usleep microseconds\n"); exit(-1); } int toint( const char c[] ){ int ret = 0; while ( *c > 47 && *c < 58 ){ ret *= 10; ret += (*c-48); *c++; } return(ret); } int main(int argc, char *argv[]){ if (argc != 2){ usage(); } int v = toint( argv[1] ); if ( v < 1 ){ // -h returns 0 as well usage(); } usleep(v); return 0; } <file_sep>#define mini_buf 4096 #define mini_vsnprintf generate #define mini_itodec generate #define mini_printl generate #define mini_dtodec generate #define mini_snprintf generate #define mini_memfrob generate #define mini__itobin generate #define mini_def generate #define mini_dprintf generate #define mini_print generate #define mini_uitodec generate #define mini_ioctl generate #define mini_getcwd generate #define mini_stat generate #define mini_gettimeofday generate #define mini_dup3 generate #define mini_mprotect generate #define mini_fstat generate #define mini_creat generate #define mini_time generate #define mini_select generate #define mini_getpid generate #define mini_rename generate #define mini_dup generate #define mini_fsync generate #define mini_unlink generate #define mini_tcsetattr generate #define mini_dup2 generate #define mini_lseek generate #define mini_open generate #define mini_def generate #define mini_read generate #define mini_tcgetattr generate #define mini_ftruncate generate #define mini_close generate #define mini_write generate #define mini_itohex generate #define mini_fread generate #define mini_putchar generate #define mini_fwrite generate #define mini_feof generate #define mini_fputs generate #define mini_fprintf generate #define mini_fgetpos generate #define mini_fopen generate #define mini_rewind generate #define mini__itohex generate #define mini_sprintf generate #define mini_puts generate #define mini_ftell generate #define mini_itoHEX generate #define mini_fseek generate #define mini_fsetpos generate #define mini_fputc generate #define mini_printf generate #define mini_fclose generate #define mini_fileno generate #define mini_getenv generate #define mini_rand generate #define mini_atoi generate #define mini_srand generate #define mini_free generate #define mini_malloc generate #define mini_strcat generate #define mini_memcpy generate #define mini_strncpy generate #define mini_strcmp generate #define mini_strerror generate #define mini_strlen generate #define mini_memcmp generate #define mini_strncmp generate #define mini_memset generate #define mini_strcpy generate #define mini_isprint generate #define mini_isspace generate <file_sep>/* See LICENSE file for copyright and license details. */ #include <limits.h> #ifndef HOST_NAME_MAX #define HOST_NAME_MAX _POSIX_HOST_NAME_MAX #endif <file_sep>/* See LICENSE file for copyright and license details. */ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "util.h" static void head(FILE *fp, const char *fname, size_t n) { char *buf = NULL; size_t i = 0, size = 0; ssize_t len; while (i < n && (len = getline(&buf, &size, fp)) > 0) { fwrite(buf, 1, len, stdout); i += (len && (buf[len - 1] == '\n')); } free(buf); if (ferror(fp)) eprintf("getline %s:", fname); } static void usage(void) { eprintf("usage: %s [-num | -n num] [file ...]\n", argv0); } int main(int argc, char *argv[]) { size_t n = 10; FILE *fp; int ret = 0, newline = 0, many = 0; ARGBEGIN { case 'n': n = estrtonum(EARGF(usage()), 0, MIN(LLONG_MAX, SIZE_MAX)); break; ARGNUM: n = ARGNUMF(); break; default: usage(); } ARGEND if (!argc) { head(stdin, "<stdin>", n); } else { many = argc > 1; for (newline = 0; *argv; argc--, argv++) { if (!strcmp(*argv, "-")) { *argv = "<stdin>"; fp = stdin; } else if (!(fp = fopen(*argv, "r"))) { weprintf("fopen %s:", *argv); ret = 1; continue; } if (many) { if (newline) putchar('\n'); printf("==> %s <==\n", *argv); } newline = 1; head(fp, *argv, n); if (fp != stdin && fshut(fp, *argv)) ret = 1; } } ret |= fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>"); return ret; } <file_sep>#if 0 mini_start mini_writes mini_puts mini_printf mini_strlen mini_itodec mini_atoi mini_buf 256 mini_verbose_errstr2 mini_short_errstr mini_shortcolornames INCLUDESRC LDSCRIPT text_and_bss globals_on_stack HEADERGUARDS shrinkelf return #endif #include "minilib.h" int main(int argc, char *argv[]){ int e =0; if ( argc == 1 ){ writes("Usage: errno [-l] [-L] [errno number]\n"); exit(0); } if ( argv[1][0]=='-' ){ if ( argv[1][1] == 'l' ){ // list all errno values for ( int a=1; a <= ERRNO_MAX; a++ ){ printf("%d: %s\n", a, verbose_errstr2(a)); } } if ( argv[1][1] == 'L' ){ for ( int a=1; a <= ERRNO_MAX; a++ ){ printf(LRED"%3d:"LGREEN" %15s"NORM" %s\n", a, short_errstr(a), verbose_errstr2(a)); } } } else { e = atoi( argv[1] ); if ( e ){ puts(verbose_errstr2(e)); } } exit(e); } <file_sep>#include "sedcomp.c" #include "sedexec.c" <file_sep>/* See LICENSE file for copyright and license details. */ #include <stdlib.h> #include "utf.h" #include "util.h" static int cflag = 0; static int dflag = 0; static int sflag = 0; struct range { Rune start; Rune end; size_t quant; }; static struct { char *name; int (*check)(Rune); } classes[] = { { "alnum", isalnumrune }, { "alpha", isalpharune }, { "blank", isblankrune }, { "cntrl", iscntrlrune }, { "digit", isdigitrune }, { "graph", isgraphrune }, { "lower", islowerrune }, { "print", isprintrune }, { "punct", ispunctrune }, { "space", isspacerune }, { "upper", isupperrune }, { "xdigit", isxdigitrune }, }; static struct range *set1 = NULL; static size_t set1ranges = 0; static int (*set1check)(Rune) = NULL; static struct range *set2 = NULL; static size_t set2ranges = 0; static int (*set2check)(Rune) = NULL; static size_t rangelen(struct range r) { return (r.end - r.start + 1) * r.quant; } static size_t setlen(struct range *set, size_t setranges) { size_t len = 0, i; for (i = 0; i < setranges; i++) len += rangelen(set[i]); return len; } static int rstrmatch(Rune *r, char *s, size_t n) { size_t i; for (i = 0; i < n; i++) if (r[i] != s[i]) return 0; return 1; } static size_t makeset(char *str, struct range **set, int (**check)(Rune)) { Rune *rstr; size_t len, i, j, m, n; size_t q, setranges = 0; int factor, base; /* rstr defines at most len ranges */ unescape(str); rstr = ereallocarray(NULL, utflen(str) + 1, sizeof(*rstr)); len = utftorunestr(str, rstr); *set = ereallocarray(NULL, len, sizeof(**set)); for (i = 0; i < len; i++) { if (rstr[i] == '[') { j = i; nextbrack: if (j >= len) goto literal; for (m = j; m < len; m++) if (rstr[m] == ']') { j = m; break; } if (j == i) goto literal; /* CLASSES [=EQUIV=] (skip) */ if (j - i > 3 && rstr[i + 1] == '=' && rstr[m - 1] == '=') { if (j - i != 4) goto literal; (*set)[setranges].start = rstr[i + 2]; (*set)[setranges].end = rstr[i + 2]; (*set)[setranges].quant = 1; setranges++; i = j; continue; } /* CLASSES [:CLASS:] */ if (j - i > 3 && rstr[i + 1] == ':' && rstr[m - 1] == ':') { for (n = 0; n < LEN(classes); n++) { if (rstrmatch(rstr + i + 2, classes[n].name, j - i - 3)) { *check = classes[n].check; return 0; } } eprintf("Invalid character class.\n"); } /* REPEAT [_*n] (only allowed in set2) */ if (j - i > 2 && rstr[i + 2] == '*') { /* check if right side of '*' is a number */ q = 0; factor = 1; base = (rstr[i + 3] == '0') ? 8 : 10; for (n = j - 1; n > i + 2; n--) { if (rstr[n] < '0' || rstr[n] > '9') { n = 0; break; } q += (rstr[n] - '0') * factor; factor *= base; } if (n == 0) { j = m + 1; goto nextbrack; } (*set)[setranges].start = rstr[i + 1]; (*set)[setranges].end = rstr[i + 1]; (*set)[setranges].quant = q ? q : setlen(set1, MAX(set1ranges, 1)); setranges++; i = j; continue; } j = m + 1; goto nextbrack; } literal: /* RANGES [_-__-_], _-__-_ */ /* LITERALS _______ */ (*set)[setranges].start = rstr[i]; if (i < len - 2 && rstr[i + 1] == '-' && rstr[i + 2] >= rstr[i]) i += 2; (*set)[setranges].end = rstr[i]; (*set)[setranges].quant = 1; setranges++; } free(rstr); return setranges; } static void usage(void) { eprintf("usage: %s [-cCds] set1 [set2]\n", argv0); } int main(int argc, char *argv[]) { Rune r, lastrune = 0; size_t off1, off2, i, m; int ret = 0; ARGBEGIN { case 'c': case 'C': cflag = 1; break; case 'd': dflag = 1; break; case 's': sflag = 1; break; default: usage(); } ARGEND if (!argc || argc > 2 || (argc == 1 && dflag == sflag)) usage(); set1ranges = makeset(argv[0], &set1, &set1check); if (argc == 2) set2ranges = makeset(argv[1], &set2, &set2check); if (!dflag || (argc == 2 && sflag)) { /* sanity checks as we are translating */ if (!sflag && !set2ranges && !set2check) eprintf("cannot map to an empty set.\n"); if (set2check && set2check != islowerrune && set2check != isupperrune) { eprintf("can only map to 'lower' and 'upper' class.\n"); } } read: if (!efgetrune(&r, stdin, "<stdin>")) { ret |= fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>"); return ret; } if (argc == 1 && sflag) goto write; for (i = 0, off1 = 0; i < set1ranges; off1 += rangelen(set1[i]), i++) { if (set1[i].start <= r && r <= set1[i].end) { if (dflag) { if (cflag) goto write; else goto read; } if (cflag) goto write; /* map r to set2 */ if (set2check) { if (set2check == islowerrune) r = tolowerrune(r); else r = toupperrune(r); } else { off1 += r - set1[i].start; if (off1 > setlen(set2, set2ranges) - 1) { r = set2[set2ranges - 1].end; goto write; } for (m = 0, off2 = 0; m < set2ranges; m++) { if (off2 + rangelen(set2[m]) > off1) { m++; break; } off2 += rangelen(set2[m]); } m--; r = set2[m].start + (off1 - off2) / set2[m].quant; } goto write; } } if (set1check && set1check(r)) { if (dflag) { if (cflag) goto write; else goto read; } if (set2check) { if (set2check == islowerrune) r = tolowerrune(r); else r = toupperrune(r); } else { r = set2[set2ranges - 1].end; } goto write; } if (!dflag && cflag) { if (set2check) { if (set2check == islowerrune) r = tolowerrune(r); else r = toupperrune(r); } else { r = set2[set2ranges - 1].end; } goto write; } if (dflag && cflag) goto read; write: if (argc == 1 && sflag && r == lastrune) { if (set1check && set1check(r)) goto read; for (i = 0; i < set1ranges; i++) { if (set1[i].start <= r && r <= set1[i].end) goto read; } } if (argc == 2 && sflag && r == lastrune) { if (set2check && set2check(r)) goto read; for (i = 0; i < set2ranges; i++) { if (set2[i].start <= r && r <= set2[i].end) goto read; } } efputrune(&r, stdout, "<stdout>"); lastrune = r; goto read; } <file_sep>#if 0 mini_start LDSCRIPT onlytext INCLUDESRC shrinkelf return #endif int main(void){ return 1; } <file_sep>/* See LICENSE file for copyright and license details. */ #include <sys/stat.h> #include <sys/types.h> struct history { struct history *prev; dev_t dev; ino_t ino; }; struct recursor { void (*fn)(const char *, struct stat *st, void *, struct recursor *); struct history *hist; int depth; int maxdepth; int follow; int flags; }; enum { SAMEDEV = 1 << 0, DIRFIRST = 1 << 1, SILENT = 1 << 2, }; extern int cp_aflag; extern int cp_fflag; extern int cp_pflag; extern int cp_rflag; extern int cp_vflag; extern int cp_follow; extern int cp_status; extern int rm_fflag; extern int rm_rflag; extern int rm_status; extern int recurse_status; void recurse(const char *, void *, struct recursor *); int cp(const char *, const char *, int); void rm(const char *, struct stat *st, void *, struct recursor *); <file_sep>#if 0 mini_start mini_putchar INCLUDESRC shrinkelf return #endif /* Usage: echo [-n] [TEXT...] */ int main(int argc, char *argv[]){ int n = 1; if ( argc>1 && argv[1][0] == '-' && argv[1][1] == 'n' ) n=2; for ( int a = n; a<argc; a++ ){ if ( a>n ) putchar(' '); for ( char *c = argv[a]; *c!=0; c++ ) putchar(*c); } if ( n==1 ) putchar( '\n' ); return 0; } <file_sep>#if 0 mini_start mini_writes mini_sleep LDSCRIPT text_and_bss shrinkelf INCLUDESRC return #endif // misc 2020/06 // BSD license void usage(){ writes("Usage: sleep val[s|m|h|d]\n"); exit(-1); } int toint( const char c[] ){ int ret = 0; while ( *c > 47 && *c < 58 ){ ret *= 10; ret += (*c-48); *c++; } switch (*c) { case 'm': ret*=60; break; case 'h': ret*=60*60; break; case 'd': ret*=60*60*24; break; case ' ': case '\0': case 's': break; default: usage(); } return(ret); } int main(int argc, char *argv[]){ if (argc != 2) { usage(); } int v = toint( argv[1] ); if ( v < 1 ){ usage(); } sleep(v); return 0; } <file_sep>#if 0 mini_start mini_write mini_writes mini_ewritesl mini_read mini_malloc_brk mini_realloc mini_buf 1024 mini_group_printf INCLUDESRC return #endif #define BUF 4096 //// doesnt ork void usage(){ writes("xorpipe [-h] [-a] [-s] [-k key] [-i file] [-o file]\n\ convert input to hexadecimal, xor with key.\n\ If the key is shorter than the input, the key is repeated.\n\ \n\ If no options are supplied, read key and input from stdin.\n\ key given as hexadecimal numbers, and separated from the input by a linebreak.\n\ \n\ -h show this help\n\ -s key is given as binary string\n\ -a: convert output to ascii\n\ \n\ "); exit(0); } #define FAIL(c,err) {ewritesl(c);exit(err);} char* index(const char *s, int c){ while( *s ){ s++; if ( *s == c ) return((char*)s); } return(0); } char* xor(char *key, char *keypos, char *keyend, char *buf, int len){ for ( int a = 0; a<len; a++ ){ *buf = *keypos ^ *buf; buf++; keypos++; if ( keypos==keyend ) keypos=key; } return(keypos); } char* xor64(char *key, char *keypos, char *keyend, char *buf, int len){ for ( int a = 0; a<=(len>>3); a++ ){ *(long*)buf = (long)(*(long*)keypos ^ *(long*)buf); buf+=8; keypos+=8; if ( keypos>keyend-8 ) keypos=key; } return(keypos); } int main(int argc, char **argv){ char buf[BUF]; char *key = malloc_brk(0); // initialize to use brk with realloc int datalen = 0; char *keyend = 0; int r; // read key while ( keyend == 0 ){ // (more) memory for the key // realloc won't copy any data, since malloc_brk is used. key = realloc(key,datalen+BUF); r = read( 0, key+datalen, BUF ); datalen = datalen + r; keyend = index( key, '\n' ); } datalen--; int keylen = keyend - key ; eprintf("keylen: %d\ndatalen: %d\nkey: ",keylen,datalen); write(2,key,keylen); eprints("\n==\n"); char *keypos = key; if ( keylen < datalen ){ keypos = xor(key,key,keyend,keyend+1,datalen-keylen); write(1,keyend+1,datalen-keylen); } while ( r ){ r=read( 0, buf, BUF ); keypos = xor(key,keypos,keyend,buf,r); write(1,buf,r); } return(0); } <file_sep> static struct { const char *argv0; char parents : 1; } opt; static int do_parents_mkdir(const char *path) { const char *parent; char *path2; if (!strcmp(path, "/") || !strcmp(path, ".")) return 0; path2 = strdup(path); if (!path2) { fprintf(stderr, "%s: unable to allocate: %s\n", opt.argv0, strerror(errno)); return 1; } parent = dirname(path2); do_parents_mkdir(parent); if (mkdir(path, 0777)) { fprintf(stderr, "%s: %s: %s\n", opt.argv0, path, strerror(errno)); return 1; } free(path2); return 0; } static int do_mkdir(const char *path) { if (mkdir(path, 0777)) { fprintf(stderr, "%s: %s: %s\n", opt.argv0, path, strerror(errno)); return 1; } return 0; } void usage(){ writes("Usage: mkdir [-p] dirname\n"); exit(1); } /* Usage mkdir [-p] DIRECTORY... */ int main(int argc, const char *argv[]) { int (*mkdir_func)(const char *); int i, ret; opt.argv0 = argv[0]; for (i = 1; i < argc; i++) { if (argv[i][0] != '-') { break; } else if (!strcmp(argv[i], "-p")) { opt.parents = 1; } else { usage(); } } if (i == argc) { usage(); } mkdir_func = (opt.parents) ? do_parents_mkdir : do_mkdir; ret = 0; for (; i < argc; i++) { if (mkdir_func(argv[i])) ret = 1; } return ret; } <file_sep>#if 0 mini_start mini_puts mini_environ mini_getenv LDSCRIPT text_and_bss shrinkelf INCLUDESRC return #endif // misc 2020/06 // BSD license int main(int argc, char *argv[], char *envp[] ){ if ( argc == 1 ) for ( int a = 0;envp[a]; a++ ) puts(envp[a]); else for ( int a = 1; argv[a]; a++ ) puts(getenv(argv[a])); return(0); } <file_sep>#if 0 COMPILE strcpy ewrites fchdir ml_getcwd mini_start mini_lstat mini_chdir mini_sprintf mini_malloc_brk mini_memcpy mini_realloc mini_getdents mini_prints mini_eprintf mini_writes mini_open mini_close mini_qsort mini_alphasort #mini_errno mini_mmap mini_strcmp mini_eprintfs mini_buf 8000 mini_printf mini_itodec mini_ltodec mini_free_brk mini_brk mini_setbrk mini_ansicolors mini_syscalls COMPILE ultohex strftime prints printsl localtime_r time growablemem getcwd strcat globalregister OPTFLAG -Os PICFLAG "-fpic -pie" STRIPFLAG ' ' #LDSCRIPT #shrinkelf #FULLDEBUG return #endif // ls. first version. // todo: // extract the options (macros for big capitals) // rewrite listdir ( scan and stat at once ) // fstatat and openat // (don't change directories) // rewrite argument scanning // /* enum shortopts { opt_A,opt_B,opt_C,opt_D,opt_E,opt_F,opt_G,opt_H,opt_I,opt_J,opt_K,opt_L,opt_M, opt_N,opt_O,opt_P,opt_Q,opt_R,opt_S,opt_T,opt_U,opt_V,opt_W,opt_X,opt_Y,opt_Z, opt_a,opt_b,opt_c,opt_d,opt_e,opt_f,opt_g,opt_h,opt_i,opt_j,opt_k,opt_l,opt_m, opt_n,opt_o,opt_p,opt_q,opt_r,opt_s,opt_t,opt_u,opt_v,opt_w,opt_x,opt_y,opt_z };*/ enum shortopts { opt_A=01,opt_B=02,opt_C=04,opt_D=010,opt_E=020,opt_F=040,opt_G=0100,opt_H=0200, opt_I=0400,opt_J=01000,opt_K=02000,opt_L=04000,opt_M=010000,opt_N=020000, opt_O=040000,opt_P=0100000,opt_Q=0200000,opt_R=0400000,opt_S=01000000, opt_T=02000000,opt_U=04000000,opt_V=010000000,opt_W=020000000,opt_X=040000000, opt_Y=0100000000,opt_Z=0200000000,opt_a=0400000000,opt_b=01000000000, opt_c=02000000000,opt_d=04000000000,opt_e=010000000000,opt_f=020000000000, opt_g=040000000000,opt_h=0100000000000,opt_i=0200000000000,opt_j=0400000000000, opt_k=01000000000000,opt_l=02000000000000,opt_m=04000000000000, opt_n=010000000000000,opt_o=020000000000000,opt_p=040000000000000, opt_q=0100000000000000,opt_r=0200000000000000,opt_s=0400000000000000, opt_t=01000000000000000,opt_u=02000000000000000,opt_v=04000000000000000, opt_w=010000000000000000,opt_x=020000000000000000,opt_y=040000000000000000, opt_z=0100000000000000000 }; // better let the praeprocessor do the work, than at runtime.. #define _LIT_A 'A' #define _LIT_B 'B' #define _LIT_C 'C' #define _LIT_D 'D' #define _LIT_E 'E' #define _LIT_F 'F' #define _LIT_G 'G' #define _LIT_H 'H' #define _LIT_I 'I' #define _LIT_J 'J' #define _LIT_K 'K' #define _LIT_L 'L' #define _LIT_M 'M' #define _LIT_N 'N' #define _LIT_O 'O' #define _LIT_P 'P' #define _LIT_Q 'Q' #define _LIT_R 'R' #define _LIT_S 'S' #define _LIT_T 'T' #define _LIT_U 'U' #define _LIT_V 'V' #define _LIT_W 'W' #define _LIT_X 'X' #define _LIT_Y 'Y' #define _LIT_Z 'Z' #define _LIT_a 'a' #define _LIT_b 'b' #define _LIT_c 'c' #define _LIT_d 'd' #define _LIT_e 'e' #define _LIT_f 'f' #define _LIT_g 'g' #define _LIT_h 'h' #define _LIT_i 'i' #define _LIT_j 'j' #define _LIT_k 'k' #define _LIT_l 'l' #define _LIT_m 'm' #define _LIT_n 'n' #define _LIT_o 'o' #define _LIT_p 'p' #define _LIT_q 'q' #define _LIT_r 'r' #define _LIT_s 's' #define _LIT_t 't' #define _LIT_u 'u' #define _LIT_v 'v' #define _LIT_w 'w' #define _LIT_x 'x' #define _LIT_y 'y' #define _LIT_z 'z' // QUOTE(x) gets 'x' #define QUOTE(a) _LIT_##a #define OPT_A 01 #define OPT_B 02 #define OPT_C 04 #define OPT_D 010 #define OPT_E 020 #define OPT_F 040 #define OPT_G 0100 #define OPT_H 0200 #define OPT_I 0400 #define OPT_J 01000 #define OPT_K 02000 #define OPT_L 04000 #define OPT_M 010000 #define OPT_N 020000 #define OPT_O 040000 #define OPT_P 0100000 #define OPT_Q 0200000 #define OPT_R 0400000 #define OPT_S 01000000 #define OPT_T 02000000 #define OPT_U 04000000 #define OPT_V 010000000 #define OPT_W 020000000 #define OPT_X 040000000 #define OPT_Y 0100000000 #define OPT_Z 0200000000 #define OPT_a 0400000000 #define OPT_b 01000000000 #define OPT_c 02000000000 #define OPT_d 04000000000 #define OPT_e 010000000000 #define OPT_f 020000000000 #define OPT_g 040000000000 #define OPT_h 0100000000000 #define OPT_i 0200000000000 #define OPT_j 0400000000000 #define OPT_k 01000000000000 #define OPT_l 02000000000000 #define OPT_m 04000000000000 #define OPT_n 010000000000000 #define OPT_o 020000000000000 #define OPT_p 040000000000000 #define OPT_q 0100000000000000 #define OPT_r 0200000000000000 #define OPT_s 0400000000000000 #define OPT_t 01000000000000000 #define OPT_u 02000000000000000 #define OPT_v 04000000000000000 #define OPT_w 010000000000000000 #define OPT_x 020000000000000000 #define OPT_y 040000000000000000 #define OPT_z 0100000000000000000 void setopt( char c, long *opts ){ if ( c>= 'A' && c <= 'X' ) *opts |= (long)1<<( c-'A'); else if ( c>='a' && c<='z' ) *opts |= ((long)1<<( c-'a'+26)); } int opt( char c, long opts ){ if ( c>= 'A' && c <= 'X' ) return(opts & (long)1<<( c-'A') ? 1 : 0 ); return( opts & ((long)1<<( c-'a'+26)) ? 1 : 0 ); } void usage(){ ewrites("Usage: ls [-h] \n"); exit(1); } int de_match(const struct dirent *de){ //if ( match(de->d_name,"*.c",0) == 0 ) // return(1); return(1); } typedef struct listcolor{ int mode; char c; //char align; char* color; } _listcolor; struct listcolor colors[] = { {S_IFLNK,'l',AC_LCYAN}, {S_IFDIR,'d',AC_BLUE}, {0111,'-' ,AC_LGREEN}, // executable {S_IFREG,'-',""}, {S_IFIFO,'p',AC_BROWN}, {S_IFBLK,'b',AC_YELLOW}, {S_IFCHR,'c',AC_YELLOW}, {S_IFSOCK,'s',AC_YELLOW}, {0} }; //"globals" DEFINE_GLOBALS( { struct tm tmnow; long opts; struct stat* pstat; struct stat* statmem; } ); #define amemset(s,c,n) { asm("push %%rdi\nrep stosb\npop %%rdi": :"a"(c), "c"(n), "D"(s) : "memory" ); }; static inline void* memset(void* s, int c, int n) { //char *sp = s; //asm("rep stosb": "=D"(sp) : "D"(sp), "a"(c), "c"(n) : "memory" ); //asm("push %%rdi\nrep stosb\npop %%rdi": :"a"(c), "c"(n), "D"(s) : "memory" ); #if 0 asm( R"( push %%rdi mov %%al,%%ah mov %%ax,%%dx shl $16,%%eax or %%eax,%%edx mov %%edx,%%eax shl $32,%%rax or %%rdx,%%rax mov %%rcx,%%rdx mov %%rdi, %%rbx shr $3,%%rcx rep stosq mov %%edx,%%ecx and $0x3f, %%ecx rep stosb pop %%rdi )": :"a"(c), "c"(n), "D"(s) : "rdx", "rbx", "r12", "memory" ); #else #if 0 asm( R"( push %%rdi mov %%al,%%ah jz _mzero push %%ax push %%ax push %%ax push %%ax pop %%rax _mzero: mov %%rcx,%%rdx mov %%rdi, %%rbx shr $3,%%rcx rep stosq mov %%edx,%%ecx and $0x3f, %%ecx rep stosb pop %%rdi )": :"a"(c), "c"(n), "D"(s) : "rdx", "rbx", "r12", "memory" ); #else #if 1 asm( R"( push %%rdi mov %%rcx,%%rbx shr $3,%%rcx jz _issmaller mov $0x101010101010101,%%rdx mul %%rdx rep stosq add %%rbx,%%rdi and $0x3f,%%rbx sub %%rbx,%%rdi _issmaller: mov %%rbx,%%rcx rep stosb pop %%rdi )": :"a"(c), "c"(n), "D"(s) : "rdx", "rbx", "r12", "memory" ); #if 0 asm( R"( push %%rdi mov %%rcx,%%rbx shr $6,%%rcx jz _issmaller imul $0x1010101,%%eax,%%edx jz _isnull and $0xff,%%rbx mov %%rdx,%%rax shl $32,%%rdx or %%rdx,%%rax _isnull: rep stosq _issmaller: mov %%rbx,%%rcx rep stosb pop %%rdi )": :"a"(c), "c"(n), "D"(s) : "rdx", "rbx", "r12", "memory" ); #endif #else asm( R"( push %%rdi mov %%al,%%ah movbe %%eax,%%edx or %%eax,%%edx movbe %%rdx,%%rax or %%rdx,%%rax mov %%rcx,%%rdx and $0x3f, %%edx shr $3,%%rcx mov %%rdi, %%rbx rep stosq mov %%edx,%%ecx rep stosb pop %%rdi )": :"a"(c), "c"(n), "D"(s) : "rdx", "rbx", "r12", "memory" ); #endif #endif #endif return(s); }; void * __attribute__((noinline))xmemset( void *s, int c, int n){ #if 1 asm( R"( mov %esi,%eax mov %edx,%ecx rep stosb mov %rdi,%rax retq )"); __builtin_unreachable(); #else int a; char *sp = s; for ( a=0; a<n; a++) sp[a] = (char)c; return(s); #endif } char* humanize( char *buf, int dec, long l ){ if ( l<=0 ){ //*(long*)(buf) = 0x45452020202020; memset( buf, ' ', 6 ); buf[7] = 0; if ( l==0 ){ buf[6] = '0'; } else { buf[5] = 'E'; buf[6] = 'E'; } } else if ( l<(1024)){ sprintf(buf,"%7u",l); return(buf); } else { char *p = "kMGTPE"; // E equals 1<<60. (Exa) long s = 1024*1024, os = 10, rs=10; while ( s < l ){ os+=10; rs<<=10; s<<=10; p++; } long r = l-((l>>os)<<os); r=r/rs; sprintf(buf,"%3u.%02u%c",l>>os,r,*p); } return(buf); } // print a direntry; this assumes dirent.d_ino to be // a pointer to a stat buf (The inode nr doesn't help so much anyways..) // the pointer isn't used, when the according options (-l,-S,.. aren't set) int printentry( char *path, struct stat* st, long opts ){ char *perms = "rwx"; char *pp = perms; char permstring[12]; permstring[10]=0; int b = 1; //return(0); for ( int perm = 0400; perm; perm >>= 1 ){ if ( st->st_mode & perm ) permstring[b] = *pp; else permstring[b] = '-'; b++;pp++; if ( *pp==0 ) pp = perms; } if ( st->st_mode & S_ISUID ) permstring[3] = 'S'; if ( st->st_mode & S_ISGID ) permstring[6] = 'S'; if ( st->st_mode & S_ISVTX ) permstring[9] = 'T'; char *color=""; for ( _listcolor *lc = colors; lc->mode!=0; lc++ ){ if ( lc->mode == ( (st->st_mode) & lc->mode ) ){ color = lc->color; permstring[0]=lc->c; break; } } //if ( st->st_mode & 0111 ) // executable // color=AC_LGREEN; //prints(permstring); char sbuf[16]; humanize(sbuf,2, st->st_size); printf("%s %4d %4d %s " , permstring,st->st_uid, st->st_gid,sbuf); struct tm tm; char buf[16]; //static struct tm tmnow = { .tm_year=0 }; if ( !(GLOBALS->tmnow.tm_year) ){ time_t tnow; time((uint*)&tnow); localtime_r( &tnow, &GLOBALS->tmnow ); } localtime_r( &st->st_mtime.tv_sec, &tm ); char *fmt = "%b %e %H:%M "; if ( GLOBALS->tmnow.tm_year - tm.tm_year ){ // year differs fmt = "%b %e %Y "; } strftime( buf, 16, fmt, &tm ); printsl(buf, color,path,AC_NORM); return(0); } int invert; int alphasort_r(const void *a,const void *b){ return(-alphasort((const struct dirent**)a,(const struct dirent**)b)); } int sizesort(const void *a,const void *b){ return ( invert^(((struct stat*)(*(const struct dirent**)a)->d_ino)->st_size < ((struct stat*)(*(const struct dirent**)b)->d_ino)->st_size) ); } int accesstimesort(const void *a,const void *b){ return ( invert^((ulong)(((struct stat*)(*(const struct dirent**)a)->d_ino)->st_mtime.tv_sec) < (ulong)(((struct stat*)(*(const struct dirent**)b)->d_ino)->st_mtime.tv_sec)) ); } typedef struct _direntry{ struct dirent* dent; struct stat* st; } direntry; int listdir(const char* dir,long opts){ // save heap start long addr = getbrk(); struct dirent **list; #define _BUFSIZE 4096 int fd; if ((fd = open(dir, O_RDONLY|O_DIRECTORY|O_CLOEXEC)) < 0){ //seterrno(fd); return(fd); } char *buf; buf= malloc_brk(_BUFSIZE); if ( buf==0 ){ //seterrno(ENOMEM); return(-ENOMEM); } int len; int pos = 0; int cnt = 0; int cp = 0; int oldcp = 0; int bufpos=0; int oldpos=0; while ( (len = getdents( fd, (struct dirent*) (buf+bufpos), _BUFSIZE) )>0){ while ( pos < len + bufpos ){ struct dirent *de = (void *)(buf+pos); pos+=de->d_reclen; // select here. //if ( !(fp_select && !(fp_select(de))) ){ // selected cnt++; cp += de->d_reclen; //printf("%s\n", de->d_name ); //} if ( oldcp < oldpos ){ //copy memcpy(buf+oldcp,buf+oldpos,de->d_reclen); } oldcp=cp; oldpos=pos; } bufpos=pos; buf=realloc(buf,bufpos+_BUFSIZE); //printf("buf: %l, pos: %d, cp: %d\n",buf,pos,cp); if ( !buf) { //seterrno(ENOMEM); close(fd); return(-ENOMEM); break; } } if ( len<0 ){ close(fd); //seterrno(len); return(len); } // alloc place for the pointer list, when needed if ( cnt*sizeof(POINTER) > _BUFSIZE+(pos-cp) ){ //prints("realloc\n"); realloc(buf,cp+(cnt*sizeof(POINTER))); if ( !buf ){ //seterrno(ENOMEM); return(-ENOMEM); } } struct dirent *de; de = (void*)buf; list= (void*)(buf+cp); for(int a=0;a<cnt;a++){ *list = de; *list++; de=(void*)de+de->d_reclen; } list = (void*)(buf+cp); if ( !(GLOBALS->pstat) ){ GLOBALS->pstat=(GLOBALS->statmem=growablemem(cnt*sizeof(struct stat))); } // save the pointer, so the memory can be "free'd" on return struct stat* fpstat = GLOBALS->pstat; GLOBALS->pstat--; if ( chdir(dir) ) eprintf("Error changing directory to %s, errno: %d\n",dir,errno); errno=0; for ( int a=0; a<cnt; a++ ){ if ( lstat( list[a]->d_name, (struct stat*)GLOBALS->pstat) ){ eprintf("Err, %s errno %d\n",list[a]->d_name,errno);// pstat is a pointer to the currently free stat buf errno=0; } else { list[a]->d_ino = (ino_t)GLOBALS->pstat; GLOBALS->pstat--; } } invert=0; int (*cmp)(const void*,const void*)= (int(*)(const void*,const void*))alphasort; if ( opts & OPT_r ){ cmp=alphasort_r; invert=1; } if ( opts & OPT_S ){ cmp=sizesort; } if ( opts & OPT_t ){ cmp=accesstimesort; } qsort( list, cnt, sizeof(POINTER), cmp ); typedef struct { char *path; struct stat* st; } t_stat; t_stat* statlist = (t_stat*)GLOBALS->pstat; statlist --; t_stat* pstatl = statlist; for ( int a=0; a<cnt; a++ ){ printentry( list[a]->d_name, (struct stat*)list[a]->d_ino, opts ); if ( (opts&OPT_R) && ( (((struct stat*)list[a]->d_ino)->st_mode) & S_IFDIR ) && !((((struct stat*)list[a]->d_ino)->st_mode) & S_IFLNK ) ){ if ( !((list[a]->d_name[0] == '.' && list[a]->d_name[1] == 0 ) || (list[a]->d_name[1] != 0 && list[a]->d_name[0] == '.' && list[a]->d_name[1] == '.' && list[a]->d_name[2] == 0 )) ){ pstatl->st = (struct stat*)list[a]->d_ino; pstatl->path = list[a]->d_name; pstatl--; // grow used mem downwards } } } GLOBALS->pstat = (struct stat*)pstatl; char cwd[PATH_MAX]; int l = ml_getcwd(cwd,PATH_MAX); while( pstatl != statlist ){ pstatl++; printsl( "\n" AC_GREEN, cwd, "/", pstatl->path, ":" AC_NORM ); //printsl( "\n" AC_GREEN, cwd, "/", (*pstatl)->de->d_name, ":" AC_NORM ); listdir( pstatl->path, opts ); //listdir( (*pstatl)->de->d_name, opts ); fchdir(fd); } // free heap setbrk(addr); // "free" mmap ( but don't unmap, possibly we need it later, // and there's no real reason to free mapped pages in a short running process GLOBALS->pstat = fpstat; close(fd); return(0); } int main(int argc, char **argv){ IMPLEMENT_GLOBALS(globals); GLOBALS->opts = 0; GLOBALS->pstat = 0; struct stat st; char buf[16]; printf("hu: -%s-\n",humanize(buf,2,-1)); printf("hu: -%s-\n",humanize(buf,2,-1000)); printf("hu: -%s-\n",humanize(buf,2,0)); printf("hu: -%s-\n",humanize(buf,2,1090)); printf("hu: -%s-\n",humanize(buf,2,100)); char b2[140]; char *b = memset(b2,'a',140); memset(b2+12,'b',14); memset(b2+1,'c',3); printf("b2: %s\n",b); memset(b2+60,'v',65); printf("b2: %s\n",b); char b3[1200]; memset(b3,'x',800); printf("b3: %s\n",b3); return(0); #define opts GLOBALS->opts // define to something other for parsing docu #ifndef OPT #define OPT(flag,desc,code) case QUOTE(flag): opts |= OPT_##flag; code; break; #endif for ( *argv++; *argv && argv[0][0]=='-'; *argv++ ){ for ( char *c = argv[0]+1; *c != 0; c++ ){ switch ( *c ){ OPT(h,"Show usage",usage()); OPT(l,"Show extended info",); OPT(r,"reverse order",); OPT(S,"Sort by size",); OPT(t,"Sort by modification time",); OPT(R,"list directories recursive",); default: usage(); } } } if ( *argv == 0 ){ listdir(".",opts); } else { for (;*argv; *argv++){ lstat( *argv, &st ); if ( S_ISDIR( st.st_mode ) ){ prints("\n",*argv,":\n"); listdir(*argv,opts); } else { printentry( *argv, &st, opts ); } } } return(0); } <file_sep>#if 0 mini_buf 1024 # define headerguards, to prevent parsing the standard header HEADERGUARDS # Startup function mini_start # optimization Flag. Os,O1,O2 might be save. O3 is known to cause sometimes trouble OPTFLAG -Os # (with debug info) #OPTFLAG -g -O0 # Build minilib source INCLUDESRC # the ldscript to use # Can be one of: default, onlytext, textandbss LDSCRIPT default # Shrink the compiled binary with shrinkelf #SHRINKELF # generate debug info (-O0 -g). Overwrites OPTFLAG and shrinkelf #DEBUG # function switches. Only functions named below will be compiled mini_close mini_closedir mini_fprintf mini_fstat mini_link mini_memcmp mini_memcpy mini_memset mini_mkdir mini_open mini_opendir mini_perror mini_printf mini_readdir mini_sprintf mini_stat mini_strcat mini_strchr mini_strcmp mini_strcpy mini_strerror mini_strlen mini_strncpy mini_symlink return #endif typedef char BOOL; #define TRUE 1 #define FALSE 0 #define BUF_SIZE 4000 static int intFlag; /* * Copyright (c) 2014 by <NAME> * Permission is granted to use, distribute, or modify this source, * provided that this copyright notice remains intact. * * The "tar" built-in command. * This allows creation, extraction, and listing of tar files. */ //#include "sash.h" #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <errno.h> /* * Tar file constants. */ #define TAR_BLOCK_SIZE 512 #define TAR_NAME_SIZE 100 /* * The POSIX (and basic GNU) tar header format. * This structure is always embedded in a TAR_BLOCK_SIZE sized block * with zero padding. We only process this information minimally. */ typedef struct { char name[TAR_NAME_SIZE]; char mode[8]; char uid[8]; char gid[8]; char size[12]; char mtime[12]; char checkSum[8]; char typeFlag; char linkName[TAR_NAME_SIZE]; char magic[6]; char version[2]; char uname[32]; char gname[32]; char devMajor[8]; char devMinor[8]; char prefix[155]; } TarHeader; #define TAR_MAGIC "ustar" #define TAR_VERSION "00" #define TAR_TYPE_REGULAR '0' #define TAR_TYPE_HARD_LINK '1' #define TAR_TYPE_SOFT_LINK '2' /* * Static data. */ static BOOL listFlag; static BOOL extractFlag; static BOOL createFlag; static BOOL verboseFlag; static BOOL inHeader; static BOOL badHeader; static BOOL errorFlag; static BOOL skipFileFlag; static BOOL warnedRoot; static BOOL eofFlag; static long dataCc; static int outFd; static char outName[TAR_NAME_SIZE]; /* * Static data associated with the tar file. */ static const char * tarName; static int tarFd; static dev_t tarDev; static ino_t tarInode; /* * Local procedures to restore files from a tar file. */ static BOOL readTarFile(int fileCount, const char ** fileTable); static BOOL readData(const char * cp, int count); static BOOL createPath(const char * name, int mode); static long getOctal(const char * cp, int len); static BOOL readHeader(const TarHeader * hp, int fileCount, const char ** fileTable); /* * Local procedures to save files into a tar file. */ static void saveFile(const char * fileName, BOOL seeLinks); static void saveRegularFile(const char * fileName, const struct stat * statbuf); static void saveDirectory(const char * fileName, const struct stat * statbuf); static BOOL wantFileName(const char * fileName, int fileCount, const char ** fileTable); static void writeHeader(const char * fileName, const struct stat * statbuf); static BOOL writeTarFile(int fileCount, const char ** fileTable); static void writeTarBlock(const char * buf, int len); static BOOL putOctal(char * cp, int len, long value); int main(int argc, const char ** argv){ const char * options; BOOL successFlag; argc--; argv++; if (argc < 2) { fprintf(stderr, "Too few arguments for tar\n"); return 1; } extractFlag = FALSE; createFlag = FALSE; listFlag = FALSE; verboseFlag = FALSE; tarName = NULL; tarDev = 0; tarInode = 0; tarFd = -1; /* * Parse the options. */ options = *argv++; argc--; for (; *options; options++) { switch (*options) { case 'f': if (tarName != NULL) { fprintf(stderr, "Only one 'f' option allowed\n"); return 1; } tarName = *argv++; argc--; break; case 't': listFlag = TRUE; break; case 'x': extractFlag = TRUE; break; case 'c': createFlag = TRUE; break; case 'v': verboseFlag = TRUE; break; default: fprintf(stderr, "Unknown tar flag '%c'\n", *options); return 1; } } /* * Validate the options. */ if (extractFlag + listFlag + createFlag != 1) { fprintf(stderr, "Exactly one of 'c', 'x' or 't' must be specified\n"); return 1; } if (tarName == NULL) { fprintf(stderr, "The 'f' flag must be specified\n"); return 1; } /* * Do the correct type of action supplying the rest of the * command line arguments as the list of files to process. */ if (createFlag) successFlag = writeTarFile(argc, argv); else successFlag = readTarFile(argc, argv); return !successFlag; } /* * Read a tar file and extract or list the specified files within it. * If the list is empty than all files are extracted or listed. * Returns TRUE on success. */ static BOOL readTarFile(int fileCount, const char ** fileTable) { const char * cp; BOOL successFlag; int cc; int inCc; int blockSize; char buf[BUF_SIZE]; skipFileFlag = FALSE; badHeader = FALSE; warnedRoot = FALSE; eofFlag = FALSE; inHeader = TRUE; successFlag = TRUE; inCc = 0; dataCc = 0; outFd = -1; blockSize = sizeof(buf); cp = buf; /* * Open the tar file for reading. */ tarFd = open(tarName, O_RDONLY); if (tarFd < 0) { perror(tarName); return FALSE; } /* * Read blocks from the file until an end of file header block * has been seen. (A real end of file from a read is an error.) */ while (!intFlag && !eofFlag) { /* * Read the next block of data if necessary. * This will be a large block if possible, which we will * then process in the small tar blocks. */ if (inCc <= 0) { cp = buf; inCc = fullRead(tarFd, buf, blockSize); if (inCc < 0) { perror(tarName); successFlag = FALSE; goto done; } if (inCc == 0) { fprintf(stderr, "Unexpected end of file from \"%s\"", tarName); successFlag = FALSE; goto done; } } /* * If we are expecting a header block then examine it. */ if (inHeader) { if (!readHeader((const TarHeader *) cp, fileCount, fileTable)) successFlag = FALSE; cp += TAR_BLOCK_SIZE; inCc -= TAR_BLOCK_SIZE; continue; } /* * We are currently handling the data for a file. * Process the minimum of the amount of data we have available * and the amount left to be processed for the file. */ cc = inCc; if (cc > dataCc) cc = dataCc; if (!readData(cp, cc)) successFlag = FALSE; /* * If the amount left isn't an exact multiple of the tar block * size then round it up to the next block boundary since there * is padding at the end of the file. */ if (cc % TAR_BLOCK_SIZE) cc += TAR_BLOCK_SIZE - (cc % TAR_BLOCK_SIZE); cp += cc; inCc -= cc; } /* * Check for an interrupt. */ if (intFlag) { fprintf(stderr, "Interrupted - aborting\n"); successFlag = FALSE; } done: /* * Close the tar file if needed. */ if ((tarFd >= 0) && (close(tarFd) < 0)) { perror(tarName); successFlag = FALSE; } /* * Close the output file if needed. * This is only done here on a previous error and so no * message is required on errors. */ if (outFd >= 0) (void) close(outFd); return successFlag; } /* * Examine the header block that was just read. * This can specify the information for another file, or it can mark * the end of the tar file. Returns TRUE on success. */ static BOOL readHeader(const TarHeader * hp, int fileCount, const char ** fileTable) { int mode; int uid; int gid; long size; time_t mtime; const char * name; int cc; BOOL hardLink; BOOL softLink; /* * If the block is completely empty, then this is the end of the * archive file. If the name is null, then just skip this header. */ name = hp->name; if (*name == '\0') { for (cc = TAR_BLOCK_SIZE; cc > 0; cc--) { if (*name++) return TRUE; } eofFlag = TRUE; return TRUE; } /* * There is another file in the archive to examine. * Extract the encoded information and check it. */ mode = getOctal(hp->mode, sizeof(hp->mode)); uid = getOctal(hp->uid, sizeof(hp->uid)); gid = getOctal(hp->gid, sizeof(hp->gid)); size = getOctal(hp->size, sizeof(hp->size)); mtime = getOctal(hp->mtime, sizeof(hp->mtime)); if ((mode < 0) || (uid < 0) || (gid < 0) || (size < 0)) { if (!badHeader) fprintf(stderr, "Bad tar header, skipping\n"); badHeader = TRUE; return FALSE; } badHeader = FALSE; skipFileFlag = FALSE; /* * Check for the file modes. */ hardLink = ((hp->typeFlag == TAR_TYPE_HARD_LINK) || (hp->typeFlag == TAR_TYPE_HARD_LINK - '0')); softLink = ((hp->typeFlag == TAR_TYPE_SOFT_LINK) || (hp->typeFlag == TAR_TYPE_SOFT_LINK - '0')); /* * Check for a directory or a regular file. */ if (name[strlen(name) - 1] == '/') mode |= S_IFDIR; else if ((mode & S_IFMT) == 0) mode |= S_IFREG; /* * Check for absolute paths in the file. * If we find any, then warn the user and make them relative. */ if (*name == '/') { while (*name == '/') name++; if (!warnedRoot) { fprintf(stderr, "Absolute path detected, removing leading slashes\n"); } warnedRoot = TRUE; } /* * See if we want this file to be restored. * If not, then set up to skip it. */ if (!wantFileName(name, fileCount, fileTable)) { if (!hardLink && !softLink && S_ISREG(mode)) { inHeader = (size == 0); dataCc = size; } skipFileFlag = TRUE; return TRUE; } /* * This file is to be handled. * If we aren't extracting then just list information about the file. */ if (!extractFlag) { if (verboseFlag) { printf("%s %3d/%-d %9ld %s %s", modeString(mode), uid, gid, size, timeString(mtime), name); } else printf("%s", name); if (hardLink) printf(" (link to \"%s\")", hp->linkName); else if (softLink) printf(" (symlink to \"%s\")", hp->linkName); else if (S_ISREG(mode)) { inHeader = (size == 0); dataCc = size; } printf("\n"); return TRUE; } /* * We really want to extract the file. */ if (verboseFlag) printf("x %s\n", name); if (hardLink) { if (link(hp->linkName, name) < 0) { perror(name); return FALSE; } return TRUE; } if (softLink) { #ifdef S_ISLNK if (symlink(hp->linkName, name) < 0) { perror(name); return FALSE; } return TRUE; #else fprintf(stderr, "Cannot create symbolic links\n"); #endif return FALSE; } /* * If the file is a directory, then just create the path. */ if (S_ISDIR(mode)) return createPath(name, mode); /* * There is a file to write. * First create the path to it if necessary with a default permission. */ if (!createPath(name, 0777)) return FALSE; inHeader = (size == 0); dataCc = size; /* * Start the output file. */ outFd = open(name, O_WRONLY | O_CREAT | O_TRUNC, mode); if (outFd < 0) { perror(name); skipFileFlag = TRUE; return FALSE; } /* * If the file is empty, then that's all we need to do. */ if (size == 0) { (void) close(outFd); outFd = -1; } return TRUE; } /* * Handle a data block of some specified size that was read. * Returns TRUE on success. */ static BOOL readData(const char * cp, int count) { /* * Reduce the amount of data left in this file. * If there is no more data left, then we need to read * the header again. */ dataCc -= count; if (dataCc <= 0) inHeader = TRUE; /* * If we aren't extracting files or this file is being * skipped then do nothing more. */ if (!extractFlag || skipFileFlag) return TRUE; /* * Write the data to the output file. */ if (fullWrite(outFd, cp, count) < 0) { perror(outName); (void) close(outFd); outFd = -1; skipFileFlag = TRUE; return FALSE; } /* * If the write failed, close the file and disable further * writes to this file. */ if (dataCc <= 0) { if (close(outFd)) perror(outName); outFd = -1; return FALSE; } return TRUE; } /* * Write a tar file containing the specified files. * Returns TRUE on success. */ static BOOL writeTarFile(int fileCount, const char ** fileTable) { struct stat statbuf; BOOL successFlag; successFlag = TRUE; errorFlag = FALSE; /* * Make sure there is at least one file specified. */ if (fileCount <= 0) { fprintf(stderr, "No files specified to be saved\n"); return FALSE; } /* * Create the tar file for writing. */ tarFd = open(tarName, O_WRONLY | O_CREAT | O_TRUNC, 0666); if (tarFd < 0) { perror(tarName); return FALSE; } /* * Get the device and inode of the tar file for checking later. */ if (fstat(tarFd, &statbuf) < 0) { perror(tarName); successFlag = FALSE; goto done; } tarDev = statbuf.st_dev; tarInode = statbuf.st_ino; /* * Append each file name into the archive file. * Follow symbolic links for these top level file names. */ while (!intFlag && !errorFlag && (fileCount-- > 0)) { saveFile(*fileTable++, FALSE); } if (intFlag) { fprintf(stderr, "Interrupted - aborting archiving\n"); successFlag = FALSE; } /* * Now write an empty block of zeroes to end the archive. */ writeTarBlock("", 1); done: /* * Close the tar file and check for errors if it was opened. */ if ((tarFd >= 0) && (close(tarFd) < 0)) { perror(tarName); successFlag = FALSE; } return successFlag; } /* * Save one file into the tar file. * If the file is a directory, then this will recursively save all of * the files and directories within the directory. The seeLinks * flag indicates whether or not we want to see symbolic links as * they really are, instead of blindly following them. */ static void saveFile(const char * fileName, BOOL seeLinks) { int status; int mode; struct stat statbuf; if (verboseFlag) printf("a %s\n", fileName); /* * Check that the file name will fit in the header. */ if (strlen(fileName) >= TAR_NAME_SIZE) { fprintf(stderr, "%s: File name is too long\n", fileName); return; } /* * Find out about the file. */ #ifdef S_ISLNK if (seeLinks) status = lstat(fileName, &statbuf); else #endif status = stat(fileName, &statbuf); if (status < 0) { perror(fileName); return; } /* * Make sure we aren't trying to save our file into itself. */ if ((statbuf.st_dev == tarDev) && (statbuf.st_ino == tarInode)) { fprintf(stderr, "Skipping saving of archive file itself\n"); return; } /* * Check the type of file. */ mode = statbuf.st_mode; if (S_ISDIR(mode)) { saveDirectory(fileName, &statbuf); return; } if (S_ISREG(mode)) { saveRegularFile(fileName, &statbuf); return; } /* * The file is a strange type of file, ignore it. */ fprintf(stderr, "%s: not a directory or regular file\n", fileName); } /* * Save a regular file to the tar file. */ static void saveRegularFile(const char * fileName, const struct stat * statbuf) { BOOL sawEof; int fileFd; int cc; int dataCount; long fullDataCount; char data[TAR_BLOCK_SIZE * 16]; /* * Open the file for reading. */ fileFd = open(fileName, O_RDONLY); if (fileFd < 0) { perror(fileName); return; } /* * Write out the header for the file. */ writeHeader(fileName, statbuf); /* * Write the data blocks of the file. * We must be careful to write the amount of data that the stat * buffer indicated, even if the file has changed size. Otherwise * the tar file will be incorrect. */ fullDataCount = statbuf->st_size; sawEof = FALSE; while (!intFlag && (fullDataCount > 0)) { /* * Get the amount to write this iteration which is * the minumum of the amount left to write and the * buffer size. */ dataCount = sizeof(data); if (dataCount > fullDataCount) dataCount = (int) fullDataCount; /* * Read the data from the file if we haven't seen the * end of file yet. */ cc = 0; if (!sawEof) { cc = fullRead(fileFd, data, dataCount); if (cc < 0) { perror(fileName); (void) close(fileFd); errorFlag = TRUE; return; } /* * If the file ended too soon, complain and set * a flag so we will zero fill the rest of it. */ if (cc < dataCount) { fprintf(stderr, "%s: Short read - zero filling", fileName); sawEof = TRUE; } } /* * Zero fill the rest of the data if necessary. */ if (cc < dataCount) memset(data + cc, 0, dataCount - cc); /* * Write the buffer to the TAR file. */ writeTarBlock(data, dataCount); fullDataCount -= dataCount; } /* * Close the file. */ if (close(fileFd) < 0) fprintf(stderr, "%s: close: %s\n", fileName, strerror(errno)); } /* * Save a directory and all of its files to the tar file. */ static void saveDirectory(const char * dirName, const struct stat * statbuf) { DIR * dir; struct dirent * entry; BOOL needSlash; char fullName[PATH_LEN]; /* * Construct the directory name as used in the tar file by appending * a slash character to it. */ strcpy(fullName, dirName); strcat(fullName, "/"); /* * Write out the header for the directory entry. */ writeHeader(fullName, statbuf); /* * Open the directory. */ dir = opendir(dirName); if (dir == NULL) { fprintf(stderr, "Cannot read directory \"%s\": %s\n", dirName, strerror(errno)); return; } /* * See if a slash is needed. */ needSlash = (*dirName && (dirName[strlen(dirName) - 1] != '/')); /* * Read all of the directory entries and check them, * except for the current and parent directory entries. */ while (!intFlag && !errorFlag && ((entry = readdir(dir)) != NULL)) { if ((strcmp(entry->d_name, ".") == 0) || (strcmp(entry->d_name, "..") == 0)) { continue; } /* * Build the full path name to the file. */ strcpy(fullName, dirName); if (needSlash) strcat(fullName, "/"); strcat(fullName, entry->d_name); /* * Write this file to the tar file, noticing whether or not * the file is a symbolic link. */ saveFile(fullName, TRUE); } /* * All done, close the directory. */ closedir(dir); } /* * Write a tar header for the specified file name and status. * It is assumed that the file name fits. */ static void writeHeader(const char * fileName, const struct stat * statbuf) { long checkSum; const unsigned char * cp; int len; TarHeader header; /* * Zero the header block in preparation for filling it in. */ memset((char *) &header, 0, sizeof(header)); /* * Fill in the header. */ strcpy(header.name, fileName); strncpy(header.magic, TAR_MAGIC, sizeof(header.magic)); strncpy(header.version, TAR_VERSION, sizeof(header.version)); putOctal(header.mode, sizeof(header.mode), statbuf->st_mode & 0777); putOctal(header.uid, sizeof(header.uid), statbuf->st_uid); putOctal(header.gid, sizeof(header.gid), statbuf->st_gid); putOctal(header.size, sizeof(header.size), statbuf->st_size); putOctal(header.mtime, sizeof(header.mtime), statbuf->st_mtime); header.typeFlag = TAR_TYPE_REGULAR; /* * Calculate and store the checksum. * This is the sum of all of the bytes of the header, * with the checksum field itself treated as blanks. */ memset(header.checkSum, ' ', sizeof(header.checkSum)); cp = (const unsigned char *) &header; len = sizeof(header); checkSum = 0; while (len-- > 0) checkSum += *cp++; putOctal(header.checkSum, sizeof(header.checkSum), checkSum); /* * Write the tar header. */ writeTarBlock((const char *) &header, sizeof(header)); } /* * Write data to one or more blocks of the tar file. * The data is always padded out to a multiple of TAR_BLOCK_SIZE. * The errorFlag static variable is set on an error. */ static void writeTarBlock(const char * buf, int len) { int partialLength; int completeLength; char fullBlock[TAR_BLOCK_SIZE]; /* * If we had a write error before, then do nothing more. */ if (errorFlag) return; /* * Get the amount of complete and partial blocks. */ partialLength = len % TAR_BLOCK_SIZE; completeLength = len - partialLength; /* * Write all of the complete blocks. */ if ((completeLength > 0) && !fullWrite(tarFd, buf, completeLength)) { perror(tarName); errorFlag = TRUE; return; } /* * If there are no partial blocks left, we are done. */ if (partialLength == 0) return; /* * Copy the partial data into a complete block, and pad the rest * of it with zeroes. */ memcpy(fullBlock, buf + completeLength, partialLength); memset(fullBlock + partialLength, 0, TAR_BLOCK_SIZE - partialLength); /* * Write the last complete block. */ if (!fullWrite(tarFd, fullBlock, TAR_BLOCK_SIZE)) { perror(tarName); errorFlag = TRUE; } } /* * Attempt to create the directories along the specified path, except for * the final component. The mode is given for the final directory only, * while all previous ones get default protections. Errors are not reported * here, as failures to restore files can be reported later. * Returns TRUE on success. */ static BOOL createPath(const char * name, int mode) { char * cp; char * cpOld; char buf[TAR_NAME_SIZE]; strcpy(buf, name); cp = strchr(buf, '/'); while (cp) { cpOld = cp; cp = strchr(cp + 1, '/'); *cpOld = '\0'; if (mkdir(buf, cp ? 0777 : mode) == 0) printf("Directory \"%s\" created\n", buf); *cpOld = '/'; } return TRUE; } /* * Read an octal value in a field of the specified width, with optional * spaces on both sides of the number and with an optional null character * at the end. Returns -1 on an illegal format. */ static long getOctal(const char * cp, int len) { long val; while ((len > 0) && (*cp == ' ')) { cp++; len--; } if ((len == 0) || !isOctal(*cp)) return -1; val = 0; while ((len > 0) && isOctal(*cp)) { val = val * 8 + *cp++ - '0'; len--; } while ((len > 0) && (*cp == ' ')) { cp++; len--; } if ((len > 0) && *cp) return -1; return val; } /* * Put an octal string into the specified buffer. * The number is zero and space padded and possibly null padded. * Returns TRUE if successful. */ static BOOL putOctal(char * cp, int len, long value) { int tempLength; char * tempString; char tempBuffer[32]; /* * Create a string of the specified length with an initial space, * leading zeroes and the octal number, and a trailing null. */ tempString = tempBuffer; sprintf(tempString, " %0*lo", len - 2, value); tempLength = strlen(tempString) + 1; /* * If the string is too large, suppress the leading space. */ if (tempLength > len) { tempLength--; tempString++; } /* * If the string is still too large, suppress the trailing null. */ if (tempLength > len) tempLength--; /* * If the string is still too large, fail. */ if (tempLength > len) return FALSE; /* * Copy the string to the field. */ memcpy(cp, tempString, len); return TRUE; } /* * See if the specified file name belongs to one of the specified list * of path prefixes. An empty list implies that all files are wanted. * Returns TRUE if the file is selected. */ static BOOL wantFileName(const char * fileName, int fileCount, const char ** fileTable) { const char * pathName; int fileLength; int pathLength; /* * If there are no files in the list, then the file is wanted. */ if (fileCount == 0) return TRUE; fileLength = strlen(fileName); /* * Check each of the test paths. */ while (fileCount-- > 0) { pathName = *fileTable++; pathLength = strlen(pathName); if (fileLength < pathLength) continue; if (memcmp(fileName, pathName, pathLength) != 0) continue; if ((fileLength == pathLength) || (fileName[pathLength] == '/')) { return TRUE; } } return FALSE; } /* END CODE */ <file_sep>/* See LICENSE file for copyright and license details. */ #include <stdio.h> #include "../util.h" void putword(FILE *fp, const char *s) { static int first = 1; if (!first) fputc(' ', fp); fputs(s, fp); first = 0; } <file_sep>#if 0 mini_start mini_vexec_q mini_writes mini_waitpid INCLUDESRC SHRINKELF LDSCRIPT onlytext return #endif void usage(){ writes("Usage: ksudo [-h] [command and options for sh]\n" "Get a kerberos ticket, execute command as root, keep the ticket.\n"); exit(1); } int main(int argc,char**argv,char**envp){ if ( argc<2 || (argv[1][0]=='-' && argv[1][1]=='h') ) usage(); char *arg[6]; arg[0]="klist"; arg[1]=0; int r = vexec_q("/usr/bin/klist",arg,envp); int i = 0; arg[0]="kinit"; while ( r ){ if ( i++ > 2 ) exit(1); r = vexec("/usr/bin/kinit",arg,envp); } arg[0] = "ksu"; arg[1] = "-q"; arg[2] = "-e"; arg[3] = "/bin/sh"; arg[4] = "-c"; arg[5] = argv[1]; for ( *argv++; *argv; *argv++ ) argv[0][-1]=' '; execve("/usr/bin/ksu", arg, envp ); writes("Couldn't execute ksu.\n"); exit(1); } // ksu -q -e /bin/sh -c "$*" <file_sep>/* public domain sha512/256 implementation based on fips180-3 */ #include "sha512.h" #define sha512_256 sha512 /*struct*/ enum { SHA512_256_DIGEST_LENGTH = 32 }; /* reset state */ void sha512_256_init(void *ctx); /* process message */ #define sha512_256_update sha512_update /* get message digest */ /* state is ruined after sum, keep a copy if multiple sum is needed */ /* part of the message might be left in s, zero it if secrecy is needed */ void sha512_256_sum(void *ctx, uint8_t md[SHA512_256_DIGEST_LENGTH]); <file_sep>/* See LICENSE file for copyright and license details. */ #include <libgen.h> #include <string.h> #include <unistd.h> #include "util.h" static void usage(void) { eprintf("usage: %s [-p] dir ...\n", argv0); } int main(int argc, char *argv[]) { int pflag = 0, ret = 0; char *d; ARGBEGIN { case 'p': pflag = 1; break; default: usage(); } ARGEND if (!argc) usage(); for (; *argv; argc--, argv++) { if (rmdir(*argv) < 0) { weprintf("rmdir %s:", *argv); ret = 1; } else if (pflag) { d = dirname(*argv); for (; strcmp(d, "/") && strcmp(d, ".") ;) { if (rmdir(d) < 0) { weprintf("rmdir %s:", d); ret = 1; break; } d = dirname(d); } } } return ret; } <file_sep>#if 0 mini_start mini_vexec mini_writes mini_waitpid INCLUDESRC SHRINKELF LDSCRIPT onlytext return #endif void usage(){ writes("Usage: su [-h] [options for kinit and ksu]\n" "Get root and keep the kerberos ticket.\n"); exit(1); } int main(int argc,char**argv,char**envp){ if ( argc>1 && argv[1][0]=='-' && argv[1][1]=='h' ) usage(); int r = vexec("/usr/bin/klist",argv,envp); int i = 0; while ( r ){ if ( i++ > 2 ) exit(1); r = vexec("/usr/bin/kinit",argv,envp); } execve("/usr/bin/ksu", argv, envp ); writes("Couldn't execute ksu.\n"); exit(1); } <file_sep>/* sedexec.c -- axecute compiled form of stream editor commands Copyright (C) 1995-2003 <NAME> Copyright (C) 2004-2014 <NAME> The single entry point of this module is the function execute(). It may take a string argument (the name of a file to be used as text) or the argument NULL which tells it to filter standard input. It executes the compiled commands in cmds[] on each line in turn. The function command() does most of the work. match() and advance() are used for matching text against precompiled regular expressions and dosub() does right-hand-side substitution. Getline() does text input; readout() and memcmp() are output and string-comparison utilities. */ #include <stdlib.h> /* exit */ #include <stdio.h> /* {f}puts, {f}printf, getc/putc, f{re}open, fclose */ #include <ctype.h> /* for isprint(), isdigit(), toascii() macros */ #include <string.h> /* for memcmp(3) */ #include "sed.h" /* command type structures & miscellaneous constants */ /***** shared variables imported from the main ******/ /* main data areas */ extern char linebuf[]; /* current-line buffer */ extern sedcmd cmds[]; /* hold compiled commands */ extern long linenum[]; /* numeric-addresses table */ /* miscellaneous shared variables */ extern int nflag; /* -n option flag */ extern int eargc; /* scratch copy of argument count */ extern sedcmd *pending; /* ptr to command waiting to be executed */ extern int last_line_used; /* last line address ($) used */ /***** end of imported stuff *****/ #define MAXHOLD MAXBUF /* size of the hold space */ #define GENSIZ MAXBUF /* maximum genbuf size */ static const char LTLMSG[] = "sed: line too long\n"; static char *spend; /* current end-of-line-buffer pointer */ static long lnum = 0L; /* current source line number */ /* append buffer maintenance */ static sedcmd *appends[MAXAPPENDS]; /* array of ptrs to a,i,c commands */ static sedcmd **aptr = appends; /* ptr to current append */ /* genbuf and its pointers */ static char genbuf[GENSIZ]; static char *loc1; static char *loc2; static char *locs; /* command-logic flags */ static int lastline; /* do-line flag */ static int line_with_newline; /* line had newline */ static int jump; /* jump to cmd's link address if set */ static int delete; /* delete command flag */ /* tagged-pattern tracking */ static char *bracend[MAXTAGS]; /* tagged pattern start pointers */ static char *brastart[MAXTAGS]; /* tagged pattern end pointers */ /* prototypes */ static char *sed_getline(char *buf, int max); static char *place(char* asp, char* al1, char* al2); static int advance(char* lp, char* ep, char** eob); static int match(char *expbuf, int gf); static int selected(sedcmd *ipc); static int substitute(sedcmd *ipc); static void command(sedcmd *ipc); static void dosub(char *rhsbuf); static void dumpto(char *p1, FILE *fp); static void listto(char *p1, FILE *fp); static void readout(void); static void truncated(int h); /* execute the compiled commands in cmds[] on a file file: name of text source file to be filtered */ void execute(char* file) { register sedcmd *ipc; /* ptr to current command */ char *execp; /* ptr to source */ if (file != NULL) /* filter text from a named file */ if (freopen(file, "r", stdin) == NULL) fprintf(stderr, "sed: can't open %s\n", file); if (pending) /* there's a command waiting */ { ipc = pending; /* it will be first executed */ pending = FALSE; /* turn off the waiting flag */ goto doit; /* go to execute it immediately */ } /* here's the main command-execution loop */ for(;;) { /* get next line to filter */ if ((execp = sed_getline(linebuf, MAXBUF+1)) == BAD) return; spend = execp; /* loop through compiled commands, executing them */ for(ipc = cmds; ipc->command; ) { /* address command to select? - If not address but allbut then invert, that is skip, the commmand */ if (ipc->addr1 || ipc->flags.allbut) { if (!ipc->addr1 || !selected(ipc)) { ipc++; /* not selected, next cmd */ continue; } } doit: command(ipc); /* execute the command pointed at */ if (delete) /* if delete flag is set */ break; /* don't exec rest of compiled cmds */ if (jump) /* if jump set, follow cmd's link */ { jump = FALSE; if ((ipc = ipc->u.link) == 0) { ipc = cmds; break; } } else /* normal goto next command */ ipc++; } /* we've now done all modification commands on the line */ /* here's where the transformed line is output */ if (!nflag && !delete) { fwrite(linebuf, spend - linebuf, 1, stdout); if (line_with_newline) putc('\n', stdout); } /* if we've been set up for append, emit the text from it */ if (aptr > appends) readout(); delete = FALSE; /* clear delete flag; about to get next cmd */ } } /* is current command selected */ static int selected(sedcmd *ipc) { register char *p1 = ipc->addr1; /* point p1 at first address */ register char *p2 = ipc->addr2; /* and p2 at second */ unsigned char c; int selected = FALSE; if (ipc->flags.inrange) { selected = TRUE; if (*p2 == CEND) ; else if (*p2 == CLNUM) { c = p2[1]; if (lnum >= linenum[c]) ipc->flags.inrange = FALSE; } else if (match(p2, 0)) ipc->flags.inrange = FALSE; } else if (*p1 == CEND) { if (lastline) selected = TRUE; } else if (*p1 == CLNUM) { c = p1[1]; if (lnum == linenum[c]) { selected = TRUE; if (p2) ipc->flags.inrange = TRUE; } } else if (match(p1, 0)) { selected = TRUE; if (p2) ipc->flags.inrange = TRUE; } return ipc->flags.allbut ? !selected : selected; } /* match RE at expbuf against linebuf; if gf set, copy linebuf from genbuf */ static int _match(char *expbuf, int gf) /* uses genbuf */ { char *p1, *p2, c; if (!gf) { p1 = linebuf; locs = NULL; } else { if (*expbuf) return FALSE; /* if the last match was zero length, continue to next */ if (loc2 - loc1 == 0) { loc2++; } locs = p1 = loc2; } p2 = expbuf; if (*p2++) { loc1 = p1; if (*p2 == CCHR && p2[1] != *p1) /* 1st char is wrong */ return FALSE; /* so fail */ return advance(p1, p2, NULL); /* else try to match rest */ } /* quick check for 1st character if it's literal */ if (*p2 == CCHR) { c = p2[1]; /* pull out character to search for */ do { if (*p1 != c) continue; /* scan the source string */ if (advance(p1, p2, NULL)) /* found it, match the rest */ return loc1 = p1, TRUE; } while (*p1++); return FALSE; /* didn't find that first char */ } /* else try for unanchored match of the pattern */ do { if (advance(p1, p2, NULL)) return loc1 = p1, TRUE; } while (*p1++); /* if got here, didn't match either way */ return FALSE; } static int match(char *expbuf, int gf) /* uses genbuf */ { const char *loc2i = loc2; const int ret = _match(expbuf, gf); /* if last match was zero length, do not allow a follpwing zero match */ if (loc2i && loc1 == loc2i && loc2 - loc1 == 0) { loc2++; return _match(expbuf, gf); } return ret; } /* attempt to advance match pointer by one pattern element lp: source (linebuf) ptr ep: regular expression element ptr */ static int advance(char* lp, char* ep, char** eob) { char *curlp; /* save ptr for closures */ char c; /* scratch character holder */ char *bbeg; int ct; signed int bcount = -1; for (;;) switch (*ep++) { case CCHR: /* literal character */ if (*ep++ == *lp++) /* if chars are equal */ continue; /* matched */ return FALSE; /* else return false */ case CDOT: /* anything but newline */ if (*lp++) /* first NUL is at EOL */ continue; /* keep going if didn't find */ return FALSE; /* else return false */ case CNL: /* start-of-line */ case CDOL: /* end-of-line */ if (*lp == 0) /* found that first NUL? */ continue; /* yes, keep going */ return FALSE; /* else return false */ case CEOF: /* end-of-address mark */ loc2 = lp; /* set second loc */ return TRUE; /* return true */ case CCL: /* a closure */ c = *lp++ & 0177; if (ep[c>>3] & bits(c & 07)) /* is char in set? */ { ep += 16; /* then skip rest of bitmask */ continue; /* and keep going */ } return FALSE; /* else return false */ case CBRA: /* start of tagged pattern */ brastart[(unsigned char)*ep++] = lp; /* mark it */ continue; /* and go */ case CKET: /* end of tagged pattern */ bcount = *ep; if (eob) { *eob = lp; return TRUE; } else bracend[(unsigned char)*ep++] = lp; /* mark it */ continue; /* and go */ case CBACK: /* match back reference */ bbeg = brastart[(unsigned char)*ep]; ct = bracend[(unsigned char)*ep++] - bbeg; if (memcmp(bbeg, lp, ct) == 0) { lp += ct; continue; } return FALSE; case CBRA|STAR: /* \(...\)* */ { char *lastlp; curlp = lp; if (*ep > bcount) brastart[(unsigned char)*ep] = bracend[(unsigned char)*ep] = lp; while (advance(lastlp=lp, ep+1, &lp)) { if (*ep > bcount && lp != lastlp) { bracend[(unsigned char)*ep] = lp; /* mark it */ brastart[(unsigned char)*ep] = lastlp; } if (lp == lastlp) break; } ep++; /* FIXME: scan for the brace end */ while (*ep != CKET) ep++; ep+=2; if (lp == curlp) /* 0 matches */ continue; lp++; /* because the star handling decrements it */ goto star; } case CBACK|STAR: /* \n* */ bbeg = brastart[(unsigned char)*ep]; ct = bracend[(unsigned char)*ep++] - bbeg; curlp = lp; while(memcmp(bbeg, lp, ct) == 0) lp += ct; while(lp >= curlp) { if (advance(lp, ep, eob)) return TRUE; lp -= ct; } return FALSE; case CDOT|STAR: /* match .* */ curlp = lp; /* save closure start loc */ while (*lp++); /* match anything */ goto star; /* now look for followers */ case CCHR|STAR: /* match <literal char>* */ curlp = lp; /* save closure start loc */ while (*lp++ == *ep); /* match many of that char */ ep++; /* to start of next element */ goto star; /* match it and followers */ case CCL|STAR: /* match [...]* */ curlp = lp; /* save closure start loc */ do { c = *lp++ & 0x7F; /* match any in set */ } while (ep[c>>3] & bits(c & 07)); ep += 16; /* skip past the set */ goto star; /* match followers */ star: /* the recursion part of a * or + match */ if (--lp == curlp) { /* 0 matches */ continue; } #if 0 if (*ep == CCHR) { c = ep[1]; do { if (*lp != c) continue; if (advance(lp, ep, eob)) return TRUE; } while (lp-- > curlp); return FALSE; } if (*ep == CBACK) { c = *(brastart[ep[1]]); do { if (*lp != c) continue; if (advance(lp, ep, eob)) return TRUE; } while (lp-- > curlp); return FALSE; } #endif /* match followers, try shorter match, if needed */ do { if (lp == locs) break; if (advance(lp, ep, eob)) return TRUE; } while (lp-- > curlp); return FALSE; default: fprintf(stderr, "sed: internal RE error, %o\n", *--ep); exit (2); } } /* perform s command ipc: ptr to s command struct */ static int substitute(sedcmd *ipc) { unsigned int n = 0; /* find a match */ while (match(ipc->u.lhs, n /* use last loc2 for n>0 */)) { /* nth 0 is implied 1 */ n++; if (!ipc->nth || n == ipc->nth) { dosub(ipc->rhs); /* perform it once */ break; } } if (n == 0) return FALSE; /* command fails */ if (ipc->flags.global) /* if global flag enabled */ do { /* cycle through possibles */ if (match(ipc->u.lhs, 1)) { /* found another */ dosub(ipc->rhs); /* so substitute */ } else /* otherwise, */ break; /* we're done */ } while (*loc2); return TRUE; /* we succeeded */ } /* generate substituted right-hand side (of s command) rhsbuf: where to put the result */ static void dosub(char *rhsbuf) /* uses linebuf, genbuf, spend */ { char *lp, *sp, *rp; int c; /* copy linebuf to genbuf up to location 1 */ lp = linebuf; sp = genbuf; while (lp < loc1) *sp++ = *lp++; /* substitute */ for (rp = rhsbuf; (c = *rp++); ) { if (c & 0200 && (c & 0177) == '0') { sp = place(sp, loc1, loc2); continue; } else if (c & 0200 && (c &= 0177) >= '1' && c < MAXTAGS+'1') { sp = place(sp, brastart[c-'1'], bracend[c-'1']); continue; } *sp++ = c & 0177; if (sp >= genbuf + MAXBUF) fprintf(stderr, LTLMSG); } /* adjust location pointers and copy reminder */ lp = loc2; { long len = loc2 - loc1; loc2 = sp - genbuf + linebuf; loc1 = loc2 - len; } while ((*sp++ = *lp++)) if (sp >= genbuf + MAXBUF) fprintf(stderr, LTLMSG); lp = linebuf; sp = genbuf; while ((*lp++ = *sp++)); spend = lp-1; } /* place chars at *al1...*(al1 - 1) at asp... in genbuf[] */ static char *place(char* asp, char* al1, char* al2) /* uses genbuf */ { while (al1 < al2) { *asp++ = *al1++; if (asp >= genbuf + MAXBUF) fprintf(stderr, LTLMSG); } return asp; } /* list the pattern space in visually unambiguous form *p1... to fp p1: the source fp: output stream to write to */ static void listto(char *p1, FILE *fp) { for (; p1<spend; p1++) if (isprint(*p1)) putc(*p1, fp); /* pass it through */ else { putc('\\', fp); /* emit a backslash */ switch(*p1) { case '\b': putc('b', fp); break; /* BS */ case '\t': putc('t', fp); break; /* TAB */ case '\n': putc('n', fp); break; /* NL */ case '\r': putc('r', fp); break; /* CR */ case '\033': putc('e', fp); break; /* ESC */ default: fprintf(fp, "%02x", *p1); } } putc('\n', fp); } /* write a hex dump expansion of *p1... to fp p1: source fp: output */ static void dumpto(char *p1, FILE *fp) { for (; p1<spend; p1++) fprintf(fp, "%02x", *p1); fprintf(fp, "%02x", '\n'); putc('\n', fp); } static void truncated(int h) { static long last = 0L; if (lnum == last) return; last = lnum; fprintf(stderr, "sed: "); fprintf(stderr, h ? "hold space" : "line %ld", lnum); fprintf(stderr, " truncated to %d characters\n", MAXBUF); } /* execute compiled command pointed at by ipc */ static void command(sedcmd *ipc) { static int didsub; /* true if last s succeeded */ static char holdsp[MAXHOLD]; /* the hold space */ static char *hspend = holdsp; /* hold space end pointer */ register char *p1, *p2; char *execp; switch(ipc->command) { case ACMD: /* append */ *aptr++ = ipc; if (aptr >= appends + MAXAPPENDS) fprintf(stderr, "sed: too many appends after line %ld\n", lnum); *aptr = 0; break; case CCMD: /* change pattern space */ delete = TRUE; if (!ipc->flags.inrange || lastline) printf("%s\n", ipc->u.lhs); break; case DCMD: /* delete pattern space */ delete = TRUE; break; case CDCMD: /* delete a line in hold space */ p1 = p2 = linebuf; while(*p1 != '\n') if ((delete = (*p1++ == 0))) return; p1++; while((*p2++ = *p1++)) continue; spend = p2-1; jump++; break; case EQCMD: /* show current line number */ fprintf(stdout, "%ld\n", lnum); break; case GCMD: /* copy hold space to pattern space */ p1 = linebuf; p2 = holdsp; while((*p1++ = *p2++)); spend = p1-1; break; case CGCMD: /* append hold space to pattern space */ *spend++ = '\n'; p1 = spend; p2 = holdsp; do { if (p1 > linebuf + MAXBUF) { truncated(FALSE); p1[-1] = 0; break; } } while((*p1++ = *p2++)); spend = p1-1; break; case HCMD: /* copy pattern space to hold space */ p1 = holdsp; p2 = linebuf; while((*p1++ = *p2++)); hspend = p1-1; break; case CHCMD: /* append pattern space to hold space */ *hspend++ = '\n'; p1 = hspend; p2 = linebuf; do { if (p1 > holdsp + MAXBUF) { truncated(TRUE); p1[-1] = 0; break; } } while((*p1++ = *p2++)); hspend = p1-1; break; case ICMD: /* insert text */ printf("%s\n", ipc->u.lhs); break; case BCMD: /* branch to label */ jump = TRUE; break; case LCMD: /* list text */ listto(linebuf, (ipc->fout != NULL)?ipc->fout:stdout); break; case CLCMD: /* dump text */ dumpto(linebuf, (ipc->fout != NULL)?ipc->fout:stdout); break; case NCMD: /* read next line into pattern space */ if (!nflag) puts(linebuf); /* flush out the current line */ if (aptr > appends) readout(); /* do pending a, r commands */ if ((execp = sed_getline(linebuf, MAXBUF+1)) == BAD) { pending = ipc; delete = TRUE; break; } spend = execp; break; case CNCMD: /* append next line to pattern space */ if (aptr > appends) readout(); *spend++ = '\n'; if ((execp = sed_getline(spend, linebuf + MAXBUF+1 - spend)) == BAD) { pending = ipc; delete = TRUE; break; } spend = execp; break; case PCMD: /* print pattern space */ puts(linebuf); break; case CPCMD: /* print one line from pattern space */ cpcom: /* so s command can jump here */ for(p1 = linebuf; *p1 != '\n' && *p1 != '\0'; ) putc(*p1++, stdout); putc('\n', stdout); break; case QCMD: /* quit the stream editor */ if (!nflag) puts(linebuf); /* flush out the current line */ if (aptr > appends) readout(); /* do any pending a and r commands */ exit(0); case RCMD: /* read a file into the stream */ *aptr++ = ipc; if (aptr >= appends + MAXAPPENDS) fprintf(stderr, "sed: too many reads after line %ld\n", lnum); *aptr = 0; break; case SCMD: /* substitute RE */ didsub = substitute(ipc); if (ipc->flags.print && didsub) { if (ipc->flags.print == TRUE) puts(linebuf); else goto cpcom; } if (didsub && ipc->fout) fprintf(ipc->fout, "%s\n", linebuf); break; case TCMD: /* branch on last s successful */ case CTCMD: /* branch on last s failed */ if (didsub == (ipc->command == CTCMD)) break; /* no branch if last s failed, else */ didsub = FALSE; jump = TRUE; /* set up to jump to assoc'd label */ break; case CWCMD: /* write one line from pattern space */ for(p1 = linebuf; *p1 != '\n' && *p1 != '\0'; ) putc(*p1++, ipc->fout); putc('\n', ipc->fout); break; case WCMD: /* write pattern space to file */ fprintf(ipc->fout, "%s\n", linebuf); break; case XCMD: /* exchange pattern and hold spaces */ p1 = linebuf; p2 = genbuf; while((*p2++ = *p1++)) continue; p1 = holdsp; p2 = linebuf; while((*p2++ = *p1++)) continue; spend = p2 - 1; p1 = genbuf; p2 = holdsp; while((*p2++ = *p1++)) continue; hspend = p2 - 1; break; case YCMD: p1 = linebuf; p2 = ipc->u.lhs; while((*p1 = p2[(unsigned char)*p1])) p1++; break; } } /* get next line of text to be filtered buf: where to send the input max: max chars to read */ static char *sed_getline(char *buf, int max) { if (fgets(buf, max, stdin) != NULL) { int c; lnum++; /* note that we got another line */ /* find the end of the input and overwrite a possible '\n' */ while (*buf != '\n' && *buf != 0) buf++; line_with_newline = *buf == '\n'; *buf=0; /* detect last line - but only if the address was used in a command */ if (last_line_used) { if ((c = fgetc(stdin)) != EOF) ungetc (c, stdin); else { if (eargc == 0) /* if no more args */ lastline = TRUE; /* set a flag */ } } return buf; /* return ptr to terminating null */ } else { return BAD; } } /* write file indicated by r command to output */ static void readout(void) { register int t; /* hold input char or EOF */ FILE *fi; /* ptr to file to be read */ aptr = appends - 1; /* arrange for pre-increment to work right */ while(*++aptr) if ((*aptr)->command == ACMD) /* process "a" cmd */ printf("%s\n", (*aptr)->u.lhs); else /* process "r" cmd */ { if ((fi = fopen((*aptr)->u.lhs, "r")) == NULL) continue; while((t = getc(fi)) != EOF) putc((char) t, stdout); fclose(fi); } aptr = appends; /* reset the append ptr */ *aptr = 0; } /* sedexec.c ends here */ <file_sep>/* See LICENSE file for copyright and license details. */ #include "../utf.h" int utftorunestr(const char *str, Rune *r) { int i, n; for(i = 0; (n = chartorune(&r[i], str)) && r[i]; i++) str += n; return i; } <file_sep>/* public domain sha256 implementation based on fips180-3 */ #include <ctype.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "../sha512.h" static uint64_t ror(uint64_t n, int k) { return (n >> k) | (n << (64-k)); } #define Ch(x,y,z) (z ^ (x & (y ^ z))) #define Maj(x,y,z) ((x & y) | (z & (x | y))) #define S0(x) (ror(x,28) ^ ror(x,34) ^ ror(x,39)) #define S1(x) (ror(x,14) ^ ror(x,18) ^ ror(x,41)) #define R0(x) (ror(x,1) ^ ror(x,8) ^ (x>>7)) #define R1(x) (ror(x,19) ^ ror(x,61) ^ (x>>6)) static const uint64_t K[80] = { 0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL, 0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL, 0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL, 0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL, 0xd807aa98a3030242ULL, 0x12835b0145706fbeULL, 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL, 0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL, 0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL, 0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL, 0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL, 0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL, 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL, 0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL, 0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL, 0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL, 0x06ca6351e003826fULL, 0x142929670a0e6e70ULL, 0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL, 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL, 0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL, 0x81c2c92e47edaee6ULL, 0x92722c851482353bULL, 0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL, 0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL, 0xd192e819d6ef5218ULL, 0xd69906245565a910ULL, 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL, 0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL, 0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL, 0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL, 0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL, 0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL, 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL, 0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL, 0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL, 0xca273eceea26619cULL, 0xd186b8c721c0c207ULL, 0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL, 0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL, 0x113f9804bef90daeULL, 0x1b710b35131c471bULL, 0x28db77f523047d84ULL, 0x32caab7b40c72493ULL, 0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL, 0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL, 0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL }; static void processblock(struct sha512 *s, const uint8_t *buf) { uint64_t W[80], t1, t2, a, b, c, d, e, f, g, h; int i; for (i = 0; i < 16; i++) { W[i] = (uint64_t)buf[8*i]<<56; W[i] |= (uint64_t)buf[8*i+1]<<48; W[i] |= (uint64_t)buf[8*i+2]<<40; W[i] |= (uint64_t)buf[8*i+3]<<32; W[i] |= (uint64_t)buf[8*i+4]<<24; W[i] |= (uint64_t)buf[8*i+5]<<16; W[i] |= (uint64_t)buf[8*i+6]<<8; W[i] |= buf[8*i+7]; } for (; i < 80; i++) W[i] = R1(W[i-2]) + W[i-7] + R0(W[i-15]) + W[i-16]; a = s->h[0]; b = s->h[1]; c = s->h[2]; d = s->h[3]; e = s->h[4]; f = s->h[5]; g = s->h[6]; h = s->h[7]; for (i = 0; i < 80; i++) { t1 = h + S1(e) + Ch(e,f,g) + K[i] + W[i]; t2 = S0(a) + Maj(a,b,c); h = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2; } s->h[0] += a; s->h[1] += b; s->h[2] += c; s->h[3] += d; s->h[4] += e; s->h[5] += f; s->h[6] += g; s->h[7] += h; } static void pad(struct sha512 *s) { unsigned r = s->len % 128; s->buf[r++] = 0x80; if (r > 112) { memset(s->buf + r, 0, 128 - r); r = 0; processblock(s, s->buf); } memset(s->buf + r, 0, 120 - r); s->len *= 8; s->buf[120] = s->len >> 56; s->buf[121] = s->len >> 48; s->buf[122] = s->len >> 40; s->buf[123] = s->len >> 32; s->buf[124] = s->len >> 24; s->buf[125] = s->len >> 16; s->buf[126] = s->len >> 8; s->buf[127] = s->len; processblock(s, s->buf); } void sha512_init(void *ctx) { struct sha512 *s = ctx; s->len = 0; s->h[0] = 0x6a09e667f3bcc908ULL; s->h[1] = 0xbb67ae8584caa73bULL; s->h[2] = 0x3c6ef372fe94f82bULL; s->h[3] = 0xa54ff53a5f1d36f1ULL; s->h[4] = 0x510e527fade682d1ULL; s->h[5] = 0x9b05688c2b3e6c1fULL; s->h[6] = 0x1f83d9abfb41bd6bULL; s->h[7] = 0x5be0cd19137e2179ULL; } void sha512_sum_n(void *ctx, uint8_t *md, int n) { struct sha512 *s = ctx; int i; pad(s); for (i = 0; i < n; i++) { md[8*i] = s->h[i] >> 56; md[8*i+1] = s->h[i] >> 48; md[8*i+2] = s->h[i] >> 40; md[8*i+3] = s->h[i] >> 32; md[8*i+4] = s->h[i] >> 24; md[8*i+5] = s->h[i] >> 16; md[8*i+6] = s->h[i] >> 8; md[8*i+7] = s->h[i]; } } void sha512_sum(void *ctx, uint8_t md[SHA512_DIGEST_LENGTH]) { sha512_sum_n(ctx, md, 8); } void sha512_update(void *ctx, const void *m, unsigned long len) { struct sha512 *s = ctx; const uint8_t *p = m; unsigned r = s->len % 128; s->len += len; if (r) { if (len < 128 - r) { memcpy(s->buf + r, p, len); return; } memcpy(s->buf + r, p, 128 - r); len -= 128 - r; p += 128 - r; processblock(s, s->buf); } for (; len >= 128; len -= 128, p += 128) processblock(s, p); memcpy(s->buf, p, len); } <file_sep># sbase version VERSION = 0.0 # paths PREFIX = /usr/local MANPREFIX = $(PREFIX)/share/man CC = cc AR = ar RANLIB = ranlib # for NetBSD add -D_NETBSD_SOURCE # -lrt might be needed on some systems CPPFLAGS = -D_DEFAULT_SOURCE -D_BSD_SOURCE -D_XOPEN_SOURCE=700 -D_FILE_OFFSET_BITS=64 CFLAGS = -std=c99 -Wall -pedantic LDFLAGS = -s <file_sep>/* See LICENSE file for copyright and license details. */ #include <sys/stat.h> #include <errno.h> #include <stdlib.h> #include "util.h" static void usage(void) { eprintf("usage: %s [-p] [-m mode] name ...\n", argv0); } int main(int argc, char *argv[]) { mode_t mode, mask; int pflag = 0, ret = 0; mask = umask(0); mode = 0777 & ~mask; ARGBEGIN { case 'p': pflag = 1; break; case 'm': mode = parsemode(EARGF(usage()), 0777, mask); break; default: usage(); } ARGEND if (!argc) usage(); for (; *argv; argc--, argv++) { if (pflag) { if (mkdirp(*argv, mode, 0777 & (~mask | 0300)) < 0) ret = 1; } else if (mkdir(*argv, mode) < 0) { weprintf("mkdir %s:", *argv); ret = 1; } } return ret; } <file_sep>/* See LICENSE file for copyright and license details. */ #include <ctype.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "text.h" #include "utf.h" #include "util.h" enum { INIT = 1, GROW = 2, }; enum { EXPAND = 0, RESET = 1, }; enum { FIELD_ERROR = -2, }; struct field { char *s; size_t len; }; struct jline { struct line text; size_t nf; size_t maxf; struct field *fields; }; struct spec { size_t fileno; size_t fldno; }; struct outlist { size_t ns; size_t maxs; struct spec **specs; }; struct span { size_t nl; size_t maxl; struct jline **lines; }; static char *sep = NULL; static char *replace = NULL; static const char defaultofs = ' '; static const int jfield = 1; /* POSIX default join field */ static int unpairsa = 0, unpairsb = 0; static int oflag = 0; static int pairs = 1; static size_t seplen; static struct outlist output; static void usage(void) { eprintf("usage: %s [-1 field] [-2 field] [-o list] [-e string] " "[-a | -v fileno] [-t delim] file1 file2\n", argv0); } static void prfield(struct field *fp) { if (fwrite(fp->s, 1, fp->len, stdout) != fp->len) eprintf("fwrite:"); } static void prsep(void) { if (sep) fwrite(sep, 1, seplen, stdout); else putchar(defaultofs); } static void swaplines(struct jline *la, struct jline *lb) { struct jline tmp; tmp = *la; *la = *lb; *lb = tmp; } static void prjoin(struct jline *la, struct jline *lb, size_t jfa, size_t jfb) { struct spec *sp; struct field *joinfield; size_t i; if (jfa >= la->nf || jfb >= lb->nf) return; joinfield = &la->fields[jfa]; if (oflag) { for (i = 0; i < output.ns; i++) { sp = output.specs[i]; if (sp->fileno == 1) { if (sp->fldno < la->nf) prfield(&la->fields[sp->fldno]); else if (replace) fputs(replace, stdout); } else if (sp->fileno == 2) { if (sp->fldno < lb->nf) prfield(&lb->fields[sp->fldno]); else if (replace) fputs(replace, stdout); } else if (sp->fileno == 0) { prfield(joinfield); } if (i < output.ns - 1) prsep(); } } else { prfield(joinfield); prsep(); for (i = 0; i < la->nf; i++) { if (i != jfa) { prfield(&la->fields[i]); prsep(); } } for (i = 0; i < lb->nf; i++) { if (i != jfb) { prfield(&lb->fields[i]); if (i < lb->nf - 1) prsep(); } } } putchar('\n'); } static void prline(struct jline *lp) { if (fwrite(lp->text.data, 1, lp->text.len, stdout) != lp->text.len) eprintf("fwrite:"); putchar('\n'); } static int jlinecmp(struct jline *la, struct jline *lb, size_t jfa, size_t jfb) { int status; /* return FIELD_ERROR if both lines are short */ if (jfa >= la->nf) { status = (jfb >= lb->nf) ? FIELD_ERROR : -1; } else if (jfb >= lb->nf) { status = 1; } else { status = memcmp(la->fields[jfa].s, lb->fields[jfb].s, MAX(la->fields[jfa].len, lb->fields[jfb].len)); LIMIT(status, -1, 1); } return status; } static void addfield(struct jline *lp, char *sp, size_t len) { if (lp->nf >= lp->maxf) { lp->fields = ereallocarray(lp->fields, (GROW * lp->maxf), sizeof(struct field)); lp->maxf *= GROW; } lp->fields[lp->nf].s = sp; lp->fields[lp->nf].len = len; lp->nf++; } static void prspanjoin(struct span *spa, struct span *spb, size_t jfa, size_t jfb) { size_t i, j; for (i = 0; i < (spa->nl - 1); i++) for (j = 0; j < (spb->nl - 1); j++) prjoin(spa->lines[i], spb->lines[j], jfa, jfb); } static struct jline * makeline(char *s, size_t len) { struct jline *lp; char *tmp; size_t i, end; if (s[len - 1] == '\n') s[--len] = '\0'; lp = ereallocarray(NULL, INIT, sizeof(struct jline)); lp->text.data = s; lp->text.len = len; lp->fields = ereallocarray(NULL, INIT, sizeof(struct field)); lp->nf = 0; lp->maxf = INIT; for (i = 0; i < lp->text.len && isblank(lp->text.data[i]); i++) ; while (i < lp->text.len) { if (sep) { if ((lp->text.len - i) < seplen || !(tmp = memmem(lp->text.data + i, lp->text.len - i, sep, seplen))) { goto eol; } end = tmp - lp->text.data; addfield(lp, lp->text.data + i, end - i); i = end + seplen; } else { for (end = i; !(isblank(lp->text.data[end])); end++) { if (end + 1 == lp->text.len) goto eol; } addfield(lp, lp->text.data + i, end - i); for (i = end; isblank(lp->text.data[i]); i++) ; } } eol: addfield(lp, lp->text.data + i, lp->text.len - i); return lp; } static int addtospan(struct span *sp, FILE *fp, int reset) { char *newl = NULL; ssize_t len; size_t size = 0; if ((len = getline(&newl, &size, fp)) < 0) { if (ferror(fp)) eprintf("getline:"); else return 0; } if (reset) sp->nl = 0; if (sp->nl >= sp->maxl) { sp->lines = ereallocarray(sp->lines, (GROW * sp->maxl), sizeof(struct jline *)); sp->maxl *= GROW; } sp->lines[sp->nl] = makeline(newl, len); sp->nl++; return 1; } static void initspan(struct span *sp) { sp->nl = 0; sp->maxl = INIT; sp->lines = ereallocarray(NULL, INIT, sizeof(struct jline *)); } static void freespan(struct span *sp) { size_t i; for (i = 0; i < sp->nl; i++) { free(sp->lines[i]->fields); free(sp->lines[i]->text.data); } free(sp->lines); } static void initolist(struct outlist *olp) { olp->ns = 0; olp->maxs = 1; olp->specs = ereallocarray(NULL, INIT, sizeof(struct spec *)); } static void addspec(struct outlist *olp, struct spec *sp) { if (olp->ns >= olp->maxs) { olp->specs = ereallocarray(olp->specs, (GROW * olp->maxs), sizeof(struct spec *)); olp->maxs *= GROW; } olp->specs[olp->ns] = sp; olp->ns++; } static struct spec * makespec(char *s) { struct spec *sp; int fileno; size_t fldno; if (!strcmp(s, "0")) { /* join field must be 0 and nothing else */ fileno = 0; fldno = 0; } else if ((s[0] == '1' || s[0] == '2') && s[1] == '.') { fileno = s[0] - '0'; fldno = estrtonum(&s[2], 1, MIN(LLONG_MAX, SIZE_MAX)) - 1; } else { eprintf("%s: invalid format\n", s); } sp = ereallocarray(NULL, INIT, sizeof(struct spec)); sp->fileno = fileno; sp->fldno = fldno; return sp; } static void makeolist(struct outlist *olp, char *s) { char *item, *sp; sp = s; while (sp) { item = sp; sp = strpbrk(sp, ", \t"); if (sp) *sp++ = '\0'; addspec(olp, makespec(item)); } } static void freespecs(struct outlist *olp) { size_t i; for (i = 0; i < olp->ns; i++) free(olp->specs[i]); } static void join(FILE *fa, FILE *fb, size_t jfa, size_t jfb) { struct span spa, spb; int cmp, eofa, eofb; initspan(&spa); initspan(&spb); cmp = eofa = eofb = 0; addtospan(&spa, fa, RESET); addtospan(&spb, fb, RESET); while (spa.nl && spb.nl) { if ((cmp = jlinecmp(spa.lines[0], spb.lines[0], jfa, jfb)) < 0) { if (unpairsa) prline(spa.lines[0]); if (!addtospan(&spa, fa, RESET)) { if (unpairsb) { /* a is EOF'd; print the rest of b */ do prline(spb.lines[0]); while (addtospan(&spb, fb, RESET)); } eofa = eofb = 1; } else { continue; } } else if (cmp > 0) { if (unpairsb) prline(spb.lines[0]); if (!addtospan(&spb, fb, RESET)) { if (unpairsa) { /* b is EOF'd; print the rest of a */ do prline(spa.lines[0]); while (addtospan(&spa, fa, RESET)); } eofa = eofb = 1; } else { continue; } } else if (cmp == 0) { /* read all consecutive matching lines from a */ do { if (!addtospan(&spa, fa, EXPAND)) { eofa = 1; spa.nl++; break; } } while (jlinecmp(spa.lines[spa.nl-1], spb.lines[0], jfa, jfb) == 0); /* read all consecutive matching lines from b */ do { if (!addtospan(&spb, fb, EXPAND)) { eofb = 1; spb.nl++; break; } } while (jlinecmp(spa.lines[0], spb.lines[spb.nl-1], jfa, jfb) == 0); if (pairs) prspanjoin(&spa, &spb, jfa, jfb); } else { /* FIELD_ERROR: both lines lacked join fields */ if (unpairsa) prline(spa.lines[0]); if (unpairsb) prline(spb.lines[0]); eofa = addtospan(&spa, fa, RESET) ? 0 : 1; eofb = addtospan(&spb, fb, RESET) ? 0 : 1; if (!eofa && !eofb) continue; } if (eofa) { spa.nl = 0; } else { swaplines(spa.lines[0], spa.lines[spa.nl - 1]); /* ugly */ spa.nl = 1; } if (eofb) { spb.nl = 0; } else { swaplines(spb.lines[0], spb.lines[spb.nl - 1]); /* ugly */ spb.nl = 1; } } freespan(&spa); freespan(&spb); } int main(int argc, char *argv[]) { size_t jf[2] = { jfield, jfield, }; FILE *fp[2]; int ret = 0, n; char *fno; ARGBEGIN { case '1': jf[0] = estrtonum(EARGF(usage()), 1, MIN(LLONG_MAX, SIZE_MAX)); break; case '2': jf[1] = estrtonum(EARGF(usage()), 1, MIN(LLONG_MAX, SIZE_MAX)); break; case 'a': fno = EARGF(usage()); if (strcmp(fno, "1") == 0) unpairsa = 1; else if (strcmp(fno, "2") == 0) unpairsb = 1; else usage(); break; case 'e': replace = EARGF(usage()); break; case 'o': oflag = 1; initolist(&output); makeolist(&output, EARGF(usage())); break; case 't': sep = EARGF(usage()); break; case 'v': pairs = 0; fno = EARGF(usage()); if (strcmp(fno, "1") == 0) unpairsa = 1; else if (strcmp(fno, "2") == 0) unpairsb = 1; else usage(); break; default: usage(); } ARGEND if (sep) seplen = unescape(sep); if (argc != 2) usage(); for (n = 0; n < 2; n++) { if (!strcmp(argv[n], "-")) { argv[n] = "<stdin>"; fp[n] = stdin; } else if (!(fp[n] = fopen(argv[n], "r"))) { eprintf("fopen %s:", argv[n]); } } jf[0]--; jf[1]--; join(fp[0], fp[1], jf[0], jf[1]); if (oflag) freespecs(&output); if (fshut(fp[0], argv[0]) | (fp[0] != fp[1] && fshut(fp[1], argv[1])) | fshut(stdout, "<stdout>")) ret = 2; return ret; } <file_sep>### Static builds for Linux x86_64 Compiled with -O1; minilib v0.0 ``` total 32K micha 155 2019-03-21 10:46 Makefile micha 73 2019-03-21 10:46 README.in micha 73 2019-08-02 06:55 README.md micha 3.3K 2019-03-21 10:46 cat micha 227 2019-03-31 15:10 false micha 1.8K 2019-03-31 15:10 pwd micha 224 2019-03-31 15:10 true micha 374 2019-03-31 15:10 yes ``` <file_sep>/* public domain sha512/224 implementation based on fips180-3 */ #include <stdint.h> #include "../sha512-224.h" extern void sha512_sum_n(void *, uint8_t *, int n); void sha512_224_init(void *ctx) { struct sha512_224 *s = ctx; s->len = 0; s->h[0] = 0x8c3d37c819544da2ULL; s->h[1] = 0x73e1996689dcd4d6ULL; s->h[2] = 0x1dfab7ae32ff9c82ULL; s->h[3] = 0x679dd514582f9fcfULL; s->h[4] = 0x0f6d2b697bd44da8ULL; s->h[5] = 0x77e36f7304c48942ULL; s->h[6] = 0x3f9d85a86a1d36c8ULL; s->h[7] = 0x1112e6ad91d692a1ULL; } void sha512_224_sum(void *ctx, uint8_t md[SHA512_224_DIGEST_LENGTH]) { sha512_sum_n(ctx, md, 4); } <file_sep>#if 0 mini_start mini_inotify_add_watch mini_inotify_init mini_writes mini_open mini_read mini_exit_errno mini_atoi mini_usleep mini_strtol mini_syscalls mini_buf 256 mini_printf mini_itodec #globals_on_stack HEADERGUARDS OPTFLAG -O0 #LDSCRIPT text_and_bss shrinkelf INCLUDESRC return #endif // misc 2020/06 // public domain / BSD 3clause void usage(){ writes("Usage: waitfor [-r] [-t timeout] file\n"); writes("Read a char from 'file',\n" "create 'file' if it doesn't exit,\n" "block until another process has written the char\n"); exit(1); } int main(int argc, char *argv[]){ if (argc < 2) { usage(); } char *fn = argv[1]; int flags = 0; int t=-1; int mode = 0664; // rw rw r // define to something other for parsing the docu #ifndef OPT #define OPT(flag,desc) case flag: #endif for ( *argv++; *argv && argv[0][0]=='-'; *argv++ ){ for ( char *c = argv[0]+1; *c != 0; c++ ){ switch ( *c ){ OPT('h',show usage) usage(); OPT('r',clear old file (truncate it)) flags = O_TRUNC; break; OPT('t',set timeout in seconds) *argv++; if ( !*argv ) usage(); t = strtol(*argv,0,0); t*=10; break; OPT('a',file attribute mask for creation as number. (default: 0664,rw rw r)) *argv++; if ( !*argv ) usage(); mode = strtol(*argv,0,0); break; } } } if ( !*argv ) usage(); int fd = open( argv[0], O_RDWR|O_CREAT|flags, mode ); if ( fd<0 ){ exit_errno(fd); } char b[1]; char buf[64]; int r = 0; r = read(fd,b,1); int nfd; // inotifyfd nfd = inotify_init(); if ( nfd<0 ){ exit_errno(nfd); } int ir = inotify_add_watch(nfd, argv[0], IN_MODIFY ); if ( ir<0 ){ exit_errno(ir); } while ( r == 0 && ( t!=0 ) ){ read(nfd,buf,64); r = read(fd,b,1); if ( t>0 ) t--; //usleep(100000); // 1/10 second } write(STDOUT_FILENO,b,1); write(STDOUT_FILENO,"\n",1); return(nfd); return(r?0:11); // 0 on success, 11 on timeout (errno 'try again') } // leaving this below. works. but using read onto the inotify fd // might be leaner. //fd_set rs; //FD_ZERO (&rs); //FD_SET(nfd,&rs); // //int l = select(nfd+1, &rs,0,0,0); <file_sep>/* public domain sha384 implementation based on fips180-3 */ #include <stdint.h> #include "../sha384.h" extern void sha512_sum_n(void *, uint8_t *, int n); void sha384_init(void *ctx) { struct sha384 *s = ctx; s->len = 0; s->h[0] = 0xcbbb9d5dc1059ed8ULL; s->h[1] = 0x629a292a367cd507ULL; s->h[2] = 0x9159015a3070dd17ULL; s->h[3] = 0x152fecd8f70e5939ULL; s->h[4] = 0x67332667ffc00b31ULL; s->h[5] = 0x8eb44a8768581511ULL; s->h[6] = 0xdb0c2e0d64f98fa7ULL; s->h[7] = 0x47b5481dbefa4fa4ULL; } void sha384_sum(void *ctx, uint8_t md[SHA384_DIGEST_LENGTH]) { sha512_sum_n(ctx, md, 6); } <file_sep>#if 0 mini_start mini_eprintsl mini_writes mini_fwrites mini_prints mini_strerror mini_read mini_write mini_printf mini_itodec mini_open mini_bsd_cksumblock mini_buf 1024 LDSCRIPT text_and_bss shrinkelf INCLUDESRC return #endif #include "shortopts.h" void usage(){ writes("sum [-h]\n"); exit(0); } #define BUFSIZE 1024 void sum(const char* file,long opts){ int fd = 0; if ( file[0] != '-' ) fd = open(file,O_RDONLY); if (fd<0){ eprintsl("Couldn't open ",file); exit(1); } char buf[BUFSIZE]; int ret; int blocks = 0; unsigned int hash = 0; while ( ret=read(fd,buf,BUFSIZE) ){ blocks++; hash=bsd_cksumblock(hash,buf,ret); printf("blocks: %d hash: %d ret: %d\n",blocks,hash,ret); } printf("%u\t%d",hash,blocks); } int main(int argc, const char *argv[]){ long opts = 0; // define to something other for parsing docu #ifndef OPT #define OPT(flag,desc,code) case QUOTE(flag): opts |= OPT_##flag; code; break; //#define OPT(flag,desc,code) case flag: setopt(flag,&opts); code; break; #endif for ( *argv++; *argv && argv[0][0]=='-'; *argv++ ){ for ( const char *c = argv[0]+1; *c != 0; c++ ){ switch ( *c ){ OPT(h,"Show usage",usage()); OPT(r,"reverse order",); default: usage(); } } } if ( *argv == 0 ){ //usage(); sum("-",opts); writes("\n"); return(0); } for (;*argv; *argv++){ sum(*argv,opts); prints("\t",*argv,"\n"); } return 0; } <file_sep>/* See LICENSE file for copyright and license details. */ #include <sys/stat.h> #include <errno.h> #include <fcntl.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include "util.h" static int aflag; static int cflag; static int mflag; static struct timespec times[2] = {{.tv_nsec = UTIME_NOW}}; static void touch(const char *file) { int fd, ret; if (utimensat(AT_FDCWD, file, times, 0) == 0) return; if (errno != ENOENT) eprintf("utimensat %s:", file); if (cflag) return; if ((fd = open(file, O_WRONLY | O_CREAT | O_EXCL, 0666)) < 0) eprintf("open %s:", file); ret = futimens(fd, times); close(fd); if (ret < 0) eprintf("futimens %s:", file); } static time_t parsetime(char *str) { time_t now; struct tm *cur, t = { 0 }; int zulu = 0; char *format; size_t len = strlen(str); if ((now = time(NULL)) == -1) eprintf("time:"); if (!(cur = localtime(&now))) eprintf("localtime:"); t.tm_isdst = -1; switch (len) { /* -t flag argument */ case 8: t.tm_year = cur->tm_year; format = "%m%d%H%M"; break; case 10: format = "%y%m%d%H%M"; break; case 11: t.tm_year = cur->tm_year; format = "%m%d%H%M.%S"; break; case 12: format = "%Y%m%d%H%M"; break; case 13: format = "%y%m%d%H%M.%S"; break; case 15: format = "%Y%m%d%H%M.%S"; break; /* -d flag argument */ case 19: format = "%Y-%m-%dT%H:%M:%S"; break; case 20: /* only Zulu-timezone supported */ if (str[19] != 'Z') eprintf("Invalid time zone\n"); str[19] = 0; zulu = 1; format = "%Y-%m-%dT%H:%M:%S"; break; default: eprintf("Invalid date format length\n", str); } if (!strptime(str, format, &t)) eprintf("strptime %s: Invalid date format\n", str); if (zulu) { t.tm_hour += t.tm_gmtoff / 60; t.tm_gmtoff = 0; t.tm_zone = "Z"; } return mktime(&t); } static void usage(void) { eprintf("usage: %s [-acm] [-d time | -r ref_file | -t time | -T time] " "file ...\n", argv0); } int main(int argc, char *argv[]) { struct stat st; char *ref = NULL; ARGBEGIN { case 'a': aflag = 1; break; case 'c': cflag = 1; break; case 'd': case 't': times[0].tv_sec = parsetime(EARGF(usage())); times[0].tv_nsec = 0; break; case 'm': mflag = 1; break; case 'r': ref = EARGF(usage()); if (stat(ref, &st) < 0) eprintf("stat '%s':", ref); times[0] = st.st_atim; times[1] = st.st_mtim; break; case 'T': times[0].tv_sec = estrtonum(EARGF(usage()), 0, LLONG_MAX); times[0].tv_nsec = 0; break; default: usage(); } ARGEND if (!argc) usage(); if (!aflag && !mflag) aflag = mflag = 1; if (!ref) times[1] = times[0]; if (!aflag) times[0].tv_nsec = UTIME_OMIT; if (!mflag) times[1].tv_nsec = UTIME_OMIT; for (; *argv; argc--, argv++) touch(*argv); return 0; } <file_sep>/* See LICENSE file for copyright and license details. */ #include <libgen.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> #include "../util.h" void enmasse(int argc, char *argv[], int (*fn)(const char *, const char *, int)) { struct stat st; char buf[PATH_MAX], *dir; int i, len; size_t dlen; if (argc == 2 && !(stat(argv[1], &st) == 0 && S_ISDIR(st.st_mode))) { fnck(argv[0], argv[1], fn, 0); return; } else { dir = (argc == 1) ? "." : argv[--argc]; } for (i = 0; i < argc; i++) { dlen = strlen(dir); if (dlen > 0 && dir[dlen - 1] == '/') len = snprintf(buf, sizeof(buf), "%s%s", dir, basename(argv[i])); else len = snprintf(buf, sizeof(buf), "%s/%s", dir, basename(argv[i])); if (len < 0 || len >= sizeof(buf)) { eprintf("%s/%s: filename too long\n", dir, basename(argv[i])); } fnck(argv[i], buf, fn, 0); } } <file_sep>/* See LICENSE file for copyright and license details. */ struct line { char *data; size_t len; }; struct linebuf { struct line *lines; size_t nlines; size_t capacity; }; #define EMPTY_LINEBUF {NULL, 0, 0,} void getlines(FILE *, struct linebuf *); int linecmp(struct line *, struct line *); <file_sep>#if 0 mini_start mini_writes mini_prints mini_fwrites mini_write mini_mount mini_open mini_errno mini_read #mini_printf #mini_printfs #mini_strlen #mini_itodec #mini_buf 256 #mini_atoi LDSCRIPT text_and_bss shrinkelf INCLUDESRC OPTFLAG -Os return #endif //+doc convert errno to str, with 3 chars length // ending the string (located on the stack (!) // with two \0\0, when errno<100 const char *errno_str(int err){ char *e="100\0"; char *p = e; if ( err>99 ){ err-=100; } else { p++; } e[1]+=err/10; e[2]+=err%10; return(p); } void usage(){ writes("mount [-h|r|m|s|e|B|M] [-t type] [-o options] source mountpoint\n"); exit(0); } int main(int argc, char *argv[]){ long flags = 0; char *type = 0; char *options = 0; char *source = 0; char *target = 0; if ( argc == 1 ){ int fd = open( "/proc/mounts", O_RDONLY ); if ( fd<0 ){ int err = errno; fwrites(STDERR_FILENO, "Error reading /proc/mounts, errno: "); write(STDERR_FILENO,errno_str(err),3); return(-1); } char buf[64]; int r = 0; while ( (r = read(fd,&buf,64 )) ){ write(STDOUT_FILENO, buf, r ); } return(0); } for ( *argv++; *argv; *argv++ ){ if ( **argv == '-' ){ for ( char *p = &argv[0][1]; *p!=0; p++ ){ switch (*p){ case 'h': usage(); break; case 'r': flags |= MS_RDONLY; break; case 'm': flags |= MS_REMOUNT; break; case 's': flags |= MS_NOSUID; break; case 'e': flags |= MS_NOEXEC; break; case 'B': flags |= MS_BIND; break; case 'M': flags |= MS_MOVE; break; case 'S': flags |= MS_SYNCHRONOUS; break; case 't': *argv++; type = *argv; break; /* only options, the according filesystem itself recognizes * may be passed. * that's another behaviour than that of gnu mount */ case 'o': *argv++; options = *argv; break; default: fwrites(STDERR_FILENO,"Unknown option: -"); write(STDERR_FILENO,p,1); write(STDERR_FILENO,"\n",1); exit(-1); } } } else { if ( source ) target = *argv; else source = *argv; } } if ( !source || !target ) usage(); //printf("mount -t %s %s %s %d\n", type, source, target,flags); if ( mount( source, target, type, flags, options ) ){ int err = errno; fwrites(STDERR_FILENO, "Error: "); write(STDERR_FILENO,errno_str(err),3); return(-1); } return(0); } <file_sep>/* public domain sha512/256 implementation based on fips180-3 */ #include <stdint.h> #include "../sha512-256.h" extern void sha512_sum_n(void *, uint8_t *, int n); void sha512_256_init(void *ctx) { struct sha512_256 *s = ctx; s->len = 0; s->h[0] = 0x22312194fc2bf72cULL; s->h[1] = 0x9f555fa3c84c64c2ULL; s->h[2] = 0x2393b86b6f53b151ULL; s->h[3] = 0x963877195940eabdULL; s->h[4] = 0x96283ee2a88effe3ULL; s->h[5] = 0xbe5e1e2553863992ULL; s->h[6] = 0x2b0199fc2c85b8aaULL; s->h[7] = 0x0eb72ddc81c52ca2ULL; } void sha512_256_sum(void *ctx, uint8_t md[SHA512_256_DIGEST_LENGTH]) { sha512_sum_n(ctx, md, 4); } <file_sep>Ongoing work. A soothing puzzle. I'm trying to get a usable unix system (without the kernel) within 64kB. All tools statically linked with (minilib)[minilib]. Ok. Possibly it's going to be 128kB. But no more. 128kB ought to be enough for everycore. Eeh. Something like this. We'll see. It's also the question of how many tools should be just "stacked". E.g., instead of `ls -lrt`, essentially just piping the tools together: `ls | stat | sort`. For example. I guess, awk might be the right tool at this place. Thinking about it, sed might already be enough. At least for executing stat foreach ls-listed file. For some of the gnu core tools, this is obviously the best solution. e.g. `dir` should either be an alias to `ls -C -b`, or, to stay with the single executables, there should be a simple sh script calling ls. ;) the script could even consist of only the first line: `#!/bin/ls -C -b` What will invoke ls, with the according parameters. I somehow like the idea of script wrappers more, than having symbolic links to multicall binaries. Amongst other, it's easier to customize them. And they are in a central directory. Aliases always tend to be spread over several config files, at least on my systems. And, to say that clearly and repeatedly, it's a fun project. I just like to have a unix system within 64kB. ;) The intention is not on being posix, systemV or whatever compatible. And for the command line options, I'm also going to implement only those, I'm using mostly, or which don't add to much size. There are other projects out there with a serious (what's the word?) 'approach'. I personally like 'toybox' most. Albite I also still believe, sort of a 'microkernel' is a better approach, and toybox is monlithic. But that's a question, I'm not sure yet. The advantages of an monolithic approach are undeniable there. On the other hand, my experiences with small statically linked tools are very good, as well. When about performance, small statically linked tools surprisingly are more responsive. When thinking about it, it's not that surprising. Only the needed "parts" of the code are loaded, the small tools (mainly less than 1kB fit even into the cpu's cache, they also are buffered in the memory's cache for the hd, and there's no linker needed. Also, dropping unicode, language, and whatever support is no loss, at least not for me. Who in the world would need unicode support for system development/programming/..? ;) I know.. Ok. That's about glibc, and also musl et al. But they also do have other targets. --- When looking for something usable, and you do not need only single tools, you're most possibly better with something more mature and more serious. I personally like the toybox project very much. Its mature, has a quite stringent posix implementation, and is also below 1MB overall. http://github.com/toybox --- For compiling, you'll need the script mini-gcc from minilib. ~What, again, reminds me of my plan to put the whole minilib into this script. No installing anymore, no version problems, just one wrapper script mini-gcc.¨ Done. `curl http://github.com/ ..TODO ` and you're good to go. (Memo to me:) basic unix core tools could be a great testcase for minilib: compile them, and then let them execute a test script. the needed scripts are already implemented in minilib/test/ The sources are partially written completely new, partially scratched together from: suckless base utils, minutils, minix. I keep all copyright notices within the sources. Please, don't get this project too serious. It's more sort of a soothing puzzle to me. --- ### Tools working so far: ``` basename 2021-04-03 569 cat 2021-04-03 1430 cat2 2021-04-03 1304 chroot 2021-04-03 620 dd 2021-04-03 5008 echo 2021-04-03 465 false 2021-04-03 214 getenv 2021-04-03 1142 gid 2021-04-03 2904 grep 2021-04-03 1104 head 2021-04-03 1528 kill 2021-04-03 1946 ln 2021-04-03 838 ls 2021-04-03 5448 ls2 2021-04-03 4752 mkdir 2021-04-03 4096 mkfifo 2021-04-03 888 mount 2021-04-03 1592 pivot_root 2021-04-03 346 printenv 2021-04-03 714 pwd 2021-04-03 338 rgrep 2021-04-03 6568 rm 2021-04-03 884 rmdir 2021-04-03 888 seq 2021-04-03 529 sleep 2021-04-03 520 stat 2021-04-03 2192 sync 2021-04-03 368 tail 2021-04-03 3032 tee 2021-04-03 2951 touch 2021-04-03 537 true 2021-04-03 211 umask 2021-04-03 487 umount 2021-04-03 1184 uname 2021-04-03 1862 usleep 2021-04-03 472 waitfor 2021-04-03 3168 where 2021-04-03 1032 yes 2021-04-03 368 =============================================== size: 64499 Bytes ``` <file_sep>#if 0 #globals_on_stack mini_errno mini_start mini_writes mini_writesl mini_ewrites mini_match_ext2 mini_mmap mini_open mini_die mini_die_if mini_printsl mini_printl mini_group_printf mini_buf 4000 COMPILE fstat munmap close #DEBUG #FULLDEBUG #STRIPFLAG #OPTFLAG -O0 mini_INCLUDESRC LDSCRIPT default #SHRINKELF return #endif int main( int argc, char *argv[], char *envp[] ){ if ( argc < 2 ){ writes("usage: rgrep pattern [file[...]]"); exit(1); } char *pattern = argv[1]; struct stat ststat; printsl(pattern); while ( argc-->2 ){ text_match stm; int fd = open(argv[argc],O_RDONLY); int r = fstat(fd,&ststat); die_if( r, r, "Couldn't stat" ); char *f = mmap(0,ststat.st_size, PROT_READ, MAP_PRIVATE, fd,0); //prints(f); if ( match_ext2( f, pattern, 0,0, &stm ) > 0){ writes("MATCH\n"); write(1,stm.pos,stm.len); write(1,"\n2\n",3); } write(1,stm.pos,stm.len); write(1,"\n1\n",3); munmap(f, ststat.st_size); close(fd); } return(0); } <file_sep>#if 0 mini_start mini_write mini_writes mini_read INCLUDESRC return #endif #define BUF 4096 void usage(){ writes("tohex. convert stdin to hexadecimal output.\n"); exit(0); } char *table = "0123456789abcdef"; int main(int argc, char **argv){ if ( argc>1 ) usage(); char c[BUF/2]; char o[BUF]; int r = 0; while ( (r=read(0,&c,BUF/2) ) > 0 ){ for (int a=0; a<r; a++ ){ o[a<<1]= table[ c[a]>>4 ]; o[(a<<1)+1]= table[ c[a] & 0xf ]; } write(1, o, r<<1 ); } return(0); } <file_sep>#if 0 mini_start mini_group_write mini_group_print mini_sendfile mini_mmap mini_exit_errno mini_errno mini_open mini_sleep mini_group_printf mini_buf 256 INCLUDESRC SHRINKELF return #endif void usage(){ writes("usage: lockfile file\n" "Load and lock a file in memory. (mmap)\n"); exit(1); } int main(int argc, char **argv){ if ( argc<2 ) usage(); int fd = open( argv[1], O_RDONLY ); if ( fd<0 ){ printsl("Couldn't open ",argv[1]); exit_errno(fd); } errno=0; struct stat ststat; fstat(fd, &ststat ); printf("Size: %d\n", ststat.st_size); void* p = mmap( 0, ststat.st_size, PROT_READ, MAP_PRIVATE| MAP_LOCKED | MAP_POPULATE , fd, 0 ); if ( errno ) exit_errno(errno); while(1){ writes("Sleeping\n"); sleep(-1); } return(0); } <file_sep>ifndef MINIGCC MINIGCC=minimake endif ifdef PROG $(PROG): $(PROG).c ifneq ("$(wildcard $(PROG).mconf)","") $(MINIGCC) --config $(PROG).mconf -o $(PROG) $(PROG).c else $(MINIGCC) --config $(PROG).c -o $(PROG) $(PROG).c endif endif src = $(patsubst %.c,%, $(wildcard *.c)) all: README.md $(foreach FILE,$(src),make PROG=$(FILE);) .PHONY: README.md README.md: cp README.in README.md #ls -lho --time-style=long-iso | grep -oE '\s*(\S*\s*){5}$$' >> README.md #echo '```'>> README.md perl Makeindex.pl >> README.md echo '```'>> README.md <file_sep>/* tail - print the end of a file */ // source: minutils #include <stdio.h> #define TRUE 1 #define FALSE 0 #define BLANK ' ' #define TAB '\t' #define NEWL '\n' int lines, chars; char buff[BUFSIZ]; main(argc, argv) int argc; char *argv[]; { char *s; FILE *input, *fopen(); int count; setbuf(stdout, buff); argc--; argv++; lines = TRUE; chars = FALSE; count = -10; if (argc == 0) { tail(stdin, count); exit(0); } s = *argv; if (*s == '-' || *s == '+') { s++; if (*s >= '0' && *s <= '9') { count = stoi(*argv); s++; while (*s >= '0' && *s <= '9') s++; } if (*s == 'c') { chars = TRUE; lines = FALSE; } else if (*s != 'l' && *s != '\0') { fprintf(stderr, "tail: unknown option %c\n", *s); argc = 0; } argc--; argv++; } if (argc < 0) { fprintf(stderr, "Usage: tail [+/-[number][lc]] [files]\n"); exit(1); } if (argc == 0) tail(stdin, count); else if ((input = fopen(*argv, "r")) == NULL) { fprintf(stderr, "tail: can't open %s\n", *argv); exit(1); } else { tail(input, count); fclose(input); } exit(0); } /* Stoi - convert string to integer */ stoi(s) char *s; { int n, sign; while (*s == BLANK || *s == NEWL || *s == TAB) s++; sign = 1; if (*s == '+') s++; else if (*s == '-') { sign = -1; s++; } for (n = 0; *s >= '0' && *s <= '9'; s++) n = 10 * n + *s - '0'; return(sign * n); } /* Tail - print 'count' lines/chars */ #define INCR(p) if (p >= end) p=cbuf ; else p++ #define BUF_SIZE 4098 char cbuf[BUF_SIZE]; tail(in, goal) FILE *in; int goal; { int c, count; char *start, *finish, *end; count = 0; if (goal > 0) { /* skip */ count++; /* start counting at 1 */ if (lines) /* lines */ while ((c = getc(in)) != EOF) { if (c == NEWL) count++; if (count >= goal) break; } else /* chars */ while (getc(in) != EOF) { count++; if (count >= goal) break; } if (count >= goal) while ((c = getc(in)) != EOF) putc(c, stdout); } else { /* tail */ goal = -goal; start = finish = cbuf; end = &cbuf[BUF_SIZE - 1]; while ((c = getc(in)) != EOF) { *finish = c; INCR(finish); if (start == finish) INCR(start); if (!lines || c == NEWL) count++; if (count > goal) { count = goal; if (lines) while (*start != NEWL) INCR(start); INCR(start); } } /* end while */ while (start != finish) { putc(*start, stdout); INCR(start); } } /* end else */ } /* end tail */ <file_sep>/* See LICENSE file for copyright and license details. */ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "util.h" extern char **environ; static void usage(void) { eprintf("usage: %s [-i] [-u var] ... [var=value] ... [cmd [arg ...]]\n", argv0); } int main(int argc, char *argv[]) { int savederrno; ARGBEGIN { case 'i': *environ = NULL; break; case 'u': if (unsetenv(EARGF(usage())) < 0) eprintf("unsetenv:"); break; default: usage(); } ARGEND for (; *argv && strchr(*argv, '='); argc--, argv++) putenv(*argv); if (*argv) { execvp(*argv, argv); savederrno = errno; weprintf("execvp %s:", *argv); _exit(126 + (savederrno == ENOENT)); } for (; *environ; environ++) puts(*environ); return fshut(stdout, "<stdout>"); } <file_sep>#if 0 mini_start mini_putchar INCLUDESRC exit 0 #endif #include "minilib.h" /* Usage: echo [TEXT...] */ int main(int argc, char *argv[]){ int n; if ( argc && argv[1][0] == '-' && argv[1][1] == 'n' ) n=2; else n=1; for ( int a = n; a<(argc); a++ ){ for ( char *c = argv[a]; *c!=0; c++ ) putchar(*c); putchar(' '); } if ( n==1 ) putchar( '\n' ); return 0; } <file_sep>/* See LICENSE file for copyright and license details. */ #include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "../crypt.h" #include "../text.h" #include "../util.h" static int hexdec(int c) { if (c >= '0' && c <= '9') return c - '0'; else if (c >= 'A' && c <= 'F') return c - 'A' + 10; else if (c >= 'a' && c <= 'f') return c - 'a' + 10; return -1; /* unknown character */ } static int mdcheckline(const char *s, uint8_t *md, size_t sz) { size_t i; int b1, b2; for (i = 0; i < sz; i++) { if (!*s || (b1 = hexdec(*s++)) < 0) return -1; /* invalid format */ if (!*s || (b2 = hexdec(*s++)) < 0) return -1; /* invalid format */ if ((uint8_t)((b1 << 4) | b2) != md[i]) return 0; /* value mismatch */ } return (i == sz) ? 1 : 0; } static void mdchecklist(FILE *listfp, struct crypt_ops *ops, uint8_t *md, size_t sz, int *formatsucks, int *noread, int *nonmatch) { int fd; size_t bufsiz = 0; int r; char *line = NULL, *file, *p; while (getline(&line, &bufsiz, listfp) > 0) { if (!(file = strstr(line, " "))) { (*formatsucks)++; continue; } if ((file - line) / 2 != sz) { (*formatsucks)++; /* checksum length mismatch */ continue; } *file = '\0'; file += 2; for (p = file; *p && *p != '\n' && *p != '\r'; p++); /* strip newline */ *p = '\0'; if ((fd = open(file, O_RDONLY)) < 0) { weprintf("open %s:", file); (*noread)++; continue; } if (cryptsum(ops, fd, file, md)) { (*noread)++; continue; } r = mdcheckline(line, md, sz); if (r == 1) { printf("%s: OK\n", file); } else if (r == 0) { printf("%s: FAILED\n", file); (*nonmatch)++; } else { (*formatsucks)++; } close(fd); } free(line); } int cryptcheck(int argc, char *argv[], struct crypt_ops *ops, uint8_t *md, size_t sz) { FILE *fp; int formatsucks = 0, noread = 0, nonmatch = 0, ret = 0; if (argc == 0) { mdchecklist(stdin, ops, md, sz, &formatsucks, &noread, &nonmatch); } else { for (; *argv; argc--, argv++) { if ((*argv)[0] == '-' && !(*argv)[1]) { fp = stdin; } else if (!(fp = fopen(*argv, "r"))) { weprintf("fopen %s:", *argv); ret = 1; continue; } mdchecklist(fp, ops, md, sz, &formatsucks, &noread, &nonmatch); if (fp != stdin) fclose(fp); } } if (formatsucks) { weprintf("%d lines are improperly formatted\n", formatsucks); ret = 1; } if (noread) { weprintf("%d listed file could not be read\n", noread); ret = 1; } if (nonmatch) { weprintf("%d computed checksums did NOT match\n", nonmatch); ret = 1; } return ret; } int cryptmain(int argc, char *argv[], struct crypt_ops *ops, uint8_t *md, size_t sz) { int fd; int ret = 0; if (argc == 0) { if (cryptsum(ops, 0, "<stdin>", md)) ret = 1; else mdprint(md, "<stdin>", sz); } else { for (; *argv; argc--, argv++) { if ((*argv)[0] == '-' && !(*argv)[1]) { *argv = "<stdin>"; fd = 0; } else if ((fd = open(*argv, O_RDONLY)) < 0) { weprintf("open %s:", *argv); ret = 1; continue; } if (cryptsum(ops, fd, *argv, md)) ret = 1; else mdprint(md, *argv, sz); if (fd != 0) close(fd); } } return ret; } int cryptsum(struct crypt_ops *ops, int fd, const char *f, uint8_t *md) { uint8_t buf[BUFSIZ]; ssize_t n; ops->init(ops->s); while ((n = read(fd, buf, sizeof(buf))) > 0) ops->update(ops->s, buf, n); if (n < 0) { weprintf("%s: read error:", f); return 1; } ops->sum(ops->s, md); return 0; } void mdprint(const uint8_t *md, const char *f, size_t len) { size_t i; for (i = 0; i < len; i++) printf("%02x", md[i]); printf(" %s\n", f); } <file_sep>/* See LICENSE file for copyright and license details. */ #include <sys/stat.h> #include <errno.h> #include <limits.h> #include "../util.h" int mkdirp(const char *path, mode_t mode, mode_t pmode) { char tmp[PATH_MAX], *p; struct stat st; if (stat(path, &st) == 0) { if (S_ISDIR(st.st_mode)) return 0; errno = ENOTDIR; weprintf("%s:", path); return -1; } estrlcpy(tmp, path, sizeof(tmp)); for (p = tmp + (tmp[0] == '/'); *p; p++) { if (*p != '/') continue; *p = '\0'; if (mkdir(tmp, pmode) < 0 && errno != EEXIST) { weprintf("mkdir %s:", tmp); return -1; } *p = '/'; } if (mkdir(tmp, mode) < 0 && errno != EEXIST) { weprintf("mkdir %s:", tmp); return -1; } return 0; } <file_sep>#if 0 mini_start mini_writes mini_ewrites mini_getresuid mini_exit_errno mini_buf 256 mini_printf mini_itodec mini_strlen INCLUDESRC SHRINKELF return #endif void usage(){ writes("getresuid\nGet the ruid, euid and suid\n"); exit(0); } int main(int argc, char *argv[]){ if ( argc > 1 ) usage(); if ( argc==1 ){ uid_t ruid, euid, suid; int e; if ( (e=getresuid( &ruid, &euid, &suid )) != 0 ){ printf("e: %d\n"); exit_errno(e); } printf(" ruid euid suid\n%5d %5d %5d\n",ruid,euid,suid); } return(0); } <file_sep>/* public domain sha1 implementation based on rfc3174 and libtomcrypt */ struct sha1 { uint64_t len; /* processed message length */ uint32_t h[5]; /* hash state */ uint8_t buf[64]; /* message block buffer */ }; enum { SHA1_DIGEST_LENGTH = 20 }; /* reset state */ void sha1_init(void *ctx); /* process message */ void sha1_update(void *ctx, const void *m, unsigned long len); /* get message digest */ /* state is ruined after sum, keep a copy if multiple sum is needed */ /* part of the message might be left in s, zero it if secrecy is needed */ void sha1_sum(void *ctx, uint8_t md[SHA1_DIGEST_LENGTH]); <file_sep>/* See LICENSE file for copyright and license details. */ #include <errno.h> #include <stdio.h> #include <unistd.h> #include <pwd.h> #include "util.h" static void usage(void) { eprintf("usage: %s\n", argv0); } int main(int argc, char *argv[]) { uid_t uid; struct passwd *pw; argv0 = *argv, argv0 ? (argc--, argv++) : (void *)0; if (argc) usage(); uid = geteuid(); errno = 0; if (!(pw = getpwuid(uid))) { if (errno) eprintf("getpwuid %d:", uid); else eprintf("getpwuid %d: no such user\n", uid); } puts(pw->pw_name); return fshut(stdout, "<stdout>"); } <file_sep>#if 0 mini_start mini_strlen mini_strcmp mini_basename mini_puts mini_ewrites LDSCRIPT onlytext INCLUDESRC shrinkelf return #endif // Original work by ammongit (github.com/ammongit/minutils) // Modified by misc 2019 static void remove_suffix(char *base, const char *suffix) { size_t baselen, suflen; char *ptr; baselen = strlen(base); suflen = strlen(suffix); ptr = base + baselen - suflen; if (!strcmp(ptr, suffix)) *ptr = '\0'; } /* Usage: basename PATH [SUFFIX] */ int main(int argc, char *argv[]) { const char *suffix; char *base; switch (argc) { case 2: suffix = NULL; break; case 3: suffix = argv[2]; break; default: ewrites("basename: missing operand\n" ); return 1; } base = basename(argv[1]); if (suffix) remove_suffix(base, suffix); puts(base); return 0; } <file_sep>#if 0 mini_start mini_writes mini_pivot_root INCLUDESRC LDSCRIPT text_and_bss HEADERGUARDS shrinkelf return #endif int main(int argc, char *argv[]){ if ( argc != 3 ){ writes("usage: pivot_root newroot put_oldroot\n"); return(0); } return( pivot_root(argv[1], argv[2]) ); } <file_sep>/* public domain sha512 implementation based on fips180-3 */ #include "sha512.h" #define sha384 sha512 /*struct*/ enum { SHA384_DIGEST_LENGTH = 48 }; /* reset state */ void sha384_init(void *ctx); /* process message */ #define sha384_update sha512_update /* get message digest */ /* state is ruined after sum, keep a copy if multiple sum is needed */ /* part of the message might be left in s, zero it if secrecy is needed */ void sha384_sum(void *ctx, uint8_t md[SHA384_DIGEST_LENGTH]); <file_sep>/* See LICENSE file for copyright and license details. */ #include <sys/resource.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include "util.h" #ifndef PRIO_MIN #define PRIO_MIN -NZERO #endif #ifndef PRIO_MAX #define PRIO_MAX (NZERO-1) #endif static void usage(void) { eprintf("usage: %s [-n inc] cmd [arg ...]\n", argv0); } int main(int argc, char *argv[]) { int val = 10, r, savederrno; ARGBEGIN { case 'n': val = estrtonum(EARGF(usage()), PRIO_MIN, PRIO_MAX); break; default: usage(); break; } ARGEND if (!argc) usage(); errno = 0; r = getpriority(PRIO_PROCESS, 0); if (errno) weprintf("getpriority:"); else val += r; LIMIT(val, PRIO_MIN, PRIO_MAX); if (setpriority(PRIO_PROCESS, 0, val) < 0) weprintf("setpriority:"); execvp(argv[0], argv); savederrno = errno; weprintf("execvp %s:", argv[0]); _exit(126 + (savederrno == ENOENT)); } <file_sep>#if 0 mini_start mini_open mini_close mini_write mini_writes mini_read mini_exit mini_exit_errno mini_dies_if mini_GETOPTS LDSCRIPT onlytext shrinkelf INCLUDESRC return #endif int main(int argc, char **argv){ int opts=0; PARSEOPTS_short(opts, argv, (m+h), SETOPT_short(opts,h)); if ( GETOPT_short(opts,h) || !*argv ){ writes("Usage: touch [-h] [-m]\n"); exit(1); } for ( char *arg=*argv; arg; arg=*(++argv) ){ int fd = open( arg, O_CREAT | O_RDWR | O_APPEND, 0644 ); if(fd<0){ ewrites("Couldn't access file\n"); exit_errno(fd); } char *v=0; if ( !GETOPT_short(opts,m) ) read( fd, (void*)v,1 ); // Read nothing, or eof. Update access time write(fd,0,1); // write eof. Update modify/and change time // This doesn't change the file's contents. // (not sure whether both confirms to posix // plase tell me, if not. It's just the smallest working solution I've been able to find) // Changing the access time only is somehow sort of unstable. // sometimes works, sometimes not. ?? // Also when syncing the file. // so I removed the option. // It might be neccessary, to use utime here. // Anyways, the binary already is at 464 Bytes. // I'd really love having all core utils within 64kB. // So, cannot afford too many rarely used options. // (misc) close(fd); } exit(0); } <file_sep> onlytext=yes echo textandbss=pwd cat tee PROG= ifndef MINI_GCC MINI_GCC=mini-gcc endif ifdef MAKEONLYTEXT $(MAKEONLYTEXT): $(MAKEONLYTEXT).c $(MAKEONLYTEXT).mconf $(MINI_GCC) --shrinkelf --ldscript onlytext --config $(MAKEONLYTEXT).mconf -include minilib.h -DINCLUDESRC -o $(MAKEONLYTEXT) $(MAKEONLYTEXT).c $(MAKEONLYTEXT).mconf: $(MINI_GCC) --shrinkelf --no-mbuf --genconf $(MAKEONLYTEXT).mconf $(MAKEONLYTEXT).c else ifdef MAKETEXTANDBSS $(MAKETEXTANDBSS): $(MAKETEXTANDBSS).c $(MAKETEXTANDBSS).mconf $(MINI_GCC) --shrinkelf --ldscript text_and_bss --config $(MAKETEXTANDBSS).mconf -include minilib.h -DINCLUDESRC -o $(MAKETEXTANDBSS) $(MAKETEXTANDBSS).c $(MAKETEXTANDBSS).mconf: $(MINI_GCC) --shrinkelf --no-mbuf --genconf $(MAKETEXTANDBSS).mconf $(MAKETEXTANDBSS).c else ifdef BUILDPROG $(BUILDPROG): $(BUILDPROG).c $(BUILDPROG).mconf $(MINI_GCC) --shrinkelf --config $(BUILDPROG).mconf -include minilib.h -DINCLUDESRC -o $(BUILDPROG) $(BUILDPROG).c $(BUILDPROG).mconf: $(MINI_GCC) --shrinkelf --genconf $(BUILDPROG).mconf $(BUILDPROG).c else all: @$(foreach P,$(onlytext),make MAKEONLYTEXT=$(P); ) @$(foreach P,$(PROG),make BUILDPROG=$(P); ) @$(foreach P,$(textandbss),make MAKETEXTANDBSS=$(P); ) clean: @echo rm $(onlytext) $(PROG) $(textandbss) rm -f $(onlytext) $(PROG) $(textandbss) #@$(foreach P,$(onlytext) $(PROG) $(textandbss), rm $P; ) endif endif endif <file_sep>// Include this file in order to use minilib functions. // define the names of the functions you'd like to use here, // uncomment unwanted functions. /// Len of buf used by read, mprintf, .. #define mini_buf 1024 #define mini_start //#define mini_vsyscalls // vsyscalls.(+ ~92 bytes). #define mini_errno // ~twice faster than standard syscalls here. #define mini_stdarg #define mini_write #define mini_open // defines also creat #define mini_close #define mini_read //#define mini_lseek // defines also ftruncate, fsync #define mini_puts #define mini_putchar #define mini_fputc //#define mini_mprints #define mini_getenv #define mini_printf #define mini_fprintf #define mini_perror #define mini_fputc #define mini_fputs #define mini_puts //#define mini_msprintf #define mini_fprintf #define mini_vprintf #define mini_mfprintf //#define mini_itohex //#define mini_itodec // also conversion %d in printf //#define mini_dtodec // also conversion %d in printf //#define mini_atoi //#define mini_itobin //#define mini_exit //#define mini_syscall //#define mini_ioctl //#define mini_tcgetattr //#define mini_tcsetattr //#define mini_select //#define mini_memfrob #define mini_strcmp #define mini_strlen //#define mini_memset //#define mini_memcpy //#define mini_strncpy //#define mini_isprint //#define mini_isprint //#define mini_isspace //#define mini_epoll // TODO:: doesn't ork //#define mini_malloc //#define mini_print //print,printl //#define powers // ipoweriui, ipoweri // Whether to overwrite the standard calls to printf, ... #define mini_overwrite #include "minilib/minilib.h" <file_sep>#if 0 mini_start mini_writes mini_mkfifo mini_perror mini_errno mini_mknod LDSCRIPT text_and_bss shrinkelf INCLUDESRC return #endif int main(int argc, const char *argv[]) { int i; if (argc == 1) { writes("Usage: mkfifo PATH [PATH...]\n"); return 1; } for (i = 1; i < argc; i++) { if (mkfifo(argv[i], 0666)) { perror("mkfifo "); return 1; } } return 0; } <file_sep>/* See LICENSE file for copyright and license details. */ #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "text.h" #include "util.h" static const char *countfmt = ""; static int dflag = 0; static int uflag = 0; static int fskip = 0; static int sskip = 0; static struct line prevl; static ssize_t prevoff = -1; static long prevlinecount = 0; static size_t uniqskip(struct line *l) { size_t i; int f = fskip, s = sskip; for (i = 0; i < l->len && f; --f) { while (isblank(l->data[i])) i++; while (i < l->len && !isblank(l->data[i])) i++; } for (; s && i < l->len && l->data[i] != '\n'; --s, i++) ; return i; } static void uniqline(FILE *ofp, struct line *l) { size_t loff; if (l) { loff = uniqskip(l); if (prevoff >= 0 && (l->len - loff) == (prevl.len - prevoff) && !memcmp(l->data + loff, prevl.data + prevoff, l->len - loff)) { ++prevlinecount; return; } } if (prevoff >= 0) { if ((prevlinecount == 1 && !dflag) || (prevlinecount != 1 && !uflag)) { if (*countfmt) fprintf(ofp, countfmt, prevlinecount); fwrite(prevl.data, 1, prevl.len, ofp); } prevoff = -1; } if (l) { if (!prevl.data || l->len >= prevl.len) { prevl.data = erealloc(prevl.data, l->len); } prevl.len = l->len; memcpy(prevl.data, l->data, prevl.len); prevoff = loff; } prevlinecount = 1; } static void uniq(FILE *fp, FILE *ofp) { static struct line line; static size_t size; ssize_t len; while ((len = getline(&line.data, &size, fp)) > 0) { line.len = len; uniqline(ofp, &line); } } static void uniqfinish(FILE *ofp) { uniqline(ofp, NULL); } static void usage(void) { eprintf("usage: %s [-c] [-d | -u] [-f fields] [-s chars]" " [input [output]]\n", argv0); } int main(int argc, char *argv[]) { FILE *fp[2] = { stdin, stdout }; int ret = 0, i; char *fname[2] = { "<stdin>", "<stdout>" }; ARGBEGIN { case 'c': countfmt = "%7ld "; break; case 'd': dflag = 1; break; case 'u': uflag = 1; break; case 'f': fskip = estrtonum(EARGF(usage()), 0, INT_MAX); break; case 's': sskip = estrtonum(EARGF(usage()), 0, INT_MAX); break; default: usage(); } ARGEND if (argc > 2) usage(); for (i = 0; i < argc; i++) { if (strcmp(argv[i], "-")) { fname[i] = argv[i]; if (!(fp[i] = fopen(argv[i], (i == 0) ? "r" : "w"))) eprintf("fopen %s:", argv[i]); } } uniq(fp[0], fp[1]); uniqfinish(fp[1]); ret |= fshut(fp[0], fname[0]) | fshut(fp[1], fname[1]); return ret; } <file_sep>/* See LICENSE file for copyright and license details. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #define SYSLOG_NAMES #include <syslog.h> #include <unistd.h> #include "util.h" static int decodetable(CODE *table, char *name) { CODE *c; for (c = table; c->c_name; c++) if (!strcasecmp(name, c->c_name)) return c->c_val; eprintf("invalid priority name: %s\n", name); return -1; /* not reached */ } static int decodepri(char *pri) { char *lev, *fac = pri; if (!(lev = strchr(pri, '.'))) eprintf("invalid priority name: %s\n", pri); *lev++ = '\0'; if (!*lev) eprintf("invalid priority name: %s\n", pri); return (decodetable(facilitynames, fac) & LOG_FACMASK) | (decodetable(prioritynames, lev) & LOG_PRIMASK); } static void usage(void) { eprintf("usage: %s [-is] [-p priority] [-t tag] [message ...]\n", argv0); } int main(int argc, char *argv[]) { size_t sz; int logflags = 0, priority = LOG_NOTICE, i; char *buf = NULL, *tag = NULL; ARGBEGIN { case 'i': logflags |= LOG_PID; break; case 'p': priority = decodepri(EARGF(usage())); break; case 's': logflags |= LOG_PERROR; break; case 't': tag = EARGF(usage()); break; default: usage(); } ARGEND openlog(tag ? tag : getlogin(), logflags, 0); if (!argc) { while (getline(&buf, &sz, stdin) > 0) syslog(priority, "%s", buf); } else { for (i = 0, sz = 0; i < argc; i++) sz += strlen(argv[i]); sz += argc; buf = ecalloc(1, sz); for (i = 0; i < argc; i++) { estrlcat(buf, argv[i], sz); if (i + 1 < argc) estrlcat(buf, " ", sz); } syslog(priority, "%s", buf); } closelog(); return fshut(stdin, "<stdin>"); } <file_sep>#if 0 mini_buf 4096 mini_start mini_fprintfs mini_itodec mini_atoi mini_itoHEX mini_printf mini_fprintf mini_prints mini_writes mini_putchar mini_strcmp mini_strerror mini_readdir mini_opendir mini_closedir mini_fputs mini_puts mini_putchar mini_malloc mini_chdir mini_errno COMPILE stat INCLUDESRC HEADERGUARDS shrinkelf return #endif // source from minutils #ifndef MLIB #include <sys/stat.h> #include <sys/types.h> #include <dirent.h> #include <errno.h> #include <stdbool.h> #include <stdio.h> #include <string.h> #endif static struct { const char *argv0; bool all : 1; int opts; } opt; //TODO: this is worth a separate header file within minilib. // It's simple and has low footprint. enum options { a, l, h }; #define SET_OPT(args,opt) { args = ( args | (0x1 << opt) ); } #define GET_OPT(args,opt) ( args & (0x1 << opt) ) //#define SET_OPT(args,opt) { args = ( args | OPTBIT_##opt ) } //#define OPTBIT_a 0x1 #define OPT(a) (1<<(a-96)) #define OPTIONS(opt) ( (1<<('a'-96)) | //int print_entry( struct dirent *ent, int args ){ int print_entry( char *name, int args ){ if ( GET_OPT( args, l ) ){ struct stat st; stat( name, &st ); switch( st.st_mode & S_IFMT ){ case S_IFREG: putchar('-'); break; case S_IFDIR: putchar('d'); break; default: putchar('-'); } int p = 0; char c[]="rwx"; for ( int i = 00400; i>0; i = i>> 1 ){ if ( st.st_mode & i ) putchar ( c[p] ); else putchar( '-' ); p++; if (p>2) p=0; } fprintf(stdout, " %d %d ", st.st_uid, st.st_gid); fprintf(stdout, "%-9d ", st.st_size); printf("%s\n", name); } else { printf("%s\n", name); } return(0); } static int list(const char *path, int label, int args) { static int notfirst; struct stat statbuf; struct dirent *ent; DIR *dh; if (stat(path, &statbuf)) { fprintfs(stderr, "ls: unable to stat %s: %s\n", path, strerror(errno)); return 1; } if (!S_ISDIR(statbuf.st_mode)) { //printf("%s\n", path); print_entry( path, args ); return 0; } if (label) { if (notfirst) putchar('\n'); notfirst = 1; printf("%s:\n", path); } dh = opendir(path); if (!dh) { fprintf(stderr, "ls: Error openening %s\n%d\n", path, errno); return 1; } chdir(path); while ((ent = readdir(dh))) { if (ent->d_name[0] == '.' && ! GET_OPT(args,a)) continue; print_entry( ent->d_name, args ); } if (closedir(dh)) { fprintfs(stderr, "ls: %s: %s\n", path, strerror(errno)); return 1; } return 0; } /* Usage: ls [-a] [PATH...] */ int main(int argc, const char *argv[]) { int i; int args = 0; for (i = 1; i < argc; i++) { if (argv[i][0] != '-') { break; } switch (argv[i][1]) { case 'a': opt.all = 1; SET_OPT(args,a); break; case 'l': SET_OPT(args,l); break; case 'h': writes( "ls [-a] [-l] [-h] [file(s) / dir(s)]\n" ); return(0); default: fprintfs(stderr, "ls: invalid argument: %s\n", argv[i]); return(1); } } //printf("opt: %d\n", args ); if (i == argc) { if (list(".", 0, args)) return 1; } else if (i == argc - 1) { if (list(argv[i], 0, args)) return 1; } else for (; i < argc; i++) { if (list(argv[i], 1, args)) return 1; } return(0); } <file_sep># Minimal shell "make" source CC = gcc CFLAGS = -Wall -O3 -fomit-frame-pointer all: $(CC) $(CFLAGS) msh.c -o msh clean: rm -f *.o core msh <file_sep>/* sedcomp.c -- stream editor main and compilation phase Copyright (C) 1995-2003 <NAME> Copyright (C) 2004-2014 <NAME> The stream editor compiles its command input (from files or -e options) into an internal form using compile() then executes the compiled form using execute(). Main() just initializes data structures, interprets command line options, and calls compile() and execute() in appropriate sequence. The data structure produced by compile() is an array of compiled-command structures (type sedcmd). These contain several pointers into pool[], the regular-expression and text-data pool, plus a command code and g & p flags. In the special case that the command is a label the struct will hold a ptr into the labels array labels[] during most of the compile, until resolve() resolves references at the end. The operation of execute() is described in its source module. */ #include <stdlib.h> /* exit */ #include <stdio.h> /* uses getc, fprintf, fopen, fclose */ #include <ctype.h> /* isdigit */ #include <string.h> /* strcmp */ #include "sed.h" /* command type struct and name defines */ /***** public stuff ******/ #define MAXCMDS 200 /* maximum number of compiled commands */ #define MAXLINES 256 /* max # numeric addresses to compile */ /* main data areas */ char linebuf[MAXBUF+1]; /* current-line buffer */ sedcmd cmds[MAXCMDS+1]; /* hold compiled commands */ long linenum[MAXLINES]; /* numeric-addresses table */ /* miscellaneous shared variables */ int nflag; /* -n option flag */ int eargc; /* scratch copy of argument count */ sedcmd *pending = NULL; /* next command to be executed */ int last_line_used = 0; /* last line address ($) was used */ void die (const char* msg) { fprintf(stderr, "sed: "); fprintf(stderr, msg, linebuf); fprintf(stderr, "\n"); exit(2); } /***** module common stuff *****/ #define POOLSIZE 10000 /* size of string-pool space */ #define WFILES 10 /* max # w output files that can be compiled */ #define RELIMIT 256 /* max chars in compiled RE */ #define MAXDEPTH 20 /* maximum {}-nesting level */ #define MAXLABS 50 /* max # of labels that can be handled */ #define SKIPWS(pc) while ((*pc==' ') || (*pc=='\t')) pc++ #define IFEQ(x, v) if (*x == v) x++ , /* do expression */ /* error messages */ static const char AGMSG[] = "garbled address %s"; static const char CGMSG[] = "garbled command %s"; static const char TMTXT[] = "too much text: %s"; static const char AD1NG[] = "no addresses allowed for %s"; static const char AD2NG[] = "only one address allowed for %s"; static const char TMCDS[] = "too many commands, last was %s"; static const char COCFI[] = "cannot open command-file %s"; static const char UFLAG[] = "unknown flag %c"; static const char CCOFI[] = "cannot create %s"; static const char ULABL[] = "undefined label %s"; static const char TMLBR[] = "too many {'s"; static const char FRENL[] = "first RE must be non-null"; static const char NSCAX[] = "no such command as %s"; static const char TMRBR[] = "too many }'s"; static const char DLABL[] = "duplicate label %s"; static const char TMLAB[] = "too many labels: %s"; static const char TMWFI[] = "too many w files"; static const char REITL[] = "RE too long: %s"; static const char TMLNR[] = "too many line numbers"; static const char TRAIL[] = "command \"%s\" has trailing garbage"; static const char RETER[] = "RE not terminated: %s"; static const char CCERR[] = "unknown character class: %s"; /* cclass to c function mapping ,-) */ static const char* cclasses[] = { "alnum", "a-zA-Z0-9", "lower", "a-z", "space", " \f\n\r\t\v", "alpha", "a-zA-Z", "digit", "0-9", "upper", "A-Z", "blank", " \t", "xdigit", "0-9A-Fa-f", "cntrl", "\x01-\x1f\x7e", "print", " -\x7e", "graph", "!-\x7e", "punct", "!-/:-@[-`{-\x7e", NULL, NULL}; typedef struct /* represent a command label */ { char *name; /* the label name */ sedcmd *last; /* it's on the label search list */ sedcmd *address; /* pointer to the cmd it labels */ } label; /* label handling */ static label labels[MAXLABS]; /* here's the label table */ static label *lab = labels + 1; /* pointer to current label */ static label *lablst = labels; /* header for search list */ /* string pool for regular expressions, append text, etc. etc. */ static char pool[POOLSIZE]; /* the pool */ static char *fp = pool; /* current pool pointer */ static char *poolend = pool + POOLSIZE; /* pointer past pool end */ /* compilation state */ static FILE *cmdf = NULL; /* current command source */ static char *cp = linebuf; /* compile pointer */ static sedcmd *cmdp = cmds; /* current compiled-cmd ptr */ static char *lastre = NULL; /* old RE pointer */ static int bdepth = 0; /* current {}-nesting level */ static int bcount = 0; /* # tagged patterns in current RE */ static char **eargv; /* scratch copy of argument list */ /* compilation flags */ static int eflag; /* -e option flag */ static int gflag; /* -g option flag */ /* prototypes */ static char *address(char *expbuf); static char *gettext(char* txp); static char *recomp(char *expbuf, char redelim); static char *rhscomp(char* rhsp, char delim); static char *ycomp(char *ep, char delim); static int cmdcomp(char cchar); static int cmdline(char *cbuf); static label *search(label *ptr); static void compile(void); static void resolve(void); /* sedexec.c protypes */ void execute(char* file); /* main sequence of the stream editor */ int main(int argc, char *argv[]) { eargc = argc; /* set local copy of argument count */ eargv = argv; /* set local copy of argument list */ cmdp->addr1 = pool; /* 1st addr expand will be at pool start */ if (eargc == 1) exit(0); /* exit immediately if no arguments */ /* scan through the arguments, interpreting each one */ while ((--eargc > 0) && (**++eargv == '-')) switch (eargv[0][1]) { case 'e': eflag++; compile(); /* compile with e flag on */ eflag = 0; continue; /* get another argument */ case 'f': if (eargc-- <= 0) /* barf if no -f file */ exit(2); if ((cmdf = fopen(*++eargv, "r")) == NULL) { fprintf(stderr, COCFI, *eargv); exit(2); } compile(); /* file is O.K., compile it */ fclose(cmdf); continue; /* go back for another argument */ case 'g': gflag++; /* set global flag on all s cmds */ continue; case 'n': nflag++; /* no print except on p flag or w */ continue; default: fprintf(stdout, UFLAG, eargv[0][1]); continue; } if (cmdp == cmds) /* no commands have been compiled */ { eargv--; eargc++; eflag++; compile(); eflag = 0; eargv++; eargc--; } if (bdepth) /* we have unbalanced squigglies */ die(TMLBR); lablst->address = cmdp; /* set up header of label linked list */ resolve(); /* resolve label table indirections */ if (eargc <= 0) /* if there were no -e commands */ execute(NULL); /* execute commands from stdin only */ else while(--eargc>=0) /* else execute only -e commands */ execute(*eargv++); exit(0); /* everything was O.K. if we got here */ } #define H 0x80 /* 128 bit, on if there's really code for command */ #define LOWCMD 56 /* = '8', lowest char indexed in cmdmask */ /* indirect through this to get command internal code, if it exists */ static char cmdmask[] = { 0, 0, H, 0, 0, H+EQCMD,0, 0, 0, 0, 0, 0, H+CDCMD,0, 0, CGCMD, CHCMD, 0, 0, 0, H+CLCMD,0, CNCMD, 0, CPCMD, 0, 0, 0, H+CTCMD,0, 0, H+CWCMD, 0, 0, 0, 0, 0, 0, 0, 0, 0, H+ACMD, H+BCMD, H+CCMD, DCMD, 0, 0, GCMD, HCMD, H+ICMD, 0, 0, H+LCMD, 0, NCMD, 0, PCMD, H+QCMD, H+RCMD, H+SCMD, H+TCMD, 0, 0, H+WCMD, XCMD, H+YCMD, 0, H+BCMD, 0, H, 0, 0, }; /* precompile sed commands out of a file */ static void compile(void) { char ccode; for(;;) /* main compilation loop */ { SKIPWS(cp); if (*cp == ';') { cp++; SKIPWS(cp); } if (*cp == '\0' || *cp == '#') /* get a new command line */ if (cmdline(cp = linebuf) < 0) break; SKIPWS(cp); if (*cp == '\0' || *cp == '#') /* a comment */ continue; /* compile first address */ if (fp > poolend) die(TMTXT); else if ((fp = address(cmdp->addr1 = fp)) == BAD) die(AGMSG); if (fp == cmdp->addr1) /* if empty RE was found */ { if (lastre) /* if there was previous RE */ cmdp->addr1 = lastre; /* use it */ else die(FRENL); } else if (fp == NULL) /* if fp was NULL */ { fp = cmdp->addr1; /* use current pool location */ cmdp->addr1 = NULL; } else { lastre = cmdp->addr1; if (*cp == ',' || *cp == ';') /* there's 2nd addr */ { cp++; if (fp > poolend) die(TMTXT); fp = address(cmdp->addr2 = fp); if (fp == BAD || fp == NULL) die(AGMSG); if (fp == cmdp->addr2) cmdp->addr2 = lastre; else lastre = cmdp->addr2; } else cmdp->addr2 = NULL; /* no 2nd address */ } if (fp > poolend) die(TMTXT); SKIPWS(cp); /* discard whitespace after address */ if (*cp == '!') { cmdp->flags.allbut = 1; cp++; SKIPWS(cp); } /* get cmd char, range-check it */ if ((*cp < LOWCMD) || (*cp > '~') || ((ccode = cmdmask[*cp - LOWCMD]) == 0)) die(NSCAX); cmdp->command = ccode & ~H; /* fill in command value */ if ((ccode & H) == 0) /* if no compile-time code */ cp++; /* discard command char */ else if (cmdcomp(*cp++)) /* execute it; if ret = 1 */ continue; /* skip next line read */ if (++cmdp >= cmds + MAXCMDS) die(TMCDS); SKIPWS(cp); /* look for trailing stuff */ if (*cp != '\0') { if (*cp == ';') { continue; } else if (*cp != '#' && *cp != '}') die(TRAIL); } } } /* compile a single command */ static int cmdcomp(char cchar) { static sedcmd **cmpstk[MAXDEPTH]; /* current cmd stack for {} */ static const char *fname[WFILES]; /* w file name pointers */ static FILE *fout[WFILES]; /* w file file ptrs */ static int nwfiles = 2; /* count of open w files */ int i; /* indexing dummy used in w */ sedcmd *sp1, *sp2; /* temps for label searches */ label *lpt; /* ditto, and the searcher */ char redelim; /* current RE delimiter */ fout[0] = stdout; fout[1] = stderr; fname[0] = "/dev/stdout"; fname[1] = "/dev/stderr"; switch(cchar) { case '{': /* start command group */ cmdp->flags.allbut = !cmdp->flags.allbut; cmpstk[bdepth++] = &(cmdp->u.link); if (++cmdp >= cmds + MAXCMDS) die(TMCDS); if (*cp == '\0') *cp++ = ';', *cp = '\0'; /* get next cmd w/o lineread */ return 1; case '}': /* end command group */ if (cmdp->addr1) die(AD1NG); /* no addresses allowed */ if (--bdepth < 0) die(TMRBR); /* too many right braces */ *cmpstk[bdepth] = cmdp; /* set the jump address */ return 1; case '=': /* print current source line number */ case 'q': /* exit the stream editor */ if (cmdp->addr2) die(AD2NG); break; case ':': /* label declaration */ if (cmdp->addr1) die(AD1NG); /* no addresses allowed */ fp = gettext(lab->name = fp); /* get the label name */ if ((lpt = search(lab))) /* does it have a double? */ { if (lpt->address) die(DLABL); /* yes, abort */ } else /* check that it doesn't overflow label table */ { lab->last = NULL; lpt = lab; if (++lab >= labels + MAXLABS) die(TMLAB); } lpt->address = cmdp; return 1; case 'b': /* branch command */ case 't': /* branch-on-succeed command */ case 'T': /* branch-on-fail command */ SKIPWS(cp); if (*cp == '\0') /* if branch is to start of cmds... */ { /* add current command to end of label last */ if ((sp1 = lablst->last)) { while((sp2 = sp1->u.link)) sp1 = sp2; sp1->u.link = cmdp; } else /* lablst->last == NULL */ lablst->last = cmdp; break; } fp = gettext(lab->name = fp); /* else get label into pool */ if ((lpt = search(lab))) /* enter branch to it */ { if (lpt->address) cmdp->u.link = lpt->address; else { sp1 = lpt->last; while((sp2 = sp1->u.link)) sp1 = sp2; sp1->u.link = cmdp; } } else /* matching named label not found */ { lab->last = cmdp; /* add the new label */ lab->address = NULL; /* it's forward of here */ if (++lab >= labels + MAXLABS) /* overflow if last */ die(TMLAB); } break; case 'a': /* append text */ case 'i': /* insert text */ case 'r': /* read file into stream */ if (cmdp->addr2) die(AD2NG); case 'c': /* change text */ if ((*cp == '\\') && (*++cp == '\n')) cp++; fp = gettext(cmdp->u.lhs = fp); break; case 'D': /* delete current line in hold space */ cmdp->u.link = cmds; break; case 's': /* substitute regular expression */ if (*cp == 0) /* get delimiter from 1st ch */ die(RETER); else redelim = *cp++; if ((fp = recomp(cmdp->u.lhs = fp, redelim)) == BAD) die(CGMSG); if (fp == cmdp->u.lhs) { /* if compiled RE zero len */ if (lastre) { cmdp->u.lhs = lastre; /* use the previous one */ cp++; /* skip delim */ } else die(FRENL); } else /* otherwise */ lastre = cmdp->u.lhs; /* save the one just found */ if ((cmdp->rhs = fp) > poolend) die(TMTXT); if ((fp = rhscomp(cmdp->rhs, redelim)) == BAD) die(CGMSG); if (gflag) cmdp->flags.global++; while (*cp == 'g' || *cp == 'p' || *cp == 'P' || isdigit(*cp)) { IFEQ(cp, 'g') cmdp->flags.global++; IFEQ(cp, 'p') cmdp->flags.print = 1; IFEQ(cp, 'P') cmdp->flags.print = 2; if (isdigit(*cp)) { if (cmdp->nth) break; /* no multiple n args */ cmdp->nth = atoi(cp); /* check 0? */ while (isdigit(*cp)) cp++; } } case 'l': /* list pattern space */ case 'L': /* dump pattern space */ if (*cp == 'w') cp++; /* and execute a w command! */ else break; /* s or L or l is done */ case 'w': /* write-pattern-space command */ case 'W': /* write-first-line command */ if (nwfiles >= WFILES) die(TMWFI); fname[nwfiles] = fp; fp = gettext((fname[nwfiles] = fp, fp)); /* filename will be in pool */ for(i = nwfiles-1; i >= 0; i--) /* match it in table */ if (strcmp(fname[nwfiles], fname[i]) == 0) { cmdp->fout = fout[i]; return 0; } /* if didn't find one, open new out file */ if ((cmdp->fout = fopen(fname[nwfiles], "w")) == NULL) { fprintf(stderr, CCOFI, fname[nwfiles]); exit(2); } fout[nwfiles++] = cmdp->fout; break; case 'y': /* transliterate text */ fp = ycomp(cmdp->u.lhs = fp, *cp++); /* compile translit */ if (fp == BAD) die(CGMSG); /* fail on bad form */ if (fp > poolend) die(TMTXT); /* fail on overflow */ break; } return 0; /* succeeded in interpreting one command */ } /* generate replacement string for substitute command right hand side rhsp: place to compile expression to delim: regular-expression end-mark to look for */ static char *rhscomp(char* rhsp, char delim) /* uses bcount */ { register char *p = cp; for(;;) /* copy for the likely case it is not s.th. special */ if ((*rhsp = *p++) == '\\') /* back reference or escape */ { if (*p >= '0' && *p <= '9') /* back reference */ { dobackref: *rhsp = *p++; /* check validity of pattern tag */ if (*rhsp > bcount + '0') return BAD; *rhsp++ |= 0x80; /* mark the good ones */ } else /* escape */ { switch (*p) { case 'n': *rhsp = '\n'; break; case 'r': *rhsp = '\r'; break; case 't': *rhsp = '\t'; break; default: *rhsp = *p; } rhsp++; p++; } } else if (*rhsp == delim) /* found RE end, hooray... */ { *rhsp++ = '\0'; /* cap the expression string */ cp = p; return rhsp; /* pt at 1 past the RE */ } else if (*rhsp == '&') /* special case, convert to backref \0 */ { *--p = '0'; goto dobackref; } else if (*rhsp++ == '\0') /* last ch not RE end, help! */ return BAD; } /* compile a regular expression to internal form expbuf: place to compile it to redelim: RE end-marker to look for */ static char *recomp(char *expbuf, char redelim) /* uses cp, bcount */ { register char *ep = expbuf; /* current-compiled-char pointer */ register char *sp = cp; /* source-character ptr */ register int c; /* current-character pointer */ char negclass; /* all-but flag */ char *lastep; /* ptr to last expr compiled */ char *lastep2; /* dito, but from the last loop */ char *svclass; /* start of current char class */ char brnest[MAXTAGS]; /* bracket-nesting array */ char *brnestp; /* ptr to current bracket-nest */ char *pp; /* scratch pointer */ int classct; /* class element count */ int tags; /* # of closed tags */ if (*cp == redelim) { /* if first char is RE endmarker */ return ep; } lastep = lastep2 = NULL; /* there's no previous RE */ brnestp = brnest; /* initialize ptr to brnest array */ tags = bcount = 0; /* initialize counters */ if ((*ep++ = (*sp == '^'))) /* check for start-of-line syntax */ sp++; for (;;) { if (*sp == 0) /* no termination */ die (RETER); if (ep >= expbuf + RELIMIT) /* match is too large */ return cp = sp, BAD; if ((c = *sp++) == redelim) /* found the end of the RE */ { cp = sp; if (brnestp != brnest) /* \(, \) unbalanced */ return BAD; *ep++ = CEOF; /* write end-of-pattern mark */ return ep; /* return ptr to compiled RE */ } lastep = lastep2; lastep2 = ep; switch (c) { case '\\': if ((c = *sp++) == '(') /* start tagged section */ { if (bcount >= MAXTAGS) return cp = sp, BAD; *brnestp++ = bcount; /* update tag stack */ *ep++ = CBRA; /* enter tag-start */ *ep++ = bcount++; /* bump tag count */ lastep2 = NULL; continue; } else if (c == ')') /* end tagged section */ { if (brnestp <= brnest) /* extra \) */ return cp = sp, BAD; *ep++ = CKET; /* enter end-of-tag */ *ep++ = *--brnestp; /* pop tag stack */ tags++; /* count closed tags */ for (lastep2 = ep-1; *lastep2 != CBRA; ) --lastep2; /* FIXME: lastep becomes start */ continue; } else if (c >= '1' && c <= '9' && c != redelim) /* tag use, if !delim */ { if ((c -= '1') >= tags) /* too few */ return BAD; *ep++ = CBACK; /* enter tag mark */ *ep++ = c; /* and the number */ continue; } else if (c == '\n') /* escaped newline no good */ return cp = sp, BAD; else if (c == 'n') /* match a newline */ c = '\n'; else if (c == 't') /* match a tab */ c = '\t'; else if (c == 'r') /* match a return */ c = '\r'; else if (c == '+') /* 1..n repeat of previous pattern */ { if (lastep == NULL) /* if + not first on line */ goto defchar; /* match a literal + */ pp = ep; /* else save old ep */ *ep++ = *lastep++ | STAR; /* flag the copy */ while (lastep < pp) /* so we can blt the pattern */ *ep++ = *lastep++; lastep2 = lastep; /* no new expression */ continue; } goto defchar; /* else match \c */ case '\0': /* ignore nuls */ continue; case '\n': /* trailing pattern delimiter is missing */ return cp = sp, BAD; case '.': /* match any char except newline */ *ep++ = CDOT; continue; case '*': /* 0..n repeat of previous pattern */ if (lastep == NULL) /* if * isn't first on line */ goto defchar; /* match a literal * */ *lastep |= STAR; /* flag previous pattern */ lastep2 = lastep; /* no new expression */ continue; case '$': /* match only end-of-line */ if (*sp != redelim) /* if we're not at end of RE */ goto defchar; /* match a literal $ */ *ep++ = CDOL; /* insert end-symbol mark */ continue; case '[': /* begin character set pattern */ if (ep + 17 >= expbuf + RELIMIT) die(REITL); *ep++ = CCL; /* insert class mark */ if ((negclass = ((c = *sp++) == '^'))) c = *sp++; svclass = sp; /* save ptr to class start */ do { if (c == '\0') die(CGMSG); /* handle predefined character classes */ if (c == '[' && *sp == ':') { /* look for the matching ":]]" */ char *p; const char *p2; for (p = sp+3; *p; p++) if (*p == ']' && *(p-1) == ']' && *(p-2) == ':') { char cc[8]; const char **it; p2 = sp+1; for (p2 = sp+1; p2 < p-2 && p2-sp-1 < sizeof(cc); p2++) cc[p2-sp-1] = *p2; cc[p2-sp-1] = 0; /* termination */ it = cclasses; while (*it && strcmp(*it, cc)) it +=2; if (!*it++) die(CCERR); /* generate mask */ p2 = *it; while (*p2) { if (p2[1] == '-' && p2[2]) { for (c = *p2; c <= p2[2]; c++) ep[c >> 3] |= bits(c & 7); p2 += 3; } else { c = *p2++; ep[c >> 3] |= bits(c & 7); } } sp = p; c = 0; break; } } /* handle character ranges */ if (c == '-' && sp > svclass && *sp != ']') for (c = sp[-2]; c < *sp; c++) ep[c >> 3] |= bits(c & 7); /* handle escape sequences in sets */ if (c == '\\') { if ((c = *sp++) == 'n') c = '\n'; else if (c == 't') c = '\t'; else if (c == 'r') c = '\r'; } /* enter (possibly translated) char in set */ if (c) ep[c >> 3] |= bits(c & 7); } while ((c = *sp++) != ']'); /* invert the bitmask if all-but was specified */ if (negclass) for(classct = 0; classct < 16; classct++) ep[classct] ^= 0xFF; ep[0] &= 0xFE; /* never match ASCII 0 */ ep += 16; /* advance ep past set mask */ continue; defchar: /* match literal character */ default: /* which is what we'd do by default */ *ep++ = CCHR; /* insert character mark */ *ep++ = c; } } } /* read next command from -e argument or command file */ static int cmdline(char *cbuf) /* uses eflag, eargc, cmdf */ { register int inc; /* not char because must hold EOF */ cbuf--; /* so pre-increment points us at cbuf */ /* e command flag is on */ if (eflag) { register char *p; /* ptr to current -e argument */ static char *savep; /* saves previous value of p */ if (eflag > 0) /* there are pending -e arguments */ { eflag = -1; if (eargc-- <= 0) exit(2); /* if no arguments, barf */ /* else transcribe next e argument into cbuf */ p = *++eargv; while((*++cbuf = *p++)) if (*cbuf == '\\') { if ((*++cbuf = *p++) == '\0') return savep = NULL, -1; else continue; } else if (*cbuf == '\n') /* end of 1 cmd line */ { *cbuf = '\0'; return savep = p, 1; /* we'll be back for the rest... */ } /* found end-of-string; can advance to next argument */ return savep = NULL, 1; } if ((p = savep) == NULL) return -1; while((*++cbuf = *p++)) if (*cbuf == '\\') { if ((*++cbuf = *p++) == '0') return savep = NULL, -1; else continue; } else if (*cbuf == '\n') { *cbuf = '\0'; return savep = p, 1; } return savep = NULL, 1; } /* if no -e flag read from command file descriptor */ while((inc = getc(cmdf)) != EOF) /* get next char */ if ((*++cbuf = inc) == '\\') /* if it's escape */ *++cbuf = inc = getc(cmdf); /* get next char */ else if (*cbuf == '\n') /* end on newline */ return *cbuf = '\0', 1; /* cap the string */ return *++cbuf = '\0', -1; /* end-of-file, no more chars */ } /* expand an address at *cp... into expbuf, return ptr at following char */ static char *address(char *expbuf) /* uses cp, linenum */ { static int numl = 0; /* current ind in addr-number table */ register char *rcp; /* temp compile ptr for forwd look */ long lno; /* computed value of numeric address */ if (*cp == '$') /* end-of-source address */ { *expbuf++ = CEND; /* write symbolic end address */ *expbuf++ = CEOF; /* and the end-of-address mark (!) */ cp++; /* go to next source character */ last_line_used = TRUE; return expbuf; /* we're done */ } if (*cp == '/') /* start of regular-expression match */ return recomp(expbuf, *cp++); /* compile the RE */ rcp = cp; lno = 0; /* now handle a numeric address */ while(*rcp >= '0' && *rcp <= '9') /* collect digits */ lno = lno*10 + *rcp++ - '0'; /* compute their value */ if (rcp > cp) /* if we caught a number... */ { *expbuf++ = CLNUM; /* put a numeric-address marker */ *expbuf++ = numl; /* and the address table index */ linenum[numl++] = lno; /* and set the table entry */ if (numl >= MAXLINES) /* oh-oh, address table overflow */ die(TMLNR); /* abort with error message */ *expbuf++ = CEOF; /* write the end-of-address marker */ cp = rcp; /* point compile past the address */ return expbuf; /* we're done */ } return NULL; /* no legal address was found */ } /* accept multiline input from *cp..., discarding leading whitespace txp: where to put the text */ static char *gettext(char* txp) /* uses global cp */ { register char *p = cp; SKIPWS(p); /* discard whitespace */ do { if ((*txp = *p++) == '\\') /* handle escapes */ *txp = *p++; if (*txp == '\0') /* we're at end of input */ return cp = --p, ++txp; else if (*txp == '\n') /* also SKIPWS after newline */ SKIPWS(p); } while (txp++); /* keep going till we find that nul */ return txp; } /* find the label matching *ptr, return NULL if none */ static label *search(label *ptr) /* uses global lablst */ { register label *rp; for(rp = lablst; rp < ptr; rp++) if ((rp->name != NULL) && (strcmp(rp->name, ptr->name) == 0)) return rp; return NULL; } /* write label links into the compiled-command space */ static void resolve(void) /* uses global lablst */ { register label *lptr; register sedcmd *rptr, *trptr; /* loop through the label table */ for(lptr = lablst; lptr < lab; lptr++) if (lptr->address == NULL) /* barf if not defined */ { fprintf(stderr, ULABL, lptr->name); exit(2); } else if (lptr->last) /* if last is non-null */ { rptr = lptr->last; /* chase it */ while((trptr = rptr->u.link)) /* resolve refs */ { rptr->u.link = lptr->address; rptr = trptr; } rptr->u.link = lptr->address; } } /* compile a y (transliterate) command ep: where to compile to delim: end delimiter to look for */ static char *ycomp(char *ep, char delim) { char *tp, *sp; int c; /* scan the 'from' section for invalid chars */ for(sp = tp = cp; *tp != delim; tp++) { if (*tp == '\\') tp++; if ((*tp == '\n') || (*tp == '\0')) return BAD; } tp++; /* tp now points at first char of 'to' section */ /* now rescan the 'from' section */ while((c = *sp++ & 0x7F) != delim) { if (c == '\\' && *sp == 'n') { sp++; c = '\n'; } if ((ep[c] = *tp++) == '\\' && *tp == 'n') { ep[c] = '\n'; tp++; } if ((ep[c] == delim) || (ep[c] == '\0')) return BAD; } if (*tp != delim) /* 'to', 'from' parts have unequal lengths */ return BAD; cp = ++tp; /* point compile ptr past translit */ for(c = 0; c < 128; c++) /* fill in self-map entries in table */ if (ep[c] == 0) ep[c] = c; return ep + 0x80; /* return first free location past table end */ } /* sedcomp.c ends here */ <file_sep>#if 0 mini_start mini_eprintsl mini_getuid mini_printsl mini_writes mini_ewrites mini_uitodec mini_getgrnam mini_atoi mini_getgrgid INCLUDESRC SHRINKELF return #endif void usage(){ writes("gid [groupname] [-g gid]\nGet the gid of groupname,\nor the groupname of gid\n"); exit(0); } void printud(uint gid){ char buf[16]; uitodec( gid, buf, 0,0,0 ); printsl(buf); exit(0); } int main(int argc, char *argv[]){ if ( argc > 1 && argv[1][0]=='-' && argv[1][1]=='h' ) usage(); if ( argc==1 ){ int gid = getuid(); if (gid<0){ ewrites("Couldn't get gid\n"); exit(1); } printud(gid); } if (argv[1][0]=='-' && argv[1][1]=='g'){ if ( argc < 3 ) usage(); int gid = atoi( argv[2] ); struct group *g = getgrgid(gid); if ( !g ){ eprintsl("Groupid not found: ",argv[2]); exit(1); } printsl(g->gr_name); exit(0); } struct group *g = getgrnam(argv[1]); if ( !g ){ eprintsl("Group not found: ",argv[1]); exit(1); } printud( g->gr_gid ); return(0); } <file_sep>#if 0 mini_start mini_writes mini_prints mini_printsl mini_chroot mini_execve INCLUDESRC LDSCRIPT text_and_bss HEADERGUARDS shrinkelf return #endif int main(int argc, char *argv[],const char*envp[]){ if (argc<2){ writes("chroot root [cmd] [arg1] [arg2] ...\n"); return(0); } if ( chroot( argv[1] )){ prints("Couldn't chroot into "); printsl(argv[1]); return(1); } if ( argc < 3 ){ char *av[]={av[0]="sh",av[1]=0 }; return(execve("/bin/sh",av,(char*const*)envp)); } return(execve(argv[2],&argv[2],(char*const*)envp)); } <file_sep>#if 0 mini_start mini_writes mini_perror mini_errno COMPILE unlink LDSCRIPT text_and_bss shrinkelf INCLUDESRC return #endif void usage(){ writes("Usage: rm file1 [file2] ...\n"); exit(1); } int main(int argc, char *argv[]) { int i; if (argc == 1) { usage(); } for (i = 1; i < argc; i++) { if (unlink(argv[i]) < 0) { perror("rm: "); return 1; } } return 0; } <file_sep> void usage(){ writes("tee file1 file2 ... [-a file3 file4 ...]\n"); exit(0); } int main(int argc, const char *argv[]) { char buf[4096]; ssize_t n; int flags = O_TRUNC; int fds[MAXSPLIT]; fds[0] = STDOUT_FILENO; int *fd = fds + 1; if ( argc == 1 || (( argv[1][0] == '-' ) && (argv[1][1] == 'h')) ){ usage(); } for ( *argv++; *argv; *argv++ ){ if ( argv[0][0] == '-' ){ switch ( argv[0][1] ) { default: eprintsl("Unknown option: ",argv[0]); case 'h': usage(); case 'a' : flags = O_APPEND; } } else { if ((*fd = open(argv[0], O_CREAT | O_WRONLY | flags, 0666))<0){ eprintsl("Couldn't open ", argv[0] ); exit_errno(*fd); } fd++; if ( fd>=(fds+MAXSPLIT) ){ eprintsl("Too many splits"); exit(1); } } } *fd = 0; while ((n = read(STDIN_FILENO, buf, sizeof(buf))) > 0) { int *f = fds; do { int e; if ((e=write( *f, buf, n)) != n){ // write with splice to stdout ? eprintsl( "Couldn't open ", argv[0]); exit_errno(e); } f++; } while ( *f ); } for ( int *f = (fds+1); *f; f++ ) close(*f); exit(0); } <file_sep>/* MIT/X Consortium Copyright (c) 2012 <NAME> <<EMAIL>> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include "../utf.h" #define MIN(x,y) ((x) < (y) ? (x) : (y)) #define UTFSEQ(x) ((((x) & 0x80) == 0x00) ? 1 /* 0xxxxxxx */ \ : (((x) & 0xC0) == 0x80) ? 0 /* 10xxxxxx */ \ : (((x) & 0xE0) == 0xC0) ? 2 /* 110xxxxx */ \ : (((x) & 0xF0) == 0xE0) ? 3 /* 1110xxxx */ \ : (((x) & 0xF8) == 0xF0) ? 4 /* 11110xxx */ \ : (((x) & 0xFC) == 0xF8) ? 5 /* 111110xx */ \ : (((x) & 0xFE) == 0xFC) ? 6 /* 1111110x */ \ : 0 ) #define BADRUNE(x) ((x) < 0 || (x) > Runemax \ || ((x) & 0xFFFE) == 0xFFFE \ || ((x) >= 0xD800 && (x) <= 0xDFFF) \ || ((x) >= 0xFDD0 && (x) <= 0xFDEF)) int runetochar(char *s, const Rune *p) { Rune r = *p; switch(runelen(r)) { case 1: /* 0aaaaaaa */ s[0] = r; return 1; case 2: /* 00000aaa aabbbbbb */ s[0] = 0xC0 | ((r & 0x0007C0) >> 6); /* 110aaaaa */ s[1] = 0x80 | (r & 0x00003F); /* 10bbbbbb */ return 2; case 3: /* aaaabbbb bbcccccc */ s[0] = 0xE0 | ((r & 0x00F000) >> 12); /* 1110aaaa */ s[1] = 0x80 | ((r & 0x000FC0) >> 6); /* 10bbbbbb */ s[2] = 0x80 | (r & 0x00003F); /* 10cccccc */ return 3; case 4: /* 000aaabb bbbbcccc ccdddddd */ s[0] = 0xF0 | ((r & 0x1C0000) >> 18); /* 11110aaa */ s[1] = 0x80 | ((r & 0x03F000) >> 12); /* 10bbbbbb */ s[2] = 0x80 | ((r & 0x000FC0) >> 6); /* 10cccccc */ s[3] = 0x80 | (r & 0x00003F); /* 10dddddd */ return 4; default: return 0; /* error */ } } int chartorune(Rune *p, const char *s) { return charntorune(p, s, UTFmax); } int charntorune(Rune *p, const char *s, size_t len) { unsigned int i, n; Rune r; if(len == 0) /* can't even look at s[0] */ return 0; switch((n = UTFSEQ(s[0]))) { case 1: r = s[0]; break; /* 0xxxxxxx */ case 2: r = s[0] & 0x1F; break; /* 110xxxxx */ case 3: r = s[0] & 0x0F; break; /* 1110xxxx */ case 4: r = s[0] & 0x07; break; /* 11110xxx */ case 5: r = s[0] & 0x03; break; /* 111110xx */ case 6: r = s[0] & 0x01; break; /* 1111110x */ default: /* invalid sequence */ *p = Runeerror; return 1; } /* add values from continuation bytes */ for(i = 1; i < MIN(n, len); i++) if((s[i] & 0xC0) == 0x80) { /* add bits from continuation byte to rune value * cannot overflow: 6 byte sequences contain 31 bits */ r = (r << 6) | (s[i] & 0x3F); /* 10xxxxxx */ } else { /* expected continuation */ *p = Runeerror; return i; } if(i < n) /* must have reached len limit */ return 0; /* reject invalid or overlong sequences */ if(BADRUNE(r) || runelen(r) < (int)n) r = Runeerror; *p = r; return n; } int runelen(Rune r) { if(BADRUNE(r)) return 0; /* error */ else if(r <= 0x7F) return 1; else if(r <= 0x07FF) return 2; else if(r <= 0xFFFF) return 3; else return 4; } size_t runenlen(const Rune *p, size_t len) { size_t i, n = 0; for(i = 0; i < len; i++) n += runelen(p[i]); return n; } int fullrune(const char *s, size_t len) { Rune r; return charntorune(&r, s, len) > 0; } <file_sep>/* public domain md5 implementation based on rfc1321 and libtomcrypt */ struct md5 { uint64_t len; /* processed message length */ uint32_t h[4]; /* hash state */ uint8_t buf[64]; /* message block buffer */ }; enum { MD5_DIGEST_LENGTH = 16 }; /* reset state */ void md5_init(void *ctx); /* process message */ void md5_update(void *ctx, const void *m, unsigned long len); /* get message digest */ /* state is ruined after sum, keep a copy if multiple sum is needed */ /* part of the message might be left in s, zero it if secrecy is needed */ void md5_sum(void *ctx, uint8_t md[MD5_DIGEST_LENGTH]); <file_sep>#if 0 COMPILE start printf dprintf prints printsl eprintfs itooct itohex stat writes \ ewrites exit_errno itodec ltodec ultohex localtime_r mini_buf 512 INCLUDESRC shrinkelf return #endif void usage(){ writes("usage: stat [-h] path1 [path2...]\n"); exit(0); } void printtime( const char* s, const struct timespec *tms ){ struct tm t; localtime_r(&tms->tv_sec,&t); printf("%s: %d-%02d-%02d %02d:%02d:%02d.%09ld\n", s, t.tm_year+1900, t.tm_mon+1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, tms->tv_nsec ); } int main(int argc, char *argv[]){ if ( argc>1 && argv[1][0] == '-' && argv[1][1] == 'h' ) usage(); struct stat st; int e=0; int tmp; char *perms = "rwx"; char *pp = perms; char permstring[12]; permstring[11]=0; typedef struct { int t; char *s; char c; } _types; #define F(x,str,chr) {.t=S_IF##x,.s=str,.c=chr} _types types[]= { F(IFO,"FIFO",'p'), F(CHR,"Char",'c'), F(DIR,"Directory",'d'), F(BLK,"Block",'b'), F(REG,"File",'-'), F(LNK,"Link",'l'), F(SOCK,"Socket",'s'), {.t=0,.s="",'-'} }; for ( *argv++; *argv; *argv++ ){ if ( (tmp=stat(*argv, &st) ) ){ eprintfs("Couldn't access %s\n",*argv); e=tmp; } else { printsl("File: ",*argv); printf("Size: %ld\t\tBlocks: %ld\t\tIO Block: %ld\t\t", st.st_size,st.st_blocks,st.st_blksize); _types *t = types; while( t->t && !(t->t&st.st_mode) ) t++; prints( t->s ); permstring[0]=t->c; printf("\nDevice: %lxh/%dd\tInode: %ld\t\tLinks: %d\n", st.st_dev,st.st_dev,st.st_ino,st.st_nlink); char *ps = permstring+1; for ( int perm = 0400; perm; perm >>= 1 ){ if ( st.st_mode & perm ) *ps = *pp; else *ps = '-'; ps++;pp++; if ( *pp==0 ) pp = perms; } if ( st.st_mode & S_ISUID ) permstring[3] = 'S'; if ( st.st_mode & S_ISGID ) permstring[6] = 'S'; printf("Access: 0%o/%s\tUid: %d\t\tGid: %d\n", st.st_mode&07777,permstring,st.st_uid,st.st_gid); printtime("Access",&st.st_atime); printtime("Modify",&st.st_mtime); printtime("Change",&st.st_ctime); } } if ( e ) exit_errno(e); exit(0); } <file_sep>#if 0 mini_start mini_puts mini_fwrites mini_getcwd mini_syscalls INCLUDESRC LDSCRIPT default shrinkelf return #endif int main(int argc, const char *argv[]) { static char cwd[PATH_MAX]; if (getcwd(cwd, sizeof(cwd))) { puts(cwd); } else { fwrites( STDERR_FILENO, "pwd: error.\n"); return 1; } return 0; } <file_sep>#if 0 mini_start mini_write #mini_strlen LDSCRIPT textandbss INCLUDESRC shrinkelf return #endif int main(int argc, char *argv[], char *envp[]){ if ( argc == 1 ){ for (;;){ write(1,"y\n",2); } } else { for ( int a=2; a<argc; a++ ){ argv[a][-1] = ' '; }; //int len = strlen(argv[argc-1])+argv[argc-1]-argv[1]; int len = *envp-argv[1]; argv[1][len] = '\n'; for ( ;; ){ write( 1,argv[1],len+1 ); } } return(0); } <file_sep>/* See LICENSE file for copyright and license details. */ #include <sys/time.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <netinet/in.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "util.h" #define BLKSIZE 512 #define HDRSIZE 4 #define PKTSIZE (BLKSIZE + HDRSIZE) #define TIMEOUT_SEC 5 /* transfer will time out after NRETRIES * TIMEOUT_SEC */ #define NRETRIES 5 #define RRQ 1 #define WWQ 2 #define DATA 3 #define ACK 4 #define ERR 5 static char *errtext[] = { "Undefined", "File not found", "Access violation", "Disk full or allocation exceeded", "Illegal TFTP operation", "Unknown transfer ID", "File already exists", "No such user" }; static struct sockaddr_storage to; static socklen_t tolen; static int timeout; static int state; static int s; static int packreq(unsigned char *buf, int op, char *path, char *mode) { unsigned char *p = buf; *p++ = op >> 8; *p++ = op & 0xff; if (strlen(path) + 1 > 256) eprintf("filename too long\n"); memcpy(p, path, strlen(path) + 1); p += strlen(path) + 1; memcpy(p, mode, strlen(mode) + 1); p += strlen(mode) + 1; return p - buf; } static int packack(unsigned char *buf, int blkno) { buf[0] = ACK >> 8; buf[1] = ACK & 0xff; buf[2] = blkno >> 8; buf[3] = blkno & 0xff; return 4; } static int packdata(unsigned char *buf, int blkno) { buf[0] = DATA >> 8; buf[1] = DATA & 0xff; buf[2] = blkno >> 8; buf[3] = blkno & 0xff; return 4; } static int unpackop(unsigned char *buf) { return (buf[0] << 8) | (buf[1] & 0xff); } static int unpackblkno(unsigned char *buf) { return (buf[2] << 8) | (buf[3] & 0xff); } static int unpackerrc(unsigned char *buf) { int errc; errc = (buf[2] << 8) | (buf[3] & 0xff); if (errc < 0 || errc >= LEN(errtext)) eprintf("bad error code: %d\n", errc); return errc; } static int writepkt(unsigned char *buf, int len) { int n; n = sendto(s, buf, len, 0, (struct sockaddr *)&to, tolen); if (n < 0) if (errno != EINTR) eprintf("sendto:"); return n; } static int readpkt(unsigned char *buf, int len) { int n; n = recvfrom(s, buf, len, 0, (struct sockaddr *)&to, &tolen); if (n < 0) { if (errno != EINTR && errno != EWOULDBLOCK) eprintf("recvfrom:"); timeout++; if (timeout == NRETRIES) eprintf("transfer timed out\n"); } else { timeout = 0; } return n; } static void getfile(char *file) { unsigned char buf[PKTSIZE]; int n, op, blkno, nextblkno = 1, done = 0; state = RRQ; for (;;) { switch (state) { case RRQ: n = packreq(buf, RRQ, file, "octet"); writepkt(buf, n); n = readpkt(buf, sizeof(buf)); if (n > 0) { op = unpackop(buf); if (op != DATA && op != ERR) eprintf("bad opcode: %d\n", op); state = op; } break; case DATA: n -= HDRSIZE; if (n < 0) eprintf("truncated packet\n"); blkno = unpackblkno(buf); if (blkno == nextblkno) { nextblkno++; write(1, &buf[HDRSIZE], n); } if (n < BLKSIZE) done = 1; state = ACK; break; case ACK: n = packack(buf, blkno); writepkt(buf, n); if (done) return; n = readpkt(buf, sizeof(buf)); if (n > 0) { op = unpackop(buf); if (op != DATA && op != ERR) eprintf("bad opcode: %d\n", op); state = op; } break; case ERR: eprintf("error: %s\n", errtext[unpackerrc(buf)]); } } } static void putfile(char *file) { unsigned char inbuf[PKTSIZE], outbuf[PKTSIZE]; int inb, outb, op, blkno, nextblkno = 0, done = 0; state = WWQ; for (;;) { switch (state) { case WWQ: outb = packreq(outbuf, WWQ, file, "octet"); writepkt(outbuf, outb); inb = readpkt(inbuf, sizeof(inbuf)); if (inb > 0) { op = unpackop(inbuf); if (op != ACK && op != ERR) eprintf("bad opcode: %d\n", op); state = op; } break; case DATA: if (blkno == nextblkno) { nextblkno++; packdata(outbuf, nextblkno); outb = read(0, &outbuf[HDRSIZE], BLKSIZE); if (outb < BLKSIZE) done = 1; } writepkt(outbuf, outb + HDRSIZE); inb = readpkt(inbuf, sizeof(inbuf)); if (inb > 0) { op = unpackop(inbuf); if (op != ACK && op != ERR) eprintf("bad opcode: %d\n", op); state = op; } break; case ACK: if (inb < HDRSIZE) eprintf("truncated packet\n"); blkno = unpackblkno(inbuf); if (blkno == nextblkno) if (done) return; state = DATA; break; case ERR: eprintf("error: %s\n", errtext[unpackerrc(inbuf)]); } } } static void usage(void) { eprintf("usage: %s -h host [-p port] [-x | -c] file\n", argv0); } int main(int argc, char *argv[]) { struct addrinfo hints, *res, *r; struct timeval tv; char *host = NULL, *port = "tftp"; void (*fn)(char *) = getfile; int ret; ARGBEGIN { case 'h': host = EARGF(usage()); break; case 'p': port = EARGF(usage()); break; case 'x': fn = getfile; break; case 'c': fn = putfile; break; default: usage(); } ARGEND if (!host || !argc) usage(); memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = IPPROTO_UDP; ret = getaddrinfo(host, port, &hints, &res); if (ret) eprintf("getaddrinfo: %s\n", gai_strerror(ret)); for (r = res; r; r = r->ai_next) { if (r->ai_family != AF_INET && r->ai_family != AF_INET6) continue; s = socket(r->ai_family, r->ai_socktype, r->ai_protocol); if (s < 0) continue; break; } if (!r) eprintf("cannot create socket\n"); memcpy(&to, r->ai_addr, r->ai_addrlen); tolen = r->ai_addrlen; freeaddrinfo(res); tv.tv_sec = TIMEOUT_SEC; tv.tv_usec = 0; if (setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) eprintf("setsockopt:"); fn(argv[0]); return 0; } <file_sep>/* See LICENSE file for copyright and license details. */ #include <sys/ioctl.h> #include <limits.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "text.h" #include "util.h" static void usage(void) { eprintf("usage: %s [-c num] [file ...]\n", argv0); } int main(int argc, char *argv[]) { FILE *fp; struct winsize w; struct linebuf b = EMPTY_LINEBUF; size_t chars = 65, maxlen = 0, i, j, k, len, cols, rows; int cflag = 0, ret = 0; char *p; ARGBEGIN { case 'c': cflag = 1; chars = estrtonum(EARGF(usage()), 1, MIN(LLONG_MAX, SIZE_MAX)); break; default: usage(); } ARGEND if (!cflag) { if ((p = getenv("COLUMNS"))) chars = estrtonum(p, 1, MIN(LLONG_MAX, SIZE_MAX)); else if (!ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) && w.ws_col > 0) chars = w.ws_col; } if (!argc) { getlines(stdin, &b); } else { for (; *argv; argc--, argv++) { if (!strcmp(*argv, "-")) { *argv = "<stdin>"; fp = stdin; } else if (!(fp = fopen(*argv, "r"))) { weprintf("fopen %s:", *argv); ret = 1; continue; } getlines(fp, &b); if (fp != stdin && fshut(fp, *argv)) ret = 1; } } for (i = 0; i < b.nlines; i++) { for (j = 0, len = 0; j < b.lines[i].len; j++) { if (UTF8_POINT(b.lines[i].data[j])) len++; } if (len && b.lines[i].data[b.lines[i].len - 1] == '\n') { b.lines[i].data[--(b.lines[i].len)] = '\0'; len--; } if (len > maxlen) maxlen = len; } for (cols = 1; (cols + 1) * maxlen + cols <= chars; cols++); rows = b.nlines / cols + (b.nlines % cols > 0); for (i = 0; i < rows; i++) { for (j = 0; j < cols && i + j * rows < b.nlines; j++) { for (k = 0, len = 0; k < b.lines[i + j * rows].len; k++) { if (UTF8_POINT(b.lines[i + j * rows].data[k])) len++; } fwrite(b.lines[i + j * rows].data, 1, b.lines[i + j * rows].len, stdout); if (j < cols - 1) for (k = len; k < maxlen + 1; k++) putchar(' '); } putchar('\n'); } ret |= fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>"); return ret; } <file_sep>#include <sys/types.h> #include <regex.h> #include <stdio.h> #include "../util.h" int enregcomp(int status, regex_t *preg, const char *regex, int cflags) { char errbuf[BUFSIZ] = ""; int r; if ((r = regcomp(preg, regex, cflags)) == 0) return r; regerror(r, preg, errbuf, sizeof(errbuf)); enprintf(status, "invalid regex: %s\n", errbuf); return r; } int eregcomp(regex_t *preg, const char *regex, int cflags) { return enregcomp(1, preg, regex, cflags); } <file_sep>#define HEADERGUARDS #define mini_start #define INCLUDESRC #define mini_fputs generate #define mini_getcwd generate #define mini_puts generate #define mini_strerror generate #include "minilib.h" <file_sep> sed: sed.h sedcomp.c sedexec.o ../../../mini-gcc --config minilib.conf -o sed sedexec.o sedcomp.c -Os -DINCLUDESRC -s sedexec.o: sedexec.c sed.h ../../../mini-gcc --config minilib.conf -c -o sedexec.o sedexec.c -Os -s <file_sep>### Static builds for linux amd64 Compiled and linked to minilib with the standard toolchain, gcc and ld, -Os; I'm trying to get a usable basic Unix system (without kernel) built statically within 64kB, it's going to be interesting. (Admittedly, possibly it's going to be 128kB. But not more.) The commands here all shall dump there usage on invocation with -h, showing the implemented arguments. (Coding this now) Just now I'm thinking about adding a tool "help" - which could be invoked by the other tools, also to dump the usage. Some sources in this directory are originally written by ammongit (github.com/ammongit/minutils) and modified by me. I also reused some fragments of minix. I kept all copyright notices within the sources. ``` basename 2022-05-10 1980 cat 2022-05-10 2845 cat2 2022-05-10 2519 chroot 2022-05-10 621 cksum 2022-05-10 2640 crc 2022-05-10 784 date 2022-05-10 2565 dd 2022-05-10 6320 echo 2022-05-10 466 false 2022-05-10 215 getenv 2022-05-10 2349 gid 2022-05-10 2772 grep 2022-05-10 1144 head 2022-05-10 1671 help 2022-05-10 544 id 2022-05-10 5584 kill 2022-05-10 3090 ln 2022-05-10 2053 loadplugin 2022-05-10 4472 ls 2022-05-10 5152 ls2 2022-05-10 5106 mkfifo 2022-05-10 2071 mount 2022-05-10 2832 pivot_root 2022-05-10 347 printenv 2022-05-10 1889 printf 2022-05-10 2976 pwd 2<PASSWORD> 635 rgrep 2022-05-10 6880 rm 2022-05-10 2067 rmdir 2022-05-10 2071 seq 2022-05-10 529 sleep 2022-05-10 500 stat 2022-05-10 5280 sum 2022-05-10 4914 sync 2022-05-10 369 tail 2022-05-10 3320 tee 2022-05-10 1401 touch 2022-05-10 720 true 2022-05-10 212 umask 2022-05-10 484 umount 2022-05-10 2328 usleep 2022-05-10 458 waitfor 2022-05-10 3693 where 2022-05-10 1258 where2 2022-05-10 1068 yes 2022-05-10 348 =============================================== size: 103542 Bytes ``` <file_sep>#define mini_start #define mini_exit #define mini_write generate #define MINILIB_OS LINUX #define MINILIB_ARCH X64 #define INCLUDESRC <file_sep>/* See LICENSE file for copyright and license details. */ #include <stdio.h> #include <string.h> #include <unistd.h> #include "text.h" #include "util.h" static void usage(void) { eprintf("usage: %s [file ...]\n", argv0); } static void rev(FILE *fp) { static char *line = NULL; static size_t size = 0; size_t i; ssize_t n; int lf; while ((n = getline(&line, &size, fp)) > 0) { lf = n && line[n - 1] == '\n'; i = n -= lf; for (n = 0; i--;) { if ((line[i] & 0xC0) == 0x80) { n++; } else { fwrite(line + i, 1, n + 1, stdout); n = 0; } } if (n) fwrite(line, 1, n, stdout); if (lf) fputc('\n', stdout); } } int main(int argc, char *argv[]) { FILE *fp; int ret = 0; ARGBEGIN { default: usage(); } ARGEND if (!argc) { rev(stdin); } else { for (; *argv; argc--, argv++) { if (!strcmp(*argv, "-")) { *argv = "<stdin>"; fp = stdin; } else if (!(fp = fopen(*argv, "r"))) { weprintf("fopen %s:", *argv); ret = 1; continue; } rev(fp); if (fp != stdin && fshut(fp, *argv)) ret = 1; } } ret |= fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>"); return ret; } <file_sep>#define INCLUDESRC #include "minilib.h" //#include "minilib/minilib_implementation.c" <file_sep>/* Minimal shell C source - (c) 1999, Spock (<NAME>) */ #include <sys/wait.h> #include <unistd.h> #include <fcntl.h> #include <stdlib.h> #include <signal.h> #include <string.h> #define chkerr(c,msg) if (c < 0) {perror("ERROR (" msg ")"); exit(-1);} #define mvdesc(d1,d2) {close(d1); dup(d2); close(d2);} #define redir(n,f) {close(n); chkerr(open(fv[n],f,0666),"open");} #define size(v,s,u,n) {(v = realloc(v,s))[u] = n;} #define l2 l1[vc] #define l3 l2[p[0]] int main(void) { char ***l1 = NULL, *fv[3] ,dir[50] ,c; int vc, bg, id, p[2], d; signal(SIGINT, SIG_IGN); signal(SIGQUIT,SIG_IGN); while (1) { getcwd(dir,50); write(1,dir,strlen(dir)); write(1," $ ",d = bg = 3); for (;bg; fv[bg] = NULL) realloc(fv[--bg],0); size(l1,4,0,NULL); for (vc = p[0] = 0; read(0,&c,1) && (c != '\n');) switch(c) { case '<': d = 0; break; case '>': d = 1; break; case '|': if (l2) {vc++; p[0] = 0;} d = 3; break; case '&': if (d < 3) d++; else bg = 1; break; case ' ': if (d < 3) {if (fv[d]) d = 3;} else if (l2 && l3) p[0]++; break; default: if (d < 3) {if (!fv[d]) size(fv[d],1,0,'\0'); size(fv[d],(id=strlen(fv[d]))+2,id,c); fv[d][id+1]='\0';} else { if (!l2) {size(l1,vc*4+8,vc+1,NULL); size(l2,4,0,NULL);} if (!l3) {size(l2,p[0]*4+8,p[0]+1,NULL); size(l3,1,0,'\0');} size(l3,(id=strlen(l3))+2,id,c); l3[id+1] = '\0';}} for (vc = 0; l2;) { if (!vc) d = dup(0); if (l1[vc+1]) chkerr(pipe(p),"pipe"); if (!strcmp(l2[0],"exit")) exit(0); if (!strcmp(l2[0],"cd")) {if (chdir(l2[1]) < 0) chdir(getenv("HOME"));} else {if (!(id = fork())) { if (fv[0] && !vc) redir(0,O_RDONLY) else mvdesc(0,d); if (fv[1]) redir(1,O_CREAT|O_WRONLY|O_TRUNC); if (fv[2]) redir(2,O_CREAT|O_WRONLY|O_TRUNC); if (l1[vc+1]) {mvdesc(1,p[1]); close(p[0]);} if (!bg) {signal(SIGINT,SIG_DFL); signal(SIGQUIT,SIG_DFL);} chkerr(execvp(l2[0],l2),"exec");} if (!l1[vc+1] && !bg) while (wait(NULL) != id);} for (id = 0; l2[id]; realloc(l2[id++],0)); realloc(l2,0); close(d); if (l1[++vc]) {d = dup(p[0]); close(p[0]); close(p[1]);}}}}<file_sep>/* public domain sha256 implementation based on fips180-3 */ struct sha256 { uint64_t len; /* processed message length */ uint32_t h[8]; /* hash state */ uint8_t buf[64]; /* message block buffer */ }; enum { SHA256_DIGEST_LENGTH = 32 }; /* reset state */ void sha256_init(void *ctx); /* process message */ void sha256_update(void *ctx, const void *m, unsigned long len); /* get message digest */ /* state is ruined after sum, keep a copy if multiple sum is needed */ /* part of the message might be left in s, zero it if secrecy is needed */ void sha256_sum(void *ctx, uint8_t md[SHA256_DIGEST_LENGTH]); <file_sep>/* public domain sha512/224 implementation based on fips180-3 */ #include "sha512.h" #define sha512_224 sha512 /*struct*/ enum { SHA512_224_DIGEST_LENGTH = 28 }; /* reset state */ void sha512_224_init(void *ctx); /* process message */ #define sha512_224_update sha512_update /* get message digest */ /* state is ruined after sum, keep a copy if multiple sum is needed */ /* part of the message might be left in s, zero it if secrecy is needed */ void sha512_224_sum(void *ctx, uint8_t md[SHA512_224_DIGEST_LENGTH]); <file_sep>#if 0 mini_start mini_open mini_close mini_write mini_writes mini_ewrites mini_read mini_group_printf mini_buf 1024 mini_GETOPTS #LDSCRIPT text_and_bss shrinkelf INCLUDESRC OPTFLAG -Os return #endif // append, extract or replace data. // read from stdin; // write to stdout. void writefile(int fd){ char buf[4096]; int l, len=0; while ( l=read(0,buf,4096) ){ write(fd,buf,l); len+=l; } //fprintf(stderr,"wrote: %d\n",len); write(fd,(char*)&len,4); write(fd,"AP\0\0",4); close(fd); } int seekfile(int fd,int trunc){ int size = lseek( fd, 0, SEEK_END ); int fsize = lseek( fd, size-8, SEEK_SET ); int len,c; read(fd,(char*)&len,4); int r = read(fd,(char*)&c,4); //fprintf(stderr,"len: %d\n",len); if ( r!=4 || ( len > fsize ) || c!=0x5041 ){ return(-1); } lseek( fd, size-8-len, SEEK_SET ); if ( trunc ) ftruncate( fd,size-8-len ); return(len); } int main(int argc, char **argv){ int opts=0; char buf[4096]; int ret = PARSEOPTS_short(opts, argv, (h+r+a+e), SETOPT_short(opts,h)); if ( GETOPT_short(opts,h) ){ writes("Usage: ap [-h] [-r] [-a] [-e] file\n\ -a append / -r replace / -e extract stdin to file / to stdout\n"); return 0; } if ( GETOPT_short(opts,a)){ int fd = open( argv[ret], O_RDWR | O_APPEND ); if ( fd<=0 ) return ( 1 ); int size = lseek( fd, 0, SEEK_END ); writefile(fd); return(0); } if ( GETOPT_short(opts,r)){ int fd = open( argv[ret], O_RDWR ); if ( fd<=0 ) return ( 1 ); int len = seekfile(fd,1); writefile(fd); return(0); } if ( GETOPT_short(opts,e)){ int fd = open( argv[ret], O_RDONLY ); if ( fd<=0 ) return ( 1 ); int len = seekfile(fd,0); if ( len<0 ){ ewrites("Error. Nothing appended.\n"); exit(-1); } int l; do { l=len; if ( len > 4096 ) l=4096; l=read(fd,buf,l); len-=l; write(1,buf,l); } while ( len>0 && l ); if ( len ){ ewrites("Error\n"); return(3); } close(fd); return(0); } return 0; } <file_sep>/* See LICENSE file for copyright and license details. */ #include <sys/stat.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "util.h" static int mflag = 0; static int oflag = 0; static FILE * parsefile(const char *fname) { struct stat st; int ret; if (!strcmp(fname, "/dev/stdout") || !strcmp(fname, "-")) return stdout; ret = lstat(fname, &st); /* if it is a new file, try to open it */ if (ret < 0 && errno == ENOENT) goto tropen; if (ret < 0) { weprintf("lstat %s:", fname); return NULL; } if (!S_ISREG(st.st_mode)) { weprintf("for safety uudecode operates only on regular files and /dev/stdout\n"); return NULL; } tropen: return fopen(fname, "w"); } static void parseheader(FILE *fp, const char *s, char **header, mode_t *mode, char **fname) { static char bufs[PATH_MAX + 18]; /* len header + mode + maxname */ char *p, *q; size_t n; if (!fgets(bufs, sizeof(bufs), fp)) if (ferror(fp)) eprintf("%s: read error:", s); if (bufs[0] == '\0' || feof(fp)) eprintf("empty or nil header string\n"); if (!(p = strchr(bufs, '\n'))) eprintf("header string too long or non-newline terminated file\n"); p = bufs; if (!(q = strchr(p, ' '))) eprintf("malformed mode string in header, expected ' '\n"); *header = bufs; *q++ = '\0'; p = q; /* now header should be null terminated, q points to mode */ if (!(q = strchr(p, ' '))) eprintf("malformed mode string in header, expected ' '\n"); *q++ = '\0'; /* now mode should be null terminated, q points to fname */ *mode = parsemode(p, *mode, 0); n = strlen(q); while (n > 0 && (q[n - 1] == '\n' || q[n - 1] == '\r')) q[--n] = '\0'; if (n > 0) *fname = q; else eprintf("header string does not contain output file\n"); } static const char b64dt[] = { -1,-1,-1,-1,-1,-1,-1,-1,-1,-2,-2,-2,-2,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63, 52,53,54,55,56,57,58,59,60,61,-1,-1,-1, 0,-1,-1,-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1, -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48, 49,50,51,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, }; static void uudecodeb64(FILE *fp, FILE *outfp) { char bufb[60], *pb; char out[45], *po; size_t n; int b = 0, e, t = -1, l = 1; unsigned char b24[3] = {0, 0, 0}; while ((n = fread(bufb, 1, sizeof(bufb), fp))) { for (pb = bufb, po = out; pb < bufb + n; pb++) { if (*pb == '\n') { l++; continue; } else if (*pb == '=') { switch (b) { case 0: /* expected '=' remaining * including footer */ if (--t) { fwrite(out, 1, (po - out), outfp); return; } continue; case 1: eprintf("%d: unexpected \"=\"" "appeared\n", l); case 2: *po++ = b24[0]; b = 0; t = 5; /* expect 5 '=' */ continue; case 3: *po++ = b24[0]; *po++ = b24[1]; b = 0; t = 6; /* expect 6 '=' */ continue; } } else if ((e = b64dt[(int)*pb]) == -1) eprintf("%d: invalid byte \"%c\"\n", l, *pb); else if (e == -2) /* whitespace */ continue; else if (t > 0) /* state is parsing pad/footer */ eprintf("%d: invalid byte \"%c\"" " after padding\n", l, *pb); switch (b) { /* decode next base64 chr based on state */ case 0: b24[0] |= e << 2; break; case 1: b24[0] |= (e >> 4) & 0x3; b24[1] |= (e & 0xf) << 4; break; case 2: b24[1] |= (e >> 2) & 0xf; b24[2] |= (e & 0x3) << 6; break; case 3: b24[2] |= e; break; } if (++b == 4) { /* complete decoding an octet */ *po++ = b24[0]; *po++ = b24[1]; *po++ = b24[2]; b24[0] = b24[1] = b24[2] = 0; b = 0; } } fwrite(out, 1, (po - out), outfp); } eprintf("%d: invalid uudecode footer \"====\" not found\n", l); } static void uudecode(FILE *fp, FILE *outfp) { char *bufb = NULL, *p; size_t n = 0; ssize_t len; int ch, i; #define DEC(c) (((c) - ' ') & 077) /* single character decode */ #define IS_DEC(c) ( (((c) - ' ') >= 0) && (((c) - ' ') <= 077 + 1) ) #define OUT_OF_RANGE(c) eprintf("character %c out of range: [%d-%d]\n", (c), 1 + ' ', 077 + ' ' + 1) while ((len = getline(&bufb, &n, fp)) > 0) { p = bufb; /* trim newlines */ if (!len || bufb[len - 1] != '\n') eprintf("no newline found, aborting\n"); bufb[len - 1] = '\0'; /* check for last line */ if ((i = DEC(*p)) <= 0) break; for (++p; i > 0; p += 4, i -= 3) { if (i >= 3) { if (!(IS_DEC(*p) && IS_DEC(*(p + 1)) && IS_DEC(*(p + 2)) && IS_DEC(*(p + 3)))) OUT_OF_RANGE(*p); ch = DEC(p[0]) << 2 | DEC(p[1]) >> 4; putc(ch, outfp); ch = DEC(p[1]) << 4 | DEC(p[2]) >> 2; putc(ch, outfp); ch = DEC(p[2]) << 6 | DEC(p[3]); putc(ch, outfp); } else { if (i >= 1) { if (!(IS_DEC(*p) && IS_DEC(*(p + 1)))) OUT_OF_RANGE(*p); ch = DEC(p[0]) << 2 | DEC(p[1]) >> 4; putc(ch, outfp); } if (i >= 2) { if (!(IS_DEC(*(p + 1)) && IS_DEC(*(p + 2)))) OUT_OF_RANGE(*p); ch = DEC(p[1]) << 4 | DEC(p[2]) >> 2; putc(ch, outfp); } } } if (ferror(fp)) eprintf("read error:"); } /* check for end or fail */ if ((len = getline(&bufb, &n, fp)) < 0) eprintf("getline:"); if (len < 3 || strncmp(bufb, "end", 3) || bufb[3] != '\n') eprintf("invalid uudecode footer \"end\" not found\n"); free(bufb); } static void usage(void) { eprintf("usage: %s [-m] [-o output] [file]\n", argv0); } int main(int argc, char *argv[]) { FILE *fp = NULL, *nfp = NULL; mode_t mode = 0; int ret = 0; char *fname, *header, *ifname, *ofname = NULL; void (*d) (FILE *, FILE *) = NULL; ARGBEGIN { case 'm': mflag = 1; /* accepted but unused (autodetect file type) */ break; case 'o': oflag = 1; ofname = EARGF(usage()); break; default: usage(); } ARGEND if (argc > 1) usage(); if (!argc || !strcmp(argv[0], "-")) { fp = stdin; ifname = "<stdin>"; } else { if (!(fp = fopen(argv[0], "r"))) eprintf("fopen %s:", argv[0]); ifname = argv[0]; } parseheader(fp, ifname, &header, &mode, &fname); if (!strncmp(header, "begin", sizeof("begin"))) d = uudecode; else if (!strncmp(header, "begin-base64", sizeof("begin-base64"))) d = uudecodeb64; else eprintf("unknown header %s:", header); if (oflag) fname = ofname; if (!(nfp = parsefile(fname))) eprintf("fopen %s:", fname); d(fp, nfp); if (nfp != stdout && chmod(fname, mode) < 0) eprintf("chmod %s:", fname); ret |= fshut(fp, (fp == stdin) ? "<stdin>" : argv[0]); ret |= fshut(nfp, (nfp == stdout) ? "<stdout>" : fname); return ret; } <file_sep>#if 0 mini_start mini_ewrites mini_writes mini_eprints mini_exit_errno mini_syscalls mini_strcpy INCLUDESRC SHRINKELF #LDSCRIPT text_and_bss return #endif // sudo for root, to drop privileges #define uid_nobody 65534 #define gid_nobody 65534 void usage(){ writes("usage: udo [-h] [-u uid] [-g gid] [-G gid1,gid2,...] [-G ...] [-G gid32] command [arguments]\n"); exit(1); } int getint( const char *c ){ if ( !c ) usage(); int ret = 0; while( (*c>='0') && (*c<='9') ){ ret*=10; ret=ret+(*c-48); c++; } if ( *c != 0 ) usage(); return(ret); } int main(int argc, char **argv, char **envp ){ int uid = uid_nobody; int gid = gid_nobody; static gid_t groups[32]; int groupcount = 0; if (argc < 2 ){ usage(); } for ( *argv++; *argv && argv[0][0]=='-'; *argv++ ){ switch ( argv[0][1] ){ case 'h': usage(); case 'u': uid = getint(argv[1]); break; //case 'H': (todo: set HOME var) // For now prepend udo with the setting // ( e.g. 'HOME=/tmp udo -u 1000 id' ) // break; case 'g': gid = getint(argv[1]); break; case 'G': { char *c = argv[1]; do { groups[groupcount] = 0; for( int i=0; (*c>='0') && (*c<='9'); c++ ) groups[groupcount] = groups[groupcount]*10 + *c-'0'; groupcount++; } while ( *c && *c==',' && c++ ); } } *argv++; } if ( !*argv ) usage(); if ( groupcount == 0){ groupcount = 1; groups[0] = gid; } int ret; #define IFFAIL(a,str) if ( (ret=a) ){ewrites(str); goto failed;} IFFAIL(sys_setgroups(groupcount,groups),"setgroups()"); IFFAIL(setgid(gid),"setgid()"); IFFAIL(setuid(uid),"setuid()"); for ( char *c = *argv; c<(*envp-1); c++ ){ if ( !*c ) *c = ' '; } char* arg[] = { "sh", "-c", *argv }; ret = execve("/bin/sh", arg, envp ); ewrites("Executing /bin/sh"); failed: ewrites(" failed\n"); exit_errno(ret); } <file_sep>/* See LICENSE file for copyright and license details. */ #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "util.h" static void usage(void) { eprintf("usage: %s [-fn] path\n", argv0); } int main(int argc, char *argv[]) { char buf[PATH_MAX]; ssize_t n; int nflag = 0, fflag = 0; ARGBEGIN { case 'f': fflag = ARGC(); break; case 'n': nflag = 1; break; default: usage(); } ARGEND if (argc != 1) usage(); if (strlen(argv[0]) >= PATH_MAX) eprintf("path too long\n"); if (fflag) { if (!realpath(argv[0], buf)) eprintf("realpath %s:", argv[0]); } else { if ((n = readlink(argv[0], buf, PATH_MAX - 1)) < 0) eprintf("readlink %s:", argv[0]); buf[n] = '\0'; } fputs(buf, stdout); if (!nflag) putchar('\n'); return fshut(stdout, "<stdout>"); } <file_sep>#if 0 mini_start mini_sync mini_writes #LDSCRIPT text_and_bss shrinkelf INCLUDESRC return #endif // misc 2020/06 // BSD license int main(int argc, char *argv[]){ if (argc > 1) { writes("Usage: sync\n"); } else { sync(); } return 0; } <file_sep>/* See LICENSE file for copyright and license details. */ #include <sys/stat.h> #include <errno.h> #include <stdio.h> #include <unistd.h> #include "../fs.h" #include "../util.h" int rm_status = 0; void rm(const char *path, struct stat *st, void *data, struct recursor *r) { if (!r->maxdepth && S_ISDIR(st->st_mode)) { recurse(path, NULL, r); if (rmdir(path) < 0) { if (!(r->flags & SILENT)) weprintf("rmdir %s:", path); if (!((r->flags & SILENT) && errno == ENOENT)) rm_status = 1; } } else if (unlink(path) < 0) { if (!(r->flags & SILENT)) weprintf("unlink %s:", path); if (!((r->flags & SILENT) && errno == ENOENT)) rm_status = 1; } } <file_sep>MCC=$(MINI_GCC) src = $(patsubst %.c,%, $(wildcard *.c)) all: $(src) README.md %: %.c $(eval OPT=--config $@.c) $(if $(wildcard $@.mconf),$(eval OPT=--config $@.mconf),) $(if $(wildcard $@.conf),$(eval OPT=--config $@.conf),) @echo -e "\e[36m" $(MCC) $(OPT) -o $@ $@.c "\e[37m" @$(MCC) $(OPT) -o $@ $@.c @touch README.in #.PHONY: README.md README.md: cp README.in README.md #ls -lho --time-style=long-iso | grep -oE '\s*(\S*\s*){5}$$' >> README.md #echo '```'>> README.md perl Makeindex.pl >> README.md echo '```'>> README.md <file_sep>/* See LICENSE file for copyright and license details. */ #include <sys/utsname.h> #include <stdio.h> #include "util.h" static void usage(void) { eprintf("usage: %s [-amnrsv]\n", argv0); } int main(int argc, char *argv[]) { struct utsname u; int mflag = 0, nflag = 0, rflag = 0, sflag = 0, vflag = 0; ARGBEGIN { case 'a': mflag = nflag = rflag = sflag = vflag = 1; break; case 'm': mflag = 1; break; case 'n': nflag = 1; break; case 'r': rflag = 1; break; case 's': sflag = 1; break; case 'v': vflag = 1; break; default: usage(); } ARGEND if (argc) usage(); if (uname(&u) < 0) eprintf("uname:"); if (sflag || !(nflag || rflag || vflag || mflag)) putword(stdout, u.sysname); if (nflag) putword(stdout, u.nodename); if (rflag) putword(stdout, u.release); if (vflag) putword(stdout, u.version); if (mflag) putword(stdout, u.machine); putchar('\n'); return fshut(stdout, "<stdout>"); } <file_sep>#if 0 globals_on_stack mini_errno mini_start mini_printsl mini_prints mini_writes mini_getenv mini_environ mini_where_l mini_INCLUDESRC LDSCRIPT onlytext SHRINKELF OPTFLAG -Os #STRIPFLAG ' ' return #endif int main( int argc, char *argv[], char *envp[] ){ int r = 1; if ( argc < 2 ){ writes("usage: where executable executable .."); } else { char buf[PATH_MAX]; for ( *argv++; *argv; *argv++ ){ const char *iter = 0; r=1; while ( where_l(*argv,&iter,buf) ){ printsl(buf); r = 0; } if ( r ) { prints( *argv, " not found\n" ); } } } exit(r); } <file_sep>#if 0 mini_start mini_open mini_close mini_write mini_writes mini_ewrites mini_read #mini_group_printf #mini_buf 1024 mini_GETOPTS #LDSCRIPT text_and_bss shrinkelf INCLUDESRC OPTFLAG -Os return #endif struct { int total; int w; } TT; // base64 // original work // Copyright 2014 <NAME> <<EMAIL>> // (BSD) // // modified 2020/12 by misc static void wraputchar(int c, int *x) { putchar(c); TT.total++; if (TT.w && ++*x == TT.w) { *x = 0; putc('\n'); }; } static void do_base64(int fd, char *name) { int out = 0, bits = 0, x = 0, i, len; char *buf = toybuf+128; TT.total = 0; for (;;) { // If no more data, flush buffer if (!(len = xread(fd, buf, sizeof(toybuf)-128))) { if (!(toys.optflags & FLAG_d)) { if (bits) wraputchar(toybuf[out<<(6-bits)], &x); while (TT.total&3) wraputchar('=', &x); if (x) xputc('\n'); } return; } for (i=0; i<len; i++) { if (toys.optflags & FLAG_d) { if (buf[i] == '=') return; if ((x = stridx(toybuf, buf[i])) != -1) { out = (out<<6) + x; bits += 6; if (bits >= 8) { putchar(out >> (bits -= 8)); out &= (1<<bits)-1; if (ferror(stdout)) perror_exit(0); } continue; } if (buf[i] == '\n' || (toys.optflags & FLAG_i)) continue; break; } else { out = (out<<8) + buf[i]; bits += 8; while (bits >= 6) { wraputchar(toybuf[out >> (bits -= 6)], &x); out &= (1<<bits)-1; } } } } } <file_sep>/* public domain sha224 implementation based on fips180-3 */ #include "sha256.h" #define sha224 sha256 /*struct*/ enum { SHA224_DIGEST_LENGTH = 28 }; /* reset state */ void sha224_init(void *ctx); /* process message */ #define sha224_update sha256_update /* get message digest */ /* state is ruined after sum, keep a copy if multiple sum is needed */ /* part of the message might be left in s, zero it if secrecy is needed */ void sha224_sum(void *ctx, uint8_t md[SHA224_DIGEST_LENGTH]); <file_sep> all: README.md cd core $(make) cd core $(make) up: all git commit -m 'update' -a git push .PHONY: README.md README.md: cp README.in README.md #ls -lho --time-style=long-iso | grep -oE '\s*(\S*\s*){5}$$' >> README.md #echo '```'>> README.md cd core && perl Makeindex.pl >> ../README.md echo '```'>> README.md <file_sep>### Static builds for linux amd64 Compiled and linked with the standard toolchain, gcc and ld, -Os; Here go tools, not neccessarily present at a standard linux system. Since I'm aiming at a 64kB (128kB max) base system, I've to separate them. ``` ap 2021-05-31 1320 conv 2021-05-31 3144 errno 2021-05-31 7837 fromhex 2021-05-31 816 getresuid 2021-05-31 2448 kgetty 2021-05-31 3832 kgetty-persistent 2021-05-31 4864 ksudo 2021-05-31 924 lockfile 2021-05-31 3776 nbdo 2021-05-31 983 sed/sed 2020-07-07 16748 su 2021-05-31 661 tohex 2021-05-31 840 udo 2021-05-31 1252 xorpipe 2021-05-31 4464 =============================================== size: 53909 Bytes ``` <file_sep>#define mini_buf 1024 #define HEADERGUARDS #define mini_start #define INCLUDESRC #define mini_fclose generate #define mini_fputc generate #define mini_fputs generate #define mini_putchar generate #define mini_strcmp generate #include "minilib.h" <file_sep>#if 0 mini_start mini_write mini_writes mini_read INCLUDESRC return #endif // misc 2020 #define BUF 4096 void usage(){ writes("fromhex. convert hexadecimal input to ascii.\n\ Doesn't check for errors.(0x, linebreaks,..)\n"); exit(0); } int main(int argc, char **argv){ if ( argc>1 ) usage(); char c[BUF]; char o[BUF/2]; int r = 0; while ( (r=read(0,&c,BUF) ) > 0 ){ for (int a=0; a<r; a+=2 ){ char t=c[a]; char t2=c[a+1]; o[a>>1]= ((47 < t && t < 58 ?(t-48) : (t-87) )<<4) | (47<t2 && t2<58 ? (t2-48) : (t2-87)); } write(1,o,r>>1); } return(0); } <file_sep>#if 0 mini_start mini_writes mini_perror mini_errno mini_rmdir LDSCRIPT text_and_bss shrinkelf INCLUDESRC return #endif void usage(){ writes("Usage: rmdir dir1 [dir2] ...\n"); exit(1); } int main(int argc, const char *argv[]) { int i; if (argc == 1) { usage(); } for (i = 1; i < argc; i++) { if (rmdir(argv[i])) { perror("rmdir: "); return 1; } } return 0; } <file_sep>#define mini_buf 1024 #define HEADERGUARDS #define mini_start #define INCLUDESRC #define mini_fclose generate #define mini_fputc generate #define mini_fputs generate #define mini_putchar generate #define mini_strcmp generate #define mini_ferror generate #define mini_fflush generate #define mini_vfprintf generate <file_sep>#ifndef sed_h #define sed_h /* sed.h -- types and constants for the stream editor Copyright (C) 1995-2003 <NAME> Copyright (C) 2004-2005 <NAME> */ #define TRUE 1 #define FALSE 0 /* data area sizes used by both modules */ #define MAXBUF 4000 /* current line buffer size */ #define MAXAPPENDS 20 /* maximum number of appends */ #define MAXTAGS 9 /* tagged patterns are \1 to \9 */ #define MAXCMDS 200 /* maximum number of compiled commands */ #define MAXLINES 256 /* max # numeric addresses to compile */ /* constants for compiled-command representation */ #define EQCMD 0x01 /* = -- print current line number */ #define ACMD 0x02 /* a -- append text after current line */ #define BCMD 0x03 /* b -- branch to label */ #define CCMD 0x04 /* c -- change current line */ #define DCMD 0x05 /* d -- delete all of pattern space */ #define CDCMD 0x06 /* D -- delete first line of pattern space */ #define GCMD 0x07 /* g -- copy hold space to pattern space */ #define CGCMD 0x08 /* G -- append hold space to pattern space */ #define HCMD 0x09 /* h -- copy pattern space to hold space */ #define CHCMD 0x0A /* H -- append hold space to pattern space */ #define ICMD 0x0B /* i -- insert text before current line */ #define LCMD 0x0C /* l -- print pattern space in escaped form */ #define CLCMD 0x20 /* L -- hexdump */ #define NCMD 0x0D /* n -- get next line into pattern space */ #define CNCMD 0x0E /* N -- append next line to pattern space */ #define PCMD 0x0F /* p -- print pattern space to output */ #define CPCMD 0x10 /* P -- print first line of pattern space */ #define QCMD 0x11 /* q -- exit the stream editor */ #define RCMD 0x12 /* r -- read in a file after current line */ #define SCMD 0x13 /* s -- regular-expression substitute */ #define TCMD 0x14 /* t -- branch on last substitute successful */ #define CTCMD 0x15 /* T -- branch on last substitute failed */ #define WCMD 0x16 /* w -- write pattern space to file */ #define CWCMD 0x17 /* W -- write first line of pattern space */ #define XCMD 0x18 /* x -- exhange pattern and hold spaces */ #define YCMD 0x19 /* y -- transliterate text */ typedef struct cmd_t /* compiled-command representation */ { char *addr1; /* first address for command */ char *addr2; /* second address for command */ union { char *lhs; /* s command lhs */ struct cmd_t *link; /* label link */ } u; char command; /* command code */ char *rhs; /* s command replacement string */ FILE *fout; /* associated output file descriptor */ struct { unsigned allbut : 1; /* was negation specified? */ unsigned global : 1; /* was p postfix specified? */ unsigned print : 2; /* was g postfix specified? */ unsigned inrange : 1; /* in an address range? */ } flags; unsigned nth; /* sed nth occurance */ } sedcmd; /* use this name for declarations */ #define BAD ((char *) -1) /* guaranteed not a string ptr */ /* address and regular expression compiled-form markers */ #define STAR 1 /* marker for Kleene star */ #define CCHR 2 /* non-newline character to be matched follows */ #define CDOT 4 /* dot wild-card marker */ #define CCL 6 /* character class follows */ #define CNL 8 /* match line start */ #define CDOL 10 /* match line end */ #define CBRA 12 /* tagged pattern start marker */ #define CKET 14 /* tagged pattern end marker */ #define CBACK 16 /* backslash-digit pair marker */ #define CLNUM 18 /* numeric-address index follows */ #define CEND 20 /* symbol for end-of-source */ #define CEOF 22 /* end-of-field mark */ #define bits(b) (1 << (b)) /* sed.h ends here */ #endif <file_sep>#if 0 mini_start mini_writes mini_fwrites mini_umount2 mini_errno mini_errno_str LDSCRIPT text_and_bss shrinkelf INCLUDESRC return #endif // misc 2020/06 // BSD license void usage(){ writes("Usage: umount [-h|f|d|e|n] mountpoint\n"); exit(-1); } int main(int argc, char *argv[]){ char *m = 0; int flags = 0; char buf[6]; if (argc < 2) { usage(); } for ( *argv++; *argv; *argv++ ){ if ( **argv == '-' ){ for ( char *p = &argv[0][1]; *p!=0; p++ ){ switch (*p){ case 'h': usage(); break; case 'f': flags |= MNT_FORCE; break; case 'd': flags |= MNT_DETACH; break; case 'e': flags |= MNT_EXPIRE; break; case 'n': flags |= UMOUNT_NOFOLLOW; break; default: fwrites(STDERR_FILENO,"Unknown option: -"); write(STDERR_FILENO,p,1); write(STDERR_FILENO,"\n",1); exit(-1); } } } else { m = *argv; } } if ( !m ) usage(); if ( umount2( m, flags ) ){ int err = errno; fwrites(STDERR_FILENO, "Error: "); write(STDERR_FILENO,errno_str(err,buf),3); return(-1); } return(0); } <file_sep>#if 0 mini_start mini_buf 512 globals_on_stack OPTFLAG "-Os" mini_printf mini_itodec mini_ltodec mini_itoHEX mini_itobin mini_itooct mini_writes mini_strtol mini_strlen LDSCRIPT textandbss INCLUDESRC SHRINKELF return #endif void usage(){ writes("Usage: conv number [base]\nbase can be 2 to 36\n"); exit(0); } int main(int argc, char** argv){ if ( argc<2 || (argv[1][0] == '-' && argv[1][1] == 'h' ) ) usage(); int base = 0; if (argc > 2 ) base = (int)strtol(argv[2],0,0); long l = strtol(argv[1],0,base); printf("%ld\n0x%X\n0%o\n%b\n", l,l,l,l); return(0); } <file_sep>#if 0 mini_start mini_putchar mini_writes mini_errno mini_symlink mini_link INCLUDESRC LDSCRIPT textandbss shrinkelf return #endif int main(int argc, char *argv[]){ if ( argc < 3 ){ writes("usage: ln [-s] path link\n"); return(1); } int s = 1; if ( argv[1][0] == '-' && argv[1][1] == 's' ) s=2; int ret; if ( s==2 ){ ret=symlink(argv[s],argv[s+1]); } else { ret=link(argv[s],argv[s+1]); } if ( ret ){ writes("ln: error: "); putchar( 48+(errno/10) ); putchar( 48+(errno%10) ); putchar( '\n' ); return(errno); } return( 0 ); } <file_sep>/* public domain sha224 implementation based on fips180-3 */ #include <stdint.h> #include "../sha224.h" extern void sha256_sum_n(void *, uint8_t *, int n); void sha224_init(void *ctx) { struct sha224 *s = ctx; s->len = 0; s->h[0] = 0xc1059ed8; s->h[1] = 0x367cd507; s->h[2] = 0x3070dd17; s->h[3] = 0xf70e5939; s->h[4] = 0xffc00b31; s->h[5] = 0x68581511; s->h[6] = 0x64f98fa7; s->h[7] = 0xbefa4fa4; } void sha224_sum(void *ctx, uint8_t md[SHA224_DIGEST_LENGTH]) { sha256_sum_n(ctx, md, 8); } <file_sep>/* See LICENSE file for copyright and license details. */ struct crypt_ops { void (*init)(void *); void (*update)(void *, const void *, unsigned long); void (*sum)(void *, uint8_t *); void *s; }; int cryptcheck(int, char **, struct crypt_ops *, uint8_t *, size_t); int cryptmain(int, char **, struct crypt_ops *, uint8_t *, size_t); int cryptsum(struct crypt_ops *, int, const char *, uint8_t *); void mdprint(const uint8_t *, const char *, size_t); <file_sep>/* See LICENSE file for copyright and license details. */ #include <sys/stat.h> #include <ctype.h> #include <fcntl.h> #include <string.h> #include <unistd.h> #include "util.h" static int intcmp(char *a, char *b) { char *s; int asign = *a == '-' ? -1 : 1; int bsign = *b == '-' ? -1 : 1; if (*a == '-' || *a == '+') a += 1; if (*b == '-' || *b == '+') b += 1; if (!*a || !*b) goto noint; for (s = a; *s; s++) if (!isdigit(*s)) goto noint; for (s = b; *s; s++) if (!isdigit(*s)) goto noint; while (*a == '0') a++; while (*b == '0') b++; asign *= !!*a; bsign *= !!*b; if (asign != bsign) return asign < bsign ? -1 : 1; else if (strlen(a) != strlen(b)) return asign * (strlen(a) < strlen(b) ? -1 : 1); else return asign * strcmp(a, b); noint: enprintf(2, "expected integer operands\n"); return 0; /* not reached */ } static int mtimecmp(struct stat *buf1, struct stat *buf2) { if (buf1->st_mtime < buf2->st_mtime) return -1; if (buf1->st_mtime > buf2->st_mtime) return +1; #ifdef st_mtime if (buf1->st_mtim.tv_nsec < buf2->st_mtim.tv_nsec) return -1; if (buf1->st_mtim.tv_nsec > buf2->st_mtim.tv_nsec) return +1; #endif return 0; } static int unary_b(char *s) { struct stat buf; if ( stat(s, &buf)) return 0; return S_ISBLK (buf.st_mode); } static int unary_c(char *s) { struct stat buf; if ( stat(s, &buf)) return 0; return S_ISCHR (buf.st_mode); } static int unary_d(char *s) { struct stat buf; if ( stat(s, &buf)) return 0; return S_ISDIR (buf.st_mode); } static int unary_f(char *s) { struct stat buf; if ( stat(s, &buf)) return 0; return S_ISREG (buf.st_mode); } static int unary_g(char *s) { struct stat buf; if ( stat(s, &buf)) return 0; return S_ISGID & buf.st_mode ; } static int unary_h(char *s) { struct stat buf; if (lstat(s, &buf)) return 0; return S_ISLNK (buf.st_mode); } static int unary_k(char *s) { struct stat buf; if ( stat(s, &buf)) return 0; return S_ISVTX & buf.st_mode ; } static int unary_p(char *s) { struct stat buf; if ( stat(s, &buf)) return 0; return S_ISFIFO (buf.st_mode); } static int unary_S(char *s) { struct stat buf; if ( stat(s, &buf)) return 0; return S_ISSOCK (buf.st_mode); } static int unary_s(char *s) { struct stat buf; if ( stat(s, &buf)) return 0; return buf.st_size ; } static int unary_u(char *s) { struct stat buf; if ( stat(s, &buf)) return 0; return S_ISUID & buf.st_mode ; } static int unary_n(char *s) { return *s; } static int unary_z(char *s) { return !*s; } static int unary_e(char *s) { return !faccessat(AT_FDCWD, s, F_OK, AT_EACCESS); } static int unary_r(char *s) { return !faccessat(AT_FDCWD, s, R_OK, AT_EACCESS); } static int unary_w(char *s) { return !faccessat(AT_FDCWD, s, W_OK, AT_EACCESS); } static int unary_x(char *s) { return !faccessat(AT_FDCWD, s, X_OK, AT_EACCESS); } static int unary_t(char *s) { int fd = enstrtonum(2, s, 0, INT_MAX); return isatty(fd); } static int binary_se(char *s1, char *s2) { return !strcmp(s1, s2); } static int binary_sn(char *s1, char *s2) { return strcmp(s1, s2); } static int binary_eq(char *s1, char *s2) { return intcmp(s1, s2) == 0; } static int binary_ne(char *s1, char *s2) { return intcmp(s1, s2) != 0; } static int binary_gt(char *s1, char *s2) { return intcmp(s1, s2) > 0; } static int binary_ge(char *s1, char *s2) { return intcmp(s1, s2) >= 0; } static int binary_lt(char *s1, char *s2) { return intcmp(s1, s2) < 0; } static int binary_le(char *s1, char *s2) { return intcmp(s1, s2) <= 0; } static int binary_ef(char *s1, char *s2) { struct stat buf1, buf2; if (stat(s1, &buf1) || stat(s2, &buf2)) return 0; return buf1.st_dev == buf2.st_dev && buf1.st_ino == buf2.st_ino; } static int binary_ot(char *s1, char *s2) { struct stat buf1, buf2; if (stat(s1, &buf1) || stat(s2, &buf2)) return 0; return mtimecmp(&buf1, &buf2) < 0; } static int binary_nt(char *s1, char *s2) { struct stat buf1, buf2; if (stat(s1, &buf1) || stat(s2, &buf2)) return 0; return mtimecmp(&buf1, &buf2) > 0; } struct test { char *name; union { int (*u)(char *); int (*b)(char *, char *); } func; }; static struct test unary[] = { { "-b", { .u = unary_b } }, { "-c", { .u = unary_c } }, { "-d", { .u = unary_d } }, { "-e", { .u = unary_e } }, { "-f", { .u = unary_f } }, { "-g", { .u = unary_g } }, { "-h", { .u = unary_h } }, { "-k", { .u = unary_k } }, { "-L", { .u = unary_h } }, { "-n", { .u = unary_n } }, { "-p", { .u = unary_p } }, { "-r", { .u = unary_r } }, { "-S", { .u = unary_S } }, { "-s", { .u = unary_s } }, { "-t", { .u = unary_t } }, { "-u", { .u = unary_u } }, { "-w", { .u = unary_w } }, { "-x", { .u = unary_x } }, { "-z", { .u = unary_z } }, { NULL }, }; static struct test binary[] = { { "=" , { .b = binary_se } }, { "!=" , { .b = binary_sn } }, { "-eq", { .b = binary_eq } }, { "-ne", { .b = binary_ne } }, { "-gt", { .b = binary_gt } }, { "-ge", { .b = binary_ge } }, { "-lt", { .b = binary_lt } }, { "-le", { .b = binary_le } }, { "-ef", { .b = binary_ef } }, { "-ot", { .b = binary_ot } }, { "-nt", { .b = binary_nt } }, { NULL }, }; static struct test * find_test(struct test *tests, char *name) { struct test *t; for (t = tests; t->name; t++) if (!strcmp(t->name, name)) return t; return NULL; } static int noarg(char *argv[]) { return 0; } static int onearg(char *argv[]) { return unary_n(argv[0]); } static int twoarg(char *argv[]) { struct test *t; if (!strcmp(argv[0], "!")) return !onearg(argv + 1); if ((t = find_test(unary, *argv))) return t->func.u(argv[1]); enprintf(2, "bad unary test %s\n", argv[0]); return 0; /* not reached */ } static int threearg(char *argv[]) { struct test *t = find_test(binary, argv[1]); if (t) return t->func.b(argv[0], argv[2]); if (!strcmp(argv[0], "!")) return !twoarg(argv + 1); enprintf(2, "bad binary test %s\n", argv[1]); return 0; /* not reached */ } static int fourarg(char *argv[]) { if (!strcmp(argv[0], "!")) return !threearg(argv + 1); enprintf(2, "too many arguments\n"); return 0; /* not reached */ } int main(int argc, char *argv[]) { int (*narg[])(char *[]) = { noarg, onearg, twoarg, threearg, fourarg }; size_t len; argv0 = *argv, argv0 ? (argc--, argv++) : (void *)0; len = argv0 ? strlen(argv0) : 0; if (len && argv0[--len] == '[' && (!len || argv0[--len] == '/') && strcmp(argv[--argc], "]")) enprintf(2, "no matching ]\n"); if (argc > 4) enprintf(2, "too many arguments\n"); return !narg[argc](argv); } <file_sep>/* See LICENSE file for copyright and license details. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "util.h" static int digitsleft(const char *d) { int shift; char *exp; if (*d == '+') d++; exp = strpbrk(d, "eE"); shift = exp ? estrtonum(exp + 1, INT_MIN, INT_MAX) : 0; return MAX(0, strspn(d, "-0123456789") + shift); } static int digitsright(const char *d) { int shift, after; char *exp; exp = strpbrk(d, "eE"); shift = exp ? estrtonum(&exp[1], INT_MIN, INT_MAX) : 0; after = (d = strchr(d, '.')) ? strspn(&d[1], "0123456789") : 0; return MAX(0, after - shift); } static int validfmt(const char *fmt) { int occur = 0; literal: while (*fmt) if (*fmt++ == '%') goto format; return occur == 1; format: if (*fmt == '%') { fmt++; goto literal; } fmt += strspn(fmt, "-+#0 '"); fmt += strspn(fmt, "0123456789"); if (*fmt == '.') { fmt++; fmt += strspn(fmt, "0123456789"); } if (*fmt == 'L') fmt++; switch (*fmt) { case 'f': case 'F': case 'g': case 'G': case 'e': case 'E': case 'a': case 'A': occur++; goto literal; default: return 0; } } static void usage(void) { eprintf("usage: %s [-f fmt] [-s sep] [-w] " "[startnum [step]] endnum\n", argv0); } int main(int argc, char *argv[]) { double start, step, end, out, dir; int wflag = 0, left, right; char *tmp, ftmp[BUFSIZ], *fmt = ftmp; const char *starts = "1", *steps = "1", *ends = "1", *sep = "\n"; ARGBEGIN { case 'f': if (!validfmt(tmp=EARGF(usage()))) eprintf("%s: invalid format\n", tmp); fmt = tmp; break; case 's': sep = EARGF(usage()); break; case 'w': wflag = 1; break; default: usage(); } ARGEND switch (argc) { case 3: steps = argv[1]; argv[1] = argv[2]; /* fallthrough */ case 2: starts = argv[0]; argv++; /* fallthrough */ case 1: ends = argv[0]; break; default: usage(); } start = estrtod(starts); step = estrtod(steps); end = estrtod(ends); dir = (step > 0) ? 1.0 : -1.0; if (step == 0 || start * dir > end * dir) return 1; if (fmt == ftmp) { right = MAX(digitsright(starts), MAX(digitsright(ends), digitsright(steps))); if (wflag) { left = MAX(digitsleft(starts), digitsleft(ends)); snprintf(ftmp, sizeof ftmp, "%%0%d.%df", right + left + (right != 0), right); } else snprintf(ftmp, sizeof ftmp, "%%.%df", right); } for (out = start; out * dir <= end * dir; out += step) { if (out != start) fputs(sep, stdout); printf(fmt, out); } putchar('\n'); return fshut(stdout, "<stdout>"); } <file_sep>/* See LICENSE file for copyright and license details. */ #include <sys/file.h> #include <sys/wait.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <unistd.h> #include "util.h" static void usage(void) { eprintf("usage: %s [-nosux] file cmd [arg ...]\n", argv0); } int main(int argc, char *argv[]) { int fd, status, savederrno, flags = LOCK_EX, nonblk = 0, oflag = 0; pid_t pid; ARGBEGIN { case 'n': nonblk = LOCK_NB; break; case 'o': oflag = 1; break; case 's': flags = LOCK_SH; break; case 'u': flags = LOCK_UN; break; case 'x': flags = LOCK_EX; break; default: usage(); } ARGEND if (argc < 2) usage(); if ((fd = open(*argv, O_RDONLY | O_CREAT, 0644)) < 0) eprintf("open %s:", *argv); if (flock(fd, flags | nonblk)) { if (nonblk && errno == EWOULDBLOCK) return 1; eprintf("flock:"); } switch ((pid = fork())) { case -1: eprintf("fork:"); case 0: if (oflag && close(fd) < 0) eprintf("close:"); argv++; execvp(*argv, argv); savederrno = errno; weprintf("execvp %s:", *argv); _exit(126 + (savederrno == ENOENT)); default: break; } if (waitpid(pid, &status, 0) < 0) eprintf("waitpid:"); if (close(fd) < 0) eprintf("close:"); if (WIFSIGNALED(status)) return 128 + WTERMSIG(status); if (WIFEXITED(status)) return WEXITSTATUS(status); return 0; } <file_sep>#if 0 mini_start mini_exit mini_writes #LDSCRIPT onlytext LDSCRIPT text_and_bss shrinkelf INCLUDESRC return #endif // misc 2020/06 // public domain void usage(){ writes("Usage: seq from/to [to]\n"); exit(-1); } int toint( const char c[] ){ int ret = 0; while ( *c > 47 && *c < 58 ){ ret *= 10; ret += (*c-48); *c++; } return(ret); } char* count(char *digit, char* first){ if ( digit < first ) first=digit; *digit = *digit+1; if ( *digit > '9' ){ *digit = '0'; first = count(digit-1,first); } return(first); } #define VOID "0000000000\n" static char* ZERO = VOID; // seems ok to assume int main(int argc, char *argv[]){ if (argc == 1) { usage(); } // A philosophical question. // However, it works, therefore it's true. char *p = ZERO + sizeof(VOID) - 3 ; char *last = p; int i=0; int to = toint( argv[1] ); if ( argc>2 ){ for ( ; i<to; i++ ) p=count(last,p); to = toint( argv[2] ); } for ( ; i<= to; i++ ){ write(STDOUT_FILENO, p, ZERO - 1 + sizeof(VOID) - p ); p=count(last,p); } return(0); } <file_sep>/* * Copyright 2005-2014 <NAME>, et al. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <string.h> #include "../util.h" char * strsep(char **str, const char *sep) { char *s = *str, *end; if (!s) return NULL; end = s + strcspn(s, sep); if (*end) *end++ = 0; else end = 0; *str = end; return s; } <file_sep>/* See LICENSE file for copyright and license details. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "text.h" #include "util.h" static int show = 0x07; static void printline(int pos, struct line *line) { int i; if (!(show & (0x1 << pos))) return; for (i = 0; i < pos; i++) { if (show & (0x1 << i)) putchar('\t'); } fwrite(line->data, 1, line->len, stdout); } static void usage(void) { eprintf("usage: %s [-123] file1 file2\n", argv0); } int main(int argc, char *argv[]) { FILE *fp[2]; static struct line line[2]; size_t linecap[2] = { 0, 0 }; ssize_t len; int ret = 0, i, diff = 0, seenline = 0; ARGBEGIN { case '1': case '2': case '3': show &= 0x07 ^ (1 << (ARGC() - '1')); break; default: usage(); } ARGEND if (argc != 2) usage(); for (i = 0; i < 2; i++) { if (!strcmp(argv[i], "-")) { argv[i] = "<stdin>"; fp[i] = stdin; } else if (!(fp[i] = fopen(argv[i], "r"))) { eprintf("fopen %s:", argv[i]); } } for (;;) { for (i = 0; i < 2; i++) { if (diff && i == (diff < 0)) continue; if ((len = getline(&(line[i].data), &linecap[i], fp[i])) > 0) { line[i].len = len; seenline = 1; continue; } if (ferror(fp[i])) eprintf("getline %s:", argv[i]); if ((diff || seenline) && line[!i].data[0]) printline(!i, &line[!i]); while ((len = getline(&(line[!i].data), &linecap[!i], fp[!i])) > 0) { line[!i].len = len; printline(!i, &line[!i]); } if (ferror(fp[!i])) eprintf("getline %s:", argv[!i]); goto end; } diff = linecmp(&line[0], &line[1]); LIMIT(diff, -1, 1); seenline = 0; printline((2 - diff) % 3, &line[MAX(0, diff)]); } end: ret |= fshut(fp[0], argv[0]); ret |= (fp[0] != fp[1]) && fshut(fp[1], argv[1]); ret |= fshut(stdout, "<stdout>"); return ret; } <file_sep>#if 0 #globals_on_stack mini_errno mini_start mini_printsl mini_prints mini_writes mini_getenv mini_environ mini_where mini_INCLUDESRC LDSCRIPT default SHRINKELF return #endif int main( int argc, char *argv[], char *envp[] ){ if ( argc < 2 ){ writes("usage: where executable executable .."); exit(1); } char buf[PATH_MAX]; int r = 1; while ( argc-->1 ){ if ( where(argv[argc],buf) ){ printsl(buf); r = 0; } else { prints( argv[argc], " not found\n" ); } } return(r); } <file_sep># suckless linux tools This is my fork of github.com/nee-san/sbase Working on a port to minilib, in order to get tiny and statical linked binaries. Seems quite useful, linked static with minilib on linux x64 "cat" now is 3K. same system, linked dynamic with gcc: 15K (18K) linked static with gcc: 747K dynamic with musl: 17K static with musl: 26K (or even 32K) ## Notes Although I don't see why, including the sources directly (instead of building the whole libutil) seems to produce slightly bigger binaries. ATM, something bloats true.c and false.c. 205Bytes for the binaries.(??) compared with 151 Bytes I got with "hello world", there are somehow 54 Bytes to much. 67 Bytes, if you count the string "hello world!". Annoying. Dunno. Have to sort this out. **I DONT LIKE BLOATWARE!!!** ;) But porting the single binaries one after another is sort of a soothing puzzle to me, so I'll go with including. Need to put ifndefs into the sources. Michael (misc) Myer, <EMAIL>, 2019 <file_sep>/* public domain sha1 implementation based on rfc3174 and libtomcrypt */ #include <stdint.h> #include <string.h> #include "../sha1.h" static uint32_t rol(uint32_t n, int k) { return (n << k) | (n >> (32-k)); } #define F0(b,c,d) (d ^ (b & (c ^ d))) #define F1(b,c,d) (b ^ c ^ d) #define F2(b,c,d) ((b & c) | (d & (b | c))) #define F3(b,c,d) (b ^ c ^ d) #define G0(a,b,c,d,e,i) e += rol(a,5)+F0(b,c,d)+W[i]+0x5A827999; b = rol(b,30) #define G1(a,b,c,d,e,i) e += rol(a,5)+F1(b,c,d)+W[i]+0x6ED9EBA1; b = rol(b,30) #define G2(a,b,c,d,e,i) e += rol(a,5)+F2(b,c,d)+W[i]+0x8F1BBCDC; b = rol(b,30) #define G3(a,b,c,d,e,i) e += rol(a,5)+F3(b,c,d)+W[i]+0xCA62C1D6; b = rol(b,30) static void processblock(struct sha1 *s, const uint8_t *buf) { uint32_t W[80], a, b, c, d, e; int i; for (i = 0; i < 16; i++) { W[i] = (uint32_t)buf[4*i]<<24; W[i] |= (uint32_t)buf[4*i+1]<<16; W[i] |= (uint32_t)buf[4*i+2]<<8; W[i] |= buf[4*i+3]; } for (; i < 80; i++) W[i] = rol(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1); a = s->h[0]; b = s->h[1]; c = s->h[2]; d = s->h[3]; e = s->h[4]; for (i = 0; i < 20; ) { G0(a,b,c,d,e,i++); G0(e,a,b,c,d,i++); G0(d,e,a,b,c,i++); G0(c,d,e,a,b,i++); G0(b,c,d,e,a,i++); } while (i < 40) { G1(a,b,c,d,e,i++); G1(e,a,b,c,d,i++); G1(d,e,a,b,c,i++); G1(c,d,e,a,b,i++); G1(b,c,d,e,a,i++); } while (i < 60) { G2(a,b,c,d,e,i++); G2(e,a,b,c,d,i++); G2(d,e,a,b,c,i++); G2(c,d,e,a,b,i++); G2(b,c,d,e,a,i++); } while (i < 80) { G3(a,b,c,d,e,i++); G3(e,a,b,c,d,i++); G3(d,e,a,b,c,i++); G3(c,d,e,a,b,i++); G3(b,c,d,e,a,i++); } s->h[0] += a; s->h[1] += b; s->h[2] += c; s->h[3] += d; s->h[4] += e; } static void pad(struct sha1 *s) { unsigned r = s->len % 64; s->buf[r++] = 0x80; if (r > 56) { memset(s->buf + r, 0, 64 - r); r = 0; processblock(s, s->buf); } memset(s->buf + r, 0, 56 - r); s->len *= 8; s->buf[56] = s->len >> 56; s->buf[57] = s->len >> 48; s->buf[58] = s->len >> 40; s->buf[59] = s->len >> 32; s->buf[60] = s->len >> 24; s->buf[61] = s->len >> 16; s->buf[62] = s->len >> 8; s->buf[63] = s->len; processblock(s, s->buf); } void sha1_init(void *ctx) { struct sha1 *s = ctx; s->len = 0; s->h[0] = 0x67452301; s->h[1] = 0xEFCDAB89; s->h[2] = 0x98BADCFE; s->h[3] = 0x10325476; s->h[4] = 0xC3D2E1F0; } void sha1_sum(void *ctx, uint8_t md[SHA1_DIGEST_LENGTH]) { struct sha1 *s = ctx; int i; pad(s); for (i = 0; i < 5; i++) { md[4*i] = s->h[i] >> 24; md[4*i+1] = s->h[i] >> 16; md[4*i+2] = s->h[i] >> 8; md[4*i+3] = s->h[i]; } } void sha1_update(void *ctx, const void *m, unsigned long len) { struct sha1 *s = ctx; const uint8_t *p = m; unsigned r = s->len % 64; s->len += len; if (r) { if (len < 64 - r) { memcpy(s->buf + r, p, len); return; } memcpy(s->buf + r, p, 64 - r); len -= 64 - r; p += 64 - r; processblock(s, s->buf); } for (; len >= 64; len -= 64, p += 64) processblock(s, p); memcpy(s->buf, p, len); } <file_sep>#if 0 mini_start mini_kill mini_writes mini_perror mini_errno mini_prints mini_putc mini_strcmp #mini_buf 256 #mini_printf #mini_itodec #mini_dtodec LDSCRIPT text_and_bss shrinkelf INCLUDESRC return #endif #define SIGMAX 31 const char* sig[]={ "", "HUP","INT","QUIT","ILL","TRAP", "ABRT","BUS","FPE","KILL","USR1","SEGV","USR2", "PIPE","ALRM","TERM","STKFLT","CHLD","CONT", "STOP","TSTP","TTIN","TTOU","URG","XCPU","XFSZ", "VTALRM","PROF","WINCH","POLL","PWR","SYS"}; int toint(const char *c){ int ret = 0; while ( *c > 47 && *c < 58 ){ ret *= 10; ret += (*c-48); *c++; } return(ret); } void usage(){ writes("Usage: kill [-l] [-SIGNAL/-signalnum] [PID1] [PID2] ...\n"); exit(1); } void print_names(){ for ( int a = 1; a<32; a++ ){ prints( sig[a] ); putc(' ',stdout); } putc('\n',stdout); exit(0); } int nokill(int p, int s){ //printf("nokill: %d, %d\n",p,s); return(0); } int cmp(const char *p, const char *p2 ){ int *l = (int*)p; int *l2 = (int*)p2; if ((*l) == (*l2)) return(0); return(1); } int to_number( const char *p ){ for ( int ret = 1; ret <= SIGMAX; ret ++ ){ if ( cmp( p, sig[ret]) == 0 ) return(ret); } writes("Unknown Signal: "); prints(p); putc('\n',stdout); exit(1); return(0); } int main(int argc, char *argv[]) { int signum=SIGTERM; pid_t pid; if (argc == 1) { usage(); } #define AV argv[0] for ( *argv++; *argv && argv[0][0]=='-'; *argv++ ){ if ( AV[1] == 'h' ) usage(); if ( AV[1] == 'l' ) print_names(); if ( AV[1] >= '0' && AV[1] <= '9' ) signum = toint( (AV +1 ) ); int tmp =1; if ( AV[1] == 'S' && AV[2] == 'I' && AV[3] == 'G' ) tmp = 4; if ( AV[tmp] >= 'A' && AV[tmp] <= 'X' ){ signum = to_number( AV+tmp ); } } int ret = 0; while (*argv){ pid = toint(*argv); if (kill(pid, signum)) { perror("kill: "); ret = 1; } *argv++; } return ret; } <file_sep>#if 0 mini_start mini_ewrites mini_writes mini_eprints mini_exit_errno mini_syscalls mini_strcpy INCLUDESRC SHRINKELF #LDSCRIPT text_and_bss return #endif // sudo to drop privileges to nobody // has to be installed with suid bit. // the intention is to be able for users // to drop privileges and, e.g., // write with the dropped privileges // to temporary files in /tmp. // // There is a known flaw, when // an attacker knows, there is going to be written to /tmp // he can make a link to another file, which will be overwritten // then with the rights of the user writing to this file. // this however relays on having an account nobody, // which doesn't have any privileges in turn. #define uid_nobody 65534 #define gid_nobody 65534 void usage(){ writes("usage: nbdo [-h] command [arguments]\n" "Exec command with id and gid of nobody\n" ); exit(1); } int main(int argc, char **argv, char **envp ){ gid_t group = gid_nobody; if (argc < 2 || (argv[1][0]=='-' && argv[1][1] == 'h' ) ){ usage(); } int ret; #define IFFAIL(a,str) if ( (ret=a) ){ewrites(str); goto failed;} IFFAIL(sys_setgroups(1,&group),"setgroups()"); IFFAIL(setgid(gid_nobody),"setgid()"); IFFAIL(setuid(uid_nobody),"setuid()"); for ( char *c = *argv++; c<(*envp-1); c++ ){ if ( !*c ) *c = ' '; } char* arg[] = { "sh", "-c", *argv }; ret = execve("/bin/sh", arg, envp ); ewrites("Executing /bin/sh"); failed: ewrites(" failed\n"); exit_errno(ret); } <file_sep>#if 0 mini_start mini_fprintf mini_itodec mini_perror mini_errno mini_strchr mini_malloc mini_free mini_open mini_creat mini_strcmp COMPILE raise close lseek read mini_buf 192 INCLUDESRC SHRINKELF LDSCRIPT textandbss return #endif #define BUF_SIZE 4096 /* * Copyright (c) 2014 by <NAME> * Permission is granted to use, distribute, or modify this source, * provided that this copyright notice remains intact. * * The "dd" built-in command. */ //#include "sash.h" #define PAR_NONE 0 #define PAR_IF 1 #define PAR_OF 2 #define PAR_BS 3 #define PAR_COUNT 4 #define PAR_SEEK 5 #define PAR_SKIP 6 typedef struct { const char * name; int value; } PARAM; static const PARAM params[] = { {"if", PAR_IF}, {"of", PAR_OF}, {"bs", PAR_BS}, {"count", PAR_COUNT}, {"seek", PAR_SEEK}, {"skip", PAR_SKIP}, {NULL, PAR_NONE} }; static long getNum(const char * cp); int main(int argc, const char ** argv) { const char * str; const PARAM * par; const char * inFile; const char * outFile; char * cp; int inFd; int outFd; int inCc; int outCc; int blockSize; long count; long seekVal; long skipVal; long inFull; long inPartial; long outFull; long outPartial; char * buf; char localBuf[BUF_SIZE]; int r; inFile = NULL; outFile = NULL; seekVal = 0; skipVal = 0; blockSize = 512; count = -1; r = 0; while (--argc > 0) { str = *++argv; cp = strchr(str, '='); if (cp == NULL) { fprintf(stderr, "Bad dd argument\n"); return 1; } *cp++ = '\0'; for (par = params; par->name; par++) { if (strcmp(str, par->name) == 0) break; } switch (par->value) { case PAR_IF: if (inFile) { fprintf(stderr, "Multiple input files illegal\n"); return 1; } inFile = cp; break; case PAR_OF: if (outFile) { fprintf(stderr, "Multiple output files illegal\n"); return 1; } outFile = cp; break; case PAR_BS: blockSize = getNum(cp); if (blockSize <= 0) { fprintf(stderr, "Bad block size value\n"); return 1; } break; case PAR_COUNT: count = getNum(cp); if (count < 0) { fprintf(stderr, "Bad count value\n"); return 1; } break; case PAR_SEEK: seekVal = getNum(cp); if (seekVal < 0) { fprintf(stderr, "Bad seek value\n"); return 1; } break; case PAR_SKIP: skipVal = getNum(cp); if (skipVal < 0) { fprintf(stderr, "Bad skip value\n"); return 1; } break; default: fprintf(stderr, "Unknown dd parameter\n"); return 1; } } buf = localBuf; if (blockSize > sizeof(localBuf)) { buf = malloc(blockSize); if (buf == NULL) { fprintf(stderr, "Cannot allocate buffer\n"); return 1; } } inFull = 0; inPartial = 0; outFull = 0; outPartial = 0; if (inFile == NULL){ inFd=STDIN_FILENO; } else { inFd = open(inFile, 0); } if (inFd < 0) { perror(inFile); if (buf != localBuf) free(buf); return 1; } if (outFile == NULL){ outFd=STDOUT_FILENO; } else { outFd = creat(outFile, 0666); } if (outFd < 0) { perror(outFile); close(inFd); if (buf != localBuf) free(buf); return 1; } if (skipVal) { if (lseek(inFd, skipVal * blockSize, 0) < 0) { while (skipVal-- > 0) { inCc = read(inFd, buf, blockSize); if (inCc < 0) { perror(inFile); r = 1; goto cleanup; } if (inCc == 0) { fprintf(stderr, "End of file while skipping\n"); r = 1; goto cleanup; } } } } if (seekVal) { if (lseek(outFd, seekVal * blockSize, 0) < 0) { perror(outFile); r = 1; goto cleanup; } } inCc = 0; while (((count < 0) || (inFull + inPartial < count)) && (inCc = read(inFd, buf, blockSize)) > 0) { if (inCc < blockSize) inPartial++; else inFull++; cp = buf; // todo: sigint handler (misc) //if (intFlag) //{ // fprintf(stderr, "Interrupted\n"); // r = 1; // goto cleanup; //} while (inCc > 0) { outCc = write(outFd, cp, inCc); if (outCc < 0) { perror(outFile); r = 1; goto cleanup; } if (outCc < blockSize) outPartial++; else outFull++; cp += outCc; inCc -= outCc; } } if (inCc < 0) perror(inFile); cleanup: close(inFd); if (close(outFd) < 0) { perror(outFile); r = 1; } if (buf != localBuf) free(buf); printf("%ld+%ld records in\n", inFull, inPartial); printf("%ld+%ld records out\n", outFull, outPartial); return r; } int isDecimal(char c){ return( (c>='0') && (c<='9') ); } /* * Read a number with a possible multiplier. * Returns -1 if the number format is illegal. */ static long getNum(const char * cp) { long value; if (!isDecimal(*cp)) return -1; value = 0; while (isDecimal(*cp)) value = value * 10 + *cp++ - '0'; switch (*cp++) { case 'k': value *= 1024; break; case 'b': value *= 512; break; case 'w': value *= 2; break; case '\0': return value; default: return -1; } if (*cp) return -1; return value; } /* END CODE */ <file_sep>/* See LICENSE file for copyright and license details. */ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "../utf.h" int fgetrune(Rune *r, FILE *fp) { char buf[UTFmax]; int i = 0, c; while (i < UTFmax && (c = fgetc(fp)) != EOF) { buf[i++] = c; if (charntorune(r, buf, i) > 0) break; } if (ferror(fp)) return -1; return i; } int efgetrune(Rune *r, FILE *fp, const char *file) { int ret; if ((ret = fgetrune(r, fp)) < 0) { fprintf(stderr, "fgetrune %s: %s\n", file, strerror(errno)); exit(1); } return ret; } <file_sep>/* See LICENSE file for copyright and license details. */ #include <fcntl.h> #include <signal.h> #include <unistd.h> #include "util.h" static void usage(void) { eprintf("usage: %s [-ai] [file ...]\n", argv0); } int main(int argc, char *argv[]) { int *fds = NULL; size_t i, nfds; ssize_t n; int ret = 0, aflag = O_TRUNC, iflag = 0; char buf[BUFSIZ]; ARGBEGIN { case 'a': aflag = O_APPEND; break; case 'i': iflag = 1; break; default: usage(); } ARGEND if (iflag && signal(SIGINT, SIG_IGN) == SIG_ERR) eprintf("signal:"); nfds = argc + 1; fds = ecalloc(nfds, sizeof(*fds)); for (i = 0; i < argc; i++) { if ((fds[i] = open(argv[i], O_WRONLY|O_CREAT|aflag, 0666)) < 0) { weprintf("open %s:", argv[i]); ret = 1; } } fds[i] = 1; while ((n = read(0, buf, sizeof(buf))) > 0) { for (i = 0; i < nfds; i++) { if (fds[i] >= 0 && writeall(fds[i], buf, n) < 0) { weprintf("write %s:", (i != argc) ? argv[i] : "<stdout>"); fds[i] = -1; ret = 1; } } } if (n < 0) eprintf("read <stdin>:"); return ret; } <file_sep>AWK = awk UNICODE = http://unicode.org/Public/UCD/latest/ucd/UnicodeData.txt default: @echo Downloading and parsing $(UNICODE) @curl -\# $(UNICODE) | $(AWK) -f mkrunetype.awk <file_sep>/* See LICENSE file for copyright and license details. */ #include <limits.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "text.h" #include "utf.h" #include "util.h" static size_t startnum = 1; static size_t incr = 1; static size_t blines = 1; static size_t delimlen = 2; static size_t seplen = 1; static int width = 6; static int pflag = 0; static char type[] = { 'n', 't', 'n' }; /* footer, body, header */ static char *delim = "\\:"; static char format[6] = "%*ld"; static char *sep = "\t"; static regex_t preg[3]; static int getsection(struct line *l, int *section) { size_t i; int sectionchanged = 0, newsection = *section; for (i = 0; (l->len - i) >= delimlen && !memcmp(l->data + i, delim, delimlen); i += delimlen) { if (!sectionchanged) { sectionchanged = 1; newsection = 0; } else { newsection = (newsection + 1) % 3; } } if (!(l->len - i) || l->data[i] == '\n') *section = newsection; else sectionchanged = 0; return sectionchanged; } static void nl(const char *fname, FILE *fp) { static struct line line; static size_t size; size_t number = startnum, bl = 1; ssize_t len; int donumber, oldsection, section = 1; while ((len = getline(&line.data, &size, fp)) > 0) { line.len = len; donumber = 0; oldsection = section; if (getsection(&line, &section)) { if ((section >= oldsection) && !pflag) number = startnum; continue; } switch (type[section]) { case 't': if (line.data[0] != '\n') donumber = 1; break; case 'p': if (!regexec(preg + section, line.data, 0, NULL, 0)) donumber = 1; break; case 'a': if (line.data[0] == '\n' && bl < blines) { ++bl; } else { donumber = 1; bl = 1; } } if (donumber) { printf(format, width, number); fwrite(sep, 1, seplen, stdout); number += incr; } fwrite(line.data, 1, line.len, stdout); } free(line.data); if (ferror(fp)) eprintf("getline %s:", fname); } static void usage(void) { eprintf("usage: %s [-p] [-b type] [-d delim] [-f type]\n" " [-h type] [-i num] [-l num] [-n format]\n" " [-s sep] [-v num] [-w num] [file]\n", argv0); } static char getlinetype(char *type, regex_t *preg) { if (type[0] == 'p') eregcomp(preg, type + 1, REG_NOSUB); else if (!type[0] || !strchr("ant", type[0])) usage(); return type[0]; } int main(int argc, char *argv[]) { FILE *fp = NULL; size_t s; int ret = 0; char *d, *formattype, *formatblit; ARGBEGIN { case 'd': switch (utflen((d = EARGF(usage())))) { case 0: eprintf("empty logical page delimiter\n"); case 1: s = strlen(d); delim = emalloc(s + 1 + 1); estrlcpy(delim, d, s + 1 + 1); estrlcat(delim, ":", s + 1 + 1); delimlen = s + 1; break; default: delim = d; delimlen = strlen(delim); break; } break; case 'f': type[0] = getlinetype(EARGF(usage()), preg); break; case 'b': type[1] = getlinetype(EARGF(usage()), preg + 1); break; case 'h': type[2] = getlinetype(EARGF(usage()), preg + 2); break; case 'i': incr = estrtonum(EARGF(usage()), 0, MIN(LLONG_MAX, SIZE_MAX)); break; case 'l': blines = estrtonum(EARGF(usage()), 0, MIN(LLONG_MAX, SIZE_MAX)); break; case 'n': formattype = EARGF(usage()); estrlcpy(format, "%", sizeof(format)); if (!strcmp(formattype, "ln")) { formatblit = "-"; } else if (!strcmp(formattype, "rn")) { formatblit = ""; } else if (!strcmp(formattype, "rz")) { formatblit = "0"; } else { eprintf("%s: bad format\n", formattype); } estrlcat(format, formatblit, sizeof(format)); estrlcat(format, "*ld", sizeof(format)); break; case 'p': pflag = 1; break; case 's': sep = EARGF(usage()); seplen = unescape(sep); break; case 'v': startnum = estrtonum(EARGF(usage()), 0, MIN(LLONG_MAX, SIZE_MAX)); break; case 'w': width = estrtonum(EARGF(usage()), 1, INT_MAX); break; default: usage(); } ARGEND if (argc > 1) usage(); if (!argc) { nl("<stdin>", stdin); } else { if (!strcmp(argv[0], "-")) { argv[0] = "<stdin>"; fp = stdin; } else if (!(fp = fopen(argv[0], "r"))) { eprintf("fopen %s:", argv[0]); } nl(argv[0], fp); } ret |= fp && fp != stdin && fshut(fp, argv[0]); ret |= fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>"); return ret; } <file_sep>#if 0 COMPILE start eprintsl getuid printsl writes writesl ewrites uitodec getgrnam \ getgrgid printfs eprintfs prints printf itodec COMPILE getpwuid pwent getusergroups getpwnam INCLUDESRC SHRINKELF #STRIPFLAG " " LDSCRIPT onlytext globals_on_stack MINIBUF 512 #FULLDEBUG return #endif #define id_OPTIONS enum { g, G, n,r,u,h } #define OPT(func,opts,option) ({ func##_OPTIONS; opts & (1<<option); }) #define SETOPT(func,opts,option) ({ func##_OPTIONS; opts = (opts | ( 1 << option )); }) void usage(){ writesl("id [user]"); exit(0); } void printud(uint id){ char buf[16]; uitodec( buf, id, 0,0,0 ); prints(buf); //exit(0); } int id_main( FILE* out, FILE* err, int opts, const char* user[] ){ return(0); } int main(int argc, char *argv[]){ const char* options = "gGnruh"; int opts = 0; for ( *argv++; *argv && argv[0][0]=='-'; *argv++ ){ for ( char *opt = *argv+1; *opt; opt++ ){ //printfs( "arg: %c\n", *opt ); int a = 1; for ( const char *c = options; *c != *opt; *c++ ){ if ( !*c ){ eprintfs( "Unknown option: %c\n", *opt ); exit(1); } a <<= 1; } opts |= a; } } if ( OPT(id,opts,h) ) usage(); struct passwd* pw; if ( !*argv ){ int uid; if ( OPT(id,opts,r) ){ writes("real\n"); uid = getuid(); } else { uid = geteuid(); } pw = getpwuid( uid ); } else { pw = getpwnam( *argv ); } if ( !pw ){ ewrites("Unable to read user entry\n"); exit(1); } int _groups[128]; int *groups = _groups; int ng = getusergroups( pw->pw_name, 128, groups ); if ( ng == -1 ){ ewrites("\nUnable to read group file\n"); exit(2); } if ( OPT(id,opts,g) ){ printf("%d\n",pw->pw_gid); exit(0); } if ( OPT(id,opts,u) ){ printf("%d\n",pw->pw_uid); exit(0); } struct group *gr = getgrgid( pw->pw_gid ); const char* fmt = "%s%d(%s)"; const char* pref = " groups="; const char* preflist= ","; if ( OPT(id,opts,n) ){ fmt="%!%!%s "; } if ( OPT(id,opts,G) ){ fmt=" %!%d"; printf("%d", pw->pw_uid); } else { printf(fmt, "uid=", pw->pw_uid, pw->pw_name ); printf(fmt, "gid=", pw->pw_gid, gr ? gr->gr_name : "?" ); //pw->pw_gid, gr ? gr->gr_name : "?" ); } while ( ng-->0 ){ gr = getgrgid( *groups ); //if ( gr && ( gr->gr_gid != pw->pw_gid )){ printf( fmt, pref, gr ? gr->gr_gid : 0, gr ? gr->gr_name : "?" ); pref=preflist; //} groups++; } writes("\n"); exit(0); } <file_sep>/* See LICENSE file for copyright and license details. */ #define mini_start #include "minilib.h" //#include "minilib/minilib.c" int main(void) { return 0; } <file_sep>#if 0 mini_start mini_writes mini_atoi mini_putchar mini_umask LDSCRIPT text_and_bss shrinkelf INCLUDESRC return #endif // misc 2020/06 // BSD license void usage(){ writes("umask \n"); exit(0); } int main(int argc, char *argv[]){ if (argc != 2) { usage(); } int i = atoi(argv[1]); char c; c = i/0100 + '0'; putchar(c); i = umask(0); //umask(i); }
d23a19bec16ab49c5abf13b78b1fe51508f7b47b
[ "Markdown", "C", "Makefile" ]
155
Markdown
michael105/minicore
111db675280b3148fa4e542da59ab5b8cfcffc7b
367d67a829459beef75c3236304443ca87588421
refs/heads/master
<file_sep>let t1 = gsap.timeline({defaults:{duration: 0.7, ease: Back.easeOut.config(2), opacity: 0}}) let t2 = gsap.timeline({defaults:{duration: 1.5, delay:1}}) let t3 = gsap.timeline({defaults:{duration: 1.5}}) t1.from('.card-bg', {delay: 1, scale: 0.2, transformOrigin: 'center' }, "=.2s") .from('.card-top', { scaleY: 0, transformOrigin: 'top' } ) .from('.card-icon', { scale: 0.2, transformOrigin: 'center' }, "-=.7" ) .from('.line1', { scaleY: 0, transformOrigin: 'bottom' }) .from('.graph1',{scaleX:0, transformOrigin:"left"} ) .from('.graph2', {scaleY:0, transformOrigin:'bottom'}) .from('.line2', { scaleY: 0, transformOrigin: 'bottom' }, "-=.2" ) .from('.line3', { scaleY: 0, transformOrigin: 'bottom' }, "-=.3" ) .from('.line4', { scaleY: 0, transformOrigin: 'bottom' }, "-=.4" ) .from('.line5', { scaleY: 0, transformOrigin: 'bottom' }, "-=.5" ) .from('.line6', { scaleY: 0, transformOrigin: 'bottom' }, "-=.6" ) .from('.line7', { scaleY: 0, transformOrigin: 'bottom' }, "-=.7" ) .from('.line8', { scaleY: 0, transformOrigin: 'bottom' }, "-=.8" ) .from('.blip1', { scaleX: 0, transformOrigin:'left'}) .from('.blip2', { scaleX: 0, transformOrigin:'left'}, '-=0.2') .from('.blip3', { scaleX: 0, transformOrigin:'left'}, '-=0.3') .from('.blip4', { scaleX: 0, transformOrigin:'left'}, '-=0.4') t2.from(".whole-card", {y:10, repeat: -1, yoyo:true}) t3.from(".details", {opacity:0,y: 40, stagger:0.3}) const navSlide = () => { const burger = document.querySelector(".ham"); const nav = document.querySelector(".nav-items"); const navItem = document.querySelectorAll(".nav-item"); burger.addEventListener('click', () => { nav.classList.toggle("nav-active"); burger.classList.toggle('toggle'); navItem.forEach((link, index) => { if(link.style.animation){ link.style.animation = ''; } else { link.style.animation = `navLinkFade 0.5s ease forwards ${index / 7 + 0.5}s`; } }) }) } navSlide(); let counter = 1; const rateSlide = document.querySelector('.rate-slide'); const rateItems = document.querySelectorAll('.rates'); //counter const size = rateItems[0].clientHeight; //console.log(size); rateSlide.style.transform = 'translateY(' + (-size * counter) +'px)'; //console.log(rateSlide.style.transform); setInterval(function(){ counter++; // console.log("interval",counter); rateSlide.style.transition = 'transform 0.3s ease-in-out'; rateSlide.style.transform = 'translateY(' + (-size * counter) +'px)'; if(rateItems[counter].id === 'firstClone'){ rateSlide.style.transition = 'none'; counter = 1; //console.log("slide",counter); rateSlide.style.transform = 'translateY(' + (-size * counter) +'px)'; } //console.log(rateSlide.style.transform); },2000); gsap.registerPlugin(ScrollTrigger); gsap.from(".image", { scrollTrigger: { trigger:'.image', start:"top center", }, x:-500, opacity: 0, duration:1.5 }) gsap.from(".media-details", { scrollTrigger: { trigger:'.image', start:"top center", }, x:500, opacity: 0, duration:1.5 }); gsap.from(".buy-section", { scrollTrigger: { trigger:'.buy-section', start:"top center", }, y:-200, opacity: 0, duration:1.5 }); gsap.from(".main", { scrollTrigger: { trigger:'.main', start:"top center", }, y:-200, opacity: 0, duration:1.5 });
8aa68b6cb3179804ebc188b2f67538453f1cd580
[ "JavaScript" ]
1
JavaScript
DHIRAJ540/cyberbyte
608f97e5c2b3c4b43b2e7932d2cdace357f1a682
7ac70f4d6d9f122fc0a63588d2953a682ea8cac7
refs/heads/master
<file_sep>import java.sql.*; import javax.swing.*; public class DeleteData { @SuppressWarnings("deprecation") public static void StudentDelete() { Connection conn = null; try { Class.forName ("com.mysql.jdbc.Driver").newInstance(); String userName = "root"; String password = "<PASSWORD>"; String url = "jdbc:mysql://localhost:3306/studentmanagementsystem"; conn = DriverManager.getConnection (url, userName, password); System.out.println ("\nDatabase Connection Established..."); String mysql = "DELETE FROM studentdatabase WHERE Student_FullName = ?"; PreparedStatement pat = conn.prepareStatement(mysql); String FullName = JOptionPane.showInputDialog("Please enter the Student Full Name that you wish to delete."); pat.setString(1, FullName); int DataDeleted = pat.executeUpdate(); if (DataDeleted > 0) { System.out.println("Data deleted."); } pat.close(); } catch(Exception e) { e.printStackTrace(); } } } <file_sep>import java.sql.*; import javax.swing.*; public class LecturerRegistration { @SuppressWarnings("deprecation") public static void LectRegister () { System.out.println("***** MySQL JDBC Connection Testing *****"); Connection conn = null; try { Class.forName ("com.mysql.jdbc.Driver").newInstance(); String userName = "root"; String password = "<PASSWORD>"; String url = "jdbc:mysql://localhost:3306/studentmanagementsystem"; conn = DriverManager.getConnection (url, userName, password); System.out.println ("\nDatabase Connection Established..."); } catch (Exception ex) { System.err.println ("Cannot connect to database server"); ex.printStackTrace(); } finally { if (conn != null) { try { String mysql = "INSERT INTO admindatabase(Lecturer_UserName, Lecturer_FullName, Lecturer_StaffID, Lecturer_Password, Lecturer_PhoneNumber, Lecturer_EmailAddress, Lecturer_City, Lecturer_Country, Lecturer_Description) values(?,?,?,?,?,?,?,?,?)"; String Lecturer_UserName = JOptionPane.showInputDialog("Please enter your username." + "\nThis username will be use for the login."); String Lecturer_FullName = JOptionPane.showInputDialog("Please enter your Full Name."); String Lecturer_StaffID = JOptionPane.showInputDialog("Please enter your Staff ID."); String Lecturer_Password = JOptionPane.showInputDialog("Please enter your Password."); String Lecturer_PhoneNumber = JOptionPane.showInputDialog("Please enter your Phone Number."); String Lecturer_EmailAddress = JOptionPane.showInputDialog("Please enter your Email Address."); String Lecturer_City = JOptionPane.showInputDialog("Please enter the current city that you live."); String Lecturer_Country = JOptionPane.showInputDialog("Please enter the current country that you live."); String Lecturer_Description = JOptionPane.showInputDialog("Describe yourself."); PreparedStatement pst = conn.prepareStatement(mysql); pst.setString(1, Lecturer_UserName); pst.setString(2, Lecturer_FullName); pst.setString(3, Lecturer_StaffID); pst.setString(4, Lecturer_Password); pst.setString(5, Lecturer_PhoneNumber); pst.setString(6, Lecturer_EmailAddress); pst.setString(7, Lecturer_City); pst.setString(8, Lecturer_Country); pst.setString(9, Lecturer_Description); int i = pst.executeUpdate(); if(i != 0) { System.out.println("All data has been added."); } else { System.out.println("Failed to add those data."); } } catch (Exception ex) { System.out.println ("Error in connection termination!"); } } } } } <file_sep>import java.sql.*; import javax.swing.JOptionPane; public class LecturerBaseUpdate { @SuppressWarnings("deprecation") public static void LecturerDataUpdate () { Connection conn = null; try { Class.forName ("com.mysql.jdbc.Driver").newInstance(); String userName = "root"; String password = "<PASSWORD>"; String url = "jdbc:mysql://localhost:3306/studentmanagementsystem"; conn = DriverManager.getConnection (url, userName, password); System.out.println ("\nDatabase Connection Established..."); String mysql = "UPDATE AdminDatabase SET Lecturer_FullName = ?, Lecturer_Password = ?, Lecturer_PhoneNumber = ?, Lecturer_EmailAddress = ?, Lecturer_City = ?, Lecturer_Country = ?, Lecturer_Description = ? WHERE Lecturer_UserName = ? "; String Lecturer_UserName = JOptionPane.showInputDialog("Please enter your UserName"); String FullName = JOptionPane.showInputDialog("Please enter your Full Name."); String Password = JOptionPane.showInputDialog("Please enter your New Password."); String PhoneNumber = JOptionPane.showInputDialog("Please enter your New Phone Number."); String EmailAddress = JOptionPane.showInputDialog("Please enter your New Email Address."); String City = JOptionPane.showInputDialog("Please enter your current City you living."); String Country = JOptionPane.showInputDialog("Please enter your current Country you living."); String Description = JOptionPane.showInputDialog("Please enter your New Description."); PreparedStatement pat = conn.prepareStatement(mysql); pat.setString(1, FullName); pat.setString(2, Password); pat.setString(3, PhoneNumber); pat.setString(4, EmailAddress); pat.setString(5, City); pat.setString(6, Country); pat.setString(7, Description); pat.setString(8, Lecturer_UserName); int DataUpdated = pat.executeUpdate(); if (DataUpdated > 0) { System.out.println("Data Updated!"); } else { System.out.println("Data is not updated!"); } pat.close(); } catch(Exception e) { e.printStackTrace(); } } }<file_sep>import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import javax.swing.JOptionPane; public class ParentBaseUpdate { @SuppressWarnings("deprecation") public static void ParentDataUpdate () { Connection conn = null; try { Class.forName ("com.mysql.jdbc.Driver").newInstance(); String userName = "root"; String password = "<PASSWORD>"; String url = "jdbc:mysql://localhost:3306/studentmanagementsystem"; conn = DriverManager.getConnection (url, userName, password); System.out.println ("\nDatabase Connection Established..."); String mysql = "UPDATE parentdatabase SET Parent_FullName = ?, Parent_Password = ?, Parent_PhoneNumber = ?, Parent_EmailAddress = ?" + "WHERE Parent_Fullname = ? "; String FullName = JOptionPane.showInputDialog("Please enter your Full Name."); String Password = JOptionPane.showInputDialog("Please enter your New Password."); String PhoneNumber = JOptionPane.showInputDialog("Please enter your New Phone Number."); String EmailAddress = JOptionPane.showInputDialog("Please enter your New Email Address."); PreparedStatement pat = conn.prepareStatement(mysql); pat.setString(1, FullName); pat.setString(2, Password); pat.setString(3, PhoneNumber); pat.setString(4, EmailAddress); pat.setString(5, FullName); int DataUpdated = pat.executeUpdate(); if (DataUpdated > 0) { System.out.println("Data Updated!"); } pat.close(); } catch(Exception e) { e.printStackTrace(); } } } <file_sep>import java.sql.*; import javax.swing.JOptionPane; public class StudentBaseUpdate { @SuppressWarnings("deprecation") public static void StudentDataUpdate () { Connection conn = null; try { Class.forName ("com.mysql.jdbc.Driver").newInstance(); String userName = "root"; String password = "<PASSWORD>"; String url = "jdbc:mysql://localhost:3306/studentmanagementsystem"; conn = DriverManager.getConnection (url, userName, password); System.out.println ("\nDatabase Connection Established..."); String mysql = "UPDATE studentdatabase SET Student_FullName = ?, Student_Password = ?, Student_PhoneNumber = ?, Student_EmailAddress = ?, Student_City = ?, Student_Country = ?, Student_Description = ? " + "WHERE Student_Fullname = ? "; String FullName = JOptionPane.showInputDialog("Please enter your Full Name."); String Password = JOptionPane.showInputDialog("Please enter your New Password."); String PhoneNumber = JOptionPane.showInputDialog("Please enter your New Phone Number."); String EmailAddress = JOptionPane.showInputDialog("Please enter your New Email Address."); String City = JOptionPane.showInputDialog("Please enter your current City you living."); String Country = JOptionPane.showInputDialog("Please enter your current Country you living."); String Description = JOptionPane.showInputDialog("Please enter your New Description."); PreparedStatement pat = conn.prepareStatement(mysql); pat.setString(1, FullName); pat.setString(2, Password); pat.setString(3, PhoneNumber); pat.setString(4, EmailAddress); pat.setString(5, City); pat.setString(6, Country); pat.setString(7, Description); pat.setString(8, FullName); int DataUpdated = pat.executeUpdate(); if (DataUpdated > 0) { System.out.println("Data Updated!"); } pat.close(); } catch(Exception e) { e.printStackTrace(); } } }<file_sep>import javax.swing.*; import java.awt.event.*; public class ManagementLogin implements ActionListener { private enum Actions { STUDENTLOGIN, LECTURERLOGIN, PARENTLOGIN, EXIT, ADMINLOGIN } public static void main(String [] args) { ManagementLogin instance = new ManagementLogin(); // Create frame JFrame frame = new JFrame("UMS Student Management System"); frame.setTitle("UMS STUDENT MANAGEMENT SYSTEM"); // Set the JFrame Name frame.setSize(400, 200); // Set the JFrame Size frame.setLocationRelativeTo(null); // Set the JFrame to the center of the screen frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Terminate the OPERATION // Create Student_Login button JButton Student_Login = new JButton ("STUDENT LOGIN"); Student_Login.setActionCommand(Actions.STUDENTLOGIN.name()); Student_Login.addActionListener(instance); // Create Lecturer_Login button JButton Lecturer_Login = new JButton ("LECTURER LOGIN"); Lecturer_Login.setActionCommand(Actions.LECTURERLOGIN.name()); Lecturer_Login.addActionListener(instance); // Create Parent Login Button JButton Parent_Login = new JButton ("PARENT LOGIN"); Parent_Login.setActionCommand(Actions.PARENTLOGIN.name()); Parent_Login.addActionListener(instance); // Create Exit Button JButton Exit = new JButton ("EXIT PROGRAM"); Exit.setActionCommand(Actions.EXIT.name()); Exit.addActionListener(instance); // Create Admin Login Button JButton Admin_Login = new JButton ("ADMIN LOGIN"); Admin_Login.setActionCommand(Actions.EXIT.name()); Admin_Login.addActionListener(instance); // Create Panel JPanel panel = new JPanel(); // Add button into panel panel.add(Student_Login); panel.add(Lecturer_Login); panel.add(Parent_Login); panel.add(Admin_Login); panel.add(Exit); // Add panel into frame frame.add(panel); frame.setVisible(true); } public void actionPerformed(ActionEvent evt) { if (evt.getActionCommand() == Actions.STUDENTLOGIN.name()) { } else if (evt.getActionCommand() == Actions.LECTURERLOGIN.name()) { LecturerLogin.LecturerLog(); } else if (evt.getActionCommand() == Actions.PARENTLOGIN.name()) { } else if (evt.getActionCommand() == Actions.EXIT.name()) { } else if (evt.getActionCommand() == Actions.ADMINLOGIN.name()) { LecturerRegistration.LectRegister(); } } }
c2f0912600a6008908b686c1a2cd6445c606e3b2
[ "Java" ]
6
Java
Leexy99/GGWP
ff44d60c69cb4efde42a1be3a695f37cec91a931
65af4564c5cec9feff894b0e1da6e458ba944bad
refs/heads/master
<repo_name>timdmulligan/govs_ball_schedule<file_sep>/govs_ball/ui.R #ui.R library(DT) library(shiny) library(plotly) library(shinythemes) library(rsconnect) # deployApp("govs_ball_schedule/govs_ball/", appName = "govs_ball") shinyUI(fluidPage( theme = shinytheme("flatly"), navbarPage( "Summer Music Festivals", #position = 'fixed-top', #collapsible = TRUE, tabPanel("Gov's Ball", sidebarLayout( sidebarPanel( h2("Use ", strong("data"), "to make sure your festival experiance", em("rocks")), p("With dozens of bands to choose from, picking a lineup to see can be a stressful experiance. This app leverages data crawled from Pitchfork and Spotify to help you prepare."), p(""), selectInput( "festival_filter", "Select a Festival:", choices = list("All Festivals", "Governor's Ball", "Bonnaroo", "Lollapalooza") ), selectInput( "group_filter", "Group Chart Markers By:", choices = list("Genre", "Day", "Festival", "Stage") ), selectInput( "genre_filter", "Genre", choices = list("All", "Metal", "Rap", "Rock/Indie", "Pop/R&B", "Electronic") ), checkboxInput("critical_check", label = "Include Non-Reviewed Artists", value = F), downloadButton('downloadData', 'Download') ), mainPanel( plotlyOutput("myChart"), dataTableOutput(outputId = "table") ) )) ) )) <file_sep>/govs_ball/server.R library(shiny) library("RSQLite") library(plotly) library(stringi) # CCSP data ### BEGIN SHINY APP ### shinyServer(function(input, output, session) { #Read in Gov's Ball Data fest_data<-reactive({ con = dbConnect(SQLite(), dbname="pitchfork-data.db") gbe <- dbGetQuery(con, "SELECT artist, popularity, followers, pf_mean AS critical, genre, day, festival, stage, time FROM fest_data_enriched") if (input$critical_check != T){ gbe <- gbe[!(is.na(gbe$critical)),] } else { gbe[is.na(gbe$critical),]$critical<- mean(gbe$critical, na.rm = T) } if (input$genre_filter != "All"){ gbe <- gbe[gbe$genre == input$genre_filter,] } if (input$festival_filter != "All Festivals"){ gbe <- gbe[gbe$festival == input$festival_filter,] } gbe }) output$myChart <- renderPlotly({ data <- fest_data() #browser() if (input$group_filter == "Genre"){ groupby = data$genre } else if (input$group_filter == "Festival"){ groupby = data$festival } else if (input$group_filter == "Stage"){ groupby = data$stage } else if (input$group_filter == "Time"){ groupby = data$time } else { groupby = data$day } p <- plot_ly(x = data$critical, y = log(data$followers), color = groupby, mode = "markers", text = data$artist, marker = list(size = 10) ) p <- layout(p, yaxis = list(title = 'Followers on Spotify (Log)'), xaxis = list(title = 'Critical Score'), paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)' ) }) output$table <- renderDataTable({ data <- fest_data() data }, options = list(pageLength = 10), selection = "single") })<file_sep>/pitchfork_correlation.R library("RSQLite") library(plotly) library(Hmisc) Sys.setenv("plotly_username"="USERNAME") Sys.setenv("plotly_api_key"="API KEY") setwd("~/govs_ball_schedule/") con = dbConnect(SQLite(), dbname="pitchfork-data.db") gbe <- dbGetQuery(con, "SELECT * FROM correlation_table WHERE popularity != 0 AND score != 0 ") rcorr(gbe$log_followers, gbe$score, type="pearson") rcorr(gbe$followers, gbe$score, type="pearson") rcorr(gbe$popularity, gbe$score, type="pearson") t <- list( family = "overpass", size = 14) a <- list( list( y = gbe[gbe$artist %in% c("THE BEATLES"),]$score, x = gbe[gbe$artist %in% c("THE BEATLES"),]$popularity, text = c( "THE BEATLES"), xref = "x", yref = "y", showarrow = TRUE, arrowhead =6, ax = 0, ay = -40 ), list( y = gbe[gbe$artist %in% c("DRAKE"),]$score, x = gbe[gbe$artist %in% c("DRAKE"),]$popularity, text = c( "DRAKE"), xref = "x", yref = "y", showarrow = TRUE, arrowhead =6, ax = 20, ay = -30 ), list( y = gbe[gbe$artist %in% c("THE CHAINSMOKERS"),]$score, x = gbe[gbe$artist %in% c("THE CHAINSMOKERS"),]$popularity, text = c( "THE CHAINSMOKERS"), xref = "x", yref = "y", showarrow = TRUE, arrowhead =6, ax = 20, ay = 35 ), list( y = gbe[gbe$artist %in% c("CHANCE THE RAPPER"),]$score, x = gbe[gbe$artist %in% c("CHANCE THE RAPPER"),]$popularity, text = c( "CHANCE THE RAPPER"), xref = "x", yref = "y", showarrow = TRUE, arrowhead =6, ax = 80, ay = -25 ) ) p <- plot_ly(y = gbe$score, x = gbe$popularity, text = gbe$artist, mode = "markers", marker = list(size = 2, color = 'rgba(255, 182, 193, .9)', line = list(color = 'rgba(152, 0, 0, .8)', width = 1.5))) p <- layout(p, xaxis = list(title = 'Followers on Spotify <br> (Log)'), yaxis = list(title = 'Mean Review Score'), paper_bgcolor='rgba(241,241,241,241)', plot_bgcolor='rgba(241,241,241,241)', title = "Pitchfork.com reviews aren't<br> influenced by popularity <br> (n = 6,910, r = -0.02)", margin = list(t = 120, l = 80, r = 80, b = 80), font = t, annotations = a ) plotly_POST(p, filename = "pitchfork") p #Popularity Vs. Followers p <- plot_ly(x = gbe$popularity, y = gbe$log_followers, mode = "markers", text = gbe$artist, marker = list(size = 2, color = 'rgba(255, 182, 193, .9)', line = list(color = 'rgba(152, 0, 0, .8)', width = 1.5))) p <- layout(p, yaxis = list(title = 'Followers on Spotify (Log)'), xaxis = list(title = 'Popularity Score'), paper_bgcolor='rgba(241,241,241,241)', plot_bgcolor='rgba(241,241,241,241)', title = "Understanding the 'Popularity' Metric", margin = list(t = 120, l = 80, r = 80, b = 80), font = t ) p # Followers Hist p <- plot_ly(x = gbe$followers, type = "histogram", mode = "markers", marker = list(size = 2, color = 'rgba(255, 182, 193, .9)', line = list(color = 'rgba(152, 0, 0, .8)', width = 1.5))) p <- layout(p, yaxis = list(title = 'Count'), xaxis = list(title = 'Followers'), paper_bgcolor='rgba(241,241,241,241)', plot_bgcolor='rgba(241,241,241,241)', title = "Followers Distribution", margin = list(t = 120, l = 80, r = 80, b = 80), font = t ) p # Followers log Hist p <- plot_ly(x = gbe$log_followers, type = "histogram", mode = "markers", marker = list(size = 2, color = 'rgba(255, 182, 193, .9)', line = list(color = 'rgba(152, 0, 0, .8)', width = 1.5))) p <- layout(p, yaxis = list(title = 'Count'), xaxis = list(title = 'Log Followers'), paper_bgcolor='rgba(241,241,241,241)', plot_bgcolor='rgba(241,241,241,241)', title = "Log Followers Distribution", margin = list(t = 120, l = 80, r = 80, b = 80), font = t ) p dbGetQuery(con, "SELECT avg(score) FROM correlation_table ") <file_sep>/README.md # Governer's Ball Scheduling Trying to create the optimum Governor's Ball 2017 schedules using Pitchfork Reviews. Crawler inspired by @nsgrantham. <file_sep>/train.py from comet_ml import Experiment from sklearn.preprocessing import LabelEncoder import pandas as pd import numpy as np from keras.utils import np_utils import pickle y_tr = pickle.load(open('y_tr.pkl', 'rb')) X_train = pickle.load(open('X_train.pkl', 'rb')) y_train = np.array(pd.get_dummies(y_tr)) max_words = 10000 from keras.models import Sequential from keras.layers import Dense, Dropout, Activation experiment = Experiment(api_key="<KEY>") model = Sequential() model.add(Dense(512, kernel_initializer='glorot_normal', input_shape=(max_words,), activation='relu')) model.add(Dropout(0.5)) model.add(Dense(256, kernel_initializer='glorot_normal', activation='sigmoid')) model.add(Dropout(0.5)) model.add(Dense(len(y_train[0]), kernel_initializer='glorot_normal', activation='softmax')) # Compile model model.compile(loss='categorical_crossentropy', optimizer='Nadam', metrics=['accuracy']) model.fit(X_train, y_train, batch_size=32, epochs=10, verbose=0, validation_split=0.3, shuffle=True)
2ed0fdb3aca3e4ae191c42e5b125fdd65672dbbd
[ "Markdown", "Python", "R" ]
5
R
timdmulligan/govs_ball_schedule
3999e2b34d2d71f98cff8cae237eb059dc8acaa2
eca367962387096f2a1f51b32e3f423cfda58aa1
refs/heads/master
<file_sep>rootProject.name = 'cubemediaserver' <file_sep>package com.github.tgiachi.cubemediaserver.controllers; import com.github.tgiachi.cubemediaserver.annotations.MediaParser; import com.github.tgiachi.cubemediaserver.entities.ConfigEntity; import com.github.tgiachi.cubemediaserver.entities.DirectoryEntryEntity; import com.github.tgiachi.cubemediaserver.entities.MediaFileTypeEnum; import com.github.tgiachi.cubemediaserver.repositories.ConfigRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("api/config") public class ConfigController { @Autowired public ConfigRepository configRepository; @RequestMapping(value = "/watched/directories", method = RequestMethod.GET) public List<DirectoryEntryEntity> getWatchedDirectoies() { ConfigEntity config = configRepository.findAll().get(0); return config.getDirectories(); } @RequestMapping(value = "/add/directory", method = RequestMethod.POST) public boolean addDirectoryToWatch(@RequestParam("name") String name, @RequestParam("directory") String directory, @RequestParam("mediaType") MediaFileTypeEnum mediaType) { ConfigEntity config = configRepository.findAll().get(0); long exists = config.getDirectories().stream().filter(s -> s.getDirectory().equals(directory)).count(); if (exists == 0) { DirectoryEntryEntity entryEntity = new DirectoryEntryEntity(); entryEntity.setDirectory(directory); entryEntity.setMediaType(mediaType); entryEntity.setName(name); config.getDirectories().add(entryEntity); configRepository.save(config); return true; } else { return false; } } } <file_sep>package com.github.tgiachi.cubemediaserver.data.events.media; import com.github.tgiachi.cubemediaserver.entities.DirectoryEntryEntity; import com.github.tgiachi.cubemediaserver.entities.MediaFileTypeEnum; import lombok.Data; @Data public class InputMediaFileEvent { DirectoryEntryEntity directoryEntry; String filename; String fullPathFileName; MediaFileTypeEnum mediaType; } <file_sep>buildscript { ext { springBootVersion = '2.0.1.RELEASE' } repositories { maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' } mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' apply plugin: 'io.spring.dependency-management' group = 'com.github.tgiachi' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.9 repositories { mavenCentral() jcenter() maven { url "https://repo.spring.io/milestone" } } dependencies { compile('org.springframework.boot:spring-boot-starter-data-mongodb') compile('org.springframework.boot:spring-boot-starter-quartz') compile('org.springframework.boot:spring-boot-starter-web') compile('org.springframework.boot:spring-boot-starter-websocket') compile('org.springframework.shell:spring-shell-starter:2.0.0.RELEASE') compile("io.springfox:springfox-swagger2:${swaggerVersion}") compile("io.springfox:springfox-swagger-ui:${swaggerVersion}") compile group: 'commons-io', name: 'commons-io', version: '2.6' compile('javax.xml.bind:jaxb-api:2.2.8') compile('info.movito:themoviedbapi:1.7') compile("net.bramp.ffmpeg:ffmpeg:0.6.2") compile 'com.github.wtekiela:opensub4j:0.2.0-SNAPSHOT' compile group: 'javax.xml.ws', name: 'jaxws-api', version: '2.3.0' compileOnly('org.projectlombok:lombok') testCompile('org.springframework.boot:spring-boot-starter-test') } <file_sep>package com.github.tgiachi.cubemediaserver.data.media; import com.github.tgiachi.cubemediaserver.entities.MediaFileTypeEnum; import lombok.Data; @Data public class ParsedMediaObject { boolean isParsed; boolean isSavedOnDb; String mediaId; String filename; MediaFileTypeEnum mediaType; } <file_sep>package com.github.tgiachi.cubemediaserver.data.events.ffmpeg; import lombok.Data; @Data public class FFMpegBuildingEvent { double percentage; String filename; double fps; double speed; } <file_sep>package com.github.tgiachi.cubemediaserver.services; import com.github.tgiachi.cubemediaserver.data.events.ffmpeg.FFMpegBuildingEvent; import com.github.tgiachi.cubemediaserver.data.events.ffmpeg.MediaInfoEvent; import com.github.tgiachi.cubemediaserver.entities.ConfigEntity; import com.github.tgiachi.cubemediaserver.interfaces.services.IFFMpegService; import com.github.tgiachi.cubemediaserver.repositories.ConfigRepository; import com.github.tgiachi.cubemediaserver.utils.CompressionUtils; import com.github.tgiachi.cubemediaserver.utils.HttpUtils; import net.bramp.ffmpeg.FFmpeg; import net.bramp.ffmpeg.FFmpegExecutor; import net.bramp.ffmpeg.FFprobe; import net.bramp.ffmpeg.builder.FFmpegBuilder; import net.bramp.ffmpeg.probe.FFmpegProbeResult; import net.bramp.ffmpeg.probe.FFmpegStream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.SystemUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.function.Function; @Component public class FFMpegService implements IFFMpegService { private static Logger mLogger = LoggerFactory.getLogger(FFMpegService.class); private String mFfmpegDirectory; private String mRootDirectory; @Autowired public ConfigRepository configRepository; @PostConstruct public void init() { boolean isFfmpegFound = false; mLogger.info("Check if FFMpeg is installed"); if (!isFFMpegInstalled()) { if (System.getenv("ffmpeg") != null) { mFfmpegDirectory = System.getenv("ffmpeg"); mLogger.info("Found FFMpeg in env variabile = {}", mFfmpegDirectory); isFfmpegFound = true; } else { checkDirectoryRoot(); } if (!isFfmpegFound) { downloadFFMpeg(); } } else { mLogger.info("FFMPEG Installed"); } //SystemUtils.IS_OS_WINDOWS } private void checkDirectoryRoot() { String userDirectory = System.getProperty("user.dir"); mRootDirectory = userDirectory + File.separator + "cube" + File.separator; mFfmpegDirectory = mRootDirectory + "ffmpeg" + File.separator; if (!new File(mRootDirectory).exists()) { mLogger.info("Creating directory {}", mRootDirectory); new File(mRootDirectory).mkdirs(); } if (!new File(mFfmpegDirectory).exists()) { mLogger.info("Creating directory {}", mFfmpegDirectory); new File(mFfmpegDirectory).mkdirs(); } } private void downloadFFMpeg() { String downloadUrl = "https://ffmpeg.zeranoe.com/builds/%s/static/ffmpeg-3.4.2-%s-static.zip"; String outFilename = System.getProperty("java.io.tmpdir") + "ffmpeg-3.4.2-%s-static.zip"; if (SystemUtils.IS_OS_WINDOWS) { downloadUrl = String.format(downloadUrl, "win64", "win64"); outFilename = String.format(outFilename, "win64"); } if (SystemUtils.IS_OS_MAC_OSX) { downloadUrl = String.format(downloadUrl, "macos64", "macos64"); outFilename = String.format(outFilename, "macos64"); } mLogger.info("Downloading {}...", outFilename); try { HttpUtils.downloadFile(downloadUrl, outFilename); mLogger.info("Download completed!"); boolean result = CompressionUtils.unzipFile(outFilename, mFfmpegDirectory); Collection<File> files = FileUtils.listFiles(new File(mFfmpegDirectory), null, true); files.forEach(file -> { if (file.toString().contains("bin")) { String ffMpeg = Paths.get(file.toString()).getParent().toString(); mLogger.info("FFMpeg root directory -> {}", ffMpeg); saveFFMpegDirectory(ffMpeg); return; } }); } catch (Exception ex) { mLogger.error("Error during download file {} => {}", outFilename, ex); } } private void saveFFMpegDirectory(String directory) { ConfigEntity entity = configRepository.findAll().get(0); entity.setFfmpegBinDirectory(directory); configRepository.save(entity); } private String getFFMpegPath() { ConfigEntity entity = configRepository.findAll().get(0); return entity.getFfmpegBinDirectory() + File.separator; } private boolean isFFMpegInstalled() { ConfigEntity entity = configRepository.findAll().get(0); return entity.getFfmpegBinDirectory() != null || entity.getFfmpegBinDirectory() != ""; } private FFmpeg getFFMpegInstance() { String ext = ""; if (SystemUtils.IS_OS_WINDOWS) ext = ".exe"; try { return new FFmpeg(getFFMpegPath() + "ffmpeg" + ext); } catch (Exception ex) { return null; } } private FFprobe getFFprobeInstance() { String ext = ""; if (SystemUtils.IS_OS_WINDOWS) ext = ".exe"; try { return new FFprobe(getFFMpegPath() + "ffprobe" + ext); } catch (Exception ex) { return null; } } @Override public MediaInfoEvent getMediaInformation(String filename) { try { MediaInfoEvent mediaInfoEvent = new MediaInfoEvent(); FFmpegProbeResult probeResult = getFFprobeInstance().probe(filename); FFmpegStream stream = probeResult.getStreams().get(0); mediaInfoEvent.setCodec(stream.codec_name); mediaInfoEvent.setFilename(filename); mediaInfoEvent.setDuration(probeResult.getFormat().duration); mediaInfoEvent.setWidth(stream.width); mediaInfoEvent.setHeight(stream.height); return mediaInfoEvent; } catch (Exception ex) { } return null; } @Override public void getMediaInformationAsync(String filename, Function<MediaInfoEvent, Void> callback) { Executors.newCachedThreadPool().submit(() -> { MediaInfoEvent event = getMediaInformation(filename); callback.apply(event); }); } private FFmpegExecutor getFFMpegExecutor() { FFmpegExecutor executor = new FFmpegExecutor(getFFMpegInstance(), getFFprobeInstance()); return executor; } private void executeFFMpegBuilder(FFmpegBuilder builder, String filename) { try { FFmpegProbeResult in = getFFprobeInstance().probe(filename); final double duration_ns = in.getFormat().duration * TimeUnit.SECONDS.toNanos(1); getFFMpegExecutor().createJob(builder, progress -> { double percentage = progress.out_time_ns / duration_ns; FFMpegBuildingEvent ffMpegBuildingEvent = new FFMpegBuildingEvent(); ffMpegBuildingEvent.setFilename(filename); ffMpegBuildingEvent.setFps(progress.fps.doubleValue()); ffMpegBuildingEvent.setSpeed(progress.speed); ffMpegBuildingEvent.setPercentage(percentage); }); } catch (Exception ex) { } } } <file_sep>package com.github.tgiachi.cubemediaserver.interfaces.plugins; /** * Interface for create plugin */ public interface ICubePlugin { } <file_sep>package com.github.tgiachi.cubemediaserver.data.events.media; import com.github.tgiachi.cubemediaserver.data.media.ParsedMediaObject; import lombok.Data; @Data public class MediaAddedEvent { String mediaId; ParsedMediaObject output; } <file_sep>/* * This file was generated by the Gradle 'init' task. * * This is a general purpose Gradle build. * Learn how to create Gradle builds at https://guides.gradle.org/creating-new-gradle-builds/ */ apply plugin: 'java' repositories { mavenCentral() } dependencies { testCompile 'junit:junit:4.11' } project.ext { springVersion = '2.0.5.RELEASE' reflectionsVersion = '0.9.11' lombokVersion = '1.16.20' swaggerVersion = '2.8.0' } project(':cubemediaserver') { apply plugin: 'java' dependencies { compile project(':cubeapi') } } allprojects() { apply plugin: 'java' repositories { mavenCentral() } dependencies { compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25' } }<file_sep>spring.data.rest.base-path=/api moviedb.apikey=<KEY><file_sep>package com.github.tgiachi.cubemediaserver.interfaces.mediaparser; import com.github.tgiachi.cubemediaserver.data.events.media.InputMediaFileEvent; import com.github.tgiachi.cubemediaserver.data.media.ParsedMediaObject; import java.util.concurrent.Future; /** * Interface for create media parsers */ public interface IMediaParser { /** * Scan file * @param inputMediaFileEvent * @return */ Future<ParsedMediaObject> Parse(InputMediaFileEvent inputMediaFileEvent); } <file_sep>package com.github.tgiachi.cubemediaserver.utils; import net.lingala.zip4j.core.ZipFile; import net.lingala.zip4j.exception.ZipException; import java.util.ArrayList; import java.util.List; public class CompressionUtils { public static boolean unzipFile(String filename, String outDirectory) { List<String> outDirectoryZip = new ArrayList<>(); try { try { ZipFile zipFile = new ZipFile(filename); zipFile.extractAll(outDirectory); } catch (ZipException e) { e.printStackTrace(); } } catch (Exception ex) { return false; } return true; } } <file_sep>package com.github.tgiachi.cubemediaserver.controllers; import com.github.tgiachi.cubemediaserver.entities.ConfigEntity; import com.github.tgiachi.cubemediaserver.repositories.ConfigRepository; import com.github.tgiachi.cubemediaserver.services.MediaParserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @Autowired public MediaParserService mediaParserService; @Autowired public ConfigRepository configRepository; @RequestMapping(value = "/test",method = RequestMethod.GET) public String testGet() { return "ok"; } @RequestMapping(value = "/scan", method = RequestMethod.GET) public String testDirectories() { ConfigEntity cfg = configRepository.findAll().get(0); mediaParserService.fullScanDirectory(cfg.getDirectories().get(0)); return "ok"; } } <file_sep>package com.github.tgiachi.cubemediaserver.interfaces.services; public interface IEventListenerService { void publishEvent(Object event); } <file_sep>package com.github.tgiachi.cubemediaserver.services; import com.github.tgiachi.cubemediaserver.annotations.MediaParser; import com.github.tgiachi.cubemediaserver.data.QueueTaskObject; import com.github.tgiachi.cubemediaserver.data.events.media.InputMediaFileEvent; import com.github.tgiachi.cubemediaserver.data.events.media.MediaAddedEvent; import com.github.tgiachi.cubemediaserver.data.media.ParsedMediaObject; import com.github.tgiachi.cubemediaserver.entities.ConfigEntity; import com.github.tgiachi.cubemediaserver.entities.DirectoryEntryEntity; import com.github.tgiachi.cubemediaserver.interfaces.mediaparser.IMediaParser; import com.github.tgiachi.cubemediaserver.interfaces.services.IMediaParserService; import com.github.tgiachi.cubemediaserver.interfaces.services.IQueueExecutorService; import com.github.tgiachi.cubemediaserver.repositories.ConfigRepository; import com.github.tgiachi.cubemediaserver.utils.EventBusUtils; import com.github.tgiachi.cubemediaserver.utils.ReflectionUtils; import com.google.common.eventbus.Subscribe; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; import org.springframework.web.context.support.GenericWebApplicationContext; import javax.annotation.PostConstruct; import java.io.File; import java.nio.file.*; import java.util.*; import java.util.concurrent.Future; @Component public class MediaParserService implements IMediaParserService { private final Logger mLogger = LoggerFactory.getLogger(MediaParserService.class); @Autowired public IQueueExecutorService mQueueExecutorService; @Autowired public ApplicationContext mApplicationContext; @Autowired public ConfigRepository mConfigRepository; @Autowired public EventListenerService eventListenerService; private Thread mWatchThread; private WatchService mWatchService; private ConfigEntity configEntity; private boolean isWatchServiceEnabled = true; private Map<WatchKey, DirectoryEntryEntity> mWatchMap = new HashMap<>(); private HashMap<String, List<Class<?>>> mMediaParsers; public MediaParserService() { mMediaParsers = new HashMap<>(); } @PostConstruct public void init() { subscribeEvents(); scanMediaParsers(); loadConfig(); initFileWatchers(); } private void subscribeEvents() { EventBusUtils.getSingleton().register(this); } private void loadConfig() { if (mConfigRepository.findAll().size() == 0) { mLogger.warn("Config is empty, creating default"); Locale locale = Locale.getDefault(); configEntity = new ConfigEntity(); configEntity.setLanguage(locale.getLanguage()); configEntity.getSubtitlesLanguages().add(locale.getLanguage()); mConfigRepository.save(configEntity); } else { configEntity = mConfigRepository.findAll().get(0); } } private Runnable getWatchRunnable() { return () -> { WatchKey key; try { while ((key = mWatchService.take()) != null || isWatchServiceEnabled) { for (WatchEvent<?> event : key.pollEvents()) { DirectoryEntryEntity directoryEntryEntity = mWatchMap.get(key); InputMediaFileEvent inputEvent = new InputMediaFileEvent(); inputEvent.setDirectoryEntry(directoryEntryEntity); inputEvent.setMediaType(directoryEntryEntity.getMediaType()); inputEvent.setFilename(event.context().toString()); inputEvent.setFullPathFileName(String.format("%s%s%s", directoryEntryEntity.getDirectory(), File.separator, inputEvent.getFilename())); broadcastInputEvent(inputEvent); } key.reset(); } } catch (Exception ex) { } }; } private void broadcastInputEvent(InputMediaFileEvent inputMediaFileEvent) { EventBusUtils.getSingleton().broadcast(inputMediaFileEvent); } private void initFileWatchers() { try { mWatchService = FileSystems.getDefault().newWatchService(); } catch (Exception ex) { mLogger.error("Error during getting watch service: {}", ex.getMessage()); } for (DirectoryEntryEntity directoryEntryEntity : configEntity.getDirectories()) { mLogger.info("Registering hook for directory: {} ({})", directoryEntryEntity.getDirectory(), directoryEntryEntity.getMediaType()); Path path = Paths.get(directoryEntryEntity.getDirectory()); try { mWatchMap.put(path.register(mWatchService, StandardWatchEventKinds.ENTRY_CREATE), directoryEntryEntity); } catch (Exception ex) { mLogger.error("Error during watch directory {} => {}", directoryEntryEntity.getDirectory(), ex.getMessage()); } } mWatchThread = new Thread(getWatchRunnable()); mWatchThread.start(); } private void scanMediaParsers() { mLogger.info("Scanning for MediaParsers"); Set<Class<?>> types = ReflectionUtils.getAnnotation(MediaParser.class); mLogger.info("Found {} media parsers", types.size()); types.stream().forEach(this::initParser); } private void initParser(Class<?> classz) { try { if (IMediaParser.class.isAssignableFrom(classz)) { MediaParser ann = classz.getAnnotation(MediaParser.class); for (String ext : ann.extensions()) { if (!mMediaParsers.containsKey(ext)) mMediaParsers.put(ext, new ArrayList<>()); mMediaParsers.get(ext).add(classz); } mLogger.info("Registering class {} for extensions {}", classz.getSimpleName(), Arrays.toString(ann.extensions())); registerBean(classz); } else { mLogger.warn("Class {} don't implements interface IMediaParser", classz.getName()); } } catch (Exception ex) { mLogger.error("Error during init parser: {} => {}", classz.getName(), ex.getMessage()); } } private void parseFile(InputMediaFileEvent inputMediaFileEvent) { try { mLogger.info("New file input: {} ({})", inputMediaFileEvent.getFullPathFileName(), inputMediaFileEvent.getMediaType()); String ext = FilenameUtils.getExtension(inputMediaFileEvent.getFilename()); if (mMediaParsers.containsKey(ext)) { List<Class<?>> parsers = mMediaParsers.get(ext); mLogger.info("Found {} media parsers for extension {}", parsers.size(), ext); for (Class<?> parser : parsers) { try { mQueueExecutorService.enqueueTask(new QueueTaskObject().Build(this.getClass(), () -> { try { IMediaParser mediaParser = (IMediaParser) mApplicationContext.getBean(parser); Future<ParsedMediaObject> fOut = mediaParser.Parse(inputMediaFileEvent); ParsedMediaObject parsedMediaObject = fOut.get(); if (parsedMediaObject != null) { MediaAddedEvent mediaAddedEvent = new MediaAddedEvent(); mediaAddedEvent.setMediaId(parsedMediaObject.getMediaId()); mediaAddedEvent.setOutput(parsedMediaObject); eventListenerService.publishEvent(mediaAddedEvent); EventBusUtils.getSingleton().broadcast(mediaAddedEvent); } } catch (Exception ex) { } })); } catch (Exception ex) { ex.printStackTrace(); } } } } catch (Exception ex) { } } public void fullScanDirectory(DirectoryEntryEntity directoryEntryEntity) { Collection<File> files = FileUtils.listFiles(new File(directoryEntryEntity.getDirectory()), null, true); files.forEach(file -> { InputMediaFileEvent event = new InputMediaFileEvent(); event.setDirectoryEntry(directoryEntryEntity); event.setFilename(FilenameUtils.getName(file.getName())); event.setMediaType(directoryEntryEntity.getMediaType()); event.setFullPathFileName(file.getName()); broadcastInputEvent(event); }); } private void registerBean(Class<?> classz) { ((GenericWebApplicationContext) mApplicationContext).registerBean(classz); } @Subscribe public void onInputMediaFile(InputMediaFileEvent event) { mQueueExecutorService.enqueueTask(new QueueTaskObject().Build(this.getClass(), () -> { parseFile(event); })); } } <file_sep>package com.github.tgiachi.cubemediaserver.data; import lombok.Data; @Data public class QueueTaskObject { Class<?> sender; Runnable runnable; public QueueTaskObject Build(Class<?> sender, Runnable runnable) { this.sender = sender; this.runnable = runnable; return this; } } <file_sep>package com.github.tgiachi.cubemediaserver; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import java.util.Properties; @SpringBootApplication public class CubemediaserverApplication { public static void main(String[] args) { SpringApplication app = new SpringApplication(CubemediaserverApplication.class); app.run(args); } } <file_sep>package com.github.tgiachi.cubemediaserver.repositories; import com.github.tgiachi.cubemediaserver.entities.MovieEntity; import org.springframework.data.mongodb.repository.MongoRepository; public interface MoviesRepository extends MongoRepository<MovieEntity, String> { MovieEntity findByTitle(String title); }
68a6dbee6b508e2e2dab2f934ac4059c513c13ae
[ "Java", "INI", "Gradle" ]
19
Gradle
tgiachi/Cube
67061e71347917c992b4555c8278de359836541d
36a465f8d9d825f6daa9a0fe3261830f81f9b855
refs/heads/master
<repo_name>prasadns14/cityWaterFlow<file_sep>/cityWaterFlow.py #!/usr/bin/python import sys, getopt from collections import OrderedDict class Node: def init(self, name, parent, cost): self.name = name self.parent = parent self.cost = cost self.color = "white" def update(self, parent, cost): self.parent = parent self.cost = cost + parent.cost class GraphInfo: def init(self, sourceNode, destNode, pathGraph, nodes, time): self.sourceNode = sourceNode self.destNode = destNode self.pathGraph = pathGraph self.nodes = nodes self.time = time def BFS(self, time): queue = [] queue.append(self.nodes[self.sourceNode[0]]) self.nodes[self.sourceNode[0]].cost = time while queue: parent = queue[0] parentName = parent.name del queue[0] if parentName in self.destNode: return(parentName + " " + str(parent.cost % 24)) break children = [] for child in self.pathGraph[parent.name]: if self.nodes[child].color != "black" and self.nodes[child].color != "grey": children.append(child) children.sort() while children: child = children[0] del children[0] self.nodes[child].update(parent, 1) self.nodes[child].color = "grey" queue.append(self.nodes[child]) parent.color = "black" return("None") def UpdateNodes(self, queue, parent): #sort for faster exec for key, value in queue.items() : if key.parent == parent: key.update(parent, pathGraph[parent][key][0] ) value = self.nodes[key].cost def UCS(self, time): queue = {} self.nodes[self.sourceNode[0]].cost = time queue[self.nodes[self.sourceNode[0]]] = time costQueue = OrderedDict(sorted(queue.items(), key = lambda t: (t[1],t[0]))) while queue: items = list(costQueue.items()) items.reverse() costQueue = OrderedDict(items) parentNode = costQueue.popitem() parent = parentNode[0] parentName = parentNode[0].name parentCost = parentNode[0].cost del queue[parent] if parentName in self.destNode: return(parentName + " " + str(parentCost % 24)) break children = [] for child in self.pathGraph[parentName]: if self.nodes[child].color == "grey": if parentCost + self.pathGraph[parentName][child][0] <= self.nodes[child].cost: if (parentCost % 24) not in self.pathGraph[parentName][child][1]: self.nodes[child].update(parent, self.pathGraph[parentName][child][0]) queue[self.nodes[child]] = self.nodes[child].cost self.UpdateNodes(queue, child) elif self.nodes[child].color == "white": children.append(child) for child in children: if (parentCost % 24) not in self.pathGraph[parentName][child][1]: self.nodes[child].update(parent, self.pathGraph[parentName][child][0]) queue[self.nodes[child]] = self.nodes[child].cost self.nodes[child].color = "grey" costQueue = OrderedDict(sorted(queue.items(), key = lambda t: (t[1],t[0].name))) parent.color = "black" return("None") def DFS(self, time): queue = [] self.nodes[self.sourceNode[0]].cost = time queue.append(self.nodes[self.sourceNode[0]]) while queue: parent = queue.pop() if parent.color == "black": while parent.color != "black": parent = queue.pop() parentName = parent.name if parentName in self.destNode: return(parentName + " " + str(parent.cost % 24)) break children = [] for child in self.pathGraph[parentName]: if self.nodes[child].color != "black": children.append(child) children.sort() while children: child = children.pop() self.nodes[child].update(parent, 1) queue.append(self.nodes[child]) parent.color = "black" return("None") def parsePath(paths, allNodes): pipeGraph = {} for node in allNodes: pipeGraph[node] = {} for path in paths: pipe = path.split() cost = int(pipe[2]) pipeGraph[pipe[0]][pipe[1]] = [cost] list = [] for i in range(0,int(pipe[3])): z = 4 + i offset1, offset2 = map(int,pipe[z].split('-')) for y in range(offset1,offset2+1): #consider time = 24 cases list.append(y) pipeGraph[pipe[0]][pipe[1]].append(list) return pipeGraph def main(argv): inputFile = "" outputFile = "output.txt" #parsing the arguements for input file name opts, args = getopt.getopt(argv,'i:') for opt, arg in opts: if opt == '-i': inputFile = arg #opening the file for read txt = open(inputFile) outTxt = open(outputFile, "w") t = int(txt.readline()) while t: pathGraph = {} sourceNode = [] paths = [] destNodes = [] middleNodes = [] noPipes = 0 task = txt.readline().rstrip() sourceNode = txt.readline().split() destNodes = txt.readline().split() middleNodes = txt.readline().split() noPipes = int(txt.readline()) for i in range(0,noPipes): paths.append(txt.readline().rstrip()) noNodes = len(destNodes) + len(middleNodes) + 1 allNodes = sourceNode + middleNodes + destNodes nodeList = {} pathGraph = parsePath(paths, allNodes) time = int(txt.readline()) for node in allNodes: x = Node() x.init(node, '', 0) nodeList[node] = x g = GraphInfo() g.init(sourceNode, destNodes, pathGraph, nodeList, time) if task == "BFS": outTxt.write(g.BFS(time) + '\n') elif task == "DFS": outTxt.write(g.DFS(time) + '\n') elif task == "UCS": outTxt.write(g.UCS(time) + '\n') txt.readline() #for the delimiter between two test cases; to be reviewed for last input t -= 1 txt.close() outTxt.close() if __name__ == "__main__": main(sys.argv[1:])
358c4e25edd27ea958e6cc62ac6b08cc1da82070
[ "Python" ]
1
Python
prasadns14/cityWaterFlow
f61fd8edc7f102177192d3a566bbf9d7a26c0f0f
68f356bed73b3cca2343915fdcec88d6ec81b7f1
refs/heads/master
<file_sep><?php require 'customcamp.php'; $session = new Customcamp('USER','PASS','http://BASECAMPURL'); $all_uncomplete = $session->find_all_uncomplete_todos(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Basecamp PHP Example</title> </head> <style type="text/css" media="screen"> /* <![CDATA[ */ body { font-family: Arial, "MS Trebuchet", sans-serif; font-size: 12px; } .rank, .project_name, .list_name { float:left; width:100px; } .item_content { margin-left:200px; } .todo { clear:both; } /* ]]> */ </style> <script type="text/javascript" language="javascript" charset="utf-8"> // <![CDATA[ // ]]> </script> <body> <h1>Basecamp</h1> <h2>New Todo</h2> <input id="project_name" > <h2>All todos!</h2> <?php foreach ($all_uncomplete as $todo_item ) { ?> <div class="todo"> <!-- <div class="rank"><?= round($todo_item->rank) ?></div> --> <div class="project_name"><?= $todo_item->in_project->name ?></div> <div class="list_name"><?= $todo_item->in_list->name ?></div> <div class="item_content"><?= $todo_item->content ?></div> </div> <?php } ?> </body> </html><file_sep><?php require 'basecamp.php'; class Customcamp extends Basecamp { /*======================/ * Text Find /*=====================*/ function find_by_id($id,$items) { for ($i=0;$i<count($items);$i++) { if ($items[$i]->id == $id) { return $items[$i]; } } return false; } function find_by_name($item_type, $item_name) { $results = array(); $pattern = "/{$item_name}/i"; $search_in = ($item_type == 'post' || $item_type == 'milestone')?"title":"name"; if (isset($this->{$item_type})) { if (is_array($this->{$item_type})) { foreach ($this->{$item_type} as $item) { if (preg_match($pattern,$item->{$search_in})) { $results[] = $item; } } } else { if (preg_match($pattern,$this->{$item_type}->{$search_in})) { $results[] = $item; } } } return $results; } function load_projects_with_lists() { $projects = $this->projects(); for ($i=0;$i < count($projects);$i++) { $lists = $this->lists($projects[$i]->id); $projects[$i]->lists = (is_array($lists))?$lists:array($lists); } return $projects; } function find_all_uncomplete_todos($in_project = false) { if ($in_project) { $projects[] = $in_project; } else { $projects = $this->projects(); //print_r($projects); } $to_dos = array(); $i=0; foreach ($projects as $project) { $lists = $this->lists($project->id); foreach ($lists as $list) { $list_data = $this->list_items($list->id); if ($list_data->{"todo-items"}->{"todo-item"}) { foreach ($list_data->{"todo-items"}->{"todo-item"} as $todo) { if ($todo->completed == "false") { $todo->in_project = $project; $todo->in_list = $list; // calculate rank $todo->rank = $list->position * $todo->position * ($this->convert_ruby_timestamp($project->{"last-modified-on"}) / time(+1)); //this is just so they all have unique keys $todo->rank += (rand(0,50) * .000001); if ($i) { print_r($todo); $i = false; } $to_dos["$todo->rank"] = $todo; } } } } } ksort($to_dos); return $to_dos; } // ruby timestamp ex // 2006-04-27T03:49:31Z function convert_ruby_timestamp($timestamp) { $chopped = str_replace(array('T','Z'),array(' ',' GMT'),$timestamp); return (strtotime($chopped)); } } //testing ?><file_sep><?php // For all the fetchin' require_once 'HTTP/Request.php'; require_once 'XML/Serializer.php'; require_once 'XML/Unserializer.php'; class Basecamp { var $user; var $pass; var $base; function Basecamp($user, $pass, $base) { $this->user = $user; $this->pass = $pass; $this->base = $base; } /*======================/ * General /*=====================*/ // Returns the info for the company referenced by id function company($id) { return $this->hook("/contacts/company/{$company_id}","company"); } // This will return an alphabetical list of all message categories in the referenced project. function message_categories($project_id) { return $this->hook("/projects/{$project_id}/post_categories","post-category"); } // This will return an alphabetical list of all file categories in the referenced project. function file_categories($project_id) { return $this->hook("/projects/{$project_id}/attachment_categories","attachment-category"); } // This will return all of the people in the given company. // If a project id is given, it will be used to filter the set of people // that are returned to include only those that can access the given project. function people($company_id) { return $this->hook("/contacts/people/{$company_id}","person"); } // This will return all of the people in the given company that can access the given project. function people_per_project($project_id, $company_id) { return $this->hook("/projects/{$project_id}/contacts/people/{$company_id}","person"); } // This will return information about the referenced person. function person($person_id) { return $this->hook("/contacts/person/{$person_id}","person"); } // This will return a list of all active, // on-hold, and archived projects that you have access to. The list is not ordered. function projects() { return $this->hook("/project/list","project"); } /*======================/ * Messages and Comments /*=====================*/ // Retrieve a specific comment by its id. function comment($comment_id) { return $this->hook("/msg/comment/{$comment_id}","comment"); } // Return the list of comments associated with the specified message. function comments($comment_id) { return $this->hook("/msg/comments/{$message_id}","comment"); } // Create a new comment, associating it with a specific message. function create_comment($comment) { return $this->hook("/msg/create_comment","comment",array("comment" => $comment)); } // Creates a new message, optionally sending notifications to a selected list of people. // Note that you can also upload files using this function, but you need to upload the // files first and then attach them. See the description at the top of this document for more information. // notify should be an array of people_id's function create_message($project_id, $message, $notify = false) { $request['post'] = $message; if ($notify) {$request['notify'] = $notify;} return $this->hook("/projects/{$project_id}/msg/create","post",$request); } // Delete the comment with the given id. function delete_comment($comment_id) { return $this->hook("/msg/delete_comment/{$comment_id}","comment"); } // Delete the message with the given id. function delete_message($message_id) { $request['post'] = 'delete'; return $this->hook("/msg/delete/{$message_id}","post", $request); } // This will return information about the referenced message. // If the id is given as a comma-delimited list, one record will be // returned for each id. In this way you can query a set of messages in a // single request. Note that you can only give up to 25 ids per request--more than that will return an error. function message($message_ids) { return $this->hook("/msg/get/{$message_ids}","post"); } // This will return a summary record for each message in a project. // If you specify a category_id, only messages in that category will be returned. // (Note that a summary record includes only a few bits of information about a post, not the complete record.) function message_archive($project_id,$category_id = false) { $request['post']['project-id'] = $project_id; if ($category_id) { $request['post']['category-id'] = $category_id; } return $this->hook("/projects/{$project_id}/msg/archive","post",$request); } // This will return a summary record for each message in a particular category. // (Note that a summary record includes only a few bits of information about a post, not the complete record.) function message_archive_per_category($project_id,$category_id) { return $this->hook("/projects/{$project_id}/msg/cat/{$category_id}/archive","post"); } // Update a specific comment. This can be used to edit the content of an existing comment. function update_comment($comment_id,$body) { $comment['comment_id'] = $comment_id; $comment['body'] = $body; return $this->hook("/msg/update_comment","comment",$comment); } // Updates an existing message, optionally sending notifications to a selected list of people. // Note that you can also upload files using this function, but you have to format the request // as multipart/form-data. (See the ruby Basecamp API wrapper for an example of how to do this.) function update_message($message_id,$message,$notify = false) { $request['post'] = $message; if ($notify) {$request['notify'] = $notify;} return $this->hook("/msg/update/{$message_id}","post",$request); } /*======================/ * Todo Lists and Items /*=====================*/ // Marks the specified item as "complete". If the item is already completed, this does nothing. function complete_item($item_id) { return $this->hook("/todos/complete_item/{$item_id}","todo-item"); } // This call lets you add an item to an existing list. The item is added to the bottom of the list. // If a person is responsible for the item, give their id as the party_id value. If a company is // responsible, prefix their company id with a 'c' and use that as the party_id value. If the item // has a person as the responsible party, you can use the notify key to indicate whether an email // should be sent to that person to tell them about the assignment. function create_item($list_id, $item, $responsible_party = false, $notify_party = false) { $request['content'] = $item; if ($responsible_party) { $request['responsible_party'] = $responsible_party; $request['notify'] = ($notify_party)?"true":"false"; } return $this->hook("/todos/create_item/{$list_id}","todo-item",$request); } // This will create a new, empty list. You can create the list explicitly, // or by giving it a list template id to base the new list off of. function create_list($project_id,$list) { return $this->hook("/projects/{$project_id}/todos/create_list","todo-list",$list); } // Deletes the specified item, removing it from its parent list. function delete_item($item_id) { return $this->hook("/todos/delete_item/{$item_id}","todo-item"); } // This call will delete the entire referenced list and all items associated with it. // Use it with caution, because a deleted list cannot be restored! function delete_list($list_id) { return $this->hook("/todos/delete_list/{$list_id}","todo-list"); } // This will return the metadata and items for a specific list. function list_items($list_id) { return $this->hook("/todos/list/{$list_id}","todo-list"); } // This will return the metadata for all of the lists in a given project. // You can further constrain the query to only return those lists that are "complete" // (have no uncompleted items) or "uncomplete" (have uncompleted items remaining). function lists($project_id, $complete = false) { $request['complete'] = ($complete)?"true":"false"; return $this->hook("/projects/{$project_id}/todos/lists","todo-list", $request); } // Changes the position of an item within its parent list. It does not currently // support reparenting an item. Position 1 is at the top of the list. Moving an // item beyond the end of the list puts it at the bottom of the list. function move_item($item_id,$to) { return $this->hook("/todos/move_item/{$item_id}","todo-item",array('to' => $to)); } // This allows you to reposition a list relative to the other lists in the project. // A list with position 1 will show up at the top of the page. Moving lists around lets // you prioritize. Moving a list to a position less than 1, or more than the number of // lists in a project, will force the position to be between 1 and the number of lists (inclusive). function move_list($list_id,$to) { return $this->hook("/todos/move_list/{$list_id}","todo-list",array('to' => $to)); } // Marks the specified item as "uncomplete". If the item is already uncompleted, this does nothing. function uncomplete_item($item_id) { return $this->hook("/todos/uncomplete_item/{$item_id}","todo-item"); } // Modifies an existing item. // The values work much like the "create item" operation, so you should refer to that for a more detailed explanation. function update_item($item_id, $item, $responsible_party = false, $notify_party = false) { $request['item']['content'] = $item; if ($responsible_party) { $request['responsible_party'] = $responsible_party; $request['notify'] = ($notify_party)?"true":"false"; } return $this->hook("/todos/update_item/{$item_id}","todo-item",$request); } // With this call you can alter the metadata for a list. function update_list($project_id,$list) { return $this->hook("/todos/update_list/{$list_id}","todo-list",array('list' => $list)); } /*======================/ * Milestones /*=====================*/ // Marks the specified milestone as complete. function complete_milestone($milestone_id) { return $this->hook("/milestones/complete/{$milestone_id}","milestone"); } // Creates a single or multiple milestone(s). function create_milestones($project_id,$milestones) { return $this->hook("/projects/{$project_id}/milestones/create","milestone",array("milestone" => $milestones)); } // Deletes the given milestone from the project. function delete_milestone($milestone_id) { return $this->hook("/milestones/delete/{$milestone_id}","milestone"); } // This lets you query the list of milestones for a project. // You can either return all milestones, or only those that are late, completed, or upcoming. function list_milestones($project_id, $find = "all") { return $this->hook("/projects/{$project_id}/milestones/list","milestone",array('find' => $find)); } // Modifies a single milestone. You can use this to shift the deadline of a single milestone, // and optionally shift the deadlines of subsequent milestones as well. function uncomplete_milestone($milestone_id) { return $this->hook("/milestones/uncomplete/{$milestone_id}","milestone"); } // Creates a single or multiple milestone(s). function update_milestone($milestone_id,$milestone,$move_upcoming_milestones = true,$move_upcoming_milestones_off_weekends = true) { $request['milestone'] = $milestone; $request['move-upcoming-milestones'] = $move_upcoming_milestones; $request['move-upcoming-milestones-off-weekends'] = $move_upcoming_milestones_off_weekends; return $this->hook("/milestones/update/{$milestones_id}","milestone",array("milestone" => $milestone)); } /*===================/ * The Worker Bees /*===================*/ function hook($url,$expected,$send = false) { $returned = $this->unserialize($this->request($url,$send)); $placement = $expected; if (isset($returned->{$expected})) { $this->{$placement} = $returned->{$expected}; return $returned->{$expected}; } else { $this->{$placement} = $returned; return $returned; } } function request($url, $params = false) { //do the connect to a server thing $req =& new HTTP_Request($this->base . $url); //authorize $req->setBasicAuth($this->user, $this->pass); //set the headers $req->addHeader("Accept", "application/xml"); $req->addHeader("Content-Type", "application/xml"); //if were sending stuff if ($params) { //serialize the data $xml = $this->serialize($params); //print_r($xml); ($xml)?$req->setBody($xml):false; $req->setMethod(HTTP_REQUEST_METHOD_POST); } $response = $req->sendRequest(); //print_r($req->getResponseHeader()); //echo $req->getResponseCode() . "\n"; if (PEAR::isError($response)) { return $response->getMessage(); } else { //print_r($req->getResponseBody()); return $req->getResponseBody(); } } function serialize($data) { $options = array( XML_SERIALIZER_OPTION_MODE => XML_SERIALIZER_MODE_SIMPLEXML, XML_SERIALIZER_OPTION_ROOT_NAME => 'request', XML_SERIALIZER_OPTION_INDENT => ' '); $serializer = new XML_Serializer($options); $result = $serializer->serialize($data); return ($result)?$serializer->getSerializedData():false; } function unserialize($xml) { $options = array (XML_UNSERIALIZER_OPTION_COMPLEXTYPE => 'object'); $unserializer = &new XML_Unserializer($options); $status = $unserializer->unserialize($xml); $data = (PEAR::isError($status))?$status->getMessage():$unserializer->getUnserializedData(); return $data; } } // match comments // \/\/ .+ ?>
ff4b5ff643e8606edc573185acf25c7b716c459d
[ "PHP" ]
3
PHP
quirkey/basecamphp
12c784871bcd8b0d62eb70bb09eb3588ddb107d3
fb6e610b11b293a8bc5a456f3b82c3dc00b5d125
refs/heads/master
<file_sep>import React, { Component } from "react"; export default class App extends Component { constructor() { super(); this.state = { username: "", password: "", }; this.clickAlert = this.clickAlert.bind(this); } handlePass(val) { this.setState({ password: val, }); } handleUser(val) { this.setState({ username: val, }); } clickAlert() { alert(`Username:${this.state.username} Password: ${this.state.password}`); } render() { return ( <div> <input placeholder="Username" onChange={(e) => this.handleUser(e.target.value)} type="text" /> <input placeholder="<PASSWORD>" onChange={(e) => this.handlePass(e.target.value)} type="text" /> <button onClick={this.clickAlert}>Login</button> </div> ); } } <file_sep>import React, { Component } from "react"; class App extends Component { constructor() { super(); this.state = { list: ["chicken", "steak", "pasta", "ice cream"], listString: "", }; } handleChange(e) { this.setState({ listString: e.target.value, }); } render() { let listDisplay = this.state.list .filter((e, i) => e.includes(this.state.listString)) .map((e, i) => <h2 key={i}>{e}</h2>); return ( <div> <input onChange={(e) => this.handleChange(e)} /> {listDisplay} </div> ); } } export default App; <file_sep>import React, { Component } from "react"; import Todo from "./component/Todo"; export default class App extends Component { constructor() { super(); this.state = { todos: [], input: "", }; this.handleUpdateTodos = this.handleUpdateTodos.bind(this); } handleInputChange(value) { this.setState({ input: value, }); } handleUpdateTodos() { this.setState({ todos: [...this.state.todos, this.state.input], input: "", }); } delTodo(ind, e) { let todosList = [...this.state.todos] todosList.splice(ind, 1) this.setState({ todos: todosList }); } render() { let list = this.state.todos.map((e, i, a) => ( <Todo delTodo={() => this.delTodo(i)} key={i} task={e} list={a} /> )); return ( <div> <h1>Cavin's Todo List</h1> <input value={this.state.input} onChange={(e) => this.handleInputChange(e.target.value)} type="text" placeholder="Enter New Task" /> <button onClick={this.handleUpdateTodos}>Add</button> {list} </div> ); } } <file_sep>import React, { Component } from "react"; import Image from "./components/Image"; export default class App extends Component { constructor() { super(); this.state = { source: "https://upload.wikimedia.org/wikipedia/en/9/99/YYK_protagonists.jpg", }; } render() { return ( <div> <Image source={this.state.source} /> </div> ); } } <file_sep>import React, { Component } from 'react' class App extends Component { constructor() { super() this.state = { list: ['chicken','steak','pasta','ice cream'] } } render() { let listDisplay = this.state.list.map((e, i) => <h2 key={i}>{e}</h2> ) return ( <div> {listDisplay} </div> ) } } export default App<file_sep>import React from 'react' export default function Image(props) { return ( <div> <img src={props.source} alt="" /> {console.log(props.source)} </div> ) }
f75a0d07b0bd60768bf5bd170d91fbdfbb18b31d
[ "JavaScript" ]
6
JavaScript
cavingayle/react-drills
bf5c897f747396994965c5d5d6c00fd67703b190
003bc9152e8b59b179c2d18c489a6fb5c242db9e
refs/heads/master
<file_sep>import sys class Cell(object): def __init__(self, number): self.number = number self.children = [] def has_child(self, number): for child in self.children: if child.number == number: return True return False def get_child(self, number): for child in self.children: if child.number == number: return child return False def add_child(self, child): self.children.append(child) def add_phone_number_to_cell(telephone, ancestor_cell, total_cell): parent_cell = ancestor_cell for number in telephone: if parent_cell.has_child(int(number)): parent_cell = parent_cell.get_child(int(number)) continue else: total_cell += 1 child_cell = Cell(int(number)) parent_cell.add_child(child_cell) parent_cell = child_cell return total_cell ancestor_cell = Cell(int(-1)) total_cell = 0 n = int(input()) for i in range(n): telephone = input() total_cell = add_phone_number_to_cell(telephone, ancestor_cell, total_cell) print(total_cell, file=sys.stderr) # Write an action using print # To debug: print("Debug messages...", file=sys.stderr) # The number of elements (referencing a number) stored in the structure. print(total_cell) <file_sep>def get_time_before_coronavirus(first_infected, human_links, number_human, min_times): list_infected = [first_infected] day_number = 0 while len(list_infected) < number_human: if day_number >= min_times: return number_human new_infected = [] for infected in list_infected: new_infected.append(infected) new_infected.extend(human_links[infected]) list_infected = list(set(new_infected)) day_number += 1 return day_number number_human = int(input()) + 1 human_links = {} for i in range(number_human): human_links[i] = [] for i in range(number_human - 1): a, b = [int(j) for j in input().split()] human_links[a].append(b) human_links[b].append(a) potential_start = [] biggest_first_spread = 0 for i in range(number_human): if len(human_links[i]) > biggest_first_spread: biggest_first_spread = len(human_links[i]) for i in range(number_human): if len(human_links[i]) >= biggest_first_spread - 10: potential_start.append(i) if len(potential_start) > 500: print(500) else: min_times = number_human best_infected = -1 # for i in range(number_human): for i in potential_start: time = get_time_before_coronavirus( first_infected=i, human_links=human_links, number_human=number_human, min_times=min_times ) if time < min_times: min_times = time best_infected = i print(min_times) <file_sep>import sys import math def move_letter_n(letter, n): ascii_letter = ord(letter) - 65 moved_ascii = (ascii_letter + n) % 26 return chr(moved_ascii + 65) def encode_ceasar_shifted(word, initial_shift): encrypted = "" shift = initial_shift for letter in word: encrypted += move_letter_n(letter, shift) shift += 1 return encrypted def decode_ceasar_shifted(word, initial_shift): decrypted = "" shift = - initial_shift for letter in word: decrypted += move_letter_n(letter, shift) shift -= 1 return decrypted def encode_with_rotor(message, rotor): encrypted = "" for letter in message: encrypted += rotor[ord(letter) - 65] return encrypted def decode_with_rotor(message, rotor): decrypted = "" for letter in message: decrypted += chr(65 + rotor.find(letter)) return decrypted operation = input() pseudo_random_number = int(input()) rotors = [] for i in range(3): rotors.append(input()) message = input() if operation == "ENCODE": encode = encode_ceasar_shifted(message, pseudo_random_number) for rotor in rotors: encode = encode_with_rotor(encode, rotor) print(encode) else: decrypted = decode_with_rotor(message, rotors[2]) decrypted = decode_with_rotor(decrypted, rotors[1]) decrypted = decode_with_rotor(decrypted, rotors[0]) decrypted = decode_ceasar_shifted(decrypted, pseudo_random_number) print(decrypted) <file_sep>inputs = [] results = [] def get_value_from_input(input_arg, results, inputs): if input_arg == "_": return 0 if input_arg.find("$") > -1: ref = int(input_arg.replace("$", "")) return get_cell_i(results, inputs, ref) else: return int(input_arg) def compute_input(results, inputs, i): input = inputs[i] arg_1 = get_value_from_input(input["arg_1"], results, inputs) arg_2 = get_value_from_input(input["arg_2"], results, inputs) operation = input["operation"] if operation == "VALUE": return arg_1 if operation == "ADD": return arg_1 + arg_2 if operation == "SUB": return arg_1 - arg_2 if operation == "MULT": return arg_1 * arg_2 return "WTF" def get_cell_i(results, inputs, i): if not bool(results[i]): results[i] = compute_input(results, inputs, i) return results[i] else: return results[i] n = int(input()) for i in range(n): operation, arg_1, arg_2 = input().split() inputs.append({ "operation": operation, "arg_1": arg_1, "arg_2": arg_2 }) for i in range(n): results.append(False) for i in range(len(inputs)): results[i] = get_cell_i(results, inputs, i) for result in results: print(result) <file_sep>d=input() r="" d=d.split(" ") for e in d: c=e[len(e)-1] e=e.replace(c,"") for e in range(int(e)): r+=c print(r)<file_sep>import sys width, height = [int(i) for i in input().split()] def is_exit(board, x, y): try: return board[y][x] == "0" except Exception as e: return False def compute_number_close_exit(board, x, y): number = 0 neighbour = [ (x - 1, y), (x + 1, y), (x, y + 1), (x, y - 1), ] for (xbis, ybis) in neighbour: if -1 < xbis < width: if -1 < ybis < height: if is_exit(board, xbis, ybis): number += 1 return str(number) board = [] for i in range(height): line = list(input()) board.append(line) new_board = [] for y in range(height): new_line = [] for x in range(width): if is_exit(board, x, y): new_line.append(compute_number_close_exit(board, x, y)) else: new_line.append("#") new_board.append(new_line) for i in range(height): print("".join(new_board[i])) <file_sep>def sort_string(string): return "".join(sorted(string)) rule = { sort_string("CP"): "C", sort_string("PR"): "P", sort_string("RL"): "R", sort_string("LS"): "L", sort_string("SC"): "S", sort_string("CL"): "C", sort_string("LP"): "L", sort_string("PS"): "P", sort_string("SR"): "S", sort_string("RC"): "R", } def get_winner(player_a, player_b): winner = chose_winner(player_a, player_b) winner["opp"].append(str(player_a["num"]) if winner["num"] == player_b["num"] else str(player_b["num"])) return winner def chose_winner(player_a, player_b): if player_a["sign"] == player_b["sign"]: return player_a if player_a["num"] < player_b["num"] else player_b winner_sign = rule[sort_string("{}{}".format(player_a["sign"], player_b["sign"]))] return player_a if player_a["sign"] == winner_sign else player_b def play_match(players): winners = [] for i in range(int(len(players) / 2)): winners.append(get_winner( players[2 * i], players[2 * i + 1] )) return winners n = int(input()) players = [] for i in range(n): numplayer, signplayer = input().split() numplayer = int(numplayer) players.append({ "num": numplayer, "sign": signplayer, "opp": [] }) while len(players) > 1: players = play_match(players) print(players[0]["num"]) print(" ".join(players[0]["opp"])) <file_sep>import copy def is_cell_empty(board, x, y): return board[y][x] == "." def is_cell_0(board, x, y): return board[y][x] == "O" def is_board_win(board): # Test columns for x in range(3): is_column_win = True for y in range(3): is_column_win = is_column_win and is_cell_0(board, x, y) if is_column_win: return True # Test lines for y in range(3): is_line_win = True for x in range(3): is_line_win = is_line_win and is_cell_0(board, x, y) if is_line_win: return True # Test diagonals is_first_diagonal_win = True for (x, y) in [(0, 0), (1, 1), (2, 2)]: is_first_diagonal_win = is_first_diagonal_win and is_cell_0(board, x, y) is_second_diagonal_win = True for (x, y) in [(2, 0), (1, 1), (0, 2)]: is_second_diagonal_win = is_second_diagonal_win and is_cell_0(board, x, y) if is_first_diagonal_win or is_second_diagonal_win: return True return False def print_board(board): for line in board: print(line) def create_new_board(board, x, y): new_board = copy.copy(board) new_line = list(new_board[y]) new_line[x] = "O" new_board[y] = "".join(new_line) return new_board board = [] for i in range(3): line = input() board.append(line) for x in range(3): for y in range(3): if is_cell_empty(board, x, y): new_board = create_new_board(board, x, y) if is_board_win(new_board): print_board(new_board) <file_sep>b="".join(list(map(lambda i:bin(ord(i))[2:].zfill(7),input()))) t=[] x=b[0] for i in b[1:]+"a": if i!=x[0]: t+=[x] x="" x+=i print(" ".join(list(map(lambda a:' '.join([["0","00"][a[0]!="1"],"".zfill(len(a))]),t))))<file_sep>import sys import math ######### utils ######### def print_log(msg): print(msg, file=sys.stderr) def is_red(speed, distance, duration): return (18 * distance) % (10 * speed * duration) >= (5 * speed * duration) ######### utils ######### speed = int(input()) light_count = int(input()) lights = [] for i in range(light_count): distance, duration = [int(j) for j in input().split()] lights.append( { "distance": distance, "duration": duration } ) max_speed = 0 for potential_speed in range(speed): potential_speed += 1 does_work = True for light in lights: does_work = does_work and not is_red(potential_speed, light["distance"], light["duration"]) if does_work: max_speed = potential_speed print(max_speed) <file_sep>import sys import math def print_log(msg): print(msg, file=sys.stderr) def dichotomy(current_pos, max_pos, min_pos): next_pos = max_pos + min_pos - current_pos if next_pos == current_pos: next_pos += 1 if next_pos > max_pos: next_pos = max_pos if next_pos < min_pos: next_pos = min_pos return round(next_pos) def update_dichotomy_result(last_pos, current_pos, max_pos, min_pos, bomb_dir): middle = (max_pos + min_pos) / 2 if bomb_dir == "WARMER": if current_pos > last_pos: return math.ceil(middle), max_pos else: return min_pos, math.floor(middle) if bomb_dir == "COLDER": if current_pos > last_pos: return min_pos, math.floor(middle) else: return math.ceil(middle), max_pos # w: width of the building. # h: height of the building. w, h = [int(i) for i in input().split()] n = int(input()) # maximum number of turns before game over. x0, y0 = [int(i) for i in input().split()] xmin = 0 ymin = 0 xmax = w - 1 ymax = h - 1 ycurrent = y0 xcurrent = x0 looking_for_x = True # game loop while True: if xmin == xmax: looking_for_x = False bomb_dir = input() # Current distance to the bomb compared to previous distance (COLDER, WARMER, SAME or UNKNOWN) if bomb_dir != "UNKNOWN": if looking_for_x: xmin, xmax = update_dichotomy_result(xlast, xcurrent, xmax, xmin, bomb_dir) else: ymin, ymax = update_dichotomy_result(ylast, ycurrent, ymax, ymin, bomb_dir) ylast = ycurrent xlast = xcurrent if looking_for_x: ycurrent = ylast xcurrent = dichotomy(xlast, xmax, xmin) else: xcurrent = xmin ycurrent = dichotomy(ylast, ymax, ymin) print("{} {}".format(xcurrent, ycurrent))
f8f1c94ac57c94f3867211ff882757bb020dcf88
[ "Python" ]
11
Python
NicolleLouis/codingame
07ba9e4e620f5ac57c3585693f59e4294e22f0e5
f130529822f0ded9170c4bd12d7f743e18686698
refs/heads/master
<repo_name>dahse89/Console<file_sep>/README.md Console ======= PHP Class for easy build CLI scripts. **basic utilities** exit if script isn't started in cli ```php Console::exitInWrongEnv("Please run in shell only"); ``` Print memory usage, pretty ```php for($i = 0; $i < 10; $i++){ $buffer[] = str_repeat(md5(uniqid()),0xfff); echo Console::getMemory(true)." "; } //512kB 768kB 1MB 1.25MB 1.5MB 1.75MB 2MB 2.25MB 2.5MB 2.75MB ``` reading cli inputs ```php Console::write("Input: "); $line = Console::readLine(); // OR $line = Console::readLine("Input: "); ``` writing unicode ```php Console::writeUnicode(0x2727); Console::writeUnicode(0x269D); Console::writeUnicode(0x2603); // ✧ ⚝ ☃ Console::writeUnicode([ PHP_EOL, 'a', 0x250C, 0x2500, 0x2510,'b', PHP_EOL, 'c',0x85, 0x2514, 0x2500, 0x2518,'d' ]); // a┌─┐b // c└─┘d ``` process visualisation ```php /* calc PI */ Console::writeLine("Calculate PI!",Color::Yellow,Style::Intensity); $accuracy = Console::readInt("Accuracy (enter Integer e.g 10000000 -> Accuracy of 7 decimal places): "); $pi = 0; Console::startProcess("calculating", $accuracy); for( $i = 1; $i < $accuracy; $i++) { $pi += 4 / ($i * 2 - 1) * ($i & 1 ? 1 : -1); Console::writeProcess($i); } Console::writeProcessEnd(); Console::writeLine($pi); //> Calculate PI! //> Accuracy (enter Integer e.g 10000 -> Accuracy of 4 decimal places): xas //> Please enter a number! //> Accuracy (enter Integer e.g 10000 -> Accuracy of 4 decimal places): 10000 //> calculating: 100% <- running from 0 to 100% //> 3.1416926635905 ``` <file_sep>/Console.php <?php /** * Created by PhpStorm. * User: pdahse * Date: 18.12.14 * Time: 14:48 */ class Console { const STDIN = "php://stdin"; private static $lastProcessValLength; private static $processlabel; private static $processTotal; private function __construct(){} public static function prettyMemory($value){ foreach(array('B','kB','MB','GB','TB') as $x => $label){ if($value < pow(0x400,$x+1)){ return round($value/ pow(0x400,$x),2) . $label; } } } public static function write($str = "", $color = Color::Reset, $style = Style::None){ $colorstyle = self::createStyle($color,$style); echo $colorstyle.$str.self::createStyle(); } private static function createStyle($color = -1, $style = -1){ if( $style === Style::None || $style === Style::Bold || $style === Style::Underline){ return "\033[$style;{$color}m"; }elseif($style === Style::Background){ $color = $color + 10; return "\033[{$color}m"; }elseif($style === Style::Intensity){ $color = $color + 60; return "\033[0;{$color}m"; }elseif($style === Style::Bold_Intensity){ return "\033[1;{$color}m"; }elseif($style === Style::Background_Intensity){ $color = $color + 70; return "\033[0;{$color}m"; } return "\033[0m"; } public static function writeLine($str = "", $color = Color::Reset, $style = Style::None){ $colorstyle = self::createStyle($color,$style); echo $colorstyle.$str.self::createStyle().PHP_EOL; } public static function writeUnicode($unicode){ if(is_array($unicode)){ if(count($unicode) === 1){ return self::writeUnicode($unicode[0]); }else{ self::writeUnicode(array_shift($unicode)); return self::writeUnicode($unicode); } } self::write((is_int($unicode) ? json_decode('"\u'. dechex($unicode).'"'): $unicode)); } public static function getMemory($pretty = false){ $memory = memory_get_usage(true); return $pretty ? self::prettyMemory($memory) : $memory; } public static function readLine($question = ""){ self::write($question); return trim(fgets(fopen(self::STDIN,"r"))); } public static function readInt($question = "") { while(!is_numeric($int = self::readLine($question))){ self::writeLine("Please enter a number!",Color::Red); } return (int) filter_var($int,FILTER_SANITIZE_NUMBER_INT); } public static function isRunningInCLI(){ return PHP_SAPI === 'cli'; } public static function exitInWrongEnv($message = ""){ if(!self::isRunningInCLI()) die($message); } public static function cursorUp($x){ self::write("\033[{$x}A"); } public static function cursorDown($x){ self::write("\033[{$x}B"); } public static function cursorForward($x){ self::write("\033[{$x}C"); } public static function cursorBackward($x){ self::write("\033[{$x}D"); } public static function cursorSave(){ self::write("\033[s"); } public static function cursorRestore(){ self::write("\033[u"); } public static function startProcess($label,$total){ self::$processlabel = $label; self::$processTotal = $total; self::cursorHide(); } public static function writeProcess($curr){ $percentage = 100/self::$processTotal * $curr; $val = round($percentage,2)."%"; $str = self::$processlabel.": "; $vallength = strlen($val); $length = strlen($str) + $vallength; $clear = 0; if($length < self::$lastProcessValLength){ $clear = self::$lastProcessValLength - $length; } self::$lastProcessValLength = $length; self::write($str); if($val < 16.5){ $color = Color::Red; $style = Style::Intensity; }elseif($val >= 16.5 && $val < 33){ $color = Color::Red; $style = Style::None; }elseif($val >= 33 && $val < 50){ $color = Color::Yellow; $style = Style::Intensity; }elseif($val >= 50 && $val < 66.5){ $color = Color::Yellow; $style = Style::None; }elseif($val >= 66.5 && $val < 83){ $color = Color::Green; $style = Style::None; }else{ $color = Color::Green; $style = Style::Intensity; } self::write($val,$color,$style); self::write(str_repeat(" ",$clear)); self::cursorBackward($length + $clear); } public static function writeProcessEnd(){ self::write(self::$processlabel.": "); self::writeLine("100% ",Color::Green,Style::Bold_Intensity); self::cursorShow(); } public static function cursorHide(){ passthru("tput civis"); } public static function cursorShow(){ passthru("tput cnorm"); } } class Color{ const Black = 30; const Red = 31; const Green = 32; const Yellow = 33; const Blue = 34; const Purple = 35; const Cyan = 36; const White = 37; const Reset = 0; } class Style{ const None = 0; const Bold = 1; const Underline = 4; const Background = 8; const Intensity = 16; const Bold_Intensity = 32; const Background_Intensity = 64; }
a064f1818088f7423bafeec84287dbbf23d7fe09
[ "Markdown", "PHP" ]
2
Markdown
dahse89/Console
c93bdf74aef67df2b0f95beb26c2fe00c88d126e
6cdced4224ab23f6bd41879229bb3084f3d34782
refs/heads/development
<repo_name>nChannelIO/quickbooks-online-channel<file_sep>/functions/InsertSalesOrder.js 'use strict'; let extractBusinessReference = require('../util/extractBusinessReference'); let request = require('request'); let InsertSalesOrder = function ( ncUtil, channelProfile, flowContext, payload, callback) { log("Building response object..."); let out = { ncStatusCode: null, response: {}, payload: {} }; let invalid = false; let invalidMsg = ""; // Check channelProfile properties if (!channelProfile) { invalid = true; invalidMsg = "InsertSalesOrder - Invalid Request: channelProfile was not passed into the function"; } else if (!channelProfile.channelAuthValues) { invalid = true; invalidMsg = "InsertSalesOrder - Invalid Request: channelAuthValues is missing from channelProfile"; } else if (!channelProfile.channelSettingsValues) { invalid = true; invalidMsg = "InsertSalesOrder - Invalid Request: channelSettingsValues is missing from channelProfile"; } else if (!channelProfile.channelSettingsValues.protocol) { invalid = true; invalidMsg = "InsertSalesOrder - Invalid Request: channelProfile.channelSettingsValues.protocol is missing"; } else if (!channelProfile.channelSettingsValues.api_uri) { invalid = true; invalidMsg = "InsertSalesOrder - Invalid Request: channelProfile.channelSettingsValues.api_uri is missing"; } else if (!channelProfile.channelSettingsValues.minor_version) { invalid = true; invalidMsg = "InsertSalesOrder - Invalid Request: channelProfile.channelSettingsValues.minor_version is missing"; } else if (!channelProfile.channelAuthValues.realm_id) { invalid = true; invalidMsg = "InsertSalesOrder - Invalid Request: channelProfile.channelAuthValues.realm_id is missing"; } else if (!channelProfile.channelAuthValues.access_token) { invalid = true; invalidMsg = "InsertSalesOrder - Invalid Request: channelProfile.channelAuthValues.access_token is missing"; } else if (!channelProfile.salesOrderBusinessReferences) { invalidMsg = "Insert Sales Order - Invalid Request: channelProfile.salesOrderBusinessReferences is missing"; invalid = true; } else if (!Array.isArray(channelProfile.salesOrderBusinessReferences)) { invalidMsg = "Insert Sales Order - Invalid Request: channelProfile.salesOrderBusinessReferences is expected to be an array"; invalid = true; } else if (channelProfile.salesOrderBusinessReferences.length === 0) { invalidMsg = "Insert Sales Order - Invalid Request: channelProfile.salesOrderBusinessReferences does not have any values"; invalid = true; } // Check callback if (!callback) { throw new Error("A callback function was not provided"); } else if (typeof callback !== 'function') { throw new TypeError("callback is not a function") } // Check Payload if (!payload) { invalidMsg = "Insert Sales Order - Invalid Request: payload was not provided"; invalid = true; } else if (!payload.doc) { invalidMsg = "Insert Sales Order - Invalid Request: payload.doc was not provided"; invalid = true; } else if (!payload.billingCustomerRemoteID) { invalidMsg = "Insert Sales Order - Invalid Request: payload.billingCustomerRemoteID was not provided"; invalid = true; } if (!invalid) { try { // First query items by sku to update the sales order line items with their remote ids. If at least one can't be found return a 400. // Get a list of skus let skus = payload.doc.Line.reduce((skus, line) => { if (line.DetailType === 'SalesItemLineDetail' && line.SalesItemLineDetail.ItemRef.name !== 'Shipping' && line.SalesItemLineDetail.ItemRef.name !== undefined) { skus[line.SalesItemLineDetail.ItemRef.name] = {Id: undefined}; } // else skip return skus; }, {}); // Build a GET Product Query Object let query = { doc: { searchFields: [{ searchField: 'Sku', searchValues: Object.keys(skus) }], page: 1, pageSize: 25 } }; // Set the Sku as the business reference so that the stub function pulls it out of the document for us :) channelProfile.productBusinessReferences = ['Item.Sku']; // Build a recursive function to execute the query until we don't receive a 206 let product = require('./GetProductSimpleFromQuery'); let getAllProducts = function (query, callback, cache) { // Execute the query product.GetProductSimpleFromQuery(ncUtil, channelProfile, flowContext, query, (response) => { if (!cache) { // If this is the first response from Get Product then initialize the cache cache = response; } else if (response.ncStatusCode === 200 || response.ncStatusCode === 206) { // otherwise concat the payload cache.payload = cache.payload.concat(response.payload); } if (response.ncStatusCode === 200 || response.ncStatusCode === 204) { // Stop recursion and return the cache if (cache.payload.length > 0) { cache.ncStatusCode = 200; } callback(cache); } else if (response.ncStatusCode === 206) { // Increment the page and make a recursive call query.doc.page++; getAllProducts(query, callback, cache); } else { // Error - return the error response callback(response); } }); }; // Call getAllProducts getAllProducts(query, (response) => { if (response.ncStatusCode === 200) { // Make sure we got a product for each sku in the query response.payload.forEach((doc) => { if (skus[doc.productBusinessReference] === undefined) { // Somehow we got a product we didn't ask for...I guess we can live with it so I won't throw an error } else { skus[doc.productBusinessReference].Id = doc.productRemoteID; } }); let errors = []; Object.keys(skus).forEach(sku => { if (skus[sku].Id === undefined) { // Didn't get this product. Throw an error errors.push('The GET Product Query did not return a result for sku: ' + sku); } }); if (errors.length > 0) { // Stop now and return an error out.ncStatusCode = 400; out.payload.error = {err: errors}; callback(out); } else { // Update the line items with their remote id payload.doc.Line.forEach(line => { if (line.DetailType === 'SalesItemLineDetail' && line.SalesItemLineDetail.ItemRef.name !== 'Shipping' && line.SalesItemLineDetail.ItemRef.name !== undefined) { line.SalesItemLineDetail.ItemRef.value = skus[line.SalesItemLineDetail.ItemRef.name].Id; delete line.SalesItemLineDetail.ItemRef.name } }); // Now Insert the order // Create endpoint let minorVersion = "?minorversion=" + channelProfile.channelSettingsValues.minor_version; let endPoint = "/company/" + channelProfile.channelAuthValues.realm_id + "/salesreceipt" + minorVersion; let url = channelProfile.channelSettingsValues.protocol + "://" + channelProfile.channelSettingsValues.api_uri + endPoint; let headers = { "Authorization": "Bearer " + channelProfile.channelAuthValues.access_token, "Accept": "application/json" }; log("Using URL [" + url + "]"); // Delete the customer and replace it with the customer remoteID delete payload.doc.Customer; payload.doc.CustomerRef = { value: payload.billingCustomerRemoteID }; /* Set URL and headers */ let options = { url: url, method: "POST", headers: headers, body: payload.doc, json: true }; // Pass in our URL and headers request(options, function (error, response, body) { try { if (!error) { log("Do InsertSalesOrder Callback"); out.response.endpointStatusCode = response.statusCode; out.response.endpointStatusMessage = response.statusMessage; // Parse data let data = body; // If we have a customer object, set out.payload.doc to be the customer document if (data && response.statusCode === 200) { out.payload = { doc: data.SalesReceipt, "salesOrderRemoteID": data.SalesReceipt.Id, "salesOrderBusinessReference": extractBusinessReference(channelProfile.salesOrderBusinessReferences, data.SalesReceipt) }; out.ncStatusCode = 201; } else if (response.statusCode === 429) { out.ncStatusCode = 429; out.payload.error = {err: data}; } else if (response.statusCode === 500) { out.ncStatusCode = 500; out.payload.error = {err: data}; } else { out.ncStatusCode = 400; out.payload.error = {err: data}; } callback(out); } else { logError("Do InsertSalesOrder Callback error - " + error); out.ncStatusCode = 500; out.payload.error = {err: error}; callback(out); } } catch (err) { logError("Exception occurred in InsertSalesOrder - " + err); out.ncStatusCode = 500; out.payload.error = {err: err, stackTrace: err.stackTrace}; callback(out); } }); } } else if (response.ncStatusCode === 204) { // Unable to find the products response.statusCode = 400; response.payload.error = { err: 'Unable to find the products listed on the order.', originalError: response.payload.error }; callback(response); } else { // Error response.payload.error = { err: 'An error occurred while retrieving the products listed on the order.', originalError: response.payload.error }; callback(response); } }); } catch (err) { logError("Exception occurred in InsertSalesOrder - " + err); out.ncStatusCode = 500; out.payload.error = {err: err, stackTrace: err.stackTrace}; callback(out); } } else { log("Callback with an invalid request - " + invalidMsg); out.ncStatusCode = 400; out.payload.error = {err: invalidMsg}; callback(out); } }; function logError(msg) { console.log("[error] " + msg); } function log(msg) { console.log("[info] " + msg); } module.exports.InsertSalesOrder = InsertSalesOrder; <file_sep>/functions/CheckForCustomer.js 'use strict'; let extractBusinessReference = require('../util/extractBusinessReference'); let jsonata = require('jsonata'); let request = require('request'); let CheckForCustomer = function ( ncUtil, channelProfile, flowContext, payload, callback) { log("Building response object..."); let out = { ncStatusCode: null, response: {}, payload: {} }; let invalid = false; let invalidMsg = ""; // Check channelProfile properties if (!channelProfile) { invalid = true; invalidMsg = "Check For Customer - Invalid Request: channelProfile was not passed into the function"; } else if (!channelProfile.channelAuthValues) { invalid = true; invalidMsg = "Check For Customer - Invalid Request: channelAuthValues is missing from channelProfile"; } else if (!channelProfile.channelSettingsValues) { invalid = true; invalidMsg = "Check For Customer - Invalid Request: channelSettingsValues is missing from channelProfile"; } else if (!channelProfile.channelSettingsValues.protocol) { invalid = true; invalidMsg = "Check For Customer - Invalid Request: channelProfile.channelSettingsValues.protocol is missing"; } else if (!channelProfile.channelSettingsValues.api_uri) { invalid = true; invalidMsg = "Check For Customer - Invalid Request: channelProfile.channelSettingsValues.api_uri is missing"; } else if (!channelProfile.channelSettingsValues.minor_version) { invalid = true; invalidMsg = "Check For Customer - Invalid Request: channelProfile.channelSettingsValues.minor_version is missing"; } else if (!channelProfile.channelAuthValues.realm_id) { invalid = true; invalidMsg = "Check For Customer - Invalid Request: channelProfile.channelAuthValues.realm_id is missing"; } else if (!channelProfile.channelAuthValues.access_token) { invalid = true; invalidMsg = "Check For Customer - Invalid Request: channelProfile.channelAuthValues.access_token is missing"; } else if (!channelProfile.customerBusinessReferences) { invalidMsg = "Check For Customer - Invalid Request: channelProfile.customerBusinessReferences is missing"; invalid = true; } else if (!Array.isArray(channelProfile.customerBusinessReferences)) { invalidMsg = "Check For Customer - Invalid Request: channelProfile.customerBusinessReferences is expected to be an array"; invalid = true; } else if (channelProfile.customerBusinessReferences.length === 0) { invalidMsg = "Check For Customer - Invalid Request: channelProfile.customerBusinessReferences does not have any values"; invalid = true; } // Check callback if (!callback) { throw new Error("A callback function was not provided"); } else if (typeof callback !== 'function') { throw new TypeError("callback is not a function") } // Check payload if (!payload) { invalid = true; invalidMsg = "payload was not provided" } else if (!payload.doc) { invalid = true; invalidMsg = "payload.doc was not provided"; } if (!invalid) { try { // Create endpoint let minorVersion = "?minorversion=" + channelProfile.channelSettingsValues.minor_version; let endPoint = "/company/" + channelProfile.channelAuthValues.realm_id + "/query"; let url = channelProfile.channelSettingsValues.protocol + "://" + channelProfile.channelSettingsValues.api_uri + endPoint; // Lookup the businessReference let values = []; let customerBusinessReference = []; channelProfile.customerBusinessReferences.forEach(function (businessReference) { let expression = jsonata(businessReference); let value = expression.evaluate(payload.doc); if (businessReference.startsWith('PrimaryEmailAddr')) { values.push("PrimaryEmailAddr = '" + encodeURIComponent(value) + "'"); } else { values.push(businessReference + " = '" + encodeURIComponent(value) + "'"); } customerBusinessReference.push(encodeURIComponent(value)); }); // Set our query for looking up customers let lookup = "&query=SELECT * from Customer Where " + values.join(" AND "); // Set headers let headers = { "Authorization": "Bearer " + channelProfile.channelAuthValues.access_token, "Accept": "application/json" }; url += minorVersion + lookup; log("Using URL [" + url + "]"); let options = { url: url, headers: headers }; // Pass in our URL and headers request(options, function (error, response, body) { try { if (!error) { log("Do CheckForCustomer Callback"); out.response.endpointStatusCode = response.statusCode; out.response.endpointStatusMessage = response.statusMessage; // Parse data let data = JSON.parse(JSON.stringify(body)); // 200 Response if (response.statusCode === 200) { data = JSON.parse(body); // _embedded.self is an array of customer data // One customer will return ncStatusCode = 200 // More than one customer will return ncStatusCode = 409 // _embedded.self is only returned if there is customer data // If not present, return ncStatusCode = 204 if (data.QueryResponse.Customer) { if (data.QueryResponse.Customer && data.QueryResponse.Customer.length === 1) { let customer = data.QueryResponse.Customer[0]; out.ncStatusCode = 200; out.payload.customerRemoteID = customer.Id; out.payload.customerBusinessReference = extractBusinessReference(channelProfile.customerBusinessReferences, customer); } else { out.ncStatusCode = 409; out.payload.error = {err: data}; } } else { out.ncStatusCode = 204; } } else if (response.statusCode === 400) { out.ncStatusCode = 400; out.payload.error = {err: data}; } else if (response.statusCode === 429) { out.ncStatusCode = 429; out.payload.error = {err: data}; } else if (response.statusCode === 500) { out.ncStatusCode = 500; out.payload.error = {err: data}; } else { out.ncStatusCode = 400; out.payload.error = {err: data}; } callback(out); } else { logError("Do CheckForCustomer Callback error - " + error); out.ncStatusCode = 500; out.payload.error = {err: error}; callback(out); } } catch (err) { logError("Exception occurred in CheckForCustomer - " + err); console.log(err); out.payload.error = {err: err, stackTrace: err.stackTrace}; out.ncStatusCode = 500; callback(out); } }); } catch (err) { logError("Exception occurred in CheckForCustomer - " + err); out.ncStatusCode = 500; out.payload.error = {err: err, stackTrace: err.stackTrace}; callback(out); } } else { log("Callback with an invalid request - " + invalidMsg); out.ncStatusCode = 400; out.payload.error = {err: invalidMsg}; callback(out); } }; function logError(msg) { console.log("[error] " + msg); } function log(msg) { console.log("[info] " + msg); } module.exports.CheckForCustomer = CheckForCustomer; <file_sep>/functions/GetProductGroupFromQuery.js 'use strict'; let product = require('./GetProductSimpleFromQuery'); let extractBusinessReference = require('../util/extractBusinessReference'); let jsonata = require('jsonata'); let GetProductGroupFromQuery = function ( ncUtil, channelProfile, flowContext, payload, callback) { log("Building response object..."); let out = { ncStatusCode: null, response: {}, payload: {} }; let invalid = false; let invalidMsg = ""; if (!channelProfile.productGroupBusinessReferences) { invalid = true; invalidMsg = "channelProfile.productGroupBusinessReferences was not provided" } else if (!Array.isArray(channelProfile.productGroupBusinessReferences)) { invalid = true; invalidMsg = "channelProfile.productGroupBusinessReferences is not an array" } else if (channelProfile.productGroupBusinessReferences.length === 0) { invalid = true; invalidMsg = "channelProfile.productGroupBusinessReferences is empty" } //If a query document was not passed in, the request is invalid if (!payload) { invalid = true; invalidMsg = "payload was not provided" } else if (!payload.doc) { invalid = true; invalidMsg = "payload.doc was not provided"; } else if (payload.doc.remoteIDs) { invalid = true; invalidMsg = "getting product groups by remoteID is not supported for QuickBooks Online" } else if (!payload.doc.searchFields && !payload.doc.modifiedDateRange) { invalid = true; invalidMsg = "either payload.doc.remoteIDs or payload.doc.searchFields or payload.doc.modifiedDateRange must be provided" } else if (payload.doc.searchFields && payload.doc.modifiedDateRange) { invalid = true; invalidMsg = "payload.doc.searchFields or payload.doc.modifiedDateRange may be provided" } else if (payload.doc.searchFields && (!Array.isArray(payload.doc.searchFields) || payload.doc.searchFields.length === 0)) { invalid = true; invalidMsg = "payload.doc.searchFields must be an Array with at least 1 key value pair: {searchField: 'key', searchValues: ['value_1']}" } else if (payload.doc.searchFields) { for (let i = 0; i < payload.doc.searchFields.length; i++) { if (!payload.doc.searchFields[i].searchField || !Array.isArray(payload.doc.searchFields[i].searchValues) || payload.doc.searchFields[i].searchValues.length === 0) { invalid = true; invalidMsg = "payload.doc.searchFields[" + i + "] must be a key value pair: {searchField: 'key', searchValues: ['value_1']}"; break; } } } else if (payload.doc.modifiedDateRange && !(payload.doc.modifiedDateRange.startDateGMT || payload.doc.modifiedDateRange.endDateGMT)) { invalid = true; invalidMsg = "at least one of payload.doc.modifiedDateRange.startDateGMT or payload.doc.modifiedDateRange.endDateGMT must be provided" } else if (payload.doc.modifiedDateRange && payload.doc.modifiedDateRange.startDateGMT && payload.doc.modifiedDateRange.endDateGMT && (payload.doc.modifiedDateRange.startDateGMT > payload.doc.modifiedDateRange.endDateGMT)) { invalid = true; invalidMsg = "startDateGMT must have a date before endDateGMT"; } //If callback is not a function if (!callback) { throw new Error("A callback function was not provided"); } else if (typeof callback !== 'function') { throw new TypeError("callback is not a function") } if (!invalid) { // Business references must reference from the root of the document. Since the productGroup schema only has one property at the root (Items), // we can remove this portion of the reference so that it references starting at the root of the product. channelProfile.productGroupBusinessReferences = channelProfile.productGroupBusinessReferences.reduce((newReferences, reference) => { if (reference.startsWith('Items')) { newReferences.push(reference.substring(reference.indexOf('.') + 1)); } else { newReferences.push(reference); } return newReferences; }, []); log("No Quickbooks product group endpoint. Deferring to GetProductSimpleFromQuery"); try { // Modified date range query if (payload.doc.modifiedDateRange) { GetProductGroupsByTimeRange(ncUtil, channelProfile, flowContext, payload, callback, {}); } else if (payload.doc.searchFields) { // Search fields query GetAllProductsInGroup(ncUtil, channelProfile, flowContext, payload, function (msg) { if (msg.ncStatusCode === 200) { // Add the productGroupBusinessReference msg.payload.productGroupBusinessReference = extractBusinessReference(channelProfile.productGroupBusinessReferences, msg.payload.doc.Items[0]); // Turn the payload in to an array msg.payload = [msg.payload]; } callback(msg); }); } } catch (err) { logError("Exception occurred in GetProductGroupFromQuery - err" + err); out.ncStatusCode = 500; out.payload.error = { err: err, stack: err.stackTrace }; callback(out); } } else { log("Callback with an invalid request"); out.ncStatusCode = 400; out.payload.error = invalidMsg; callback(out); } }; /** * Retrieves all product groups which have changed in the given time range. * * Paging is handled internally. The callback function may be called multiple times. * * Payload is expected to be a `modifiedTimeRange` query * * Ex: * { * doc: { * modifiedDateRange: { * startDateGMT: '2017-05-12T10:00:00.000Z', * endDateGMT: '2017-05-12T12:00:00.000Z' * }, * page: 1, * pageSize: 25 * } * } * * @param ncUtil * @param channelProfile * @param flowContext * @param payload * @param callback * @param cache */ function GetProductGroupsByTimeRange(ncUtil, channelProfile, flowContext, payload, callback, cache) { product.GetProductSimpleFromQuery(ncUtil, channelProfile, flowContext, payload, function (msg) { log("Do GetProductGroupFromQuery Callback"); // If GetProduct did not return an error then group the products by the product group BR if (msg.ncStatusCode === 200 || msg.ncStatusCode === 206) { let products = coalescePayloadDocs(msg.payload); let groups = getGroupReferencesSet(products, channelProfile.productGroupBusinessReferences); getFullGroups(groups, cache, function (msg) { callback(msg); }); } else { // Otherwise leave the msg un-altered callback(msg); } if (msg.ncStatusCode === 206) { payload.doc.page += 1; GetProductGroupsByTimeRange(ncUtil, channelProfile, flowContext, payload, callback, cache); } }); /** * Get the entire product group for each group uniquely identified in `groups` * * @param groups - dictionary of productGroupBusinessReferences and key-value pairs. See `getGroupReferencesSet` * @param cache - object containing the businessReferences of already processed groups * @param callback - function called once all groups have processed * @param groupNames - keys in the `groups` dictionary; defaults to Object.keys(groups) * @param accumulator - accumulator for processed groups; defaults to [] */ function getFullGroups(groups, cache, callback, groupNames = Object.keys(groups), accumulator = []) { if (groupNames.length === 0) { let res = { ncStatusCode: accumulator.length > 0 ? 200 : 204, payload: accumulator }; callback(res); } else { let groupName = groupNames.pop(); if (!cache[groupName]) { let groupQueryPayload = buildQueryPayload(groups[groupName]); groupQueryPayload.doc.pageSize = payload.doc.pageSize; GetAllProductsInGroup(ncUtil, channelProfile, flowContext, groupQueryPayload, function (msg) { if (msg.ncStatusCode === 200) { msg.payload.productGroupBusinessReference = groupName; msg.payload.productGroupRemoteID = msg.payload.doc.Items[0].Item.Id; accumulator.push(msg.payload); cache[groupName] = true; getFullGroups(groups, cache, callback, groupNames, accumulator); } else { callback(msg); } }); } else { getFullGroups(groups, cache, callback, groupNames, accumulator); } } } } /** * Get the entire product group. i.e. an array of the all products with matching key-value pairs (BRs) * * Paging is handled internally to retrieve all products in the group. * * Payload is expected to be a `searchFields` query. * * Ex: * { * doc: { * searchFields: [{ * searchField: 'Name', * searchValues: ['Office Supplies'] * }], * page: 1, * pageSize: 25 * } * } * * @param ncUtil * @param channelProfile * @param flowContext * @param payload * @param callback */ function GetAllProductsInGroup(ncUtil, channelProfile, flowContext, payload, callback) { queryForGroup([], payload, callback); function queryForGroup(group, payload, callback) { product.GetProductSimpleFromQuery(ncUtil, channelProfile, flowContext, payload, function (msg) { if (msg.ncStatusCode === 200 || msg.ncStatusCode === 206) { group = group.concat(coalescePayloadDocs(msg.payload)) } if (msg.ncStatusCode === 206) { payload.doc.page += 1; queryForGroup(group, payload, callback); } else if (msg.ncStatusCode === 200 || msg.ncStatusCode === 204) { let res = { ncStatusCode: group.length > 0 ? 200 : 204, payload: { doc: {Items: group} } }; callback(res); } else { callback(msg); } }); } } /** * Given an array of payloads, returns an array of <payload.doc> * * Ex: Converts this payload * [ * { * doc: {<doc1>}, * productBusinessReference: ..., * productRemoteID: ... * }, * { * doc: {<doc2>}, * productBusinessReference: ..., * productRemoteID: ... * }, * ... * ] * * into this * [ * {<doc1>}, * {<doc2>}, * ... * ] * * @param payload */ function coalescePayloadDocs(payload) { return payload.reduce((group, payload) => { group.push(payload.doc); return group; }, []); } /** * Given a dictionary of key-value pairs (businessReference-value), constructs a `searchFields` query document. * * @param brMap - a map of businessReference key-value pairs * @returns {{doc: {searchFields: Array, page: number}}} */ function buildQueryPayload(brMap) { let payload = { doc: { searchFields: [], page: 1 } }; Object.keys(brMap).forEach((field) => { let searchField = { searchField: field, searchValues: [brMap[field]] }; payload.doc.searchFields.push(searchField); }); return payload; } /** * Returns a dictionary of productGroupBusinessReferences and key-value pairs * * Ex: * { * 'Office Supplies.1111': { * 'Name': 'Office Supplies', * 'Sku': '1111' * }, * 'School Supplies.2222': { * 'Name': 'School Supplies', * 'Sku': '2222' * }, * ... * } * * @param products - an array of products * @param businessReferences - keys used to extract the productGroupBusinessReference */ function getGroupReferencesSet(products, businessReferences) { return products.reduce((groups, item) => { let values = []; let brMap = {}; businessReferences.forEach((businessReference) => { let expression = jsonata(businessReference); let value = expression.evaluate(item); values.push(value); brMap[businessReference.split('.').pop()] = value; }); let groupName = values.join('.'); if (!groups[groupName]) { groups[groupName] = brMap; } return groups; }, {}); } function logError(msg) { console.log("[error] " + msg); } function log(msg) { console.log("[info] " + msg); } module.exports.GetProductGroupFromQuery = GetProductGroupFromQuery; <file_sep>/functions/UpdateProductPricing.js 'use strict'; let extractBusinessReference = require('../util/extractBusinessReference'); let request = require('request'); let UpdateProductPricing = function ( ncUtil, channelProfile, flowContext, payload, callback) { log("Building response object..."); let out = { ncStatusCode: null, response: {}, payload: {} }; let invalid = false; let invalidMsg = ""; //If channelProfile does not contain channelSettingsValues, channelAuthValues or productPricingBusinessReferences, the request can't be sent if (!channelProfile) { invalid = true; invalidMsg = "channelProfile was not provided" } else if (!channelProfile.channelSettingsValues) { invalid = true; invalidMsg = "channelProfile.channelSettingsValues was not provided" } else if (!channelProfile.channelSettingsValues.protocol) { invalid = true; invalidMsg = "channelProfile.channelSettingsValues.protocol was not provided" } else if (!channelProfile.channelSettingsValues.api_uri) { invalid = true; invalidMsg = "channelProfile.channelSettingsValues.api_uri was not provided" } else if (!channelProfile.channelSettingsValues.minor_version) { invalid = true; invalidMsg = "channelProfile.channelSettingsValues.minor_version was not provided"; } else if (!channelProfile.channelAuthValues) { invalid = true; invalidMsg = "channelProfile.channelAuthValues was not provided" } else if (!channelProfile.channelAuthValues.access_token) { invalid = true; invalidMsg = "channelProfile.channelAuthValues.access_token was not provided" } else if (!channelProfile.channelAuthValues.realm_id) { invalid = true; invalidMsg = "channelProfile.channelAuthValues.realm_id was not provided" } else if (!channelProfile.productPricingBusinessReferences) { invalid = true; invalidMsg = "channelProfile.productPricingBusinessReferences was not provided" } else if (channelProfile.productPricingBusinessReferences.length === 0) { invalid = true; invalidMsg = "channelProfile.productPricingBusinessReferences is empty" } //If a productDocument or productPricingRemoteID was not passed in, the request is invalid if (!payload) { invalid = true; invalidMsg = "payload was not provided" } else if (!payload.doc) { invalid = true; invalidMsg = "payload.doc was not provided" } else if (!payload.doc.Item) { invalid = true; invalidMsg = "payload.doc.Item was not provided" } else if (!payload.productPricingRemoteID) { invalid = true; invalidMsg = "payload.productPricingRemoteID was not provided" } //If callback is not a function if (!callback) { throw new Error("A callback function was not provided"); } else if (typeof callback !== 'function') { throw new TypeError("callback is not a function") } if (!invalid) { // Create endpoint let minorVersion = "?minorversion=" + channelProfile.channelSettingsValues.minor_version; let endPoint = "/company/" + channelProfile.channelAuthValues.realm_id + "/item"; let url = channelProfile.channelSettingsValues.protocol + "://" + channelProfile.channelSettingsValues.api_uri + endPoint; // Set headers let headers = { "Authorization": "Bearer " + channelProfile.channelAuthValues.access_token }; log("Using URL [" + url + "]"); // Set ID and minor version let readUrl = url + "/" + payload.productPricingRemoteID + minorVersion; let readOptions = { url: readUrl, method: "GET", headers: headers, json: true }; // Query the product request(readOptions, function (error, response, read) { try { if (!error) { if (response.statusCode === 200) { log("Do UpdateProductPricing Callback"); out.response.endpointStatusCode = response.statusCode; out.response.endpointStatusMessage = response.statusMessage; let readData = JSON.parse(JSON.stringify(read)); // Get the SyncToken /* Quickbooks Online expects a SyncToken to be passed in with body of the update (i.e. "1") Querying for the product will give us the most recent SyncToken that can be used with the update Not providing the SyncToken or using a previously used SyncToken will return an error Quickbooks will automatically increment the SyncToken on each update */ let syncToken = parseInt(readData.Item.SyncToken); // Add productPricingRemoteID to Id of doc as it's required for this function payload.doc.Item.Id = payload.productPricingRemoteID; // Set the SyncToken payload.doc.Item.SyncToken = syncToken; // Remove Item Wrapper let item = payload.doc.Item; // Set sparse to true to do a partial update (product pricing is a subset of product) item.sparse = true; let options = { url: url + minorVersion, method: "POST", headers: headers, body: item, json: true }; // Pass in our URL and headers request(options, function (error, response, body) { try { if (!error) { out.response.endpointStatusCode = response.statusCode; out.response.endpointStatusMessage = response.statusMessage; // Parse data let data = JSON.parse(JSON.stringify(body)); // If we have a product object, set product.payload.doc to be the product document if (data && response.statusCode === 200) { out.payload = { "productPricingBusinessReference": extractBusinessReference(channelProfile.productPricingBusinessReferences, data) }; out.ncStatusCode = 200; } else if (response.statusCode === 429) { out.ncStatusCode = 429; out.payload.error = data; } else if (response.statusCode === 500) { out.ncStatusCode = 500; out.payload.error = data; } else { out.ncStatusCode = 400; out.payload.error = data; } callback(out); } else { logError("Do UpdateProductPricing Callback error - " + error); out.payload.error = {err: error}; out.ncStatusCode = 400; callback(out); } } catch (err) { logError("Exception occurred in UpdateProductPricing - " + err); out.ncStatusCode = 500; out.payload.error = {err: err, stack: err.stackTrace}; callback(out); } }); } else if (response.statusCode === 429) { out.ncStatusCode = 429; out.payload.error = {err: read}; callback(out); } else if (response.statusCode === 500) { out.ncStatusCode = 500; out.payload.error = {err: read}; callback(out); } else { out.ncStatusCode = 400; out.payload.error = {err: read}; callback(out); } } else { logError("Do UpdateProductPricing Callback error - " + error); out.payload.error = error; out.ncStatusCode = 400; callback(out); } } catch (err) { logError("Exception occurred in UpdateProductPricing - " + err); out.ncStatusCode = 500; out.payload.error = {err: err, stack: err.stackTrace}; callback(out); } }); } else { log("Callback with an invalid request - " + invalidMsg); out.ncStatusCode = 400; out.payload.error = {err: "Callback with an invalid request - " + invalidMsg}; callback(out); } }; function logError(msg) { console.log("[error] " + msg); } function log(msg) { console.log("[info] " + msg); } module.exports.UpdateProductPricing = UpdateProductPricing; <file_sep>/functions/GetSalesOrderFromQuery.js 'use strict'; let extractBusinessReference = require('../util/extractBusinessReference'); let request = require('request'); let GetSalesOrderFromQuery = function ( ncUtil, channelProfile, flowContext, payload, callback) { log("Building response object..."); let out = { ncStatusCode: null, response: {}, payload: {} }; let invalid = false; let invalidMsg = ""; //If channelProfile does not contain channelSettingsValues, channelAuthValues or salesOrderBusinessReferences, the request can't be sent if (!channelProfile) { invalid = true; invalidMsg = "channelProfile was not provided" } else if (!channelProfile.channelSettingsValues) { invalid = true; invalidMsg = "channelProfile.channelSettingsValues was not provided" } else if (!channelProfile.channelSettingsValues.protocol) { invalid = true; invalidMsg = "channelProfile.channelSettingsValues.protocol was not provided" } else if (!channelProfile.channelSettingsValues.api_uri) { invalid = true; invalidMsg = "channelProfile.channelSettingsValues.api_uri was not provided" } else if (!channelProfile.channelSettingsValues.minor_version) { invalid = true; invalidMsg = "channelProfile.channelSettingsValues.minor_version was not provided"; } else if (!channelProfile.channelAuthValues) { invalid = true; invalidMsg = "channelProfile.channelAuthValues was not provided" } else if (!channelProfile.channelAuthValues.access_token) { invalid = true; invalidMsg = "channelProfile.channelAuthValues.access_token was not provided" } else if (!channelProfile.channelAuthValues.realm_id) { invalid = true; invalidMsg = "channelProfile.channelAuthValues.realm_id was not provided" } else if (!channelProfile.salesOrderBusinessReferences) { invalid = true; invalidMsg = "channelProfile.salesOrderBusinessReferences was not provided" } else if (!Array.isArray(channelProfile.salesOrderBusinessReferences)) { invalid = true; invalidMsg = "channelProfile.salesOrderBusinessReferences is not an array" } else if (channelProfile.salesOrderBusinessReferences.length === 0) { invalid = true; invalidMsg = "channelProfile.salesOrderBusinessReferences is empty" } //If a query document was not passed in, the request is invalid if (!payload) { invalid = true; invalidMsg = "payload was not provided" } else if (!payload.doc) { invalid = true; invalidMsg = "payload.doc was not provided"; } else if (!payload.doc.remoteIDs && !payload.doc.searchFields && !payload.doc.modifiedDateRange) { invalid = true; invalidMsg = "either payload.doc.remoteIDs or payload.doc.searchFields or payload.doc.modifiedDateRange must be provided" } else if (payload.doc.remoteIDs && (payload.doc.searchFields || payload.doc.modifiedDateRange)) { invalid = true; invalidMsg = "only one of payload.doc.remoteIDs or payload.doc.searchFields or payload.doc.modifiedDateRange may be provided" } else if (payload.doc.remoteIDs && (!Array.isArray(payload.doc.remoteIDs) || payload.doc.remoteIDs.length === 0)) { invalid = true; invalidMsg = "payload.doc.remoteIDs must be an Array with at least 1 remoteID" } else if (payload.doc.searchFields && (!Array.isArray(payload.doc.searchFields) || payload.doc.searchFields.length === 0)) { invalid = true; invalidMsg = "payload.doc.searchFields must be an Array with at least 1 key value pair: {searchField: 'key', searchValues: ['value_1']}" } else if (payload.doc.searchFields) { for (let i = 0; i < payload.doc.searchFields.length; i++) { if (!payload.doc.searchFields[i].searchField || !Array.isArray(payload.doc.searchFields[i].searchValues) || payload.doc.searchFields[i].searchValues.length === 0) { invalid = true; invalidMsg = "payload.doc.searchFields[" + i + "] must be a key value pair: {searchField: 'key', searchValues: ['value_1']}"; break; } } } else if (payload.doc.modifiedDateRange && !(payload.doc.modifiedDateRange.startDateGMT || payload.doc.modifiedDateRange.endDateGMT)) { invalid = true; invalidMsg = "at least one of payload.doc.modifiedDateRange.startDateGMT or payload.doc.modifiedDateRange.endDateGMT must be provided" } else if (payload.doc.modifiedDateRange && payload.doc.modifiedDateRange.startDateGMT && payload.doc.modifiedDateRange.endDateGMT && (payload.doc.modifiedDateRange.startDateGMT > payload.doc.modifiedDateRange.endDateGMT)) { invalid = true; invalidMsg = "startDateGMT must have a date before endDateGMT"; } //If callback is not a function if (!callback) { throw new Error("A callback function was not provided"); } else if (typeof callback !== 'function') { throw new TypeError("callback is not a function") } if (!invalid) { let minorVersion = "?minorversion=" + channelProfile.channelSettingsValues.minor_version; let endPoint = "/company/" + channelProfile.channelAuthValues.realm_id + "/query" + minorVersion; let url = channelProfile.channelSettingsValues.protocol + "://" + channelProfile.channelSettingsValues.api_uri + endPoint; /* Create query string for searching customers by specific fields */ let queryParams = []; let filterParams = []; if (payload.doc.searchFields) { let fields = []; payload.doc.searchFields.forEach(function (searchField) { // Check fields to get the base property to use in the query if (searchField.searchField !== "MetaData.CreateTime" && searchField.searchField !== "MetaData.LastUpdatedTime") { if (searchField.searchField === "CustomerRef.value") { searchField.searchField = "CustomerRef"; } } // Loop through each value let values = []; searchField.searchValues.forEach(function (searchValue) { values.push("'" + searchValue + "'"); }); fields.push(searchField.searchField + " IN (" + values.join(',') + ")"); }); filterParams.push(fields.join(' AND ')); } else if (payload.doc.remoteIDs) { /* Add remote IDs as a query parameter */ let ids = []; payload.doc.remoteIDs.forEach((remoteID) => { ids.push("'" + remoteID + "'"); }); filterParams.push("Id IN (" + ids.join(',') + ")"); } else if (payload.doc.modifiedDateRange) { /* Add modified date ranges to the query */ if (payload.doc.modifiedDateRange.startDateGMT) { filterParams.push("MetaData.LastUpdatedTime >= '" + payload.doc.modifiedDateRange.startDateGMT + "'"); } if (payload.doc.modifiedDateRange.endDateGMT) { filterParams.push("MetaData.LastUpdatedTime <= '" + payload.doc.modifiedDateRange.endDateGMT + "'"); } } // Format the 'filter' query parameter queryParams.push(filterParams.join(' AND ')); /* Add page to the query */ let startDoc = (payload.doc.page - 1) * payload.doc.pageSize; if (payload.doc.page) { if (startDoc > 0) { queryParams.push("STARTPOSITION " + startDoc); } } /* Add pageSize (limit) to the query */ if (payload.doc.pageSize) { queryParams.push("MAXRESULTS " + payload.doc.pageSize); } /* Format the query parameters and append them to the url */ url += "&query=SELECT * FROM SalesReceipt WHERE " + queryParams.join(' '); log("Using URL [" + url + "]"); // Add the authorization header let headers = { "Authorization": "Bearer " + channelProfile.channelAuthValues.access_token, "Accept": "application/json" }; /* Set URL and headers */ let options = { url: url, headers: headers, json: true }; // Pass in our URL and headers request(options, function (error, response, body) { try { if (!error) { log("Do GetSalesOrderFromQuery Callback"); out.response.endpointStatusCode = response.statusCode; out.response.endpointStatusMessage = response.statusMessage; // Parse data let docs = []; let data = body; if (response.statusCode === 200) { // If we have an array of orders, set out.payload to be the array of orders returned if (data.QueryResponse.SalesReceipt && data.QueryResponse.SalesReceipt.length > 0) { for (let i = 0; i < data.QueryResponse.SalesReceipt.length; i++) { let order = data.QueryResponse.SalesReceipt[i]; docs.push({ doc: order, salesOrderRemoteID: order.Id, salesOrderBusinessReference: extractBusinessReference(channelProfile.salesOrderBusinessReferences, order) }); } if (docs.length === payload.doc.pageSize) { out.ncStatusCode = 206; } else { out.ncStatusCode = 200; } out.payload = docs; } else { out.ncStatusCode = 204; out.payload = data; } } else if (response.statusCode === 429) { out.ncStatusCode = 429; out.payload.error = data; } else if (response.statusCode === 500) { out.ncStatusCode = 500; out.payload.error = data; } else { out.ncStatusCode = 400; out.payload.error = data; } callback(out); } else { logError("Do GetSalesOrderFromQuery Callback error - " + error); out.ncStatusCode = 500; out.payload.error = error; callback(out); } } catch (err) { logError("Exception occurred in GetSalesOrderFromQuery - err" + err); out.ncStatusCode = 500; out.payload.error = { err: err, stack: err.stackTrace }; callback(out); } }); } else { log("Callback with an invalid request - " + invalidMsg); out.ncStatusCode = 400; out.payload.error = invalidMsg; callback(out); } }; function logError(msg) { console.log("[error] " + msg); } function log(msg) { console.log("[info] " + msg); } module.exports.GetSalesOrderFromQuery = GetSalesOrderFromQuery;
118c116650e998adc5300c2fa62022963695940d
[ "JavaScript" ]
5
JavaScript
nChannelIO/quickbooks-online-channel
eb5d5cbb8368b81602ca563b9154d2fee4bb92cc
ac0f5660b19450a04e0ba32c5b2eecd18a32867f
refs/heads/master
<repo_name>ftsujikawa/rust-the-book<file_sep>/loops/src/main.rs fn main() { // loop { // println!("again!"); // } // for number in (1..4).rev() { // println!("{}!", number); // } // println!("LIFTOFF!!!"); for number in 1..4 { println!("{}!", number); } println!("LIFTOFF!!!"); } <file_sep>/ch08/p147/src/main.rs fn main() { let v = vec![1,2,3,4,5]; let third: &i32 = &v[100]; // カーネルパニック println!("third is {}", third); let third: Option<&i32> = v.get(100);// None println!("third is {:?}", third); } <file_sep>/ch10/list10-16/src/main.rs use list10_16::Pair; fn main() { let n = Pair::new(10, 50); n.cmp_display(); } <file_sep>/ch08/ren3/src/main.rs use std::collections::HashMap; fn main() { let texts = vec![ "Add Sally to Engineering", "Add tsu to Sales", "Add Amir to Sales", ]; let mut map: HashMap<&str, Vec<&str>> = HashMap::new(); for text in texts { let mut i = 0; let mut key = ""; let mut val = ""; for x in text.split_whitespace() { if i == 1 { val = x; } else if i == 3 { key = x; } i += 1; } let names = map.entry(&key).or_insert(Vec::new()); names.push(val); names.sort(); } for (section, names) in &map { print!("{}: ", section); for name in names { print!("{} ", name); } println!(""); } } <file_sep>/ch08/p157/src/main.rs fn main() { let hello = "こんにちは"; let s = &hello[0..3]; println!("s is {}", s); for c in hello.chars() { println!("{}", c); } } <file_sep>/ch08/ren2/src/main.rs fn main() { let word = "first"; let word = "apple"; let first = word.chars().next(); //println!("{:?}", first); let result = match first { Some('a') => format!("{}-hay", word), Some('i') => format!("{}-hay", word), Some('u') => format!("{}-hay", word), Some('e') => format!("{}-hay", word), Some('o') => format!("{}-hay", word), Some(x) => format!("{}-{}ay", &word[1..], x), None => format!("{}", word), }; println!("{}", result); } <file_sep>/ch09/p170/src/main.rs use std::fs::File; fn main() { let f:u32 = File::open("hello.txt"); } <file_sep>/ch08/list8-12/src/main.rs fn main() { let data = "initial contents"; let s = data.to_string(); let s = "initial contents".to_string(); let s = String::from("initial contents"); println!("{}", s); } <file_sep>/ch08/p146/src/main.rs fn main() { let v = vec![1,2,3,4,5]; let third: &i32 = &v[2]; println!("third is {}", third); let third: Option<&i32> = v.get(2); println!("third is {:?}", third); } <file_sep>/ch08/ren1/src/main.rs use std::collections::HashMap; fn main() { let mut v = vec![23, 53, 12, 62, 35, 98, 71, 31, 12]; let mut t = 0; for i in &v { t += i; } println!("mean is {}", t / v.len()); v.sort(); println!("v is {:?}", v); println!("median is {}", v[v.len() / 2]); let mut map = HashMap::new(); for val in &v { let count = map.entry(val).or_insert(0); *count += 1; } println!("{:?}", map); let mut max = 0; let mut k: &&usize = &&0; for (key, val) in &map { if max < *val { k = key; max = *val; } } println!("mode is {}", k); } <file_sep>/ch06/p109/src/main.rs enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(i32, i32, i32), } impl Message { fn call(&self) { } } fn main() { let msg = Message::Move { x: 10, y: 20}; msg.call(); let m = Message::Write(String::from("hello")); m.call(); } <file_sep>/ch11/list11-10/src/lib.rs fn print_and_returns_10(a: i32) -> i32 { println!("I got the value {}", a); 10 } #[cfg(test)] mod tests { use super::*; #[test] fn this_test_will_pass() { let value = print_and_returns_10(4); assert_eq!(10, value); } #[test] fn this_test_will_fail() { let value = print_and_returns_10(8); assert_eq!(5, value); } }
24890cefa4cad90cec389599ba1d09ea3fcc9c8f
[ "Rust" ]
12
Rust
ftsujikawa/rust-the-book
88a2f98e0c6c619c712b5c2616bf9670cea86fef
73c7782c3029204cef80b3c290c1923f172ee185
refs/heads/master
<repo_name>nguyenvanthuong0201/XetTuyen-GDU<file_sep>/XetTuyen-GDU/XetTuyen-GDU/View/frmHome.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using DevExpress.XtraEditors; using DevExpress.XtraPrinting; using DevExpress.Export; namespace XetTuyen_GDU.View { public partial class frmHome : DevExpress.XtraBars.Ribbon.RibbonForm { public frmHome() { InitializeComponent(); setVisibleTuyenSinh(false); setVisibleDaoTao(false); setVisibleKeToan(false); } void navBarControl_ActiveGroupChanged(object sender, DevExpress.XtraNavBar.NavBarGroupEventArgs e) { navigationFrame.SelectedPageIndex = navBarControl.Groups.IndexOf(e.Group); if(navigationFrame.SelectedPageIndex == 0) { setVisibleAdmin(true); setVisibleTuyenSinh(false); setVisibleDaoTao(false); setVisibleKeToan(false); } else if (navigationFrame.SelectedPageIndex == 1) { setVisibleTuyenSinh(true); setVisibleDaoTao(false); setVisibleKeToan(false); setVisibleAdmin(false); } else if (navigationFrame.SelectedPageIndex == 2) { setVisibleAdmin(false); setVisibleTuyenSinh(false); setVisibleDaoTao(true); setVisibleKeToan(false); } else if (navigationFrame.SelectedPageIndex == 3) { setVisibleAdmin(false); setVisibleTuyenSinh(false); setVisibleDaoTao(false); setVisibleKeToan(true); } } void barButtonNavigation_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { int barItemIndex = barSubItemNavigation.ItemLinks.IndexOf(e.Link); navBarControl.ActiveGroup = navBarControl.Groups[barItemIndex]; } public void setVisibleAdmin(bool status) { AdminAbout.Visible = status; AdminHome.Visible = status; AdminManage.Visible = status; } public void setVisibleTuyenSinh(bool status) { PageCategoryPhongTuyenSinh.Visible = status; } public void setVisibleDaoTao(bool status) { PageCategoryPhongKeToan.Visible = status; } public void setVisibleKeToan(bool status) { PageCategoryPhongDaoTao.Visible = status; } private void btnXuatFileExcel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { ExportExcel(""); } private bool ExportExcel(string filename) { try { if (gridViewKeToan.FocusedRowHandle < 0) { } else { var dialog = new SaveFileDialog(); dialog.Title = @"Export file excel"; dialog.FileName = filename; dialog.Filter = @"Microsoft Excel|.xlsx"; if (dialog.ShowDialog() == DialogResult.OK) { gridViewKeToan.ColumnPanelRowHeight = 40; gridViewKeToan.OptionsPrint.AutoWidth = AutoSize; gridViewKeToan.OptionsPrint.ShowPrintExportProgress = true; gridViewKeToan.OptionsPrint.AllowCancelPrintExport = true; XlsxExportOptions options = new XlsxExportOptions(); options.TextExportMode = TextExportMode.Text; options.ExportMode = XlsxExportMode.SingleFile; options.SheetName = @"Sheet1"; ExportSettings.DefaultExportType = ExportType.Default; gridViewKeToan.ExportToXlsx(dialog.FileName, options); XtraMessageBox.Show("Thành Công !!!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } catch (Exception e) { XtraMessageBox.Show("Lỗi: " + e, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } return false; } private void btnDongKT_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { this.Close(); } private void btnDongDT_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { this.Close(); } } }
83f1bf6eadec354f087bfaf8ba1335a082f8137f
[ "C#" ]
1
C#
nguyenvanthuong0201/XetTuyen-GDU
22392b2fcea59de2c065dd168c53d09713524eb4
07060734345a7a5d9f67f87593b21cef80e13725
refs/heads/master
<repo_name>frangucc/gnaf<file_sep>/README.md # gnaf # Those are two different parts that I'm working on. The website.zip contains a basic index.html page which can contain different tabs at # the top for an admin user to view different customer's graphs. The login-system1.zip contains a login/registration page index.php which # handles logging in and registering. Neither are finished but they are some things. I might not use that login system, but I'm tinkering # around with it trying to figure out how to make it work, it didn't work even though it was claimed to be working by a tutorial on it.<file_sep>/login-system/db.php <?php /* Database connection settings */ $host = 'mysql.itemlids.dreamhosters.com'; $user = 'user199'; $pass = '<PASSWORD>'; $db = 'accounts1'; $mysqli = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
be7f25af04e92b7a51f8f6e52ccc207a84d49f37
[ "Markdown", "PHP" ]
2
Markdown
frangucc/gnaf
12424f7d0e7bb3e8ac71ab7e85858abca83ca440
cc7526b33c250caf3c9920df945d9e88f0ddb682
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ClubOneAdmin { public partial class ClassesManageForm : Form { public string action; public string classID, className, facility, tutor, timeslot, day, price; public ClassesManageForm() { InitializeComponent(); } private void ClassesManageForm_Load(object sender, EventArgs e) { this.Text = action; lbTitle.Text = action + " Class"; loadFacility(); loadTutor(); loadDay(); if (action.Equals("Add")) { //btnInsert.Visible = true; btnUpdate.Visible = false; btnReset.Visible = false; } else if (action.Equals("Edit")) { btnInsert.Visible = false; //btnUpdate.Visible = true; populateEditingData(); } } private void loadFacility() { SqlConnection sqlConnection = new SqlConnection("Server=LAPTOP-SMQPLLME\\SQLEXPRESS; UId=admin1; Password=<PASSWORD>; " + "Database=clubone;"); sqlConnection.Open(); SqlCommand cmd = new SqlCommand("select fID, fName from Facility", sqlConnection); IDataAdapter adapter = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); adapter.Fill(ds); //create a row DataRow defaultRow = ds.Tables[0].NewRow(); //insert the default value to the row defaultRow[0] = 0; defaultRow[1] = "--SELECT Facility--"; //insert the default row into the ds ds.Tables[0].Rows.InsertAt(defaultRow, 0); cmbFacility.DataSource = ds.Tables[0].DefaultView; cmbFacility.DisplayMember = "fName"; cmbFacility.ValueMember = "fID"; sqlConnection.Close(); } private void loadTutor() { SqlConnection sqlConnection = new SqlConnection("Server=LAPTOP-SMQPLLME\\SQLEXPRESS; UId=admin1; Password=<PASSWORD>; " + "Database=clubone;"); sqlConnection.Open(); SqlCommand cmd = new SqlCommand("select tID, name from Tutor", sqlConnection); IDataAdapter adapter = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); adapter.Fill(ds); //create a row DataRow defaultRow = ds.Tables[0].NewRow(); //insert the default value to the row defaultRow[0] = 0; defaultRow[1] = "--SELECT Tutor--"; //insert the default row into the ds ds.Tables[0].Rows.InsertAt(defaultRow, 0); cmbTutor.DataSource = ds.Tables[0].DefaultView; cmbTutor.DisplayMember = "name"; cmbTutor.ValueMember = "tID"; sqlConnection.Close(); } private void loadDay() { cmbDay.DisplayMember = "Text"; cmbDay.ValueMember = "Value"; var items = new[] { new { Text = "--SELECT Day--", Value = "0" }, new { Text = "Sunday", Value = "Sunday" }, new { Text = "Monday", Value = "Monday" }, new { Text = "Tuesday", Value = "Tuesday" }, new { Text = "Wednesday", Value = "Wednesday" }, new { Text = "Thursday", Value = "Thursday" }, new { Text = "Friday", Value = "Friday" }, new { Text = "Saturday", Value = "Saturday" } }; cmbDay.DataSource = items; } private void btnReset_Click(object sender, EventArgs e) { populateEditingData(); } private void ClassesManageForm_FormClosing(object sender, FormClosingEventArgs e) { this.Hide(); } private void populateEditingData() { tbID.Text = classID; tbClass.Text = className; cmbFacility.SelectedIndex = cmbFacility.FindString(facility); cmbTutor.SelectedIndex = cmbTutor.FindString(tutor); tbTimeslot.Text = timeslot; cmbDay.SelectedIndex = cmbDay.FindString(day); numPrice.Value = Convert.ToInt32(price); } private void btnUpdate_Click(object sender, EventArgs e) { string message, title; if ((int)cmbFacility.SelectedValue == 0) { message = "Please select a facility"; title = "Insert Fail"; MessageBox.Show(message, title); } else if ((int)cmbTutor.SelectedValue == 0) { message = "Please select a Tutor"; title = "Insert Fail"; MessageBox.Show(message, title); } else if ((string)cmbDay.SelectedValue == "0") { message = "Please select a Day"; title = "Insert Fail"; MessageBox.Show(message, title); } if ((int)cmbFacility.SelectedValue != 0 && (int)cmbTutor.SelectedValue != 0 && (string)cmbDay.SelectedValue != "0") { SqlConnection sqlConnection = new SqlConnection("Server=LAPTOP-SMQPLLME\\SQLEXPRESS; UId=admin1; Password=<PASSWORD>; " + "Database=clubone;"); sqlConnection.Open(); SqlCommand sqlCommand = new SqlCommand("update TrainingClass " + "set className = @C , facilityID = @FID, tutorID = @TID, timeSlot = @TS," + " days = @D, price = @P " + "where tcID = @ID", sqlConnection); sqlCommand.Parameters.AddWithValue("@C", tbClass.Text); sqlCommand.Parameters.AddWithValue("@FID", cmbFacility.SelectedValue); sqlCommand.Parameters.AddWithValue("@TID", cmbTutor.SelectedValue); sqlCommand.Parameters.AddWithValue("@TS", tbTimeslot.Text); sqlCommand.Parameters.AddWithValue("@D", cmbDay.SelectedValue); sqlCommand.Parameters.AddWithValue("@P", numPrice.Value); sqlCommand.Parameters.AddWithValue("@ID", tbID.Text); int success = sqlCommand.ExecuteNonQuery(); if (success != 0) { message = "success"; title = "Operation"; MessageBox.Show(message, title); this.DialogResult = DialogResult.OK; } sqlConnection.Close(); } } private void btnCancel_Click(object sender, EventArgs e) { this.Hide(); } private void btnInsert_Click(object sender, EventArgs e) { string message = ""; string title = ""; if ((int)cmbFacility.SelectedValue == 0) { message = "Please select a facility"; title = "Insert Fail"; MessageBox.Show(message, title); } else if ((int)cmbTutor.SelectedValue == 0) { message = "Please select a Tutor"; title = "Insert Fail"; MessageBox.Show(message, title); } else if ((string)cmbDay.SelectedValue == "0") { message = "Please select a Day"; title = "Insert Fail"; MessageBox.Show(message, title); } if ((int)cmbFacility.SelectedValue != 0 && (int)cmbTutor.SelectedValue != 0 && (string)cmbDay.SelectedValue != "0") { SqlConnection sqlConnection = new SqlConnection("Server=LAPTOP-SMQPLLME\\SQLEXPRESS; UId=admin1; Password=<PASSWORD>; " + "Database=clubone;"); sqlConnection.Open(); SqlCommand sqlCommand = new SqlCommand("insert into TrainingClass " + "(className, facilityID, tutorID, timeSlot, days, price) " + "values (@C, @FID, @TID, @TS, @D, @P)", sqlConnection); sqlCommand.Parameters.AddWithValue("@C", tbClass.Text); sqlCommand.Parameters.AddWithValue("@FID", cmbFacility.SelectedValue); sqlCommand.Parameters.AddWithValue("@TID", cmbTutor.SelectedValue); sqlCommand.Parameters.AddWithValue("@TS", tbTimeslot.Text); sqlCommand.Parameters.AddWithValue("@D", cmbDay.SelectedValue); sqlCommand.Parameters.AddWithValue("@P", numPrice.Value); int success = sqlCommand.ExecuteNonQuery(); if (success != 0) { message = "success"; title = "Operation"; MessageBox.Show(message, title); this.DialogResult = DialogResult.OK; } sqlConnection.Close(); } } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ClubOneAdmin { public partial class FormFacilities : Form { public FormFacilities() { InitializeComponent(); } private void FormFacilities_Load(object sender, EventArgs e) { loadFacilityData(); } private void loadFacilityData() { SqlConnection sqlConnection = new SqlConnection("Server=LAPTOP-SMQPLLME\\SQLEXPRESS; UId=admin1; Password=<PASSWORD>; " + "Database=clubone;"); sqlConnection.Open(); SqlCommand cmd = new SqlCommand("select * from Facility", sqlConnection); IDataAdapter adapter = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); adapter.Fill(ds); sqlConnection.Close(); for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { FacilityItem fitem = new FacilityItem(); fitem.fID = ds.Tables[0].Rows[i][0].ToString(); fitem.ItemLabel = ds.Tables[0].Rows[i][1].ToString(); fitem.Availability = ds.Tables[0].Rows[i][2].ToString(); fitem.Capacity = ds.Tables[0].Rows[i][3].ToString(); fitem.ItemImage = ConvertBytesToImage((byte[])ds.Tables[0].Rows[i][4]); flowpnlFacilities.Controls.Add(fitem); fitem.MouseClick += new MouseEventHandler(this.facilityEvent); } } void facilityEvent(object sender, MouseEventArgs e) { FacilityItem currentItem = (FacilityItem)sender; //show dialog FacilityManagementForm fmForm = new FacilityManagementForm(); fmForm.fID = currentItem.fID; fmForm.facility = currentItem.ItemLabel; fmForm.availability = currentItem.Availability; fmForm.capacity = currentItem.Capacity; fmForm.image = currentItem.ItemImage; fmForm.action = "Edit"; if (fmForm.ShowDialog() == DialogResult.OK) { this.Controls.Clear(); InitializeComponent(); FormFacilities_Load(null, EventArgs.Empty); } } private void panel2_Paint(object sender, PaintEventArgs e) { } public Image ConvertBytesToImage(byte[] data) { using (MemoryStream ms = new MemoryStream(data)) return Image.FromStream(ms); } private void btnAddFacility_Click(object sender, EventArgs e) { FacilityManagementForm fmForm = new FacilityManagementForm(); fmForm.action = "Add"; if (fmForm.ShowDialog() == DialogResult.OK) { this.Controls.Clear(); InitializeComponent(); FormFacilities_Load(null, EventArgs.Empty); } } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ClubOneAdmin { public partial class FormTrainingClasses : Form { public FormTrainingClasses() { InitializeComponent(); } private void FormTrainingClasses_Load(object sender, EventArgs e) { SqlConnection sqlConnection = new SqlConnection("Server=LAPTOP-SMQPLLME\\SQLEXPRESS; UId=admin1; Password=<PASSWORD>; " + "Database=clubone;"); sqlConnection.Open(); SqlCommand cmd = new SqlCommand("select fID, fName from Facility", sqlConnection); IDataAdapter adapter = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); adapter.Fill(ds); //create a row DataRow defaultRow = ds.Tables[0].NewRow(); //insert the default value to the row defaultRow[0] = 0; defaultRow[1] = "--All--"; //insert the default row into the ds ds.Tables[0].Rows.InsertAt(defaultRow, 0); cmbFacilities.DataSource = ds.Tables[0].DefaultView; cmbFacilities.DisplayMember = "fName"; cmbFacilities.ValueMember = "fID"; sqlConnection.Close(); //add a checkbox to first column dgvTrainingClass.Columns.Add(new DataGridViewCheckBoxColumn()); dgvLoadTrainingClass(); } private void panel1_Paint(object sender, PaintEventArgs e) { } private void cmbFacilities_SelectedValueChanged(object sender, EventArgs e) { } private void cmbFacilities_SelectionChangeCommitted(object sender, EventArgs e) { dgvLoadTrainingClass(); } private void dgvLoadTrainingClass() { SqlConnection sqlConnection = new SqlConnection("Server=LAPTOP-SMQPLLME\\SQLEXPRESS; UId=admin1; Password=<PASSWORD>; " + "Database=clubone;"); sqlConnection.Open(); SqlCommand cmd; //select all traning classes if ((int)cmbFacilities.SelectedValue == 0) { cmd = new SqlCommand("select tcID, className, fc.fName, tt.name, timeSlot, days, price " + "from TrainingClass tc " + "inner join Facility fc on tc.facilityID = fc.fID " + "left join Tutor tt on tc.tutorID = tt.tID ", sqlConnection); } else //select training classes corresponding to the selected facility { string fid = cmbFacilities.SelectedValue.ToString(); cmd = new SqlCommand("select tcID, className, fc.fName, tt.name, timeSlot, days, price " + "from TrainingClass tc " + "inner join Facility fc on tc.facilityID = fc.fID " + "left join Tutor tt on tc.tutorID = tt.tID " + "where facilityID = @FID", sqlConnection); cmd.Parameters.AddWithValue("@FID", fid); } IDataAdapter adapter = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); adapter.Fill(ds); dgvTrainingClass.DataSource = ds.Tables[0].DefaultView; dgvTrainingClass.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; dgvTrainingClass.Columns[0].Width = 50; dgvTrainingClass.Columns[1].Width = 60; //set header text dgvTrainingClass.Columns[1].HeaderText = "ID"; dgvTrainingClass.Columns[2].HeaderText = "CLASS"; dgvTrainingClass.Columns[3].HeaderText = "LOCATION"; dgvTrainingClass.Columns[4].HeaderText = "TUTOR"; dgvTrainingClass.Columns[5].HeaderText = "TIMESLOT"; dgvTrainingClass.Columns[6].HeaderText = "DAY"; dgvTrainingClass.Columns[7].HeaderText = "PRICE"; dgvTrainingClass.Columns[7].Width = 100; } private void btnAddClass_Click(object sender, EventArgs e) { ClassesManageForm cmf = new ClassesManageForm(); cmf.action = "Add"; if(cmf.ShowDialog() == DialogResult.OK) { dgvLoadTrainingClass(); } } private string classID = "0", className, facility, tutor, timeSlot, day, price; private void btnDeleteClass_Click(object sender, EventArgs e) { string message = "Are You Sure to Remove Selected Training Class?"; string caption = "Remove Training Class"; MessageBoxButtons buttons = MessageBoxButtons.YesNo; DialogResult result; // Displays the MessageBox. result = MessageBox.Show(message, caption, buttons); if (result == DialogResult.Yes) { SqlConnection sqlConnection = new SqlConnection("Server=LAPTOP-SMQPLLME\\SQLEXPRESS; UId=admin1; Password=<PASSWORD>; " + "Database=clubone;"); sqlConnection.Open(); SqlCommand sqlCommand; bool checkPoint = false; for (int i = 0; i < dgvTrainingClass.Rows.Count; i++) { sqlCommand = new SqlCommand("delete from TrainingClass where tcID = @ID", sqlConnection); if (dgvTrainingClass.Rows[i].Cells[0].Value != null && (bool)dgvTrainingClass.Rows[i].Cells[0].Value == true) { checkPoint = true; sqlCommand.Parameters.AddWithValue("@ID", dgvTrainingClass.Rows[i].Cells[1].Value); sqlCommand.ExecuteNonQuery(); } } sqlConnection.Close(); if(!checkPoint) { MessageBox.Show("No data is selected", "Operation Fail"); return; } dgvLoadTrainingClass(); } } private void btnEditClass_Click(object sender, EventArgs e) { if(classID != "0") { ClassesManageForm cmf = new ClassesManageForm(); cmf.action = "Edit"; cmf.classID = classID; cmf.className = className; cmf.facility = facility; cmf.tutor = tutor; cmf.timeslot = timeSlot; cmf.day = day; cmf.price = price; if (cmf.ShowDialog() == DialogResult.OK) { dgvLoadTrainingClass(); } } else { MessageBox.Show("No data is selected", "Operation Fail"); } } private void dgvTrainingClass_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { int index_row = e.RowIndex; classID = dgvTrainingClass.Rows[index_row].Cells[1].Value.ToString(); className = dgvTrainingClass.Rows[index_row].Cells[2].Value.ToString(); facility = dgvTrainingClass.Rows[index_row].Cells[3].Value.ToString(); tutor = dgvTrainingClass.Rows[index_row].Cells[4].Value.ToString(); timeSlot = dgvTrainingClass.Rows[index_row].Cells[5].Value.ToString(); day = dgvTrainingClass.Rows[index_row].Cells[6].Value.ToString(); price = dgvTrainingClass.Rows[index_row].Cells[7].Value.ToString(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ClubOneAdmin { public partial class FormTutorsManagement : Form { public FormTutorsManagement() { InitializeComponent(); } private void FormTutorsManagement_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the 'cluboneDataSet.Tutor' table. You can move, or remove it, as needed. this.tutorTableAdapter.Fill(this.cluboneDataSet.Tutor); //add a checkbox to first column grdviewTutor.Columns.Add(new DataGridViewCheckBoxColumn()); gridView_LoadData(); } private void gridView_LoadData() { SqlConnection sqlConnection = new SqlConnection("Server=LAPTOP-SMQPLLME\\SQLEXPRESS; UId=admin1; Password=<PASSWORD>; " + "Database=clubone;"); sqlConnection.Open(); SqlCommand cmd = new SqlCommand("select * from Tutor", sqlConnection); IDataAdapter adapter = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); adapter.Fill(ds); sqlConnection.Close(); grdviewTutor.DataSource = ds.Tables[0].DefaultView; grdviewTutor.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; grdviewTutor.Columns[0].Width = 60; grdviewTutor.Columns[1].Width = 60; //set header text grdviewTutor.Columns[1].HeaderText = "ID"; grdviewTutor.Columns[2].HeaderText = "NAME"; grdviewTutor.Columns[3].HeaderText = "AGE"; grdviewTutor.Columns[4].HeaderText = "EMAIL"; grdviewTutor.Columns[5].HeaderText = "PHONE"; grdviewTutor.Columns[6].HeaderText = "EXPERIENCES"; } private void grdviewTutor_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void grdviewTutor_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { int index_row = e.RowIndex; tbID.Text = grdviewTutor.Rows[index_row].Cells[1].Value.ToString(); tbName.Text = grdviewTutor.Rows[index_row].Cells[2].Value.ToString(); tbAge.Text = grdviewTutor.Rows[index_row].Cells[3].Value.ToString(); tbEmail.Text = grdviewTutor.Rows[index_row].Cells[4].Value.ToString(); tbPhone.Text = grdviewTutor.Rows[index_row].Cells[5].Value.ToString(); tbExp.Text = grdviewTutor.Rows[index_row].Cells[6].Value.ToString(); } private void btnModify_Click(object sender, EventArgs e) { if (tbID.Text != "") { string message; string caption; SqlConnection sqlConnection = new SqlConnection("Server=LAPTOP-SMQPLLME\\SQLEXPRESS; UId=admin1; Password=<PASSWORD>; " + "Database=clubone;"); sqlConnection.Open(); SqlCommand sqlCommand = new SqlCommand("update Tutor set name = @N, " + "age = @A, email = @E, phone = @P, experience = @EXP where tID = @ID", sqlConnection); sqlCommand.Parameters.AddWithValue("@N", tbName.Text); sqlCommand.Parameters.AddWithValue("@A", tbAge.Text); sqlCommand.Parameters.AddWithValue("@E", tbEmail.Text); sqlCommand.Parameters.AddWithValue("@P", tbPhone.Text); sqlCommand.Parameters.AddWithValue("@EXP", tbExp.Text); sqlCommand.Parameters.AddWithValue("@ID", tbID.Text); int success = sqlCommand.ExecuteNonQuery(); if (success != 0) { message = "success"; caption = "Operation"; MessageBox.Show(message, caption); this.DialogResult = DialogResult.OK; } sqlConnection.Close(); gridView_LoadData(); } else { MessageBox.Show("No data is selected", "Operation Fail"); } } private void btnInsert_Click(object sender, EventArgs e) { SqlConnection sqlConnection = new SqlConnection("Server=LAPTOP-SMQPLLME\\SQLEXPRESS; UId=admin1; Password=<PASSWORD>; " + "Database=clubone;"); sqlConnection.Open(); SqlCommand sqlCommand = new SqlCommand("insert into Tutor " + "(name, age, email, phone, experience) values (@N, @A, @E, @P, @EXP)", sqlConnection); sqlCommand.Parameters.AddWithValue("@N", tbName.Text); sqlCommand.Parameters.AddWithValue("@A", tbAge.Text); sqlCommand.Parameters.AddWithValue("@E", tbEmail.Text); sqlCommand.Parameters.AddWithValue("@P", tbPhone.Text); sqlCommand.Parameters.AddWithValue("@EXP", tbExp.Text); sqlCommand.Parameters.AddWithValue("@ID", tbID.Text); sqlCommand.ExecuteNonQuery(); sqlConnection.Close(); gridView_LoadData(); } private void btnDelete_Click(object sender, EventArgs e) { string message = "Are You Sure to Remove Selected Tutor Information?"; string caption = "Remove Tutor Information"; MessageBoxButtons buttons = MessageBoxButtons.YesNo; DialogResult result; // Displays the MessageBox. result = MessageBox.Show(message, caption, buttons); if (result == DialogResult.Yes) { SqlConnection sqlConnection = new SqlConnection("Server=LAPTOP-SMQPLLME\\SQLEXPRESS; UId=admin1; Password=<PASSWORD>; " + "Database=clubone;"); sqlConnection.Open(); SqlCommand sqlCommand; bool checkPoint = false; for (int i = 0; i < grdviewTutor.Rows.Count; i++) { sqlCommand = new SqlCommand("delete from Tutor where tID = @ID", sqlConnection); if (grdviewTutor.Rows[i].Cells[0].Value != null && (bool)grdviewTutor.Rows[i].Cells[0].Value == true) { checkPoint = true; sqlCommand.Parameters.AddWithValue("@ID", grdviewTutor.Rows[i].Cells[1].Value); int success = sqlCommand.ExecuteNonQuery(); if (success != 0) { message = "success"; caption = "Operation"; MessageBox.Show(message, caption); this.DialogResult = DialogResult.OK; } } } if (!checkPoint) { MessageBox.Show("No data is selected", "Operation Fail"); return; } sqlConnection.Close(); gridView_LoadData(); } } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ClubOneAdmin { public partial class FacilityManagementForm : Form { public string action; public string fID, facility, availability, capacity; public Image image; public FacilityManagementForm() { InitializeComponent(); } private void FacilityManagementForm_Load(object sender, EventArgs e) { //set Form title lbTitle.Text = action + " Facility"; picboxImage.AllowDrop = true; loadAvailability(); if(action.Equals("Edit")) { btnInsert.Visible = false; populateEditingData(); } else if (action.Equals("Add")) { btnUpdate.Visible = false; btnDelete.Visible = false; } } private void populateEditingData() { tbID.Text = fID; tbFacility.Text = facility; cmbAvailability.SelectedValue = availability; numpadCapacity.Value = Convert.ToInt32(capacity); picboxImage.Image = image; } private void btnUpdate_Click(object sender, EventArgs e) { string message, title; byte[] image = ConvertImageToBytes(picboxImage.Image); SqlConnection sqlConnection = new SqlConnection("Server=LAPTOP-SMQPLLME\\SQLEXPRESS; UId=admin1; Password=<PASSWORD>; " + "Database=clubone;"); sqlConnection.Open(); SqlCommand sqlCommand = new SqlCommand("update Facility " + "set fName = @FN , availability = @A, capacity = @C, image=@IMG " + "where fID = @ID", sqlConnection); sqlCommand.Parameters.AddWithValue("@FN", tbFacility.Text); sqlCommand.Parameters.AddWithValue("@A", cmbAvailability.SelectedValue); sqlCommand.Parameters.AddWithValue("@C", numpadCapacity.Value); sqlCommand.Parameters.AddWithValue("@IMG", image); sqlCommand.Parameters.AddWithValue("@ID", tbID.Text); int success = sqlCommand.ExecuteNonQuery(); if (success != 0) { message = "success"; title = "Operation"; MessageBox.Show(message, title); this.DialogResult = DialogResult.OK; } sqlConnection.Close(); } private void lbClassID_Click(object sender, EventArgs e) { } private void picboxImage_DragDrop(object sender, DragEventArgs e) { var data = e.Data.GetData(DataFormats.FileDrop); if (data != null) { var fileNames = data as string[]; if (fileNames.Length > 0) picboxImage.Image = Image.FromFile(fileNames[0]); } } private void picboxImage_DragEnter(object sender, DragEventArgs e) { e.Effect = DragDropEffects.Copy; } private void btnCancel_Click(object sender, EventArgs e) { this.Hide(); } private void btnInsert_Click(object sender, EventArgs e) { string message, title; byte[] image = ConvertImageToBytes(picboxImage.Image); SqlConnection sqlConnection = new SqlConnection("Server=LAPTOP-SMQPLLME\\SQLEXPRESS; UId=admin1; Password=<PASSWORD>; " + "Database=clubone;"); sqlConnection.Open(); SqlCommand sqlCommand = new SqlCommand("insert into Facility " + "(fName, availability, capacity, image) " + "values (@N, @A, @C, @I)", sqlConnection); sqlCommand.Parameters.AddWithValue("@N", tbFacility.Text); sqlCommand.Parameters.AddWithValue("@A", cmbAvailability.SelectedValue); sqlCommand.Parameters.AddWithValue("@C", numpadCapacity.Value); sqlCommand.Parameters.AddWithValue("@I", image); int success = sqlCommand.ExecuteNonQuery(); if (success != 0) { message = "success"; title = "Operation"; MessageBox.Show(message, title); this.DialogResult = DialogResult.OK; } sqlConnection.Close(); } private void btnDelete_Click(object sender, EventArgs e) { string message = "Are You Sure to Remove Selected Training Class?"; string caption = "Remove Training Class"; MessageBoxButtons buttons = MessageBoxButtons.YesNo; DialogResult result; // Displays the MessageBox. result = MessageBox.Show(message, caption, buttons); if (result == DialogResult.Yes) { SqlConnection sqlConnection = new SqlConnection("Server=LAPTOP-SMQPLLME\\SQLEXPRESS; UId=admin1; Password=<PASSWORD>; " + "Database=clubone;"); sqlConnection.Open(); SqlCommand sqlCommand = new SqlCommand("delete from Facility where fID = @ID", sqlConnection); sqlCommand.Parameters.AddWithValue("@ID", tbID.Text); int success = sqlCommand.ExecuteNonQuery(); if (success != 0) { message = "success"; caption = "Operation"; MessageBox.Show(message, caption); this.DialogResult = DialogResult.OK; } sqlConnection.Close(); } } private void loadAvailability() { cmbAvailability.DisplayMember = "Text"; cmbAvailability.ValueMember = "Value"; var items = new[] { new { Text = "--Available--", Value = "1" }, new { Text = "--Not Available--", Value = "0" }, }; cmbAvailability.DataSource = items; } byte[] ConvertImageToBytes(Image img) { using(MemoryStream ms = new MemoryStream()) { img.Save(ms, System.Drawing.Imaging.ImageFormat.Png); return ms.ToArray(); } } public Image ConvertBytesToImage(byte[] data) { using (MemoryStream ms = new MemoryStream(data)) return Image.FromStream(ms); } } } <file_sep># Club Management Admin System This is a simple desktop application, Club Management System for admin-side. <br/> The desktop application is a **Windows Forms Application** developed using **.NET Framework** and **C#**. <br/> The application is developed for **University Project** purpose. <br/> The admin can manage Tutors, Training Classes, Sport Facilities, Bookings and view Payment Records done by the club members. <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ClubOneAdmin { public partial class FormPayments : Form { public FormPayments() { InitializeComponent(); } private void FormPayments_Load(object sender, EventArgs e) { gridView_LoadData(); } private void gridView_LoadData() { SqlConnection sqlConnection = new SqlConnection("Server=LAPTOP-SMQPLLME\\SQLEXPRESS; UId=admin1; Password=<PASSWORD>; Database=clubone;"); sqlConnection.Open(); SqlCommand cmd = new SqlCommand("select pdID, userID, username, trainingclassName, pd.amount " + "from Payment pt " + "join PaymentDetail pd on pt.pID = pd.paymentID ", sqlConnection); IDataAdapter adapter = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); adapter.Fill(ds); sqlConnection.Close(); grdviewPayment.DataSource = ds.Tables[0].DefaultView; grdviewPayment.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; grdviewPayment.Columns[0].Width = 60; //set header text grdviewPayment.Columns[0].HeaderText = "ID"; grdviewPayment.Columns[1].HeaderText = "UserID"; grdviewPayment.Columns[2].HeaderText = "USERNAME"; grdviewPayment.Columns[3].HeaderText = "TRAINING CLASS"; grdviewPayment.Columns[4].HeaderText = "AMOUNT"; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ClubOneAdmin { public partial class FacilityItem : UserControl { private string fid, availability, capacity; public string fID { get { return this.fid; } set { this.fid = value; } } public string Availability { get { return this.availability; } set { this.availability = value; } } public string Capacity { get { return this.capacity; } set { this.capacity = value; } } public FacilityItem() { InitializeComponent(); } private void FacilityItem_Load(object sender, EventArgs e) { } public Image ItemImage { get { return picbxFacility.Image; } set { picbxFacility.Image = value; } } public string ItemLabel { get { return lbFacility.Text; } set { lbFacility.Text = value; } } private void FacilityItem_MouseEnter(object sender, EventArgs e) { this.BackColor = Color.FromArgb(71, 117, 209); } private void FacilityItem_MouseLeave(object sender, EventArgs e) { this.BackColor = Color.FromArgb(37, 42, 64); } } } <file_sep>using FontAwesome.Sharp; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ClubOneAdmin { public partial class FormBookings : Form { //check whether which bookings are selected //0 for Facility //1 for Training Class private int selection = 0; private IconButton currentButton; public FormBookings() { InitializeComponent(); } private void FormBookings_Load(object sender, EventArgs e) { loadStatus(); //add a checkbox to first column dgvBookings.Columns.Add(new DataGridViewCheckBoxColumn()); ActivateButton(btnBookFacility, Color.FromArgb(77, 184, 255)); selection = 0; FacilityBookingLoad(); } private void ActivateButton(object senderBtn, Color color) { if (senderBtn != null) { DeAvtivateButton(); //Button currentButton = (IconButton)senderBtn; currentButton.ForeColor = color; currentButton.IconColor = color; //panel pnlSelectedNav.Width = currentButton.Width; pnlSelectedNav.Location = new Point(currentButton.Location.X, 74); pnlSelectedNav.Visible = true; } } private void DeAvtivateButton() { if (currentButton != null) { currentButton.ForeColor = Color.FromArgb(255, 255, 255); currentButton.IconColor = Color.FromArgb(255, 255, 255); } } private void loadStatus() { cmbStatus.DisplayMember = "Text"; cmbStatus.ValueMember = "Value"; var items = new[] { new { Text = "--ALL STATUS--", Value = "0" }, new { Text = "Pending", Value = "Pending" }, new { Text = "Approved", Value = "Approved" }, new { Text = "Declined", Value = "Declined" }, }; cmbStatus.DataSource = items; } private void TrainingClassBookingLoad() { SqlConnection sqlConnection = new SqlConnection("Server=LAPTOP-SMQPLLME\\SQLEXPRESS; UId=admin1; Password=<PASSWORD>; " + "Database=clubone;"); sqlConnection.Open(); SqlCommand cmd; if (cmbStatus.SelectedValue.ToString() == "0") { cmd = new SqlCommand("select btID, userID, tc.className, bt.timeSlot, bt.days, status " + "from BookingTraining bt " + "left join TrainingClass tc on bt.classID = tc.tcID ", sqlConnection); } else { string status = cmbStatus.SelectedValue.ToString(); cmd = new SqlCommand("select btID, userID, tc.className, bt.timeSlot, bt.days, status " + "from BookingTraining bt " + "left join TrainingClass tc on bt.classID = tc.tcID " + "where status = @STAT", sqlConnection); cmd.Parameters.AddWithValue("@STAT", status); } IDataAdapter adapter = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); adapter.Fill(ds); dgvBookings.DataSource = ds.Tables[0].DefaultView; dgvBookings.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; dgvBookings.Columns[0].Width = 60; dgvBookings.Columns[1].Width = 60; dgvBookings.Columns[2].Width = 80; //set header text dgvBookings.Columns[1].HeaderText = "ID"; dgvBookings.Columns[2].HeaderText = "UserID"; dgvBookings.Columns[3].HeaderText = "CLASS"; dgvBookings.Columns[4].HeaderText = "TIMESLOT"; dgvBookings.Columns[5].HeaderText = "DAY"; dgvBookings.Columns[6].HeaderText = "STATUS"; } private void FacilityBookingLoad() { SqlConnection sqlConnection = new SqlConnection("Server=LAPTOP-SMQPLLME\\SQLEXPRESS; UId=admin1; Password=123456; " + "Database=clubone;"); sqlConnection.Open(); SqlCommand cmd; if (cmbStatus.SelectedValue.ToString() == "0") { cmd = new SqlCommand("select bfID, userID, fc.fName, timeSlot, days, status " + "from BookingFacility bf " + "left join Facility fc on bf.facilityID = fc.fID ", sqlConnection); } else { string status = cmbStatus.SelectedValue.ToString(); cmd = new SqlCommand("select bfID, userID, fc.fName, timeSlot, days, status " + "from BookingFacility bf " + "left join Facility fc on bf.facilityID = fc.fID " + "where status = @STAT", sqlConnection); cmd.Parameters.AddWithValue("@STAT", status); } IDataAdapter adapter = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); adapter.Fill(ds); dgvBookings.DataSource = ds.Tables[0].DefaultView; dgvBookings.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; dgvBookings.Columns[0].Width = 60; dgvBookings.Columns[1].Width = 60; dgvBookings.Columns[2].Width = 80; //set header text dgvBookings.Columns[1].HeaderText = "ID"; dgvBookings.Columns[2].HeaderText = "UserID"; dgvBookings.Columns[3].HeaderText = "FACILITY"; dgvBookings.Columns[4].HeaderText = "TIMESLOT"; dgvBookings.Columns[5].HeaderText = "DAY"; dgvBookings.Columns[6].HeaderText = "STATUS"; } private void btnBookFacility_Click(object sender, EventArgs e) { ActivateButton(sender, Color.FromArgb(77, 184, 255)); selection = 0; FacilityBookingLoad(); } private void btnBookClass_Click(object sender, EventArgs e) { ActivateButton(sender, Color.FromArgb(77, 184, 255)); selection = 1; TrainingClassBookingLoad(); } private void cmbStatus_SelectionChangeCommitted(object sender, EventArgs e) { if(cmbStatus.SelectedValue.Equals("Pending")) { btnApprove.Enabled = true; btnDecline.Enabled = true; } else { btnApprove.Enabled = false; btnDecline.Enabled = false; } if (selection == 1) TrainingClassBookingLoad(); else FacilityBookingLoad(); } private void btnApprove_Click(object sender, EventArgs e) { string status = "Approved"; string message = "Are You Sure to Approve Booking?"; string caption = "Bookings"; MessageBoxButtons buttons = MessageBoxButtons.YesNo; DialogResult result; // Displays the MessageBox. result = MessageBox.Show(message, caption, buttons); if (result == DialogResult.Yes) { if (selection == 0) //approve Facility Booking { updateFacilityBookingStatus(status); FacilityBookingLoad(); } else //approve Training Class Booking { updateTrainingClassBookingStatus(status); TrainingClassBookingLoad(); } } } private void btnDecline_Click(object sender, EventArgs e) { string status = "Declined"; string message = "Are You Sure to Decline Booking?"; string caption = "Bookings"; MessageBoxButtons buttons = MessageBoxButtons.YesNo; DialogResult result; // Displays the MessageBox. result = MessageBox.Show(message, caption, buttons); if (result == DialogResult.Yes) { if (selection == 0) //approve Facility Booking { updateFacilityBookingStatus(status); FacilityBookingLoad(); } else //approve Training Class Booking { updateTrainingClassBookingStatus(status); TrainingClassBookingLoad(); } } } private void updateFacilityBookingStatus(string status) { SqlConnection sqlConnection = new SqlConnection("Server=LAPTOP-SMQPLLME\\SQLEXPRESS; UId=admin1; Password=<PASSWORD>; " + "Database=clubone;"); sqlConnection.Open(); SqlCommand sqlCommand; bool checkPoint = false; for (int i = 0; i < dgvBookings.Rows.Count; i++) { sqlCommand = new SqlCommand("update BookingFacility set status = @S " + "where bfID = @ID", sqlConnection); if (dgvBookings.Rows[i].Cells[0].Value != null && (bool)dgvBookings.Rows[i].Cells[0].Value == true) { checkPoint = true; sqlCommand.Parameters.AddWithValue("@S", status); sqlCommand.Parameters.AddWithValue("@ID", dgvBookings.Rows[i].Cells[1].Value); sqlCommand.ExecuteNonQuery(); } } if (!checkPoint) { MessageBox.Show("No data is selected", "Operation Fail"); } sqlConnection.Close(); } private void updateTrainingClassBookingStatus(string status) { SqlConnection sqlConnection = new SqlConnection("Server=LAPTOP-SMQPLLME\\SQLEXPRESS; UId=admin1; Password=<PASSWORD>; " + "Database=clubone;"); sqlConnection.Open(); SqlCommand sqlCommand; bool checkPoint = false; for (int i = 0; i < dgvBookings.Rows.Count; i++) { sqlCommand = new SqlCommand("update BookingTraining set status = @S " + "where btID = @ID", sqlConnection); if (dgvBookings.Rows[i].Cells[0].Value != null && (bool)dgvBookings.Rows[i].Cells[0].Value == true) { checkPoint = true; sqlCommand.Parameters.AddWithValue("@S", status); sqlCommand.Parameters.AddWithValue("@ID", dgvBookings.Rows[i].Cells[1].Value); sqlCommand.ExecuteNonQuery(); } } if (!checkPoint) { MessageBox.Show("No data is selected", "Operation Fail"); } sqlConnection.Close(); } } } <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; using FontAwesome.Sharp; namespace ClubOneAdmin { public partial class MainForm : Form { public string username; public string uid; private IconButton currentButton; [DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")] private static extern IntPtr CreateRoundRectRgn ( int nLeftRect, int nTopRect, int nRightRect, int nBottomRect, int mWidthEllipse, int mHeightEllipse ); private Form currentChildForm; public MainForm() { InitializeComponent(); /*Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 25, 25)); pnlSelectedNav.Visible = false;*/ //this.Text = string.Empty; //this.ControlBox = false; //this.MaximizedBounds = Screen.FromHandle(this.Handle).WorkingArea; } private void MainForm_Load(object sender, EventArgs e) { currentButton = btnDashboard; ActivateButton(currentButton, Color.FromArgb(46, 51, 73)); OpenChildForm(new FormDashBoard()); } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { Application.Exit(); } private void ActivateButton(object senderBtn, Color color) { if(senderBtn != null) { DeAvtivateButton(); //Button currentButton = (IconButton)senderBtn; currentButton.BackColor = color; currentButton.IconColor = Color.FromArgb(0, 126, 249); currentButton.TextAlign = ContentAlignment.MiddleCenter; currentButton.ImageAlign = ContentAlignment.MiddleRight; currentButton.TextImageRelation = TextImageRelation.TextBeforeImage; //panel pnlSelectedNav.Height = currentButton.Height; pnlSelectedNav.Location = new Point(0, currentButton.Location.Y); pnlSelectedNav.Visible = true; //HeadTitle section iconHeadTitle.IconChar = currentButton.IconChar; lbHeadTitle.Text = currentButton.Text; } } private void DeAvtivateButton() { if (currentButton != null) { currentButton.BackColor = Color.FromArgb(24, 30, 54); currentButton.IconColor = Color.FromArgb(255,255,255); currentButton.TextAlign = ContentAlignment.MiddleLeft; currentButton.ImageAlign = ContentAlignment.MiddleLeft; currentButton.TextImageRelation = TextImageRelation.ImageBeforeText; } } private void OpenChildForm(Form childForm) { if (currentChildForm != null) currentChildForm.Close(); //format current child form currentChildForm = childForm; childForm.TopLevel = false; childForm.FormBorderStyle = FormBorderStyle.None; childForm.Dock = DockStyle.Fill; //fill the container with child form pnlChildFormContainer.Controls.Add(childForm); pnlChildFormContainer.Tag = childForm; childForm.BringToFront(); childForm.Show(); } private void label2_Click(object sender, EventArgs e) { } //import function to allow windows dragging [DllImport("user32.DLL", EntryPoint = "ReleaseCapture")] private extern static void ReleaseCapture(); [DllImport("user32.DLL", EntryPoint = "SendMessage")] private extern static void SendMessage(System.IntPtr hWnd, int wMsg, int wParam, int lParam); private void pnlHeadTitle_MouseDown(object sender, MouseEventArgs e) { //dragging windows ReleaseCapture(); SendMessage(this.Handle, 0x112, 0xf012, 0); } private void btnDashboard_Click(object sender, EventArgs e) { ActivateButton(sender, Color.FromArgb(46, 51, 73)); OpenChildForm(new FormDashBoard()); } private void btnTutor_Click(object sender, EventArgs e) { ActivateButton(sender, Color.FromArgb(46, 51, 73)); OpenChildForm(new FormTutorsManagement()); } private void btnTraningClasses_Click(object sender, EventArgs e) { ActivateButton(sender, Color.FromArgb(46, 51, 73)); OpenChildForm(new FormTrainingClasses()); } private void btnFacilities_Click(object sender, EventArgs e) { ActivateButton(sender, Color.FromArgb(46, 51, 73)); OpenChildForm(new FormFacilities()); } private void btnBookings_Click(object sender, EventArgs e) { ActivateButton(sender, Color.FromArgb(46, 51, 73)); OpenChildForm(new FormBookings()); } private void pnlChildFormContainer_Paint(object sender, PaintEventArgs e) { } private void btnPayments_Click(object sender, EventArgs e) { ActivateButton(sender, Color.FromArgb(46, 51, 73)); OpenChildForm(new FormPayments()); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ClubOneAdmin { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void pictureBox1_Click(object sender, EventArgs e) { Application.Exit(); } private void btnMinimise_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Minimized; } private void btnLogin_Click(object sender, EventArgs e) { string username = tbUsername.Text; string password = <PASSWORD>; SqlConnection sqlConnection = new SqlConnection("Server=LAPTOP-SMQPLLME\\SQLEXPRESS; UId=admin1; Password=<PASSWORD>; " + "Database=clubone;"); sqlConnection.Open(); SqlCommand cmd = new SqlCommand("select * from Admin where username = @UN and " + "password = <PASSWORD>", sqlConnection); cmd.Parameters.AddWithValue("@UN", username); cmd.Parameters.AddWithValue("@PWD", password); IDataAdapter adapter = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); adapter.Fill(ds); if(ds.Tables[0].Rows.Count != 0) { this.Hide(); MainForm mf = new MainForm(); mf.username = username; mf.uid = ds.Tables[0].Rows[0]["aID"].ToString(); mf.Show(); } else { lbFail.Text = "Fail to Log in ! Incorrect username or password !"; } } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { Application.Exit(); } private void btnExit_MouseEnter(object sender, EventArgs e) { btnExit.BackColor = Color.FromArgb(71, 117, 209); } private void btnExit_MouseLeave(object sender, EventArgs e) { btnExit.BackColor = Color.FromArgb(31, 31, 46); } private void btnMinimise_MouseEnter(object sender, EventArgs e) { btnMinimise.BackColor = Color.FromArgb(71, 117, 209); } private void btnMinimise_MouseLeave(object sender, EventArgs e) { btnMinimise.BackColor = Color.FromArgb(31, 31, 46); } } }
d134ef8fa4403ae2f531bdf37505f94b73a3d5ff
[ "Markdown", "C#" ]
11
C#
craymon777/Club-Management-Admin
5b1f4b95410ef20e2cae5b9454a169214d3a9329
4bde29dbbfc60cb657f0a109bd9186e0d3541a7b
refs/heads/master
<repo_name>bricerb/regression<file_sep>/OTCRegression/src/test/java/mobile/android/tests/AddInvalidCardTest.java package mobile.android.tests; import org.junit.Assert; import org.junit.Test; import org.openqa.selenium.By; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertNull; public class AddInvalidCardTest extends AbstractTest{ @Test public void invalidCard(){ app.termsAndConditionsScreen().findElementWithTimeout(By.id("com.incomm.otc:id/tc_accept_cb"), 30); // terms & conditions app.termsAndConditionsScreen().checkBox.click(); app.termsAndConditionsScreen().submitButton.click(); // walkthrough app.walkthroughScreen().nextButton.click(); app.walkthroughScreen().nextButton.click(); app.walkthroughScreen().nextButton.click(); app.walkthroughScreen().nextButton.click(); // add invalid card driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); app.addNewCardScreen().cardNumber.setValue(""); driver.hideKeyboard(); app.addNewCardScreen().addCardBtn.click(); driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); Assert.assertNotNull(app.addNewCardScreen().cardNumber); } } <file_sep>/OTCRegression/src/test/java/mobile/android/tests/RemoveAllCardsTest.java package mobile.android.tests; import org.junit.Assert; import org.junit.Test; import org.openqa.selenium.By; import io.appium.java_client.MobileElement; import io.appium.java_client.TouchAction; import java.util.concurrent.TimeUnit; public class RemoveAllCardsTest extends AbstractTest{ @Test public void removeCards(){ app.termsAndConditionsScreen().findElementWithTimeout(By.id("com.incomm.otc:id/tc_accept_cb"), 30); // terms & conditions app.termsAndConditionsScreen().checkBox.click(); app.termsAndConditionsScreen().submitButton.click(); // walkthrough app.walkthroughScreen().nextButton.click(); app.walkthroughScreen().nextButton.click(); app.walkthroughScreen().nextButton.click(); app.walkthroughScreen().nextButton.click(); // add initial valid card driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); app.addNewCardScreen().cardNumber.setValue("1234567890123456789"); driver.hideKeyboard(); app.addNewCardScreen().addCardBtn.click(); // add an additional valid card app.dashboardScreen().findElementWithTimeout(By.id("com.incomm.otc:id/add_card_btn"), 30); app.dashboardScreen().addCardDashboardBtn.click(); app.addNewCardScreen().cardNumber.setValue("0000000000000000000"); driver.hideKeyboard(); app.addNewCardScreen().addCardBtn.click(); //Delete First Card deleteCard(); //Delete Second Card deleteCard(); Assert.assertNotNull(app.addNewCardScreen().addCardBtn); } public void deleteCard() { try { Thread.sleep(7000); } catch (Exception e) { } new TouchAction(driver).press(900, 850).waitAction(500).moveTo(200, 850).release().perform(); driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); new TouchAction(driver).tap(790, 815).perform(); driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); MobileElement dialogAcceptButton1 = (MobileElement) driver.findElementById("android:id/button1"); dialogAcceptButton1.click(); } } <file_sep>/OTCRegression/src/test/java/mobile/android/tests/TermsAndConditionsTest.java package mobile.android.tests; import org.junit.Assert; import org.junit.Test; import org.openqa.selenium.By; import java.util.concurrent.TimeUnit; public class TermsAndConditionsTest extends AbstractTest { @Test public void acceptTermsAndConditions() { app.termsAndConditionsScreen().findElementWithTimeout(By.id("com.incomm.otc:id/tc_accept_cb"), 30); app.termsAndConditionsScreen().checkBox.click(); app.termsAndConditionsScreen().submitButton.click(); Assert.assertNotNull(app.walkthroughScreen().nextButton); } } <file_sep>/OTCRegression/src/test/java/mobile/android/tests/EmptyRetailerList.java package mobile.android.tests; import io.appium.java_client.MobileElement; import io.appium.java_client.TouchAction; import org.junit.Assert; import org.junit.Test; import org.openqa.selenium.By; import java.util.List; import java.util.concurrent.TimeUnit; public class EmptyRetailerList extends AbstractTest { @Test public void EmptyRetailerList() { // Walkthrough app.termsAndConditionsScreen().findElementWithTimeout(By.id("com.incomm.otc:id/tc_accept_cb"), 30); // Terms & Conditions app.termsAndConditionsScreen().checkBox.click(); app.termsAndConditionsScreen().submitButton.click(); // Walkthrough app.walkthroughScreen().nextButton.click(); app.walkthroughScreen().nextButton.click(); app.walkthroughScreen().nextButton.click(); app.walkthroughScreen().nextButton.click(); // Add initial valid card driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); app.addNewCardScreen().cardNumber.setValue("1234561234561234567"); driver.hideKeyboard(); app.addNewCardScreen().addCardBtn.click(); // Dashboard Screen app.dashboardScreen().findElementWithTimeout(By.id("com.incomm.otc:id/scan_products_btn"), 30); app.dashboardScreen().scanProductsBtn.click(); // Select Retailer Screen driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); List<MobileElement> retailers = app.selectRetailerScreen().retailerListView .findElements(By.className("android.widget.CheckedTextView")); Assert.assertTrue(retailers.isEmpty()); } } <file_sep>/OTCRegression/src/test/java/mobile/android/utils/AppiumDriverBuilder.java package mobile.android.utils; import io.appium.java_client.AppiumDriver; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.android.AndroidElement; import io.appium.java_client.remote.MobileCapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import java.io.File; import mobile.android.TestCapabilities; import java.net.MalformedURLException; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; public abstract class AppiumDriverBuilder<SELF, DRIVER extends AppiumDriver> { protected String apiKey; protected String testReportId; public static AndroidDriverBuilder forAndroid() { return new AndroidDriverBuilder(); } public static class AndroidDriverBuilder extends AppiumDriverBuilder<AndroidDriverBuilder, AndroidDriver> { DesiredCapabilities capabilities = new DesiredCapabilities(); @Override public AndroidDriver build() { File file = new File("otc.app"); capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, TestCapabilities.DEVICE_NAME); capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, TestCapabilities.PLATFORM_NAME); capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, TestCapabilities.PLATFORM_VERSION_NUMBER); capabilities.setCapability(MobileCapabilityType.APP, TestCapabilities.APK_PATH); capabilities.setCapability("appWaitActivity", TestCapabilities.APP_WAIT_ACTIVITY); AndroidDriver<AndroidElement> driver = null; try { driver = new AndroidDriver(new URL(TestCapabilities.END_POINT), capabilities); } catch (MalformedURLException ex) { Logger.getLogger(AppiumDriverBuilder.class.getName()).log(Level.SEVERE, null, ex); } return driver; } } public abstract DRIVER build(); } <file_sep>/mock_server/src/main/java/io/bricerb/otcregression/rest/SubmitItem.java package io.bricerb.otcregression.rest; import io.bricerb.otcregression.models.SubmitItemRequest; import io.bricerb.otcregression.models.SubmitItemResponse; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class SubmitItem { @PostMapping(path = "/WebApi/ReportError") public SubmitItemResponse submitItem (@RequestBody SubmitItemRequest request) { return new SubmitItemResponse(); } } <file_sep>/script.sh # Resolve Mock Server Dependencies cp -a OTCRegression/data mock_server cd mock_server mvn dependency:resolve mvn spring-boot:run </dev/null &>/dev/null & cd .. # Resolve Regression Test Dependencies cd OTCRegression mvn dependency:resolve appium & mvn test<file_sep>/OTCRegression/src/test/java/mobile/android/tests/AbstractTest.java package mobile.android.tests; import io.appium.java_client.AppiumDriver; import org.junit.Before; import mobile.android.OTC; import mobile.android.utils.AppiumDriverBuilder; import java.net.MalformedURLException; public class AbstractTest { protected AppiumDriver driver; protected OTC app; protected String medicareNoOffersCardNumber = "1234567890123456789"; protected String medicaidOffersCardNumber = "0000000000000000000"; protected String eligibleItemWithoutOffers = "440337005307"; protected String eligibleItemWithOffers = "703500733044"; @Before public void connect() throws MalformedURLException { this.driver = AppiumDriverBuilder.forAndroid().build(); app = new OTC(driver); } } <file_sep>/OTCRegression/src/test/java/mobile/android/screens/TermsAndConditionsScreen.java package mobile.android.screens; import io.appium.java_client.AppiumDriver; import io.appium.java_client.MobileElement; import io.appium.java_client.android.AndroidElement; import io.appium.java_client.pagefactory.AndroidFindBy; public class TermsAndConditionsScreen extends AbstractScreen { @AndroidFindBy(id = "com.incomm.otc:id/tc_accept_cb") public MobileElement checkBox; @AndroidFindBy(id = "com.incomm.otc:id/submit_button") public MobileElement submitButton; public TermsAndConditionsScreen (AppiumDriver driver) { super(driver); } } <file_sep>/OTCRegression/src/test/java/mobile/android/tests/RetailerDisplayMedicareCardTest.java package mobile.android.tests; import io.appium.java_client.MobileElement; import org.junit.Assert; import org.junit.Test; import org.openqa.selenium.By; import java.util.List; import java.util.concurrent.TimeUnit; public class RetailerDisplayMedicareCardTest extends AbstractTest { @Test public void retailerDisplayMedicareCardTest () { String[] expectedRetailers = {"CVS", "Discount Drug Mart", "Dollar General", "Duane Reade", "Family Dollar", "Freds, H-E-B", "Independent Merchants", "Meijer", "Rite Aid", "Sams Club", "WALGREENS", "Walmart", "Winn-Dixie Stores"}; app.termsAndConditionsScreen().findElementWithTimeout(By.id("com.incomm.otc:id/tc_accept_cb"), 30); // terms & conditions app.termsAndConditionsScreen().checkBox.click(); app.termsAndConditionsScreen().submitButton.click(); // walkthrough app.walkthroughScreen().nextButton.click(); app.walkthroughScreen().nextButton.click(); app.walkthroughScreen().nextButton.click(); app.walkthroughScreen().nextButton.click(); // add initial valid card driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); app.addNewCardScreen().cardNumber.setValue(medicareNoOffersCardNumber); driver.hideKeyboard(); app.addNewCardScreen().addCardBtn.click(); // Dashboard app.dashboardScreen().findElementWithTimeout(By.id("com.incomm.otc:id/scan_products_btn"), 30); app.dashboardScreen().scanProductsBtn.click(); // Retailer List driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); List<MobileElement> retailers = app.selectRetailerScreen().retailerListView .findElements(By.className("android.widget.CheckedTextView")); for (int i = 0; i < retailers.size(); i++) { Assert.assertEquals(expectedRetailers[i], retailers.get(i).getText()); } } } <file_sep>/OTCRegression/src/test/java/mobile/android/OTC.java package mobile.android; import io.appium.java_client.AppiumDriver; import mobile.android.screens.*; public class OTC { private final AppiumDriver driver; public OTC(AppiumDriver driver) { this.driver = driver; } public TermsAndConditionsScreen termsAndConditionsScreen() { return new TermsAndConditionsScreen(driver); } public WalkthroughScreen walkthroughScreen() { return new WalkthroughScreen(driver); } public AddNewCardScreen addNewCardScreen() { return new AddNewCardScreen(driver); } public DashboardScreen dashboardScreen() { return new DashboardScreen(driver); } public SelectRetailerScreen selectRetailerScreen() { return new SelectRetailerScreen(driver); } public ScanScreen scanScreen() { return new ScanScreen(driver); } public EnterUPCScreen enterUPCScreen() { return new EnterUPCScreen(driver); } public ItemEligibilityScreen itemEligibilityScreen(){ return new ItemEligibilityScreen(driver); } public SurveyScreen surveyScreen(){ return new SurveyScreen(driver); } } <file_sep>/OTCRegression/src/test/java/mobile/android/tests/DiscountEligibilityEligibleAndOptedInTest.java package mobile.android.tests; import org.junit.Assert; import org.junit.Test; import org.openqa.selenium.By; import java.util.concurrent.TimeUnit; public class DiscountEligibilityEligibleAndOptedInTest extends AbstractTest { @Test public void discountEligibleAndOptIn() { app.termsAndConditionsScreen().findElementWithTimeout(By.id("com.incomm.otc:id/tc_accept_cb"), 30); // terms & conditions app.termsAndConditionsScreen().checkBox.click(); app.termsAndConditionsScreen().submitButton.click(); // walkthrough app.walkthroughScreen().nextButton.click(); app.walkthroughScreen().nextButton.click(); app.walkthroughScreen().nextButton.click(); app.walkthroughScreen().nextButton.click(); // add initial valid card driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); app.addNewCardScreen().cardNumber.setValue(medicaidOffersCardNumber); driver.hideKeyboard(); app.addNewCardScreen().addCardBtn.click(); //start scanning app.dashboardScreen().findElementWithTimeout(By.id("com.incomm.otc:id/scan_products_btn"), 30); app.dashboardScreen().scanProductsBtn.click(); //select retailer & submit driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); app.selectRetailerScreen().retailer.click(); app.selectRetailerScreen().submitRetailerBtn.click(); // enter upc number & submit driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); app.scanScreen().enterUpcBtn.click(); app.enterUPCScreen().enterUpcField.setValue(eligibleItemWithOffers); app.enterUPCScreen().upcSubmitBtn.click(); // //item is eligible app.itemEligibilityScreen().findElementWithTimeout(By.id("com.incomm.otc:id/eligible_item_tv"), 30); Assert.assertEquals("This Item is Eligible", app.itemEligibilityScreen().itemIsEligibleOrNot.getText()); } }<file_sep>/mock_server/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>groupId</groupId> <artifactId>mockserver</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2.1</version> <configuration> <mainClass>Regression</mainClass> <arguments> <argument>argument1</argument> </arguments> </configuration> </plugin> </plugins> </build> <properties> <java>1.9</java> <maven.compiler.source>1.9</maven.compiler.source> <maven.compiler.target>1.9</maven.compiler.target> <!--<start-class>io.bricerb.otcregression.OTCRegressionApplication</start-class>--> <!--<guava.version>25.1-jre</guava.version>--> </properties> <!--<dependencyManagement>--> <!--<dependencies>--> <!--<dependency>--> <!--<groupId>com.google.guava</groupId>--> <!--<artifactId>guava</artifactId>--> <!--<version>25.1-jre</version>--> <!--</dependency>--> <!--</dependencies>--> <!--</dependencyManagement>--> <dependencies> <!--<dependency>--> <!--<groupId>org.springframework</groupId>--> <!--<artifactId>spring-context-support</artifactId>--> <!--</dependency>--> <!--<dependency>--> <!--<groupId>com.google.guava</groupId>--> <!--<artifactId>guava</artifactId>--> <!--<version>21.0</version>--> <!--</dependency>--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>5.2.3.Final</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> </dependency> <!--<dependency>--> <!--<groupId>junit</groupId>--> <!--<artifactId>junit</artifactId>--> <!--<version>4.12</version>--> <!--</dependency>--> <!--<dependency>--> <!--<groupId>io.appium</groupId>--> <!--<artifactId>java-client</artifactId>--> <!--<version>4.1.2</version>--> <!--<exclusions>--> <!--<exclusion>--> <!--<groupId>com.google.guava</groupId>--> <!--<artifactId>guava</artifactId>--> <!--</exclusion>--> <!--</exclusions>--> <!--</dependency>--> </dependencies> </project><file_sep>/OTCRegression/src/test/java/mobile/android/TestCapabilities.java package mobile.android; public class TestCapabilities { private static boolean isBitriseBuild = (System.getenv().get("REGRESSION_TEST_GIT_URL") != null); public static final String APK_PATH = isBitriseBuild ? System.getenv("BITRISE_APK_PATH") : "/Users/Brice/AndroidStudioProjects/mobile-otc-android-andotc/app/build/outputs/apk/regression/app-regression.apk"; public static final String PLATFORM_VERSION_NUMBER = isBitriseBuild ? "8.0" : "8.0"; // Bitrise URL and Version // public static final String APK_PATH = "/bitrise/deploy/app-regression.apk"; // public static final String PLATFORM_VERSION_NUMBER = "8.0" : "8.0"; // Local URL and Version // public static final String APK_PATH = "/Users/Brice/AndroidStudioProjects/mobile-otc-android-andotc/app/build/outputs/apk/regression/app-regression.apk"; // public static final String PLATFORM_VERSION_NUMBER = "8.1"; // Rebecca's local // public static final String APK_PATH = isBitriseBuild ? "/bitrise/deploy/app-debug.apk" : "C:/Users/rtellez/AndroidStudioProjects/Incomm/mobile-otc-android-andotc/app/build/outputs/apk/regression/app-regression.apk"; // public static final String PLATFORM_VERSION_NUMBER = isBitriseBuild ? "8.0" : "8.1"; // David's Local // public static final String APK_PATH = isBitriseBuild ? "/bitrise/deploy/app-debug.apk" : "C:/NotOneDrive/Appium/app-regression.apk"; // public static final String PLATFORM_VERSION_NUMBER = isBitriseBuild ? "8.0" : "8.0"; public static final String PLATFORM_NAME = "Android"; public static final String DEVICE_NAME = "Android Emulator"; public static final String END_POINT = "http://localhost:4723/wd/hub"; public static final String APP_WAIT_ACTIVITY = "com.incomm.otc.views.termscondition.TermsAndConditionsActivity"; } <file_sep>/mock_server/src/main/java/io/bricerb/otcregression/utils/Utilities.java package io.bricerb.otcregression.utils; import com.google.gson.Gson; import io.bricerb.otcregression.models.ItemEligibilityRequest; import io.bricerb.otcregression.models.ItemEligibilityResponse; import io.bricerb.otcregression.models.MemberDetailsRequest; import io.bricerb.otcregression.models.MemberDetailsResponse; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class Utilities { public static List<String> deserialize(String base) { List<String> list = new ArrayList<>(); try { List<File> filesInFolder = Files.walk(Paths.get(base)) .filter(Files::isRegularFile) .map(Path::toFile) .collect(Collectors.toList()); filesInFolder.forEach(file -> list.add(file.getPath())); } catch (Exception e) { } return list; } } <file_sep>/mock_server/src/main/java/io/bricerb/otcregression/models/SubmitItemResponse.java package io.bricerb.otcregression.models; public class SubmitItemResponse { } <file_sep>/OTCRegression/src/test/java/mobile/android/tests/BalanceDisplayTest.java package mobile.android.tests; import org.junit.Assert; import org.junit.Test; import org.openqa.selenium.By; import java.util.concurrent.TimeUnit; public class BalanceDisplayTest extends AbstractTest { @Test public void balanceDisplayTest () { String cardNumber = "0000000000000000000"; String expectedBalance = "$55.00"; app.termsAndConditionsScreen().findElementWithTimeout(By.id("com.incomm.otc:id/tc_accept_cb"), 30); // terms & conditions app.termsAndConditionsScreen().checkBox.click(); app.termsAndConditionsScreen().submitButton.click(); // walkthrough app.walkthroughScreen().nextButton.click(); app.walkthroughScreen().nextButton.click(); app.walkthroughScreen().nextButton.click(); app.walkthroughScreen().nextButton.click(); // add initial valid card driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); app.addNewCardScreen().cardNumber.setValue(cardNumber); driver.hideKeyboard(); app.addNewCardScreen().addCardBtn.click(); app.dashboardScreen().findElementWithTimeout(By.id("com.incomm.otc:id/account_balance"), 30); Assert.assertEquals(expectedBalance, app.dashboardScreen().accountBalance.getText()); } }
4b2232224cf1c18334e3c39f679762660771ca43
[ "Java", "Maven POM", "Shell" ]
17
Java
bricerb/regression
22d051a2114cdd10d32611fadd548e8ddf3ab6ed
be12afdcb688b6af1487619ea1032e911fca7630
refs/heads/main
<file_sep>import express from 'express'; import cors from 'cors'; import dayjs from 'dayjs'; const app = express(); app.use(cors()); app.use(express.json()); let users = []; const messages = []; app.post('/participants', (req, res) => { const user = req.body; if(user.name === '') { res.sendStatus(400); } else { users.push({ ...user, lastStatus: Date.now(), }); messages.push({ from: user.name, to: 'Todos', text: 'entra na sala...', type: 'status', time: dayjs().format('HH:mm:ss'), }) res.sendStatus(200); } }); app.get('/participants', (req, res) => { res.send(users); }) app.post('/messages', (req, res) => { const username = req.headers.user; const message = req.body if( message.to === '' || message.text === '' || (message.type !== 'message' && message.type !== 'private_message') || !users.find(user => user.name === username) ) { res.sendStatus(400) } else { messages.push({ ...message, from: username, time: dayjs().format('HH:mm:ss'), }); res.sendStatus(200); } }); app.get('/messages', (req, res) => { const limit = Number(req.query.limit); const accessibleMessages = messages.filter(message => !(message.type === 'private_message' && message.to !== req.headers.user && message.from !== req.headers.user)); if(accessibleMessages.length <= limit || limit === undefined) { res.send(accessibleMessages); } else { const messagesWithLimit = []; for(let i = 0; i < accessibleMessages.length; i++) { if(i >= accessibleMessages.length - 1 - limit) { messagesWithLimit.push(accessibleMessages[i]); } } res.send(messagesWithLimit); } }); app.post('/status', (req, res) => { const username = req.headers.user; if(!!users.find(user => user.name === username)) { users.map(user => { if(user.name === username) { user.lastStatus = Date.now(); } }) res.sendStatus(200); } else { res.sendStatus(400); } }) setInterval(() => { users = users.filter(user => Date.now() - user.lastStatus <= 10000); }, 15000) app.listen(4000);
320275dae6329e47483a756eaf7043fb4da0d3ea
[ "JavaScript" ]
1
JavaScript
Kadugs/bate-papo-uol-back
a53b49471ec20600be22e0cf82f85a71b29d0007
b91fce7a9d3716858a288e5ee0967625cada8ce8
refs/heads/master
<file_sep>number1 = int(input("Enter the first factor: ")) number2 = int(input ("Enter the second factor: ")) addFunction = 0 answer = 0 if addFunction < number2: while True: answer = answer + number1 addFunction = addFunction + 1 if addFunction == number2: break print ("The product is", answer)
5ab96bc8621ec8957584d248761b1be2ab68ec04
[ "Python" ]
1
Python
jacob-w-bonner/Unit-6-08---Python
bdddc7b9140c39b2373704f334f13476231bdc9d
ca34f9951f00108b3a310cf66b1e8f446ec3fee1
refs/heads/master
<file_sep>require "emay_sms/version" require "emay_sms/configuration" require "savon" require "logger" module EmaySms class << self def setup yield config end def config @config ||= Configuration.new end def logger @logger ||= Logger.new(STDOUT) end def client @client ||= Savon.client(wsdl: EmaySms.config.server, log: true, log_level: :debug, pretty_print_xml: true) end def sign_message(message, sign = nil) if sign.nil? "#{EmaySms.config.sign}#{message}" else "【#{sign}】#{message}" end end def active response = client.call(:regist_ex, message: { arg0: EmaySms.config.account, arg1: EmaySms.config.secret, arg2: EmaySms.config.password }) if response.body[:regist_ex_response].nil? || response.body[:regist_ex_response][:return] != "0" return false else return true end end def register(hash = {}) response = client.call(:regist_detail_info, message: { arg0: EmaySms.config.account, arg1: EmaySms.config.secret, arg2: hash[:name], arg3: hash[:contact], arg4: hash[:phone_number], arg5: hash[:mobile], arg6: hash[:email], arg7: hash[:fax], arg8: hash[:address], arg9: hash[:post_code]}) if response.body[:regist_detail_info_response].nil? || response.body[:regist_detail_info_response][:return] != "0" return false else return true end end def send(message, mobiles = [], sign = nil) response = client.call(:send_sms, message: { arg0: EmaySms.config.account, arg1: EmaySms.config.secret, arg2: "", arg3: mobiles, arg4: EmaySms.sign_message(message, sign), arg5: "", arg6: "UTF-8", arg7: 1, arg8: 0 }) if response.body[:send_sms_response].nil? || response.body[:send_sms_response][:return] != "0" return false else return true end end end end <file_sep>lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'emay_sms/version' Gem::Specification.new do |spec| spec.name = "emay_sms" spec.version = EmaySms::VERSION spec.authors = ["liuzelei"] spec.email = ["<EMAIL>"] spec.summary = "亿美短信接口" spec.description = "就是那个亿美啦" spec.homepage = "" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.6" spec.add_development_dependency "rake" spec.add_development_dependency "rspec" spec.add_development_dependency "guard" spec.add_development_dependency "guard-rspec" spec.add_development_dependency "codeclimate-test-reporter" spec.add_dependency "savon", "~> 2.7.2" end <file_sep>module EmaySms class Configuration def server @server ||= "http://sdk4report.eucp.b2m.cn:8080/sdk/SDKService?wsdl" end def server=(server) @server = server end def account @account ||= "account" end def account=(account) @account = account end def password @password ||= "<PASSWORD>" end def password=(password) @password = password end def secret @secret ||= SecureRandom.hex(10) end def secret=(secret) @secret = secret end def sign @sign end def sign=(sign) @sign = "【#{sign}】" end end end<file_sep>======= emay_sms ======== 亿美软通短信接口<file_sep>require "spec_helper" describe "Service" do it "should active new key" do response = EmaySms.active expect(response).to be true end it "should register info" do data = { name: '一个神奇的网站', contact: '大理石', phone_number: '021-12345678', mobile: '13800138000', email: '<EMAIL>', fax: '021-12345678', address: '天朝', post_code: '200100' } response = EmaySms.register(data) expect(response).to be true end it "should send message" do response = EmaySms.send("订单 #{Time.now.to_i} 已经团购成功, 请访问 http://www.baidu.com 支付.", ["13817513107", "18101801755", "18616015606"]) expect(response).to be true end it "should send message by custom sign" do response = EmaySms.send("订单 #{Time.now.to_i} 已经团购成功, 请访问 http://www.baidu.com 支付.", ["13681695220"], "中国移动") expect(response).to be true end end<file_sep>require "codeclimate-test-reporter" CodeClimate::TestReporter.start require 'bundler/setup' require 'emay_sms' Bundler.setup EmaySms.setup do |config| config.server = "http://sdk4report.eucp.b2m.cn:8080/sdk/SDKService?wsdl" config.account = "<KEY>" config.password = "<PASSWORD>" config.secret = "<KEY>" #config.sign = "就诊通" end RSpec.configure do |config| config.before(:each) do end end
4e32ed0666d2c3506cc6f03c9be3472f0a02bf78
[ "Markdown", "Ruby" ]
6
Ruby
wangrui438/emay_sms
3be413be7c28ba9340b8334919186d42f3f0c025
cd7c05cbd80502688f0058095a4234e5c8eaf29e