branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<repo_name>posmatrach/tiny-agv<file_sep>/src/com/hexbugsrnr/tinyagv/SimpleAGV.java
package com.hexbugsrnr.tinyagv;
import java.util.concurrent.BlockingQueue;
import java.util.Map;
/**
* Created by null on 9/06/16.
*/
public class SimpleAGV extends Thread
{
private final String id;
private final BlockingQueue<Message> commQueue;
private final Map<String, Coordinates> locationMap;
private final Map<String, Direction> directionMap;
private volatile Coordinates coordinates;
private volatile Direction direction;
private volatile boolean stopped = false;
public SimpleAGV(String id, Coordinates coordinates, BlockingQueue<Message> commQueue, Map<String, Coordinates> locationMap, Map<String, Direction> directionMap)
{
super(id + "_THREAD");
this.id = id;
this.coordinates = coordinates;
this.commQueue = commQueue;
this.locationMap = locationMap;
this.directionMap = directionMap;
this.locationMap.put(id, coordinates);
}
@Override
public void run()
{
try
{
while(true)
{
Message m = commQueue.take();
System.out.println("[" + id.toString() + "]" + "> Received command: " + m.getType() + "; Value: " + m.getValue());
if(m.getType() == MessageType.DIRECTION)
{
this.direction = (Direction) m.getValue();
directionMap.put(this.id, this.direction);
}
else if(m.getType() == MessageType.START && null != direction)
{
stopped = false;
move();
}
else
this.stopped = (m.getType() == MessageType.STOP);
}
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
private void move()
{
Thread t = new Thread(() -> {
while(!stopped)
{
if(null == coordinates || null == direction)
break;
synchronized (direction)
{
coordinates = new Coordinates(coordinates.getX() + direction.getDx(), coordinates.getY() + direction.getDy());
locationMap.put(id, this.coordinates);
}
try
{
Thread.sleep(250);
} catch (InterruptedException e)
{
break;
}
}
});
t.start();
}
}
|
cf4f1a654a0b106d10cd71993c599401e04fb671
|
[
"Java"
] | 1 |
Java
|
posmatrach/tiny-agv
|
53652afdc50295ae0c9cf051a4b8fdca62cd673a
|
4f6e08cb6a81c487740638e4e7e4516b6a21ae43
|
refs/heads/master
|
<repo_name>Nooruddin1993/june52020ClassWork<file_sep>/file1.js
// for loop works by iterating a set of instructiins a certain specified number of times
function a(){
sum = 0;
for(i=0; i<10 ;i++) {
console.log("Hello Happy Summer!!!" +i);
sum += i;
if (i==5) {
break;
}
}
return sum;
}
console.log("sum is", a());
|
3d41cd10900a3c52b8966bf7bb3352f6bdaf9f74
|
[
"JavaScript"
] | 1 |
JavaScript
|
Nooruddin1993/june52020ClassWork
|
ef2fb2a82c2f9ce33da861ade598301c2b2ccf9b
|
758ec33e99ad316047cc6967404d87ca9d2c2ef5
|
refs/heads/main
|
<file_sep>window.onload = ()=>{
getTopstories('home');
var colnav = myElement('div','mb-3');
var nav = myElement('nav','navbar navbar-expand-lg justify-content-between');
var a1 = myElement('button','btn btn-dark');
a1.setAttribute('style','font-weight:normal')
a1.setAttribute('onclick',"getTopstories('home')");
a1.innerHTML = 'HOME';
var a2 = myElement('button','btn btn-dark');
a2.setAttribute('style','font-weight:normal');
a2.setAttribute('onclick',"getTopstories('world')");
a2.innerHTML = 'WORLD';
var a3 = myElement('button','btn btn-dark');
a3.setAttribute('style','font-weight:normal');
a3.setAttribute('onclick',"getTopstories('politics')");
a3.innerHTML = 'POLITICS';
var a4 = myElement('button','btn btn-dark');
a4.setAttribute('style','font-weight:normal')
a4.setAttribute('onclick',"getTopstories('magazine')");
a4.innerHTML = 'MAGAZINE';
var a5 = myElement('button','btn btn-dark');
a5.setAttribute('style','font-weight:normal')
a5.setAttribute('onclick',"getTopstories('technology')");
a5.innerHTML = 'TECHNOLOGY';
var a6 = myElement('button','btn btn-dark');
a6.setAttribute('style','font-weight:normal');
a6.setAttribute('onclick',"getTopstories('science')");
a6.innerHTML = 'SCIENCE';
var a7 = myElement('button','btn btn-dark');
a7.setAttribute('style','font-weight:normal');
a7.setAttribute('onclick',"getTopstories('health')");
a7.innerHTML = 'HEALTH';
var a8 = myElement('button','btn btn-dark');
a8.setAttribute('style','font-weight:normal');
a8.setAttribute('onclick',"getTopstories('sports')");
a8.innerHTML = 'SPORTS';
var a9 = myElement('button','btn btn-dark');
a9.setAttribute('style','font-weight:normal');
a9.setAttribute('onclick',"getTopstories('arts')");
a9.innerHTML = 'ARTS';
var a10 = myElement('button','btn btn-dark');
a10.setAttribute('style','font-weight:normal');
a10.setAttribute('onclick',"getTopstories('fashion')");
a10.innerHTML = 'FASHION';
var a11 = myElement('button','btn btn-dark');
a11.setAttribute('style','font-weight:normal');
a11.setAttribute('onclick',"getTopstories('food')");
a11.innerHTML = 'FOOD';
var a12 = myElement('button','btn btn-dark');
a12.setAttribute('style','font-weight:normal');
a12.setAttribute('onclick',"getTopstories('travel')");
a12.innerHTML = 'TRAVEL';
nav.append(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12);
colnav.append(nav);
var hr = document.createElement('hr');
var main = myElement('div','container','main');
document.body.append(colnav,hr,main);
}
//Get data from API
async function getTopstories(sec)
{
try{
// document.getElementsByClassName('container').empty();
var response = await fetch('https://api.nytimes.com/svc/topstories/v2/'+sec+'.json?api-key=<KEY>');
var result = await response.json();
var data = result.results;
var divsec = myElement('div','container','divsecid');
data.forEach((element)=>
{
//console.log(element);
var row = myElement('div','row');
var col1 = myElement('div','col-md-12 mb-3');
var card = myElement('div','card');
var row1 = myElement('div','row no-gutters');
var col2 = myElement('div','col-md-9');
var cardbody = myElement('div','card-body');
var section = myElement('div','section-card');
var psection = myElement('p');
psection.setAttribute('style','font-style:italic;font-weight:bold;color:blue');
psection.innerHTML = element.section.toUpperCase();
section.append(psection);
var dtitle = myElement('div','title-card');
dtitle.setAttribute('style','font-style:italic;font-weight:bold');
dtitle.innerHTML = element.title;
var ddate = myElement('div','date-card');
ddate.setAttribute('style','font-style:italic');
var by = myElement('div');
by.setAttribute('style','font-style:italic');
by.innerHTML = element.byline;
var d = new Date(element.created_date);
ddate.innerHTML = d.toLocaleString('default', { month: 'long' })+' '+d.getDate()+', '+d.getFullYear();
var dabstract = myElement('div','abstract-card');
dabstract.setAttribute('style','font-style:italic');
dabstract.innerHTML = element.abstract;
var cr = myElement('p');
cr.setAttribute('style','font-style:italic;color:blue')
var acr = myElement('a');
acr.setAttribute('href',element.url);
acr.setAttribute('target','_blank');
acr.innerHTML = 'Continue Reading';
cr.append(acr);
var col3 = myElement('div','col-md-3');
var img = myElement('img','img-fluid card-img-top');
img.setAttribute('src',element.multimedia[4].url);
img.setAttribute('style','display:block;height:250px;width:100%')
cardbody.append(section,dtitle,by,ddate,dabstract,cr);
col2.append(cardbody);
col3.append(img);
row1.append(col2,col3);
card.append(row1);
col1.append(card);
row.append(col1);
divsec.append(row);
});
main.innerHTML = divsec.innerHTML;
}
catch(error){
console.log(error);
}
}
//create element through DOM
function myElement(elemName,elemClass='',elemId='')
{
var elem = document.createElement(elemName);
elem.setAttribute('class',elemClass);
elem.setAttribute('id',elemId);
return elem;
}
|
4fe31f1b3f993fb3fee5ad976386e47ea8f8838f
|
[
"JavaScript"
] | 1 |
JavaScript
|
chinna18/Newyork-times-api
|
70ad0af6018252b758303cd69c1ecbf38ac7d089
|
a687c49c1442110a535af17f1909b3230b09447e
|
refs/heads/master
|
<repo_name>nganhopro2010/Mock1<file_sep>/app/src/main/java/com/hovanngan/mock1/model/History.kt
package com.hovanngan.mock1.model
data class History (val phoneNumber: String, val totalTime: String, val dateCreated: String)
<file_sep>/app/src/main/java/com/hovanngan/mock1/contact/ContactAdapter.kt
package com.hovanngan.mock1.contact
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.hovanngan.mock1.R
import com.hovanngan.mock1.databinding.ContactItemBinding
import com.hovanngan.mock1.model.Contact
class ContactAdapter :
RecyclerView.Adapter<ContactAdapter.ViewHolder>() {
private val data = ArrayList<Contact>()
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var mBinding: ContactItemBinding? = null
init {
mBinding = DataBindingUtil.bind(itemView)
}
}
fun setData(data: ArrayList<Contact>) {
this.data.addAll(data)
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.contact_item, parent, false)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = data[position]
holder.mBinding!!.apply {
tvName.text = item.name
tvPhoneNumber.text = item.phoneNumber
if (item.img != null) {
imgProfile.setImageBitmap(item.img)
} else {
imgProfile.setImageDrawable(
ContextCompat.getDrawable(
holder.itemView.context,
R.drawable.ic_contact_default_24dp
)
)
}
}
}
override fun getItemCount(): Int = data.size
}
<file_sep>/app/src/main/java/com/hovanngan/mock1/PagerAdapter.kt
package com.hovanngan.mock1
import android.content.Context
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import com.hovanngan.mock1.callhistory.CallHistoryFragment
import com.hovanngan.mock1.contact.ContactFragment
import com.hovanngan.mock1.model.Contact
import com.hovanngan.mock1.model.History
class PagerAdapter(private val context: Context, fm: FragmentManager) : FragmentStatePagerAdapter(fm) {
private var contacts = ArrayList<Contact>()
private var histories = ArrayList<History>()
override fun getCount() = 2
override fun getItem(position: Int): Fragment {
return when (position) {
0 -> {
ContactFragment.newInstance(contacts)
}
else -> {
CallHistoryFragment.newInstance(histories)
}
}
}
override fun getPageTitle(position: Int): CharSequence {
var title = ""
title = when (position) {
0 -> {
context.getString(R.string.danh_ba)
}
else -> {
context.getString(R.string.nhat_ky)
}
}
return title
}
override fun getItemPosition(`object`: Any): Int {
return POSITION_NONE
}
fun setData(contacts: ArrayList<Contact>, histories: ArrayList<History>) {
this.contacts = contacts
this.histories = histories
notifyDataSetChanged()
}
}
<file_sep>/app/src/main/java/com/hovanngan/mock1/callhistory/CallHistoryAdapter.kt
package com.hovanngan.mock1.callhistory
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.hovanngan.mock1.R
import com.hovanngan.mock1.databinding.HistoryItemBinding
import com.hovanngan.mock1.model.History
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList
class CallHistoryAdapter : RecyclerView.Adapter<CallHistoryAdapter.ViewHolder>() {
private val data = ArrayList<History>()
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var mBinding: HistoryItemBinding? = null
init {
mBinding = DataBindingUtil.bind(itemView)
}
}
fun setData(data: ArrayList<History>) {
this.data.addAll(data)
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.history_item, parent, false)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = data[position]
holder.mBinding!!.apply {
tvPhoneNumber.text = item.phoneNumber
tvTotalTime.text = getMinuteFromDuration(item.totalTime.toInt())
tvDateCreated.text = getTimeFromTimestamp(item.dateCreated.toLong())
}
}
override fun getItemCount(): Int = data.size
private fun getTimeFromTimestamp(time: Long): String {
return SimpleDateFormat("HH:mm:ss dd-MM-yyyy", Locale.getDefault()).format(time)
}
private fun getMinuteFromDuration(duration: Int): String {
val sec: Int = duration % 60
val min: Int = duration / 60 % 60
val hours: Int = duration / 60 / 60
return if (hours == 0) {
"[$min:$sec]"
} else {
"[$hours:$min:$sec]"
}
}
}
<file_sep>/app/src/main/java/com/hovanngan/mock1/MainActivity.kt
package com.hovanngan.mock1
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.CallLog
import android.provider.ContactsContract
import android.provider.MediaStore
import android.provider.Settings
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.databinding.DataBindingUtil
import com.hovanngan.mock1.databinding.ActivityMainBinding
import com.hovanngan.mock1.model.Contact
import com.hovanngan.mock1.model.History
class MainActivity : AppCompatActivity() {
private var mBinding: ActivityMainBinding? = null
private lateinit var pagerAdapter: PagerAdapter
companion object {
const val REQUEST_CODE: Int = 100
const val REQUEST_CODE_PERMISSION: Int = 200
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
pagerAdapter = PagerAdapter(this, supportFragmentManager)
mBinding?.apply {
pager.adapter = pagerAdapter
tabLayout.setupWithViewPager(pager)
}
checkPermissions()
}
private fun checkPermissions() {
if (ActivityCompat.checkSelfPermission(
this, Manifest.permission.READ_CONTACTS
) != PackageManager.PERMISSION_GRANTED ||
ActivityCompat.checkSelfPermission(
this,
Manifest.permission.READ_CALL_LOG
) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.READ_CONTACTS, Manifest.permission.READ_CALL_LOG),
REQUEST_CODE
)
} else {
updateUI()
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == REQUEST_CODE &&
grantResults[0] == PackageManager.PERMISSION_GRANTED &&
grantResults[1] == PackageManager.PERMISSION_GRANTED
) {
updateUI()
} else {
Toast.makeText(
this, getString(R.string.you_have_not_enough_grant_permission), Toast.LENGTH_SHORT
).show()
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
intent.data = Uri.parse("package:" + this.packageName)
startActivityForResult(intent, REQUEST_CODE_PERMISSION)
}
}
private fun updateUI() {
pagerAdapter.setData(
readContact(),
readCallHistory()
)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CODE_PERMISSION) {
checkPermissions()
}
}
private fun readCallHistory(): ArrayList<History> {
val histories = ArrayList<History>()
val cursor = contentResolver.query(
CallLog.Calls.CONTENT_URI,
null,
null,
null,
null
)
while (cursor!!.moveToNext()) {
val phoneNumber = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER))
val totalTime = cursor.getString(cursor.getColumnIndex(CallLog.Calls.DURATION))
val dateCreate = cursor.getString(cursor.getColumnIndex(CallLog.Calls.DATE))
val history = History(phoneNumber, totalTime, dateCreate)
histories.add(history)
}
cursor.close()
return histories
}
private fun readContact(): ArrayList<Contact> {
val contacts = ArrayList<Contact>()
val cursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
null,
null,
null
)
while (cursor!!.moveToNext()) {
val name =
cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME))
val numberPhone =
cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
val photoUri =
cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI))
val contact = Contact(name, null, numberPhone)
if (photoUri != null) {
contact.img = MediaStore.Images.Media.getBitmap(
contentResolver,
Uri.parse(photoUri)
)
}
contacts.add(contact)
}
cursor.close()
return contacts
}
}
<file_sep>/app/src/main/java/com/hovanngan/mock1/callhistory/CallHistoryFragment.kt
package com.hovanngan.mock1.callhistory
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import com.hovanngan.mock1.R
import com.hovanngan.mock1.databinding.FragmentHistoryBinding
import com.hovanngan.mock1.model.History
class CallHistoryFragment : Fragment() {
private var data = ArrayList<History>()
private var mBinding: FragmentHistoryBinding? = null
private lateinit var historyAdapter: CallHistoryAdapter
companion object {
fun newInstance(histories: ArrayList<History>) = CallHistoryFragment().apply {
data = histories
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_history, container, false)
return mBinding!!.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
historyAdapter = CallHistoryAdapter()
mBinding!!.rvHistory.adapter = historyAdapter
historyAdapter.setData(data)
if (data.size == 0) {
mBinding!!.tvNoData.visibility = View.VISIBLE
mBinding!!.rvHistory.visibility = View.GONE
} else {
mBinding!!.tvNoData.visibility = View.GONE
mBinding!!.rvHistory.visibility = View.VISIBLE
}
}
}
<file_sep>/app/src/main/java/com/hovanngan/mock1/model/Contact.kt
package com.hovanngan.mock1.model
import android.graphics.Bitmap
data class Contact(val name: String, var img: Bitmap?, val phoneNumber: String)
|
185824635604420bd9933c21fb0de54e1db20260
|
[
"Kotlin"
] | 7 |
Kotlin
|
nganhopro2010/Mock1
|
b2b7ff7f4ac51cf2d5e789dd4dd6f262869f2cf6
|
17590b046fef262b3bf8e14b802e00c7c5385d22
|
refs/heads/master
|
<repo_name>dqdinh3464/an-lac-vien<file_sep>/app/Eloquent/Owner.php
<?php
namespace App\Eloquent;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Owner extends Authenticatable
{
use FullTextSearch;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'phonenumber',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected function fullTextWildcards($term)
{
// removing symbols used by MySQL
$reservedSymbols = ['-', '+', '<', '>', '@', '(', ')', '~'];
$term = str_replace($reservedSymbols, '', $term);
$words = explode(' ', $term);
foreach ($words as $key => $word) {
/*
* applying + operator (required word) only big words
* because smaller ones are not indexed by mysql
*/
if (strlen($word) >= 1) {
$words[$key] = '+' . $word . '*';
}
}
$searchTerm = implode(' ', $words);
return $searchTerm;
}
public function fullTextSearch($query, $columns, $term)
{
$query->whereRaw("MATCH ({$columns}) AGAINST (? IN BOOLEAN MODE)", $this->fullTextWildcards($term));
return $query;
}
}
<file_sep>/app/Helpers/helper.php
<?php
use App\Home;
if (!function_exists('getOwner')) {
function getOwner($id)
{
$owner = \App\Owner::where('id', $id)->first();
return $owner;
}
}
if (!function_exists('getHomeType')) {
function getHomeType($id)
{
$type = \App\HomeType::where('id', $id)->first();
return $type;
}
}
if (!function_exists('getRow')) {
function getRow($y)
{
$rowHomes = Home::where('y', $y)->get()->sortBy('x')->toArray();
return $rowHomes;
}
}
<file_sep>/app/Http/Controllers/HomeController.php
<?php
namespace App\Http\Controllers;
use App\Home;
use App\HomeType;
use App\Owner;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
//Đăng nhập mới xem được chi tiết bên trong
// public function __construct()
// {
// $this->middleware('auth');
// }
/**
* Show the application dashboard.
*
* @return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
$homes = Home::all();
$owners = Owner::all();
$home_types = HomeType::all();
return view('map', compact('homes', 'owners', 'home_types'));
}
public function search(Request $request){
if ($request->ajax()) {
$listOwners = Owner::where('name', 'LIKE', '%' . $request->search . '%')->get();
$listIDOwners[] = null;
foreach ($listOwners as $key => $item){
$listIDOwners[$key] = $item->id;
}
return Response($listIDOwners);
}
}
}
<file_sep>/app/Owner.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Owner extends Model
{
protected $table = 'owners';
/**
* Reverse the migrations.
*
* @return void
*/
}
<file_sep>/database/migrations/2020_09_07_075607_create_owners_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateOwnersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('owners', function (Blueprint $table) {
DB::statement('ALTER TABLE owners ADD FULLTEXT `name` (`name`)'); //đánh index cho cột name
DB::statement('ALTER TABLE owners ENGINE = MyISAM');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('owners', function (Blueprint $table) {
DB::statement('ALTER TABLE users DROP INDEX name'); // khi chạy lệnh rollback thì làm điều ngược lại với thằng trên thế thôi
});
}
}
|
9645ac9f2f16a00c550ec05bdad1cb5f9a8972d4
|
[
"PHP"
] | 5 |
PHP
|
dqdinh3464/an-lac-vien
|
a72cc8593c82127f6c02cf795b958ba8116b59f0
|
ca1ab82d9e8da7ea0356b13bd95704575bc86a75
|
refs/heads/master
|
<repo_name>MajoPilande/axiedb<file_sep>/src/pages/Customers.jsx
import React from 'react'
import Table from '../components/table/Table'
import scholarList from '../assets/JsonData/scholars-list.json'
const customerTableHead = [
'',
'name',
'Ronin',
'Manager Share',
'Isko Share',
'Total Slp',
'Average'
]
const renderHead = (item, index) => <th key={index}>{item}</th>
const renderBody = (item, index) => (
<tr key={index}>
<td>{item.id}</td>
<td>{item.name}</td>
<td>{item.eth}</td>
<td>{item.managerShare}</td>
<td>{item.iskoShare}</td>
<td>{item.totalSlp}</td>
<td>{item.average}</td>
</tr>
)
const Customers = () => {
return (
<div>
<h2 className="page-header">
customers
</h2>
<div className="row">
<div className="col-12">
<div className="card">
<div className="card__body">
<Table
limit='10'
headData={customerTableHead}
renderHead={(item, index) => renderHead(item, index)}
bodyData={scholarList}
renderBody={(item, index) => renderBody(item, index)}
/>
</div>
</div>
</div>
</div>
</div>
)
}
export default Customers
|
a8f588ff7e7fe3eb7625ad68919a577b2bc42257
|
[
"JavaScript"
] | 1 |
JavaScript
|
MajoPilande/axiedb
|
3f5fa18b0b246bb3c7489456b1c8767564baffbe
|
4519ca87b42e3c7cfb363fec29df67fad5f301b4
|
refs/heads/master
|
<file_sep>// Instance method will be available to all instances but only load once in memory
CustomLoader.prototype.publicMethod = function () {
alert(this.publicVariable);
};
// Static variable shared by all instances
CustomLoader.current = null;
function CustomLoader(dom) {
this.progress = 0.0;
this.message = "";
this.dom = dom;
this.bullets = null;
this.bullets1 = null;
var SetImagesPositions = null;
var Update = null;
var loadingImageCount = 0;
//alert("onload before: " + this.dom + " / " + this.message + " / " + this.progress + " / " + loadingImageCount);
var parent = dom.parentNode;
var background = document.createElement("div");
background.style.background = "#a9bb8e";
background.style.position = "absolute";
parent.appendChild(background);
this.background = background;
background.style.display = "inline";
background.style.top = dom.offsetTop + 'px';
background.style.left = dom.offsetLeft + 'px';
background.style.width = dom.offsetWidth + 'px';
background.style.height = dom.offsetHeight + 'px';
var logoImage = document.createElement("img");
//alert("onload before0: " + loadingImageCount);
loadingImageCount++;
//alert("onload before1: " + loadingImageCount);
logoImage.onload = function (){
//alert("onload before2: " + loadingImageCount);
loadingImageCount--;
if(loadingImageCount<=0){
if(SetImagesPositions != null){
SetImagesPositions();
}
if(Update != null){
Update();
}
}
//alert("onload: " + loadingImageCount+" / "+SetImagesPositions);
};
logoImage.src = "TemplateData/soldier.png";
logoImage.style.position = "absolute";
parent.appendChild(logoImage);
this.logoImage = logoImage;
logoImage.style.width = 127 + 'px';
logoImage.style.height = 143 + 'px';
logoImage.style.display = "inline";
var companyImage = document.createElement("img");
loadingImageCount++;
companyImage.onload = function (){
loadingImageCount--;
if(loadingImageCount<=0){
if(SetImagesPositions != null){
SetImagesPositions();
}
if(Update != null){
Update();
}
}
};
companyImage.src = "TemplateData/logo.png";
companyImage.style.position = "absolute";
parent.appendChild(companyImage);
this.companyImage = companyImage;
companyImage.style.width = 368 + 'px';
companyImage.style.height = 17 + 'px';
companyImage.style.display = "inline";
var bullets = new Array(18);
for (var i = 0; i < bullets.length; i++) {
var bullet = document.createElement("img");
loadingImageCount++;
bullet.onload = function (){
loadingImageCount--;
if(loadingImageCount<=0){
if(SetImagesPositions != null){
SetImagesPositions();
}
if(Update != null){
Update();
}
}
};
bullet.src = "TemplateData/emptyBullet.png";
bullet.style.position = "absolute";
parent.appendChild(bullet);
bullet.style.width = 16 + 'px';
bullet.style.height = 64 + 'px';
bullet.style.display = "inline";
bullets[i] = bullet;
}
this.bullets = bullets;
var bullets1 = new Array(bullets.length);
for (var i = 0; i < bullets.length; i++) {
var bullet = document.createElement("img");
loadingImageCount++;
bullet.onload = function (){
loadingImageCount--;
if(loadingImageCount<=0){
if(SetImagesPositions != null){
SetImagesPositions();
}
if(Update != null){
Update();
}
}
};
bullet.src = "TemplateData/fullBullet.png";
bullet.style.position = "absolute";
parent.appendChild(bullet);
bullet.style.width = 16 + 'px';
bullet.style.height = 64 + 'px';
bullet.style.display = "inline";
bullets1[i] = bullet;
}
this.bullets1 = bullets1;
var messageArea = document.createElement("p");
messageArea.style.position = "absolute";
parent.appendChild(messageArea);
this.messageArea = messageArea;
messageArea.style.left = 0;
messageArea.style.width = '100%';
messageArea.style.textAlign = 'center';
messageArea.style.display = "inline";
this.SetProgress = function (progress) {
if (this.progress < progress)
this.progress = progress;
//this.messageArea.style.display = "none";
this.Update();
}
this.SetMessage = function (message) {
this.message = message;
this.messageArea.innerHTML = this.message;
/*this.background.style.display = "inline";
this.logoImage.style.display = "inline";
for (var i = 0; i < bullets.length; i++) {
var bullet = this.bullets[i];
bullet.style.display = "inline";
}
for (var i = 0; i < bullets1.length; i++) {
var bullet = this.bullets1[i];
bullet.style.display = "inline";
}*/
//this.Update();
}
this.Clear = function () {
this.background.style.display = "none";
this.logoImage.style.display = "none";
this.companyImage.style.display = "none";
for (var i = 0; i < bullets.length; i++) {
var bullet = this.bullets[i];
bullet.style.display = "none";
}
for (var i = 0; i < bullets1.length; i++) {
var bullet = this.bullets1[i];
bullet.style.display = "none";
}
}
SetImagesPositions = this.SetImagesPositions = function () {
if(this.bullets1 == null){
return;
}
this.interval = this.bullets[0].width + 5;
this.leftPos = dom.offsetLeft + (dom.offsetWidth * 0.5 - this.interval * bullets.length + logoImage.width);
this.topPos = dom.offsetTop + (dom.offsetHeight * 0.5 - logoImage.height * 0.5);
logoImage.style.top = this.topPos + 'px';
logoImage.style.left = this.leftPos + 'px';
this.leftPos += logoImage.width - 25;
this.topPos += logoImage.height * 0.5 - this.bullets[0].height * 0.5;
companyImage.style.top = this.topPos + this.bullets[0].height + 5 + 'px';
companyImage.style.left = this.leftPos + this.interval * bullets.length - companyImage.width - 5 + 'px';
this.messageArea.style.top = this.topPos + this.bullets[0].height + 25 + 'px';
}
this.SetImagesPositions();
Update = this.Update = function () {
if(this.bullets1 == null){
return;
}
this.SetImagesPositions();
for (var i = 0; i < bullets.length; i++) {
var bullet = this.bullets[i];
bullet.style.top = this.topPos + 'px';
bullet.style.left = this.leftPos + this.interval * i + 'px';
}
var full = bullets1.length * Math.min(this.progress, 1);
for (var i = 0; i < bullets1.length; i++) {
var bullet = this.bullets1[i];
if (i < full) {
//bullet.style.display = "inline";
bullet.style.opacity = "1.0";
} else if (i - full < 1) {
//bullet.style.display = "inline";
bullet.style.opacity = 1 - (i - full);
} else {
//bullet.style.display = "none";
bullet.style.opacity = "0.0";
}
bullet.style.top = this.topPos + 'px';
bullet.style.left = this.leftPos + this.interval * i + 'px';
}
}
}<file_sep>//alert("main: " + frameHref);
function SetStorageItem(itemName, itemValue) {
try {
if (supportsLocalStorage()) {
localStorage.setItem(itemName, itemValue);
}
} catch (e) {
}
}
function GetStorageItem(itemName) {
try {
if (supportsLocalStorage()) {
var itemValue = localStorage.getItem(itemName);
if (itemValue != null) {
SendMessage("GameManager", "GetStorageItem", itemName + "=" + itemValue);
} else {
SendMessage("GameManager", "GetStorageItem", itemName + "=");
}
}
} catch (e) {
}
}
function DeleteStorageItem(itemName) {
try {
if (supportsLocalStorage()) {
localStorage.removeItem(itemName);
}
} catch (e) {
}
}
function SyncFiles() { FS.syncfs(false, function (err) { }); }
function GetBrowserInfo() {
SendMessage("GameManager", "GetBrowserInfo", browsers.join(',') + "|" + (isMobile ? "1" : "0"));
}
function GetParams() {
//alert("frameHref: " + frameHref);
//alert("frameReferrer: " + frameReferrer);
SendMessage("GameManager", "OnGetHrefString", frameHref);
SendMessage("GameManager", "OnGetReferrer", frameReferrer);
}
function CanUseHardwareCursor() {
SendMessage("GameManager", "CanUseHardwareCursor", (isEdge || isIE) ? "0" : "1");
}
function GetScrollParams() {
SendMessage("GameManager", "GetScrollParams", "0.1|5|0.135");
}
function OpenNewTab(url) {
var newwindow = window.open(url, '_blank');
if (newwindow != null) {
newwindow.focus();
} else {
//SendMessage("GameManager", "OpenUrlError", "");
OpenUrl(url, '_blank');
}
}
function OpenUrl(url, windowType) {
var link = document.getElementById(canvasId);
var val = 1;
link.onmouseup = function () {
if (val == 1) {
var newwindow = window.open(url, windowType);
if (newwindow != null) {
newwindow.focus();
} else {
SendMessage("GameManager", "OpenUrlError", "");
}
val = 0;
} else {
// console.log("no");
}
}
}
function DebugAlert(err) {
alert(err);
}
function ShowError(err) {
alert(err);
}
function WrongBrowser() {
var imgLoaded = false;
var img = document.createElement("img");
var onLoad = function () {
if(imgLoaded){
return;
}
imgLoaded=true;
var w = document.documentElement.clientWidth, h = document.documentElement.clientHeight;
img.style.position = 'absolute';
var hOffset = (w / 2 - 650 / 2);
var top = (h - 180) / 2 + window.pageYOffset;
img.style.left = hOffset + 'px';
img.style.top = top + 'px';
var showInfo = function (text) {
var infoBlock = document.createElement('div');
var infoNode = document.createTextNode(text);
infoBlock.appendChild(infoNode);
infoBlock.style.color = "#222714";
infoBlock.style.textAlign = "center";
infoBlock.style.fontWeight = 'bold';
infoBlock.style.fontSize = "20px";
infoBlock.style.overflow = 'hidden';
//infoBlock.style.verticalAlign = 'middle';
infoBlock.style.position = img.style.position;
infoBlock.style.left = hOffset + 185 + 'px';
infoBlock.style.right = hOffset + 10 + 'px';
infoBlock.style.top = top + 50 + 'px';
infoBlock.style.bottom = top + 18 + 'px';
document.body.appendChild(infoBlock);
};
//alert("try text");
var infoXhr = GetXMLHttpRequest('StreamingAssets/GameAssets/Locale/' + locale + '/wrongBrowser.txt', 1000);
/*infoXhr.onreadystatechange = function() {
if (infoXhr.readyState == 4) {
if(infoXhr.status == 200) {
alert(infoXhr.responseText);
}
}
};*/
infoXhr.onload = function (e) {
if (infoXhr.status != 200) {
showInfo("\"Internet Explorer\" does not support this WebGL content fully. Use a different browser to start this game.");
} else {
showInfo(infoXhr.response);
}
};
infoXhr.ontimeout = function (e) {
showInfo("\"Internet Explorer\" does not support this WebGL content fully. Use a different browser to start this game.");
};
infoXhr.send();
//img.style.visibility = 'visible';
}
img.onload = onLoad;
img.setAttribute("src", 'StreamingAssets/wrongBrowser.jpg');
img.style.visibility = 'visible';
document.body.appendChild(img);
//onLoad();
/*try{
var cnv = document.getElementById("canvas");
cnv.parentElement.removeChild(cnv);
//document.removeChild(oldcanv)
}catch(e){
//alert(e);
}
try{
this.progress.Clear();
}catch(e){}*/
}
var onError = false;
function Errorhandler(err, url, line) {
if (onError) {
return true;
}
onError = true;
if(isIE){
WrongBrowser();
return true;
}
var img = document.createElement("img");
img.onload = function () {
var w = document.documentElement.clientWidth, h = document.documentElement.clientHeight;
img.style.position = 'absolute';
var hOffset = (w / 2 - img.offsetWidth / 2);
var top = (h - img.offsetHeight) / 2 + window.pageYOffset;
img.style.left = hOffset + 'px';
img.style.top = top + 'px';
var showTitle = function (text) {
var titleBlock = document.createElement('div');
var titleNode = document.createTextNode(text);
titleBlock.appendChild(titleNode);
titleBlock.style.color = "#a3ad82";
titleBlock.style.textAlign = "center";
titleBlock.style.fontWeight = 'bold';
titleBlock.style.fontSize = "20px";
titleBlock.style.overflow = 'hidden';
titleBlock.style.position = img.style.position;
titleBlock.style.left = hOffset + 120 + 'px';
titleBlock.style.right = hOffset + 120 + 'px';
titleBlock.style.top = top + 14 + 'px';
titleBlock.style.bottom = top + 165 + 'px';
document.body.appendChild(titleBlock);
};
var showInfo = function (text) {
var infoBlock = document.createElement('div');
var infoNode = document.createTextNode(text);
infoBlock.appendChild(infoNode);
infoBlock.style.color = "#222714";
infoBlock.style.textAlign = "center";
infoBlock.style.fontWeight = 'bold';
infoBlock.style.fontSize = "20px";
infoBlock.style.overflow = 'hidden';
//infoBlock.style.verticalAlign = 'middle';
infoBlock.style.position = img.style.position;
infoBlock.style.left = hOffset + 10 + 'px';
infoBlock.style.right = hOffset + 10 + 'px';
infoBlock.style.top = top + 60 + 'px';
infoBlock.style.bottom = top + 18 + 'px';
document.body.appendChild(infoBlock);
};
var titleXhr = GetXMLHttpRequest('StreamingAssets/GameAssets/Locale/' + locale + '/warningTitle.txt', 1000);
titleXhr.onload = function (e) {
if (titleXhr.status != 200) {
//alert( titleXhr.status + ': ' + titleXhr.statusText ); // пример вывода: 404: Not Found
showTitle("Warning");
} else {
showTitle(titleXhr.response);
}
};
titleXhr.ontimeout = function (e) {
showTitle("Warning");
};
titleXhr.send();
var infoXhr = GetXMLHttpRequest('StreamingAssets/GameAssets/Locale/' + locale + '/warningInfo.txt', 1000);
infoXhr.onload = function (e) {
if (infoXhr.status != 200) {
showInfo("An unknown error occurred, please try to restart the browser page.");
} else {
showInfo(infoXhr.response);
}
};
infoXhr.ontimeout = function (e) {
showInfo("An unknown error occurred, please try to restart the browser page.");
};
infoXhr.send();
img.style.visibility = 'visible';
}
img.setAttribute("src", 'StreamingAssets/servWinBg.png');
img.style.visibility = 'hidden';
document.body.appendChild(img);
alert(err);
return true;
}
function Compatibilitycheck() {
//WrongBrowser();
}
|
c2d9ceb4873049536e3115541e6e3801d2bb9198
|
[
"JavaScript"
] | 2 |
JavaScript
|
tank555/tank555.github.io
|
4e9e1f23c6cc0434869b654dc2f1e37fd9a0d7c3
|
dee08ff9a0a0a119a5482a78c8138fa38adc761c
|
refs/heads/main
|
<file_sep>import tkinter
import pyaudio
import wave
import threading
import subprocess
import os
from tkinter import Grid
import cv2
import PIL.Image, PIL.ImageTk
import time
import datetime
counter = 0
running = False
class AudioRecorder:
# Audio class based on pyAudio and Wave
def __init__(self):
self.open = True
self.rate = 44100
self.frames_per_buffer = 1024
self.channels = 2
self.format = pyaudio.paInt16
self.audio_filename = "../temp_audio2.wav"
self.audio = pyaudio.PyAudio()
self.stream = self.audio.open(format=self.format,
channels=self.channels,
rate=self.rate,
input=True,
frames_per_buffer=self.frames_per_buffer)
self.audio_frames = []
# Audio starts being recorded
def record(self):
self.stream.start_stream()
while self.open:
data = self.stream.read(self.frames_per_buffer)
self.audio_frames.append(data)
if not self.open:
break
# Finishes the audio recording therefore the thread too
def stop(self):
if self.open:
self.open = False
self.stream.stop_stream()
self.stream.close()
self.audio.terminate()
waveFile = wave.open(self.audio_filename, 'wb')
waveFile.setnchannels(self.channels)
waveFile.setsampwidth(self.audio.get_sample_size(self.format))
waveFile.setframerate(self.rate)
waveFile.writeframes(b''.join(self.audio_frames))
waveFile.close()
pass
# Launches the audio recording function using a thread
def start(self):
audio_thread = threading.Thread(target=self.record)
audio_thread.start()
# def start_audio_recording(filename):
# global audio_thread
#
# audio_thread = AudioRecorder()
# audio_thread.start()
#
# return filename
def start_AVrecording(filename):
#global video_thread
global audio_thread
#video_thread = VideoRecorder()
audio_thread = AudioRecorder()
audio_thread.start()
#video_thread.start()
return filename
def stop_AVrecording(filename):
audio_thread.stop()
#frame_counts = video_thread.frame_counts
#elapsed_time = time.time() - video_thread.start_time
#recorded_fps = frame_counts / elapsed_time
#print("total frames " + str(frame_counts))
#print("elapsed time " + str(elapsed_time))
#print("recorded fps " + str(recorded_fps))
#video_thread.stop()
# Makes sure the threads have finished
while threading.active_count() > 1:
time.sleep(1)
# Merging audio and video signal
# if abs(recorded_fps - 6) >= 0.01: # If the fps rate was higher/lower than expected, re-encode it to the expected
#
# print("Re-encoding")
# cmd = "ffmpeg -r " + str(recorded_fps) + " -i temp_video.avi -pix_fmt yuv420p -r 6 temp_video2.avi"
# subprocess.call(cmd, shell=True)
#
# print("Muxing")
# cmd = "ffmpeg -ac 2 -channel_layout stereo -i temp_audio.wav -i temp_video2.avi -pix_fmt yuv420p " + filename + ".avi"
# subprocess.call(cmd, shell=True)
#
# else:
#
# print("Normal recording\nMuxing")
# cmd = "ffmpeg -ac 2 -channel_layout stereo -i temp_audio.wav -i temp_video.avi -pix_fmt yuv420p " + filename + ".avi"
# subprocess.call(cmd, shell=True)
#
# print("..")
def file_manager(filename):
local_path = os.getcwd()
if os.path.exists(str(local_path) + "/temp_audio2.wav"):
os.remove(str(local_path) + "/temp_audio2.wav")
if os.path.exists(str(local_path) + "/" + filename + ".avi"):
os.remove(str(local_path) + "/" + filename + ".avi")
class App:
def __init__(self, window, window_title, video_source=0):
self.window = window
self.window.title(window_title)
self.video_source = video_source
# open video source (by default this will try to open the computer webcam)
self.vid = MyVideoCapture(self.video_source)
# Create a canvas that can fit the above video source size
self.canvas = tkinter.Canvas(window, width=self.vid.width, height=self.vid.height)
self.canvas.pack()
label = tkinter.Label(window, text="Welcome!", fg="black", font="Verdana 30 bold")
label.pack()
# Button that lets the user take a snapshot
self.btn_snapshot = tkinter.Button(window, text="Snapshot", width=30, command=self.snapshot)
self.btn_snapshot.pack(side=tkinter.LEFT)
# self.btn_snapshot.grid(row=0,column=0,sticky="NSEW")
# Button for start
self.btn_start = tkinter.Button(window, text="Start", width=30, command=lambda:self.start(label))
self.btn_start.pack(side=tkinter.LEFT)
# self.btn_start.grid(row=0, column=0, sticky="NSEW")
# Button for stop
self.btn_stop = tkinter.Button(window, text="Stop", width=30, fg="red", command=self.stop)
self.btn_stop.pack(side=tkinter.LEFT)
# self.btn_stop.grid(row=0, column=0, sticky="NSEW")
# After it is called once, the update method will be automatically called every delay milliseconds
self.delay = 15
self.update()
self.window.mainloop()
def snapshot(self):
# Get a frame from the video source
ret, frame = self.vid.get_frame()
if ret:
cv2.imwrite("frame-" + time.strftime("%d-%m-%Y-%H-%M-%S") + ".jpg", cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
def update(self):
# Get a frame from the video source
ret, frame = self.vid.get_frame()
if ret:
self.photo = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(frame))
self.canvas.create_image(0, 0, image=self.photo, anchor=tkinter.NW)
self.window.after(self.delay, self.update)
def _set_max_timer(self):
""" Add Student Popup """
self._popup_win = tkinter.Toplevel()
self._popup = set_max_timer(self._popup_win, self._close_student_cb)
# https://www.geeksforgeeks.org/create-stopwatch-using-python/
def counter_label(self, label):
def count():
if running:
global counter
# To manage the intial delay.
if counter == 0:
display = "Starting..."
else:
tt = datetime.datetime.fromtimestamp(counter)
print("THIS IS TT", tt)
string = tt.strftime("%M:%S")
display = string
label['text'] = display # Or label.config(text=display)
label.after(1000, count)
counter += 1
# Triggering the start of the counter.
count()
def start(self, label):
global running
running = True
self.counter_label(label)
# self.file_manager("file")
self.start_audio_recording()
self.btn_start['state'] = 'disabled'
self.btn_stop['state'] = 'normal'
# Stop function of the stopwatch
def stop(self):
global running
self.btn_start['state'] = 'normal'
self.btn_stop['state'] = 'disabled'
self.stop_AVrecording()
running = False
def file_manager(filename):
local_path = os.getcwd()
if os.path.exists(str(local_path) + "/temp_audio2.wav"):
os.remove(str(local_path) + "/temp_audio2.wav")
if os.path.exists(str(local_path) + "/" + filename + ".avi"):
os.remove(str(local_path) + "/" + filename + ".avi")
def start_audio_recording(filename):
global audio_thread
audio_thread = AudioRecorder()
audio_thread.start()
return filename
def stop_AVrecording(filename):
audio_thread.stop()
# frame_counts = video_thread.frame_counts
# elapsed_time = time.time() - video_thread.start_time
# recorded_fps = frame_counts / elapsed_time
# print("total frames " + str(frame_counts))
# print("elapsed time " + str(elapsed_time))
# print("recorded fps " + str(recorded_fps))
# video_thread.stop()
# Makes sure the threads have finished
while threading.active_count() > 1:
time.sleep(1)
# Merging audio and video signal
# if abs(recorded_fps - 6) >= 0.01: # If the fps rate was higher/lower than expected, re-encode it to the expected
#
# print("Re-encoding")
# cmd = "ffmpeg -r " + str(recorded_fps) + " -i temp_video.avi -pix_fmt yuv420p -r 6 temp_video2.avi"
# subprocess.call(cmd, shell=True)
#
# print("Muxing")
# cmd = "ffmpeg -ac 2 -channel_layout stereo -i temp_audio.wav -i temp_video2.avi -pix_fmt yuv420p " + filename + ".avi"
# subprocess.call(cmd, shell=True)
#
# else:
#
# print("Normal recording\nMuxing")
# cmd = "ffmpeg -ac 2 -channel_layout stereo -i temp_audio.wav -i temp_video.avi -pix_fmt yuv420p " + filename + ".avi"
# subprocess.call(cmd, shell=True)
#
# print("..")
class MyVideoCapture:
def __init__(self, video_source=0):
# Open the video source
self.vid = cv2.VideoCapture(video_source)
if not self.vid.isOpened():
raise ValueError("Unable to open video source", video_source)
# Get video source width and height
self.width = self.vid.get(cv2.CAP_PROP_FRAME_WIDTH)
self.height = self.vid.get(cv2.CAP_PROP_FRAME_HEIGHT)
def get_frame(self, ret=None):
if self.vid.isOpened():
ret, frame = self.vid.read()
if ret:
# Return a boolean success flag and the current frame converted to BGR
return ret, cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
else:
return ret, None
else:
return ret, None
# Release the video source when the object is destroyed
def __del__(self):
if self.vid.isOpened():
self.vid.release()
# Create a window and pass it to the Application object
App(tkinter.Tk(), "AUDIENCE")
<file_sep>from pathlib import Path
class Speech:
def transcribe_file(speech_file):
"""Transcribe the given audio file."""
from google.cloud import speech
import io
client = speech.SpeechClient()
with io.open(speech_file, "rb") as audio_file:
content = audio_file.read()
audio = speech.RecognitionAudio(content=content)
config = speech.RecognitionConfig(
encoding=speech.RecognitionConfig.AudioEncoding.FLAC,
sample_rate_hertz=16000,
language_code="en-US",
)
response = client.recognize(config=config, audio=audio)
# Each result is for a consecutive portion of the audio. Iterate through
# them to get the transcripts for the entire audio file.
for result in response.results:
# The first alternative is the most likely one for this portion.
print(u"Transcript: {}".format(result.alternatives[0].transcript))
@staticmethod
def transform():
import sox
import os
local_path = Path(os.getcwd())
tfm = sox.Transformer()
tfm.set_output_format(file_type='flac', rate=16000, channels=1, bits=16, encoding='signed-integer')
tfm.build(str(local_path / "temp_audio2.wav"), str(local_path / "temp_audio3.flac"))
<file_sep>import cv2
import os
import io
from google.cloud import vision
"""
Wrapper class for Google Vision API calls working with OpenCV to detect labels and to detect faces
"""
class cloud_vision_helpers:
"""
Constructor for cloud_vision object
"""
def __init__(self):
self.labels = None
"""
Method for detecting labels from Google API documents
@param path: A string indicating the location in a system to write to upon taking a photo
"""
def detect_label(self, path):
# Imports the Google Cloud client library
# Instantiates a client
client = vision.ImageAnnotatorClient()
# The name of the image file to annotate
file_name = path
# Loads the image into memory
with io.open(file_name, 'rb') as image_file:
content = image_file.read()
image = vision.Image(content=content)
# Performs label detection on the image file
response = client.label_detection(image=image)
labels = response.label_annotations
print('Labels:')
for label in labels:
print(label.description)
self.labels = label.description
"""
Method for detecting faces and emotions from Google API documents
@param path: A string indicating the location in a system to write to upon taking a photo
"""
@staticmethod
def detect_faces(path):
"""Detects faces in an image."""
from google.cloud import vision
import io
client = vision.ImageAnnotatorClient()
with io.open(path, 'rb') as image_file:
content = image_file.read()
image = vision.Image(content=content)
response = client.face_detection(image=image)
faces = response.face_annotations
# Names of likelihood from google.cloud.vision.enums
likelihood_name = ('UNKNOWN', 'VERY_UNLIKELY', 'UNLIKELY', 'POSSIBLE',
'LIKELY', 'VERY_LIKELY')
print('Faces:')
for face in faces:
print('anger: {}'.format(likelihood_name[face.anger_likelihood]))
print('joy: {}'.format(likelihood_name[face.joy_likelihood]))
print('surprise: {}'.format(likelihood_name[face.surprise_likelihood]))
vertices = (['({},{})'.format(vertex.x, vertex.y)
for vertex in face.bounding_poly.vertices])
print('face bounds: {}'.format(','.join(vertices)))
if response.error.message:
raise Exception(
'{}\nFor more info on error messages, check: '
'https://cloud.google.com/apis/design/errors'.format(
response.error.message))
def getlabels(self):
return self.labels
if __name__ == "__main__":
cap = cv2.VideoCapture(0)
directory = r'/home/chrischang5/PycharmProjects/SFHACKS2021'
os.chdir(directory)
CV1 = cloud_vision_helpers()
while True:
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('l'):
cv2.imwrite('file.jpg', frame)
CV1.detect_label('/home/chrischang5/PycharmProjects/SFHACKS2021/file.jpg')
if cv2.waitKey(1) & 0xFF == ord('f'):
cv2.imwrite('file.jpg', frame)
CV1.detect_faces(r'C:\Users\caleb\Pictures\test\file.jpg')
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
<file_sep>import threading
import pyaudio
import wave
from SpeechRecognize import Speech
import tkinter
from tkinter import Grid, simpledialog
import cv2
import PIL.Image, PIL.ImageTk
import time
import datetime
# from input_gui import MaxTimeWindow
from cloud_vision_helpers import cloud_vision_helpers
import os
from pathlib import Path
counter = 0
running = False
class AudioRecorder:
# Audio class based on pyAudio and Wave
def __init__(self):
self.open = True
self.rate = 44100
self.frames_per_buffer = 1024
self.channels = 2
self.format = pyaudio.paInt16
self.audio_filename = "temp_audio2.wav"
self.audio = pyaudio.PyAudio()
self.stream = self.audio.open(format=self.format,
channels=self.channels,
rate=self.rate,
input=True,
frames_per_buffer=self.frames_per_buffer)
self.audio_frames = []
# Audio starts being recorded
def record(self):
self.stream.start_stream()
while self.open:
data = self.stream.read(self.frames_per_buffer)
self.audio_frames.append(data)
if not self.open:
break
# Finishes the audio recording therefore the thread too
def stop(self):
if self.open:
self.open = False
self.stream.stop_stream()
self.stream.close()
self.audio.terminate()
waveFile = wave.open(self.audio_filename, 'wb')
waveFile.setnchannels(self.channels)
waveFile.setsampwidth(self.audio.get_sample_size(self.format))
waveFile.setframerate(self.rate)
waveFile.writeframes(b''.join(self.audio_frames))
waveFile.close()
pass
# Launches the audio recording function using a thread
def start(self):
audio_thread = threading.Thread(target=self.record)
audio_thread.start()
class App:
def __init__(self, window, window_title, video_source=0):
# Path object to store paths on both Linux and Windows
# self.file_path = Path()
self.window = window
self.window.title(window_title)
self.video_source = video_source
self.counting = 0
# open video source (by default this will try to open the computer webcam)
self.vid = MyVideoCapture(self.video_source)
# Create a canvas that can fit the above video source size
self.canvas = tkinter.Canvas(window, width=self.vid.width, height=self.vid.height)
self.canvas.pack()
label = tkinter.Label(window, text="Welcome!", fg="black", font="Verdana 30 bold")
label.pack()
# Button that lets the user take a snapshot
# self.btn_snapshot = tkinter.Button(window, text="Snapshot", width=30, command=self.snapshot)
# self.btn_snapshot.pack(side=tkinter.LEFT)
# self.btn_snapshot.grid(row=0,column=0,sticky="NSEW")
# Button for start
self.btn_start = tkinter.Button(window, text="Start", width=30, command=lambda: self.start(label))
self.btn_start.pack(side=tkinter.LEFT)
# self.btn_start.grid(row=0, column=0, sticky="NSEW")
# Button for stop
self.btn_stop = tkinter.Button(window, text="Stop", width=30, fg="red", command=self.stop)
self.btn_stop.pack(side=tkinter.LEFT)
# self.btn_stop.grid(row=0, column=0, sticky="NSEW")
# Button for Input
# self.btn_max_time = tkinter.Button(window, text="Set max time limit", width=30,
# command=self.set_max_timer_window )
# self.btn_max_time.pack(side=tkinter.LEFT)
# After it is called once, the update method will be automatically called every delay milliseconds
self.delay = 15
self.update()
self.window.mainloop()
def cv_function(self):
local_path = Path(os.getcwd())
c = self.counting
i = 1
while i <= c:
cloud_vision_helpers.detect_faces(local_path / ("frame-" + str(i) + ".jpg"))
os.remove(local_path / ("frame-" + str(i) + ".jpg"))
i += 1
@staticmethod
def speechtotext():
local_path = Path(os.getcwd())
Speech.transform()
Speech.transcribe_file(local_path / "temp_audio3.flac")
def snapshot(self):
# Get a frame from the video source
self.counting += 1
ret, frame = self.vid.get_frame()
if ret:
cv2.imwrite(f"frame-{self.counting}.jpg", cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
threading.Timer(10, self.snapshot).start()
def stop_snapshot(self):
threading.Timer(10, self.snapshot).cancel()
def update(self):
# Get a frame from the video source
ret, frame = self.vid.get_frame()
if ret:
self.photo = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(frame))
self.canvas.create_image(0, 0, image=self.photo, anchor=tkinter.NW)
self.window.after(self.delay, self.update)
def set_max_timer_window(self):
self._popup_win = tkinter.Toplevel()
# self._popup = MaxTimeWindow(self._popup_win, self._close_student_cb)
# max_time_window = simpledialog.askinteger(title="Test",
# prompt="Maximum Time")
# max_time_window = tkinter.Toplevel(self.window)
# max_time_window.geometry("300x200")
# tkinter.Label(max_time_window, text="Maximum Time").pack()
def _close_student_cb(self):
""" Close Add Student Popup """
self._popup_win.destroy()
# https://www.geeksforgeeks.org/create-stopwatch-using-python/
def counter_label(self, label):
def count():
if running:
global counter
# To manage the intial delay.
if counter == 0:
display = "Starting..."
else:
tt = datetime.datetime.fromtimestamp(counter)
string = tt.strftime("%M:%S")
display = string
label['text'] = display # Or label.config(text=display)
label.after(1000, count)
counter += 1
# Triggering the start of the counter.
count()
def start(self, label):
global running
global t
running = True
self.counter_label(label)
self.start_audio_recording()
self.btn_start['state'] = 'disabled'
self.btn_stop['state'] = 'normal'
t = threading.Timer(10, self.snapshot)
t.start()
# self.snapshot()
# Stop function of the stopwatch
def stop(self):
global running
self.btn_start['state'] = 'normal'
self.btn_stop['state'] = 'disabled'
self.stop_AVrecording()
t.cancel()
running = False
# self.stop_snapshot()
self.cv_function()
self.speechtotext()
@staticmethod
def file_manager(filename):
local_path = Path(os.getcwd())
print(local_path / "temp_audio2.wav")
print(local_path / (str(filename) + ".avi"))
if os.path.exists(local_path / "temp_audio2.wav"):
os.remove(local_path / "temp_audio2.wav")
if os.path.exists(local_path / (str(filename) + ".avi")):
os.remove(local_path / (str(filename) + ".avi"))
@staticmethod
def start_audio_recording():
global audio_thread
audio_thread = AudioRecorder()
audio_thread.start()
def stop_AVrecording(self):
audio_thread.stop()
class MyVideoCapture:
def __init__(self, video_source=0):
# Open the video source
self.vid = cv2.VideoCapture(video_source)
if not self.vid.isOpened():
raise ValueError("Unable to open video source", video_source)
# Get video source width and height
self.width = self.vid.get(cv2.CAP_PROP_FRAME_WIDTH)
self.height = self.vid.get(cv2.CAP_PROP_FRAME_HEIGHT)
def get_frame(self, ret=None):
if self.vid.isOpened():
ret, frame = self.vid.read()
if ret:
# Return a boolean success flag and the current frame converted to BGR
return ret, cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
else:
return ret, None
else:
return ret, None
# Release the video source when the object is destroyed
def __del__(self):
if self.vid.isOpened():
self.vid.release()
# Create a window and pass it to the Application object
App(tkinter.Tk(), "AUDIENCE")
<file_sep># Audience
This project was created and submitted as part of SFHacks 2021. Audience is a Python application that provides presenters with metrics and analytics on a presentation's delivery, including insights on facial emotions and automatically conversion of audio into a text transcript.
# Video Demonstration
[](http://www.youtube.com/watch?v=fJ8iqvdxKxc "Video Demonstration")
# DevPost Project Post
https://devpost.com/software/audience
# Inspiration
We wanted to create an application that would allow presenters to evaluate their presentations to ensure they are conveying their message as intended based on their facial expressions.
# What it does
As you begin to record yourself on the program, it takes a picture of your face at certain times in your recording and evaluates your expressions in the recording. Utilizing Google's cloud vision API, we are able to categorize expressions you would make at any time and return the results, allowing you to see the overall emotions your face seems to be expressed throughout the presentation. We wanted to create a kind of practice tool that would allow presenters to evaluate their presentation to ensure they are conveying their message as intended based on their facial expressions.
# How we built it
We used the Vision and Speech Google Cloud Platform APIs to process and analyze audio and video data. Tkinter was used as the UI framework and PyAudio and SoX were used to process audio data to work with the Speech GCP API.
# Technologies Used
- GCP Speech
- GCP Vision
- Tkinter
- SoX
- OpenCV
# Challenges we ran into
We had issues with threading as we wanted to have multiple processes running at the same time. For example, we wanted to capture audio, capture video, and show a GUI simultaneously.
# Accomplishments that we're proud of
We are proud that we have a working foundation for our idea and that we were able to take an idea and execute it so quickly.
# What we learned
Our team learned more about the usefulness of APIs and got some first-hand experience on the many different ways we could incorporate these APIs into our programs. We also learned to work with threads and basic UI design principles.
# What's next for Audience
We plan to utilize more of the Vision and Speech APIs to provide more metrics for presenters and expand on the current UI using matplotlib to provide further analytics.
|
6a6a5d0e111fd935cdd3aedb310c4f8580ea86e7
|
[
"Markdown",
"Python"
] | 5 |
Python
|
chrischang5/SFHACKS2021-Audience
|
533a1518c73910b39a81e0cf889ed63a2383fa34
|
3f55a4b64600cbd43ec5ae3e326696ef5705cdb5
|
refs/heads/master
|
<file_sep>$(document).ready(function(){
if(typeof localStorage.srvSubmit !== "undefined"){
$(".body-left-form-title").html(thankyouElement());
$(".input-section").hide();
}
$("input[type='text']").on("change",function(){
var id = $(this).attr("id").toLowerCase();
var value = $(this).val();
var condition;
if(id=="postcode")condition=validatePost(value);
if(id=="email")condition=validateEmail(value);
if(id=="mobile")condition=validateMobile(value);
if(!condition){
displayError(id);
}else{
displayCheck(id);
}
});
$("input[type='submit']").click(function(e){
e.preventDefault();
var err=0;
var con;
var postcode = $("input[name='potcode']").val();
var enforce = $("input[name='enforce']:checked").val();
var email = $("input[name='email']").val();
var mobile = $("input[name='mobile']").val();
var arr = ["postcode","email","mobile"];
if(enforce=="" || typeof enforce==="undefined"){
err++;
displayRadioError();
}else{
localStorage.enforce = enforce;
}
$.each(arr,function(key,value){
var xval = $("input[name='"+value+"']").val();
if(value=="postcode")con=validatePost(xval);
if(value=="email")con=validateEmail(xval);
if(value=="mobile")con=validateMobile(xval);
if(xval=="" || !con){
err++;
displayError(value);
}else{
displayCheck(value);
localStorage.setItem(value,xval);
}
});
//console.log(err);
if(err<=0){
localStorage.srvSubmit = 1;
$(".input-section").hide();
$(".body-left-form-title").hide();
showLeftLoading();
setTimeout(function(){
hideLeftLoading();
$(".body-left-form-title").html(thankyouElement());
$(".body-left-form-title").fadeIn();
},500);
//$(".body-left-form-title").fadeIn();
//$(".body-left-form-title").html(thankyouElement());
}
});
$("input[name='enforce'] + label").click(removeRadioError);
});
function displayError(id){
$("#"+id).removeClass();
$("#"+id).addClass("error");
//$("#"+id).
// $("#"+id).parent().append("<img src='images/error2.png' width='34em' style='display: inline-block;vertical-align: bottom;'/>");
}
function displayRadioError(){
removeRadioError();
//console.log($("input[name='enforce']").parent().find("label").css({"border-color":"red!important"}));
$("input[name='enforce']").parent().find("label").css({"border-color":"red"});
$("input[name='enforce']").parent().append("<img src='images/error2.png' width='25em'>");
}
function removeRadioError(){
if($("input[name='enforce']").parent().find("img").length >0){
$("input[name='enforce']").parent().find("img").remove();
}
$("input[name='enforce']").parent().find("label").css({"border-color":"#0176d2"});
}
function removeError(id){
$("#"+id).removeClass("error");
}
function displayCheck(id){
$("#"+id).removeClass();
$("#"+id).addClass("check");
}
function validatePost(post){
var patern = /^[0-9]{4}$/;
return patern.test(post);
}
function validateEmail(email) {
var patern = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return patern.test(email);
}
function validateMobile(mobile) {
var patern = /^(\+63|09)+[0-9]{9}$/;
return patern.test(mobile);
}
function thankyouElement(){
return "Thank you for you willingness to participate on our research study. <br/><br/> <small>Survey link was sent to your email address.</small> <br/><br/><img src='images/emailsend.gif'/>";
}
function showLeftLoading(){
$("#body-left .loader").show();
}
function hideLeftLoading(){
$("#body-left .loader").hide();
}
function mobileDropMenuToggle(){
$("#centerNav").toggle();
}
/*
$(document).ready(function(){
var xaudio = $("#myAudio")[0];
var xvideo = $("#myVideo")[0];
var xmedia,xfunction;
$("#myAudio").hide();
$("#audioList").on("change",function(){
$("#myAudio").attr("src","audio/"+$(this).val());
$("#playBtn").html("Pause");
$("#playBtn").click();
});
$("button").click(function(){
xmedia = ($(this).attr("class") == "audio")?xaudio:xvideo;
xfunction = $(this).attr("_f");
if(xfunction=="play"){
if (!xmedia.paused) {
xmedia.pause();
$(this).html("Play");
} else {
xmedia.play();
$(this).html("Pause");
}
}
if(xfunction=="stop"){
xmedia.pause();
xmedia.load();
$("#"+$(this).attr("class")+"Field").find("button:eq(0)").html("Play");
}
});
checkLocalStorage();
$("#mySubmitwebworker").click(function(e){
e.preventDefault();
var email = $("input[name='email']").val();
var w;
if(email!="") {
if (typeof(Worker) !== "undefined") {
if (typeof(w) == "undefined") {
w = new Worker("js/webworkers.js");
}
w.onmessage = function (event) {
console.log(event.data);
var myDatas = event.data[email];
if (typeof myDatas !== "undefined") {
$.each(myDatas, function (key, value) {
localStorage.clickcount = 1;
$("#postcode").val(value.postcode);
$("#mobilenum").val(value.mobilenum);
$("#enforce").val((value.enforce) ? "Yes" : "No");
localStorage.setItem("postcode", value.postcode);
localStorage.setItem("mobilenum", value.mobilenum);
localStorage.setItem("enforce", value.enforce);
$(".formholder").hide();
});
} else {
alert("no records fetched!");
}
};
} else {
//document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Workers...";
}
}else{
alert("empty email");
}
});
$("#mySubmitajax").click(function(e){
e.preventDefault();
var email = $("input[name='email']").val();
if(email!="") {
$.ajax({
url: 'js/users.json',
type: "get",
dataType: "json",
success: function (data) {
//console.log(data['<EMAIL>']);
//console.log(object.keys(data).length);
if(typeof data[email] !== "undefined") {
localStorage.clickcount = 1;
$.each(data[email], function (key, value) {
$("#postcode").val(value.postcode);
$("#mobilenum").val(value.mobilenum);
$("#enforce").val((value.enforce) ? "Yes" : "No");
localStorage.setItem("postcode", value.postcode);
localStorage.setItem("mobilenum", value.mobilenum);
localStorage.setItem("enforce", value.enforce);
$(".formholder").hide();
});
}else{
alert("no records fetched!");
}
},
error: function () {
alert("error");
}
});
}else{
alert("empty email");
}
});
function checkLocalStorage(){
if(typeof localStorage.clickcount !== "undefined"){
$("#postcode").val(localStorage.getItem("postcode"));
$("#mobilenum").val(localStorage.getItem("mobilenum"));
$("#enforce").val((localStorage.getItem("enforce"))?"Yes":"No");
$(".formholder").hide();
}
}
});
*/
/*
var myAudio = document.getElementById("myAudio");
var myVideo = document.getElementById("myVideo");
var audioSelection = document.getElementById("audioList");
var selectedAudio;
document.getElementById("myVideo").controls=false;
var buttons = document.getElementsByTagName("button");
for(i=0;i<buttons.length;i++){
buttons[i].style.width = "5%";
buttons[i].style.borderRadius = "10px";
buttons[i].setAttribute("onclick","myClick(this)");
}
myAudio.style.display="none ";
audioSelection.onchange = function(){
selectedAudio = document.getElementById("audioList").value;
if(selectedAudio!="#")
myAudio.setAttribute("src", "audio/" + selectedAudio);
else
myAudio.setAttribute("src", "");
myAudio.load();
playBtn.innerHTML="Play";
};
function myClick(element){
var id = element.getAttribute("id");
var btn = document.getElementById(id);
if(id=="playBtn"){
var audioSrc = document.getElementById("myAudio").getAttribute("src");
if(audioSrc!=null && audioSrc!="") {
if (!myAudio.paused) {
myAudio.pause();
btn.innerHTML = "Play";
} else {
myAudio.play();
btn.innerHTML = "Pause";
}
myAudio.addEventListener("ended", function(){
btn.innerHTML = "Play";
});
}else{
alert("No audio selected.");
}
}
if(id=="stopBtn"){
myAudio.pause();
myAudio.load();
document.getElementById("playBtn").innerHTML="Play";
}
if(id=="playBtnVid"){
if (!myVideo.paused) {
myVideo.pause();
btn.innerHTML = "Play Video";
} else {
myVideo.play();
btn.innerHTML = "Pause Video";
}
myVideo.addEventListener("ended", function(){
btn.innerHTML = "Play Video";
});
}
if(id=="stopBtnVid"){
myVideo.pause();
myVideo.load();
document.getElementById("playBtnVid").innerHTML="Play Video";
}
}
*/
<file_sep>var i = 0;
function timedCount() {
i = i + 1;
loadData(i);
setTimeout("timedCount()",1);
}
function loadData(size){
var xobj = new XMLHttpRequest();
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == 200) {
var obj = JSON.parse(xobj.responseText);
if(size <= Object.keys(obj).length) {
if (size == Object.keys(obj).length) {
postMessage(obj);
}
}
}
};
xobj.open('GET', 'users.json');
xobj.send();
}
timedCount();
|
1876fba311d23792acbfc7d4292f4b25ea9dc99d
|
[
"JavaScript"
] | 2 |
JavaScript
|
dpritos/LIBERO
|
1e52f1edd1685edceb619854faed807cf56054dc
|
b020848ef90721f09a7a538892495c7f7050a967
|
refs/heads/master
|
<repo_name>AkashChauhanSoftEngi/SpringBootRestUniversityElectionSystem<file_sep>/src/main/java/com/example/entity/Person.java
package com.example.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Person {
@Id
String name;
String post;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPost() {
return post;
}
public void setPost(String post) {
this.post = post;
}
}
<file_sep>/src/main/java/com/example/service/ElectionSystemServiceImpl.java
package com.example.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.dto.PersonDto;
import com.example.dto.PostDto;
import com.example.dto.StudentDto;
import com.example.entity.Person;
import com.example.entity.Post;
import com.example.entity.Student;
import com.example.repository.PersonRepository;
import com.example.repository.PostRepository;
import com.example.repository.StudentRepository;
@Service
public class ElectionSystemServiceImpl implements ElectionSystemService {
@Autowired
StudentRepository studentRepository;
@Autowired
PersonRepository personRepository;
@Autowired
PostRepository postRepository;
@Override
public StudentDto saveStudent(StudentDto inStudentDto) {
if(inStudentDto.getChoiceForPresident().equals(inStudentDto.getChoiceForVicePresident())){
return null;
}
if(inStudentDto.getChoiceForPresident().equals(inStudentDto.getChoiceForSecretary())){
return null;
}
if(inStudentDto.getChoiceForVicePresident().equals(inStudentDto.getChoiceForSecretary())){
return null;
}
Optional<Person> person1 = personRepository.findById(inStudentDto.getChoiceForPresident());
Optional<Person> person2 = personRepository.findById(inStudentDto.getChoiceForVicePresident());
Optional<Person> person3 = personRepository.findById(inStudentDto.getChoiceForSecretary());
if (person1.isPresent() && person2.isPresent() && person3.isPresent()) {
Student outStudent = new Student();
BeanUtils.copyProperties(inStudentDto, outStudent);
outStudent = studentRepository.save(outStudent);
BeanUtils.copyProperties(outStudent, inStudentDto);
return inStudentDto;
} else {
return null;
}
}
@Override
public PersonDto savePerson(PersonDto inPersonDto) {
Optional<Post> post = postRepository.findById(inPersonDto.getPost());
if(post.isPresent()){
Person outPerson = new Person();
BeanUtils.copyProperties(inPersonDto, outPerson);
outPerson = personRepository.save(outPerson);
BeanUtils.copyProperties(outPerson, inPersonDto);
return inPersonDto;
}else{
return null;
}
}
@Override
public String findElectedPresident() {
List<Student> studentList = studentRepository.findAll();
List<StudentDto> allDtoStudent = new ArrayList<>();
for (com.example.entity.Student student : studentList) {
StudentDto newDtoUser = new StudentDto();
BeanUtils.copyProperties(student, newDtoUser);
allDtoStudent.add(newDtoUser);
}
ListIterator<StudentDto> iterator = allDtoStudent.listIterator();
List<String> allPresidents = new ArrayList<String>();
while (iterator.hasNext()) {
allPresidents.add(iterator.next().getChoiceForPresident());
}
Map<String, Long> frequency = allPresidents.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Map<Long, String> reverseKeysAndValues = new HashMap<Long, String>();
Long max = 0L;
for (Map.Entry<String, Long> map : frequency.entrySet()) {
Long value = map.getValue();
String key = map.getKey();
reverseKeysAndValues.put(value, key);
if (max < value) {
max = value;
}
}
return reverseKeysAndValues.get(max);
}
@Override
public String findElectedVicePresident() {
List<Student> studentList = studentRepository.findAll();
List<StudentDto> allDtoStudent = new ArrayList<>();
for (com.example.entity.Student student : studentList) {
StudentDto newDtoUser = new StudentDto();
BeanUtils.copyProperties(student, newDtoUser);
allDtoStudent.add(newDtoUser);
}
ListIterator<StudentDto> iterator = allDtoStudent.listIterator();
List<String> allVicePresidents = new ArrayList<String>();
while (iterator.hasNext()) {
allVicePresidents.add(iterator.next().getChoiceForVicePresident());
}
Map<String, Long> frequency = allVicePresidents.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Map<Long, String> reverseKeysAndValues = new HashMap<Long, String>();
Long max = 0L;
for (Map.Entry<String, Long> map : frequency.entrySet()) {
Long value = map.getValue();
String key = map.getKey();
reverseKeysAndValues.put(value, key);
if (max < value) {
max = value;
}
}
return reverseKeysAndValues.get(max);
}
@Override
public String findElectedSecretary() {
List<Student> studentList = studentRepository.findAll();
List<StudentDto> allDtoStudent = new ArrayList<>();
for (com.example.entity.Student student : studentList) {
StudentDto newDtoUser = new StudentDto();
BeanUtils.copyProperties(student, newDtoUser);
allDtoStudent.add(newDtoUser);
}
ListIterator<StudentDto> iterator = allDtoStudent.listIterator();
List<String> allSecretary = new ArrayList<String>();
while (iterator.hasNext()) {
allSecretary.add(iterator.next().getChoiceForSecretary());
}
Map<String, Long> frequency = allSecretary.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Map<Long, String> reverseKeysAndValues = new HashMap<Long, String>();
Long max = 0L;
for (Map.Entry<String, Long> map : frequency.entrySet()) {
Long value = map.getValue();
String key = map.getKey();
reverseKeysAndValues.put(value, key);
if (max < value) {
max = value;
}
}
return reverseKeysAndValues.get(max);
}
@Override
public PostDto savePosts(PostDto inPostDto) {
Post outPost = new Post();
BeanUtils.copyProperties(inPostDto, outPost);
outPost = postRepository.save(outPost);
BeanUtils.copyProperties(outPost, inPostDto);
return inPostDto;
}
}
<file_sep>/src/main/java/com/example/entity/Student.java
package com.example.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Student {
@Id
String name;
String choiceForPresident;
String choiceForVicePresident;
String choiceForSecretary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getChoiceForPresident() {
return choiceForPresident;
}
public void setChoiceForPresident(String choiceForPresident) {
this.choiceForPresident = choiceForPresident;
}
public String getChoiceForVicePresident() {
return choiceForVicePresident;
}
public void setChoiceForVicePresident(String choiceForVicePresident) {
this.choiceForVicePresident = choiceForVicePresident;
}
public String getChoiceForSecretary() {
return choiceForSecretary;
}
public void setChoiceForSecretary(String choiceForSecretary) {
this.choiceForSecretary = choiceForSecretary;
}
}
<file_sep>/README.md
# SpringBootRestUniversityElectionSystem
## 1. Requirements
* One Student can choose listed members only or in another words, if they exist in Person table. Other wise Exception must be thrown.
* One person can only choose one post for the Election {it can easily be resolved by making Person.name as primary key}.
* Person should not be able to enter post not existed in post table
* Student can not choose, same member from Person table for mulitple posts. Other wise Exception must be thrown.
## 2. Steps to achieve these requirements
* Make Student.name and Person.name primary key of respective tables. So no two entries can have same names. Other wise throw an Exception.
* Check if Student enters different members for multiple positions before storing into the database. Other wise throw an Exception.
* Before storing any student into Student table, there should be a conditional check if the name selected for posts exist in Person table or not. Other wise throw an Exception.
* Before storing any person into Person table, there should be a conditional check if the chosen post exists in Post table or not. Other wise throw an Exception.
* addPost must be executed before addPerson, and addPerson must be executed before addStudent
## 3. Technologies
* Spring Boot 2.0.3.RELEASE (Latest)
* Rest Architecture
* JPA {ORM}
* H2-Database
* Maven 3.1
* JSTL 1.2
## 4. To Run this project locally
* $ git clone https://github.com/AkashChauhanSoftEngi/SpringBootRestUniversityElectionSystem
* $ tomcat {Embedded}
## 5. Access/End Points
* POST http://localhost:8080/addPost
* POST http://localhost:8080/addPerson
* POST http://localhost:8080/addStudent
* GET http://localhost:8080/findElectedPresident
* GET http://localhost:8080/findElectedVicePresedent
* GET http://localhost:8080/findElectedSecretary
## 6. Overview of thr system {High Level Design, HLD}
```text
* 6 Rest End/Access Points: addPost, addPerson, addStudent, findElectedPresident, findElectedVicePresedent, findElectedSecretary
* POST: {"post":"President"}->addPost->{"post":"President"}
* POST: {"name":"satya", "post":"vice-president"}->addPerson->{"name":"satya", "post":"vice-president"}
* POST: {"name":"Akash", "choiceForPresident":"satya", "choiceForVicePresident":"nitin", "choiceForSecretary":"neeraj"}->addStudent->{"name":"Akash", "choiceForPresident":"satya", "choiceForVicePresident":"nitin", "choiceForSecretary":"neeraj"}
* GET: findElectedPresident->"satya"
* GET: findElectedVicePresedent->"nitin"
* GET: findElectedSecretary->"neeraj"
* addPost API must be executed before addPerson API, and addPerson API must be executed before addStudent API
- addPost > addPerson > addStudent
- In addPerson person must enter post already existed in Post table, and in addStudent Student must enter person already existed in Person table
```
## 7. Internal Work flow of API or End points {Low Level Design, LLD}
* Example: /addStudnet
```text
Student {name, choiceForPresident, choiceForVicePresident, choiceForSecretary}
||
\/
Rest Controller {Post: /addStudent}
||
\/
ElectionSystemService {Interface, saveStudent() method}
||
\/
ElectionSystemServiceImpl {Implementation, saveStudent() method, Use Dto classes}
||
\/
StudentRepository {save(Student), JpaRepository<Student, String>}
||
\/
DAO {student table, return back after saving the data in the student table}
```
## 8. Database Schema Design
* Related files added above with names: "SchemaDesignPhoto.PNG" and "SchemaDesign.docx"
<file_sep>/src/main/java/com/example/dto/PersonDto.java
package com.example.dto;
public class PersonDto {
String name;
String post;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPost() {
return post;
}
public void setPost(String post) {
this.post = post;
}
}
<file_sep>/src/main/java/com/example/service/ElectionSystemService.java
package com.example.service;
import com.example.dto.PersonDto;
import com.example.dto.PostDto;
import com.example.dto.StudentDto;
public interface ElectionSystemService {
StudentDto saveStudent(StudentDto student);
PersonDto savePerson(PersonDto person);
String findElectedPresident();
String findElectedVicePresident();
String findElectedSecretary();
PostDto savePosts(PostDto post);
}
<file_sep>/src/main/java/com/example/dto/StudentDto.java
package com.example.dto;
public class StudentDto {
String name;
String choiceForPresident;
String choiceForVicePresident;
String choiceForSecretary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getChoiceForPresident() {
return choiceForPresident;
}
public void setChoiceForPresident(String choiceForPresident) {
this.choiceForPresident = choiceForPresident;
}
public String getChoiceForVicePresident() {
return choiceForVicePresident;
}
public void setChoiceForVicePresident(String choiceForVicePresident) {
this.choiceForVicePresident = choiceForVicePresident;
}
public String getChoiceForSecretary() {
return choiceForSecretary;
}
public void setChoiceForSecretary(String choiceForSecretary) {
this.choiceForSecretary = choiceForSecretary;
}
}
|
aa736c3f1b4b06d8dd1bfc10ee35a6b6bfc15ace
|
[
"Markdown",
"Java"
] | 7 |
Java
|
AkashChauhanSoftEngi/SpringBootRestUniversityElectionSystem
|
85ab2faa0adc91438db15978edbd429eea0c78fe
|
019c6a61fb889482e3b330f0962f1f5a42d323de
|
refs/heads/master
|
<repo_name>rubcarmo/MyIonicProject<file_sep>/src/pages/aplicar-inspecao/aplicar-inspecao.module.ts
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { AplicarInspecaoPage } from './aplicar-inspecao';
@NgModule({
declarations: [
AplicarInspecaoPage,
],
imports: [
IonicPageModule.forChild(AplicarInspecaoPage),
],
})
export class AplicarInspecaoPageModule {}
|
224b39100cebd0bc168c7e67d1fd7f5b26b0d59c
|
[
"TypeScript"
] | 1 |
TypeScript
|
rubcarmo/MyIonicProject
|
cd79e0b0d4e7908e5113845a0874ab2611c489ba
|
35f54841357016c9a4142cb6e64ee1c2e912b3c3
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using GummiBearKingdom.Models;
using Microsoft.EntityFrameworkCore;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace GummiBearKingdom.Controllers
{
public class AdminController : Controller
{
// GET: /<controller>/
private GummiBearKingdomContext db = new GummiBearKingdomContext();
public IActionResult Index()
{
return View(db.Products.ToList());
}
public ActionResult AddProduct()
{
return View();
}
[HttpPost]
public ActionResult AddProduct(Product product)
{
db.Products.Add(product);
db.SaveChanges();
return RedirectToAction("Index");
}
public IActionResult EditProduct(int id)
{
var thisItem = db.Products.FirstOrDefault(products => products.ProductsId == id);
return View(thisItem);
}
[HttpPost]
public IActionResult EditProduct(Product product)
{
db.Entry(product).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
public IActionResult DeleteProduct(int id)
{
var Product = db.Products.FirstOrDefault(product => product.ProductsId == id);
return View(Product);
}
[HttpPost, ActionName("DeleteProduct")]
public IActionResult DeleteConfirmed(int id)
{
var Product = db.Products.FirstOrDefault(product => product.ProductsId == id);
db.Products.Remove(Product);
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using GummiBearKingdom.Models;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace GummiBearKingdom.Controllers
{
public class BlogController : Controller
{
private GummiBearKingdomContext db = new GummiBearKingdomContext();
private BlogModel theView = new BlogModel();
public IActionResult Index()
{
return View(db.Blog.ToList());
}
[HttpPost]
public ActionResult Index(Blog blog)
{
db.Blog.Add(blog);
db.SaveChanges();
return RedirectToAction("Index");
}
public class BlogModel
{
public IEnumerable<Blog> BlogList { get; set; }
public Blog Blog { get; set; }
private GummiBearKingdomContext db = new GummiBearKingdomContext();
public BlogModel()
{
BlogList = db.Blog.ToList();
}
}
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GummiBearKingdom.Models
{
public class GummiBearKingdomContext : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Blog> Blog { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=GummiBear;integrated security=True");
}
}
}
<file_sep># GummiBearKingdom
independent project
.Net Core using Entity framwork and migration
## Specs
* User can add product to the product list
* User can choose the Category type of product when add to the list
* User can edit the product detail
* User can delete the product
* User can add Blog page to the blog section with their name, title, picture and blog detail.
* Blog arrange by the newest first
## Setup/Installation
1. Files can be cloned from # GummiBearKingdom
independent project
.Net Core using Entity framwork and migration
## Specs
* User can add product to the product list
* User can choose the Category type of product when add to the list
* User can edit the product detail
* User can delete the product
* User can add Blog page to the blog section with their name, title, picture and blog detail.
* Blog arrange by the newest first
## Setup/Installation
1. Files can be cloned from https://github.com/Rouz1130/GummiBearKingdom
2. Open Visual Studio 2015 : File>Open>Project/Solution
3. Click Build GummiBearKingdom
4. Click IIS Express on the Menu Bar to go to the site
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using GummiBearKingdom.Models;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace GummiBearKingdom.Controllers
{
public class ProductsController : Controller
{
private GummiBearKingdomContext db = new GummiBearKingdomContext();
public Product Product { get; private set; }
public IActionResult Index()
{
return View(db.Products.ToList());
}
public IActionResult Details(int id)
{
var thisProduct = db.Products.FirstOrDefault(ProductsController => ProductsController.ProductsId == id);
return View(thisProduct);
}
}
}
|
d317b87457e24a16593da76ebb8a3055738562f6
|
[
"Markdown",
"C#"
] | 5 |
C#
|
Rouz1130/GummiBearKingdom
|
a41148008a18a3c9128cdc087f8d2d62555d51e7
|
102b42bf2a7a3bccea4115d02d183a95b70d88b3
|
refs/heads/main
|
<file_sep><form action="input-diri.php" method="POST">
<label for= "nis">Nomor Induk siswa
<input type="number" name="nis" placeholder="Ex.12001142"/><br>
<label for="nama">Nama Lengkap :</label>
<input type="text" name="nama" placeholder="Ex. Firdaus "/><br>
<label for="tanggal_lahir">Tanggal Lahir :</label>
<input type="date" name="tanggal_lahir" /><br>
<label for="nilai">Nilai :</label>
<input type="number" name="nilai" placeholder="Ex. 80.56" /><br>
<input type="submit" name="simpan" value="Simpan data" />
</form>
<?php
include('./input-config.php');
echo "<hr>";
//Menampilkan data dari database
$no = 1;
$tabledata = "";
$data = mysqli_query($mysqli,"SELECT * FROM datadiri ");
while($row = mysqli_fetch_array($data)){
$tabledata .="
<tr>
<td>".$row["nis"] ."</td>
<td>".$row["namalengkap"] ."</td>
<td>".$row["namalengkap"] ."</td>
<td>".$row["nilai"] ."</td>
</tr>
";
$no++;
}
echo "
<table cellpading=5 border=1 cellspacing=0>
<tr>
<th>NIS</th>
<th>Nama Lengkap</th>
<th>Tanggal Lahir</th>
<th>Nilai</th>
<tr>
$tabledata
</table>
";
?>
<file_sep><?php
define("BASE_URL", "http://localhost/phpnative/");
<file_sep><form action="Jajargenjang.php" method="POST">
<h1>Rumus Menghitung Luas Jajar genjang </h1>
<p>Alas : </p>
<input type= "number" name="alas" placeholder="Ex. 5" />
<p>Tinggi : </p>
<input type= "number" name="tinggi" placeholder="Ex. 5" />
<input type="submit" name="proses" value="Hitung Luas"/>
</form>
<?php
if (isset($_POST["proses"]) ){
echo "<hr>";
$alas = $_POST['alas'];
$tinggi = $_POST['tinggi'];
// menghitung Luas Jajar Genjang
$luas = $alas * $tinggi;
echo "Diketahui;<br />";
echo "Alas : $alas <br>";
echo "Tinggi : $tinggi <br>";
echo "Maka Luas Jajar Genjang adalah : $luas <br>";
}<file_sep><!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<title>Data Nilai</title>
</head>
<body>
<h1>Data Nilai Mahasiswa</h1>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html>
<?php
include('./mhsiswa-config.php');
echo "<a href='mhsiswa-tambah.php'>Tambah Data</a>";
echo "<hr>";
// Menampilkan data nilai database
$no = 1;
$tabledata = "";
$data = mysqli_query($mysqli," SELECT * FROM mahasiswa ");
while($row = mysqli_fetch_array($data)){
$nilai_akhir=($row["kehadiran"]*0.1+$row["tugas"]*0.4+$row["uts"]*0.25+$row["uas"]*0.25);
$tabledata .= "
<tr>
<td>".$row["npm"]."</td>
<td>".$row["namamahasiswa"]."</td>
<td>".$row["prodi"]."</td>
<td>".$row["kehadiran"]."</td>
<td>".$row["tugas"]."</td>
<td>".$row["uts"]."</td>
<td>".$row["uas"]."</td>
<td>".$nilai_akhir."</td>
<td>
<a href='mhsiswa-edit.php?npm=".$row["npm"]."'>Edit</a>
-
<a href='mhsiswa-hapus.php?npm=".$row["npm"]."'
onclick='return confirm(\"Hapus?\");'>Hapus</a>
</td>
</tr>
";
$no++;
}
echo "
<table cellpadding=5 border=1 cellspacing=0>
<tr>
<th>NPM</th>
<th>Nama Mahasiswa</th>
<th>Prodi</th>
<th>Kehadiran</th>
<th>tugas</th>
<th>UTS</th>
<th>UAS</th>
<th>Nilai Akhir</th>
<th>Aksi</th>
</tr>
$tabledata
</table>
";
?><file_sep><?php
require_once('function/helper.php');
require_once('function/koneksi.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="<?= BASE_URL . 'assets/css/style01.css' ?>">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,500;0,700;0,900;1,400;1,500;1,700&display=swap" rel="stylesheet">
</head>
<body>
<div class="topbar">
<h3 class="text-topbar"></h3>
</div>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320">
<path fill="#0099ff" fill-opacity="1" d="M0,192L60,192C120,192,240,192,360,208C480,224,600,256,720,261.3C840,267,960,245,1080,218.7C1200,192,1320,160,1380,144L1440,128L1440,0L1380,0C1320,0,1200,0,1080,0C960,0,840,0,720,0C600,0,480,0,360,0C240,0,120,0,60,0L0,0Z"></path>
</svg>
<div class="content">
<div class="card-login">
<div class="card-main">
<div class="card-header">Form Login</div>
<div class="card-body">
<form class="form-login" method="POST" action="<?= BASE_URL . 'process/process_login.php' ?>">
<label class="form-label">Username</label>
<input type="username" name="username" class="form-input">
<label class="form-label">Password</label>
<input type="<PASSWORD>" name="password" class="form-input">
<button type="submit" class="btn btn-login">Login</button>
</form>
</div>
</div>
</div>
</div>
</body>
</html><file_sep><form action="Balok.php" method="POST">
<h1>Rumus Menghitung Volume Balok </h1>
<p>Panjang : </p>
<input type= "number" name="panjang" placeholder="Ex. 5" /> <br>
<p>Lebar : </p>
<input type= "number" name="lebar" placeholder="Ex. 5" /> <br>
<p>Tinggi : </p>
<input type= "number" name="tinggi" placeholder="Ex. 5" />
<input type="submit" name="proses" value="Hitung Luas"/>
</form>
<?php
if(isset($_POST['proses'])){
$panjang =$_POST["panjang"];
$lebar =$_POST["lebar"];
$tinggi =$_POST["tinggi"];
// menghitung volume balok
$volume_balok =$panjang*$lebar*$tinggi;
echo "Hasil hitung volume balok adalah sebagai berikut:<br />";
echo "Diketahui;<br />";
echo "Panjang = $panjang<br />";
echo "Lebar = $lebar<br />";
echo "Tinggi = $tinggi<br />";
echo "Maka volume balok sama dengan [ $panjang x $lebar x $tinggi ] = $volume_balok";
}
<file_sep><?php
require_once('function/helper.php');
session_start();
$page = isset($_GET['page']) ? ($_GET['page']) : false;
if ($_SESSION['id'] == null) {
header("location: " . BASE_URL);
exit();
}
?>
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous">
<!--Bootstrap Icons-->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">
<!-- My CSS-->
<link rel="stylesheet" href="style.css"/>
<title>Epi halimah</title>
</head>
<body id="Home">
<!--Navbar-->
<nav class="navbar navbar-expand-lg navbar-dark bg-primary shadow-sm fixed-top">
<div class="container">
<a class="navbar-brand" href="#">Epi</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ms-auto">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#Home">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#Profile">Profile</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#About">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#contact me">Contact</a>
</li>
</ul>
</div>
</div>
</nav>
<!--Akhir Navbar-->
</html><file_sep><?php
if ( isset($_GET["nis"]) ){
$nis = $_GET["nis"];
$check_nis = "SELECT * FROM datadiri WHERE nis = '$nis'; ";
include('./input-config.php');
$query = mysqli_query($mysqli, $check_nis);
$row = mysqli_fetch_array($query);
}
?>
<h1>Edit Data</h1>
<form action="input-datadiri-edit.php" method="POST">
<label for="nis">Nomor Induk Siswa :</label><br>
<input value="<?php echo $row["nis"]; ?>" type="number" name="nis" placeholder="Ex. 12003102" readonly/><br>
<label for="nama">Nama Lengkap :</label><br>
<input value="<?php echo $row["namalengkap"]; ?>" type="text" name="nama" placeholder="Ex. Firdaus" /><br>
<label for="tanggal_lahir">Tanggal Lahir :</label><br>
<input value="<?php echo $row["tanggal_lahir"]; ?>" type="date" name="tanggal_lahir" /><br>
<label for="nilai">Nilai :</label><br>
<input value="<?php echo $row["nilai"]; ?>" type="number" name="nilai" placeholder="Ex. 80.56" /><br>
<br>
<input type="submit" name="edit" value="Edit Data" />
<a href="input-datadiri.php">Kembali</a>
</form>
<?php
if ( isset($_POST["edit"]) ) {
$nis = $_POST["nis"];
$nama = $_POST["nama"];
$tanggal_lahir = $_POST["tanggal_lahir"];
$nilai = $_POST["nilai"];
// EDIT - Memperbaharui Data
$query = "
UPDATE datadiri SET namalengkap = '$nama',
tanggal_lahir = '$tanggal_lahir',
nilai = '$nilai'
WHERE nis = '$nis';
";
include ('./input-config.php');
$update = mysqli_query($mysqli, $query);
if($update){
echo "
<script>
alert('Data berhasil diperbaharui');
window.location='input-datadiri.php';
</script>
";
}else{
echo "
<script>
alert('Data gagal');
window.location='input-datadiri-edit.php?nis=$nis';
</script>
";
}
}
?><file_sep><?php
include('./input-config.php');
session_destroy();
echo"
<script>
alert ('logout Berhasil')
window.location='login.php';
</script>
";
?><file_sep><h1>Tambah Data</h1>
<form action="input-data-nilai-tambah.php" method="POST">
<label for="nis">Nomor Induk Siswa : </label>
<input type="number" name="nis" placeholder="Ex. 12003102" /> <br>
<label for="nama_lengkap">Nama Lengkap : </label>
<input type="text" name="nama_lengkap" placeholder="Ex. Firdaus" /> <br>
<label for="kelas">Kelas :</label>
<input type="text" name="kelas" placeholder="Ex. 11 RPL 1" /><br>
<label for="kehadiran">Kehadiran :</label>
<input type="number" name="kehadiran" placeholder="Ex. 80"><br>
<label for="tugas">Tugas :</label>
<input type="number" name="tugas" placeholder="Ex. 80"><br>
<label for="uts">UTS :</label>
<input type="number" name="uts" placeholder="Ex. 80"><br>
<label for="uas">UAS :</label>
<input type="number" name="uas" placeholder="Ex. 80"><br>
<input type="submit" name="simpan" value="Simpan Data" />
<a href="input-data_nilai.php">Kembali</a>
</form>
<?php
if( isset($_POST["simpan"]) ){
$nis = $_POST["nis"];
$nama_lengkap = $_POST["nama_lengkap"];
$kelas = $_POST["kelas"];
$kehadiran = $_POST["kehadiran"];
$tugas = $_POST["tugas"];
$uts = $_POST["uts"];
$uas = $_POST["uas"];
// CREATE - Menambahkan Data ke Database
$query = "
INSERT INTO siswa_nilai VALUES
('$nis', '$nama_lengkap', '$kelas', '$kehadiran', '$tugas', '$uts', '$uas');
";
include ('./input-nilai-config.php');
$insert = mysqli_query($mysqli, $query);
if ($insert){
echo "
<script>
alert('Data berhasil ditambahkan');
window.location='input-data-nilai.php';
</script>
";
}
}
?><file_sep><?php
$nama = "<NAME>";
echo $nama . "<br>";
$nama_array = array("Fariz","Eben","Haikal","<NAME>",);
print_r($nama_array); echo "<br>";
echo $nama_array[0] . "<br>";
echo $nama_array[1] . "<br>";
echo $nama_array[2] . "<br>";
echo "<hr>";
// Versi Foreach
foreach ($nama_array AS $datanama) {
echo $datanama . "<br>";
}
echo "<hr>";
//Versi for
for ($i = 0; $i < COUNT($nama_array); $i++){
echo $nama_array[$i] . "<br>";
}
//Multiple Array
$kelas11rpl1 = array(
array("<NAME>" , "L" , "Mancing"),
array("Eben" , "L" ,"Main Bola"),
array("Fariz" , "L" , array( "Berenang" , "Maen Game","Basket")),
array("volly" , array("maen kelereng", array("maen layangan")) )
);
echo "<pre>";
print_r($kelas11rpl1);
echo "</pre>";
echo "<hr>";
echo $kelas11rpl1[1][0] . " ";
echo $kelas11rpl1[2][2][0] . " ";
echo $kelas11rpl1[3][1][1][0]. " ";
echo $kelas11rpl1[0][2];
<file_sep><form action="Persegi-Panjang.php" method="POST">
<h1>Rumus Persegi Panjang </h1>
<p>Panjang : </p>
<input type= "number" name="Panjang" placeholder="Ex. 5" /><br>
<p>Lebar : </p>
<input type= "number" name="lebar" placeholder="Ex. 5" />
<input type="submit" name="proses" value="Hitung Luas"/>
</form>
<?php
if (isset($_POST["proses"]) ){
echo "<hr>";
$Panjang = $_POST['Panjang'];
$tinggi = $_POST['lebar'];
// menghitung Luas Persegi Panjang
$luas = $Panjang * $lebar;
echo "Hasil hitung Persegi Panjang adalah sebagai berikut:<br />";
echo "Diketahui;<br />";
echo "Panjang : $Panjang <br>";
echo "Tinggi : $lebar <br>";
echo "Maka Luas Persegi Panjang adalah : $luas <br>";
}<file_sep><form action="Lingkaran.php" method="POST">
<h1>Rumus Menghitung Luas lingkaran </h1>
<p>Jari Jari : </p>
<input type= "number" name="JariJari" placeholder="Ex. 5" />
<input type="submit" name="proses" value="Hitung Luas"/>
</form>
<?php
if (isset($_POST["proses"]) ){
echo "<hr>";
$JariJari = $_POST['JariJari'];
// menghitung Luas Lingkaran
$luas = 3.14 * $JariJari;
echo "Hasil hitung Luas Lingkaran adalah sebagai berikut:<br />";
echo "Diketahui;<br />";
echo "Jari Jari : $JariJari <br>";
echo "Maka Luas Lingkaran adalah : $luas <br>";
}<file_sep><?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "akademik";
$koneksi = mysqli_connect($host, $user, $pass, $db);
if (!$koneksi) { //cek koneksi
die("Tidak bisa terkoneksi ke database");
}
$nim = "";
$nama = "";
$alamat = "";
$fakultas = "";
$sukses = "";
$error = "";
if (isset($_GET['op'])) {
$op = $_GET['op'];
} else {
$op = "";
}
if($op == 'delete'){
$id = $_GET['id'];
$sql1 = "delete from mahasiswa where id = '$id'";
$q1 = mysqli_query($koneksi,$sql1);
if($q1){
$sukses = "Berhasil hapus data";
}else{
$error = "Gagal melakukan delete data";
}
}
if ($op == 'edit') {
$id = $_GET['id'];
$sql1 = "select * from mahasiswa where id = '$id'";
$q1 = mysqli_query($koneksi, $sql1);
$r1 = mysqli_fetch_array($q1);
$nim = $r1['nim'];
$nama = $r1['nama'];
$alamat = $r1['alamat'];
$fakultas = $r1['fakultas'];
if ($nim == '') {
$error = "Data tidak ditemukan";
}
}
if (isset($_POST['simpan'])) { //untuk create
$nim = $_POST['nim'];
$nama = $_POST['nama'];
$alamat = $_POST['alamat'];
$fakultas = $_POST['fakultas'];
if ($nim && $nama && $alamat && $fakultas) {
if ($op == 'edit') { //untuk update
$sql1 = "update mahasiswa set nim = '$nim',nama='$nama',alamat = '$alamat',fakultas='$fakultas' where id = '$id'";
$q1 = mysqli_query($koneksi, $sql1);
if ($q1) {
$sukses = "Data berhasil diupdate";
} else {
$error = "Data gagal diupdate";
}
} else { //untuk insert
$sql1 = "insert into mahasiswa(nim,nama,alamat,fakultas) values ('$nim','$nama','$alamat','$fakultas')";
$q1 = mysqli_query($koneksi, $sql1);
if ($q1) {
$sukses = "Berhasil memasukkan data baru";
} else {
$error = "Gagal memasukkan data";
}
}
} else {
$error = "Silakan masukkan semua data";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Data Mahasiswa</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous">
<style>
.mx-auto {
width: 800px
}
.card {
margin-top: 10px;
}
</style>
</head>
<body>
<div class="mx-auto">
<!-- untuk memasukkan data -->
<div class="card">
<div class="card-header">
Create / Edit Data
</div>
<div class="card-body">
<?php
if ($error) {
?>
<div class="alert alert-danger" role="alert">
<?php echo $error ?>
</div>
<?php
header("refresh:5;url=index.php");//5 : detik
}
?>
<?php
if ($sukses) {
?>
<div class="alert alert-success" role="alert">
<?php echo $sukses ?>
</div>
<?php
header("refresh:5;url=index.php");
}
?>
<form action="" method="POST">
<div class="mb-3 row">
<label for="nim" class="col-sm-2 col-form-label">NIM</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="nim" name="nim" value="<?php echo $nim ?>">
</div>
</div>
<div class="mb-3 row">
<label for="nama" class="col-sm-2 col-form-label">Nama</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="nama" name="nama" value="<?php echo $nama ?>">
</div>
</div>
<div class="mb-3 row">
<label for="alamat" class="col-sm-2 col-form-label">Alamat</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="alamat" name="alamat" value="<?php echo $alamat ?>">
</div>
</div>
<div class="mb-3 row">
<label for="fakultas" class="col-sm-2 col-form-label">Fakultas</label>
<div class="col-sm-10">
<select class="form-control" name="fakultas" id="fakultas">
<option value="">- Pilih Fakultas -</option>
<option value="saintek" <?php if ($fakultas == "saintek") echo "selected" ?>>saintek</option>
<option value="soshum" <?php if ($fakultas == "soshum") echo "selected" ?>>soshum</option>
</select>
</div>
</div>
<div class="col-12">
<input type="submit" name="simpan" value="Simpan Data" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<!-- untuk mengeluarkan data -->
<div class="card">
<div class="card-header text-white bg-secondary">
Data Mahasiswa
</div>
<div class="card-body">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">NIM</th>
<th scope="col">Nama</th>
<th scope="col">Alamat</th>
<th scope="col">Fakultas</th>
<th scope="col">Aksi</th>
</tr>
</thead>
<tbody>
<?php
$sql2 = "select * from mahasiswa order by id desc";
$q2 = mysqli_query($koneksi, $sql2);
$urut = 1;
while ($r2 = mysqli_fetch_array($q2)) {
$id = $r2['id'];
$nim = $r2['nim'];
$nama = $r2['nama'];
$alamat = $r2['alamat'];
$fakultas = $r2['fakultas'];
?>
<tr>
<th scope="row"><?php echo $urut++ ?></th>
<td scope="row"><?php echo $nim ?></td>
<td scope="row"><?php echo $nama ?></td>
<td scope="row"><?php echo $alamat ?></td>
<td scope="row"><?php echo $fakultas ?></td>
<td scope="row">
<a href="index.php?op=edit&id=<?php echo $id ?>"><button type="button" class="btn btn-warning">Edit</button></a>
<a href="index.php?op=delete&id=<?php echo $id?>" onclick="return confirm('Yakin mau delete data?')">
<button type="button" class="btn btn-danger">Delete</button></a>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html><file_sep><form action="Tabung.php" method="POST">
<h1> Rumus Luas dan Volume Tabung </h1>
<p> Jari Jari : </p>
<input type="number" name="jari" placeholder="Ex. 5" /><br>
<p> Tinggi : </p>
<input type="number" name="tinggi" placeholder="Ex. 5" />
<input type="submit" name="proses" value="Hitung Luas dan Volume" />
</form>
<?php
if ( isset($_POST["proses"]) ) {
echo "<hr>";
$jari = $_POST["jari"];
$tinggi = $_POST["tinggi"];
// menghitung volume dan Luas balok
$Pi = 22/7;
$luas = 2 * $Pi * $jari * ($jari + $tinggi);
$volume = $Pi * $jari * $jari * $tinggi;
echo "Jari-Jari : $jari <br>";
echo "Tinggi : $tinggi <br>";
echo "Luas Tabung : $luas <br>";
echo "Volume Tabung : $volume <br>";
echo "<hr>";
}
?><file_sep><?php
include ('./input-config.php');
if( $_SESSION["login"] !=TRUE) {
header('location:login.php');
}
if( $_SESSION["role"] !="admin") {
echo "
<script>
alert('Akses tidak diberikan, kamu bukan admin');
window.location='input-datadiri.php';
</script>
";
}
if ( isset($_GET["nis"]) && $_SESSION["role"] =="admin" ){
$nis = $_GET["nis"];
$query = "
DELETE FROM datadiri
WHERE nis = '$nis';
";
$delete = mysqli_query($mysqli, $query);
if($delete){
echo "
<script>
alert('Data berhasil dihapus');
window.location='input-datadiri.php';
</script>
";
}else{
echo "
<script>
alert('Data gagal');
window.location='input-datadiri.php';
</script>
";
}
}
?><file_sep><?php
//materi percabagan(IF ELSE)
$nilai = 78;
echo "nilai kamu adalah $nilai <br>";
echo "maka setatus kamu =";
if ($nilai >= 78 ){
echo "lulus beneran";
}else if ($nilai == 78) {
echo "lulus KKM ";
}else {
echo "tidak lulus";
}
echo "<hr>";
$nilai_web = 79;
$nilai_pbo = 82;
echo "nilai web kamu = $nilai_web <br>";
echo "nilai pbo kamu = $nilai_pbo <br>";
echo "kelulusan kamu =";
if ($nilai_web >= 80 AND $nilai_pbo >= 80 ){
echo "lulus 2 mapel produktif";
}else if ($nilai_web >= 80 OR $nilai_pbo >= 80 ){
if ($nilai_web >= 80){
echo "lulus mapel web";
}
if ($nilai_pbo >= 80){
echo "lulus mapel pbo";
}
}else {
echo "tidak lulus mapel produktif";
}
echo "<hr>";
//materi perulagan (while, do while ,for)
$i = 1;
while ( $i <= 5){
echo "hello word ! ke - $i <br>";
$i++; //assigment +1
}
echo "<hr>";
$j = 1;
do{
echo $j. "<br>";
$j++;
}while ($j <= 5);
echo "<hr>";
$k = 1;
for ($k = 1; $k <= 10; $k++){
echo $k."<br>";
}
echo "<hr>";
for ($x = 9; $x >= 1; $x--){
for ($y = 1; $y <= $x; $y++)
echo "*";{
echo "<br>";
}
}
echo "<hr>";
for ($x = 9; $x >= 1; $x--){
for ($y = 1; $y <= $x; $y++)
echo "$y";{
echo "<br>";
}
}
echo "<hr>";
for ($z = 1; $z <= 10; $z++) {
if ($z %2 ==0){
echo $z . "- genap <br>";
}else {
echo $z . "-ganjil <br> ";
}
}
?><file_sep><?php
require_once('../function/helper.php');
require_once('../function/koneksi.php');
// Menangkap request
$username = $_POST['username'];
$password = md5($_POST['password']);
$query = mysqli_query($koneksi, "SELECT * FROM admin WHERE username = '$username' AND password = '$password'");
// Mengecek pengguna
if (mysqli_num_rows($query) != 0) {
$row = mysqli_fetch_assoc($query);
// var_dump($row);
// die();
// Membuat session
session_start();
$_SESSION['id'] = $row['id'];
header("location: " . BASE_URL . 'dashboard.php?page=home');
} else {
header("location: " . BASE_URL);
}
<file_sep><form action="Bola.php" method="POST">
<h1> Rumus Luas dan Volume Bola </h1>
<p>Jari - Jari :</p>
<input type="number" name="r" placeholder="Ex. 5" />
<input type="submit" name="proses" value="Hitung Luas dan Volume" />
</form>
<?php
if ( isset($_POST["proses"]) ) {
echo "<hr>";
$jari = $_POST["r"];
$pi = 22/7;
$x = 4/3;
$LP = 4 * $pi * $jari * $jari;
$volume = $x * $pi * $jari * $jari * $jari;
echo "Jari - jari : $jari <br>";
echo "Luas Permukaan Bola : $LP <br>";
echo "Volume Bola : $volume <br>";
}
?><file_sep><h1>Tambah Data</h1>
<form action="mhsiswa-tambah.php" method="POST">
<label for="npm">Nomor Pokok Mahasiswa : </label>
<input type="number" name="npm" placeholder="Ex. 12003102" /> <br>
<label for="namamahasiswa">Nama Mahasiswa : </label>
<input type="text" name="namamahasiswa" placeholder="Ex. Alyael" /> <br>
<label for="prodi">Prodi :</label>
<input type="text" name="prodi" placeholder="Informatika" /><br>
<label for="kehadiran">Kehadiran :</label>
<input type="number" name="kehadiran" placeholder="Ex. 80"><br>
<label for="tugas">Tugas :</label>
<input type="number" name="tugas" placeholder="Ex. 80"><br>
<label for="uts">UTS :</label>
<input type="number" name="uts" placeholder="Ex. 80"><br>
<label for="uas">UAS :</label>
<input type="number" name="uas" placeholder="Ex. 80"><br>
<input type="submit" name="simpan" value="Simpan Data" />
<a href="mhsiswa.php">Kembali</a>
</form>
<?php
if( isset($_POST["simpan"]) ){
$npm = $_POST["npm"];
$namamahasiswa = $_POST["namamahasiswa"];
$prodi = $_POST["prodi"];
$kehadiran = $_POST["kehadiran"];
$tugas = $_POST["tugas"];
$uts = $_POST["uts"];
$uas = $_POST["uas"];
echo $npm . "<br>";
echo $namamahasiswa . "<br>";
echo $prodi . "<br>";
echo $kehadiran . "<br>";
echo $tugas . "<br>";
echo $uts . "<br>";
echo $uas . "<br>";
// CREATE - Menambahkan Data ke Database
$query = "
INSERT INTO mahasiswa VALUES
('$npm', '$namamahasiswa', '$prodi', '$kehadiran', '$tugas', '$uts', '$uas');
";
include ('./mhsiswa-config.php');
$insert = mysqli_query($mysqli, $query);
if ($insert){
echo "
<script>
alert('Data berhasil ditambahkan');
window.location='mhsiswa.php';
</script>
";
}
}
?><file_sep><?php
if ( isset($_GET["nis"]) ){
$nis = $_GET["nis"];
$check_nis = "SELECT * FROM datadiri WHERE nis = '$nis';";
include('./input-config.php');
$querry = mysqli_query($mysqli, $check_nis);
$row = mysqli_fetch_array($querry);
}
?>
<h1>Edit Data</h1>
<form action="input-datadiri-edit.php" method="POST">
<label for="nis"> Nomor Induk siswa :</label>
<input value="<?php echo $row["nis"]; ?>" readonly type="number" name="nis" placeholder="Ex. 12001142" /><br>
<label for="nama"> Nama Lengkap :</label>
<input value="<?php echo $row["namalengkap"]; ?>" type="text" name="nama" placeholder="Ex. <NAME>" /><br>
<label for="tanggal_lahir"> Tanggal Lahir :</label>
<input value="<?php echo $row["tanggal_lahir"]; ?>" type="date" name="tanggal_lahir" /><br>
<label for="nilai"> Nilai :</label>
<input value="<?php echo $row["nilai"]; ?>" type="number" name="nilai" placeholder="Ex. 80.56" /><br>
<input type="submit" name="simpan" value="Simpan Data" />
<a href="input-datadiri.php">kembali</a>
</form>
<?php
if ( isset($_POST["simpan"])) {
$nis = $_POST["nis"];
$nama = $_POST["nama"];
$tanggal_lahir = $_POST["tanggal_lahir"];
$nilai = $_POST["nilai"];
//Edit - Memperbarui Data
$query ="
UPDATE datadiri SET namalengkap = '$nama',
tanggal_lahir = '$tanggal_lahir',
nilai = '$nilai'
WHERE nis = '$nis';
";
include ('./input-config.php');
$update = mysqli_query($mysqli, $query);
if($update){
echo "
<script>
alert('Data Berhasil Diperbaharui');
window.location='input-datadiri.php';
</script>
";
}else{
echo "
<script>
alert('Data Gagal diperbaharui');
window.location='input-datadiri-edit.php?nis=$nis';
</script>
";
}
}
?><file_sep><form action="Trapesium.php" method="POST">
<h1>Rumus Menghitung Luas Trapesium </h1>
<p>Atas : </p>
<input type= "number" name="atas" placeholder="Ex. 5" /><br>
<p>Bawah : </p>
<input type= "number" name="bawah" placeholder="Ex. 5" />
<p>Tinggi : </p>
<input type= "number" name="tinggi" placeholder="Ex. 5" />
<input type="submit" name="proses" value="Hitung Luas"/>
</form>
<?php
if (isset($_POST["proses"]) ){
echo "<hr>";
$atas = $_POST['atas'];
$bawah = $_POST['bawah'];
$tinggi = $_POST['tinggi'];
// menghitung Luas Trapesium
$luas = (($atas + $bawah)*$tinggi)/2;
echo "Hasil hitung Luas Trapesium adalah sebagai berikut:<br />";
echo "Diketahui<br>";
echo "Sisi Atas= $atas cm<br>";
echo "Sisi Bawah= $bawah cm<br>";
echo "Tinggi = $tinggi cm<br>";
echo "<br>";
echo "Maka: <br>";
echo "Luas Trapesium = ".$luas.";
}<file_sep><?php
include ('./input-nilai-config.php');
$data=mysqli_query($mysqli,"DELETE FROM siswa_nilai WHERE nis='".$_GET["nis"]."'");
header("location:input-data-nilai.php");
?><file_sep><form action="rumus-persegi.php" method="POST">
<h1>Rumus Luas dan Keliling Persegi </h1>
<p>Sisi : </p>
<input type= "number" name="sisi" placeholder="Ex. 5" />
<input type="submit" name="proses" value="Hitung Luas & Keliling"/>
</form>
<?php
if (isset($_POST["proses"]) ){
echo "<hr>";
$sisi = $_POST["sisi"];
$luas = $sisi * $sisi;
$keliling = 4 * $sisi;
echo "sisi : $sisi <br>";
echo "Luas Persegi : $luas <br>";
echo "Keliling Persegi : $keliling <br>";
}<file_sep><?php
include ('./input-config.php');
$data=mysqli_query($mysqli,"DELETE FROM datadiri WHERE nis='".$_GET["nis"]."'");
header("location:input-datadiri.php")
?>
<file_sep><form action="post.php" method="POST">
<input type="text" name="namalengkap" placeholder= "Ex.Indra EL" />
<input type="text" name="kelas" placeholder= "Ex. 11 RPL1" />
<input type="text" name="NIS" placeholder= "Ex. 7859644" />
<input type="submit" name="simpan" value="Simpan Data" />
</form>
<?php
if( isset($_POST["simpan"]) ){
echo "<hr>";
$namalengkap = $_POST["namalengkap"];
$kelas = $_POST["kelas"];
$NIS = $_POST["NIS"];
echo "Nama Lengkap : " . $namalengkap . "<br>";
echo "Kelas : " . $kelas . "<br>";
echo "NIS : " . $NIS;
}
?><file_sep><?php
include('./input-config.php');
if ( $_SESSION ["login"] != TRUE){
header ('location:login.php');
}
echo "<NAME>, " . $_SESSION["username"] . "<br>";
echo "Anda sebagai : " . $_SESSION["role"];
echo "<hr>";
echo "<a href='logout.php'>Logout</a>";
echo "<hr>";
echo "<a href='input-datadiri-tambah.php'>Tambah Data</a>";
echo "<hr>";
// READ - Menampilkan data dari database
$no = 1;
$tabledata = "";
$data = mysqli_query($mysqli, " SELECT * FROM datadiri ");
while($row = mysqli_fetch_array($data)){
$tabledata .= "
<tr>
<td>".$row["nis"]."</td>
<td>".$row["namalengkap"]."</td>
<td>".$row["tanggal_lahir"]."</td>
<td>".$row["nilai"]."</td>
<td>
<a href='input-datadiri-edit.php?nis=".$row["nis"]."'>Edit</a>
-
<a href='input-datadiri-hapus.php?nis=".$row["nis"]."'
onclick='return confirm(\"Yakin Dek ?\");'>Hapus</a>
</td>
</tr>
";
$no++;
}
echo "
<table cellpadding=5 border=1 cellspacing=0>
<tr>
<th>NIS</th>
<th>Nama Lengkap</th>
<th>Tanggal Lahir</th>
<th>Nilai</th>
<th>Aksi</th>
</tr>
$tabledata
</table>
";
?><file_sep><?php
include ('./mhsiswa-config.php');
$data=mysqli_query($mysqli,"DELETE FROM mahasiswa WHERE npm='".$_GET["npm"]."'");
header("location:mhsiswa.php");
?><file_sep><h1>Tambah Data</h1>
<form action="input-datadiri-tambah.php" method="POST">
<label for="nis"> Nomor Induk siswa :</label>
<input type="number" name="nis" placeholder="Ex. 12001142" /><br>
<label for="nama"> Nama Lengkap :</label>
<input type="text" name="nama" placeholder="Ex. <NAME>" /><br>
<label for="tanggal_lahir"> Tanggal Lahir :</label>
<input type="date" name="tanggal_lahir" /><br>
<label for="nilai"> Nilai :</label>
<input type="number" name="nilai" placeholder="Ex. 80.56" /><br>
<input type="submit" name="simpan" value="Simpan Data" />
<a href="input-datadiri.php">kembali</a>
</form>
<?php
if( isset($_POST["simpan"])){
$nis = $_POST["nis"];
$nama = $_POST["nama"];
$tanggal_lahir= $_POST["tanggal_lahir"];
$nilai = $_POST["nilai"];
//CREATE - Menambahkan Data ke DataBase
$query = "
INSERT INTO datadiri VALUES
('$nis', '$nama', '$tanggal_lahir', '$nilai');
";
include ('./input-config.php');
$insert = mysqli_query($mysqli, $query);
if ($insert){
echo"
<script>
alert('Data Berhasil ditambahkan');
window.location='input-datadiri.php';
</script>
";
}
}
?><file_sep><?php
include('./input-nilai-config.php');
echo "<a href='input-data-nilai-tambah.php'>Tambah Data</a>";
echo "<hr>";
// Menampilkan data nilai database
$no = 1;
$tabledata = "";
$data = mysqli_query($mysqli," SELECT * FROM siswa_nilai ");
while($row = mysqli_fetch_array($data)){
$nilai_akhir=($row["kehadiran"]+$row["tugas"]+$row["uts"]+$row["uas"])/4;
$tabledata .= "
<tr>
<td>".$row["nis"]."</td>
<td>".$row["nama_lengkap"]."</td>
<td>".$row["kelas"]."</td>
<td>".$row["kehadiran"]."</td>
<td>".$row["tugas"]."</td>
<td>".$row["uts"]."</td>
<td>".$row["uas"]."</td>
<td>".$nilai_akhir."</td>
<td>
<a href='input-data-nilai-edit.php?nis=".$row["nis"]."'>Edit</a>
-
<a href='input-data-nilai-hapus.php?nis=".$row["nis"]."'
onclick='return confirm(\"Yakin Hapus ?\");'>Hapus</a>
</td>
</tr>
";
$no++;
}
echo "
<table cellpadding=5 border=1 cellspacing=0>
<tr>
<th>NIS</th>
<th>Nama Lengkap</th>
<th>Kelas</th>
<th>Kehadiran</th>
<th>Tugas</th>
<th>UTS</th>
<th>UAS</th>
<th>Nilai Akhir</th>
<th>Aksi</th>
</tr>
$tabledata
</table>
";
?><file_sep><?php
if ( isset($_GET["nis"]) ){
$nis = $_GET["nis"];
$check_nis = "SELECT * FROM siswa_nilai WHERE nis = '$nis';";
include('./input-nilai-config.php');
$querry = mysqli_query($mysqli, $check_nis);
$row = mysqli_fetch_array($querry);
}
?>
<h1>Edit Data</h1>
<form action="input-data-nilai-edit.php" method="POST">
<label for="nis"> Nomor Induk siswa :</label>
<input value="<?php echo $row["nis"]; ?>" readonly type="number" name="nis" placeholder="Ex. 12001142" /><br>
<label for="nama_lengkap"> Nama Lengkap :</label>
<input value="<?php echo $row["nama_lengkap"]; ?>" type="text" name="nama_lengkap" placeholder="Ex. <NAME>" /><br>
<label for="kelas"> Kelas :</label>
<input value="<?php echo $row["kelas"]; ?>" type="text" name="kelas" placeholder="Ex. XI RPL 1" /><br>
<label for="kehadiran"> Kehadiran :</label>
<input value="<?php echo $row["kehadiran"]; ?>" type="number" name="kehadiran" /><br>
<label for="tugas"> Tugas :</label>
<input value="<?php echo $row["tugas"]; ?>" type="number" name="tugas" placeholder="Ex. 80.56" /><br>
<label for="uts"> UTS :</label>
<input value="<?php echo $row["uts"]; ?>" type="number" name="uts" placeholder="Ex. 80.56" /><br>
<label for="nilai"> UAS :</label>
<input value="<?php echo $row["uas"]; ?>" type="number" name="uas" placeholder="Ex. 80.56" /><br>
<input type="submit" name="simpan" value="Simpan Data" />
<a href="input-data-nilai.php">kembali</a>
</form>
<?php
if ( isset($_POST["simpan"])) {
$nis = $_POST["nis"];
$nama_lengkap = $_POST["nama_lengkap"];
$kelas = $_POST["kelas"];
$kehadiran = $_POST["kehadiran"];
$tugas = $_POST["tugas"];
$uts = $_POST["uts"];
$uas = $_POST["uas"];
//Edit - Memperbarui Data
$query ="
UPDATE siswa_nilai SET
nama_lengkap = '$nama_lengkap',
kelas = '$kelas',
kehadiran = '$kehadiran',
tugas = '$tugas',
uts = '$uts',
uas = '$uas'
WHERE nis = '$nis';
";
include ('./input-nilai-config.php');
$update = mysqli_query($mysqli, $query);
if($update){
echo "
<script>
alert('Data Berhasil Diperbaharui');
window.location='input-data-nilai.php';
</script>
";
}else{
echo "
<script>
alert('Data Gagal diperbaharui');
window.location='input-data-nilai-edit.php?nis=$nis';
</script>
";
}
}
?><file_sep><?php
// Variable
// $1nama; Contoh Salah (Karena diawali angka)
// $#nama; Contoh Salah (Ada simbol ditengah)
// nama; Contoh Salah (Tidak ada simbol $)
$nama = "Rizki";
$usia = 16;
echo "Nama saya $nama <br>";
echo "Usia saya $usia tahun";
// Tipe data (Integer, float, string)
// (Boolean, array)
$Namalengkap = "Rizki Giant 90";
$umur = 16; // integer
$nilai = 75.50; // Float
$jomblo = TRUE; // boolean (TRUE/FALSE)
// Array string
$namarpl1 = array("Alya", "Davit", "Eben");
echo "Nama lengkap : $Namalengkap <br>";
echo "Umur : $umur <br>";
echo "Nilai: $nilai <br>";
echo "Jomblo : $jomblo <br>";
echo "<hr>";
echo "Array 0 : $namarpl1[0] <br>"; // Alya
echo "Array 2 : $namarpl1[2] <br>"; // Eben
// Aritmatika (+ - / * %)
$angka1 = 10;
$angka2 = 5;
echo "<hr>";
echo "Tambah :" .$tambah = $angka1 + $angka2 . "<br>";
echo "Kurang :" .$kurang = $angka1 - $angka2 . "<br>";
echo "Bagi :" .$bagi = $angka1 / $angka2 . "<br>";
echo "Kali :" .$kali = $angka1 * $angka2 . "<br>";
echo "Sisa bagi :" .$sisabagi = $angka1 % $angka2 . "<br>";
echo "<hr>";
//Operator perbandingan (>,<, !=, ==, ===)
//Return TRUE(1), FALSE(NULL)
$a = 10;
$b = 5;
$c ="10";
echo "== :"; echo $a == $b; echo "<br>";
echo "> :"; echo $a > $b; echo "<br>";
echo "< :"; echo $a < $b; echo "<br>";
echo "!= :"; echo $a != $b; echo "<br>";
echo "=== :"; echo $a === $b; echo "<br>";
echo "<hr>";
//Operator Logika (AND,OR,&&, ||)
//IF ELSE
$x = 10;
$y = 20;
if ($x == 10 AND $y == 20){ echo "Terpenuhi 2 Variable <br>"; }
echo "<hr>";
if ($x == 10 OR $y == 10){ echo "Salah satu Variable Terpenuhi <br>"; }
echo "<hr>";
?><file_sep><form action="input-siswa.php" method="POST">
<label for= "nis">Nomor Induk siswa
<input type="number" name="nis" placeholder="Ex.12001142"/><br>
<label for="nama">Nama Lengkap :</label>
<input type="text" name="nama" placeholder="Ex. <NAME>"/><br>
<label for="jk">Jenis Kelamin :</label>
<input type="radio" name="jk" value="L"/> Laki Laki
<input type="radio" name="jk" value="P"/> Perempuan<br>
<label for="Kelas">Kelas:</label>
<select name="kelas">
<option>10 RPL 1</option>
<option>10 RPL 2</option>
<option>11 RPL 1</option>
<option>11 RPL 2</option>
<option>12 RPL 1</option>
<option>12 RPL 2</option>
</select><br>
<label for="tanggal_lahir">Tanggal Lahir :</label>
<input type="date" name="tanggal_lahir" /><br>
<label for="alamat">Alamat :</label>
<textarea name="alamat" placeholder="Ex. Jl. <NAME>" ></textarea><br>
<label for="nilai">Nilai :</label>
<input type="number" name="nilai" placeholder="Ex. 80.56" /><br>
<input type="submit" name="simpan" value="Simpan data" />
<input type="reset" name="reset" value="Reset Input" />
</form>
<?php
if (isset($_POST["simpan"]) ){
echo "<hr>";
// Deklarasi variabel
$nis = $_POST["nis"];
$namalengkap = $_POST["nama"];
$jeniskelamin = $_POST["jk"];
$kelas = $_POST["kelas"];
$tanggal_lahir = $_POST["tanggal_lahir"];
$alamat = $_POST["alamat"];
$nilai = $_POST["nilai"];
// Tampil Data Variabel
echo "
Hasil Inputan Seagai Berikut : <br>
Nomor Induk Siswa : $nis <br>
Nama Lengkap : $namalengkap <br>
Jenis Kelamin : $jeniskelamin <br>
Kelas : $kelas <br>
Tanggal Lahir : $tanggal_lahir <br>
Alamat : $alamat <br>
Nilai : $nilai <br>
";
}<file_sep><h1>Form Login</h1>
<form action="login.php" method="POST">
<label >Username</label><br>
<input type="text" name="username" placeholder="Ex. wananda" />
<br>
<label>password</label><br>
<input type="<PASSWORD>" name="password" placeholder="Ex. ---" />
<br>
<input type="submit" name="login" value="Masuk" />
</form>
<?php
include("./input-config.php");
if( isset($_POST["login"]) ) {
$username = $_POST["username"];
$password = $_POST["password"];
$query = "SELECT * FROM akun
WHERE username='$username' AND password=MD5('<PASSWORD>'); ";
$data = mysqli_query($mysqli, $query);
if(mysqli_num_rows($data) > 0) {
$row = mysqli_fetch_array($data);
$_SESSION["login"] =TRUE;
$_SESSION["akun_id"] = $row["akun_id"];
$_SESSION["username"] = $row["username"];
$_SESSION["role"] = $row["role"];
echo "
<script>
alert('Login Berhasil');
window.location='input-datadiri.php';
</script>
";
}else{
echo "
<script>
alert('Akun tidak ditemukan, coba lagi');
window.location='login.php';
</script>
";
}
}
?><file_sep><form action="Layang-Layang.php" method="POST">
<h1>Rumus Menghitung Luas Layang Layang </h1>
<p>Diagonal 1 : </p>
<input type= "number" name="Diagonal1" placeholder="Ex. 5" />
<p>Diagonal 2 : </p>
<input type= "number" name="Diagonal2" placeholder="Ex. 5" />
<input type="submit" name="proses" value="Hitung Luas"/>
</form>
<?php
if (isset($_POST["proses"]) ){
echo "<hr>";
$Diagonal1 = $_POST['Diagonal1'];
$Diagonal2 = $_POST['Diagonal2'];
// menghitung Luas Layang Layang
$luas = 1/2 * $Diagonal1 * $Diagonal2;
echo "Hasil hitung Luas Layang Layang adalah sebagai berikut:<br />";
echo "Diketahui;<br />";
echo "Diagonal 1 : $Diagonal1 <br>";
echo "Diagonal 2 : $Diagonal2 <br>";
echo "Luas Layang Layang = ".$luas." cm<sup>2</sup><br/>";
}<file_sep><form action="Kerucut.php" method="POST">
<h1> Rumus Menghitung Luas dan Volume Kerucut </h1>
<p> Jari Jari : </p>
<input type="number" name="kerucut_r" placeholder="Ex. 5" /><br>
<p> Tinggi Kerucut : </p>
<input type="number" name="kerucut_t" placeholder="Ex. 5" />
<p> Panjang sisi Kerucut: </p>
<input type="number" name="kerucut_s" placeholder="Ex. 5" />
<input type="submit" name="proses" value="Hitung Luas dan Volume" />
</form>
<?php
if(isset($_POST['proses'])){
$kerucut_r = $_POST['kerucut_r'];
$kerucut_s = $_POST['kerucut_s'];
$kerucut_t = $_POST['kerucut_t'];
// menghitung Luas dan volume Kerucut
$phi = 3.14;
$kerucut_luas_alas = $phi * $kerucut_r * $kerucut_r;
$kerucut_luas_selimut = $phi * $kerucut_r * $kerucut_s;
$kerucut_luas_permukaan = $kerucut_luas_alas + $kerucut_luas_selimut;
$kerucut_volume = $kerucut_luas_alas * $kerucut_t / 3;
echo "Diketahui;<br />";
echo "<p>Luas alas = $kerucut_luas_alas</p>";
echo "<p>Luas selimut = $kerucut_luas_selimut</p>";
echo "<p>Luas permukaan = $kerucut_luas_permukaan</p>";
echo "<p>Volume kerucut = $kerucut_volume</p>";
}
?><file_sep><?php
if ( isset($_GET["npm"]) ){
$npm = $_GET["npm"];
$check_npm = "SELECT * FROM mahasiswa WHERE npm = '$npm';";
include('./mhsiswa-config.php');
$querry = mysqli_query($mysqli, $check_npm);
$row = mysqli_fetch_array($querry);
}
?>
<h1>Edit Data</h1>
<form action="mhsiswa-edit.php" method="POST">
<label for="npm"> Nomor Penduduk Mahasiswa :</label>
<input value="<?php echo $row["npm"]; ?>" readonly type="number" name="npm" placeholder="Ex. 12001142" /><br>
<label for="namamahasiwa">namamahasiswa :</label>
<input value="<?php echo $row["namamahasiswa"]; ?>" type="text" name="namamahasiswa" placeholder="Ex. Alyael" /><br>
<label for="prodi"> Prodi :</label>
<input value="<?php echo $row["prodi"]; ?>" type="text" name="prodi" placeholder="Informatika" /><br>
<label for="kehadiran"> Kehadiran :</label>
<input value="<?php echo $row["kehadiran"]; ?>" type="number" name="kehadiran" /><br>
<label for="tugas"> Tugas :</label>
<input value="<?php echo $row["tugas"]; ?>" type="number" name="tugas" placeholder="Ex. 80" /><br>
<label for="uts"> UTS :</label>
<input value="<?php echo $row["uts"]; ?>" type="number" name="uts" placeholder="Ex. 80" /><br>
<label for="nilai"> UAS :</label>
<input value="<?php echo $row["uas"]; ?>" type="number" name="uas" placeholder="Ex. 80" /><br>
<input type="submit" name="simpan" value="Simpan Data" />
<a href="mhsiswa.php">kembali</a>
</form>
<?php
if (isset($_POST["simpan"])) {
$npm = $_POST["npm"];
$namamahasiswa = $_POST["namamahasiswa"];
$prodi = $_POST["prodi"];
$kehadiran = $_POST["kehadiran"];
$tugas = $_POST["tugas"];
$uts = $_POST["uts"];
$uas = $_POST["uas"];
$query ="
UPDATE mahasiswa SET namamahasiswa = '$namamahasiswa',
prodi = '$prodi',
kehadiran = '$kehadiran',
tugas = '$tugas',
uts = '$uts',
uas = '$uas'
WHERE npm = '$npm';
";
include ('./mhsiswa-config.php');
$update = mysqli_query ($mysqli, $query);
if ($update){
echo "
<script>
alert('Data Berhasil Diperbaharui');
window.location='mhsiswa.php';
</script>
";
}else {
echo "
<script>
alert('Data Gagal');
window.location='mhsiswa-edit.php?nis=$nis';
</script>
";
}
}
?>
|
bf15e0b444a1a7103643363d9328b062f250a5ef
|
[
"PHP"
] | 37 |
PHP
|
EpiHalimah/epiihaliimah
|
56c0afa8f199abe64d8d9296cd5d67b8f0aadee7
|
1fab2e63213710db2c529aaae377ff8c41c8c653
|
refs/heads/master
|
<file_sep><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Codon by <NAME> -->
<project basedir="." default="build" name="codon">
<path id="classpath-main">
<pathelement location="bin/main" />
</path>
<path id="classpath-test">
<pathelement location="lib/junit4.jar" />
<pathelement location="bin/main" />
<pathelement location="bin/test" />
</path>
<path id="classpath-testplugin">
<pathelement location="bin/main" />
<pathelement location="bin/testplugin" />
</path>
<!-- Macro compiling a source dierctory -->
<macrodef name="compile">
<attribute name="name" />
<sequential>
<mkdir dir="bin/@{name}" />
<!-- Copy all source to binary directory
Keep the .java files for code navigation -->
<copy includeemptydirs="false" todir="bin/@{name}">
<fileset dir="src/@{name}/java" excludes="**/*.launch" />
</copy>
<!-- Compile with given settings -->
<javac srcdir="bin/@{name}" destdir="bin/@{name}"
classpathref="classpath-test" debug="true"
debuglevel="source,lines,vars"
source="1.6" target="1.6" />
</sequential>
</macrodef>
<target name="init">
<mkdir dir="bin" />
</target>
<target name="clean">
<delete dir="bin" />
</target>
<target depends="init" name="build-project">
<compile name="main" />
<compile name="test" />
<compile name="testplugin" />
<jar destfile="bin/codon.jar" basedir="bin/main" />
<jar destfile="bin/codon-test.jar" basedir="bin/test" />
<jar destfile="bin/codon-testplugin.jar" basedir="bin/testplugin" />
</target>
<target depends="build-project" name="test">
<mkdir dir="reports" />
<junit printsummary="yes" haltonfailure="yes">
<classpath refid="classpath-test" />
<formatter type="plain" />
<batchtest fork="yes" todir="reports" haltonfailure="yes">
<fileset dir="bin/test">
<include name="**/*Test*.java" />
</fileset>
</batchtest>
</junit>
</target>
<!-- Misc targets -->
<target name="build-refprojects" />
<target name="build-subprojects" />
<target depends="clean" name="cleanall" />
<target depends="build-subprojects,build-project" name="build" />
</project>
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.commands.core;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.dnikulin.codon.log.CountingLogger;
import org.dnikulin.codon.plugin.PluginLinker;
import org.dnikulin.codon.plugin.PluginLoader;
import org.junit.Test;
public class PluginCommandTest {
public static final String NODE_CLASS = "test.TestPluginNode";
@Test
public void testImportJar() {
testGoodImport("bin/codon-testplugin.jar");
}
@Test
public void testImportTree() {
testGoodImport("bin");
}
@Test
public void testImportLibraryJar() {
testGoodImport("bin/codon.jar", "bin/codon-testplugin.jar");
}
@Test
public void testImportAll() {
testGoodImport("bin", "bin/codon.jar", "bin/codon-testplugin.jar");
}
@Test
public void testMissingFile() {
testBadImport("bin/fail");
}
public static void testGoodImport(String... paths) {
PluginLinker linker = new PluginLinker();
PluginLoader loader = new PluginLoader();
PluginCommand command = new PluginCommand(linker, loader);
// Loader must not yet have test node class
try {
loader.loadClass(NODE_CLASS);
// Must not reach
fail();
} catch (ClassNotFoundException ex) {
// Correct
}
CountingLogger log = new CountingLogger();
for (String path : paths)
command.execute(new String[] { path }, log);
// Must not log anything for correct operation
// Note that the linker and loader still have null loggers
assertEquals(0, log.count());
// Loader must have bytes for the test node class
try {
loader.loadClass(NODE_CLASS);
} catch (ClassNotFoundException ex) {
fail();
}
}
public static void testBadImport(String path) {
PluginLinker linker = new PluginLinker();
PluginLoader loader = new PluginLoader();
PluginCommand command = new PluginCommand(linker, loader);
CountingLogger log = new CountingLogger();
command.execute(new String[] { path }, log);
// Must not log exactly once for a failed import
assertEquals(1, log.count());
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon;
import java.util.Map;
import java.util.TreeMap;
import org.dnikulin.codon.command.Command;
/** Help file registry for commands. */
public class HelpFiles {
private final Map<String, String> files;
public HelpFiles() {
files = new TreeMap<String, String>();
}
public synchronized void addFile(String name, String file) {
files.put(name, file);
}
public synchronized String getFile(String name) {
return files.get(name);
}
public synchronized String getFile(Command cmd) {
String file = files.get(cmd.getClass().getSimpleName());
if (file != null)
return file;
String topic = cmd.getCommandTopic();
String name = cmd.getCommandName();
return files.get(topic + "-" + name);
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.misc;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
/** CLI style string arguments. */
public class Arguments {
private final List<String> thetokens;
private final List<String> argv;
private final Set<String> flags;
/** Number of raw tokens. */
public final int tokens;
/** Number of positional (non-flag) arguments. */
public final int args;
/**
* Interpret token array as CLI arguments.
*
* @param tokens
* Token array
*/
public Arguments(String[] tokens) {
thetokens = new ArrayList<String>(tokens.length);
argv = new ArrayList<String>(tokens.length);
flags = new TreeSet<String>();
boolean argsOnly = false;
for (String token : tokens) {
this.thetokens.add(token);
if (token.equals("--"))
argsOnly = true;
else if (!argsOnly && isFlag(token))
flags.add(token.substring(1));
else
argv.add(token);
}
this.tokens = thetokens.size();
args = argv.size();
}
/**
* Check if a parameterless flag was used. Example: check for "-test" with
* flag("test")
*
* @param flag
* Flag string (without the leading '-')
* @return true if the flag was used and without a parameter
*/
public boolean flag(String flag) {
return flags.contains(flag);
}
/**
* Check if a flag was used with a parameter. Example: check for "-i3" with
* flagHasArg("i")
*
* @param flag
* Flag string (without the leading '-')
* @return true if the flag was used and with a parameter
*/
public boolean flagHasArg(String flag) {
String value = get(flag);
return (value != null) && (!value.isEmpty());
}
/**
* Check if a flag was used with or without a parameter.
*
* @param flag
* Flag string (without the leading '-')
* @return true if the flag was used, with or without a parameter
*/
public boolean flagOrHasArg(String flag) {
return flag(flag) || flagHasArg(flag);
}
/**
* Return specific raw token as given in constructor.
*
* @param i
* Token index
* @return Token string
*/
public String token(int i) {
return thetokens.get(i);
}
/**
* Return specific positional (non-flag) argument.
*
* @param i
* Argument index
* @return Argument string
*/
public String get(int i) {
return argv.get(i);
}
/**
* Return specific flag argument.
*
* @param flag
* Flag prefix (without the leading '-')
* @return Flag argument value (null if flag not found)
*/
public String get(String flag) {
for (String keyString : flags) {
if (keyString.startsWith(flag))
return keyString.substring(flag.length());
}
return null;
}
/**
* Construct an array of the positional (non-flag) arguments.
*
* @return Array of positional arguments
*/
public String[] getPositional() {
String[] out = new String[args];
for (int i = 0; i < out.length; i++)
out[i] = get(i);
return out;
}
/**
* Return integer represented by specific positional argument.
*
* @param i
* Argument index
* @return Flag argument value (def if flag not found)
*/
public int getInt(int i, int def) {
return parseIntOr(get(i), def);
}
/**
* Return double-precision float represented by specific positional
* argument.
*
* @param i
* Argument index
* @return Flag argument value (def if flag not found)
*/
public double getDouble(int i, double def) {
return parseDoubleOr(get(i), def);
}
/**
* Return integer represented by specific flag argument.
*
* @param flag
* Flag prefix (without the leading '-')
* @return Flag argument value (def if flag not found)
*/
public int getInt(String flag, int def) {
return parseIntOr(get(flag), def);
}
/**
* Return double-precision float represented by specific flag argument.
*
* @param flag
* Flag prefix (without the leading '-')
* @return Flag argument value (def if flag not found)
*/
public double getDouble(String flag, double def) {
return parseDoubleOr(get(flag), def);
}
/**
* Check if a token string represents a flag. Flags start with a - and
* follow with a non-digit character.
*
* @param token
* Token to check
* @return true if the token is a flag
*/
public static boolean isFlag(String token) {
if (token.length() < 2)
return false;
if (!token.startsWith("-"))
return false;
return !Character.isDigit(token.charAt(1));
}
/**
* Parse an integer string or return a default value.
*
* @param value
* String to parse
* @param def
* Default value
* @return Parsed integer or default
*/
public static int parseIntOr(String value, int def) {
if (value == null || value.isEmpty())
return def;
try {
return Integer.parseInt(value);
} catch (NumberFormatException ex) {
return def;
}
}
/**
* Parse a double float string or return a default value.
*
* @param value
* String to parse
* @param def
* Default value
* @return Parsed float or default
*/
public static double parseDoubleOr(String value, double def) {
if (value == null || value.isEmpty())
return def;
try {
return Double.parseDouble(value);
} catch (NumberFormatException ex) {
return def;
}
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.pipe.simple;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import org.dnikulin.codon.log.LineLogger;
import org.dnikulin.codon.log.NullLogger;
import org.dnikulin.codon.pipe.Consumer;
import org.dnikulin.codon.pipe.Pipe;
import org.dnikulin.codon.pipe.Producer;
import org.dnikulin.codon.pipe.compiler.PipeLinker;
import org.dnikulin.codon.pipe.except.PipeTypeException;
/** A pipe that is implemented by a list of linked pipes. */
public class CompoundPipe implements Pipe {
private final List<Pipe> pipes;
private final Consumer first;
private final Producer last;
private final AtomicReference<LineLogger> logger;
/**
* Construct a compound pipe from the list of pipes. The pipes are linked
* immediately. Throws IndexOutOfBoundsException if the list is empty.
*
* @param pipes
* Pipes to form a compound pipe
*/
public CompoundPipe(List<Pipe> pipes) throws PipeTypeException {
this.pipes = new ArrayList<Pipe>(pipes);
this.first = this.pipes.get(0);
this.last = this.pipes.get(this.pipes.size() - 1);
logger = new AtomicReference<LineLogger>(NullLogger.INSTANCE);
linkPipes();
}
/**
* Connect adjacent pipes in the pipeline, starting from the last pipe.
* Throws on type error.
*/
private void linkPipes() throws PipeTypeException {
Pipe prev = null;
for (int i = pipes.size() - 1; i >= 0; i--) {
Pipe pipe = pipes.get(i);
if (prev != null)
PipeLinker.linkPipes(pipe, prev);
prev = pipe;
}
}
// From Consumer
@Override
public Class<?> getInputType() {
return first.getInputType();
}
@Override
public void consume(Object value) {
first.consume(value);
}
// From Producer
@Override
public Class<?> getOutputType() {
return last.getOutputType();
}
@Override
public boolean addConsumer(Consumer consumer) {
return last.addConsumer(consumer);
}
@Override
public boolean hasConsumer() {
return last.hasConsumer();
}
@Override
public void removeConsumer(Consumer consumer) {
last.removeConsumer(consumer);
}
@Override
public void removeConsumers() {
last.removeConsumers();
}
// From LogSource
@Override
public LineLogger getLineLogger() {
return logger.get();
}
@Override
public void setLineLogger(LineLogger logger) {
this.logger.set(NullLogger.or(logger));
}
// From Resettable
@Override
public void reset() {
for (Pipe pipe : pipes)
pipe.reset();
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.pipe.record;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.GZIPOutputStream;
import org.dnikulin.codon.format.ObjectFormat;
import org.dnikulin.codon.log.LineLogger;
import org.dnikulin.codon.pipe.simple.SimplePipe;
/** Pipe that records objects to a stream. */
public class RecordPipe extends SimplePipe implements Runnable {
private final LineLogger log;
private final ObjectFormat format;
private final Class<?> type;
private DataOutputStream stream;
/**
* Construct a record pipe.
*
* @param log
* Line logger
* @param format
* Object format
* @param output
* Output stream
*/
public RecordPipe(LineLogger log, ObjectFormat format, OutputStream output)
throws IOException {
this.log = log;
this.format = format;
this.type = format.getObjectClass();
BufferedOutputStream bos1 = new BufferedOutputStream(output);
GZIPOutputStream gos = new GZIPOutputStream(bos1);
BufferedOutputStream bos2 = new BufferedOutputStream(gos);
this.stream = new DataOutputStream(bos2);
Runtime.getRuntime().addShutdownHook(new Thread(this));
}
@Override
public synchronized void consume(Object value) {
try {
if (stream != null) {
byte[] bytes = format.encode(value);
stream.writeInt(bytes.length);
stream.write(bytes);
}
} catch (IOException ex) {
log.print("Record error: " + ex.getLocalizedMessage());
close();
} finally {
produce(value);
}
}
private synchronized void close() {
if (stream == null)
return;
try {
stream.close();
} catch (IOException ex) {
// Ignore
} finally {
stream = null;
}
}
@Override
public void run() {
close();
}
/** Force stream flush. The pipe will no longer record objects. */
@Override
public void reset() {
super.reset();
close();
}
@Override
protected void finalize() throws Throwable {
close();
}
@Override
public Class<?> getInputType() {
return type;
}
@Override
public Class<?> getOutputType() {
return type;
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.format.registry;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.dnikulin.codon.format.ObjectFormat;
import org.dnikulin.codon.format.except.ObjectFormatNotFoundException;
/** Object format registry. */
public class ObjectFormats {
private final Map<String, ObjectFormat> byName;
private final Map<String, ObjectFormat> byClass;
/** Construct empty object format registry. */
public ObjectFormats() {
byName = new TreeMap<String, ObjectFormat>();
byClass = new TreeMap<String, ObjectFormat>();
}
/**
* Query registered object formats.
*
* @return List of object formats
*/
public synchronized List<ObjectFormat> getFormats() {
return new ArrayList<ObjectFormat>(byClass.values());
}
/**
* Register an object format.
*
* @param format
* Object format
*/
public synchronized void add(ObjectFormat format) {
String formatName = format.getFormatName();
String className = format.getObjectClass().getName();
byName.put(formatName, format);
byClass.put(className, format);
}
/**
* Find object format by format name.
*
* @param formatName
* Format name
* @return Object format
* @exception ObjectFormatNotFoundException
* If the format was not found
*/
public synchronized ObjectFormat getByName(String formatName)
throws ObjectFormatNotFoundException {
return find(byName, formatName);
}
/**
* Find object format by class name.
*
* @param className
* Class name
* @return Object format
* @exception ObjectFormatNotFoundException
* If the format was not found
*/
public synchronized ObjectFormat getByClass(String className)
throws ObjectFormatNotFoundException {
return find(byClass, className);
}
/**
* Find object format by class.
*
* @param klass
* Class
* @return Object format
* @exception ObjectFormatNotFoundException
* If the format was not found
*/
public ObjectFormat getByClass(Class<?> klass)
throws ObjectFormatNotFoundException {
return getByClass(klass.getName());
}
private static ObjectFormat find(Map<String, ObjectFormat> map, String key)
throws ObjectFormatNotFoundException {
ObjectFormat format = map.get(key);
if (format == null)
throw new ObjectFormatNotFoundException();
return format;
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.commands.core;
import static org.dnikulin.codon.command.CommandTools.printUsage;
import static org.dnikulin.codon.misc.TimeTools.sleepFor;
import org.dnikulin.codon.command.EffectCommand;
import org.dnikulin.codon.log.LineLogger;
public class SleepCommand implements EffectCommand {
@Override
public void execute(String[] args, LineLogger log) {
if (args.length != 1) {
printUsage(log, this);
return;
}
try {
long millis = Long.parseLong(args[0]);
sleepFor(millis);
} catch (NumberFormatException ex) {
log.print("Argument is not an integer");
}
}
@Override
public String getCommandTopic() {
return "core";
}
@Override
public String getCommandName() {
return "sleep";
}
@Override
public String getCommandUsage() {
return "<millis>";
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.pipe.simple;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.List;
import org.dnikulin.codon.pipe.Consumer;
import org.dnikulin.codon.pipe.Pipe;
import org.dnikulin.codon.pipe.except.PipeTypeException;
import org.dnikulin.codon.pipe.test.TestPipe;
import org.junit.Test;
public class CompoundPipeTest {
@Test
public void testEmpty() {
try {
new CompoundPipe(new ArrayList<Pipe>());
// Must not reach
fail();
} catch (PipeTypeException ex) {
fail();
} catch (IndexOutOfBoundsException ex) {
// Correct
}
}
@Test
public void testGoodTypes() {
TestPipe pipe1 = new TestPipe(Object.class, Pipe.class);
TestPipe pipe2 = new TestPipe(Pipe.class, Pipe.class);
TestPipe pipe3 = new TestPipe(Consumer.class, Object.class);
TestPipe pipe4 = new TestPipe(Object.class, Object.class);
List<Pipe> pipes = new ArrayList<Pipe>();
pipes.add(pipe1);
pipes.add(pipe2);
pipes.add(pipe3);
CompoundPipe cpipe = null;
try {
cpipe = new CompoundPipe(pipes);
} catch (PipeTypeException ex) {
fail();
}
// Must have connected only in between pipes
assertTrue(pipe1.hasConsumer());
assertTrue(pipe2.hasConsumer());
assertFalse(pipe3.hasConsumer());
assertFalse(cpipe.hasConsumer());
// Must connect outputs to last pipe
cpipe.addConsumer(pipe4);
assertTrue(pipe3.hasConsumer());
assertTrue(cpipe.hasConsumer());
// Enable propagation
pipe1.setPass(true);
pipe2.setPass(true);
pipe3.setPass(true);
// Must not have passed anything yet
assertEquals(0, pipe1.count());
assertEquals(0, pipe2.count());
assertEquals(0, pipe3.count());
assertEquals(0, pipe4.count());
assertSame(null, pipe4.last());
// Must pass objects correctly
pipe1.consume(pipe1);
assertEquals(1, pipe1.count());
assertEquals(1, pipe2.count());
assertEquals(1, pipe3.count());
assertEquals(1, pipe4.count());
assertSame(pipe1, pipe4.last());
}
@Test
public void testBadTypes() {
TestPipe pipe1 = new TestPipe(Object.class, Object.class);
// Connection fine here
TestPipe pipe2 = new TestPipe(Object.class, List.class);
// Connection bad here
TestPipe pipe3 = new TestPipe(String.class, Object.class);
// Connection fine here (but won't reach)
TestPipe pipe4 = new TestPipe(Object.class, Object.class);
List<Pipe> pipes = new ArrayList<Pipe>();
pipes.add(pipe1);
pipes.add(pipe2);
pipes.add(pipe3);
pipes.add(pipe4);
try {
new CompoundPipe(pipes);
// Must not reach
fail();
} catch (PipeTypeException ex) {
// Correct
}
// Must have connected only *until* the first type error
assertFalse(pipe1.hasConsumer());
assertFalse(pipe2.hasConsumer());
assertTrue(pipe3.hasConsumer());
assertFalse(pipe4.hasConsumer());
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.daemon.test;
import static org.dnikulin.codon.command.CommandTools.printUsage;
import org.dnikulin.codon.daemon.Daemon;
import org.dnikulin.codon.daemon.thread.DaemonThread;
import org.dnikulin.codon.daemon.thread.DaemonThreads;
import org.dnikulin.codon.log.LineLogger;
import org.dnikulin.codon.pipe.Consumer;
import org.dnikulin.codon.pipe.command.ProducerCommand;
/** A command to initiate a TestDaemon. */
public class TestDaemonCommand implements ProducerCommand {
private final DaemonThreads threads;
/**
* Create a test daemon command.
*
* @param threads
* Daemon thread registry.
*/
public TestDaemonCommand(DaemonThreads threads) {
this.threads = threads;
}
@Override
public void produce(String[] args, LineLogger log, Consumer consumer) {
if (args.length != 2) {
printUsage(log, this);
return;
}
int ticks = Integer.parseInt(args[0]);
int sleep = Integer.parseInt(args[1]);
Daemon daemon = new TestDaemon(log, consumer, ticks, sleep);
DaemonThread thread = threads.start(daemon);
log.print("Started test daemon in ID " + thread.getPID());
}
@Override
public String getCommandTopic() {
return "test";
}
@Override
public String getCommandName() {
return "testdaemon";
}
@Override
public String getCommandUsage() {
return "<ticks> <milliseconds>";
}
@Override
public Class<?> getOutputType() {
return String.class;
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.log;
import java.util.concurrent.atomic.AtomicLong;
import org.dnikulin.codon.misc.Resettable;
/** A LineLogger that only counts its invocations. */
public class CountingLogger implements LineLogger, Resettable {
private final AtomicLong prints;
/** Construct a LineLogger with a zero print count. */
public CountingLogger() {
prints = new AtomicLong(0);
}
/**
* Reset print count.
*
* @param count
* New print count
*/
public void setCount(long count) {
prints.set(count);
}
/** Reset print count to 0. */
@Override
public void reset() {
setCount(0);
}
/**
* Query print count.
*
* @return Current print count
*/
public long count() {
return prints.get();
}
/**
* Increment count.
*
* @param line
* Print line (ignored)
*/
@Override
public void print(String line) {
prints.incrementAndGet();
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.pipe.record;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.dnikulin.codon.daemon.Daemon;
import org.dnikulin.codon.daemon.except.DaemonException;
import org.dnikulin.codon.format.ObjectFormat;
import org.dnikulin.codon.format.primitive.StringObjectFormat;
import org.dnikulin.codon.log.LineLogger;
import org.dnikulin.codon.log.NullLogger;
import org.dnikulin.codon.pipe.test.TestPipe;
import org.junit.Test;
public class RecordReplayTest {
private static final LineLogger LOG = NullLogger.INSTANCE;
private static final ObjectFormat FORMAT = StringObjectFormat.INSTANCE;
@Test
public void testRecordReplay() throws IOException {
String[] strings = makeStrings();
byte[] bytes = record(strings);
replay(strings, bytes);
}
private static byte[] record(String[] strings) throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
RecordPipe recorder = new RecordPipe(LOG, FORMAT, stream);
for (String string : strings)
recorder.consume(string);
// Force flush
recorder.reset();
// Must have written some bytes
byte[] bytes = stream.toByteArray();
assertTrue(bytes.length > 0);
return bytes;
}
private static void replay(String[] strings, byte[] bytes)
throws IOException {
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
TestPipe pipe = new TestPipe();
ReplayDaemon daemon = new ReplayDaemon(pipe, LOG, FORMAT, in,
"Test stream");
// Must not have produced anything yet
assertEquals(0, pipe.count());
// Run through daemon
runDaemon(daemon);
// Must have produced every string
assertEquals(strings.length, pipe.count());
assertEquals(strings[strings.length - 1], pipe.last());
}
private static void runDaemon(Daemon daemon) {
try {
while (true)
daemon.resumeDaemon();
} catch (DaemonException ex) {
// Ignore
}
}
private static String[] makeStrings() {
final int count = 127;
String[] out = new String[count];
for (int i = 0; i < count; i++)
out[i] = "test-" + i;
return out;
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package test;
import org.dnikulin.codon.log.LineLogger;
import org.dnikulin.codon.pipe.command.PipeCommand;
import org.dnikulin.codon.pipe.command.registry.PipeCommands;
import org.dnikulin.codon.pipe.command.registry.PipeCommandsPluginNode;
import org.dnikulin.codon.pipe.Pipe;
import org.dnikulin.codon.pipe.except.PipeFactoryException;
import org.dnikulin.codon.pipe.except.PipeNameInUseException;
import org.dnikulin.codon.pipe.except.PipeNameInvalidException;
import org.dnikulin.codon.pipe.nulled.NullPipe;
import org.dnikulin.codon.plugin.PluginNode;
public class TestPluginNode implements PipeCommandsPluginNode, PipeCommand {
@Override
public String getPluginName() {
return "Test plugin node";
}
@Override
public String getPluginVersion() {
return "0";
}
@Override
public void addPipeCommands(PipeCommands commands)
throws PipeNameInvalidException, PipeNameInUseException {
commands.add(this);
}
@Override
public String getCommandTopic() {
return "test";
}
@Override
public String getCommandName() {
return "testplug";
}
@Override
public String getCommandUsage() {
return "";
}
@Override
public Pipe makePipe(String[] args, LineLogger log)
throws PipeFactoryException {
log.print("Test plugin working");
return NullPipe.INSTANCE;
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import org.dnikulin.codon.log.CountingLogger;
import org.dnikulin.codon.log.NullLogger;
import org.dnikulin.codon.pipe.command.registry.PipeCommands;
import org.junit.Test;
public class CodonKernelTest {
@Test
public void testCodonKernel() {
CodonKernel ck = new CodonKernel();
// All associated objects must be non-null
assertNotNull(ck.getPluginLinker());
assertNotNull(ck.getPluginLoader());
assertNotNull(ck.getPipeLinker());
assertNotNull(ck.getPipeCommands());
assertNotNull(ck.getObjectFormats());
// Must start with null logger
assertSame(NullLogger.INSTANCE, ck.getLineLogger());
// Must associate line logger correctly
CountingLogger log = new CountingLogger();
ck.setLineLogger(log);
assertSame(log, ck.getLineLogger());
// Must not yet have "testplug" command
PipeCommands cmds = ck.getPipeCommands();
assertFalse(cmds.has("testplug"));
// Must not have logged anything yet
assertEquals(0, log.count());
// Must have working "plugin" command
// Import specific jar
ck.runCommand("plugin bin/codon-testplugin.jar");
// Import entire bin directory (including all jars)
ck.runCommand("plugin bin");
// Must log for installations
assertTrue(log.count() > 0);
// Must now have "testplug" command
assertTrue(cmds.has("testplug"));
// Must log when testplug is run
log.reset();
ck.runCommand("testplug");
assertTrue(log.count() > 0);
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.format.tools;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.dnikulin.codon.format.ObjectFormat;
import org.dnikulin.codon.format.except.ObjectCorruptException;
/**
* Object format for lists containing objects that are all supported by a
* specific format.
*/
public class ListObjectFormat extends StreamObjectFormat<List<?>> {
private final ObjectFormat format;
/**
* Construct a list object format with the given element format.
*
* @param format
* Element format
*/
public ListObjectFormat(ObjectFormat format) {
this.format = format;
}
@Override
public String getFormatName() {
return "list(" + format.getFormatName() + ")";
}
@Override
public Class<?> getObjectClass() {
return List.class;
}
@Override
public void write(DataOutputStream out, List<?> list) throws IOException {
for (Object object : list) {
byte[] bytes = format.encode(object);
out.writeInt(bytes.length);
out.write(bytes);
}
}
@Override
public List<?> read(DataInputStream in) throws IOException,
ObjectCorruptException {
List<Object> list = new ArrayList<Object>();
while (in.available() > 0) {
int size = in.readInt();
byte[] bytes = new byte[size];
in.read(bytes);
Object object = format.decode(bytes);
list.add(object);
}
return list;
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.format.primitive;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import org.dnikulin.codon.format.ObjectFormat;
/** Object format supporting java.lang.String (UTF8 encoding). */
public class StringObjectFormat implements ObjectFormat {
/** Singleton instance. */
public static final StringObjectFormat INSTANCE = new StringObjectFormat();
/** Character encoding. */
public static final Charset UTF8 = Charset.forName("utf-8");
@Override
public String getFormatName() {
return "string-utf8";
}
@Override
public Class<?> getObjectClass() {
return String.class;
}
@Override
public byte[] encode(Object object) {
return ((String) object).getBytes(UTF8);
}
@Override
public Object decode(byte[] bytes) {
return new String(bytes, UTF8);
}
/**
* Write a string to the given output stream.
*
* @param out
* Data output stream
* @param str
* String
*/
public static void writeString(DataOutputStream out, String str)
throws IOException {
byte[] bytes = str.getBytes(UTF8);
out.writeInt(bytes.length);
out.write(bytes);
}
/**
* Read a string from the given input stream.
*
* @param in
* Data input stream
* @return String
*/
public static String readString(DataInputStream in) throws IOException {
int length = in.readInt();
byte[] bytes = new byte[length];
in.read(bytes);
return new String(bytes, UTF8);
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.netpipe;
import java.io.IOException;
import java.net.InetAddress;
import java.nio.channels.SocketChannel;
import org.dnikulin.codon.net.SocketLink;
import org.dnikulin.codon.netpipe.packet.ChannelObjectReader;
import org.dnikulin.codon.netpipe.packet.ChannelObjectWriter;
import org.dnikulin.codon.netpipe.packet.ObjectListener;
public abstract class NetPipeLink implements SocketLink, ObjectListener {
protected final SocketChannel channel;
protected final ChannelObjectReader reader;
protected final ChannelObjectWriter writer;
protected boolean willSend;
protected boolean willReceive;
public NetPipeLink(SocketChannel channel) throws IOException {
this.channel = channel;
this.reader = new ChannelObjectReader(channel, new ObjectListener() {
@Override
public void takeObject(byte[] body) {
receivedObject(body);
}
});
this.writer = new ChannelObjectWriter(channel);
this.willSend = false;
this.willReceive = false;
}
@Override
public SocketChannel getChannel() {
return channel;
}
@Override
public synchronized void takeObject(byte[] body) {
if (willSend)
writer.takeObject(body);
}
@Override
public synchronized boolean wantsWrite() {
return writer.wantsWrite();
}
@Override
public synchronized void canWrite() throws IOException {
writer.flush();
}
@Override
public synchronized boolean wantsRead() {
return willReceive;
}
@Override
public synchronized void canRead() throws IOException {
reader.consume();
}
@Override
public synchronized void connectionMade(InetAddress address) {
System.err.println("Connected to " + address);
}
@Override
public synchronized void connectionLost() {
reader.reset();
writer.reset();
System.err.println("Disconnected");
}
protected abstract void receivedObject(byte[] body);
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.plugin;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.dnikulin.codon.log.LineLogger;
import org.dnikulin.codon.log.NullLogger;
/**
* A plugin slot and node registry. Supports automatic type-safe plugin
* installation.
*/
public class PluginLinker {
private final LineLogger logger;
private final List<PluginSlot> slots;
private final List<PluginNode> nodes;
private final Map<Integer, Set<Integer>> installed;
private final Set<String> nodeClasses;
/**
* Construct a PluginLinker with the given line logger.
*
* @param logger
* Line logger (may be null)
*/
public PluginLinker(LineLogger logger) {
this.logger = NullLogger.or(logger);
slots = new ArrayList<PluginSlot>();
nodes = new ArrayList<PluginNode>();
installed = new TreeMap<Integer, Set<Integer>>();
nodeClasses = new TreeSet<String>();
}
/**
* Construct a PluginLinker with no line logger.
*/
public PluginLinker() {
this(NullLogger.INSTANCE);
}
/**
* Query connected LineLogger.
*
* @return Connected LineLogger
*/
public LineLogger getLineLogger() {
return logger;
}
/**
* Register a plugin slot. This slot will receive compatible plugins.
*
* @param slot
* Plugin slot
*/
public synchronized boolean addPluginSlot(PluginSlot slot) {
if (slots.contains(slot))
return false;
int islot = slots.size();
slots.add(slot);
String name = slot.getPluginSlotName();
logger.print("Registered plugin slot '" + name + "'");
for (int inode = 0; inode < nodes.size(); inode++)
installAndRegister(islot, inode);
return true;
}
/**
* Return a copy of the plugin slot list. Changes to the returned list will
* not affect the internal slot list.
*
* @return Slot list copy
*/
public synchronized List<PluginSlot> getPluginSlots() {
return new ArrayList<PluginSlot>(slots);
}
/**
* Register a plugin node. This node may be installed into compatible slots.
*
* @param node
* Plugin node
*/
public synchronized boolean addPluginNode(PluginNode node) {
if (nodes.contains(node))
return false;
int inode = nodes.size();
nodeClasses.add(node.getClass().getName());
nodes.add(node);
String name = node.getPluginName();
logger.print("Registered plugin node '" + name + "'");
for (int islot = 0; islot < slots.size(); islot++)
installAndRegister(islot, inode);
return true;
}
/**
* Return a copy of the plugin node list. Changes to the returned list will
* not affect the internal node list.
*
* @return Node list copy
*/
public synchronized List<PluginNode> getPluginNodes() {
return new ArrayList<PluginNode>(nodes);
}
/**
* Check if the linker has registered at least one node of this precise
* class.
*
* @param klass
* Node class (exact, not superclass)
* @return true iff at least one node is registered with this exact class
*/
public synchronized boolean hasPluginNodeForClass(Class<?> klass) {
return nodeClasses.contains(klass.getName());
}
/**
* Instantiate and add any plugin node classes that have no added instances.
* Only classes that implement PluginNode will be used.
*
* @param classes
* Collection of candidate classes
*/
public synchronized void makePluginNodes(Collection<Class<?>> classes) {
for (Class<?> klass : classes) {
// Only consider PluginNode subclasses
if (!PluginNode.class.isAssignableFrom(klass))
continue;
// Cannot instantiate an interface
if (klass.isInterface())
continue;
// Cannot instantiate an abstract class
if (Modifier.isAbstract(klass.getModifiers()))
continue;
// Do not auto-add if an instance is already added
// (Whether or not it was added by this method!)
// This is the most expensive check so do it last
if (nodeClasses.contains(klass.getName()))
continue;
try {
Object nodeObject = klass.newInstance();
PluginNode node = (PluginNode) nodeObject;
boolean added = addPluginNode(node);
assert (added == true);
assert (nodeClasses.contains(klass.getName()));
} catch (Exception ex) {
String name = klass.getSimpleName();
String msg = ex.getLocalizedMessage();
logger.print("Failed to make " + name + ": " + msg);
}
}
}
// Package-private
synchronized boolean installAndRegister(int islot, int inode) {
PluginSlot slot = slots.get(islot);
PluginNode node = nodes.get(inode);
if (isCompatible(slot, node) == false)
return false;
Set<Integer> installedNodes = installed.get(islot);
if (installedNodes == null) {
installedNodes = new TreeSet<Integer>();
installed.put(islot, installedNodes);
} else if (installedNodes.contains(inode)) {
return false;
}
if (installPlugin(slot, node)) {
installedNodes.add(inode);
return true;
}
return false;
}
// Package-private
boolean installPlugin(PluginSlot slot, PluginNode node) {
String slotName = slot.getPluginSlotName();
String nodeName = node.getPluginName();
String combo = "'" + nodeName + "' into '" + slotName + "'";
try {
slot.installPlugin(node);
logger.print("Installed " + combo);
return true;
} catch (Exception ex) {
String msg = ex.getLocalizedMessage();
logger.print("Failed to install " + combo + ": " + msg);
return false;
}
}
/**
* Determine if a plugin slot is compatible with a plugin node.
*
* @param slot
* Plugin slot
* @param node
* Plugin node
* @return true if the slot and node are compatible
*/
public static boolean isCompatible(PluginSlot slot, PluginNode node) {
return slot.getPluginInterface().isAssignableFrom(node.getClass());
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.format.tools;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.dnikulin.codon.format.ObjectFormat;
import org.dnikulin.codon.format.except.ObjectCorruptException;
/** An ObjectFormat implemented using DataInputStream and DataOutputStream. */
public abstract class StreamObjectFormat<T> implements ObjectFormat {
@Override
@SuppressWarnings("unchecked")
public byte[] encode(Object object) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(bytes);
try {
write(out, (T) object);
out.flush();
return bytes.toByteArray();
} catch (IOException ex) {
return null;
}
}
@Override
public Object decode(byte[] bytes) throws ObjectCorruptException {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
DataInputStream in = new DataInputStream(bis);
try {
return read(in);
} catch (IOException ex) {
throw new ObjectCorruptException(ex);
}
}
/**
* Read an object from a data input stream.
*
* @param in
* Input stream
* @return Object
*/
public abstract T read(DataInputStream in) throws IOException,
ObjectCorruptException;
/**
* Write an object to a data output stream.
*
* @param out
* Output stream
* @param object
* Object
*/
public abstract void write(DataOutputStream out, T object)
throws IOException;
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.misc;
public class StatusToken<StatusEnum> {
private volatile StatusEnum current;
private volatile Exception exception;
public StatusToken(StatusEnum start) {
current = start;
exception = null;
}
public synchronized Exception waitForStatus(StatusEnum status) {
while (current != status) {
try {
wait();
} catch (Exception ignored) {
}
}
return exception;
}
public synchronized void setStatus(StatusEnum status, Exception ex) {
current = status;
exception = ex;
notifyAll();
}
public synchronized void setStatus(StatusEnum from, StatusEnum to,
Exception ex) {
if (current == from)
setStatus(to, ex);
}
public void setStatus(StatusEnum status) {
setStatus(status, (Exception) null);
}
public void setStatus(StatusEnum from, StatusEnum to) {
setStatus(from, to, (Exception) null);
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.net;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
import org.dnikulin.codon.misc.Cancellable;
import org.dnikulin.codon.misc.StatusToken;
import org.dnikulin.codon.net.util.ClientBind;
import org.dnikulin.codon.net.util.ConnectStatus;
import org.dnikulin.codon.net.util.HostBind;
import org.dnikulin.codon.net.util.ListenStatus;
public class SelectorThread implements Executor, Cancellable {
public static final int SOCKET_SIZE = 1024 * 32;
public final Selector selector;
private final AtomicBoolean running;
private final Queue<Runnable> queue;
private final Thread thread;
public SelectorThread(Selector selector) {
this.selector = selector;
this.running = new AtomicBoolean(true);
this.queue = new LinkedList<Runnable>();
this.thread = new Thread(new Runnable() {
@Override
public void run() {
runLoop();
}
}, "codon-selector");
this.thread.start();
}
public SelectorThread() throws IOException {
this(Selector.open());
}
@Override
public String toString() {
return selector.getClass().getName();
}
@Override
public void execute(Runnable runnable) {
synchronized (queue) {
queue.add(runnable);
}
selector.wakeup();
}
@Override
public void cancel() {
running.set(false);
}
public void listen(final int port, final LinkFactory factory,
final StatusToken<ListenStatus> status) {
execute(new Runnable() {
public void run() {
try {
ServerSocketChannel listener = ServerSocketChannel.open();
HostBind binding = new HostBind(factory, listener);
listener.configureBlocking(false);
listener.socket().bind(new InetSocketAddress(port));
register(listener, SelectionKey.OP_ACCEPT, binding);
status.setStatus(ListenStatus.LISTENING);
} catch (IOException ex) {
status.setStatus(ListenStatus.FAILED, ex);
}
}
});
status.setStatus(ListenStatus.CREATED, ListenStatus.SCHEDULED);
}
public void connect(final String host, final int port,
final SocketLink link, final StatusToken<ConnectStatus> status) {
execute(new Runnable() {
public void run() {
try {
SocketChannel channel = link.getChannel();
ClientBind binding = new ClientBind(link, status);
tuneChannel(channel);
register(channel, SelectionKey.OP_CONNECT, binding);
channel.connect(new InetSocketAddress(host, port));
status.setStatus(ConnectStatus.CONNECTING);
} catch (IOException ex) {
status.setStatus(ConnectStatus.FAILED, ex);
}
}
});
status.setStatus(ConnectStatus.CREATED, ConnectStatus.SCHEDULED);
}
public void updateKey(final SocketLink link) {
execute(new Runnable() {
public void run() {
try {
final int ops;
if (link.wantsWrite()) {
ops = SelectionKey.OP_WRITE;
System.err.println("setting " + link + " for write");
} else {
ops = SelectionKey.OP_READ;
System.err.println("setting " + link + " for read");
}
register(link.getChannel(), ops, link);
} catch (IOException ex) {
// link.exception(ex);
}
}
});
}
protected synchronized void register(SelectableChannel channel, int ops,
Object data) throws IOException {
if (channel.isOpen())
channel.register(selector, ops, data);
}
public static void tuneChannel(SocketChannel channel) throws IOException,
SocketException {
channel.configureBlocking(false);
Socket socket = channel.socket();
socket.setReceiveBufferSize(SOCKET_SIZE);
socket.setSendBufferSize(SOCKET_SIZE);
}
protected void runLoop() {
try {
while (running.get() == true) {
runQueue();
// Blocks here - may be interrupted
int selected = selector.select();
if (selected > 0)
handleKeys();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void runQueue() {
Runnable work;
while (true) {
synchronized (queue) {
work = queue.poll();
if (work == null)
return;
}
work.run();
}
}
private void handleKeys() {
Set<SelectionKey> selectedKeys = selector.selectedKeys();
for (SelectionKey key : selectedKeys) {
if (!key.isValid())
continue;
try {
handleKey(key);
} catch (IOException ex) {
try {
ex.printStackTrace();
key.channel().close();
key.cancel();
} catch (IOException ex2) {
// Ignored
}
}
}
selectedKeys.clear();
}
private void handleKey(SelectionKey key) throws IOException {
// Handle server socket ready to accept
if (key.isAcceptable()) {
HostBind binding = (HostBind) key.attachment();
SocketChannel channel = binding.channel.accept();
if (channel == null)
return;
SelectorThread.tuneChannel(channel);
SocketLink link = binding.factory.makeLink(channel);
link.connectionMade(channel.socket().getInetAddress());
updateKey(link);
return;
}
// Handle client socket ready to connect
if (key.isConnectable()) {
ClientBind binding = (ClientBind) key.attachment();
SocketLink link = binding.link;
SocketChannel channel = link.getChannel();
channel.finishConnect();
link.connectionMade(channel.socket().getInetAddress());
key.attach(link);
updateKey(link);
binding.status.setStatus(ConnectStatus.CONNECTED);
return;
}
// Handle socket ready to read
if (key.isReadable()) {
SocketLink link = (SocketLink) key.attachment();
link.canRead();
updateKey(link);
return;
}
// Handle socket ready to write
if (key.isWritable()) {
SocketLink link = (SocketLink) key.attachment();
link.canWrite();
updateKey(link);
return;
}
}
}
<file_sep>package org.dnikulin.codon;
import org.dnikulin.codon.pipe.except.PipeException;
import org.dnikulin.codon.plugin.PluginNode;
import org.dnikulin.codon.plugin.PluginSlot;
public class CodonKernelPluginSlot implements PluginSlot {
private final CodonKernel kernel;
public CodonKernelPluginSlot(CodonKernel kernel) {
this.kernel = kernel;
}
@Override
public String getPluginSlotName() {
return "Codon kernel";
}
@Override
public Class<? extends PluginNode> getPluginInterface() {
return CodonKernelPluginNode.class;
}
@Override
public void installPlugin(PluginNode plugin) {
try {
((CodonKernelPluginNode) plugin).addToCodonKernel(kernel);
} catch (PipeException ex) {
ex.printStackTrace();
}
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.commands.record;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.dnikulin.codon.daemon.Daemon;
import org.dnikulin.codon.daemon.thread.DaemonThreads;
import org.dnikulin.codon.format.ObjectFormat;
import org.dnikulin.codon.log.IndirectLogger;
import org.dnikulin.codon.log.LineLogger;
import org.dnikulin.codon.pipe.Consumer;
import org.dnikulin.codon.pipe.nulled.NullPipe;
import org.dnikulin.codon.pipe.record.ReplayDaemon;
/** A pipe that creates a replay daemon for every consumer added. */
public class ReplayDaemonPipe extends NullPipe {
private final DaemonThreads threads;
private final IndirectLogger log;
private final ObjectFormat format;
private final String path;
/**
* Construct a replay daemon pipe.
*
* @param threads
* Daemon thread registry
* @param log
* Line logger
* @param format
* Object format
* @param path
* File path
*/
public ReplayDaemonPipe(DaemonThreads threads, LineLogger log,
ObjectFormat format, String path) {
this.threads = threads;
this.log = new IndirectLogger(log);
this.format = format;
this.path = path;
}
@Override
public Class<?> getOutputType() {
return format.getObjectClass();
}
@Override
public boolean addConsumer(Consumer consumer) {
try {
InputStream input = new FileInputStream(path);
Daemon daemon = new ReplayDaemon(consumer, log, format, input, path);
threads.start(daemon);
return true;
} catch (IOException ex) {
log.print("Could not start replay: " + ex.getLocalizedMessage());
return false;
}
}
@Override
public LineLogger getLineLogger() {
return log.getLineLogger();
}
@Override
public void setLineLogger(LineLogger logger) {
this.log.setLineLogger(logger);
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.pipe.record;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import org.dnikulin.codon.daemon.Daemon;
import org.dnikulin.codon.daemon.except.DaemonException;
import org.dnikulin.codon.daemon.except.DaemonExitException;
import org.dnikulin.codon.format.ObjectFormat;
import org.dnikulin.codon.format.except.ObjectCorruptException;
import org.dnikulin.codon.log.LineLogger;
import org.dnikulin.codon.pipe.Consumer;
/** A daemon that reads objects recorded by RecordPipe. */
public class ReplayDaemon implements Daemon {
private final Consumer consumer;
private final LineLogger log;
private final ObjectFormat format;
private final String inputName;
private DataInputStream stream;
private boolean done;
/**
* Construct replay daemon.
*
* @param consumer
* Object consumer
* @param log
* Line logger
* @param format
* Object format
* @param input
* Input stream
* @param inputName
* Input stream name (filename, etc)
*/
public ReplayDaemon(Consumer consumer, LineLogger log, ObjectFormat format,
InputStream input, String inputName) throws IOException {
this.consumer = consumer;
this.log = log;
this.format = format;
this.inputName = inputName;
BufferedInputStream bis1 = new BufferedInputStream(input);
GZIPInputStream gis = new GZIPInputStream(bis1);
BufferedInputStream bis2 = new BufferedInputStream(gis);
this.stream = new DataInputStream(bis2);
this.done = false;
}
@Override
public String getDaemonName() {
return "Replay from " + inputName;
}
@Override
public synchronized void resumeDaemon() throws DaemonException {
if (done == true)
return;
try {
int size = stream.readInt();
byte[] bytes = new byte[size];
stream.read(bytes);
Object object = format.decode(bytes);
consumer.consume(object);
} catch (EOFException ex) {
done = true;
close();
log.print("Replay complete");
throw new DaemonExitException();
} catch (IOException ex) {
log.print("Replay error: " + ex.getLocalizedMessage());
close();
} catch (ObjectCorruptException ex) {
log.print("Replay ignoring corrupt object");
}
}
private synchronized void close() {
if (stream == null)
return;
try {
stream.close();
} catch (IOException ex) {
// Ignore
} finally {
stream = null;
}
}
@Override
public void cancel() {
close();
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.pipe.command.registry;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.dnikulin.codon.command.EffectCommand;
import org.dnikulin.codon.log.LineLogger;
import org.dnikulin.codon.log.NullLogger;
import org.dnikulin.codon.pipe.Pipe;
import org.dnikulin.codon.pipe.command.PipeCommand;
import org.dnikulin.codon.pipe.command.ProducerCommand;
import org.dnikulin.codon.pipe.command.wrap.EffectPipeCommand;
import org.dnikulin.codon.pipe.command.wrap.ProducerPipeCommand;
import org.dnikulin.codon.pipe.except.PipeException;
import org.dnikulin.codon.pipe.except.PipeFactoryException;
import org.dnikulin.codon.pipe.except.PipeNameInUseException;
import org.dnikulin.codon.pipe.except.PipeNameInvalidException;
import org.dnikulin.codon.pipe.except.PipeNotFoundException;
import org.dnikulin.codon.pipe.test.TestEffectCommand;
import org.dnikulin.codon.pipe.test.TestPipe;
import org.dnikulin.codon.pipe.test.TestPipeCommand;
import org.dnikulin.codon.pipe.test.TestProducerCommand;
import org.junit.Test;
public class PipeCommandsTest {
@Test
public void testPipeCommands() {
LineLogger log = NullLogger.INSTANCE;
PipeCommands commands = new PipeCommands();
PipeCommand cmd = TestPipeCommand.INSTANCE;
try {
// Must be able to register commands with their default names
commands.add(cmd);
assertSame(cmd, commands.get(cmd.getCommandName()));
} catch (PipeNameInvalidException ex) {
fail();
} catch (PipeNameInUseException ex) {
fail();
} catch (PipeNotFoundException ex) {
fail();
}
try {
// Must be able to register the same command with multiple names
commands.add("test1", cmd);
commands.add("test2", cmd);
commands.add("test3", cmd);
} catch (PipeNameInvalidException ex) {
fail();
} catch (PipeNameInUseException ex) {
fail();
}
try {
// Must forbid addition with invalid names
commands.add("7", cmd);
// Must not reach
fail();
} catch (PipeNameInvalidException ex) {
// Correct
} catch (PipeNameInUseException ex) {
fail();
}
try {
// Must forbid re-addition with same name
// (even using the same instance)
commands.add("test1", cmd);
// Must not reach
fail();
} catch (PipeNameInvalidException ex) {
fail();
} catch (PipeNameInUseException ex) {
// Correct
}
try {
// Must allow lookup for correct names
assertSame(cmd, commands.get("test1"));
assertSame(cmd, commands.get("test2"));
assertSame(cmd, commands.get("test3"));
} catch (PipeNotFoundException ex) {
fail();
}
try {
// Must throw for lookup with incorrect names
assertSame(cmd, commands.get("test4"));
// Must not reach
fail();
} catch (PipeNotFoundException ex) {
// Correct
}
try {
// Must allow construction for correct names and tokens
Pipe pipe = commands.makePipe("test1", new String[] {}, log);
assertNotNull(pipe);
assertTrue(pipe instanceof TestPipe);
assertSame(Object.class, pipe.getInputType());
assertSame(Object.class, pipe.getOutputType());
} catch (PipeNotFoundException ex) {
fail();
} catch (PipeFactoryException ex) {
fail();
}
try {
// Must propagate exceptions from commands
commands.makePipe("test1", new String[] { "org.NoClass" }, log);
// Must not reach
fail();
} catch (PipeNotFoundException ex) {
fail();
} catch (PipeFactoryException ex) {
// Correct
}
}
@Test
public void testEffectCommand() {
try {
PipeCommands commands = new PipeCommands();
EffectCommand cmd = TestEffectCommand.INSTANCE;
// Must add effect command as a pipe command
commands.add(cmd);
// Must use original command name
PipeCommand pcmd = commands.get(cmd.getCommandName());
assertNotSame(cmd, pcmd);
// Must use the EffectPipeCommand wrapper
assertTrue(pcmd instanceof EffectPipeCommand);
} catch (PipeException ex) {
fail();
}
}
@Test
public void testProducerCommand() {
try {
PipeCommands commands = new PipeCommands();
ProducerCommand cmd = TestProducerCommand.INSTANCE;
// Must add producer command as a pipe command
commands.add(cmd);
// Must use original command name
PipeCommand pcmd = commands.get(cmd.getCommandName());
assertNotSame(cmd, pcmd);
// Must use the ProducerPipeCommand wrapper
assertTrue(pcmd instanceof ProducerPipeCommand);
} catch (PipeException ex) {
fail();
}
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.pipe.compiler;
import java.util.ArrayList;
import java.util.List;
import org.dnikulin.codon.misc.ParserToken;
import org.dnikulin.codon.pipe.except.PipeException;
// Sample pipelines:
// cmd1 arg1 arg2 | cmd2 arg1 arg2
// ~pipe1 cmd1 arg1 arg2 | ~pipe2 cmd2 arg1 arg2
// cmd1 arg1 arg2 | ~pipe1
// ~pipe1 [ cmd1 arg1 arg2 | cmd2 arg1 arg2 ]
/** Parses a string definition of a pipeline. */
public class PipeShellParser {
public static final char QUOTE = '"';
public static final char BACKSLASH = '\\';
public static final char SPACE = ' ';
public static final char TAB = '\t';
public static final char SHARP = '#';
public static final char PIPENAME = '~';
public static final char LINK = '|';
public static final char GROUP_START = '[';
public static final char GROUP_END = ']';
private enum State {
WHITE, TOKEN, ESCAPED, QUOTED, QUOTED_ESCAPED, COMMENT, NAMING
}
private final PipeShellCompiler compiler;
private final ParserToken token;
private final List<String> tokens;
private State state;
private String command;
private final List<String> arguments;
/** Construct an initial parser. */
public PipeShellParser(PipeShellCompiler compiler) {
this.compiler = compiler;
token = new ParserToken();
tokens = new ArrayList<String>();
state = State.WHITE;
command = null;
arguments = new ArrayList<String>();
}
/**
* Query pipe compiler.
*
* @return Associated pipe compiler
*/
public PipeShellCompiler getCompiler() {
return compiler;
}
/** Reset parser state. */
public void reset() {
token.reset();
tokens.clear();
state = State.WHITE;
}
/** Parse an entire string. State is kept from previous parses. */
public void feed(String str) throws PipeException {
compiler.startCompile();
reset();
for (int i = 0; i < str.length(); i++)
feed(str.charAt(i));
feedEnd();
compiler.stopCompile();
}
/** Parse a single character. */
public void feed(char ch) throws PipeException {
switch (state) {
case COMMENT:
break;
case NAMING:
case TOKEN:
switch (ch) {
case SPACE:
case TAB:
storeToken();
state = State.WHITE;
break;
case BACKSLASH:
state = State.ESCAPED;
break;
case QUOTE:
state = State.QUOTED;
break;
case LINK:
endCommand();
compiler.takePipeLink();
state = State.WHITE;
break;
case GROUP_START:
endCommand();
compiler.takeGroupStart();
state = State.WHITE;
break;
case GROUP_END:
endCommand();
compiler.takeGroupEnd();
state = State.WHITE;
break;
default:
token.append(ch);
}
break;
case WHITE:
switch (ch) {
case SPACE:
case TAB:
break;
case BACKSLASH:
state = State.ESCAPED;
break;
case QUOTE:
state = State.QUOTED;
break;
case SHARP:
state = State.COMMENT;
break;
case LINK:
endCommand();
compiler.takePipeLink();
break;
case PIPENAME:
state = State.NAMING;
break;
case GROUP_START:
endCommand();
compiler.takeGroupStart();
break;
case GROUP_END:
endCommand();
compiler.takeGroupEnd();
break;
default:
state = State.TOKEN;
token.append(ch);
}
break;
case QUOTED:
switch (ch) {
case QUOTE:
state = State.TOKEN;
break;
case BACKSLASH:
state = State.QUOTED_ESCAPED;
break;
default:
token.append(ch);
}
break;
case QUOTED_ESCAPED:
token.append(ch);
state = State.QUOTED;
break;
case ESCAPED:
token.append(ch);
state = State.TOKEN;
break;
default:
assert (false);
}
}
/** Note the termination of a string. */
public void feedEnd() throws PipeException {
endCommand();
}
// Package-private
String[] getTokens() {
String[] out = new String[tokens.size()];
for (int i = 0; i < out.length; i++)
out[i] = tokens.get(i);
return out;
}
private void endCommand() throws PipeException {
try {
storeToken();
if (command != null) {
String[] ntokens = new String[arguments.size()];
for (int i = 0; i < ntokens.length; i++)
ntokens[i] = arguments.get(i);
compiler.takeCommand(command, ntokens);
}
} finally {
command = null;
arguments.clear();
}
}
private void storeToken() throws PipeException {
String ntoken = token.drain();
if (ntoken.isEmpty())
return;
tokens.add(ntoken);
switch (state) {
case NAMING:
compiler.takePipeName(ntoken);
break;
case TOKEN:
if (command == null)
command = ntoken;
else
arguments.add(ntoken);
break;
}
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.misc;
/** Utility class containing time-related methods. */
public final class TimeTools {
/**
* Suspend execution for at least a given time.
*
* @param millis
* Milliseconds to sleep for
*/
public static void sleepFor(long millis) {
long started = System.currentTimeMillis();
sleepUntil(started + millis, started);
}
/**
* Suspend execution until at least a given time, by the contract of
* System.currentTimeMillis()
*
* @param time
* Milliseconds to sleep until
*/
public static void sleepUntil(long time) {
sleepUntil(time, System.currentTimeMillis());
}
/**
* Suspend execution until at least a given time, assuming a specific
* current time, by the contract of System.currentTimeMillis()
*
* @param time
* Milliseconds to sleep until
* @param start
* Starting time
*/
public static void sleepUntil(long time, long start) {
long from = start;
while (true) {
long duration = time - from;
if (duration <= 0)
break;
try {
Thread.sleep(duration);
break;
} catch (InterruptedException ex) {
from = System.currentTimeMillis();
}
}
}
private TimeTools() {
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.daemon.thread;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.dnikulin.codon.daemon.Daemon;
import org.dnikulin.codon.daemon.except.DaemonAbortException;
import org.dnikulin.codon.daemon.except.DaemonExitException;
import org.dnikulin.codon.misc.Cancellable;
/** A single thread executing a single daemon. */
public class DaemonThread extends Thread implements Cancellable {
/** Daemon logic has not been started. */
public static final int WAITING = 0;
/** Daemon logic is executing normally. */
public static final int RUNNING = 1;
/** Daemon logic has completed normally. */
public static final int COMPLETED = 2;
/** Daemon thread or logic was aborted. */
public static final int ABORTED = 3;
/** Daemon logic threw an exception. */
public static final int ERROR = 4;
private final Daemon daemon;
private final int pid;
private final AtomicBoolean running;
private final AtomicInteger state;
/**
* Construct a daemon thread.
*
* @param daemon
* Daemon logic
* @param pid
* Process identifier
*/
public DaemonThread(Daemon daemon, int pid) {
super("codon-daemon-" + pid);
setDaemon(true);
this.daemon = daemon;
this.pid = pid;
this.running = new AtomicBoolean(true);
this.state = new AtomicInteger(WAITING);
}
/**
* Query daemon thread process identifier (PID).
*
* @return Daemon thread PID
*/
public int getPID() {
return pid;
}
/**
* Query daemon name.
*
* @return Daemon name
*/
public String getDaemonName() {
return daemon.getDaemonName();
}
/**
* Query daemon thread state.
*
* @return Daemon thread state
*/
public int getDaemonState() {
return state.get();
}
/**
* Query daemon termination state. A daemon is "running" if it has not
* exited, been aborted or thrown an error.
*
* @return true iff the daemon logic is waiting or running.
*/
public boolean isRunning() {
return running.get();
}
/**
* Abort the daemon thread. If the daemon logic has not yet completed, its
* state will be considered aborted.
*/
@Override
public void cancel() {
running.set(false);
}
/**
* Suspend execution of the current thread until the daemon thread has
* terminated in some way. Note that daemon logic may block indefinitely.
*/
public void waitForJoin() {
while (true) {
try {
join();
return;
} catch (InterruptedException ex) {
// Ignore
}
}
}
@Override
public void run() {
try {
// Only transition here once
if (state.compareAndSet(WAITING, RUNNING) == false)
return;
// Loop until cancel or exception
while (isRunning())
daemon.resumeDaemon();
// To reach here, must have been cancel()ed
daemon.cancel();
state.compareAndSet(RUNNING, ABORTED);
} catch (DaemonExitException ex) {
state.compareAndSet(RUNNING, COMPLETED);
} catch (DaemonAbortException ex) {
state.compareAndSet(RUNNING, ABORTED);
} catch (Exception ex) {
state.compareAndSet(RUNNING, ERROR);
} finally {
running.set(false);
}
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.commands.core;
import static org.dnikulin.codon.command.CommandTools.printUsage;
import java.io.File;
import org.dnikulin.codon.command.EffectCommand;
import org.dnikulin.codon.log.LineLogger;
import org.dnikulin.codon.plugin.PluginLinker;
import org.dnikulin.codon.plugin.PluginLoader;
/** Command to import and install plugins. */
public class PluginCommand implements EffectCommand {
private final PluginLinker linker;
private final PluginLoader loader;
/**
* Construct a plugin command with the given plugin linker and loader.
*
* @param linker
* Plugin Linker
* @param loader
* Plugin loader
*/
public PluginCommand(PluginLinker linker, PluginLoader loader) {
this.linker = linker;
this.loader = loader;
}
@Override
public void execute(String[] args, LineLogger log) {
if (args.length != 1) {
printUsage(log, this);
return;
}
String path = args[0];
File file = new File(path);
if (!file.exists()) {
log.print("Path '" + path + "' does not exist");
return;
}
// importTree performs importJar automatically
loader.importTree(file);
loader.givePluginLinkerNodes(linker);
}
@Override
public String getCommandTopic() {
return "core";
}
@Override
public String getCommandName() {
return "plugin";
}
@Override
public String getCommandUsage() {
return "<jar or directory>";
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.pipe.command.wrap;
import org.dnikulin.codon.command.EffectCommand;
import org.dnikulin.codon.log.LineLogger;
import org.dnikulin.codon.pipe.Pipe;
import org.dnikulin.codon.pipe.command.PipeCommand;
import org.dnikulin.codon.pipe.except.PipeFactoryException;
import org.dnikulin.codon.pipe.nulled.NullPipe;
/**
* A pipe command that allows an effect command to be executed as part of a
* pipeline.
*/
public class EffectPipeCommand implements PipeCommand, EffectCommand {
private final EffectCommand command;
/**
* Wrap an effect command in a pipe command.
*
* @param command
* Effect command
*/
public EffectPipeCommand(EffectCommand command) {
this.command = command;
}
@Override
public void execute(String[] args, LineLogger log) {
command.execute(args, log);
}
@Override
public Pipe makePipe(String[] args, LineLogger log)
throws PipeFactoryException {
command.execute(args, log);
return NullPipe.INSTANCE;
}
@Override
public String getCommandTopic() {
return command.getCommandTopic();
}
@Override
public String getCommandName() {
return command.getCommandName();
}
@Override
public String getCommandUsage() {
return command.getCommandUsage();
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.command;
import org.dnikulin.codon.log.LineLogger;
import org.dnikulin.codon.pipe.Pipe;
import org.dnikulin.codon.pipe.except.PipeFactoryException;
/** Utility methods for shell commands. */
public final class CommandTools {
/**
* Print command usage suggestion to a line logger.
*
* @param log
* Line logger
* @param cmd
* Command
*/
public static void printUsage(LineLogger log, Command cmd) {
String name = cmd.getCommandName();
String usage = cmd.getCommandUsage();
log.print("Usage: " + name + " " + usage);
}
/**
* Print command usage suggestion to a line logger, and throw a
* PipeFactoryException.
*
* @param log
* Line logger
* @param cmd
* Command
*/
public static Pipe printPipeUsage(LineLogger log, Command cmd)
throws PipeFactoryException {
printUsage(log, cmd);
throw new PipeFactoryException("Pipe command arguments invalid");
}
private CommandTools() {
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.pipe.compiler;
import static org.dnikulin.codon.pipe.compiler.EarlyPipeShellCompilerTest.makeTestCommands;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.List;
import org.dnikulin.codon.pipe.Pipe;
import org.dnikulin.codon.pipe.command.registry.PipeCommands;
import org.dnikulin.codon.pipe.except.PipeException;
import org.dnikulin.codon.pipe.except.PipeNotFoundException;
import org.dnikulin.codon.pipe.simple.CompoundPipe;
import org.dnikulin.codon.pipe.test.TestPipe;
import org.junit.Test;
public class PipeShellParserTest {
@Test
public void testBlankString() {
assertParse("");
assertParse(" \t ");
}
@Test
public void testSimpleTokens() {
assertParse("foo", "foo");
}
@Test
public void testPaddedTokens() {
assertParse(" foo \t", "foo");
assertParse(" foo bar \t", "foo", "bar");
}
@Test
public void testEscapedTokens() {
assertParse("\\");
assertParse("\\ ", " ");
assertParse("\\\\", "\\");
assertParse(" foo\\ ba\\r \\\\ ", "foo ", "bar", "\\");
}
@Test
public void testQuotedTokens() {
assertParse("\"foo\"", "foo");
assertParse(" \"foo bar\" ", "foo bar");
assertParse("\"foo \\\" bar\"", "foo \" bar");
assertParse("\"foo \\\\ bar\"", "foo \\ bar");
// Test unterminated quotation as well
assertParse("\"foo \\\\ bar ", "foo \\ bar ");
assertParse("\"foo \\\\ bar \\", "foo \\ bar ");
}
@Test
public void testComment() {
// Comments must start with ' #' or '\t#'
assertParse("foo bar # ignore rest", "foo", "bar");
assertParse("\"foo bar\"\t# ignore rest", "foo bar");
// If following token, quote or escape, not a comment
assertParse("foo bar# baz", "foo", "bar#", "baz");
assertParse(" \"foo bar\"# baz ", "foo bar#", "baz");
assertParse("foo \\# bar", "foo", "#", "bar");
}
@Test
public void testCompile() {
try {
// Must not register any pipes
PipeLinker linker = compile("test");
assertTrue(linker.getPipeNames().isEmpty());
// Must name a single pipe
compile("~pipe1 test java.lang.String java.util.List", linker);
assertEquals(1, linker.getPipeNames().size());
Pipe pipe1 = linker.getPipe("pipe1");
assertTrue(pipe1 instanceof TestPipe);
assertFalse(pipe1.hasConsumer());
assertSame(String.class, pipe1.getInputType());
assertSame(List.class, pipe1.getOutputType());
// Must refer to a single pipe and name a new pipe
compile("~pipe1 | ~pipe2 test", linker);
// Must have linked pipe1 to pipe2
assertTrue(pipe1.hasConsumer());
Pipe pipe2 = linker.getPipe("pipe2");
assertTrue(pipe2 instanceof TestPipe);
assertNotSame(pipe1, pipe2);
assertFalse(pipe2.hasConsumer());
assertSame(Object.class, pipe2.getInputType());
assertSame(Object.class, pipe2.getOutputType());
// Must connect a new anonymous pipe
compile("~pipe2 | test", linker);
assertTrue(pipe2.hasConsumer());
// Must create a named group
compile("~pipe3[test | test | test]", linker);
Pipe pipe3 = linker.getPipe("pipe3");
assertTrue(pipe3 instanceof CompoundPipe);
assertFalse(pipe3.hasConsumer());
// Must created a nested named group
compile("test [ ~pipe4 [ test | test", linker);
Pipe pipe4 = linker.getPipe("pipe4");
assertTrue(pipe4 instanceof CompoundPipe);
assertFalse(pipe4.hasConsumer());
// Must created a nested named group containing a back reference
compile("test [ ~pipe5 [ test | ~pipe4", linker);
Pipe pipe5 = linker.getPipe("pipe5");
assertTrue(pipe5 instanceof CompoundPipe);
assertFalse(pipe5.hasConsumer());
// Must support comments after pipelines
compile("test # A test pipe");
// Must support comment-only lines
compile("# Comment");
} catch (PipeNotFoundException ex) {
ex.printStackTrace();
fail();
}
}
public static PipeLinker compile(String line, PipeLinker linker) {
try {
PipeCommands commands = makeTestCommands();
PipeShellCompiler compiler = new EarlyPipeShellCompiler(commands,
linker);
PipeShellParser parser = new PipeShellParser(compiler);
parser.feed(line);
return linker;
} catch (PipeException ex) {
ex.printStackTrace();
fail();
return null;
}
}
public static PipeLinker compile(String line) {
return compile(line, new PipeLinker());
}
/**
* Assert that a parse results in the tokens expected.
*
* @param line
* Line to parse
* @param expect
* Tokens expected
*/
public static void assertParse(String line, String... expect) {
String[] result = parse(line);
assertEquals(expect.length, result.length);
assertArrayEquals(expect, result);
}
/**
* Return the tokens parsed from a string.
*
* @param line
* String to parse
* @return Tokens parsed
*/
public static String[] parse(String line) {
try {
PipeShellCompiler compiler = NullPipeShellCompiler.INSTANCE;
PipeShellParser parser = new PipeShellParser(compiler);
// Must start with no tokens
assertEquals(0, parser.getTokens().length);
parser.feed(line);
return parser.getTokens();
} catch (PipeException ex) {
fail();
return new String[] {};
}
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.commands.core;
import static org.dnikulin.codon.command.CommandTools.printUsage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import org.dnikulin.codon.command.EffectCommand;
import org.dnikulin.codon.log.LineLogger;
import org.dnikulin.codon.pipe.compiler.PipeShellParser;
import org.dnikulin.codon.pipe.except.PipeException;
/** Command to execute all commands in a batch script. */
public class BatchCommand implements EffectCommand {
private final PipeShellParser parser;
/**
* Construct a batch command to feed the given parser.
*
* @param parser
* Parser to feed commands
*/
public BatchCommand(PipeShellParser parser) {
this.parser = parser;
}
@Override
public void execute(String[] args, LineLogger log) {
if (args.length != 1) {
printUsage(log, this);
return;
}
String path = args[0];
File file = new File(path);
if (!file.exists()) {
log.print("Path '" + path + "' does not exist");
return;
}
try {
runFile(file, log);
} catch (IOException ex) {
log.print("Could not read batch file: " + ex.getLocalizedMessage());
}
}
/**
* Execute all commands in the given batch script file.
*
* @param file
* Batch script file
* @param log
* Line logger
*/
public void runFile(File file, LineLogger log) throws IOException {
BufferedReader in = new BufferedReader(new FileReader(file));
try {
String line;
while ((line = in.readLine()) != null)
runCommand(line, log);
} finally {
in.close();
}
}
/**
* Execute a single command.
*
* @param line
* Command line
* @param log
* Line logger
*/
public void runCommand(String line, LineLogger log) {
log.print("\n> " + line);
try {
parser.feed(line);
} catch (PipeException ex) {
log.print("Error: " + ex.getLocalizedMessage());
}
}
@Override
public String getCommandTopic() {
return "core";
}
@Override
public String getCommandName() {
return "batch";
}
@Override
public String getCommandUsage() {
return "<batch script path>";
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.pipe.command.wrap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import org.dnikulin.codon.log.CountingLogger;
import org.dnikulin.codon.pipe.Pipe;
import org.dnikulin.codon.pipe.command.ProducerCommand;
import org.dnikulin.codon.pipe.except.PipeFactoryException;
import org.dnikulin.codon.pipe.test.TestPipe;
import org.dnikulin.codon.pipe.test.TestProducerCommand;
import org.junit.Test;
public class ProducerPipeCommandTest {
@Test
public void testProducerCommand() {
ProducerCommand cmd = TestProducerCommand.INSTANCE;
ProducerPipeCommand pcmd = new ProducerPipeCommand(cmd);
// Must retain output type
assertSame(cmd.getOutputType(), pcmd.getOutputType());
for (int i = 0; i < 5; i++) {
String[] args = new String[i];
for (int j = 0; j < i; j++)
args[j] = "test-" + j;
try {
CountingLogger log = new CountingLogger();
TestPipe tpipe = new TestPipe();
// Must produce pipe silently
Pipe pipe = pcmd.makePipe(args, log);
assertEquals(0, log.count());
// Pipe must have correct output type
assertSame(cmd.getOutputType(), pipe.getOutputType());
for (int j = 1; j <= 5; j++) {
pipe.addConsumer(tpipe);
// Must log once per consumer add
assertEquals(j, log.count());
// Must produce each argument once
assertEquals(j * i, tpipe.count());
Object last = tpipe.last();
if (last != null)
assertSame(String.class, last.getClass());
}
} catch (PipeFactoryException ex) {
fail();
}
}
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.pipe.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.dnikulin.codon.log.CountingLogger;
import org.dnikulin.codon.log.NullLogger;
import org.dnikulin.codon.pipe.Consumer;
import org.dnikulin.codon.pipe.Pipe;
import org.dnikulin.codon.pipe.Producer;
import org.junit.Test;
public class TestPipeTest {
@Test
public void testConstructor() {
// Default constructor must assign Object as both types
TestPipe defpipe = new TestPipe();
assertSame(Object.class, defpipe.getInputType());
assertSame(Object.class, defpipe.getOutputType());
// Specific constructor must assign given types
TestPipe pipe = new TestPipe(String.class, List.class);
assertSame(String.class, pipe.getInputType());
assertSame(List.class, pipe.getOutputType());
// Must construct with null logger and no consumers
assertFalse(pipe.hasConsumer());
assertSame(NullLogger.INSTANCE, pipe.getLineLogger());
// Must construct with count at 0, no saved value, not passing
assertEquals(0, pipe.count());
assertSame(null, pipe.last());
assertFalse(pipe.passes());
}
@Test
public void testConsumeRecord() {
TestPipe pipe = new TestPipe();
// Must construct with count at 0, no saved value, not passing
assertEquals(0, pipe.count());
assertSame(null, pipe.last());
// Must increment count on every consume()
pipe.consume(pipe);
assertEquals(1, pipe.count());
pipe.consume(pipe);
assertEquals(2, pipe.count());
// Must reset count to specific value
pipe.resetCount(7);
assertEquals(7, pipe.count());
pipe.consume(pipe);
assertEquals(8, pipe.count());
// Must reset count to 0
pipe.reset();
assertEquals(0, pipe.count());
// Must save value
assertSame(pipe, pipe.last());
}
@Test
public void testConnection() {
TestPipe pipe1 = new TestPipe(Object.class, Pipe.class);
CountingLogger log1 = new CountingLogger();
pipe1.setLineLogger(log1);
assertEquals(0, log1.count());
TestPipe pipe2A = new TestPipe(Pipe.class, Pipe.class);
CountingLogger log2A = new CountingLogger();
pipe2A.setLineLogger(log2A);
assertEquals(0, log2A.count());
TestPipe pipe2B = new TestPipe(Consumer.class, Producer.class);
CountingLogger log2B = new CountingLogger();
pipe2B.setLineLogger(log2B);
assertEquals(0, log2B.count());
TestPipe pipe3 = new TestPipe(Pipe.class, Object.class);
CountingLogger log3 = new CountingLogger();
pipe3.setLineLogger(log3);
assertEquals(0, log3.count());
// Must connect for identical type (Pipe)
assertTrue(pipe1.addConsumer(pipe2A));
assertTrue(pipe1.hasConsumer());
assertTrue(pipe2A.addConsumer(pipe3));
assertTrue(pipe2A.hasConsumer());
// Must connect for supertype (Pipe to Consumer)
assertTrue(pipe1.addConsumer(pipe2B));
// Must not connect for subtype (Producer to Pipe)
assertFalse(pipe2B.addConsumer(pipe3));
assertFalse(pipe2B.hasConsumer());
// Must not re-connect old connections
assertFalse(pipe1.addConsumer(pipe2A));
assertFalse(pipe2A.addConsumer(pipe3));
assertFalse(pipe1.addConsumer(pipe2B));
// Must not log anything yet
assertEquals(0, log1.count());
assertEquals(0, log2A.count());
assertEquals(0, log2B.count());
assertEquals(0, log3.count());
// Must not pass values by default
pipe1.consume(pipe1);
assertEquals(1, pipe1.count());
assertEquals(0, pipe2A.count());
assertEquals(0, pipe2B.count());
assertEquals(0, pipe3.count());
// Must pass values when configured to
pipe1.setPass(true);
pipe1.consume(pipe1);
assertEquals(2, pipe1.count());
assertEquals(1, pipe2A.count());
assertEquals(1, pipe2B.count());
assertEquals(0, pipe3.count());
assertSame(pipe1, pipe2A.last());
assertSame(pipe1, pipe2B.last());
// Must pass values when configured to
pipe2A.setPass(true);
pipe2B.setPass(true);
pipe1.consume(pipe1);
assertEquals(3, pipe1.count());
assertEquals(2, pipe2A.count());
assertEquals(2, pipe2B.count());
assertEquals(1, pipe3.count()); // From 2A but not 2B
assertSame(pipe1, pipe3.last());
// Must be able to disconnect consumers (specific or all)
pipe1.removeConsumers();
pipe2A.removeConsumer(pipe3);
assertFalse(pipe1.hasConsumer());
assertFalse(pipe2A.hasConsumer());
assertFalse(pipe2B.hasConsumer());
assertFalse(pipe3.hasConsumer());
// Must not pass when disconnected
pipe1.consume(pipe1);
assertEquals(4, pipe1.count());
assertEquals(2, pipe2A.count());
assertEquals(2, pipe2B.count());
assertEquals(1, pipe3.count());
assertSame(pipe1, pipe3.last());
// Must log for each pass only
// +1 for these pipes because they started without passing
assertEquals(pipe1.count(), log1.count() + 1);
assertEquals(pipe2A.count(), log2A.count() + 1);
assertEquals(pipe2B.count(), log2B.count() + 1);
assertEquals(0, log3.count());
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.format.tools;
import static org.dnikulin.codon.format.PrimitiveFormatsTest.testFormat;
import java.util.LinkedList;
import java.util.List;
import org.dnikulin.codon.format.ObjectFormat;
import org.dnikulin.codon.format.primitive.StringObjectFormat;
import org.junit.Test;
public class ListObjectFormatTest {
private static final ObjectFormat efmt = StringObjectFormat.INSTANCE;
private static final ObjectFormat lfmt = new ListObjectFormat(efmt);
@Test
public void testEmptyList() {
testFormat(lfmt, new LinkedList<Object>());
}
@Test
public void testOneString() {
List<String> list = new LinkedList<String>();
list.add("1232s сдфadrde");
testFormat(lfmt, list);
}
@Test
public void testMultipleStrings() {
List<String> list = new LinkedList<String>();
list.add("");
list.add("test");
list.add("1232s сдфadrde");
testFormat(lfmt, list);
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.format;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Arrays;
import org.dnikulin.codon.format.except.ObjectFormatException;
import org.dnikulin.codon.format.primitive.DoubleObjectFormat;
import org.dnikulin.codon.format.primitive.FloatObjectFormat;
import org.dnikulin.codon.format.primitive.IntegerObjectFormat;
import org.dnikulin.codon.format.primitive.LongObjectFormat;
import org.dnikulin.codon.format.primitive.StringObjectFormat;
import org.junit.Test;
public class PrimitiveFormatsTest {
@Test
public void testString() {
testFormat(StringObjectFormat.INSTANCE, "", "test", "1232s сдфadrde");
}
@Test
public void testInteger() {
testFormat(IntegerObjectFormat.INSTANCE, -7, 0, 7, Integer.MIN_VALUE,
Integer.MAX_VALUE);
}
@Test
public void testLong() {
testFormat(LongObjectFormat.INSTANCE, -7L, 0L, 7L, Long.MIN_VALUE,
Long.MAX_VALUE);
}
@Test
public void testFloat() {
testFormat(FloatObjectFormat.INSTANCE, 0.f, Float.NaN, Float.MIN_VALUE,
Float.MAX_VALUE, Float.NEGATIVE_INFINITY,
Float.POSITIVE_INFINITY);
}
@Test
public void testDouble() {
testFormat(DoubleObjectFormat.INSTANCE, 0., Double.NaN,
Double.MIN_VALUE, Double.MAX_VALUE, Double.NEGATIVE_INFINITY,
Double.POSITIVE_INFINITY);
}
public static void testFormat(ObjectFormat format, Object... objects) {
// Test must be called with non-null format
assertNotNull(format);
// Test must be called with at least one object
assertTrue(objects.length > 0);
// Must have non-null non-empty name string
String name = format.getFormatName();
assertNotNull(name);
assertFalse(name.isEmpty());
// Must have non-null object class
Class<?> klass = format.getObjectClass();
assertNotNull(klass);
try {
for (Object object : objects) {
// Test must be called with non-null objects of the correct type
assertNotNull(object);
assertTrue(klass.isAssignableFrom(object.getClass()));
// Object must have consistent equals()
assertEquals(object, object);
// Must encode to non-null bytes without errors
// Empty array is fine
byte[] bytes = format.encode(object);
assertNotNull(bytes);
// Must decode to non-null object without errors
// Object must equal original object
// (as defined by the object class)
// May return same reference, assuming state is immutable
Object object2 = format.decode(bytes);
assertNotNull(object2);
assertEquals(object, object2);
// Decoded object must encode to the SAME non-null bytes,
// but NOT the same reference, as it may be modified
byte[] bytes2 = format.encode(object2);
assertNotNull(bytes2);
assertNotSame(bytes, bytes2);
assertEquals(bytes.length, bytes2.length);
assertTrue(Arrays.equals(bytes, bytes2));
// Subsequent encodings must still be identical,
// but NOT the same reference, as it may be modified
byte[] bytes3 = format.encode(object2);
assertNotNull(bytes3);
assertNotSame(bytes, bytes3);
assertNotSame(bytes2, bytes3);
assertEquals(bytes.length, bytes3.length);
assertTrue(Arrays.equals(bytes, bytes3));
assertTrue(Arrays.equals(bytes2, bytes3));
}
} catch (ObjectFormatException ex) {
fail();
}
}
}
<file_sep>// Copyright (c) 2009 <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.dnikulin.codon.plugin;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import org.dnikulin.codon.log.LineLogger;
import org.dnikulin.codon.log.NullLogger;
/**
* A ClassLoader which imports from files and archives, combining many dynamic
* paths into one tree.
*/
public class PluginLoader extends ClassLoader {
public static final String NODE_SUFFIX = "PluginNode";
private final LineLogger logger;
private final byte[] streamBuffer;
private final Map<String, byte[]> bytes;
private final Map<String, Class<?>> classes;
/**
* Construct a PluginLoader with the given parent loader and line logger.
*
* @param parent
* Parent ClassLoader
*
* @param logger
* Line logger (may be null)
*/
public PluginLoader(ClassLoader parent, LineLogger logger) {
super(parent);
this.logger = NullLogger.or(logger);
streamBuffer = new byte[8192];
bytes = new HashMap<String, byte[]>();
classes = new HashMap<String, Class<?>>();
}
/**
* Construct a PluginLoader with the given parent ClassLoader and no line
* logger.
*
* @param parent
* Parent class loader
*/
public PluginLoader(ClassLoader parent) {
this(parent, NullLogger.INSTANCE);
}
/**
* Construct a PluginLoader with the default parent ClassLoader and the
* given line logger.
*
* @param logger
* Line logger (may be null)
*/
public PluginLoader(LineLogger logger) {
this(getSystemClassLoader(), logger);
}
/**
* Construct a PluginLoader with the default parent ClassLoader and no line
* logger.
*/
public PluginLoader() {
this(getSystemClassLoader(), NullLogger.INSTANCE);
}
/**
* Query connected LineLogger.
*
* @return Connected LineLogger
*/
public LineLogger getLineLogger() {
return logger;
}
/**
* Load a class from stored bytes or parent loader.
*
* @param className
* Name of class to load
* @param resolve
* Resolve class or not
* @return Loaded class
*/
@Override
public synchronized Class<?> loadClass(String className, boolean resolve)
throws ClassNotFoundException {
// Check for class in parent class loader first
try {
Class<?> klass = getParent().loadClass(className);
assert (klass != null);
classes.put(className, klass);
return klass;
} catch (ClassNotFoundException ex) {
// Continue
}
// Check for cached class
Class<?> klass = classes.get(className);
if (klass != null)
return klass;
// Check for class for which bytes are available
byte[] classBytes = bytes.get(classToPath(className));
if (classBytes == null) {
String msg = "Class " + className + " not found in bytes or parent";
logger.print(msg);
throw new ClassNotFoundException(msg);
}
try {
// Bytes found, interpret as class
klass = defineClass(className, classBytes, 0, classBytes.length);
assert (klass != null);
// Resolve if asked
if (resolve)
resolveClass(klass);
classes.put(className, klass);
return klass;
} catch (ClassFormatError ex) {
logger.print(ex.getLocalizedMessage());
throw ex;
}
}
/**
* Attempt to load classes from all matching .class resources available.
*
* @param suffix
* Class name suffix (e.g. PluginNode to match MyPluginNode and
* YourPluginNode), empty string for all classes
*/
public synchronized void loadClasses(String suffix) {
String suffixDotClass = suffix + ".class";
for (String path : bytes.keySet()) {
if (!path.endsWith(suffixDotClass))
continue;
String className = pathToClass(path);
if (classes.containsKey(className))
continue;
try {
byte[] classBytes = bytes.get(path);
assert (classBytes != null);
Class<?> klass = defineClass(className, classBytes, 0,
classBytes.length);
assert (klass != null);
resolveClass(klass);
classes.put(className, klass);
} catch (NoClassDefFoundError er) {
// Dependency not found, ignore
} catch (ClassFormatError ex) {
// Corrupted class file, ignore
}
}
}
/**
* Produce a list of all loaded classes, i.e. those for which loadClass()
* was called.
*
* @return List of loaded classes
*/
public List<Class<?>> getLoadedClasses() {
return new ArrayList<Class<?>>(classes.values());
}
/**
* Import a resource from an InputStream.
*
* @param stream
* Input stream to read
* @param path
* Original resource path
*/
public synchronized void importStream(InputStream stream, String path)
throws IOException {
bytes.put(path, readStream(stream));
}
/**
* Import a resource from a file.
*
* @param file
* File to read
* @param pathHead
* Leading relative path elements (e.g. "org/test/")
*/
public void importFile(File file, String pathHead) throws IOException {
FileInputStream fis = new FileInputStream(file);
try {
BufferedInputStream bis = new BufferedInputStream(fis);
importStream(bis, pathHead + file.getName());
bis.close();
} finally {
fis.close();
}
}
/**
* Import all resources in a Jar.
*
* @param file
* jar file
*/
public void importJar(File file) throws IOException {
BufferedInputStream buffer = null;
JarInputStream stream = null;
try {
buffer = new BufferedInputStream(new FileInputStream(file));
stream = new JarInputStream(buffer);
JarEntry entry = null;
while ((entry = stream.getNextJarEntry()) != null) {
if (entry.isDirectory())
continue;
importStream(stream, entry.getName());
}
} finally {
if (stream != null)
stream.close();
if (buffer != null)
buffer.close();
}
}
/**
* Import all files in a tree (starting with a single file or directory)
* recursively with a given prefix. Jar files have their contents imported
* as well. Can be called for a package sub-hierarchy to restore correct
* package path.
*
* @param root
* Directory tree root
* @param head
* Prefix of resource names
*/
public synchronized void importTree(File root, String head) {
try {
if (root.isDirectory()) {
for (File child : root.listFiles()) {
if (child.isDirectory()) {
importTree(child, head + child.getName() + "/");
} else {
importTree(child, head);
}
}
} else if (root.isFile() && root.canRead()) {
if (root.getName().endsWith(".jar"))
importJar(root);
// Keep the jar just in case
importFile(root, head);
}
} catch (IOException ex) {
// Ignore exception
}
}
/**
* Import all files in a tree (starting with a single file or directory)
* recursively. For classes, the root should be directly above the first
* package element.
*
* @param root
* Directory tree root
*/
public void importTree(File root) {
importTree(root, "");
}
/**
* Load all classes with names ending in PluginNode, and submit <i>all</i>
* loaded classes to linker's makePluginNodes().
*
* @param linker
* Plugin linker
*/
public void givePluginLinkerNodes(PluginLinker linker) {
// Load only classes with the node suffix name
loadClasses(NODE_SUFFIX);
// Give linker all classes for node construction
// Use copy of list since installations may modify the original
linker.makePluginNodes(getLoadedClasses());
}
// Package-private
synchronized byte[] getBytes(String path) {
return bytes.get(path);
}
// Package-private
synchronized byte[] readStream(InputStream stream) throws IOException {
ByteArrayOutputStream nbytes = new ByteArrayOutputStream();
int didread = 0;
while ((didread = stream.read(streamBuffer)) > 0)
nbytes.write(streamBuffer, 0, didread);
nbytes.close();
return nbytes.toByteArray();
}
/**
* Converts a class path such as org.test.Test to org/test/Test.class
*
* @param className
* Class name to convert
* @return Resource path
*/
public static String classToPath(String className) {
return className.replace('.', '/') + ".class";
}
/**
* Converts a resource path such as org/test/Test.class to org.test.Test
*
* @param path
* Resource path to convert
* @return Class name
*/
public static String pathToClass(String path) {
assert (path.endsWith(".class"));
return path.substring(0, path.length() - 6).replace('/', '.');
}
}
|
fc31835c34f72a5d73a17b0836a7d1d2954d4048
|
[
"Java",
"Ant Build System"
] | 38 |
Ant Build System
|
dnikulin/codon
|
13479a6806508f35563070e2ee08e41b3c5f1a82
|
6d96788f8f5100ef64b21a629928be543b9c8ab0
|
refs/heads/master
|
<file_sep>import { expect } from "chai";
import "mocha";
import * as moment from 'moment';
import * as uuid from 'uuid';
import { SeriesRepository } from "./series";
describe("SeriesRepository", () => {
describe("getData", () => {
it("should return data with greater timestamp", async () => {
const timestamp = new Date();
const seriesRepository: SeriesRepository = new SeriesRepository('mongodb://localhost:27017/open-stats-testdb', null);
const randomId = uuid.v4();
await seriesRepository.saveData(`simple.data-${randomId}`, 10, moment(timestamp).subtract(4, 'minute').toDate().getTime(), 'token', {});
await seriesRepository.saveData(`simple.data-${randomId}`, 15, moment(timestamp).subtract(3, 'minute').toDate().getTime(), 'token', {});
await seriesRepository.saveData(`simple.data-${randomId}`, 20, moment(timestamp).subtract(2, 'minute').toDate().getTime(), 'token', {});
await seriesRepository.saveData(`simple.data-${randomId}`, 25, moment(timestamp).subtract(1, 'minute').toDate().getTime(), 'token', {});
const result = await seriesRepository.getData(`simple.data-${randomId}`, moment(timestamp).subtract(5, 'minute').toDate().getTime(), 'token', {});
expect(result.length).to.be.eq(4);
});
it("should return no data given other token", async () => {
const timestamp = new Date();
const seriesRepository: SeriesRepository = new SeriesRepository('mongodb://localhost:27017/open-stats-testdb', null);
const randomId = uuid.v4();
await seriesRepository.saveData(`simple.data-${randomId}`, 25, moment(timestamp).subtract(1, 'minute').toDate().getTime(), 'token', {});
const result = await seriesRepository.getData(`simple.data-${randomId}`, moment(timestamp).subtract(2, 'minute').toDate().getTime(), 'other-token', {});
expect(result.length).to.be.eq(0);
});
it("should return no data given other name", async () => {
const timestamp = new Date();
const seriesRepository: SeriesRepository = new SeriesRepository('mongodb://localhost:27017/open-stats-testdb', null);
const randomId = uuid.v4();
await seriesRepository.saveData(`simple.data-${randomId}`, 25, moment(timestamp).subtract(1, 'minute').toDate().getTime(), 'token', {});
const result = await seriesRepository.getData(`other.simple.data-${randomId}`, moment(timestamp).subtract(2, 'minute').toDate().getTime(), 'token', {});
expect(result.length).to.be.eq(0);
});
it("should return data given tag", async () => {
const timestamp = new Date();
const seriesRepository: SeriesRepository = new SeriesRepository('mongodb://localhost:27017/open-stats-testdb', null);
const randomId = uuid.v4();
await seriesRepository.saveData(`simple.data-${randomId}`, 25, moment(timestamp).subtract(1, 'minute').toDate().getTime(), 'token', {
hostname: 'my-hostname',
});
const result = await seriesRepository.getData(`simple.data-${randomId}`, moment(timestamp).subtract(2, 'minute').toDate().getTime(), 'token', {
hostname: 'my-hostname',
});
expect(result.length).to.be.eq(1);
});
it("should return data given parital tag match", async () => {
const timestamp = new Date();
const seriesRepository: SeriesRepository = new SeriesRepository('mongodb://localhost:27017/open-stats-testdb', null);
const randomId = uuid.v4();
await seriesRepository.saveData(`simple.data-${randomId}`, 25, moment(timestamp).subtract(1, 'minute').toDate().getTime(), 'token', {
environment: 'live',
hostname: 'my-hostname-1',
});
await seriesRepository.saveData(`simple.data-${randomId}`, 25, moment(timestamp).subtract(1, 'minute').toDate().getTime(), 'token', {
environment: 'live',
hostname: 'my-hostname-2',
});
const result = await seriesRepository.getData(`simple.data-${randomId}`, moment(timestamp).subtract(2, 'minute').toDate().getTime(), 'token', {
environment: 'live',
});
expect(result.length).to.be.eq(2);
});
it("should return no data given other tag", async () => {
const timestamp = new Date();
const seriesRepository: SeriesRepository = new SeriesRepository('mongodb://localhost:27017/open-stats-testdb', null);
const randomId = uuid.v4();
await seriesRepository.saveData(`simple.data-${randomId}`, 25, moment(timestamp).subtract(1, 'minute').toDate().getTime(), 'token', {
hostname: 'my-hostname',
});
const result = await seriesRepository.getData(`simple.data-${randomId}`, moment(timestamp).subtract(2, 'minute').toDate().getTime(), 'token', {
hostname: 'my-other-hostname',
});
expect(result.length).to.be.eq(0);
});
});
describe("getAggregatedData", () => {
it("should return data with greater timestamp", async () => {
const timestamp = new Date(2017, 1, 1, 13, 40, 0);
const seriesRepository: SeriesRepository = new SeriesRepository('mongodb://localhost:27017/open-stats-testdb', null);
const randomId = uuid.v4();
await seriesRepository.saveData(`simple.data-${randomId}`, 6, moment(timestamp).subtract(180, 'second').toDate().getTime(), 'token', {});
await seriesRepository.saveData(`simple.data-${randomId}`, 5, moment(timestamp).subtract(170, 'second').toDate().getTime(), 'token', {});
await seriesRepository.saveData(`simple.data-${randomId}`, 4, moment(timestamp).subtract(160, 'second').toDate().getTime(), 'token', {});
await seriesRepository.saveData(`simple.data-${randomId}`, 3, moment(timestamp).subtract(150, 'second').toDate().getTime(), 'token', {});
await seriesRepository.saveData(`simple.data-${randomId}`, 2, moment(timestamp).subtract(140, 'second').toDate().getTime(), 'token', {});
await seriesRepository.saveData(`simple.data-${randomId}`, 1, moment(timestamp).subtract(130, 'second').toDate().getTime(), 'token', {});
await seriesRepository.saveData(`simple.data-${randomId}`, 2, moment(timestamp).subtract(120, 'second').toDate().getTime(), 'token', {});
await seriesRepository.saveData(`simple.data-${randomId}`, 3, moment(timestamp).subtract(110, 'second').toDate().getTime(), 'token', {});
await seriesRepository.saveData(`simple.data-${randomId}`, 4, moment(timestamp).subtract(100, 'second').toDate().getTime(), 'token', {});
await seriesRepository.saveData(`simple.data-${randomId}`, 5, moment(timestamp).subtract(90, 'second').toDate().getTime(), 'token', {});
await seriesRepository.saveData(`simple.data-${randomId}`, 6, moment(timestamp).subtract(80, 'second').toDate().getTime(), 'token', {});
await seriesRepository.saveData(`simple.data-${randomId}`, 7, moment(timestamp).subtract(70, 'second').toDate().getTime(), 'token', {});
await seriesRepository.saveData(`simple.data-${randomId}`, 8, moment(timestamp).subtract(60, 'second').toDate().getTime(), 'token', {});
await seriesRepository.saveData(`simple.data-${randomId}`, 9, moment(timestamp).subtract(50, 'second').toDate().getTime(), 'token', {});
await seriesRepository.saveData(`simple.data-${randomId}`, 10, moment(timestamp).subtract(40, 'second').toDate().getTime(), 'token', {});
await seriesRepository.saveData(`simple.data-${randomId}`, 15, moment(timestamp).subtract(30, 'second').toDate().getTime(), 'token', {});
await seriesRepository.saveData(`simple.data-${randomId}`, 20, moment(timestamp).subtract(20, 'second').toDate().getTime(), 'token', {});
await seriesRepository.saveData(`simple.data-${randomId}`, 25, moment(timestamp).subtract(10, 'second').toDate().getTime(), 'token', {});
const result = await seriesRepository.getAggregatedData(`simple.data-${randomId}`, moment(timestamp).subtract(5, 'minute').toDate().getTime(), 'token', {}, 'average', 1);
expect(result.length).to.be.eq(3);
});
});
});
<file_sep>import * as express from 'express';
import * as path from 'path';
import * as bodyParser from "body-parser";
import * as cors from "cors";
import * as exphbs from 'express-handlebars';
// imports services
import { MetricService } from "./services/metric";
// imports models
import { Counter } from "./models/counter";
import { Gauge } from "./models/gauge";
import { Timing } from "./models/timing";
export class RESTInterface {
constructor(
private app: any,
private metricService: MetricService,
) {
this.app.use(cors());
this.app.use(bodyParser.urlencoded({ extended: false }));
this.app.use(bodyParser.json({}));
app.engine('handlebars', exphbs({
defaultLayout: 'main',
layoutsDir: path.join(__dirname, 'views/layouts'),
}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'handlebars');
this.initialize();
}
private initialize(): void {
this.app.use('/coverage', express.static(path.join(__dirname, './../coverage/lcov-report')));
this.app.post("/api/metrics/log", async (req, res) => {
const data: any = req.body;
await this.metricService.log(data.type, data.name, data.value, data.token, data.tags);
res.send("OK");
});
this.app.get("/api/metrics/names", async (req, res) => {
const result: string[] = await this.metricService.listNames(req.query.token);
res.json(result);
});
this.app.post("/api/metrics/series", async (req, res) => {
const result: Array<{ timestamp: string, x: number, y: number }> = await this.metricService.getData(req.body.name, parseInt(req.body.timestamp, undefined), req.body.token, req.body.tags);
res.json(result);
});
this.app.post("/api/metrics/seriesAggregated", async (req, res) => {
const result: Array<{ timestamp: string, x: number, y: number }> = await this.metricService.getAggregatedData(req.body.name, parseInt(req.body.timestamp, undefined), req.body.token, req.body.tags, req.body.aggregate, parseInt(req.body.intervalInMinutes, undefined));
res.json(result);
});
this.app.get("/api/metrics/chart", async (req, res) => {
res.render('api/metrics/chart');
});
}
}
<file_sep>// imports interfaces
import { ISeriesRepository } from "./../repositories/series";
// imports models
import { Aggregate } from "./../models/aggregate";
import { Counter } from "./../models/counter";
import { Gauge } from "./../models/gauge";
import { Timing } from "./../models/timing";
// imports services
import { StatsService } from "./stats";
export class MetricService {
private statsService: StatsService = new StatsService();
private counters: {} = {};
private gauges: {} = {};
private timings: {} = {};
constructor(private seriesRepository: ISeriesRepository, private onLog: (type: string, name: string, value: number, tags: {}) => void) {
}
public async log(type: string, name: string, value: number, token: string, tags: {}): Promise<void> {
switch (type) {
case 'counter':
this.updateCounter(name, value, token || 'default', tags);
break;
case 'gauge':
this.updateGauge(name, value, token || 'default', tags);
break;
case 'timing':
this.updateTiming(name, value, token || 'default', tags);
break;
case 'series':
await this.seriesRepository.saveData(name, value, new Date().getTime(), token || 'default', tags);
break;
}
this.updateCounter('open-stats.metrics', 1, token || 'default', tags);
if (this.onLog) {
this.onLog(type, name, value, tags);
}
}
public async sendAggerate(intervalInSeconds: number): Promise<void> {
const timestamp: number = new Date().getTime();
const aggregate: Aggregate = this.aggerate(intervalInSeconds);
for (const counter of aggregate.counters) {
await this.seriesRepository.saveData(counter.name, counter.value, timestamp, counter.token, counter.tags);
await this.seriesRepository.saveData(`${counter.name}.rate`, counter.value / intervalInSeconds, timestamp, counter.token, counter.tags);
}
for (const gauge of aggregate.gauges) {
await this.seriesRepository.saveData(gauge.name, gauge.value, timestamp, gauge.token, gauge.tags);
}
for (const timing of aggregate.timings) {
await this.seriesRepository.saveData(`${timing.name}.maximum`, timing.maximum, timestamp, timing.token, timing.tags);
await this.seriesRepository.saveData(`${timing.name}.mean`, timing.mean, timestamp, timing.token, timing.tags);
await this.seriesRepository.saveData(`${timing.name}.median`, timing.median, timestamp, timing.token, timing.tags);
await this.seriesRepository.saveData(`${timing.name}.minimum`, timing.minimum, timestamp, timing.token, timing.tags);
await this.seriesRepository.saveData(`${timing.name}.standardDeviation`, timing.standardDeviation, timestamp, timing.token, timing.tags);
}
}
public aggerate(intervalInSeconds: number): Aggregate {
const aggregateCounters: Counter[] = [];
for (const token in this.counters) {
for (const tagBucket in this.counters[token]) {
for (const name in this.counters[token][tagBucket]) {
aggregateCounters.push(new Counter(name, this.counters[token][tagBucket][name].value, this.counters[token][tagBucket][name].value / intervalInSeconds, token, this.counters[token][tagBucket][name].tags));
}
}
}
this.counters = {};
const aggregateGauges: Gauge[] = [];
for (const token in this.gauges) {
for (const tagBucket in this.gauges[token]) {
for (const name in this.gauges[token][tagBucket]) {
aggregateGauges.push(new Gauge(name, this.gauges[token][tagBucket][name].value, token, this.gauges[token][tagBucket][name].tags));
}
}
}
const aggregateTimings: Timing[] = [];
for (const token in this.timings) {
for (const tagBucket in this.timings[token]) {
for (const name in this.timings[token][tagBucket]) {
aggregateTimings.push(new Timing(
name,
this.statsService.calculateMean(this.timings[token][tagBucket][name].values),
this.statsService.calculateMedian(this.timings[token][tagBucket][name].values),
this.statsService.calculateMinimum(this.timings[token][tagBucket][name].values),
this.statsService.calculateMaximum(this.timings[token][tagBucket][name].values),
this.statsService.calculateStandardDeviation(this.timings[token][tagBucket][name].values),
token,
this.timings[token][tagBucket][name].tags,
));
}
}
}
this.timings = {};
return new Aggregate(aggregateCounters, aggregateGauges, aggregateTimings);
}
public async getData(name: string, timestamp: number, token: string, tags: {}): Promise<Array<{ timestamp: string, x: number, y: number, tags: {} }>> {
return this.seriesRepository.getData(name, timestamp, token || 'default', tags);
}
public async getAggregatedData(name: string, timestamp: number, token: string, tags: {}, aggregate: string, intervalInMinutes: number): Promise<Array<{ timestamp: string, x: number, y: number, tags: {} }>> {
return this.seriesRepository.getAggregatedData(name, timestamp, token || 'default', tags, aggregate || 'average', intervalInMinutes || 1);
}
public async listNames(token: string): Promise<string[]> {
return this.seriesRepository.listNames(token || 'default');
}
public async clearStaleData(hours: number): Promise<boolean> {
return this.seriesRepository.clearStaleData(hours);
}
private updateCounter(name: string, value: number, token: string, tags: {}): void {
const tagBucket: string = tags && Object.keys(tags).length > 0 ? Object.keys(tags).map((x) => `${x}:${tags[x]}`).sort().join(',') : 'default';
if (!this.counters[token]) {
this.counters[token] = {};
}
if (!this.counters[token][tagBucket]) {
this.counters[token][tagBucket] = {};
}
if (!this.counters[token][tagBucket][name]) {
this.counters[token][tagBucket][name] = {
tags,
value,
};
} else {
this.counters[token][tagBucket][name].value += value;
}
}
private updateGauge(name: string, value: number, token: string, tags: {}): void {
const tagBucket: string = tags && Object.keys(tags).length > 0 ? Object.keys(tags).map((x) => `${x}:${tags[x]}`).sort().join(',') : 'default';
if (!this.gauges[token]) {
this.gauges[token] = {};
}
if (!this.gauges[token][tagBucket]) {
this.gauges[token][tagBucket] = {};
}
if (!this.gauges[token][tagBucket][name]) {
this.gauges[token][tagBucket][name] = {
tags,
value,
};
} else {
this.gauges[token][tagBucket][name].value = value;
}
}
private updateTiming(name: string, value: number, token: string, tags: {}): void {
const tagBucket: string = tags && Object.keys(tags).length > 0 ? Object.keys(tags).map((x) => `${x}:${tags[x]}`).sort().join(',') : 'default';
if (!this.timings[token]) {
this.timings[token] = {};
}
if (!this.timings[token][tagBucket]) {
this.timings[token][tagBucket] = {};
}
if (!this.timings[token][tagBucket][name]) {
this.timings[token][tagBucket][name] = {
tags,
values: [value],
};
} else {
this.timings[token][tagBucket][name].values.push(value);
}
}
}
<file_sep>export class StatsService {
public calculateMean(data: number[]): number {
if (data.length === 0) {
return 0;
}
let total: number = 0;
for (let i: number = 0; i < data.length; i += 1) {
total += data[i];
}
return total / data.length;
}
public calculateMedian(data: number[]): number {
if (data.length === 0) {
return 0;
}
data = data.sort((a: number, b: number) => {
return a - b;
});
if (data.length % 2 === 0) {
return (data[data.length / 2 - 1] + data[data.length / 2]) / 2;
} else {
return data[(data.length - 1) / 2];
}
}
public calculateMinimum(data: number[]): number {
if (data.length === 0) {
return 0;
}
data = data.sort((a: number, b: number) => {
return a - b;
});
return data[0];
}
public calculateMaximum(data: number[]): number {
if (data.length === 0) {
return 0;
}
data = data.sort((a: number, b: number) => {
return a - b;
});
return data[data.length - 1];
}
public calculateSum(data: number[]): number {
let total: number = 0;
for (let i: number = 0; i < data.length; i += 1) {
total += data[i];
}
return total;
}
public calculateStandardDeviation(data: number[]): number {
if (data.length === 0) {
return 0;
}
const mean: number = this.calculateMean(data);
const a: number[] = data.map((x) => Math.pow(x - mean, 2));
const newMean: number = this.calculateMean(a);
return Math.sqrt(newMean);
}
public recalculateStandardDeviation(sum: number, n: number, sumSquared: number): number {
const meanSum: number = sum / n;
const meanSumSquared: number = sumSquared / n;
const result: number = meanSumSquared - Math.pow(meanSum, 2);
return Math.sqrt(result);
}
}
<file_sep>import { expect } from "chai";
import "mocha";
import { MetricService } from "./metric";
import { Aggregate } from './../models/aggregate';
describe("MetricService", () => {
describe("log - Counter", () => {
it("should return value given single log value", async () => {
const metricService: MetricService = new MetricService(null, null);
await metricService.log('counter', 'simple.counter', 5, 'token', {});
const aggregate: Aggregate = metricService.aggerate(10);
expect(aggregate.counters[0].value).to.be.eq(5);
});
it("should return rate given single log value", async () => {
const metricService: MetricService = new MetricService(null, null);
await metricService.log('counter', 'simple.counter', 5, 'token', {});
const aggregate: Aggregate = metricService.aggerate(10);
expect(aggregate.counters[0].rate).to.be.eq(0.5);
});
it("should return value given multiple log values", async () => {
const metricService: MetricService = new MetricService(null, null);
await metricService.log('counter', 'simple.counter', 5, 'token', {});
await metricService.log('counter', 'simple.counter', -2, 'token', {});
await metricService.log('counter', 'simple.counter', 10, 'token', {});
const aggregate: Aggregate = metricService.aggerate(10);
expect(aggregate.counters[0].value).to.be.eq(13);
});
it("should return rate given multiple log values", async () => {
const metricService: MetricService = new MetricService(null, null);
await metricService.log('counter', 'simple.counter', 5, 'token', {});
await metricService.log('counter', 'simple.counter', -2, 'token', {});
await metricService.log('counter', 'simple.counter', 10, 'token', {});
const aggregate: Aggregate = metricService.aggerate(10);
expect(aggregate.counters[0].rate).to.be.eq(1.3);
});
it("should clear counters when aggregate is called", async () => {
const metricService: MetricService = new MetricService(null, null);
await metricService.log('counter', 'simple.counter', 5, 'token', {});
metricService.aggerate(10);
const aggregate: Aggregate = metricService.aggerate(10);
expect(aggregate.counters.length).to.be.eq(0);
});
});
describe("log - Gauge", () => {
it("should return value given single log value", async () => {
const metricService: MetricService = new MetricService(null, null);
await metricService.log('gauge', 'simple.gauge', 5, 'token', {});
const aggregate: Aggregate = metricService.aggerate(10);
expect(aggregate.gauges[0].value).to.be.eq(5);
});
it("should return value given multiple log values", async () => {
const metricService: MetricService = new MetricService(null, null);
await metricService.log('gauge', 'simple.gauge', 5, 'token', {});
await metricService.log('gauge', 'simple.gauge', -2, 'token', {});
await metricService.log('gauge', 'simple.gauge', 10, 'token', {});
const aggregate: Aggregate = metricService.aggerate(10);
expect(aggregate.gauges[0].value).to.be.eq(10);
});
it("should not clear gauges when aggregate is called", async () => {
const metricService: MetricService = new MetricService(null, null);
await metricService.log('gauge', 'simple.gauge', 5, 'token', {});
metricService.aggerate(10);
const aggregate: Aggregate = metricService.aggerate(10);
expect(aggregate.gauges.length).to.be.eq(1);
});
});
describe("log - Timing", () => {
it("should return mimimum given single log value", async () => {
const metricService: MetricService = new MetricService(null, null);
await metricService.log('timing', 'simple.timing', 5, 'token', {});
const aggregate: Aggregate = metricService.aggerate(10);
expect(aggregate.timings[0].minimum).to.be.eq(5);
});
it("should return minimum given multiple log values", async () => {
const metricService: MetricService = new MetricService(null, null);
await metricService.log('timing', 'simple.timing', 5, 'token', {});
await metricService.log('timing', 'simple.timing', -2, 'token', {});
await metricService.log('timing', 'simple.timing', 10, 'token', {});
const aggregate: Aggregate = metricService.aggerate(10);
expect(aggregate.timings[0].minimum).to.be.eq(-2);
});
it("should return maximum given single log value", async () => {
const metricService: MetricService = new MetricService(null, null);
await metricService.log('timing', 'simple.timing', 5, 'token', {});
const aggregate: Aggregate = metricService.aggerate(10);
expect(aggregate.timings[0].maximum).to.be.eq(5);
});
it("should return maximum given multiple log values", async () => {
const metricService: MetricService = new MetricService(null, null);
await metricService.log('timing', 'simple.timing', 5, 'token', {});
await metricService.log('timing', 'simple.timing', -2, 'token', {});
await metricService.log('timing', 'simple.timing', 10, 'token', {});
const aggregate: Aggregate = metricService.aggerate(10);
expect(aggregate.timings[0].maximum).to.be.eq(10);
});
it("should return mean given single log value", async () => {
const metricService: MetricService = new MetricService(null, null);
await metricService.log('timing', 'simple.timing', 5, 'token', {});
const aggregate: Aggregate = metricService.aggerate(10);
expect(aggregate.timings[0].mean).to.be.eq(5);
});
it("should return mean given multiple log values", async () => {
const metricService: MetricService = new MetricService(null, null);
await metricService.log('timing', 'simple.timing', 5, 'token', {});
await metricService.log('timing', 'simple.timing', -2, 'token', {});
await metricService.log('timing', 'simple.timing', 10, 'token', {});
const aggregate: Aggregate = metricService.aggerate(10);
expect(aggregate.timings[0].mean).to.be.eq(4.333333333333333);
});
it("should return median given single log value", async () => {
const metricService: MetricService = new MetricService(null, null);
await metricService.log('timing', 'simple.timing', 5, 'token', {});
const aggregate: Aggregate = metricService.aggerate(10);
expect(aggregate.timings[0].median).to.be.eq(5);
});
it("should return median given multiple log values", async () => {
const metricService: MetricService = new MetricService(null, null);
await metricService.log('timing', 'simple.timing', 5, 'token', {});
await metricService.log('timing', 'simple.timing', -2, 'token', {});
await metricService.log('timing', 'simple.timing', 10, 'token', {});
const aggregate: Aggregate = metricService.aggerate(10);
expect(aggregate.timings[0].median).to.be.eq(5);
});
it("should return standard deviation given single log value", async () => {
const metricService: MetricService = new MetricService(null, null);
await metricService.log('timing', 'simple.timing', 5, 'token', {});
const aggregate: Aggregate = metricService.aggerate(10);
expect(aggregate.timings[0].standardDeviation).to.be.eq(0);
});
it("should return standard deviation given multiple log values", async () => {
const metricService: MetricService = new MetricService(null, null);
await metricService.log('timing', 'simple.timing', 5, 'token', {});
await metricService.log('timing', 'simple.timing', -2, 'token', {});
await metricService.log('timing', 'simple.timing', 10, 'token', {});
const aggregate: Aggregate = metricService.aggerate(10);
expect(aggregate.timings[0].standardDeviation).to.be.eq(4.9216076867444665);
});
it("should clear timings when aggregate is called", async () => {
const metricService: MetricService = new MetricService(null, null);
await metricService.log('timing', 'simple.timing', 5, 'token', {});
metricService.aggerate(10);
const aggregate: Aggregate = metricService.aggerate(10);
expect(aggregate.timings.length).to.be.eq(0);
});
});
});
<file_sep>import { expect } from "chai";
import "mocha";
import * as sinon from 'sinon';
import { MetricService } from "./services/metric";
import { UDPInterface } from "./udp-interface";
describe("UDPInterface", () => {
describe("onMessage", () => {
it("should call MetricService.log once given valid message", async () => {
const metricService: MetricService = new MetricService(null, null);
const logSpy = sinon.spy(metricService, 'log');
const udpInterface: UDPInterface = new UDPInterface('', 0, metricService);
await udpInterface._onMessage(Buffer.from('simple.counter:5|c'), null);
expect(logSpy.calledOnce).to.be.true;
});
it("should call MetricService.log twice given valid messages", async () => {
const metricService: MetricService = new MetricService(null, null);
const logSpy = sinon.spy(metricService, 'log');
const udpInterface: UDPInterface = new UDPInterface('', 0, metricService);
await udpInterface._onMessage(Buffer.from('simple.counter:5|c\r\nsimple.counter:5|c'), null);
expect(logSpy.calledTwice).to.be.true;
});
it("should call MetricService.log once given valid message with tags", async () => {
const metricService: MetricService = new MetricService(null, null);
const logSpy = sinon.spy(metricService, 'log');
const udpInterface: UDPInterface = new UDPInterface('', 0, metricService);
await udpInterface._onMessage(Buffer.from('simple.counter:5|c|#tag1:abc,tag2:def'), null);
expect(logSpy.calledOnce).to.be.true;
});
});
});
<file_sep>import { Counter } from "./../models/counter";
import { Gauge} from "./../models/gauge";
import { Timing } from "./../models/timing";
export class Aggregate {
constructor(public counters: Counter[], public gauges: Gauge[], public timings: Timing[]) {
}
}
<file_sep>// imports
import * as cron from 'cron';
import * as express from "express";
import * as http from "http";
import * as path from 'path';
import * as winston from 'winston';
import * as yargs from 'yargs';
import { RESTInterface } from "./rest-interface";
import { TCPAdminInterface } from "./tcp-admin-interface";
import { UDPInterface } from "./udp-interface";
import { WebSocketInterface } from "./web-socket-interface";
// imports services
import { MetricService } from "./services/metric";
// imports repositories
import { SeriesRepository } from "./repositories//mongo-lite/series";
import { ISeriesRepository } from "./repositories/series";
const argv = yargs.argv;
const logger = winston.createLogger({
transports: [
new winston.transports.File({
filename: path.join(__dirname, 'open-stats.log'),
level: 'info',
}),
new winston.transports.Console(),
],
});
// HTTP Server
const app = express();
const httpServer = http.createServer(app);
// TCP Admin Interface
const tcpAdminInterface: TCPAdminInterface = new TCPAdminInterface("0.0.0.0", 8126);
tcpAdminInterface.start();
const seriesRepository: ISeriesRepository = new SeriesRepository('mongodb://localhost:27017/open-stats-001', (name: string, value: number) => {
logger.info(`${name}: ${value}`);
});
const metricService: MetricService = new MetricService(seriesRepository, (type: string, name: string, value: number) => {
logger.info(`${name}: ${value}`);
tcpAdminInterface.sendUpdateToAllSockets(name, value);
});
// Web Socket Interface
const websocketInterface: WebSocketInterface = new WebSocketInterface(httpServer, metricService);
// UDP Interface
const udpInterface: UDPInterface = new UDPInterface("0.0.0.0", 8125, metricService);
udpInterface.start();
// REST Interface
const restInterface: RESTInterface = new RESTInterface(app, metricService);
httpServer.listen(argv.port || 3000);
const jobAggregate = new cron.CronJob('*/20 * * * * *', async () => {
await metricService.sendAggerate(20);
logger.info('metricService.sendAggerate');
}, null, true);
const jobClearStaleData = new cron.CronJob('0 0 */3 * * *', async () => {
await metricService.clearStaleData(5);
logger.info('metricService.clearStaleData');
}, null, true);
jobAggregate.start();
jobClearStaleData.start();
metricService.clearStaleData(5).then(() => {
logger.info('metricService.clearStaleData');
});
<file_sep>// imports
import * as net from "net";
export class TCPAdminInterface {
private server: any;
private sockets: any[] = [];
constructor(
private host: string,
private port: number,
) {
this.server = net.createServer((socket: any) => this.onConnect(socket));
}
public start(): void {
this.server.listen(this.port, this.host);
}
public async sendUpdateToAllSockets(name: string, value: number): Promise<void> {
for (const socket of this.sockets) {
try {
socket.write(`${name}: ${value}\r\n`);
} catch (error) {
this.sockets.splice(this.sockets.indexOf(socket), 1);
}
}
}
private onConnect(socket: any): void {
this.sockets.push(socket);
}
}
<file_sep>import { expect } from "chai";
import "mocha";
import { StatsService } from "./stats";
describe("StatsService", () => {
describe("calculateMaximum", () => {
it("should return maximum", () => {
const statsService: StatsService = new StatsService();
const result: number = statsService.calculateMaximum([10, 5, 50, 1]);
expect(result).to.be.eq(50);
});
it("should return 0 given empty array", () => {
const statsService: StatsService = new StatsService();
const result: number = statsService.calculateMaximum([]);
expect(result).to.be.eq(0);
});
});
describe("calculateMean", () => {
it("should return mean", () => {
const statsService: StatsService = new StatsService();
const result: number = statsService.calculateMean([10, 5, 50, 1]);
expect(result).to.be.eq(16.5);
});
it("should return 0 given empty array", () => {
const statsService: StatsService = new StatsService();
const result: number = statsService.calculateMean([]);
expect(result).to.be.eq(0);
});
});
describe("calculateMedian", () => {
it("should return median", () => {
const statsService: StatsService = new StatsService();
const result: number = statsService.calculateMedian([10, 5, 50, 1]);
expect(result).to.be.eq(7.5);
});
it("should return 0 given empty array", () => {
const statsService: StatsService = new StatsService();
const result: number = statsService.calculateMedian([]);
expect(result).to.be.eq(0);
});
});
describe("calculateMinimum", () => {
it("should return minimum", () => {
const statsService: StatsService = new StatsService();
const result: number = statsService.calculateMinimum([10, 5, 50, 1]);
expect(result).to.be.eq(1);
});
it("should return 0 given empty array", () => {
const statsService: StatsService = new StatsService();
const result: number = statsService.calculateMinimum([]);
expect(result).to.be.eq(0);
});
});
describe("calculateStandardDeviation", () => {
it("should return standard deviation", () => {
const statsService: StatsService = new StatsService();
const result: number = statsService.calculateStandardDeviation([10, 5, 50, 1]);
expect(result).to.be.eq(19.60229578391266);
});
it("should return 0 given empty array", () => {
const statsService: StatsService = new StatsService();
const result: number = statsService.calculateStandardDeviation([]);
expect(result).to.be.eq(0);
});
});
describe("recalculateStandardDeviation", () => {
it("should return standard deviation", () => {
const statsService: StatsService = new StatsService();
const result: number = statsService.recalculateStandardDeviation(
statsService.calculateSum([10, 5, 50, 1]),
[10, 5, 50, 1].length,
statsService.calculateSum([10, 5, 50, 1].map((x) => Math.pow(x, 2))),
);
expect(result).to.be.eq(19.60229578391266);
});
});
describe("calculateSum", () => {
it("should return sum", () => {
const statsService: StatsService = new StatsService();
const result: number = statsService.calculateSum([10, 5, 50, 1]);
expect(result).to.be.eq(66);
});
it("should return 0 given empty array", () => {
const statsService: StatsService = new StatsService();
const result: number = statsService.calculateSum([]);
expect(result).to.be.eq(0);
});
});
});
<file_sep>// imports
import * as dgram from "dgram";
// imports services
import { MetricService } from "./services/metric";
export class UDPInterface {
private server: any;
constructor(
private host: string,
private port: number,
private metricService: MetricService,
) {
this.server = dgram.createSocket("udp4");
this.server.on("message", (data: Buffer, remote: any) => this.onMessage(data, remote));
}
public start(): void {
this.server.bind(this.port, this.host);
}
public async _onMessage(dataBuffer: Buffer, remote: any): Promise<void> {
return this.onMessage(dataBuffer, remote);
}
private async onMessage(dataBuffer: Buffer, remote: any): Promise<void> {
const messages: string[] = dataBuffer.toString().split(/\n/g);
for (const message of messages) {
const splittedMessage: string[] = message.split('|');
const name: string = splittedMessage[0].split(':')[0];
const value: string = splittedMessage[0].split(':')[1];
const letter: string = splittedMessage[1];
const tags: {} = {};
const rawTags: string[] = splittedMessage[2] ? splittedMessage[2].substring(1).split(',') : [];
for (const item of rawTags) {
tags[item.split(':')[0]] = item.split(':')[1];
}
const token: string = tags['token'] || tags['Token'];
tags['token'] = undefined;
tags['Token'] = undefined;
let type: string = null;
switch (letter) {
case "c":
type = "counter";
break;
case "g":
type = "gauge";
break;
case "ms":
type = "timing";
break;
case "s":
type = "series";
break;
}
await this.metricService.log(type, name, parseFloat(value), token, tags);
}
}
}
<file_sep>// imports
import * as moment from "moment";
import * as mongo from "mongodb";
// imports interfaces
import { ISeriesRepository } from "./../series";
import { StatsService } from "./../../services/stats";
export class SeriesRepository implements ISeriesRepository {
private db: mongo.Db;
constructor(private uri: string, private onSaveData: (name: string, value: number, tags: {}) => void) {
}
public async saveData(name: string, value: number, timestamp: number, token: string, tags: {}): Promise<boolean> {
if (!this.db) {
this.db = await mongo.MongoClient.connect(this.uri);
}
const collection: mongo.Collection = this.db.collection("series");
const timestampMomentjs = moment(timestamp);
const result: any = await collection.insertOne({
name,
tags: tags || {},
timestamp,
timestampDate: new Date(timestamp),
timestampElements: {
day: timestampMomentjs.date(),
hours: timestampMomentjs.hours(),
minutes: timestampMomentjs.minutes(),
month: timestampMomentjs.month() + 1,
seconds: timestampMomentjs.seconds(),
year: timestampMomentjs.year(),
},
token,
value,
});
if (this.onSaveData) {
this.onSaveData(name, value, tags);
}
return true;
}
public async listNames(token: string): Promise<string[]> {
if (!this.db) {
this.db = await mongo.MongoClient.connect(this.uri);
}
const collection: mongo.Collection = this.db.collection("series");
const result: any[] = await collection.distinct('name', {
token,
});
return result;
}
public async getData(name: string, timestamp: number, token: string, tags: {}): Promise<Array<{ timestamp: string, x: number, y: number, tags: {} }>> {
if (!this.db) {
this.db = await mongo.MongoClient.connect(this.uri);
}
const collection: mongo.Collection = this.db.collection("series");
const query = {
name,
timestamp: { $gt: timestamp },
token,
};
if (tags) {
for (const tag in tags) {
query[`tags.${tag}`] = tags[tag];
}
}
const result: any[] = await collection.find(query)
.sort({
timestamp: 1,
})
.toArray();
return result.map((x) => {
return {
tags: x.tags,
timestamp: moment(x.timestamp).format('YYYY/MM/DD HH:mm:ss'),
x: x.timestamp,
y: x.value,
};
});
}
public async getAggregatedData(name: string, timestamp: number, token: string, tags: {}, aggregate: string, intervalInMinutes: number): Promise<Array<{ timestamp: string, x: number, y: number, tags: {} }>> {
if (!this.db) {
this.db = await mongo.MongoClient.connect(this.uri);
}
const collection: mongo.Collection = this.db.collection("series");
const query = {
name,
timestamp: { $gt: timestamp },
token,
};
if (tags) {
for (const tag in tags) {
query[`tags.${tag}`] = tags[tag];
}
}
const result: any[] = await collection.aggregate([
{
$match: query,
},
{
$group: {
_id: {
day: '$timestampElements.day',
hours: '$timestampElements.hours',
// minutes: '$timestampElements.minutes',
minutes: {
$subtract: [
{ $minute: '$timestampDate' },
{ $mod: [{ $minute: '$timestampDate' }, intervalInMinutes] },
],
},
month: '$timestampElements.month',
// seconds: '$timestampElements.seconds',
year: '$timestampElements.year',
},
average: {
$avg: '$value',
},
maximum: {
$max: '$value',
},
minimum: {
$min: '$value',
},
sum: {
$sum: '$value',
},
},
},
]).toArray();
return result.map((x) => {
return {
tags,
timestamp: moment(new Date(x._id.year, x._id.month - 1, x._id.day, x._id.hours, x._id.minutes, 0)).format('YYYY/MM/DD HH:mm:ss'),
x: new Date(x._id.year, x._id.month - 1, x._id.day, x._id.hours, x._id.minutes, 0).getTime(),
y: x[aggregate],
};
}).sort((a, b) => {
if (a.timestamp < b.timestamp) {
return -1;
}
if (a.timestamp > b.timestamp) {
return 1;
}
return 0;
});
}
public async clearStaleData(hours: number): Promise<boolean> {
if (!this.db) {
this.db = await mongo.MongoClient.connect(this.uri);
}
const collection: mongo.Collection = this.db.collection("series");
await collection.remove({
timestamp: { $lt: moment().subtract(hours, 'hour').toDate().getTime() },
});
return true;
}
}
<file_sep>export interface ISeriesRepository {
saveData(name: string, value: number, timestamp: number, token: string, tags: {}): Promise<boolean>;
getData(name: string, timestamp: number, token: string, tags: {}): Promise<Array<{ timestamp: string, x: number, y: number, tags: {} }>>;
getAggregatedData(name: string, timestamp: number, token: string, tags: {}, aggregate: string, intervalInMinutes: number): Promise<Array<{ timestamp: string, x: number, y: number, tags: {} }>>;
listNames(token: string): Promise<string[]>;
clearStaleData(hours: number): Promise<boolean>;
}
<file_sep>export class Timing {
constructor(
public name: string,
public mean: number,
public median: number,
public minimum: number,
public maximum: number,
public standardDeviation: number,
public token: string,
public tags: {},
) {
}
}
<file_sep>// imports
import * as WebSocket from "ws";
// imports services
import { MetricService } from "./services/metric";
export class WebSocketInterface {
private server: any;
constructor(
private httpServer: any,
private metricService: MetricService,
) {
this.server = new WebSocket.Server({
path: '/open-stats',
server: this.httpServer,
});
this.server.on("connection", this.onConnect);
}
private onConnect(ws: any): void {
ws.on("message", (message) => this.onMessage(message));
}
private async onMessage(message: string): Promise<void> {
const data: any = JSON.parse(message);
await this.metricService.log(data.type, data.name, data.value, data.token, data.tags);
}
}
|
1ed058fe5b8c2576f064c01cea5aa1d6a943d743
|
[
"TypeScript"
] | 15 |
TypeScript
|
barend-erasmus/open-stats
|
513804993cc61b4187412b6feb640d86faa7c764
|
6267d5554259287d513c2d8485a74e79dbca0a8d
|
refs/heads/master
|
<repo_name>ardell/Chef<file_sep>/cookbooks/application/recipes/apache2.rb
#
# Cookbook Name:: application
# Recipe:: default
#
# Copyright 2011, Tourbuzz LLC.
#
app = node.run_state[:current_app]
include_recipe "apache2"
<file_sep>/README.markdown
# Basic Chef Setup
## Installation
1. Install Ruby (we recommend rvm with Ruby 1.8.7-p173)
2. `gem install bundler`
3. `bundle install` (installs chef, knife, and other tools)
4. `cp .chef/knife.rb.sample .chef/knife.rb` and customize
## To add a cookbook
This command will import a cookbook from the "blessed" Opscode cookbooks at http://cookbooks.opscode.com.
knife cookbook site vendor COOKBOOK_NAME
knife cookbook upload COOKBOOK_NAME
## To add a role
knife role from file ROLE_NAME.rb
## To add a data_bag
knife data bag create DATA_BAG_NAME
knife data bag from file DIR DATA_BAG_NAME.json
## To boot a server
knife ec2 server create 'role[staging]' 'role[base]' 'role[app]' 'role[database_master]' --ssh-key ec2-keypair --identity-file .chef/ec2-keypair.pem --ssh-user ubuntu --groups default --image ami-88f504e1 --flavor m1.small -Z us-east-1a
### Flags:
+ `-f` m1.small is the size of the instance we want
+ `-i` ami-480df921 says use the stock ubuntu ebs volume instance
+ `-S` ec2-keypair is the name of the keypair on aws
+ `-x` ubuntu says connect via ssh with the "ubuntu" username (instead of default=root)
+ `-I` ~/Documents/workspace/chef/.chef/ec2-keypair.pem says use the key at this location
+ `-Z` us-east-1a Amazon doesn't have capacity of m1.small servers at us-east-1b (which is our default data center), so we use this one instead
+ `-N` [name] is required because otherwise amazon gives chef a _local_.internal hostname that doesn't work. If we reference it by name it works
## To update your server
knife ssh 'role:app' 'sudo chef-client' -a ec2.public_hostname --ssh-user ubuntu
<file_sep>/cookbooks/application/recipes/phocoa.rb
#
# Cookbook Name:: application
# Recipe:: default
#
# Copyright 2011, Tourbuzz LLC.
#
app = node.run_state[:current_app]
###
# You really most likely don't want to run this recipe from here - let the
# default application recipe work its mojo for you.
###
## First, install any application specific packages
if app['packages']
app['packages'].each do |pkg,ver|
package pkg do
action :install
version ver if ver && ver.length > 0
end
end
end
## Next, install any application specific gems
if app['gems']
app['gems'].each do |gem,ver|
gem_package gem do
action :install
version ver if ver && ver.length > 0
end
end
end
directory app['deploy_to'] do
owner app['owner']
group app['group']
mode '0755'
recursive true
end
directory "#{app['deploy_to']}/shared" do
owner app['owner']
group app['group']
mode '0755'
recursive true
end
%w{ log pids system vendor_bundle }.each do |dir|
directory "#{app['deploy_to']}/shared/#{dir}" do
owner app['owner']
group app['group']
mode '0755'
recursive true
end
end
template "#{app['deploy_to']}/deploy-ssh-wrapper" do
source "deploy-ssh-wrapper.erb"
owner app['owner']
group app['group']
mode "0755"
variables app.to_hash
end
if app["database_master_role"]
dbm = nil
# If we are the database master
if node.run_list.roles.include?(app["database_master_role"][0])
dbm = node
else
# Find the database master
results = search(:node, "run_list:role\\[#{app["database_master_role"][0]}\\] AND app_environment:#{node[:app_environment]}", nil, 0, 1)
rows = results[0]
if rows.length == 1
dbm = rows[0]
end
end
# Assuming we have one...
db_config_name = 'database'
if dbm
# We do this using ConfigMagic
# db_config_name = app["databases"][node.app_environment]["adapter"] =~ /mongodb/ ? 'mongoid' : 'database'
# template "#{app['deploy_to']}/shared/#{db_config_name}.yml" do
# source "#{db_config_name}.yml.erb"
# owner app["owner"]
# group app["group"]
# mode "644"
# variables(
# :host => dbm['fqdn'],
# :databases => app['databases']
# )
# end
else
Chef::Log.warn("No node with role #{app["database_master_role"][0]}, #{db_config_name}.yml not rendered!")
end
end
## Then, deploy
deploy_revision app['id'] do
# TODO: Mimic gitflow's determining of the current production tag
revision app['revision'][node.app_environment]
repository app['repository']
user app['owner']
group app['group']
deploy_to app['deploy_to'][node.app_environment]
action app['force'][node.app_environment] ? :force_deploy : :deploy
ssh_wrapper "#{app['deploy_to']}/deploy-ssh-wrapper" if app['deploy_key']
execute "update externals" do
command "rake externals:init && rake externals:update"
cwd "#{app['deploy_to']}/current"
action :run
end
node.default[:apps][app['id']][node.app_environment][:run_migrations] = false
if app['migrate'][node.app_environment] && node[:apps][app['id']][node.app_environment][:run_migrations]
migrate true
migration_command app['migration_command'] || "rake db:migrate"
else
migrate false
end
end<file_sep>/roles/database_master.rb
name "database_master"
description "Database master for the application."
run_list(
"recipe[postgresql::server]"
)
<file_sep>/Gemfile
source 'http://rubygems.org'
gem 'chef'
gem 'net-ssh'
gem 'net-ssh-multi'
gem 'fog'
gem 'highline'
|
b6beab7219823912e749df94cb4b7e1917c9226a
|
[
"Markdown",
"Ruby"
] | 5 |
Ruby
|
ardell/Chef
|
da7239719847bd5a502f6a4ee092e70065e97a66
|
a6e390a175578e52707ea1242742190709d31a71
|
refs/heads/main
|
<repo_name>ByoungilYoun/AVFoundation_Tutorials<file_sep>/VideoRecordAndPlay/VideoRecordAndPlay/MainViewController.swift
//
// MainViewController.swift
// VideoRecordAndPlay
//
// Created by 윤병일 on 2021/09/24.
//
import UIKit
import SnapKit
import AVKit
import MobileCoreServices
import AVFoundation
import AVFAudio
class MainViewController : UIViewController, UINavigationControllerDelegate {
//MARK: - Properties
var videoAndImageReview = UIImagePickerController()
var videoURL : URL?
let recordStartButton : UIButton = {
let bt = UIButton()
bt.setTitle("Record Video", for: .normal)
bt.setTitleColor(.black, for: .normal)
bt.backgroundColor = .lightGray
bt.addTarget(self, action: #selector(recordStart), for: .touchUpInside)
return bt
}()
let playVideoButton : UIButton = {
let bt = UIButton()
bt.setTitle("Play Video", for: .normal)
bt.setTitleColor(.black, for: .normal)
bt.backgroundColor = .yellow
bt.addTarget(self, action: #selector(playVideo), for: .touchUpInside)
return bt
}()
//MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
}
//MARK: - Functions
private func configureUI() {
view.backgroundColor = .white
let stack = UIStackView(arrangedSubviews: [recordStartButton, playVideoButton])
stack.axis = .vertical
stack.distribution = .fillEqually
stack.spacing = 10
view.addSubview(stack)
stack.snp.makeConstraints {
$0.center.equalToSuperview()
$0.width.equalTo(300)
$0.height.equalTo(400)
}
func videoAndImageReview(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
videoURL = info[UIImagePickerController.InfoKey.mediaURL.rawValue] as? URL
print("\(String(describing: videoURL))")
self.dismiss(animated: true, completion: nil)
}
}
//MARK: - @objc func
@objc func recordStart() {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
print("Camera Available")
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .camera
// imagePicker.mediaTypes = [kUTTypeMovie as String]
imagePicker.mediaTypes = ["public.movie"]
// imagePicker.mediaTypes = ["com.apple.quicktime-movie"]
// imagePicker.mediaTypes = [kUTTypeQuickTimeMovie as String]
// imagePicker.mediaTypes = NSArray(objects: UTType.quickTimeMovie) as! [String]
// var identifier = UTType.quickTimeMovie.identifier
// identifier = "com.apple.quicktime-movie"
// imagePicker.mediaTypes = [identifier as String]
// imagePicker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .camera) ?? []
// imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil];
// imagePicker.mediaTypes = UTType["com.apple.quicktime-movie"]
// imagePicker.mediaTypes =
// let type = UTType.init("com.apple.quicktime-movie")
// imagePicker.mediaTypes = [type as String]
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
} else {
print("Camera Unavailable")
}
}
@objc func playVideo() {
print("play Video")
videoAndImageReview.sourceType = .savedPhotosAlbum
videoAndImageReview.delegate = self
videoAndImageReview.mediaTypes = ["public.movie"]
present(videoAndImageReview, animated: true, completion: nil)
}
@objc func videoSave(_ videoPath : String, didFinishSavingWithError error : Error?, contextInfo info : AnyObject) {
let title = (error == nil) ? "Success" : "Error"
let message = (error == nil) ? "Video was saved" : "Video failed to save"
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
present(alert, animated: true, completion: nil)
}
}
//MARK: - UIImagePickerControllerDelegate
extension MainViewController : UIImagePickerControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
dismiss(animated: true, completion: nil)
guard let mediaType = info[.mediaType] as? String,
mediaType == (kUTTypeMovie as String),
let url = info[.mediaURL] as? URL,
UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(url.path) else {return}
// Handle a movie capture
UISaveVideoAtPathToSavedPhotosAlbum(url.path, self, #selector(videoSave(_:didFinishSavingWithError:contextInfo:)), nil)
}
}
<file_sep>/VideoRecordingPractice/VideoRecordingPractice/RecordingViewController.swift
//
// RecordingViewController.swift
// VideoRecordingPractice
//
// Created by 윤병일 on 2021/10/09.
//
import UIKit
import SnapKit
import AVFoundation
import RxCocoa
import RxSwift
import CoreMotion
import Then
class RecordingViewController : UIViewController {
//MARK: - Properties
var disposeBag = DisposeBag()
let captureSession = AVCaptureSession().then {
$0.sessionPreset = .low
} // 세션 low 로 설정
var videoDevice : AVCaptureDevice!
var videoInput : AVCaptureDeviceInput!
var audioInput : AVCaptureDeviceInput!
var videoOutput : AVCaptureMovieFileOutput!
lazy var previewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession).then {
$0.bounds = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
$0.position = CGPoint(x: self.view.bounds.midX, y: self.view.bounds.midY)
$0.videoGravity = .resizeAspectFill
}
let topContainer = UIView()
let swapButton = UIButton().then { $0.setTitle("Swap", for: .normal) }
let recordButton = UIButton().then { $0.setTitle("Record", for: .normal) }
let recordPoint = UIView().then {
$0.backgroundColor = .red
$0.layer.cornerRadius = 3
$0.alpha = 0
}
let timerLabel = UILabel().then {
$0.text = "00:00:00"
$0.textColor = .white
}
var outputURL : URL?
var motionManager : CMMotionManager!
var deviceOrientation : AVCaptureVideoOrientation = .portrait
var timer : Timer?
var secondsOfTimer = 0
//MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
bind()
videoDevice = bestDevice(in: .back)
setupSession()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
initMotionManager()
if !captureSession.isRunning {
captureSession.startRunning()
}
}
override func viewWillDisappear(_ animated: Bool) {
motionManager.stopAccelerometerUpdates()
stopTimer()
}
//MARK: - Functions
private func configureUI() {
self.view.layer.addSublayer(previewLayer)
self.view.addSubview(topContainer)
topContainer.snp.makeConstraints {
$0.top.equalTo(view.safeAreaLayoutGuide.snp.top).offset(10)
$0.leading.trailing.equalToSuperview()
$0.height.equalTo(50)
}
[swapButton, timerLabel, recordPoint].forEach {
topContainer.addSubview($0)
}
swapButton.snp.makeConstraints {
$0.centerY.equalToSuperview()
$0.trailing.equalToSuperview().offset(-15)
$0.height.equalTo(40)
}
timerLabel.snp.makeConstraints {
$0.centerX.centerY.equalToSuperview()
}
recordPoint.snp.makeConstraints {
$0.centerY.equalToSuperview()
$0.trailing.equalTo(timerLabel.snp.leading).offset(-5)
$0.width.height.equalTo(6)
}
self.view.addSubview(recordButton)
recordButton.snp.makeConstraints {
$0.centerX.equalToSuperview()
$0.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-50)
$0.height.equalTo(40)
}
}
private func bind() {
recordButton.rx.tap
.subscribe(onNext : { [weak self] in
guard let self = self else { return }
if self.videoOutput.isRecording {
self.stopRecording()
self.recordButton.setTitle("Record", for: .normal)
} else {
self.startRecording()
self.recordButton.setTitle("Stop", for: .normal)
}
}).disposed(by: self.disposeBag)
swapButton.rx.tap
.subscribe(onNext : { [weak self] in
guard let self = self else { return }
self.swapCameraType()
}).disposed(by: self.disposeBag)
}
private func setupSession() {
do {
captureSession.beginConfiguration()
videoInput = try AVCaptureDeviceInput(device: videoDevice)
if captureSession.canAddInput(videoInput) {
captureSession.addInput(videoInput)
}
let audioDevice = AVCaptureDevice.default(for: AVMediaType.audio)!
audioInput = try AVCaptureDeviceInput(device: audioDevice)
if captureSession.canAddInput(audioInput) {
captureSession.addInput(audioInput)
}
videoOutput = AVCaptureMovieFileOutput()
if captureSession.canAddOutput(videoOutput) {
captureSession.addOutput(videoOutput)
}
captureSession.commitConfiguration()
} catch let error as NSError {
NSLog("\(error), \(error.localizedDescription)")
}
}
private func bestDevice(in position : AVCaptureDevice.Position) -> AVCaptureDevice {
var deviceTypes : [AVCaptureDevice.DeviceType]!
if #available(iOS 11.1, *) {
deviceTypes = [.builtInTrueDepthCamera, .builtInDualCamera, .builtInWideAngleCamera]
} else {
deviceTypes = [.builtInDualCamera, .builtInWideAngleCamera]
}
let discoverySession = AVCaptureDevice.DiscoverySession(
deviceTypes: deviceTypes,
mediaType: .video,
position: .unspecified)
let devices = discoverySession.devices
guard !devices.isEmpty else { fatalError("Missing capture devices")}
return devices.first(where: { device in device.position == position})!
}
private func swapCameraType() {
guard let input = captureSession.inputs.first(where: { input in
guard let input = input as? AVCaptureDeviceInput else { return false }
return input.device.hasMediaType(.video)
}) as? AVCaptureDeviceInput else {return}
captureSession.beginConfiguration()
defer { captureSession.commitConfiguration() }
// Create new capture device
var newDevice : AVCaptureDevice?
if input.device.position == .back {
newDevice = bestDevice(in: .front)
} else {
newDevice = bestDevice(in: .back)
}
do {
videoInput = try AVCaptureDeviceInput(device: newDevice!)
} catch let error {
NSLog("\(error), \(error.localizedDescription)")
return
}
// Swap cature device inputs
captureSession.removeInput(input)
captureSession.addInput(videoInput!)
}
//MARK: - Recording Methods
private func startRecording() {
let connection = videoOutput.connection(with: AVMediaType.video)
// orientation 을 설정해야 가로/세로 방향에 따른 레코딩 출력이 잘 나옴
if (connection?.isVideoOrientationSupported)! {
connection?.videoOrientation = self.deviceOrientation
}
let device = videoInput.device
if device.isSmoothAutoFocusEnabled {
do {
try device.lockForConfiguration()
device.isSmoothAutoFocusEnabled = false
device.unlockForConfiguration()
} catch {
print("Error setting configuration : \(error.localizedDescription)")
}
}
recordPoint.alpha = 1
self.fadeViewInThenOut(view: recordPoint, delay: 0)
self.startTimer()
outputURL = tempURL()
videoOutput.startRecording(to: outputURL!, recordingDelegate: self)
}
private func stopRecording() {
if videoOutput.isRecording {
self.stopTimer()
videoOutput.stopRecording()
recordPoint.layer.removeAllAnimations()
}
}
private func fadeViewInThenOut(view : UIView, delay : TimeInterval) {
let animationDuration = 0.5
UIView.animate(withDuration: animationDuration, delay: delay, options: [UIView.AnimationOptions.autoreverse, UIView.AnimationOptions.repeat], animations: {
view.alpha = 0
}, completion: nil)
}
private func tempURL() -> URL? {
let directory = NSTemporaryDirectory() as NSString
if directory != "" {
let path = directory.appendingPathComponent(NSUUID().uuidString + ".mp4")
return URL(fileURLWithPath: path)
}
return nil
}
// 가속도계(자이로스코프)를 측정해서 화면이 Lock 상태에서도 orientation 구하기.
private func initMotionManager() {
motionManager = CMMotionManager()
motionManager.accelerometerUpdateInterval = 0.2
motionManager.gyroUpdateInterval = 0.2
motionManager.startAccelerometerUpdates( to: OperationQueue() ) { [weak self] accelerometerData, _ in
guard let data = accelerometerData else { return }
if abs(data.acceleration.y) < abs(data.acceleration.x) {
if data.acceleration.x > 0 {
self?.deviceOrientation = .landscapeLeft
} else {
self?.deviceOrientation = .landscapeRight
}
} else {
if data.acceleration.y > 0 {
self?.deviceOrientation = .portraitUpsideDown
} else {
self?.deviceOrientation = .portrait
}
}
}
}
//MARK: - Timer Methods
private func startTimer() {
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] timer in
guard let self = self else { return }
self.secondsOfTimer += 1
self.timerLabel.text = Double(self.secondsOfTimer).format(units: [.hour, .minute, .second])
}
}
private func stopTimer() {
timer?.invalidate()
self.timerLabel.text = "00:00:00"
}
}
//MARK: - Extension AVCaptureFileOutputRecordingDelegate
extension RecordingViewController : AVCaptureFileOutputRecordingDelegate {
// 레코딩이 시작되면 호출
func fileOutput(_ output: AVCaptureFileOutput, didStartRecordingTo fileURL: URL, from connections: [AVCaptureConnection]) {
}
// 레코딩이 끝나면 호출
func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {
print("하하 레코딩 끝남")
}
}
extension Double {
func format(units: NSCalendar.Unit) -> String {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
formatter.allowedUnits = units
formatter.zeroFormattingBehavior = [ .pad ]
return formatter.string(from: self)!
}
}
<file_sep>/README.md
# AVFoundation_Tutorials
AVFoundation 을 이용한 카메라 영상 관련 공부
1. [기본 커스텀 카메라](https://github.com/ByoungilYoun/AVFoundation_Tutorials/blob/main/CustomCamera/CustomCamera/MainViewController.swift)
<file_sep>/CustomCamera/CustomCamera/MainViewController.swift
//
// MainViewController.swift
// CustomCamera
//
// Created by 윤병일 on 2021/09/24.
//
import UIKit
import AVFoundation
class MainViewController : UIViewController {
//MARK: - Properties
// Capture Session
var session : AVCaptureSession?
// Photo Output
let output = AVCapturePhotoOutput()
// Video Preview
let previewLayer = AVCaptureVideoPreviewLayer()
// Shutter button
private let shutterButton : UIButton = {
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
button.layer.cornerRadius = 100 / 2
button.layer.borderWidth = 10
button.layer.borderColor = UIColor.white.cgColor
button.addTarget(self, action: #selector(didTapTakePhoto), for: .touchUpInside)
return button
}()
//MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
checkCameraPermissions()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
previewLayer.frame = view.bounds
shutterButton.center = CGPoint(x: view.frame.width / 2, y: view.frame.size.height - 100)
}
//MARK: - Functions
private func configureUI() {
view.backgroundColor = .black
view.layer.addSublayer(previewLayer)
view.addSubview(shutterButton)
}
private func checkCameraPermissions() {
switch AVCaptureDevice.authorizationStatus(for: .video) {
case .notDetermined:
// Request
AVCaptureDevice.requestAccess(for: .video) { [weak self] granted in
guard granted else {
return
}
DispatchQueue.main.async {
self?.setUpCamera()
}
}
case .restricted :
break
case .denied :
break
case .authorized :
setUpCamera()
default:
break
}
}
private func setUpCamera() {
let session = AVCaptureSession()
if let device = AVCaptureDevice.default(for: .video) {
do {
let input = try AVCaptureDeviceInput(device: device)
if session.canAddInput(input) {
session.addInput(input)
}
if session.canAddOutput(output) {
session.addOutput(output)
}
previewLayer.videoGravity = .resizeAspectFill
previewLayer.session = session
session.startRunning()
self.session = session
} catch {
print(error)
}
}
}
//MARK: - @objc func
@objc private func didTapTakePhoto() {
output.capturePhoto(with: AVCapturePhotoSettings(), delegate: self)
}
}
//MARK: - AVCapturePhotoCaptureDelegate
extension MainViewController : AVCapturePhotoCaptureDelegate {
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
guard let data = photo.fileDataRepresentation() else {
return
}
let image = UIImage(data: data)
session?.stopRunning()
let imageView = UIImageView(image: image)
imageView.contentMode = .scaleAspectFill
imageView.frame = view.bounds
view.addSubview(imageView)
}
}
<file_sep>/MyTimeLapseBuilderPractice/MyTimeLapseBuilderPractice/ViewController.swift
//
// ViewController.swift
// MyTimeLapseBuilderPractice
//
// Created by 윤병일 on 2021/11/02.
//
import UIKit
import SnapKit
import AVKit
class ViewController: UIViewController {
//MARK: - Properties
let timeLaspseBuilderButton : UIButton = {
let bt = UIButton()
bt.setTitle("Build Timelapse", for: .normal)
bt.setTitleColor(.black, for: .normal)
bt.addTarget(self, action: #selector(buildTimeLapse), for: .touchUpInside)
return bt
}()
let myProgressView : UIProgressView = {
let v = UIProgressView()
v.progress = 1
v.progressTintColor = .lightGray
return v
}()
//MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
}
//MARK: - Functions
private func configureUI() {
view.backgroundColor = .white
[timeLaspseBuilderButton, myProgressView].forEach {
view.addSubview($0)
}
timeLaspseBuilderButton.snp.makeConstraints {
$0.center.equalToSuperview()
$0.height.equalTo(30)
}
myProgressView.snp.makeConstraints {
$0.top.equalTo(timeLaspseBuilderButton.snp.bottom).offset(20)
$0.leading.equalToSuperview().offset(24)
$0.trailing.equalToSuperview().offset(-24)
}
}
private func assetList(count: Int) -> [String] {
let assetType = "jpg"
let bundle = Bundle.main
let urls = [
bundle.url(forResource: "11", withExtension: assetType)!.absoluteString,
bundle.url(forResource: "21", withExtension: assetType)!.absoluteString,
bundle.url(forResource: "31", withExtension: assetType)!.absoluteString,
// bundle.url(forResource: "white", withExtension: assetType)!.absoluteString,
// bundle.url(forResource: "blue", withExtension: assetType)!.absoluteString,
// bundle.url(forResource: "red", withExtension: assetType)!.absoluteString,
]
var assets = [String]()
for i in 1...count {
assets.append(urls[i % urls.count])
}
return assets
}
//MARK: - @objc func
@objc func buildTimeLapse(_ sender : Any) {
self.myProgressView.progress = 0
// 1분에 1장 -> 1시간 60장, 5시간 300장, 8시간 480장
// 1분에 2장 -> 1시간 120장, 5시간 600장, 8시간 960장
// 1분에 3장 -> 1시간 180장, 5시간 900장, 8시간 1440장
// 1분에 4장 -> 1시간 240장, 5시간 1200장, 8시간 1920장
let assets = assetList(count: 1920)
let timeLapseBuilder = TimeLapseBuilder(delegate: self)
let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
timeLapseBuilder.build(with: assets, atFrameRate: 30, type: .mov, toOutputPath: documentPath.appendingPathComponent("AssembledVideo.mov"))
}
}
//MARK: - TimelapseBuilderDelegate
extension ViewController : TimelapseBuilderDelegate {
func timeLapseBuilder(_ timelapseBuilder: TimeLapseBuilder, didMakeProgress progress: Progress) {
DispatchQueue.main.async {
self.myProgressView.setProgress(Float(progress.fractionCompleted), animated: true)
}
}
func timeLapseBuilder(_ timelapseBuilder: TimeLapseBuilder, didFinishWithURL url: URL) {
DispatchQueue.main.async {
let playerVC = AVPlayerViewController()
playerVC.player = AVPlayer(url: url)
self.present(playerVC, animated: true) {
self.myProgressView.setProgress(0, animated: true)
}
UISaveVideoAtPathToSavedPhotosAlbum(url.path, nil, nil, nil) // 사진 앨범에 저장
}
}
func timeLapseBuilder(_ timelapseBuilder: TimeLapseBuilder, didFailWithError error: Error) {
let alert = UIAlertController(title: "Couldn't build timelapse", message: "\(error)", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
|
013a24de2cb32ce1dabebbefa9499354256bb922
|
[
"Swift",
"Markdown"
] | 5 |
Swift
|
ByoungilYoun/AVFoundation_Tutorials
|
506fc968bdc766c243862f5d9d32db8869b99f64
|
dac7e354e29d5a045a1cc0a6e7c142b401c12f66
|
refs/heads/main
|
<file_sep>import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'angular-demo';
chaDeInputForm :string;
logoInputForm :string;
vInputForm :string;
danhSachTraLoi :cauTraLoi [] = [];
constructor() {
this.chaDeInputForm = "";
this.logoInputForm = "";
this.vInputForm = "";
}
submit() {
console.log(this.chaDeInputForm);
console.log(this.logoInputForm);
console.log(this.vInputForm);
const cauTraLoi : cauTraLoi = {
chaDe : this.chaDeInputForm,
logo : this.logoInputForm,
v : this.vInputForm
}
this.danhSachTraLoi.push(cauTraLoi);
}
}
export interface cauTraLoi {
chaDe :string;
logo :string;
v :string;
}
<file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DemoHocsinhComponent } from './demo-hocsinh/demo-hocsinh.component';
const routes: Routes = [
{ path: 'hocsinh', component: DemoHocsinhComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
3c574a2f7cc8314308ebc5dda0f8b87917e0ec43
|
[
"TypeScript"
] | 2 |
TypeScript
|
Hoann03/angular-demo
|
c21c5206b5f1b4798c9fe72cfdd06aea8f49ca4d
|
148fae37d22c9e04674b6ebb6ee3a66aa96dd03c
|
refs/heads/master
|
<file_sep>package com.daotec.demoapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
public void convert(View view) {
EditText editText = (EditText) findViewById(R.id.editText);
String amountInPounds = editText.getText().toString();
double amountInPoundsDouble = Double.parseDouble(amountInPounds);
double amountInDollarsDouble= amountInPoundsDouble * 1.3;
String amountInDollarsString = String.format("%.2f",amountInDollarsDouble);
Log.i("Amount in dollars", amountInDollarsString);
Toast.makeText(this, amountInPounds + " euros is " + amountInDollarsString + " USD", Toast.LENGTH_LONG).show();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
|
635a9be60fb75be884648e830e474ce749e49dc2
|
[
"Java"
] | 1 |
Java
|
kingdayx/Currency-Converter
|
23c5668a49655c102fc9dc1ade658a1985430ac3
|
0f04e195f091ddcc5b2a0578779496a385f46d39
|
refs/heads/master
|
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
void fun()
{
pthread_t tid = pthread_self();
char a[1024];
while(1)
{
}
}
int main()
{
int cnt = 0;
while(1)
{
int ret;
pthread_t tid;
ret = pthread_create(&tid, NULL, (void *)&fun, NULL);
if(ret == -1)
{
printf("Max: %d threads\n", cnt);
perror("ctreate\n");
}
cnt++;
}
return 0;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
void fun(void *arg)
{
//int i = *(int *)arg;
int i = (int)arg;
printf("%d\n", i);
pthread_exit((void *)i);
}
//create 10 threads, join them.
int main()
{
int ret;
int i;
//pthread_join status, fetch the value from pthread_exit
void *status;
pthread_t tid[10];
pthread_attr_t attr;
//set thread_attr joinable
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(i = 0; i < 10; i++)
{
//ret = pthread_create(&tid[i], NULL, (void *)&fun, (void *)&i);
ret = pthread_create(&tid[i], &attr, (void *)&fun, (void *)i);
if(ret)
{
perror("create");
exit(-1);
}
}
pthread_attr_destroy(&attr);
for(i = 0; i < 10; i++)
{
ret = pthread_join(tid[i], &status);
if(ret)
{
perror("join");
exit(-1);
}
printf("join %d\n", (int)status);
}
//pthread_exit(NULL);
return 0;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
void error_handling(char *msg)
{
perror(msg);
exit(0);
}
void clean()
{
printf("clean\n");
}
void fun()
{
pthread_t tid;
pthread_cleanup_push(clean, NULL);
printf("this is subthread\n");
tid = pthread_self();
printf("%u\n", tid);
pthread_exit((void *)-1);
pthread_cleanup_pop(0);
}
int main()
{
#ifdef _POSIX_THREADS
printf("OK, This OS support pthread lib\n");
#endif
pthread_t tid;
int ret;
ret = pthread_create(&tid, NULL, (void *)&fun, NULL);
if(ret)
{
error_handling("pthread create");
}
//sleep(1);
int status;
pthread_join(tid, (void *)&status);
printf("%d\n", status);
return 0;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 8888
void error_handling(char *msg)
{
perror(msg);
exit(-1);
}
int main()
{
int sock_fd;
struct sockaddr_in serv_addr;
int ret;
char message[100];
sock_fd = socket(PF_INET, SOCK_STREAM, 0);
if(sock_fd == -1)
{
error_handling("socket");
}
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
serv_addr.sin_port = htons(PORT);
ret = connect(sock_fd,(struct sockaddr *)&serv_addr, sizeof(serv_addr));
if(ret == -1)
{
error_handling("connect");
}
char msg[1024];
fgets(msg, 1024, stdin);
ret = write(sock_fd, msg, strlen(msg));
if(ret == -1)
{
error_handling("read");
}
close(sock_fd);
return 0;
}
<file_sep>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define PORT 8888
void error_handling(char *msg)
{
perror(msg);
exit(-1);
}
int main()
{
int serv_fd;
int clnt_fd;
int ret;
struct sockaddr_in serv_addr;
struct sockaddr_in clnt_addr;
socklen_t clnt_addr_size;
serv_fd = socket(PF_INET, SOCK_STREAM, 0);
if(serv_fd == -1)
{
error_handling("socket");
}
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);
serv_addr.sin_port=htons(PORT);
ret = bind(serv_fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
if(ret == -1)
error_handling("bind");
ret = listen(serv_fd, 5);
if(ret == -1)
error_handling("listen");
clnt_addr_size = sizeof(clnt_addr);
clnt_fd = accept(serv_fd, (struct sockaddr *)&clnt_addr, &clnt_addr_size);
if(clnt_fd == -1)
error_handling("accept");
write(clnt_fd, "hello", sizeof("hello"));
sleep(4);
close(clnt_fd);
close(serv_fd);
return 0;
}
<file_sep>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define PORT 8888
#define QUEUE 10
#define BUFSIZE 4096
void error_handling(char *msg)
{
perror(msg);
exit(0);
}
int main()
{
int serv_fd;
struct sockaddr_in serv_addr;
int ret;
serv_fd = socket(PF_INET, SOCK_STREAM, 0);
if(serv_fd == -1)
{
error_handling("socket");
}
memset((void *)&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(PORT);
ret = bind(serv_fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
if(ret == -1)
{
close(serv_fd);
error_handling("bind");
}
ret = listen(serv_fd, QUEUE);
if(ret == -1)
{
close(serv_fd);
error_handling("listen");
}
char message[BUFSIZE];
while(1)
{
int clnt_fd;
struct sockaddr_in clnt_addr;
socklen_t len = sizeof(clnt_addr);
clnt_fd = accept(serv_fd, (struct sockaddr *)&clnt_addr, &len);
if(clnt_fd == -1)
{
close(serv_fd);
error_handling("accept");
}
printf("ok accept\n");
int n = read(clnt_fd, message, BUFSIZE);
if(n)
{
message[n] = '\0';
printf("%s", message);
}
memset(message, 0 , BUFSIZE);
close(clnt_fd);
}
close(serv_fd);
return 0;
}
|
07c7c1288d0544fea06b5a3f3a9d01e4fc57ec8a
|
[
"C"
] | 6 |
C
|
gzq/network
|
ae8267e37cbe0eec0b2e4c828e90d619441f581c
|
14aa5ac4a40b56818e70816d4fd0d0c7ab67a3ca
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FriendshipFinder.Models;
using System.IO;
using FriendshipFinder.Models.ViewModel;
namespace FriendshipFinder.Controllers
{
public class ProfileController : Controller
{
GerardJennyEntities db;
public ActionResult Index()
{
if (Session["Login"] != null)
{
int UserId = Convert.ToInt32(Session["Login"]);
using (db = new GerardJennyEntities())
{
var num = from p in db.Posts
join u in db.Users
on p.UserID equals u.ID into bases
from sb in bases.DefaultIfEmpty()
where p.UserID == UserId
orderby p.PostID descending
select new PostUser
{
PostID = p.PostID,
PostedOn = p.PostedOn,
Likes = p.Likes,
Dislikes = p.Dislikes,
Photo = p.Photo,
Description = p.Description,
UserID = p.UserID,
ID = sb.ID,
Name = sb.Name,
ProfilePicture = sb.ProfilePicture,
video=p.video,
};
return View(num.ToList());
}
}
return RedirectToAction("Index", "User");
}
[HttpPost]
public ActionResult Index(FormCollection form, HttpPostedFileBase videos)
{
Post timeline = new Post();
string fileName = "";
int UserId = Convert.ToInt32(Session["Login"]);
using (db = new GerardJennyEntities())
{
try
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
if (file != null && file.ContentLength > 0)
{
fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("/Uploads/Images/"), fileName);
timeline.Photo = timeline.Photo + fileName;
if (i == Request.Files.Count - 2)
{
file.SaveAs(path);
break;
}
else
{
timeline.Photo += ",";
}
file.SaveAs(path);
}
}
if (videos != null && videos.ContentLength > 0)
{
var vidName = Path.GetFileName(videos.FileName);
var path = Path.Combine(Server.MapPath("/Uploads/Videos/"), vidName);
videos.SaveAs(path);
if (timeline.Photo == vidName + ",")
{
timeline.Photo = null;
}
timeline.video = vidName;
}
if (ModelState.IsValid)
{
timeline.Description = form["texts"];
timeline.PostedOn = DateTime.Now;
timeline.UserID = UserId;
db.Posts.Add(timeline);
db.SaveChanges();
}
}
catch
{
ViewData["ERROR"] = "Something went wrong!";
}
var num = from p in db.Posts
join u in db.Users
on p.UserID equals u.ID into bases
from sb in bases.DefaultIfEmpty()
where p.UserID == UserId
orderby p.PostID descending
select new PostUser
{
PostID = p.PostID,
PostedOn = p.PostedOn,
Likes = p.Likes,
Dislikes = p.Dislikes,
Photo = p.Photo,
video = p.video,
Description = p.Description,
UserID = p.UserID,
ID = sb.ID,
Name = sb.Name,
ProfilePicture = sb.ProfilePicture,
};
return View(num.ToList());
}
}
public ActionResult About()
{
if (Session["Login"] != null)
{
return View();
}
return RedirectToAction("Index", "User");
}
private void UpdateLikes(int post)
{
var count = (from PostLike in db.PostLikes where PostLike.PostId == post select PostLike).Count();
Post p = (from x in db.Posts
where x.PostID == post
select x).First();
p.Likes = count;
db.SaveChanges();
}
public ActionResult Likes(int post, int user)
{
bool query;
int UserId = Convert.ToInt32(Session["Login"]);
using (db = new GerardJennyEntities())
{
query = (from PostLike in db.PostLikes where PostLike.PostId == post && PostLike.UserId == user select PostLike).Any();
if (query == false)
{
PostLike postlike = new PostLike();
postlike.PostId = post;
postlike.UserId = user;
db.PostLikes.Add(postlike);
db.SaveChanges();
UpdateLikes(post);
}
else
{
ViewData["Exists"] = "You Already liked this post!";
}
var num = from p in db.Posts
join u in db.Users
on p.UserID equals u.ID into bases
from sb in bases.DefaultIfEmpty()
where p.UserID == UserId
orderby p.PostID descending
select new PostUser
{
PostID = p.PostID,
PostedOn = p.PostedOn,
Likes = p.Likes,
Dislikes = p.Dislikes,
Photo = p.Photo,
Description = p.Description,
UserID = p.UserID,
ID = sb.ID,
Name = sb.Name,
ProfilePicture = sb.ProfilePicture,
video = p.video,
};
return Json(num.ToList(), JsonRequestBehavior.AllowGet);
}
}
private void UpdateDisLikes(int post)
{
var count = (from PostDislike in db.PostDislikes where PostDislike.PostId == post select PostDislike).Count();
Post p = (from x in db.Posts
where x.PostID == post
select x).First();
p.Dislikes = count;
db.SaveChanges();
}
public ActionResult DisLikes(int post, int user)
{
bool query;
int UserId = Convert.ToInt32(Session["Login"]);
using (db = new GerardJennyEntities())
{
query = (from PostDislike in db.PostDislikes where PostDislike.PostId == post && PostDislike.UserId == user select PostDislike).Any();
if (query == false)
{
PostDislike postdislike = new PostDislike();
postdislike.PostId = post;
postdislike.UserId = user;
db.PostDislikes.Add(postdislike);
db.SaveChanges();
UpdateDisLikes(post);
}
else
{
ViewData["Exists"] = "You Already liked this post!";
}
var num = from p in db.Posts
join u in db.Users
on p.UserID equals u.ID into bases
from sb in bases.DefaultIfEmpty()
where p.UserID == UserId
orderby p.PostID descending
select new PostUser
{
PostID = p.PostID,
PostedOn = p.PostedOn,
Likes = p.Likes,
Dislikes = p.Dislikes,
Photo = p.Photo,
Description = p.Description,
UserID = p.UserID,
ID = sb.ID,
Name = sb.Name,
ProfilePicture = sb.ProfilePicture,
video = p.video,
};
return Json(num.ToList(), JsonRequestBehavior.AllowGet);
}
}
public ActionResult DisplayComment(int id)
{
using (db = new GerardJennyEntities())
{
var postComment = from c in db.PostComments
join u in db.Users
on c.UserId equals u.ID into bases
from sb in bases.DefaultIfEmpty()
where c.PostId == id
select new CommentUser
{
CommentID = c.ID,
Description = c.Description,
PostId = c.PostId,
UserId = c.UserId,
ID = sb.ID,
Name = sb.Name,
};
return PartialView("_Comment", postComment.ToList());
}
}
[HttpPost]
public ActionResult Comment(int Commentpost, int CommentUser, string description)
{
int UserId = Convert.ToInt32(Session["Login"]);
using (db = new GerardJennyEntities())
{
PostComment comment = new PostComment();
comment.Description = description;
comment.PostId = Convert.ToInt32(Commentpost);
comment.UserId = Convert.ToInt32(CommentUser);
db.PostComments.Add(comment);
db.SaveChanges();
var num = from p in db.Posts
join u in db.Users
on p.UserID equals u.ID into bases
from sb in bases.DefaultIfEmpty()
where p.UserID == UserId
orderby p.PostID descending
select new PostUser
{
PostID = p.PostID,
PostedOn = p.PostedOn,
Likes = p.Likes,
Dislikes = p.Dislikes,
Photo = p.Photo,
Description = p.Description,
UserID = p.UserID,
ID = sb.ID,
Name = sb.Name,
ProfilePicture = sb.ProfilePicture,
video = p.video,
};
return Json(num.ToList(), JsonRequestBehavior.AllowGet);
}
}
public ActionResult Introduction()
{
if (Session["Login"] != null)
{
using (db = new GerardJennyEntities())
{
var num = from w in db.Writings
join u in db.Users
on w.UserId equals u.ID into bases
from sb in bases.DefaultIfEmpty()
orderby w.ContentID descending
select new ContentUser
{
ContentID = w.ContentID,
Description = w.Description,
UserId = w.UserId,
ID = sb.ID,
Name = sb.Name,
ProfilePicture = sb.ProfilePicture,
};
return View(num.ToList());
}
}
return RedirectToAction("Index", "User");
}
[HttpPost]
public ActionResult Introduction(FormCollection form)
{
int UserId = Convert.ToInt32(Session["Login"]);
using (db = new GerardJennyEntities())
{
Writing write = new Writing();
write.Description = form["texts"];
write.UserId = UserId;
db.Writings.Add(write);
db.SaveChanges();
var num = from w in db.Writings
join u in db.Users
on w.UserId equals u.ID into bases
from sb in bases.DefaultIfEmpty()
orderby w.ContentID descending
select new ContentUser
{
ContentID = w.ContentID,
Description = w.Description,
UserId = w.UserId,
ID = sb.ID,
Name = sb.Name,
ProfilePicture = sb.ProfilePicture,
};
return View(num.ToList());
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FriendshipFinder.Models;
namespace FriendshipFinder.Controllers
{
public class UserController : Controller
{
GerardJennyEntities db;
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(FormCollection form)
{
using (db=new GerardJennyEntities())
{
User user = new User();
var Username = form["username"];
var Password = form["<PASSWORD>"];
var queryId = (from User in db.Users where User.Email == Username && User.Password == <PASSWORD> select User.ID).FirstOrDefault();
var queryName = (from User in db.Users where User.Email == Username && User.Password == <PASSWORD> select User.Name).FirstOrDefault();
var queryImage = (from User in db.Users where User.Email == Username && User.Password == <PASSWORD> select User.ProfilePicture).FirstOrDefault();
if (queryId != 0)
{
Session["Login"] = queryId;
Session["Name"] = queryName;
Session["ProfileImage"] = queryImage;
return RedirectToAction("Index", "Home");
}
else
{
ViewData["LoginError"]="Username or Password is incorrect!";
}
}
return View();
}
public ActionResult Logout()
{
if (Session["Login"] != null)
{
Session.Remove("Login");
}
return RedirectToAction("Index", "User");
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace FriendshipFinder.Models.ViewModel
{
public class CommentUser
{
public int CommentID { get; set; }
public string Description { get; set; }
public Nullable<int> PostId { get; set; }
public Nullable<int> UserId { get; set; }
public int ID { get; set; }
public string Name { get; set; }
public string ProfilePicture { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace FriendshipFinder.Models.ViewModel
{
public class PostUser
{
public int PostID { get; set; }
public Nullable<System.DateTime> PostedOn { get; set; }
public Nullable<int> Likes { get; set; }
public Nullable<int> Dislikes { get; set; }
public string Photo { get; set; }
public string Description { get; set; }
public Nullable<int> UserID { get; set; }
public int ID { get; set; }
public string Name { get; set; }
public string ProfilePicture { get; set; }
public string video { get; set; }
}
}
|
ed8375bbc6459744e5c357c8c2626eecd331205d
|
[
"C#"
] | 4 |
C#
|
ayeshaa/FriendshipFinder
|
43b1069e61f4a82c65439f3faa2a331e7e08702e
|
57e41f352f908b4cf2fc7cf36ddb8157831f3e5d
|
refs/heads/master
|
<repo_name>jinyphp/polyglot<file_sep>/test/index.php
<?php
require '../../../../vendor/autoload.php';
$msg = polyglot();
$msg->enableTrans("transkey.php");
$str = "오류가 발생하였습니다.";
echo $msg->echo($str,"en");
<file_sep>/src/Trans.php
<?php
/*
* This file is part of the jinyPHP package.
*
* (c) hojinlee <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Jiny\Polyglot;
use Google\Cloud\Translate\TranslateClient;
trait Trans
{
private $_apikey;
/**
* 번역을 활성화 합니다.
*/
public function enableTrans($keyfile)
{
if (file_exists($keyfile)) {
// 외부에서 구글 키를 가지고 옵니다.
$this->_apikey = include $keyfile;
}
return $this;
}
/**
* 자동번역을 실행합니다.
*/
public function trans($str, $lang)
{
// API 키가 존재할경우
// Lang 코드가 "str" 아닌경우
if ($this->_apikey && $lang != "str") {
$google = new TranslateClient($this->_apikey);
$result = $google->translate($str, [
'target' => $lang
]);
return $result['text'];
} else {
// 번역을 할 수 없는 경우 입력값 반환
return $str;
}
}
/**
*
*/
}<file_sep>/src/Text.php
<?php
namespace Jiny\Polyglot;
class Text
{
// 번역 문자열
public $text;
// 변경일자
public $timestamp;
// 작성자
public $email;
public $default;
/**
* 문자열을 초기화 합니다.
*/
public function __construct($text=null)
{
$this->text = $text;
$this->timestamp = time();
}
/**
*
*/
}<file_sep>/src/Helpers/Helper.php
<?php
/*
* This file is part of the jinyPHP package.
*
* (c) hojinlee <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
if (! function_exists('polyglot')) {
function polyglot($path=null)
{
return \Jiny\Polyglot\Message::instance($path);
//$obj = new \Jiny\Polyglot\Message($path);
//return $obj;
}
}
/*
if (! function_exists('msg_init')) {
function _msg_init($path=null)
{
$obj = new \Jiny\Polyglot\Message($path);
return $obj;
}
}
*/<file_sep>/README.md
# polyglot
`jiny/polyglot`은 파일기반의 다국어 메시지를 처리할 수 있는 문자열 관리 패키지 입니다.
## 다국어 처리
---
소스코드의 변경없이 다국어를 처리할 수 있습니다.
## 자동번역
---
다국어 처리를 위하여 `구글번역 API`를 지원합니다.<file_sep>/transkey.php
<?php
/**
* 구글 API 설정파일
*/
return [
'key' => '<KEY>'
];<file_sep>/src/Message.php
<?php
/*
* This file is part of the jinyPHP package.
*
* (c) hojinlee <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Jiny\Polyglot;
class Message
{
use Trans;
/**
* 인스턴스 생성
*/
public static $Instance;
public static function instance($path=null)
{
if (!isset(self::$Instance)) {
self::$Instance = new self();
if ($path) {
self::$Instance->setPath($path);
} else {
self::$Instance->initPath();
}
return self::$Instance;
} else {
// 인스턴스가 중복
return self::$Instance;
}
}
public $_path;
private $_sha = "sha3-512";
public $fromLanguage = "en";
public $toLanguage = "ko";
private $key;
public $trans = [];
public $count = 0;
public $total = 0;
private function getHistory($json, $language=null)
{
if(!$language) $language = $this->toLanguage;
// 언어객체를 반환합니다.
if (isset($json[$language])) {
return $json[$language];
}
return false;
}
public function makeTransText($str, $language=null, $text=null)
{
if(!$language) $language = $this->toLanguage;
if(!$text) {
// 구글번역
$text = $this->trans($str, $language);
$obj = $this->factory($text); // 새롭게 생성
$obj->email = "google";
} else {
$obj = $this->factory($text); // 새롭게 생성
}
$json['language'] = $this->fromLanguage;
$json['text'] = $str;
$json['key'] = $this->key;
$json[$language]=[];
array_unshift($json[$language], $obj); // 배열 앞에 추가
// 저장합니다.
$this->save($str, $json);
return $json[$language];
}
/**
* 문자열을 반환합니다.
*/
public function echo($str, $language=null)
{
$this->total++; // 전체 번역갯수
if(!$language) $language = $this->toLanguage;
// 파일이 존재하는 경우
if ($json = $this->load($str)) {
$history = $this->getHistory($json, $language);
if(!$history) {
// 번역 기록이 없는 경우
$history = $this->makeTransText($str, $language);
}
$this->count++; // 번역한 갯수
} else {
// 파일이 없는 경우
// 기존 텍스트 반환
return $str;
//새롭게 저장
//$history = $this->makeTransText($str, $language);
}
//
// 기록이 1개만 있는 경우
if (is_object($history)) {
return $history->text;
} else
if (is_array($history)) {
if (empty($history)) {
// 비어있는 배열일 경우 : 기록을 모두 삭제한 경우 발생...
// 다시 생성
$history = $this->makeTransText($str, $language);
}
if(isset($history[0])) {
if(is_object($history[0])) {
return $history[0]->text;
} else
if(is_array($history[0])) {
return $history[0]['text'];
}
}
}
return false;
}
public function factory($text)
{
return new \Jiny\Polyglot\Text($text);
}
/**
* 패스 경로를 초기화 합니다.
*/
public function initPath()
{
// 기본 설정경로를 초기화 합니다.
if (!is_dir("resource")) {
mkdir("resource");
}
if (!is_dir("resource/polyglot")) {
mkdir("resource/polyglot");
}
$this->_path = "resource/polyglot";
}
/**
* 경로를 설정합니다.
*/
public function setPath($path)
{
$this->_path = $path;
$this->is_path($path);
}
/**
* 경로를 확인, 생성합니다.
*/
public function is_path($path)
{
$p = explode(DIRECTORY_SEPARATOR, $path);
$temp = "";
foreach ($p as $dir) {
$temp .= $dir;
if (!is_dir($temp)) {
mkdir($temp);
}
$temp .= DIRECTORY_SEPARATOR;
}
return true;
}
/**
* sha 서브경로를 생성합니다.
*/
public function sha1_path($sha)
{
$key = substr($sha,0,4).DIRECTORY_SEPARATOR;
$key .= substr($sha,4,4).DIRECTORY_SEPARATOR;
$key .= substr($sha,8,4);
$this->key = $key;
return $key;
}
/**
* 문자열 해쉬 파일명을 생성합니다.
*/
public function filename($str)
{
return hash($this->_sha, $str);
}
public function setSHA($_sha)
{
$this->_sha = $_sha;
}
/**
* 문자열 파일저장
*/
public function save($str, $json)
{
$filename = $this->filename($str);
$key = $this->sha1_path($filename);
if($this->is_path($this->_path.DIRECTORY_SEPARATOR.$key)) {
file_put_contents(
$this->_path.DIRECTORY_SEPARATOR.$key.DIRECTORY_SEPARATOR.$filename.".msg",
json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
);
return $str;
}
return false;
}
/**
* 해쉬 문자열 데이터를 읽어 옵니다.
*/
public function load($str)
{
// 파일경로와 파일명을 계산합니다.
$filename = $this->filename($str);
$key = $this->sha1_path($filename);
//if($this->is_path($this->_path.DIRECTORY_SEPARATOR.$key)) {
$filename = $this->_path.DIRECTORY_SEPARATOR.$key.DIRECTORY_SEPARATOR.$filename.".msg";
if (file_exists($filename)) {
// 파일이 존재하는 경우
$a = file_get_contents($filename);
return json_decode($a, true); //
}
//}
return false;
}
/**
* 리소스 파일을 삭제합니다.
*/
public function remove($str)
{
// 파일경로와 파일명을 계산합니다.
$filename = $this->filename($str);
$key = $this->sha1_path($filename);
$this->is_path($this->_path.DIRECTORY_SEPARATOR.$key);
$filename = $this->_path.DIRECTORY_SEPARATOR.$key.DIRECTORY_SEPARATOR.$filename.".msg";
if (file_exists($filename)) {
// 파일이 존재하는 경우, 삭제함
unlink($filename);
}
}
/**
*
*/
}
|
7d74f8dbfc07dabe74fabf5d8e928fbde6ca36c0
|
[
"Markdown",
"PHP"
] | 7 |
PHP
|
jinyphp/polyglot
|
1bac7963065a509dc684b580d4ff60a33a98f4c6
|
4f5eb459138fd2e55f798a9f3545f68c48b2251b
|
refs/heads/main
|
<repo_name>jorgetrad99/tec-pagos-v1<file_sep>/views/home.php
<?php
include '../layouts/header.php';
?>
<!-- Main Site Section -->
<main>
<!-- Site Title -->
<section class="site-title">
<div class="site-background">
<h3>Sistema de Pagos Electrónicos de Servicios Escolares</h3>
<br><br><br><br>
<h1>Bienvenido a SPESE</h1>
<br><br>
<h3>La nueva forma de pagar servicios escolares</h3>
<!-- <button class="btn">Explore</button> -->
<br>
<br>
<iframe width="360" height="315" src="https://www.youtube.com/embed/5AsUv_biS74" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</section>
<!-- --x--Site Title--x-- -->
<!-- ---------- Site Content ---------- -->
<!-- -----x----- Site Content -----x----- -->
</main>
<!-- Jquery Library File -->
<script src="../js/jquery3.5.1.min.js"></script>
<script src="../js/main.js"></script>
</body>
<!-- ----x--- Main Site Section ---x---- -->
<?
include '../layouts/footer.php';<file_sep>/views/inicio-sesion.php
<?php
include '../layouts/header.php';
?>
<!-- Main Site Section -->
<link rel="stylesheet" href="../css/formulario.css">
<main>
<!-- ---------- Site Content ---------- -->
<section class="site-title">
<div class="wrapper">
<div class="title">
Inicio de Sesión</div>
<form action="#">
<div class="field">
<input type="number" min="0" max="99999999" required>
<label>Número de Control</label>
</div>
<div class="field">
<input type="password" required>
<label>Contraseña</label>
</div>
<div class="content">
<div class="checkbox">
<input type="checkbox" id="remember-me">
<label for="remember-me">Recuerdame</label>
</div>
<div class="pass-link">
<a href="#">¿Olvidaste tu contraseña?</a>
</div>
</div>
<div class="field">
<input type="submit" value="Iniciar sesión">
</div>
<div class="signup-link">
¿No tienes cuenta? <a href="./registro.php">Crear cuenta</a></div>
</form>
</div>
</section>
<!-- -----x----- Site Content -----x----- -->
</main>
<!-- Jquery Library File -->
<script src="../js/jquery3.5.1.min.js"></script>
<script src="../js/main.js"></script>
</body>
<!-- ----x--- Main Site Section ---x---- -->
<?
include '../layouts/footer.php';<file_sep>/views/registro.php
<?php
include '../layouts/header.php';
?>
<!-- Main Site Section -->
<link rel="stylesheet" href="../css/formulario.css">
<main>
<!-- ---------- Site Content ---------- -->
<section class="site-title">
<div class="wrapper">
<div class="title">
Crea tu cuenta</div>
<form action="#">
<div class="field">
<input type="text" required>
<label>Nombre(s)</label>
</div>
<div class="field">
<input type="text" required>
<label>Apellido Paterno</label>
</div>
<div class="field">
<input type="text" required>
<label>Apellido Materno</label>
</div>
<div class="field">
<input type="number" min="0" max="99999999" required>
<label>Número de Control</label>
</div>
<div class="field">
<input type="email" required>
<label>Correo Institucional</label>
</div>
<div class="field">
<input type="password" required>
<label>Contraseña</label>
</div>
<div class="field">
<input type="password" required>
<label>Repita la contraseña</label>
</div>
<div class="field">
<input type="submit" value="Crear Cuenta">
</div>
</form>
</div>
</section>
<!-- -----x----- Site Content -----x----- -->
</main>
<!-- Jquery Library File -->
<script src="../js/jquery3.5.1.min.js"></script>
<script src="../js/main.js"></script>
</body>
<!-- ----x--- Main Site Section ---x---- -->
<?
include '../layouts/footer.php';
|
b47a7fe26fad1d41a060b9207123f2e961cfb45a
|
[
"PHP"
] | 3 |
PHP
|
jorgetrad99/tec-pagos-v1
|
047059d4532c469caf8c77087ec1aa90424e970c
|
b6d468fd8a8372877037f0ee64469026af36d9b8
|
refs/heads/master
|
<file_sep>import os
import pyglet as pg
"""
screen_width = 1280
screen_height = 720
pg.init()
screen = pg.display.set_mode((screen_width,screen_height))
BLACK = (0,0,0)
"""
def load_all_gfx(directory, colorkey=(255,0,255), accept=('.png', 'jpg', 'bmp')):
graphics = {}
for pic in os.listdir(directory):
name, ext = os.path.splitext(pic)
if ext.lower() in accept:
img = pg.image.load(os.path.join(directory, pic))
graphics[name]=img
return graphics
GFX= load_all_gfx(os.path.abspath("graphics"))
|
18a5ab832cd5d363ed3978907d871570703e6692
|
[
"Python"
] | 1 |
Python
|
forhad111/Mario_Game
|
e0180062045238ee59a707b48128b5d5c89f02c9
|
45210944510883e9afed49c17bf1c683ab1b7d53
|
refs/heads/main
|
<repo_name>kalbzero/react-azure-express-typeorm<file_sep>/server/src/routes/categories.router.ts
/**
* Required External Modules and Interfaces
*/
import express, { Request, Response } from "express";
import * as categoriesService from "../service/categories.service";
import { CategoryInterface, BaseCategory } from '../interfaces/category';
/**
* Router Definition
*/
export const categoriesRouter = express.Router();
/**
* Controller Definitions
*/
// GET categories
categoriesRouter.get("/", async (req: Request, res: Response) => {
try {
const categories: CategoryInterface[] = await categoriesService.findAll();
res.status(200).send(categories);
} catch (e: any) {
res.status(500).send(e.message);
}
});
// GET categories/:id
categoriesRouter.get("/:id", async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10);
try {
const category: CategoryInterface | undefined = await categoriesService.find(id);
if (category) {
return res.status(200).send(category);
}
res.status(404).send("category ["+ id +"] not found");
} catch (e: any) {
res.status(500).send(e.message);
}
});
// POST categories
categoriesRouter.post("/", async (req: Request, res: Response) => {
try {
const category: BaseCategory = req.body;
const newCategory = await categoriesService.create(category);
res.status(201).json(newCategory);
} catch (e: any) {
res.status(500).send(e.message);
}
});
// PUT categories/:id
categoriesRouter.put("/:id", async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10);
try {
const categoryUpdate: CategoryInterface = req.body;
const existingCategory: CategoryInterface | undefined = await categoriesService.find(id);
if (existingCategory) {
const updatedCategory = await categoriesService.update(id, categoryUpdate);
return res.status(200).json(updatedCategory);
}
const newCategory = await categoriesService.create(categoryUpdate);
res.status(201).json(newCategory);
} catch (e: any) {
res.status(500).send(e.message);
}
});
// DELETE categories/:id
categoriesRouter.delete("/:id", async (req: Request, res: Response) => {
try {
const id: number = parseInt(req.params.id, 10);
await categoriesService.remove(id);
res.sendStatus(204);
} catch (e: any) {
res.status(500).send(e.message);
}
});<file_sep>/web/src/interfaces/log.ts
import { Course } from './course';
import { File } from './file';
export interface Log {
id: string;
id_user: string;
id_course: Course;
id_file: File;
progress: string;
}
<file_sep>/web/src/interfaces/search.ts
export interface Search {
id: string;
name: string;
createdBy: string;
url?: string;
type?: string;
}
<file_sep>/server/README.md
# API Classroom
Este proejto foi criado para gerenciar as informações dos cursos e arquivos no sistema NLClassroom.
Programador Criador: <NAME>
## Executando o projeto
Após clonar o projeto do gitlab, entrar na pasta do projeto (server), executar `npm run dev`, o backend irá rodar na porta 7000.
## Documentação
A base dessa API foi feita através desse <a href="https://auth0.com/blog/node-js-and-typescript-tutorial-build-a-crud-api/">tutotial</a>.
### 0. Erros
### 0.1 QueryFailedError: Table 'nl_cr_categories_files' already exists
No arquivo ormconfig, altere a variável `syncronize` para `false` enquanto estiver em desenvolvimento. Quando quiser recriar as tabelas, apague as tabelas no banco e altere essa variável para `true`. Essa variável fica dentro da configuração do Banco, então em cada objeto do array vai ter essa variavel, altere apenas no banco que estiver usando.
### 1. Linguagens e ferramentas
<a href="https://nodejs.org" target="_blank"> <img src="https://raw.githubusercontent.com/devicons/devicon/master/icons/nodejs/nodejs-original-wordmark.svg" alt="nodejs" width="40" height="40"/> </a> <a href="https://expressjs.com" target="_blank"> <img src="https://raw.githubusercontent.com/devicons/devicon/master/icons/express/express-original-wordmark.svg" alt="express" width="40" height="40"/> </a> <a href="https://www.typescriptlang.org/" target="_blank"> <img src="https://raw.githubusercontent.com/devicons/devicon/master/icons/typescript/typescript-original.svg" alt="typescript" width="40" height="40"/> </a> <a href="https://www.oracle.com/" target="_blank"> <img src="https://raw.githubusercontent.com/devicons/devicon/master/icons/oracle/oracle-original.svg" alt="oracle" width="40" height="40"/> </a>
### 1.1 TypeORM
Ao instalar o typeorm, foi necessário instalar outra biblioteca e importada no index.ts `import "reflect-metadata";`, ela é improtante para o funcioanemnto do TypeORm, não apague!
No arquivo `tsconfig.json`, descomente esses dois campos:
- "emitDecoratorMetadata": true,
- "experimentalDecorators": true,
Existe um arquivo que fica na raiz do projeto chamado `ormconfig.json`, este arquivo fica armazenado os dados de conexão com o banco de dados, para teste eu deixei a configuração do MySQL e para produção a configuração do Oracle.
Quando estiver usando multiplas conexões, precisa indicar qual delas irá usar, com isso, passando essa informaçaõ no parâmetro `createConnection(/* 'prod' */ )`, neste exemplo o parâmetro está comentado, pois por default ele carrega o arquivo que não tem um atributo `name` ou que tenha um atributo `name` com o valor `default`. Este comando é chamado uma vez no `index.ts` e nos services é usado o `getRepository()` para fazer as consultas e inserções no banco de dados.
### 1.2 Oracle
A configuração do Oracle no backend é bem peculiar, tendo uma configuração mais complexa que está neste <a href="https://github.com/oracle/node-oracledb">link</a> e neste <a href="https://oracle.github.io/node-oracledb/INSTALL.html#windowsinstallation">link</a> para rodar no Windows.
### 1.3 MySQL2
Existem duas bibliotecas para MySQl, o `mysql` e o `mysql2`, a segunda biblioteca possui uma perfomance melhor do que a primeira, segundo esse <a href="https://stackoverflow.com/questions/25344661/what-is-the-difference-between-mysql-mysql2-considering-nodejs">link</a>.
Para rodar local, crie a database `nlclassroom` e o TypeORM irá fazer o resto do serviço.
### 2. Entity
A pasta entity armazena as classes usadas pelo TypeORM para criar as tabelas, colunas e os relacionamentos. Esses arquivos são usados no Service para especificar a tabela a ser consultada. Os comandos mais comuns nestes arquivos são:
- Entity: Define que o arquivo irá ser uma tabela.
- Column: Define que aquele atributo será usado como coluna na tabela a ser criada.
- PrimaryGeneratedColumn: Define a coluna como chave primária e auto geradora.
- JoinTable: Define que essa tabela tem relação com outra, a coluna irá armazenar a chave estrangeira, ter uma lista de chaves estrangeiras ou definir a tabela que é proprietária da relação (no caso de um `@ManyToMany`).
- OneToMany: A coluna irá armazenar uma lista de chaves estrangeiras.
- ManyToOne: A coluna armazena a chave estrangeira (aqui não precisa colocar `@JoinEntity`).
- ManyToMany: Cria uma terceira tabela com esse relacionamento. Ambos os arquivos Entity devem ter esse comando e em apenas um deles deve ter o `@JoinEntity`.
### 2.1 Migration
A migration é apenas um único arquivo com consultas sql para atualizar um esquema de banco de dados e aplicar novas alterações a um banco de dados existente (alterar tabela, coluna ...). Neste projeto não será necessário utilizar, pois as tabelas da NL são gerenciadas pelo CS.
### 2.2 Subscriber
O <a href="https://github.com/typeorm/typeorm/blob/master/docs/listeners-and-subscribers.md">subscriber</a> é o comando para escutar(listener) os eventos. Se você quer escutar os eventos de uma classe da Entity, crie um arquivo (ex:log.subscriber.ts) e coloque o comando `@EventSubscriber()` logo acima do `export class LogSubscriber implements EntitySubscriberInterface<Log>`, importando a Entity a ser escutada.
Nos arquivos Entity, coloca-se a marcação do evento a ser escutado:
```
@Entity()
export class Log {
@BeforeRemove()
updateStatus() {
this.status = "removed";
}
}
```
Os tipos de eventos são:
- @AfterLoad
- @BeforeInsert
- @AfterInsert
- @BeforeUpdate
- @AfterUpdate
- @BeforeRemove
- @AfterRemove
No arquivo Subscriber, insira o comando `listenTo()` para saber qual entity deve escutar. Logo abaixo, coloque as funções a serem executadas quando o método for chamado. Se não colocar o método `listenTo()`, este arquivo irá escutar todos os eventos do backend de qualquer Entity.
### 3. Interfaces
A pasta interfaces possui os arquivos utilizados nas requisições como usuario, arquivos, categorias, cursos e logs; com uma interface para o objeto em si (tendo id ou não) e outra para um array de objetos.
### 4. Services
A pasta Service possui as requisições pro banco de dados, com as funções find(), findAll(), create(), update() e remove().
### 5. Routes
A pasta routes armazena os caminhos das operações CRUD para cada assunto a ser requisitado.
Por padrão, todos tem as mesmas URL's, sendo elas:
- GET '/': Para pegar todos os itens.
- GET '/:id': Para pegar um item pelo identificador.
- POST '/': Para criar um objeto daquele item.
- PUT '/:id': Para atualizar o item com aquele identificador, se não achar o objeto, cria um novo.
- DELETE '/:id': Para deletar o item com aquele identificador.
No arquivo `index.ts`, esses routes são importados para definir o caminho base de cada um deles, sendo:
- "/api/nlclassroom/categories"
- "/api/nlclassroom/courses"
- "/api/nlclassroom/files"
- "/api/nlclassroom/logs"
Outros dois arquivos foram criados para tratar os erros de requisição, ambos devem ficar sempre no final destas requisições acima, pois eles funcionam como uma ideia de try/catch, caso alguma das URL's acima não sejam iguais a da requisição recebida, irá disparar um desses dois arquivos:
- errorHandler: Para tratar os erros do tipo 400 e 500.
- notFoundHandler: Para tratar o erro 404.
<file_sep>/web/src/interfaces/category.ts
export interface Category {
num_seq: string;
name: string;
}
<file_sep>/server/src/interfaces/category.ts
export interface BaseCategory {
name: string;
}
export interface CategoryInterface extends BaseCategory {
num_seq: number;
}<file_sep>/server/src/routes/file-course.router.ts
/**
* Required External Modules and Interfaces
*/
import express, { Request, Response } from "express";
import * as fileCourseService from "../service/file-course.service";
import { FileCourseInterface } from "../interfaces/file-course";
/**
* Router Definition
*/
export const fileCourseRouter = express.Router();
/**
* Controller Definitions
*/
// POST item
fileCourseRouter.post("/", async (req: Request, res: Response) => {
const body: FileCourseInterface = req.body;
try {
const existFileCourse = await fileCourseService.find(body);
if (existFileCourse.length > 0) return res.status(400).send();
const newFileCourse = await fileCourseService.create(body);
res.status(201).json(newFileCourse);
} catch (e: any) {
res.status(500).send(e.message);
}
});
<file_sep>/web/src/services/api.ts
import axios from 'axios';
export const getUrl = () => {
let url;
if (process.env.NODE_ENV === 'development') {
url = 'http://localhost:7000/api/nlclassroom/';
}
if (process.env.NODE_ENV === 'production') {
url = 'https://stackoverflow.com/';
}
return url;
};
const api = axios.create({
baseURL: getUrl(),
});
export default api;
<file_sep>/server/src/routes/courses.router.ts
/**
* Required External Modules and Interfaces
*/
import express, { Request, Response } from "express";
import * as coursesService from "../service/courses.service";
import { CourseInterface, BaseCourse } from '../interfaces/course';
/**
* Router Definition
*/
export const coursesRouter = express.Router();
/**
* Controller Definitions
*/
// GET items
coursesRouter.get("/", async (req: Request, res: Response) => {
try {
const courses: CourseInterface[] = await coursesService.findAll();
res.status(200).send(courses);
} catch (e: any) {
res.status(500).send(e.message);
}
});
/// GET items/:id
coursesRouter.get("/:id", async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10);
try {
const course: CourseInterface | undefined = await coursesService.find(id);
if (course) {
return res.status(200).send(course);
}
res.status(404).send("course ["+ id +"] not found");
} catch (e: any) {
res.status(500).send(e.message);
}
});
// POST items
coursesRouter.post("/", async (req: Request, res: Response) => {
try {
const course: BaseCourse = req.body;
const newCourse = await coursesService.create(course);
res.status(201).json(newCourse);
} catch (e: any) {
res.status(500).send(e.message);
}
});
// PUT items/:id
coursesRouter.put("/:id", async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10);
try {
const courseUpdate: CourseInterface = req.body;
const existingCourse: CourseInterface | undefined = await coursesService.find(id);
if (existingCourse) {
const updatedCourse = await coursesService.update(id, courseUpdate);
return res.status(200).json(updatedCourse);
}
const newCourse = await coursesService.create(courseUpdate);
res.status(201).json(newCourse);
} catch (e: any) {
res.status(500).send(e.message);
}
});
// DELETE items/:id
coursesRouter.delete("/:id", async (req: Request, res: Response) => {
try {
const id: number = parseInt(req.params.id, 10);
await coursesService.remove(id);
res.sendStatus(204);
} catch (e: any) {
res.status(500).send(e.message);
}
});<file_sep>/web/src/NLTheme.ts
import { createTheme, darken, lighten } from '@material-ui/core';
const mainColor = '#fc7422';
const NLTheme = createTheme({
palette: {
primary: {
main: mainColor,
contrastText: '#fff',
dark: darken(mainColor, 0.5),
light: lighten(mainColor, 0.5),
},
},
overrides: {
MuiTableBody: {
root: {
'&& .MuiTableRow-root': {
transition: 'background-color 0.2s',
'&:nth-of-type(odd)': {
backgroundColor: `rgba(0, 0, 0, 0.04)`,
},
'&:hover': {
backgroundColor: `rgba(0, 0, 0, 0.08)`,
},
},
},
},
},
});
export default NLTheme;
<file_sep>/server/src/interfaces/log.ts
export interface BaseLog {
id_user: string;
id_course: number;
id_file: number;
progress: string;
}
export interface LogInterface extends BaseLog {
num_seq: number;
}<file_sep>/server/src/entity/file-category.ts
import {
Entity,
Column,
PrimaryGeneratedColumn,
ManyToOne,
JoinColumn,
} from "typeorm";
import { Category } from "./category";
import { File } from "./file";
@Entity("NL_CR_CATEGORIES_FILES")
export class FileCategory {
@PrimaryGeneratedColumn()
num_seq: number = 0;
@ManyToOne(() => File, (file) => file.file_course, {
nullable: false,
eager: true,
})
@JoinColumn({ name: "id_file" })
file: File = {} as File;
@ManyToOne(() => Category, (category) => category.file_category, {
nullable: false,
eager: true,
})
@JoinColumn({ name: "id_category" })
category: Category = {} as Category;
@Column()
id_category: number = 0;
@Column()
id_file: number = 0;
}
<file_sep>/server/src/entity/file-course.ts
import {
Entity,
Column,
PrimaryGeneratedColumn,
ManyToOne,
JoinColumn,
} from "typeorm";
import { Course } from "./course";
import { File } from "./file";
@Entity("NL_CR_COURSES_FILES")
export class FileCourse {
@PrimaryGeneratedColumn()
num_seq: number = 0;
@ManyToOne(() => File, (file) => file.file_course, {
nullable: false,
eager: true,
})
@JoinColumn({ name: "id_file" })
file: File = {} as File;
@ManyToOne(() => Course, (course) => course.file_course, {
nullable: false,
eager: true,
})
@JoinColumn({ name: "id_course" })
course: Course = {} as Course;
@Column()
id_course: number = 0;
@Column()
id_file: number = 0;
}
<file_sep>/web/src/interfaces/course.ts
import { Category } from './category';
export interface Course {
num_seq: string;
name: string;
createdBy: string;
id_category: Category;
}
<file_sep>/server/src/interfaces/file-course.ts
export interface FileCourseInterface {
id_file: number;
id_course: number;
}<file_sep>/README.md
# react-azure-express-typeorm
Projeto que usa as tecnologias de React, Tailwind, API Azure para Login e Material-UI no Frontend; e no Backend NodeJs, Express e TypeORM
<file_sep>/server/src/service/home.service.ts
/**
* Data Model Interfaces
*/
import { Search } from '../interfaces/search';
import { Course } from '../entity/course';
import { getRepository, Like } from 'typeorm';
/**
* Service Methods
*/
export const find = async (searchTerm: string = ''): Promise<Course[]> => {
let list:any[] =[];
if(searchTerm == ''){
return list;
} else {
list = await getRepository(Course).find({
where: {
name: Like(`%${searchTerm}%`),
},
order: {
name: 'ASC'
}
});
return list;
}
};<file_sep>/server/src/interfaces/file.ts
export interface BaseFile {
name: string;
url: string;
}
export interface FileInterface extends BaseFile {
num_seq: number;
}<file_sep>/server/src/entity/file.ts
import { Entity, Column, PrimaryGeneratedColumn, OneToMany } from "typeorm";
import { FileCourse } from './file-course';
import { FileCategory } from './file-category';
@Entity('NL_CR_FILES')
export class File {
@PrimaryGeneratedColumn()
num_seq: number = 0;
@Column({ length: 200 })
name: string = '';
@Column({ length: 200 })
url: string = '';
@OneToMany(() => FileCourse, file_course => file_course.file)
file_course? : FileCourse[];
@OneToMany(() => FileCategory, file_category => file_category.file)
file_category? : FileCategory[];
}<file_sep>/web/README.md
# NL Classroom
Esse projeto foi criado para unir todas as video-aulas, pdf's e todo material que está nos servidores e outros programas da NL.
Programador Criador: <NAME>
Programador Atual: <NAME>
## Executando o projeto
Após clonar o projeto do gitlab, entrar na pasta do projeto (Web), executar `yarn install` e,0 após a instalação, executar o comando `yarn start`, após uma aba no navegador irá se abrir com o endereço `localhost:3000`.
## Documentação
### 0. Erros
### 0.1 findDOMNode is deprecated in StrictMode.
Alguns métodos dão esse erro ao utilizar as bibliotecas do Material UI.
Para resolver, segundo a documentação, basta atualizar "@material-ui/core": "^4.12.3" para "@material-ui/core": "^5.0.0" (versão beta).
### 1. Linguagens e ferramentas
<a href="https://www.typescriptlang.org/" target="_blank"> <img src="https://raw.githubusercontent.com/devicons/devicon/master/icons/typescript/typescript-original.svg" alt="typescript" width="40" height="40"/> </a> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript" target="_blank"> <img src="https://raw.githubusercontent.com/devicons/devicon/master/icons/javascript/javascript-original.svg" alt="javascript" width="40" height="40"/> </a> <a href="https://reactjs.org/" target="_blank"> <img src="https://raw.githubusercontent.com/devicons/devicon/master/icons/react/react-original-wordmark.svg" alt="react" width="40" height="40"/> </a> <a href="https://tailwindcss.com/" target="_blank"> <img src="https://www.vectorlogo.zone/logos/tailwindcss/tailwindcss-icon.svg" alt="tailwind" width="40" height="40"/> </a>
### 1.1 Configurações dos Plugins do VCS
- ESlint
A configuração dele se dá pela instalação no projeto através dos comandos `yarn add -D eslint`, após iniciar a configuração dele pelo comando `yarn run eslint --init`, após selecionará as seguintes opções:
- **To check syntax, find problems and enforce code style**
- **JavaScript modules (import/export)**
- **React**
- **Yes**
- **Browser**
- **Use a popular style guide**
- **Airbnb**
- **JSON**
- **No**
Após instalar as bibliotecas pedidas com yarn, só cuidar a versão dita na msg, aqui é um exemplo: `yarn add -D babel-eslint eslint-plugin-react@^7.21.5 eslint-config-airbnb@latest eslint-plugin-import@^2.22.1 eslint-plugin-jsx-a11y@^6.4.1 eslint-plugin-react-hooks@^4`
Criar o arquivo `.eslintignore` e incluir `node_modules`.
Editar o arquivo `.eslintrc.json` com a seguinte configuração:
```json
{
"env": {
"browser": true,
"es2021": true
},
"extends": [
"plugin:react/recommended",
"plugin:import/typescript",
"airbnb",
"prettier"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": 12,
"sourceType": "module"
},
"plugins": ["react", "@typescript-eslint", "prettier"],
"rules": {
"arrow-parens": [2, "as-needed"],
"camelcase": "off",
"global-require": "off",
"import/prefer-default-export": "off",
"import/no-extraneous-dependencies": ["error", { "devDependencies": true }],
"import/no-named-as-default": 0,
"no-param-reassign": "off",
"no-underscore-dangle": "off",
"no-unused-vars": ["error", { "argsIgnorePattern": "^_" }],
"no-use-before-define": "off",
"no-console": ["error", { "allow": ["tron"] }],
"prettier/prettier": "error",
"react/jsx-filename-extension": [
1,
{ "extensions": [".js", ".jsx", "ts", "tsx"] }
],
"react/jsx-one-expression-per-line": "off",
"react/jsx-props-no-spreading": "off",
"react-native/no-raw-text": "off",
"react/prop-types": 0,
"@typescript-eslint/no-use-before-define": ["error"],
"import/extensions": [
"error",
"always",
{
"js": "never",
"jsx": "never",
"ts": "never",
"tsx": "never"
}
]
},
"settings": {
"import/resolver": {
"node": {
"extensions": [".ts", ".tsx", ".js", ".jsx"]
}
}
}
}
```
Por último, instale o plugin do ESlint, recarregue a janela do VSC e reinicie o projeto.
### 1.2 Prettier
Executar o seguinte comando: `yarn add prettier eslint-config-prettier eslint-plugin-prettier -D`
Criar o arquivo `.prettierrc` e adicionar o seguinte comando:
```json
{
"singleQuote": true,
"trailingComma": "all",
"arrowParens": "avoid"
}
```
Instale o plugin Prettier no seu projeto, após isso, basta abrir os arquivos e salvá-los para que o prettier os padronize ou execute o comando `npm run pretty`.
### 1.3 EditorConfig
Instalar o plugin no projeto, após, na raiz do projeto, clique com o botão direito do mouse e selecione a opção `Generate .editorconfig`.
Edite o arquivo gerado com os seguintes comandos:
```
root = true
[*]
end_of_line = lf
indent_style = space
indent_size = 2
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
```
### 1.4 Tailwind Css
Após fazer a instalação das biliotecas `npm install -D tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9`, é necessário instalar depois o `npm install @craco/craco --save`.
Agora irá precisar alterar o `package.json`:
```
// trocar isso
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
// por isso
"start": "craco start",
"build": "craco build",
"test": "craco test",
```
Crie um arquivo de configuração na raiz do projeto chamado `/craco.config.js`, e dentro dele cole o seguinte código:
```
module.exports = {
style: {
postcss: {
plugins: [require('tailwindcss'), require('autoprefixer')],
},
},
};
```
Agora precisa criar a configuração do tailwind com o comando `npx tailwindcss-cli@latest init`. Este comando irá criar um arquivo na raiz do projeto chamado `tailwind.config.ts`, se o tailwind já foi instalado, então esse arquivo já deve existir.
Neste arquivo você pode adicionar um comando para remover o código css que não é utilizado, basta adicionar ` purge: ['./src/**/*.{js,jsx,ts,tsx}', './public/index.html'],`.
Importe as bibliotecas do tailwind no arquivo `src/index.css` na raiz do projeto, com o comando:
```
@tailwind base;
@tailwind components;
@tailwind utilities;
```
PS: Se aparecer uma mensagem de erro dizendo que a regra @tailwind é desconhecida, instale esse plugin: <a href="https://marketplace.visualstudio.com/items?itemName=csstools.postcss">PostCSS Language</a>. Após instalar o plugin, precisa acessar o comando do VSC `Preferences: Open Settings (JSON)` e adicionar o comando:
```
"emmet.includeLanguages": {
"postcss": "css"
}
```
PS2: Se aparecer o erro `PostCSS plugin tailwindcss requires PostCSS 8.`, desinstale as bibliotecas `npm uninstall tailwindcss postcss autoprefixer` e re-instale `npm install -D tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9`.
### 1.5 Microsoft Graph REST API v1.0
Para fazer uma listagem e pegar os items da nuvem do OneDrive, será necessário fazer uma série de configurações:
1. Instale as <a href="https://docs.microsoft.com/pt-br/graph/sdks/sdk-installation">bibliotecas</a> `npm install @microsoft/microsoft-graph-client --save` e
`npm install @microsoft/microsoft-graph-types --save-dev`.
2. Adicionar as permissões na <a href="https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/CallAnAPI/appId/873e7d84-533f-4f54-a9c2-d1f03114dcf2/isMSAApp/">conta Microsoft </a>seguindo <a href="https://docs.microsoft.com/pt-br/graph/api/driveitem-search?view=graph-rest-1.0&tabs=javascript">esse</a> tutorial.
3. Rota padrão é `https://graph.microsoft.com/v1.0/`, para testar as requisições da APi basta acessar esse <a href="https://developer.microsoft.com/en-us/graph/graph-explorer">link</a> e <a href="https://www.youtube.com/watch?v=f_3wc4UgqTI">aqui</a> tem um tutorial rápido de 5 minutos. Na APi de teste, libere as permissões na aba `Modify Permissions (Preview)` e clique em `Consent` em cada permissão da lista.
4. Precisa salvar o `access_token` do usuário para ter acesso após o mesmo fazer login. Este será usado para ter acesso ao OneDrive. Este token tem a duração de 1 hora.
5. Essa API do MS Graph é bem confusa, sugiro que veja esse <a href="https://docs.microsoft.com/pt-br/onedrive/developer/rest-api/resources/driveitem?view=odsp-graph-online">link</a> para saber mais dsobre o `DriveItem`.
### 2. Login / Autenticação
A autentiação é feita utilizando a conta da microsoft, através da ferramenta azure authetication. Tutotial de como foi feito através deste <a href="https://docs.microsoft.com/pt-br/azure/developer/javascript/tutorial/single-page-application-azure-login-button-sdk-msal">link</a>
No <a href="https://portal.azure.com/?quickstart=True#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredApps">portal azure</a>, algumas configurações devem ser feitas para receber os dados do usuário logado:
1- No menu lateral esquerdo, clique na opção "Autenticação/Authentication".
2- Clique em " + Adicionar plataforma" (caso não tenha alguma) e selecione "Single-Page-Application".
3- Dentro das opções dessa plataforma, adicione a URL de redirecionamento "http://localhost:3000", mude essa URL quando for para produção ou adicione outra URL.
4- Informe uma URL para Logout: "https://localhost:3000" ou a URL de produção.
5- Na opção "Select the tokens you would like to be issued by the authorization endpoint:", selecione as duas opções que são `Access tokens (used for implicit flows)` e `ID tokens (used for implicit and hybrid flows)`.
6- Na opção "Supported account types" selecione a opção `Accounts in any organizational directory (Any Azure AD directory - Multitenant)`.
7- Mais abaixo tem a opção "Advanced settings", selecione a opção `Yes`.
8- Salve as alterações feitas clicando na opção "Save" que está no topo da página.
9- Vá ao menu lateral e selecione a opção "Manifest", essa opção é um arquivo JSON, procure nele o atributo "allowPublicClient" e verifique se está setado como `true`.
### 2.1 Salvar os dados do usuário logado
Na pasta Page encontra-se o arquivo "login", dentro dele irá ter um `useEffect` que fica monitorando a variavel `currentUser`. Caso tenha um usuário logado, essa função irá salvar os dados de e-mail e nome na `localStorage`, com os nomes `@nlclassroom/username` para o e-mail e `@nlclassroom/name` para o nome.
Essas informações ficam salvas no arquivo `util/index.tsx`, onde tem as funções para verificar se está logado `isLogin()`, sair da página `logout()`, e para pegar e enviar o e-mail e nome do usuário.
No arquivo de rotas, foi separa a rota de login das outras, que serão rotas privadas, tendo acesso após login. A verificação é feita na função `PrivateRoute()`, onde consulta o `localstorage` se tem algum dado salvo.
### 3. Página Categorias
A página de categorias tem 3 rotas, a rota da listagem `category/list`, de criar `category/form` e de editar `category/form:id`.
Dentro da listagem, uma requisição é feita para buscar a lista de categorias que será exibida numa tabela. Nesta tabela o usuário poderá clicar no botão de editar. Acima da tabela tem o botão de criar.
Na página de criar ou editar, está página verifica se tem um `id` na URL, se tem, então exibe o título de edição e faz uma requisição `PUT` ao servidor; caso contrário irá criar uma nova categoria e enviar uma requisição `POST` ao servidor. Após criar ou editar, o usuário volta para a página da listagem. Todos os dados devem ser preenchidos, se não o sistema exibe uma mensagem de aviso.
### 4. Página Cursos
A página de cursos tem 3 rotas, a rota da listagem `category/list`, de criar `category/form` e de editar `category/form:id`.
Dentro da listagem, uma requisição é feita para buscar a lista dos cursos que serão exibidos numa tabela. Nesta tabela o usuário poderá clicar no botão de editar. Acima da tabela tem o botão de criar.
Na página de criar ou editar, está página verifica se tem um `id` na URL, se tem, então exibe o título de edição e faz uma requisição `PUT` ao servidor; caso contrário irá criar um novo curso e enviar uma requisição `POST` ao servidor. Esta página carrega uma lista de categorias para o usuário escolher. Todos os dados devem ser preenchidos, se não o sistema exibe uma mensagem de aviso.
Após criar ou editar, o usuário volta para a página da listagem.
### 5. Página de Arquivo
A página de arquivo tem 3 rotas, a rota da listagem `file/list`, de criar `file/form` e de editar `file/form:id`.
Dentro da listagem, uma requisição é feita para buscar a lista dos arquivos que serão exibidos numa tabela. Nesta tabela o usuário poderá clicar no botão de editar. Acima da tabela tem o botão de criar.
Na página de criar ou editar, está página verifica se tem um `id` na URL, se tem, então exibe o título de edição e faz uma requisição `PUT` ao servidor; caso contrário irá criar um novo curso e enviar uma requisição `POST` ao servidor. Esta página carrega uma lista de cursos para o usuário escolher. Todos os dados devem ser preenchidos, se não o sistema exibe uma mensagem de aviso.
### 6. Home
Após o usuário fazer a autenticação, ele é redirecionado para a Home, onde terá uma barra de pesquisa, a qual irá mostrar os resultados pelo termo pesquisado. A busca irá mostrar os cursos, categorias e arquivos com aquele termo.
### 7. Página da API MG
Esta página é uma automatização de código para pegar os arquivos do OneDrive do `<EMAIL>` e salvar o link deles no banco de dados. Essa automatização pega os arquivos tanto do OneDrive quanto os compartilhados.
<file_sep>/server/src/entity/course.ts
import { Entity, Column, PrimaryGeneratedColumn, OneToMany, ManyToOne, JoinColumn } from "typeorm";
import { Category } from './category';
import { FileCourse } from './file-course';
@Entity('NL_CR_COURSES')
export class Course {
@PrimaryGeneratedColumn()
num_seq: number = 0;
@Column({ length: 200 })
name: string = '';
@Column({ length: 200 })
createdBy: string = '';
//Vários cursos podem pertencer a mesma categoria
@ManyToOne(() => Category, category => category.num_seq, { nullable: false, eager: true })
@JoinColumn({ name: "id_category" })
id_category: number = 0;
@OneToMany(() => FileCourse, file_course => file_course.file)
file_course? : FileCourse[];
}<file_sep>/server/src/service/file-course.service.ts
/**
* Data Model Interfaces
*/
import { FileCourseInterface } from '../interfaces/file-course';
import { FileCourse } from '../entity/file-course';
import { getRepository } from 'typeorm';
/**
* Service Methods
*/
export const find = async (body: FileCourseInterface): Promise<FileCourseInterface[]> => {
const response = await getRepository<FileCourseInterface>(FileCourse).find({
where: {
id_course: body.id_course,
id_file: body.id_file
},
});
console.log('2', response);
return response;
};
export const create = async (body: FileCourseInterface) => {
return await getRepository<FileCourseInterface>(FileCourse).save(body);
};<file_sep>/server/src/interfaces/course.ts
export interface BaseCourse {
name: string;
createdBy: string;
id_category: number;
category?: string;
}
export interface CourseInterface extends BaseCourse {
num_seq: number;
}<file_sep>/server/src/service/courses.service.ts
/**
* Data Model Interfaces
*/
import { CourseInterface, BaseCourse } from '../interfaces/course';
import { Course } from '../entity/course';
import { getRepository, Like } from 'typeorm';
/**
* Service Methods
*/
export const findAll = async (searchTerm: string = ''): Promise<CourseInterface[]> => {
if(searchTerm == ''){
const list = await getRepository<CourseInterface>(Course).find({
order: {
name: 'ASC'
}
});
return list;
} else {
const list = await getRepository<CourseInterface>(Course).find({
where: {
name: Like(`%${searchTerm}%`),
},
order: {
name: 'ASC'
}
});
return list;
}
};
export const find = async (num_seq: number | undefined): Promise<CourseInterface | undefined> => {
const obj = await getRepository<CourseInterface>(Course).findOne({ num_seq: num_seq });
return obj;
};
export const create = async (newCourse: BaseCourse): Promise<CourseInterface> => {
return await getRepository<CourseInterface>(Course).save(newCourse);
};
export const update = async ( num_seq: number, courseUpdate: BaseCourse ): Promise<CourseInterface | null> => {
const file = await find(num_seq);
if (!file) {
return null;
}
const obj: CourseInterface = {
num_seq: num_seq,
name: courseUpdate.name,
createdBy: courseUpdate.createdBy,
id_category: courseUpdate.id_category
};
return await getRepository<CourseInterface>(Course).save(obj);
}
export const remove = async ( id: number ): Promise<null | void> => {
const file = await find(id);
if (!file) {
return null;
}
getRepository(Course).delete(id);
}<file_sep>/server/src/routes/files.router.ts
/**
* Required External Modules and Interfaces
*/
import express, { Request, Response } from "express";
import * as filesService from "../service/files.service";
import { FileInterface, BaseFile } from '../interfaces/file';
/**
* Router Definition
*/
export const filesRouter = express.Router();
/**
* Controller Definitions
*/
// GET items
filesRouter.get("/", async (req: Request, res: Response) => {
try {
const files: FileInterface[] = await filesService.findAll();
res.status(200).send(files);
} catch (e: any) {
res.status(500).send(e.message);
}
});
// GET items/:id
filesRouter.get("/:id", async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10);
try {
const file: FileInterface | undefined = await filesService.find(id);
if (file) {
return res.status(200).send(file);
}
res.status(404).send("file ["+ id +"] not found");
} catch (e: any) {
res.status(500).send(e.message);
}
});
// POST items
filesRouter.post("/", async (req: Request, res: Response) => {
try {
const file: BaseFile = req.body;
const existingFile: FileInterface | undefined = await filesService.findOne(file);
if (existingFile) {
const updatedItem = await filesService.update(existingFile.num_seq, file);
return res.status(200).json(updatedItem);
}
const newFile = await filesService.create(file);
res.status(201).json(newFile);
} catch (e: any) {
res.status(500).send(e.message);
}
});
// PUT items/:id
filesRouter.put("/:id", async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10);
try {
const fileUpdate: FileInterface = req.body;
const existingFile: FileInterface | undefined = await filesService.find(id);
if (existingFile) {
const updatedItem = await filesService.update(id, fileUpdate);
return res.status(200).json(updatedItem);
}
const newFile = await filesService.create(fileUpdate);
res.status(201).json(newFile);
} catch (e: any) {
res.status(500).send(e.message);
}
});
// DELETE items/:id
filesRouter.delete("/:id", async (req: Request, res: Response) => {
try {
const id: number = parseInt(req.params.id, 10);
await filesService.remove(id);
res.sendStatus(204);
} catch (e: any) {
res.status(500).send(e.message);
}
});<file_sep>/web/src/styles/colors.js
export default {
primary: '#fc7422',
};
<file_sep>/server/src/interfaces/file-category.ts
export interface FileCategoryInterface {
id_file: number;
id_category: number;
}<file_sep>/server/src/entity/log.ts
import { Entity, Column, PrimaryGeneratedColumn, ManyToOne, JoinColumn } from "typeorm";
import { Course } from './course';
import { File } from './file';
@Entity('NL_CR_LOGS')
export class Log {
@PrimaryGeneratedColumn()
id: number = 0;
@Column({ length: 200 })
id_user: string = '';
@Column({ length: 200 })
progress: string = '';
//Vários logs podem ter o mesmo Curso
@ManyToOne(() => Course, course => course.num_seq, { nullable: false, eager: true })
@JoinColumn({ name: "id_course" })
id_course: number = 0;;
//Vários logs podem ter o mesmo File
@ManyToOne(() => File, file => file.num_seq, { nullable: false, eager: true })
@JoinColumn({ name: "id_file" })
id_file: number = 0;;
}<file_sep>/server/src/index.ts
/**
* Required External Modules
*/
import * as dotenv from "dotenv";
import express from "express";
import cors from "cors";
import helmet from "helmet";
import "reflect-metadata";
import { createConnection } from "typeorm";
import { errorHandler } from "./middleware/error.middleware";
import { notFoundHandler } from "./middleware/not-found.middleware";
import { categoriesRouter } from './routes/categories.router';
import { coursesRouter } from './routes/courses.router';
import { filesRouter } from './routes/files.router';
import { logsRouter } from './routes/logs.router';
import { homeRouter } from './routes/home.router';
import { fileCategoryRouter } from './routes/file-category.router';
import { fileCourseRouter } from './routes/file-course.router';
dotenv.config();
/**
* TypeORM Init DB
*/
createConnection("default").catch( err => console.error(err)); // 'prod'
/**
* App Variables
*/
if (!process.env.PORT) {
process.exit(1);
}
const PORT: number = parseInt(process.env.PORT as string, 10);
const app = express();
/**
* App Configuration
*/
app.use(helmet());
app.use(cors());
app.use(express.json());
app.use("/api/nlclassroom/categories", categoriesRouter);
app.use("/api/nlclassroom/courses", coursesRouter);
app.use("/api/nlclassroom/files", filesRouter);
app.use("/api/nlclassroom/logs", logsRouter);
app.use("/api/nlclassroom/home", homeRouter);
app.use("/api/nlclassroom/file-course", fileCourseRouter);
app.use("/api/nlclassroom/file-category", fileCategoryRouter);
app.use(errorHandler);
app.use(notFoundHandler);
/**
* Server Activation
*/
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});<file_sep>/server/src/routes/logs.router.ts
/**
* Required External Modules and Interfaces
*/
import express, { Request, Response } from "express";
import * as logsService from "../service/logs.service";
import { LogInterface, BaseLog } from '../interfaces/log';
/**
* Router Definition
*/
export const logsRouter = express.Router();
/**
* Controller Definitions
*/
// GET items
logsRouter.get("/", async (req: Request, res: Response) => {
try {
const logs: LogInterface[] = await logsService.findAll();
res.status(200).send(logs);
} catch (e: any) {
res.status(500).send(e.message);
}
});
/// GET items/:id
logsRouter.get("/:id", async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10);
try {
const log: LogInterface | undefined = await logsService.find(id);
if (log) {
return res.status(200).send(log);
}
res.status(404).send("log ["+ id +"] not found");
} catch (e: any) {
res.status(500).send(e.message);
}
});
// POST items
logsRouter.post("/", async (req: Request, res: Response) => {
try {
const log: BaseLog = req.body;
const newLog = await logsService.create(log);
res.status(201).json(newLog);
} catch (e: any) {
res.status(500).send(e.message);
}
});
// PUT items/:id
logsRouter.put("/:id", async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10);
try {
const logUpdate: LogInterface = req.body;
const existingLog: LogInterface | undefined = await logsService.find(id);
if (existingLog) {
const updatedLog = await logsService.update(id, logUpdate);
return res.status(200).json(updatedLog);
}
const newLog = await logsService.create(logUpdate);
res.status(201).json(newLog);
} catch (e: any) {
res.status(500).send(e.message);
}
});
// DELETE items/:id
logsRouter.delete("/:id", async (req: Request, res: Response) => {
try {
const id: number = parseInt(req.params.id, 10);
await logsService.remove(id);
res.sendStatus(204);
} catch (e: any) {
res.status(500).send(e.message);
}
});<file_sep>/server/src/service/categories.service.ts
/**
* Data Model Interfaces
*/
import { CategoryInterface, BaseCategory } from '../interfaces/category';
import { Category } from '../entity/category';
import { getRepository, Like } from 'typeorm';
/**
* Service Methods
*/
export const findAll = async (searchTerm: string = ''): Promise<CategoryInterface[]> => {
if(searchTerm == ''){
const list = await getRepository<CategoryInterface>(Category).find({
order: {
name: 'ASC'
}
});
return list;
} else {
const list = await getRepository<CategoryInterface>(Category).find({
where: {
name: Like(`%${searchTerm}%`),
},
order: {
name: 'ASC'
}
});
return list;
}
};
export const find = async (num_seq: number): Promise<CategoryInterface | undefined> => {
const obj = await getRepository<CategoryInterface>(Category).findOne({ num_seq });
return obj;
};
export const create = async (newCategory: BaseCategory): Promise<CategoryInterface> => {
return await getRepository<CategoryInterface>(Category).save(newCategory);
};
export const update = async ( num_seq: number, categoryUpdate: BaseCategory ): Promise<CategoryInterface | null> => {
const file = await find(num_seq);
if (!file) {
return null;
}
const obj: CategoryInterface = {
num_seq,
name: categoryUpdate.name,
};
return await getRepository<CategoryInterface>(Category).save(obj);
}
export const remove = async ( id: number ): Promise<null | void> => {
const file = await find(id);
if (!file) {
return null;
}
getRepository(Category).delete(id);
}<file_sep>/web/src/interfaces/file.ts
import { Category } from './category';
import { Course } from './course';
export interface File {
num_seq: string;
name: string;
url: string;
id_course: Course;
id_category: Category;
}
<file_sep>/server/src/service/files.service.ts
/**
* Data Model Interfaces
*/
import { FileInterface, BaseFile } from '../interfaces/file';
import { File } from '../entity/file';
import { getRepository } from 'typeorm';
/**
* Service Methods
*/
export const findAll = async (): Promise<FileInterface[]> => {
const list = await getRepository<FileInterface>(File).find({
order: {
name: 'ASC'
}
});
return list;
};
export const find = async (num_seq: number): Promise<FileInterface | undefined> => {
const obj = await getRepository<FileInterface>(File).findOne({ num_seq });
return obj;
};
export const findOne = async (file: BaseFile) => {
const obj = await getRepository<FileInterface>(File).findOne({ where: {name: file.name, url: file.url} });
return obj;
};
export const create = async (newFile: BaseFile): Promise<FileInterface> => {
return await getRepository<FileInterface>(File).save(newFile);
};
export const update = async ( num_seq: number, fileUpdate: BaseFile ): Promise<FileInterface | null> => {
const file = await find(num_seq);
if (!file) {
return null;
}
const obj: FileInterface = {
num_seq,
name: fileUpdate.name,
url: fileUpdate.url
};
return await getRepository<FileInterface>(File).save(obj);
}
export const remove = async ( num_seq: number ): Promise<null | void> => {
const file = await find(num_seq);
if (!file) {
return null;
}
getRepository(File).delete(num_seq);
}<file_sep>/server/src/entity/category.ts
import { Entity, Column, PrimaryGeneratedColumn, JoinTable, OneToMany, ManyToMany, JoinColumn } from "typeorm";
import { Course } from './course';
import { FileCategory } from './file-category';
@Entity('NL_CL_CATEGORIES')
export class Category {
@PrimaryGeneratedColumn()
num_seq: number = 0;
@Column({ length: 200 })
name: string = '';
// Uma categoria pode existir em vários cursos
@OneToMany(() => Course, course => course.id_category)
@JoinColumn()
courses?: Course[];
@OneToMany(() => FileCategory, file_course => file_course.file)
file_category? : FileCategory[];
}<file_sep>/web/src/interfaces/onedrive-file.ts
import { User } from './user';
export interface OneDriveFile {
id: string;
name: string;
createdBy: User;
webUrl: string;
file?: { hashes: { quickXorHash: string }; mimeType: string };
folder?: { childCount: number };
remoteItem: {
parentReference: { driveId: string; driveType: string; id: string };
};
}
<file_sep>/server/src/service/logs.service.ts
/**
* Data Model Interfaces
*/
import { LogInterface, BaseLog } from '../interfaces/log';
import { Log } from '../entity/log';
import { getRepository } from 'typeorm';
// createConnection(/*prod*/).then().catch( (error) => { console.log(error); });
/**
* Service Methods
*/
export const findAll = async (id_user: string = ''): Promise<LogInterface[]> => {
if(id_user == ''){
const list = await getRepository<LogInterface>(Log).find({
order: {
id_user: 'ASC'
}
});
return list;
} else {
const list = await getRepository<LogInterface>(Log).find({
where: {
id_user: id_user,
}
});
return list;
}
};
export const find = async (num_seq: number): Promise<LogInterface | undefined> => {
const obj = await getRepository<LogInterface>(Log).findOne({ num_seq });
return obj;
};
export const create = async (newLog: BaseLog): Promise<LogInterface> => {
return await getRepository<LogInterface>(Log).save(newLog);
};
export const update = async ( num_seq: number, logUpdate: BaseLog ): Promise<LogInterface | null> => {
const file = await find(num_seq);
if (!file) {
return null;
}
const obj: LogInterface = {
num_seq,
id_user: logUpdate.id_user,
id_course: logUpdate.id_course,
id_file: logUpdate.id_file,
progress: logUpdate.progress
};
return await getRepository<LogInterface>(Log).save(obj);
}
export const remove = async ( num_seq: number ): Promise<null | void> => {
const file = await find(num_seq);
if (!file) {
return null;
}
getRepository(Log).delete(num_seq);
}<file_sep>/server/src/service/file-category.service.ts
/**
* Data Model Interfaces
*/
import { FileCategoryInterface } from '../interfaces/file-category';
import { FileCategory } from '../entity/file-category';
import { getRepository } from 'typeorm';
/**
* Service Methods
*/
export const find = async (body: FileCategoryInterface): Promise<FileCategoryInterface[]> => {
const response = await getRepository<FileCategoryInterface>(FileCategory).find({
where: {
id_category: body.id_category,
id_file: body.id_file
},
});
return response;
};
export const create = async (body: FileCategoryInterface) => {
return await getRepository<FileCategoryInterface>(FileCategory).save(body);
};<file_sep>/server/src/routes/home.router.ts
/**
* Required External Modules and Interfaces
*/
import express, { Request, Response } from "express";
import * as homeService from "../service/home.service";
/**
* Router Definition
*/
export const homeRouter = express.Router();
/**
* Controller Definitions
*/
// GET items
homeRouter.get("/", async (req: Request, res: Response) => {
const searchTerm: any | undefined = req.query.searchTerm;
try {
const search: any[] = await homeService.find(searchTerm);
res.status(200).send(search);
} catch (e: any) {
res.status(500).send(e.message);
}
});<file_sep>/web/src/services/apimg.ts
import axios from 'axios';
const token = localStorage.getItem('@nlclassroom/access_token');
const headers = token
? {
Authorization: `Bearer ${token}`,
}
: undefined;
const apimg = axios.create({
baseURL: 'https://graph.microsoft.com/v1.0/',
headers,
});
export default apimg;
|
05fc1711a760ac49b032154d43a54bf061faec4d
|
[
"Markdown",
"TypeScript",
"JavaScript"
] | 39 |
TypeScript
|
kalbzero/react-azure-express-typeorm
|
eebef1373bce53309e1664d3ca24be0299f92eaa
|
76f0c6e0f8868d24784d92069466536eef2307f7
|
refs/heads/master
|
<file_sep>#include <iostream>
#include <sstream>
#include <string>
using namespace std;
class myObject
{
public:
virtual ~myObject() { }
virtual string GetString() const = 0;
};
class Hello : virtual public myObject
{
public:
virtual string GetHello() const = 0;
};
class World : virtual public myObject
{
public:
virtual string GetWorld() const = 0;
};
class Object :
public Hello,
public World
{
public:
string GetString() const
{
ostringstream ostr;
ostr << "str: " << GetHello() << GetWorld() << endl;
return ostr.str();
}
string GetHello() const
{
return "Hello";
}
string GetWorld() const
{
return "World";
}
private:
};
void showHello(const Hello& obj)
{
cout << obj.GetHello() << " ";
}
void showWorld(const World& obj)
{
cout << obj.GetWorld() << " ";
}
ostream& operator<<(ostream& ostr, const myObject& obj)
{
return ostr << obj.GetString();
}
int main()
{
Object o;
cout << o << flush;
showHello(o);
showWorld(o);
cout << endl;
}
<file_sep># helloworld
test world
sd
asdfasd
ad
a
sd
|
b386780e0a799b8a820e78beaefb0b601ba278e2
|
[
"Markdown",
"C++"
] | 2 |
C++
|
penny12/helloworld
|
b7b611a442524489c5fd0c8b63dd2feebf935daa
|
7e939a67bcdc47fe989bab4970cc44f7aefd6fde
|
refs/heads/master
|
<repo_name>bjackson13/iste-444-apm-tool<file_sep>/System/SystemPrinter.sh
#! /bin/bash
# ISTE-444 Project 1
# <NAME>
# <NAME>
# <NAME>
# SystemPrinter - prints results sent by the System monitor to a csv file
# Also controls timing and the loop for system monitoring
# catch function - removes temp file
remove_temp () {
rm -f temp.txt
}
trap remove_temp EXIT
# ip passed in as first arg
ip=$1
# run the loop until told not to
while true
do
# sleep for 5 seconds in the background
sleep 5 &
# run the system monitor commands in the background to avoid delays caused by the 1 second sample in ifstat
# errors are ignored
./System/SystemMonitor.sh $ip > temp.txt 2> /dev/null &
# print the script runtime and the system monitor results to the log file
wait
echo "$SECONDS,$(<temp.txt)" >> system_metrics.csv
done
<file_sep>/Process/AppMonitor.sh
#! /bin/bash
# ISTE-444 Project 1
# <NAME>
# <NAME>
# <NAME>
# AppMonitor - monitors the resources used by the 6 C scripts
process=$(ps -e | egrep "APM$1" | awk '{print $1}')
process_metrics=$(ps -p $process -o %cpu,%mem)
# individual process cpu and memory usage
memory=$(echo $process_metrics | awk '{print $3}')
cpu=$(echo $process_metrics | awk '{print $4}')
echo $memory,$cpu
<file_sep>/Process/AppPrinter.sh
#! /bin/bash
# ISTE-444 Project 1
# <NAME>
# <NAME>
# <NAME>
# AppPrinter - prints results sent by the app monitor to a csv file
remove_temp () {
rm -f temp*.txt
}
trap remove_temp EXIT
while true
do
# sleep for 5 seconds in the background
sleep 5 &
for i in {1..6}
do
./Process/AppMonitor.sh $i > temp$i.txt 2> /dev/null &
done
wait
# set SECONDS to variable since the metrics were already received and we need to run the for loop still which skews the times
seconds=$SECONDS
# print once 5 seconds has passed
for i in {1..6}
do
echo "$seconds,$(<temp$i.txt)" >> ./APM"$i"_metrics.csv
done
done
<file_sep>/APMStarter.sh
#! /bin/bash
# ISTE-444 Project 1
# <NAME>
# <NAME>
# <NAME>
# APMStarter - Starts the app monitoring tool
# Get IP address from args
ip=$1
# remove all old csv files
rm -f *.csv 2> /dev/null
# Start the 6 C scripts
start_c_scripts () {
for i in {1..6}
do
./Scripts/APM$i $ip &
done
}
# start the monitor scripts
start_printer_scripts () {
# start the process monitor
./Process/AppPrinter.sh &
# start the system monitor
./System/SystemPrinter.sh $ip &
echo Montoring started...
}
# Exit trap function - kills c scripts and monitor scripts
cleanup () {
# kill the system monitor/printer
systemid=$( ps -e | egrep "SystemPrinter" | awk '{print $1}' )
kill -15 $systemid 1> /dev/null 2> /dev/null
echo System monitoring killed.
# kill the process monitor/printer
processid=$( ps -e | egrep "AppPrinter" | awk '{print $1}' )
kill -15 -p $processid 1> /dev/null 2> /dev/null
echo App monitoring killed.
# kill the APM c scripts
for i in {1..6}
do
pid=$( ps -e | egrep "APM$i" | awk '{print $1}' )
kill -15 $pid 2> /dev/null
done
echo Test Scripts killed.
}
# trap for exit - call cleanup
trap 'cleanup' EXIT
# call our functions to start the APM tool
start_c_scripts
start_printer_scripts
wait
echo Script and monitoring stopped...
<file_sep>/System/SystemMonitor.sh
#! /bin/bash
# ISTE-444 Project 1
# <NAME>
# <NAME>
# <NAME>
# SystemMonitor - monitors system resource usage
# IP address passed to script
ip=$1
# Get the network interface card based on the ip address passed in
nic=$( ifconfig | grep -B 1 "$ip" | awk -F: 'NR==1 {print $1}' )
# get network utilizatio with sample after 1 second
bandwidth=$( ifstat -t 1 $nic | awk 'NR==4 {print $6" "$8}' )
rx=$( echo $bandwidth | cut -d " " -f 1 | sed 's/K//g' )
tx=$( echo $bandwidth | cut -d " " -f 2 )
# Get the disk writes in kB/s
diskwrites=$( iostat -d sda | grep sda | awk '{print $4}' )
# Get disk utilization for '/' mount in MB
diskutil=$( df -BM / | awk 'NR==2{print $4}' | egrep -o [0-9] | tr -d "\n" )
# echo out results
echo "$rx,$tx,$diskwrites,$diskutil"
<file_sep>/README.md
# iste-444-apm-tool
APM Tool for iste-444
Creators: <NAME>, <NAME>, <NAME>
How to run: use command './APMStarter.sh' and pass in your IP address as the only argument
ex: ./APMStarter.sh 192.168.1.2
|
fe64cafccc97dae3c992bcbd2572939051cce486
|
[
"Markdown",
"Shell"
] | 6 |
Shell
|
bjackson13/iste-444-apm-tool
|
9c0f87171344e646c552f7c59a12282da181e17b
|
b3c53327117cfec342268e441b2c952ca3691216
|
refs/heads/master
|
<repo_name>ishancoder/car-rental-app<file_sep>/src/components/CarCard/CarCard.js
import React from "react";
import "./CarCard.sass";
function getButtonText(isUnavailable, isSelected) {
if (isUnavailable)
return "Not Available";
if (isSelected)
return "SELECTED";
return "SELECT";
}
function CarCard(props) {
const {
id,
name,
carType,
fuelType,
seats,
photo,
price,
availability,
location,
isSelected,
transmission
} = props.car;
const isUnavailable = availability.indexOf(props.startDate.day()) === -1;
return <div className="car-card">
<header className="backgrounded">
<h3>
{name} ({fuelType})
</h3>
</header>
<div className="card-content backgrounded">
<img src={photo} alt={`${name}`} />
<div>
<p><strong>Location : </strong> {location}</p>
<p><strong>Number of Seats : </strong> {seats}</p>
<p><strong>Car Type : </strong> {carType}</p>
<p><strong>Transmission : </strong> {transmission}</p>
</div>
</div>
<footer className="backgrounded">
<span className="price-tag">
₹{price}
</span>
<button
className={isSelected ? "selected" : ""}
disabled={isUnavailable}
onClick={() => props.onSelect(id)}>{getButtonText(isUnavailable, isSelected)}</button>
</footer>
</div>;
}
export default CarCard;<file_sep>/README.md
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## What i've implemented ?
1. There will be a Landing page which ask for Location and Start Date.
2. Once provided the app will animate to the next page.
3. The next page will contain a list of cards for CARS.
4. You can select a CAR by clicking on the select button.
5. All the cars are sorted according to the availability.
6. You can search for cars in the search box provided above.
7. There is a button in the lower left corner with a Tornabo Symbol on it. Click on it to bring up more filer options.
## How to get this thing working ?
1. Use `git clone` or download the zip.
2. If you've downloaded the zip extract it.
3. `cd` into the repository.
4. Run `npm install` or `yarn` (if you're using it)
5. Run `npm start` or `yarn start` (Again if you're using it)
6. A browser window will automatically open & in case if it didn't open your favourite browser and go to : [http://localhost:3000](http://localhost:3000).
## What did I use to build it ?
1. **React.js** my choice of front end framework for almost all projects.
2. **node-uuid** to generate cars id which were not provided by the API.
3. **SASS** Syntactically Awesome.
4. Where is **REDUX** ? you might be asking but to be honest I didn't felt the need of using **REDUX** in this project. <file_sep>/src/components/CarListings/CarListings.js
import React, { Component } from "react";
import "./CarListings.sass";
import CarCard from "../CarCard/CarCard";
import { getCars } from "../../data/api";
import Paginator from "../Paginator/Paginator";
import { paginate } from "../../utils/utils";
class CarListings extends Component {
constructor(props) {
super(props);
this.pageSize = 6;
this.state = {
cars: [],
pageNumber: 0,
query: ""
};
}
handleSelect = carId => {
// We'll be returning a new cars list rather than updating the currnt one
// Fine the targeted car
const targetIdx = this.state.cars.findIndex(car => car.id === carId);
// Make sure that the car indeed exists in the state.
if (targetIdx === -1)
return;
const targetCar = this.state.cars[targetIdx];
// Set the car state using a brand new list.
this.setState(prevState => ({
cars: [
...prevState.cars.slice(0, targetIdx), // Former elements
{ ...targetCar, isSelected: !targetCar.isSelected }, // Modified element
...prevState.cars.slice(targetIdx + 1, prevState.cars.length) // Later elements
]
}));
};
handlePageChange = ({ target: { name } }, totalElements) => {
const totalPages = totalElements / this.pageSize;
switch (name) {
case "previous":
this.setState(prevState => {
if (prevState.pageNumber > 0) {
return { pageNumber: prevState.pageNumber - 1 };
}
})
break;
case "next":
this.setState(prevState => {
if (prevState.pageNumber < totalPages - 1) {
return { pageNumber: prevState.pageNumber + 1 };
}
})
break;
default:
break;
}
};
handleSearch = ({ target: { value } }) => {
this.setState({ query: value });
};
applyFiltersAndGetCars() {
const { filters } = this.props;
// We're goint a little bit functional here and we're returning a brand new list of all the cars that pass the criteria.
return this.state.cars.filter(car => {
// We take all the keys in filter and match it with the cars property.
// One major benifit ot doing it if we have to use another filter we don't have to change this logic.
return Object.keys(filters).every(filterKey => {
if (!filters[filterKey]) {
return true;
}
return filters[filterKey].toLocaleLowerCase() === car[filterKey].toLocaleLowerCase();
})
}).filter(car => {
return car.name.toLocaleLowerCase().includes(this.state.query.toLocaleLowerCase())
}).slice().sort((carA, carB) => {
// Then we're going to sort the cars and put unavailable at the end
const availableA = carA.availability.indexOf(this.props.startDate.day()) !== -1;
const availableB = carB.availability.indexOf(this.props.startDate.day()) !== -1;
// Since availableA and availableB are boolean values it'll be coerced as 1 and 0 for true and false by JS.
return availableB - availableA;
});
}
async componentDidMount() {
// Get the list of all cars since the list has only 29 elements this is going to be pretty efficient.
const cars = await getCars();
this.setState({ cars });
}
render() {
const cars = this.applyFiltersAndGetCars();
const carPage = paginate(cars, this.state.pageNumber, this.pageSize);
return <section className="car-listings">
<Paginator
pageNumber={this.state.pageNumber}
pageSize={this.pageSize}
totalElements={cars.length}
onPageChange={ev => this.handlePageChange(ev, cars.length)}
onChange={this.handleSearch}
/>
<div className="card-section">
{
carPage.map(car => {
return <CarCard
key={car.id}
car={car}
startDate={this.props.startDate}
onSelect={this.handleSelect} />;
})
}
{!carPage.length ? <h3 className="no-result">No Results were found</h3> : ""}
</div>
</section>
}
}
export default CarListings;<file_sep>/src/data/api.js
import {v4 as uuid} from "uuid";
const weekDayMap = {
Sun: 0,
Mon: 1,
Tue: 2,
Wed: 3,
Thu: 4,
Fri: 5,
Sat: 6,
};
const URL = "https://api.sheety.co/311576ae-321a-43e3-9a5b-61b3ac373d85";
// This will also come handy when suppose the keys from the backend changes the only thing that you need to change will be this function.
function transformCarsJson(carsArray) {
/* Since I'm using ES6 destructuring almost everywhere an I do not like to have underscores in my variable name
I'll be transforming the response a little bit also There is no id proviede by the backend so I'm generating my own to perform actions like selection etc. */
return carsArray.map((car) => ({
...car,
id: uuid(),
availability: car.availability.split(", ").map(day => weekDayMap[day]),
carType: car.car_Type,
fuelType: car.fuel_Type,
isSelected: false
}));
}
export function getCars() {
return fetch(URL)
.then(res => res.json())
.then(transformCarsJson);
}
export function getCarTypes() {
return getCars()
.then(arr => new Set(arr.map(elem => elem.carType)))
.then(set => Array.from(set));
}<file_sep>/src/components/FilterPane/FilterPane.js
import React from "react";
import "./FilterPane.sass";
const carTypes = ["Hatchback", "SUV", "Sedan", "Mini SUV"];
const fuelTypes = ["Diesel", "Petrol"]
const transmission = ["Manual", "Automatic"]
function FilterPane(props) {
return <aside className={`${(props.open) ? "open" : ""} filter-pane`}>
<button className="close-btn" onClick={props.onClose}>✕</button>
<h1>Car Type</h1>
<div>
{
carTypes.map(type => <label key={type}>
<input
type="radio"
name="carType"
value={type}
checked={props.filters.carType === type}
onChange={props.onChange}/> {type}
</label>)
}
</div>
<h1>Fuel Type</h1>
<div>
{
fuelTypes.map(type => <label key={type}>
<input
type="radio"
name="fuelType"
value={type}
checked={props.filters.fuelType === type}
onChange={props.onChange}/> {type}
</label>)
}
</div>
<h1>Transmission</h1>
<div>
{
transmission.map(type => <label key={type}>
<input
type="radio"
name="transmission"
value={type}
checked={props.filters.transmission === type}
onChange={props.onChange}/> {type}
</label>)
}
</div>
<button onClick={props.onClearAll} className="danger">CLEAR ALL</button>
</aside>;
}
export default FilterPane;<file_sep>/src/components/Header/Header.js
import React from "react";
import "./Header.sass";
function Header(props) {
return <header className={`${(props.fullScreen) ? "full-screen" : "collapse"} backgrounded controls main-header`}>
<h1 className="title">Rent Your <span role="img" aria-label="car">🚗</span></h1>
<div className="input-wrapper">
<input type="text" name="location" onChange={props.handleFilterChange} placeholder="Location" value={props.location}/>
<input type="date" name="startDate" onChange={props.handleDateChange} defaultValue={props.startDate.format("YYYY-MM-DD")}/>
</div>
<button onClick={props.handleSubmit}>SUBMIT</button>
</header>;
}
export default Header;<file_sep>/src/components/Paginator/Paginator.js
import React from "react";
import "./Paginator.sass";
function Paginator(props) {
let {pageNumber, pageSize, totalElements} = props;
// We'll be showing at least one page.
const totalPages = Math.max(Math.ceil(totalElements / pageSize), 1);
return <div className="paginator backgrounded">
<div className="search-wrapper">
<input
type="text"
placeholder="Search..."
value={props.query}
onChange={props.onChange}/>
</div>
<nav className="">
<button name="previous" onClick={props.onPageChange}>←</button>
<span>{pageNumber + 1} / {totalPages}</span>
<button name="next" onClick={props.onPageChange}>→</button>
</nav>
</div>;
}
export default Paginator;
|
baa6d34dbfdc26134a998dd031b86dc13b9b0639
|
[
"JavaScript",
"Markdown"
] | 7 |
JavaScript
|
ishancoder/car-rental-app
|
3f9bcfb13e1d0c55eb3ed9c9e2841951ba68f12b
|
cf0e56fff6a0e7d1feeed7d68db2946dc8ee6234
|
refs/heads/master
|
<repo_name>eleutherius/graylog-docker-compose<file_sep>/docker-compose.yml
version: '2'
networks:
graylog.net:
volumes:
graylog.data.elastic:
driver: "local"
graylog.data.mongo:
driver: "local"
services:
mongo:
image: mongo:3
container_name: mongo
hostname: mongo
environment:
- "TZ=Europe/Amsterdam"
volumes:
- graylog.data.mongo:/data/db
networks:
- graylog.net
elasticsearch:
image: docker.elastic.co/elasticsearch/elasticsearch:5.6.3
container_name: elasticsearch
hostname: graylog.elastic
ulimits:
memlock:
soft: -1
hard: -1
mem_limit: 1g
volumes:
- graylog.data.elastic:/usr/share/elasticsearch/data
environment:
- http.host=0.0.0.0
- transport.host=localhost
- network.host=0.0.0.0
- "TZ=Europe/Amsterdam"
- cluster.name=graylog
- bootstrap.memory_lock=true
- "ES_JAVA_OPTS=-Xms512m -Xmx512m"
- xpack.security.enabled=false
networks:
- graylog.net
ulimits:
memlock:
soft: -1
hard: -1
mem_limit: 1g
volumes:
- graylog.data.elastic:/usr/share/elasticsearch/data
networks:
- graylog.net
ports:
- "9200:9200"
graylog:
image: graylog/graylog:2.4
hostname: graylog
environment:
- "TZ=Europe/Amsterdam"
- GRAYLOG_PASSWORD_SECRET=<PASSWORD>
- GRAYLOG_ROOT_PASSWORD_SHA2=<PASSWORD>
- GRAYLOG_WEB_ENDPOINT_URI=http://melle4.synology.me:9000/api
- GRAYLOG_ROOT_TIMEZONE= Europe/Amsterdam
ports:
- 9000:9000
# Syslog UDP
- 514:514/udp
# GELF UDP DOCKER
- 12201:12201/udp
# GELF UDP MYSQL
- 12202:12202/udp
- 12305:12305/udp
- 5044:5044/udp
links:
- mongo
- elasticsearch
networks:
- graylog.net
<file_sep>/custom_gelf_log.sh
#!/bin/bash
test_env=`tail -1 test`
message=`tail -1 /var/log/elasticsearch/fwyl-production.log`
date1=`echo ${message} | cut -c 1-25`
if [[ "$test_env" != "$date1" ]]; then
hostname='fywl-server'
short_message=`tail -1 /var/log/elasticsearch/fwyl-production.log | cut -c 33-`
full_message=$message
level=1
facility='some_text'
#date=`tail -1 /var/log/elasticsearch/fwyl-production.log | cut -c 1-25`
date=$(date +'%s.%N')
env_name='elasticsearch-fywl-server'
app_name='elasticsearch'
# Read the message into the variable ${gelf_message}
# see http://graylog2.org/gelf for mor info
read -r -d '' gelf_message <<EOF
{
"version": "1.0",
"host": "${hostname}",
"short_message": "${short_message}",
"full_message": "${full_message}",
"timestamp": ${date},
"level": ${level},
"facility": "${facility}",
"_user_id": 42,
"_Environment": "${env_name}",
"_AppName": "${app_name}"
}
EOF
echo ${date1} > test
echo "${gelf_message}"| gzip -c -f - | nc -w 1 -u 192.168.100.137 12202
#echo "${gelf_message}"
fi
<file_sep>/README.md
Installing GRAYLOG Documentation
----
It's simply graylog installation instruction for to install graylog in the docker container.
Docker-compose.yml file for graylog
```custom_gelf_log.sh``` - custom script for transfer log data vía GELF protocol.
## Mysql Server logining tools
Mysql logining via script :
https://github.com/arikogan/mysql-gelf
For Docker container we need to add this lines in docker-compose.yml
```
logging:
driver: "gelf"
options:
gelf-address: "udp://192.168.100.137:12201"
tag: "sidekiq"
```
## Docker composer autostart
```
# /etc/systemd/system/docker-compose-app.service
[Unit]
Description=Docker Compose Application Service
Requires=docker.service
After=docker.service
[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=/srv/docker
ExecStart=/usr/local/bin/docker-compose up -d --force-recreate
ExecStop=/usr/local/bin/docker-compose down
TimeoutStartSec=0
[Install]
WantedBy=multi-user.target
```
Change the ```WorkingDirectory``` parameter with your dockerized project path. And enable the service to start automatically:
```systemctl enable docker-compose-app```
|
81ca33c0fa831fc9e1c27306c0c0ed0a0077dd8a
|
[
"Markdown",
"YAML",
"Shell"
] | 3 |
YAML
|
eleutherius/graylog-docker-compose
|
518fae037de96d489c714d894c723a6254822bfd
|
55f7d8a5d8a848a04b414edfd4bbb993bea63a2b
|
refs/heads/master
|
<repo_name>MustafaAli789/Connect4<file_sep>/scriptPvP.js
//handles clicking
canvas.addEventListener("click", (event)=>{
if(playAgain){
main(event);
}
});
function main(event){
let columnNum = getColumn(getMouseXCoorRelativeToCanvas(event)).column;
if(isValidColumn(columnNum, gridMain).valid){
let rowNum = isValidColumn(columnNum, gridMain).row;
addCircleToColumn(columnNum, turn, gridMain);
drawCircleInColumn(rowNum, columnNum);
if(verifyWin(turn, gridMain).win){
let winObj = verifyWin(turn, gridMain);
drawWin(winObj.row, winObj.column, winObj.direction)
setTimeout(win, 1.5);
} else{
if(turn==="red"){
turn="green";
}else{turn="red";}
clearTopRow();
showCircleAboveGrid(getCenterCoords(rowNum, columnNum).x);
}
}
}
<file_sep>/README.md
# Connect4
The popular connect 4 game implemented with HTML5 Canvas and Javasciprt with 2 player or 1 player (A.I) capabailities.
Repl.it link: https://connect-4.mustafaali6.repl.co/
<file_sep>/scriptStart.js
const PvPButton = document.getElementById("PvP");
const PvCButton = document.getElementById("PvC");
var gameType = "pvp";
PvPButton.addEventListener("click", ()=>{
gameType = "pvp";
window.location.href = "connect4PvP.html";
});
PvCButton.addEventListener("click", ()=>{
gameType="pvc";
window.location.href = "connect4PvC.html";
});
|
ef82ee35cca6eec076dd110c6645907a12ae80cb
|
[
"JavaScript",
"Markdown"
] | 3 |
JavaScript
|
MustafaAli789/Connect4
|
7b14b86e396bb164bc93d6070574a20aeabbb4f4
|
c5780bf8a4104fd1698152cc1daba656afbbae3b
|
refs/heads/master
|
<repo_name>fautalan1/Grupo-A-022018-Auction-Front-End<file_sep>/src/containers/App.js
import React, { Component } from 'react';
import '../App.css';
import { Route, Switch } from 'react-router-dom'
import Header from '../components/Header';
import 'react-notifications/lib/notifications.css'
import Login from './Login'
import Home from './Home';
export default class App extends Component {
constructor(){
super();
this.state = {
name: ""
}
}
render() {
return (
<div>
<Header/>
<Switch>
<Route exact path="/" render={()=><Home anUserName={this.state.name}/>}/>
<Route exact path="signIn" component ={Login}/>
</Switch>
</div>
);
}
}
|
b6a8bb77e1f604f89745463ab0e741c7cd1e4662
|
[
"JavaScript"
] | 1 |
JavaScript
|
fautalan1/Grupo-A-022018-Auction-Front-End
|
fa0ba0b605b23d1a1279974dae9374379b959635
|
79a4feaf8572b522a366d7a24bbb750e8b128a12
|
refs/heads/master
|
<file_sep>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* answer: 871198282 */
/* version: 1 */
void merge(char **ptr, int n1, int n2)
{
char **tmp;
int i = 0;
int j1 = 0;
int j2 = 0;
int j;
tmp = malloc((n1 + n2) * sizeof(char *));
for (j = 0; j < n1 + n2; j++)
{
tmp[j] = malloc(20 * sizeof(char));
}
while (j1 < n1 && j2 < n2)
{
tmp[i++] = strcmp(ptr[j1], ptr[n1 + j2]) <= 0 ? ptr[j1++] : ptr[n1 + j2++];
}
while (j1 < n1)
{
tmp[i++] = ptr[j1++];
}
while (j2 < n2)
{
tmp[i++] = (ptr + n1)[j2++];
}
for (i = 0; i < n1 + n2; i++)
{
ptr[i] = tmp[i];
}
free(tmp);
}
void merge_sort(char **ptr, int size)
{
int n1, n2;
if (size > 1)
{
n1 = size / 2;
n2 = size - n1;
merge_sort(ptr, n1);
merge_sort(ptr + n1, n2);
merge(ptr, n1, n2);
}
}
int main()
{
FILE *fin;
char **names;
int i, j;
int sum = 0;
int total = 0;
fin = fopen("22.txt", "r");
names = malloc(5163 * sizeof(char*));
for (i = 0; i < 5163; i++)
{
names[i] = malloc(20 * sizeof(char));
}
i = 0;
while (fscanf(fin, "\"%[A-Z]s", names[i++]) != EOF)
{
fseek(fin, 2L, SEEK_CUR);
}
merge_sort(names, 5163);
for (i = 0; i < 5163; i++)
{
for (j = 0; names[i][j] != '\0'; j++)
{
sum += names[i][j] - 'A' + 1;
}
total += sum * (i + 1);
sum = 0;
}
printf("%d\n", total);
free(names);
fclose(fin);
return 0;
}
<file_sep>#include <stdio.h>
/* answer: 104743 */
/* version 1 */
int main()
{
int prime_set[10001];
int* ptr = prime_set + 1;
int index = 2;
int number = 5;
int i;
int flag = 1;
int key = 0;
int k = 1;
prime_set[0] = 2;
prime_set[1] = 3;
while (index < 10001)
{
/* generate primes */
for (i = *ptr; i*i <= number; i = *(++ptr))
{
if (number % i == 0)
{
flag = 0;
break;
}
}
if (flag) prime_set[index++] = number;
flag = 1;
if (key)
{
number = 6*k - 1;
key = 0;
}
else
{
number = 6*k + 1;
k++;
key = 1;
}
ptr = prime_set + 1;
}
printf("prime: %d\tindex: %d\n", prime_set[index - 1], index);
return 0;
}
<file_sep>#include <stdio.h>
/* answer: 213168 */
/* version 1 */
/*
int main()
{
int sum3 = 0;
int sum5 = 0;
int sum15 = 0;
int i;
int j = 1;
for (i = 1; 3*i < 1000; i++)
{
sum3 += 3*i;
++j;
}
for (i = 1; 5*i < 1000; i++)
{
sum5 += i*5;
++j;
}
for (i = 0; i*15 < 1000; i++)
{
sum15 += 15*i;
++j;
}
printf("sum: %d\ni: %d", sum3 + sum5 - sum15, j);
return 0;
}
*/
/* version 1.1 */
/*
int main()
{
int sum = 0;
int i;
for (i = 0; 3*i < 1000; i++)
{
for (; 5*i < 1000; i++)
{
for (; 15*i < 1000; i++)
{
sum += -15*i + 5*i + 3*i;
}
sum += 5*i + 3*i;
}
sum += 3*i;
}
printf("sum: %d\ni: %d", sum, i);
return 0;
}
*/
/* version 1.2 */
int main()
{
int numberof_3_multiplies = 999/3;
int numberof_5_multiplies = 999/5;
int numberof_15_multiplies = 999/15;
int sum = 0;
sum += (numberof_3_multiplies*(3 + 999))/2;
sum += (numberof_5_multiplies*(5 + 995))/2;
sum -= (numberof_15_multiplies*(15 + 990))/2;
printf("sum: %d\n", sum);
return 0;
}
<file_sep>#include <stdio.h>
/* answer: 4782 */
/* version 1 */
// ToDo: use Binet's formula
int main()
{
int fn[1000] = {0};
int fn_1[1000] = {0};
int fn_2[1000] = {0};
int i;
int index;
int carry = 0;
int tmp;
int counter = 2;
fn_1[999] = 1;
fn_2[999] = 1;
index = 998;
while (index > -1)
{
carry = 0;
for (i = 999; i > index; i--)
{
tmp = fn_1[i] + fn_2[i] + carry;
fn[i] = tmp % 10;
carry = tmp / 10;
}
if (carry)
{
fn[index] = carry;
index--;
}
for (i = 999; i > index; i--)
{
fn_1[i] = fn_2[i];
fn_2[i] = fn[i];
}
counter++;
}
for (i = 0; i < 1000; i++)
{
printf("%d", fn[i]);
}
printf("\n%d\n", counter);
return 0;
}
<file_sep>#include <stdio.h>
/* answer 25164150 */
/* version 1 */
int main()
{
int sumof_squares;
int squareof_sums;
int diff;
squareof_sums = (100*(100 + 1)*(2*100 + 1))/6;
sumof_squares = ((100*(100 + 1))/2)*((100*(100 + 1))/2);
diff = sumof_squares - squareof_sums;
printf("diff: %d\n", diff);
return 0;
}
<file_sep>#include <stdio.h>
/**/
/**/
int main()
{
int num[20];
int den[20];
int i, j, k;
long long n = 1;
int d = 1;
int found = 0;
for (i = 0; i < 20; i++)
{
num[i] = i + 21;
}
for (i = 0; i < 20; i++)
{
den[i] = i + 1;
}
for (i = 20; i > 1; i--)
{
for (j = 0; j < 20; j++)
{
if (num[j] % i == 0)
{
for (k = 0; k < 20; k++)
{
if (den[k] % i == 0)
{
den[k] /= i;
found = 1;
break;
}
}
if (found)
{
num[j] /= i;
found = 0;
//break;
}
}
}
}
for (i = 0; i < 20; i++)
{
n *= num[i];
d *= den[i];
}
printf("%lld\n", n/d);
}
<file_sep>#include <stdio.h>
int main()
{
char init[] = {"one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen",
"seventeen", "eighteen", "nineteen", "twenty"
}
for (i = 0; i < 20; i++)
{
sum += strlen(init);
}
for (i = 21; i < 1001; i++)
{
dfjgdfsjh;
}
}
<file_sep>#include <stdio.h>
/* answer: 76576500 */
/* version ?*/
/*
int main()
{
int base = 3;
int tri_num;
int i, j;
int counter = 1;
int found = 0;
int composite = 0;
int index = 2;
int tmp;
int primes[1000000] = {0};
int tally[1000000];
int flag = 0;
for (i = 0; i < 1000000; i++)
{
tally[i] = 1;
}
primes[0] = 2;
primes[1] = 3;
while (!found)
{
counter = 1;
base++;
tri_num = (base*(base + 1)) / 2;
for (i = primes[index - 1] + 1; i <= tri_num / 2; i++)
{
for (j = 0; primes[j]*primes[j] <= i && j < index; j++)
{
composite = 0;
if (i % primes[j] == 0)
{
composite = 1;
break;
}
}
if (!composite)
{
primes[index++] = i;
}
}
for (i = 0; (i < index) && !flag; i++)
{
while (tri_num % primes[i] == 0)
{
tally[i] += 1;
tri_num /= primes[i];
if (tri_num == 1) flag = 1;
}
}
flag = 0;
for (j = 0; j < index; j++)
{
counter *= tally[j];
tally[j] = 1;
}
if (counter > 400) found = 1;
}
printf("%d\t%d\n", tmp, counter);
return 0;
}
*/
/* theory: For every exact divisorup to the square root,
* there is a corresponding divisor above the square root
*/
int main()
{
int tri_num;
int base = 1;
int found = 0;
int counter = 0;
int i;
while (!found)
{
counter = 0;
tri_num = (base*(base + 1)) / 2;
for (i = 1; i*i <= tri_num; i++)
{
if (tri_num % i == 0) counter += 2;
}
if (counter > 500) found = 1;
else base++;
}
printf("%d\t%d\n", tri_num, counter);
}
<file_sep>#include <stdio.h>
/* answer: 4613732 */
/*version 1 */
/*
int main()
{
int x = 1;
int y = 2;
int z;
int i;
long long int sum = 0;
//for (i = 0; i < 10; i++)
//{
//z = x + y;
//x = y;
//y = z;
//printf("%d\n", z);
//}
x = 1;
y = 2;
while (y < 4000000)
{
if (y % 2 == 0) sum += y;
y = y + x;
x = y - x;
}
printf("%lld\n", sum);
return 0;
}
*/
int main()
{
int x = 1;
int y = 2;
long long int sum = 2;
while (y < 4000000)
{
sum += y;
y = y + x;
x = y - x;
y = y + x;
x = y - x;
y = y + x;
x = y - x;
}
printf("%lld\n", sum);
return 0;
}
<file_sep>#include <stdio.h>
#include <math.h>
/* answer: 837799 */
/* version 1 */
int main()
{
int num;
unsigned long tmp;
int numberof_terms = 1;
int max = 0;
int target;
for (num = 999999; num > 500000; num--)
{
tmp = num;
while (tmp != 1)
{
/* does'n optimize at all! */
/*if (log2(tmp) - (int)log2(tmp) == 0)
{
numberof_terms += log2(tmp) + 1;
break;
}*/
if (tmp % 2 == 0) tmp /= 2;
else tmp = 3 * tmp + 1;
numberof_terms++;
}
if (numberof_terms > max)
{
max = numberof_terms;
target = num;
}
numberof_terms = 0;
}
printf("target: %d\tterms: %d\n", target, max);
return 0;
}
/* backtracking solution, not working yet */
/*
int main()
{
long long int powof_two = 1;
int i;
for (i = 0; i < 10; i++)
{
powof_two *= 2;
}
while ((powof_two - 1) % 3 != 0)
{
powof_two /= 2;
}
i = 0;
while (i < 500)
{
if ((powof_two - 1) % 3 == 0)
{
powof_two = (powof_two - 1) / 3;
continue;
}
else
{
powof_two *= 2;
}
i++;
}
printf("%lld\n", powof_two);
}
*/
<file_sep>#include <stdio.h>
#include <math.h>
int main()
{
//int a, b, c;
int m = 1;
int n = 0;
int i, j, k;
int flag = 0;
/*do {
a = m * m - n * n;
b = 2 * m * n;
c = m * m + n * n;
m++;
n++;
} while (a + b + c != 1000);
*/
for (i = 0; i < 4 && !flag; i++)
{
for (j = 0; j < 4 && !flag; j++)
{
m = pow(2, i) * pow(5, j);
for (n = 1; n < m; n++)
{
if ((2 * m * (m + n)) == 1000)
{
flag = 1;
break;
}
}
}
}
printf("%d\t%d\t%d\n", m*m - n*n, 2*m*n, m*m + n*n);
return 0;
}
<file_sep>project-euler
=============
Answer to project Euler's programming challenges
<file_sep>#include <stdio.h>
/* answer: 6857 */
/* version 1.1 */
/* every number n can at most have one prime factor greater than sqrt(n) */
int main()
{
int primes[1000];
long long num = 600851475143L;
int index = 1;
int i, j;
int prime = 1;
//int base = 7;
primes[0] = 3;
while (num != 1)
{
// generate primes
for (i = primes[index - 1] + 2; !prime; i += 2)
{
prime = 1;
for (j = 0; primes[j]*primes[j] <= i; j++)
{
if (i % primes[j] == 0)
{
prime = 0;
break;
}
}
if (prime) primes[index++] = i;
}
prime = 0;
while (num % primes[index - 1] == 0)
{
num /= primes[index - 1];
}
}
printf("%d\t%d\n", primes[index - 1], index);
return 0;
}
//for (i = primes[index - 1] + 2; i < base; i += 2)
//{
//prime = 1;
//for (j = 0; primes[j]*primes[j] <= i; j++)
//{
//if (i % primes[j] == 0)
//{
//prime = 0;
//break;
//}
//}
//if (prime)
//{
//primes[index++] = i;
//}
//}
//base += 2;
<file_sep>#include <stdio.h>
int main()
{
int num[159] = {0};
int aux[159] = {0};
int i, j, k, m;
int tmp;
int carry;
int sum = 0;
int a = 100;
aux[158] = num[158] = 1;
for (i = 0; i < 100; i++)
{
for (j = 0; j < i; j++)
{
tmp = 0;
carry = 0;
for (k = 158; k > -1 + a; k--)
{
tmp = aux[k] + num[k] + carry;
num[k] = tmp % 10;
carry = tmp / 10;
}
}
a--;
for (m = 158; m > -1; m--)
{
aux[m] = num[m];
}
}
for (i = 0; i < 159; i++)
{
sum += num[i];
}
printf("%d\n", sum);
return 0;
}
<file_sep>#include <stdio.h>
/* answer: 906609 */
/* version 1 */
int reverse(int a)
{
int reverse = 0;
while (a > 0)
{
reverse = (10 * reverse) + (a % 10);
a /= 10;
}
return reverse;
}
/*
int main()
{
int i, j;
for (i = 999*999; i > 100*100; i--)
{
if (i == reverse(i))
{
for (j = 999; j > 99; j--)
{
if (i % j == 0 && (i / j) / 1000 == 0)
{
printf("%d\t%d\n", i, i/j);
break;
}
}
}
}
return 0;
}
*/
/* version 1.1 */
int main()
{
int i, j;
int r;
int flag = 1;
for (i = 997; i > 99 && flag; i--)
{
r = i*1000 + reverse(i);
for (j = 999; j > 99; j--)
{
if (r % j == 0 && (r / j) / 100 != 0 && (r / j) / 1000 == 0)
{
printf("%d: %d x %d\n", r, j, r / j);
flag = 0;
break;
}
}
}
return 0;
}
<file_sep>#include <stdio.h>
#include <string.h>
/* answer: 5537376230390876637302048746832985971773659831892672 */
/* version 1 */
/* TODO: How many numbers should be calculated to obtain n correct digits ? */
int main()
{
FILE *fin = fopen("13.txt", "r");
int table[100][52];
int sum[52] = {0};
int partial_sum = 0;
int carry = 0;
int i, j;
char flag;
for (i = 0; i < 100 && flag != EOF; i++)
{
for (j = 0; j < 52 && flag != EOF; j++)
{
if (j < 2)
{
table[i][j] = 0;
continue;
}
flag = fgetc(fin);
if (flag >= '0' && flag <= '9') table[i][j] = flag - '0';
else if (flag == '\n') j--;
else if (flag == EOF) continue;
}
}
fclose(fin);
for (i = 0; i < 100; i++)
{
partial_sum = 0;
carry = 0;
for (j = 12; j > -1; j--)
{
partial_sum = sum[j] + table[i][j] + carry;
sum[j] = partial_sum % 10;
carry = partial_sum / 10;
}
}
for (i = 0; i < 52; i++)
{
printf("%d", sum[i]);
}
printf("\n");
return 0;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
/* answer: 70600674 */
/* version 1 */
int main()
{
FILE *fin = fopen("11.txt", "r");
int table[20][20];
int arr[4][4];
int i, j;
int left_col = 1;
int right_col = 1;
int hprdct = 1;
int vprdct = 1;
int major_dprdct = 1;
int minor_dprdct = 1;
int hv_max;
int d_max;
int max = 0;
int counter = 0;
int x = 0;
int y = 0;
char flag;
for (i = 0; i < 20 && flag != EOF; i++)
{
for (j = 0; j < 20 && flag != EOF; j++)
{
//flag = fgets(s, 3, fin);
flag = fscanf(fin, "%d", &table[i][j]);
//table[i][j] = counter;
//fseek(fin, 1, SEEK_CUR);
}
//fseek(fin, 60 - 12, SEEK_CUR);
}
//fseek(fin, 4 * (-60) + 3, SEEK_CUR);
while (x != 17 || y != 17)
{
if (y == 17) y = 0;
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
arr[i][j] = table[x + i][y + j];
}
}
y++;
if (y == 17) x++;
right_col = 1;
for (i = 0; i < 4; i++)
{
right_col *= arr[i][3];
}
if (right_col > left_col)
{
counter++;
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
hprdct *= arr[i][j];
vprdct *= arr[j][i];
if (i == j) major_dprdct *= arr[i][j];
if (i + j == 3) minor_dprdct *= arr[i][j];
}
hv_max = hprdct > vprdct ? hprdct : vprdct;
hprdct = vprdct = 1;
}
d_max = major_dprdct > minor_dprdct ? major_dprdct : minor_dprdct;
major_dprdct = minor_dprdct = 1;
max = hv_max > max ? hv_max : max;
max = d_max > max ? d_max : max;
}
left_col = 1;
for (i = 0; i < 4; i++)
{
left_col *= arr[i][0];
}
}
printf("%d\n%d\n", max, counter);
return 0;
}
<file_sep>#include <stdio.h>
/* answer: 142913828922 */
/* version 1.1 */
int main()
{
long int prime_set[1999999];
long int *ptr = prime_set + 1;
long int number = 5;
unsigned long long sum = 5; /* prevent overflow */
int index = 2;
int i;
int flag = 1;
int key = 0;
int k = 1;
prime_set[0] = 2;
prime_set[1] = 3;
while (number < 2000000)
{
for (i = *ptr; i*i <= number; i = *(++ptr))
{
if (number % i == 0)
{
flag = 0;
break;
}
}
if (flag)
{
prime_set[index++] = number;
if (number < 2000000)
sum += number;
//else break;
}
flag = 1;
if (key)
{
number = 6*k - 1;
key = 0;
}
else
{
number = 6*k + 1;
k++;
key = 1;
}
ptr = prime_set + 1;
}
printf("prime: %ld\tindex: %d\tsum: %lld\n", prime_set[index - 1], index, sum);
return 0;
}
<file_sep>#include <stdio.h>
/* answer: 1366 */
/* version 1 */
int main()
{
/* number of digits = [log(2^1000)] + 1 */
short the_number[302] = {0};
int i, j;
int tmp;
int carry = 0;
int sum = 0;
int tail = 300;
the_number[301] = 1;
for (i = 0; i < 1000; i++)
{
for (j = 301; j > tail; j--)
{
tmp = the_number[j] * 2;
if (tmp < 10)
{
the_number[j] = tmp;
the_number[j] += carry;
carry = 0;
}
else
{
the_number[j] = tmp - 10;
the_number[j] += carry;
carry = 1;
}
}
if (carry == 1)
{
the_number[tail--] += 1;
carry = 0;
}
}
for (i = tail + 1; i < 302; i++)
{
printf("%d", the_number[i]);
sum += the_number[i];
}
printf("\nsum: %d\n", sum);
return 0;
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int fact(int **p, int n)
{
double sum = (double)0;
int no_digits = 0;
int partial_sum;
int carry;
int *tmp;
int index;
int i, j, k, m;
/* calculating number of digits */
if (n > 0)
{
for (i = 1; i < n + 1; i++)
{
sum += log10(i);
}
no_digits = (int)sum + 1;
}
else if (n == 0) no_digits = 1;
else return -1;
*p = malloc(no_digits * sizeof(int));
if (*p == NULL) return -1;
tmp = malloc(no_digits * sizeof(int));
if (tmp == NULL) return -1;
/* initializing */
for (i = 0; i < no_digits; i++)
{
*(*p + i) = 0;
tmp[i] = 0;
}
*(*p + no_digits - 1) = 1;
tmp[no_digits - 1] = 1;
/* optimization */
if (no_digits == 1) index = -1;
else index = no_digits - 2;
/* main alogrithm */
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < i + 1; j++)
{
partial_sum = 0;
carry = 0;
for (k = no_digits - 1; k > index; k--)
{
partial_sum = *(*p + k) + tmp[k] + carry;
*(*p + k) = partial_sum % 10;
carry = partial_sum / 10;
}
if (index > -1) index--;
}
for (m = 0; m < no_digits; m++)
{
tmp[m] = *(*p + m);
}
}
return no_digits;
}
int main()
{
int *ptr;
int i;
int no;
no = fact(&ptr, 10000);
for (i = 0; i < no; i++)
{
printf("%d", ptr[i]);
}
printf("\n");
free(ptr);
return 0;
}
|
9d0cdffd2165d02933e1eede5d3aeaa67153cc83
|
[
"Markdown",
"C"
] | 20 |
C
|
mahyarap/project-euler
|
1f52f2507705d65ea7f585c256376023daeb0298
|
60d7044dc5dd62cfbb94732a3949a955dbc85e29
|
refs/heads/master
|
<file_sep>#!/bin/sh
VIMHOME=~/.dot_proj/vim
warn() {
echo "$1" >&2
}
die() {
warn "$1"
exit 1
}
git clone https://github.com/dotfile-projects/vim.git "$VIMHOME"
cd "$VIMHOME"
sh run.sh
echo "Install complate!!!"
|
54afd0b5557f4cfd5f7896f254c806c08ddd37b1
|
[
"Shell"
] | 1 |
Shell
|
dotfile-projects/vim
|
ceadfa04de0b50a34d7743eaa0aae39fe770776c
|
dc1a03b00a7dd0a49afe02cdaa86ef3a33eae844
|
refs/heads/main
|
<file_sep>// this will login
<file_sep>import React from "react";
import { Navbar, Nav } from "react-bootstrap";
// import { BrowserRouter as Router, Link, Route } from "react-router-dom";
// import "./style.css";
function Header() {
return (
<div>
<Navbar bg="light" variant="light">
<Navbar.Brand href="#home">NER for ESL</Navbar.Brand>
<Navbar.Toggle aria-controls="responsive-navbar-nav" />
<Navbar.Collapse id="responsive-navbar-nav">
<Nav className="mr-auto">
<Nav.Link href="#home">Home</Nav.Link>
<Nav.Link href="#features">Features</Nav.Link>
<Nav.Link href="#pricing">Pricing</Nav.Link>
</Nav>
<Nav>
<Nav.Link href="#login">Login</Nav.Link>
</Nav>
</Navbar.Collapse>
</Navbar>
</div>
);
}
export default Header;
<file_sep>import React from "react";
import "./style.scss";
function App() {
return <Desktop1 {...Desktop1Data} />;
}
export default App;
function Desktop1(props) {
const {
text1,
font1,
address,
spanText,
spanText2,
spanText3,
untitledDesign81,
backgroundProps,
footerMini6Props,
linksRow2Props,
frameProps,
adjustablePrimaryLargeProps,
header7Props,
previewCardProps,
} = props;
return (
<div className="desktop-1">
<div className="overlap-group">
<Background
purpleCircle={backgroundProps.purpleCircle}
turquoiseCircle={backgroundProps.turquoiseCircle}
bg={backgroundProps.bg}
group1Props={backgroundProps.group1Props}
/>
<FooterMini6 untitledDesign91={footerMini6Props.untitledDesign91} />
<LinksRow2
about={linksRow2Props.about}
features={linksRow2Props.features}
license={linksRow2Props.license}
help={linksRow2Props.help}
privacyPolicy={linksRow2Props.privacyPolicy}
/>
<Frame copyright={frameProps.copyright} />
<h1 className="text-1 manrope-extra-bold-eerie-black-72px">{text1}</h1>
<AdjustablePrimaryLarge
labelI541147={adjustablePrimaryLargeProps.labelI541147}
/>
<Header7
untitledDesign81={header7Props.untitledDesign81}
text2={header7Props.text2}
labelI551367={header7Props.labelI551367}
labelI551646={header7Props.labelI551646}
labelI551365={header7Props.labelI551365}
labelI551357={header7Props.labelI551357}
vector={header7Props.vector}
/>
<div className="font-1 manrope-extra-bold-black-18px">{font1}</div>
<PreviewCard
line1={previewCardProps.line1}
namedentityextraction1={previewCardProps.namedentityextraction1}
/>
<div className="address manrope-bold-black-18px">{address}</div>
<div className="text-3 manrope-extra-bold-white-28px">
<span className="span">{spanText}</span>
<span className="span1">{spanText2}</span>
<span className="span">{spanText3}</span>
</div>
<img
className="untitled-design-8-1-1"
alt="esl icon"
src={untitledDesign81}
/>
</div>
</div>
);
}
function Background(props) {
const { purpleCircle, turquoiseCircle, bg, group1Props } = props;
return (
<div className="background">
<div className="overlap-group1">
<img className="purple-circle" alt="purple cirlce" src={purpleCircle} />
<img
className="turquoise-circle"
alt="turquoise cirlce"
src={turquoiseCircle}
/>
<img className="bg" alt="background" src={bg} />
<Group1
leftBand2={group1Props.leftBand2}
leftBand1={group1Props.leftBand1}
rightBand1={group1Props.rightBand1}
rightBand2={group1Props.rightBand2}
rightBand3={group1Props.rightBand3}
/>
</div>
</div>
);
}
function Group1(props) {
const { leftBand2, leftBand1, rightBand1, rightBand2, rightBand3 } = props;
return (
<div className="group-1">
<div className="overlap-group3">
<img className="left-band-2" alt="background shape" src={leftBand2} />
<img className="left-band-1" alt="background shape" src={leftBand1} />
</div>
<div className="overlap-group2">
<img className="right-band-1" alt="background shape" src={rightBand1} />
<img className="right-band-2" alt="background shape" src={rightBand2} />
<img className="right-band-3" alt="background shape" src={rightBand3} />
</div>
</div>
);
}
function FooterMini6(props) {
const { untitledDesign91 } = props;
return (
<div className="footer-mini-6">
<img
className="untitled-design-9-1"
alt="esl icon"
src={untitledDesign91}
/>
</div>
);
}
function LinksRow2(props) {
const { about, features, license, help, privacyPolicy } = props;
return (
<div className="links-row-2">
<div className="about manrope-normal-white-16px">{about}</div>
<div className="features manrope-normal-white-16px">{features}</div>
<div className="license manrope-normal-white-16px">{license}</div>
<div className="help manrope-normal-white-16px">{help}</div>
<div className="privacy-policy manrope-normal-white-16px">
{privacyPolicy}
</div>
</div>
);
}
function Frame(props) {
const { copyright } = props;
return (
<div className="frame">
<p className="copyright manrope-normal-alto-14px">{copyright}</p>
</div>
);
}
function AdjustablePrimaryLarge(props) {
const { labelI541147 } = props;
return (
<div className="adjustable-primary-large">
<div className="label-i541147 manrope-bold-white-20px">
{labelI541147}
</div>
</div>
);
}
function Header7(props) {
const {
untitledDesign81,
text2,
labelI551367,
labelI551646,
labelI551365,
labelI551357,
vector,
} = props;
return (
<div className="header-7">
<img
className="untitled-design-8-1"
alt="esl icon"
src={untitledDesign81}
/>
<div className="text-2 manrope-bold-black-20px">{text2}</div>
<div className="overlap-group4">
<div className="right-nav"></div>
<div className="nav-items">
<div className="label-i551367 manrope-bold-eerie-black-14px">
{labelI551367}
</div>
<div className="label-i551646 manrope-bold-eerie-black-14px">
{labelI551646}
</div>
<div className="label-i551365 manrope-bold-eerie-black-14px">
{labelI551365}
</div>
<div className="header-menu-dropdown">
<div className="label-i551357 manrope-bold-eerie-black-14px">
{labelI551357}
</div>
<div className="essential-icons-chevron-down">
<img className="vector" alt="arrow down icon" src={vector} />
</div>
</div>
<div className="menu-item-default"></div>
</div>
</div>
</div>
);
}
function PreviewCard(props) {
const { line1, namedentityextraction1 } = props;
return (
<div className="preview-card">
<div className="content">
<div className="feedback-person-details"></div>
</div>
<img className="line-1" alt="line vector" src={line1} />
<img
className="namedentityextraction-1"
alt="ner example"
src={namedentityextraction1}
/>
</div>
);
}
const group1Data = {
leftBand2:
"https://anima-uploads.s3.amazonaws.com/projects/604159adc5e397710c55b205/releases/604159be40730c056abbd273/img/[email protected]",
leftBand1:
"https://anima-uploads.s3.amazonaws.com/projects/604159adc5e397710c55b205/releases/604159be40730c056abbd273/img/[email protected]",
rightBand1:
"https://anima-uploads.s3.amazonaws.com/projects/604159adc5e397710c55b205/releases/604159be40730c056abbd273/img/[email protected]",
rightBand2:
"https://anima-uploads.s3.amazonaws.com/projects/604159adc5e397710c55b205/releases/604159be40730c056abbd273/img/[email protected]",
rightBand3:
"https://anima-uploads.s3.amazonaws.com/projects/604159adc5e397710c55b205/releases/604159be40730c056abbd273/img/[email protected]",
};
const backgroundData = {
purpleCircle:
"https://anima-uploads.s3.amazonaws.com/projects/604159adc5e397710c55b205/releases/604159be40730c056abbd273/img/[email protected]",
turquoiseCircle:
"https://anima-uploads.s3.amazonaws.com/projects/604159adc5e397710c55b205/releases/604159be40730c056abbd273/img/[email protected]",
bg:
"https://anima-uploads.s3.amazonaws.com/projects/604159adc5e397710c55b205/releases/604159be40730c056abbd273/img/[email protected]",
group1Props: group1Data,
};
const footerMini6Data = {
untitledDesign91:
"https://anima-uploads.s3.amazonaws.com/projects/604159adc5e397710c55b205/releases/604159be40730c056abbd273/img/[email protected]",
};
const linksRow2Data = {
about: "About",
features: "Features",
license: "License",
help: "Help",
privacyPolicy: "Privacy Policy",
};
const frameData = {
copyright: "© 2020 NER for ESL. All rights reserved",
};
const adjustablePrimaryLargeData = {
labelI541147: "Get Started",
};
const header7Data = {
untitledDesign81:
"https://anima-uploads.s3.amazonaws.com/projects/604159adc5e397710c55b205/releases/604159be40730c056abbd273/img/[email protected]",
text2: "NER for ESL",
labelI551367: "About",
labelI551646: "Features",
labelI551365: "Blog",
labelI551357: "More",
vector:
"https://anima-uploads.s3.amazonaws.com/projects/604159adc5e397710c55b205/releases/604159be40730c056abbd273/img/[email protected]",
};
const previewCardData = {
line1:
"https://anima-uploads.s3.amazonaws.com/projects/604159adc5e397710c55b205/releases/604159be40730c056abbd273/img/[email protected]",
namedentityextraction1:
"https://anima-uploads.s3.amazonaws.com/projects/604159adc5e397710c55b205/releases/604159be40730c056abbd273/img/[email protected]",
};
const Desktop1Data = {
text1: "Enhance your fluency.",
font1: "LOG IN",
address: "27 tags",
spanText: "Input any English text and our ",
spanText2: "named-entity recognition",
spanText3:
" AI model will help you identify proper nouns and learn unknown vocabulary.",
untitledDesign81:
"https://anima-uploads.s3.amazonaws.com/projects/604159adc5e397710c55b205/releases/604159be40730c056abbd273/img/[email protected]",
backgroundProps: backgroundData,
footerMini6Props: footerMini6Data,
linksRow2Props: linksRow2Data,
frameProps: frameData,
adjustablePrimaryLargeProps: adjustablePrimaryLargeData,
header7Props: header7Data,
previewCardProps: previewCardData,
};
<file_sep># NER-for-ESL
|
61743ca891c450b8a7e839d2f0a8e880874f1695
|
[
"JavaScript",
"Markdown"
] | 4 |
JavaScript
|
avnoto/NER-for-ESL
|
0b2454ccfbbceffdbecbb2bba4da3a13c32f7c56
|
9a70b63035a8972e451fa302c10463216ae121e3
|
refs/heads/main
|
<repo_name>Kneck12/covid-vaccination-flight-levels<file_sep>/.ipynb_checkpoints/file_consol-checkpoint.py
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "b95ac170",
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"\n",
"import os\n",
"\n",
"flight_data=pd.read_csv('flight_data12.csv')\n",
"\n",
"counter=13\n",
"directory = r'/Users/moritz/Desktop/private_repository/flight_analysis/flight_data'\n",
"for entry in os.scandir(directory):\n",
" if entry.path.endswith(\".csv\") and entry.is_file():\n",
" csv_data=pd.read_csv(entry)\n",
" flight_data=pd.concat([flight_data,csv_data],axis=0, sort=False)\n",
" flight_data.to_csv(f'flight_data{counter}.csv')\n",
" print (counter)\n",
" print ('\\n')\n",
" print (entry)\n",
" counter+=1"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.8"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
<file_sep>/README.md
# covid-vaccination-flight-levels
Analysis of impact of COVID vaccination rates on the return of air traffic to pre covid levels
Research question and result overview available at https://docs.google.com/presentation/d/1HKj2pFCa-pj3hAhTwpqigHJ8Tjvx3Tcg6jm2LkI8ls4/edit?usp=sharing
Detailed blog post available at TBD
|
9a44ea41f0d00c13541419b63a21ebed8b7c494c
|
[
"Markdown",
"Python"
] | 2 |
Python
|
Kneck12/covid-vaccination-flight-levels
|
23409755588e6f21ed0fec09890718e584c8b649
|
4ca38bfbb0cfba504ae2bb6fceb20248e3201164
|
refs/heads/master
|
<repo_name>IgnacioArredondo/tfg<file_sep>/task.js
const express = require('express');
const Task = require('../models/task');
const User = require('../models/user');
const Project= require('../models/project')
const createError = require('http-errors');
const Verify = require('./verify');
let router = express.Router();
let rootRoute = router.route('/');
/* GET Query tasks. */
rootRoute.get(function(req, res, next) {
let query = {
deleted: null
};
const projection = {
name: true,
details: true,
state: true,
project: true,
user:true,
end_date:true,
estimated_time:true,
activities:true,
};
Task.find(query, projection, (err, tasks) => {
if (err) {
return next(createError(500));
}
return res.status(200).send(tasks);
});
});
let checkTaskNameRoute = router.route('/checktaskname');
checkTaskNameRoute.all(Verify.verifyOrdinaryUser);
checkTaskNameRoute.get(function(req, res, next) {
let name = req.query.name.toLowerCase();
const projection =
{
name: true,
};
Task.findOne({name: new RegExp(name)}, projection, (err, task) => {
if (err) {
return next(createError(500));
}
console.log(task);
console.log(name);
if (task) {
task.name=task.name.toLowerCase();
if (task.name === name) {
return res.status(401).json({
err: 'Task name already exists'
});
}
}
return res.status(200).send({message: 'Task name does not exist'});
});
});
/* POST create new task. */
rootRoute.post(function(req, res, next) {
const data = req.body;
// create new task from data
const task = new Task({
name: data.name,
details: data.details,
project: data.project,
state: data.state,
user: data.user,
start_date: data.start_date,
end_date: data.end_date,
estimated_time: data.estimated_time,
activities:data.activities,
});
// insert task into db
task.save((err) => {
if (err) {
return next(createError(400, err));
}
return res.status(201).send(task);
});
});
let userTaskRoute = router.route('/user-tasks');
userTaskRoute.all(Verify.verifyOrdinaryUser);
/* GET retrieve task by id. */
userTaskRoute.get(function(req, res, next) {
// return only these fields from the user + the _id
const projection = {
name: true,
details: true,
project: true,
state: true,
user: true,
start_date: true,
end_date: true,
estimated_time: true,
activities:true,
};
//extraer usuario token y leer tareas campo user donde coincide el id
let user=req.decoded.user;
let query = {
user:user,
deleted: null
};
Task.find(query, projection, (err, tasks) =>
{
if (err)
{
console.log(err);
return next(createError(500));
}
return res.status(200).send(tasks);
})
});
/*
--------------------------------------------------------------------------------------------------------
*/
let userDashTaskRoute = router.route('/dashboard');
userDashTaskRoute.all(Verify.verifyOrdinaryUser);
/* GET retrieve task by id. */
userDashTaskRoute.get(function(req, res, next) {
// return only these fields from the user + the _id
const projection = {
name: true,
details: true,
project: true,
state: true,
user: true,
start_date: true,
end_date: true,
estimated_time: true,
activities:true,
};
let user=req.decoded.user;
let query = {
user:user,
deleted: null
};
// Task.find({end_date: {"$lte":new Date()},user}
Task.find(query,projection)
.populate("project").then((tasks) => {
return res.status(200).send(tasks);
});
});
/*
-------------------------------------------------------------------------------------------------------
*/
let DashTaskRoute = router.route('/todotask');
DashTaskRoute.all(Verify.verifyOrdinaryUser);
DashTaskRoute.get(function(req, res, next) {
let query = {
deleted: null
};
let user=req.decoded.user;
const projection = {
name: true,
};
//Task.find({end_date: {"$gte":new Date()},user}, projection, (err, tasks) => {
Task.find(query, projection, (err, tasks) => {
if (err)
{
console.log(err);
return next(createError(500));
}
}).count(function(err, count){
console.log(count);
return res.status(200).send(String(count));
});
});
/*
--------------------------------------------------------------------------------------------------
*/
let adminOverdueTaskRoute = router.route('/overduetask');
adminOverdueTaskRoute.all(Verify.verifyOrdinaryUser);
adminOverdueTaskRoute.get(function(req, res, next) {
let query = {
deleted: null
};
const projection = {
name: true,
details: true,
project: true,
state: true,
user: true,
start_date: true,
end_date: true,
estimated_time: true,
activities:true,
};
//Task.find({end_date: {"$lte":new Date()}}, projection, (err, tasks) => {
Task.find(query, projection)
.populate("project").then((tasks) => {
return res.status(200).send(tasks);
});
});
/*
-----------------------------------------
------------------------------------------
-----------------------------------------
--------------------------------------------------------------------------------------------------
*/
let adminTaskProjectRoute = router.route('/taskproject');
adminTaskProjectRoute.all(Verify.verifyOrdinaryUser);
adminTaskProjectRoute.get(function(req, res, next) {
let t;
const projection = {
name: true,
project:true,
}
Task.aggregate( [
{ $match: {end_date: {"$gte":new Date()}}},
{ $group: { _id: "$project", count:{ $sum: 1}}},
], function(err, result)
{
console.log(result);
Project.populate(result, {path: '_id'}, function(err, taskPopulate)
{
return res.status(200).send(taskPopulate);
});
});
});
/*
------------------------------------------------
---------------------------------------------------------
------------------------------------------------
-------------------------------------------
--------------------------------------------------------------------------------------------------
*/
let idRoute = router.route('/:id');
idRoute.all(Verify.verifyOrdinaryUser);
/* GET retrieve task by id. */
idRoute.get(function(req, res, next) {
// return only these fields from the user + the _id
const projection = {
name: true,
details: true,
project: true,
state: true,
user: true,
start_date: true,
end_date: true,
estimated_time: true,
activities:true,
};
Task.findOne({
_id: req.params.id,
deleted: null
}, projection, (err, task) => {
if (err) {
return next(createError(500));
}
}).populate('project').populate('user').exec(function(err,task)
{
return res.status(200).send(task);
});
});
/* PUT update task. */
idRoute.put(function(req, res, next) {
// the data to update with
const data = req.body;
// validate and update project
Task.update({
_id: req.params.id
}, {
$set: {
name: data.name,
details: data.details,
project: data.project,
state: data.state,
user: data.user,
start_date: data.start_date,
end_date: data.end_date,
estimated_time: data.estimated_time,
activities:data.activities,
}
}, (err) => {
if (err) {
return next(createError(400, err));
}
return res.status(204).send();
});
});
/* DELETE delete task. */
idRoute.delete(function(req, res, next) {
Task.update({
_id: req.params.id
}, {
$set: {
deleted: new Date()
}
}, (err) => {
if (err) {
return next(createError(400, err));
}
return res.status(204).send();
});
});
module.exports = router;
<file_sep>/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule, Http, RequestOptions } from '@angular/http';
import {HttpClientModule, HttpClient} from '@angular/common/http';
import { RouterModule, Routes } from '@angular/router';
import { ReactiveFormsModule} from '@angular/forms';
import { AppComponent } from './app.component';
import { ProjectsComponent } from './projects/projects.component';
import { ProjectNewComponent } from './project-new/project-new.component';
import { ProjectEditComponent } from './project-edit/project-edit.component';
import { ProjectDeleteComponent } from './project-delete/project-delete.component';
import { ProjectService} from './project.service';
import { HashLocationStrategy, LocationStrategy } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ClientNewComponent } from './client-new/client-new.component';
import { ClientEditComponent } from './client-edit/client-edit.component';
import { ClientDeleteComponent } from './client-delete/client-delete.component';
import { ClientComponent } from './client/client.component';
import { ClientService} from './client.service';
import { ProjectDetailComponent } from './project-detail/project-detail.component';
import { ClientDetailComponent } from './client-detail/client-detail.component';
import { TaskNewComponent } from './task-new/task-new.component';
import { TasksComponent } from './tasks/tasks.component';
import { TaskService } from './task.service';
import { Globals } from './globals';
import { MyTasksComponent } from './my-tasks/my-tasks.component';
import { ProjectTaskComponent } from './project-task/project-task.component';
import { DragulaModule, DragulaService } from '../../node_modules/ng2-dragula/ng2-dragula';
import { FlexLayoutModule } from '@angular/flex-layout';
import { MdSidenavModule} from '@angular/material';
import { BrowserAnimationsModule} from '@angular/platform-browser/animations';
import { MdCardModule, MdButtonModule, MdIconModule, MdIconRegistry} from '@angular/material';
import { MdToolbarModule} from '@angular/material';
import { MdMenuModule} from '@angular/material';
import { MaterialModule } from '@angular/material';
import { MdProgressBarModule} from '@angular/material';
import { MdDialogModule} from '@angular/material';
import { DialogInputComponent } from './dialog-input/dialog-input.component';
import { MdChipsModule} from '@angular/material';
import { HomeComponent } from './home/home.component';
import { ResourceService } from './resource.service';
import { TaskEditComponent } from './task-edit/task-edit.component';
import { TaskDetailComponent } from './task-detail/task-detail.component';
import { TaskDeleteComponent } from './task-delete/task-delete.component';
import { UserComponent } from './user/user.component';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
import { UserService } from './user.service';
import { ActivityService } from './activity.service';
import { AuthenticationService } from './authentication.service';
import { UserCreateComponent } from './user-create/user-create.component';
import { UserEditComponent } from './user-edit/user-edit.component';
import { UserDetailComponent } from './user-detail/user-detail.component';
import { UserDeleteComponent } from './user-delete/user-delete.component';
import { PasswordStrengthBarModule } from 'ng2-password-strength-bar';
import { GuardadoComponent } from './guardado/guardado.component';
import { RegisterSuccessComponent } from './register-success/register-success.component';
import { ConfirmComponent } from './confirm/confirm.component';
import { ConfirmFailedComponent } from './confirm-failed/confirm-failed.component';
import { ConfirmSuccessComponent } from './confirm-success/confirm-success.component';
import { AuthGuard } from './auth.guard';
import { AdminGuard } from './admin.guard';
import { AuthHttp, AuthConfig } from 'angular2-jwt';
import { AppRoutingModule } from './app.routing.module';
import { HistoricoComponent } from './historico/historico.component';
import { ActivityComponent } from './activity/activity.component';
import { UserPasswordComponent } from './user-password/user-password.component';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';
import {TranslateModule, TranslateLoader} from '@ngx-translate/core';
import { DashboardComponent } from './dashboard/dashboard.component';
export function authHttpServiceFactory(http: Http, options: RequestOptions) {
return new AuthHttp(new AuthConfig({
tokenName: 'projectAuth',
tokenGetter: (() => sessionStorage.getItem('projectAuth')),
globalHeaders: [{ 'Content-Type': 'application/json' }],
}), http, options);
}
export function createTranslateLoader(http: HttpClient) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
@NgModule({
declarations: [
AppComponent,
ProjectsComponent,
ProjectNewComponent,
ProjectEditComponent,
ProjectDeleteComponent,
ClientNewComponent,
ClientEditComponent,
ClientDeleteComponent,
ClientComponent,
ProjectDetailComponent,
ClientDetailComponent,
TaskNewComponent,
TasksComponent,
MyTasksComponent,
ProjectTaskComponent,
DialogInputComponent,
HomeComponent,
TaskEditComponent,
TaskDetailComponent,
TaskDeleteComponent,
UserComponent,
LoginComponent,
RegisterComponent,
UserCreateComponent,
UserEditComponent,
UserDetailComponent,
UserDeleteComponent,
GuardadoComponent,
RegisterSuccessComponent,
ConfirmComponent,
ConfirmFailedComponent,
ConfirmSuccessComponent,
HistoricoComponent,
ActivityComponent,
UserPasswordComponent,
DashboardComponent,
],
imports: [
BrowserModule,
ReactiveFormsModule,
FormsModule,
HttpModule,
HttpClientModule,
AppRoutingModule,
MaterialModule,
FormsModule,
DragulaModule,
FlexLayoutModule,
MdSidenavModule,
BrowserAnimationsModule,
MdToolbarModule,
MdCardModule,
MdButtonModule,
MdIconModule,
MdMenuModule,
MdProgressBarModule,
MdDialogModule,
MdChipsModule,
PasswordStrengthBarModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [HttpClient]
}
})
],
providers: [ProjectService, ClientService, Globals, TaskService, UserService, AuthenticationService, DragulaService, MdIconRegistry, ResourceService,ActivityService,
{ provide: LocationStrategy, useClass: HashLocationStrategy }, [AuthGuard],[AdminGuard],
{
provide: AuthHttp,
useFactory: authHttpServiceFactory,
deps: [Http, RequestOptions]
}
],
bootstrap: [AppComponent],
entryComponents: [DialogInputComponent],
})
export class AppModule { }
<file_sep>/users.js
const express = require('express');
const User = require('../models/user');
const createError = require('http-errors');
const passport = require('passport');
const Verify = require('./verify');
let router = express.Router();
let rootRoute = router.route('/');
rootRoute.all(Verify.verifyOrdinaryUser);
/* GET Query users. */
rootRoute.get(function(req, res, next) {
let query = {
deleted: null
};
if (req.query.username) {
query.username = req.query.username.toLowerCase();
}
if (req.query.email) {
query.email = req.query.email.toLowerCase();
}
// return only these fields from the user + the _id
const projection = {
username: true,
email: true,
role:true,
createdAt: true
};
User.find(query, projection, (err, user) => {
if (err) {
return next(createError(500));
}
return res.status(200).send(user);
});
});
let checkEmailRoute = router.route('/checkemail');
checkEmailRoute.all(Verify.verifyOrdinaryUser);
checkEmailRoute.get(function(req, res, next) {
let email = req.query.email.toLowerCase();
User.findOne({deleted: null, email: email}, (err, user) => {
if (err) {
// return next(createError(500));
return next(err);
}
if (user) {
if (user._id != req.query.userId) {
// return next(createError(400, 'Email already exists'));
return res.status(401).json({
err: 'Email already exists'
});
}
}
return res.status(200).send({message: 'email does not exist'});
});
});
let changePasswordRoute = router.route('/changepassword');
changePasswordRoute.all(Verify.verifyOrdinaryUser);
/* POST change password */
changePasswordRoute.post(function(req, res, next) {
// find the user
User.findOne({_id: req.body.userId}, function (err, user) {
if (err) {
return next(err);
}
user.setPassword(req.body.password, function (err) {
if (err) {
return next(err);
}
// user._id = '';
user.save();
return res.status(200).send({message: 'password changed'});
});
});
});
/* POST create new user. */
rootRoute.post(function(req, res, next) {
const data = req.body;
// create new user from data
const user = new User({
username: data.username,
email: data.email,
password:<PASSWORD>,
role:data.role,
});
// insert user into db
user.save((err) => {
if (err) {
return next(createError(400, err));
}
return res.status(201).send(user);
});
});
let idRoute = router.route('/:id');
idRoute.all(Verify.verifyOrdinaryUser);
/* GET retrieve user by id. */
idRoute.get(function(req, res, next) {
// return only these fields from the user + the _id
const projection = {
username: true,
userPassword: true,
email: true,
role:true,
createdAt: true
};
User.findOne({_id: req.params.id, deleted: null}, projection, (err, user) => {
if (err) {
return next(createError(500));
}
return res.status(200).send(user);
});
});
/* PUT update user. */
idRoute.put(function(req, res, next) {
// the data to update with
const data = req.body;
// validate and update user
User.update({_id: req.params.id}, {
$set: {
username: data.username,
email: data.email ? data.email.toLowerCase() : undefined,
userPassword: <PASSWORD>,
role:data.role,
}
}, (err) => {
if (err) {
return next(createError(400, err));
}
return res.status(204).send();
});
});
/* DELETE delete user. */
idRoute.delete(function(req, res, next) {
User.update({_id: req.params.id}, {
$set: {
deleted: new Date()
}
}, (err) => {
if (err) {
return next(createError(400, err));
}
return res.status(204).send();
});
});
let logoutRoute = router.route('/logout');
logoutRoute.get(function(req, res) {
req.logout();
res.status(200).json({
status: 'Bye!'
});
});
module.exports = router;
<file_sep>/task.service.ts
import { Injectable } from '@angular/core';
import { Task } from './task';
import { Http, Headers} from '@angular/http';
import { AuthenticationService } from './authentication.service';
import { environment } from '../environments/environment';
import { AuthHttp} from 'angular2-jwt';
import 'rxjs/add/operator/map';
@Injectable()
export class TaskService {
private api: string = "/tasks";
constructor(private http: AuthHttp, private authenticationService: AuthenticationService) { }
save(data: Task): Promise<Task>{
return new Promise((resolve, reject) => {
this.http.post(environment.apiEndpoint + this.api, data)
.map(res => res.json())
.subscribe(res => {
resolve(res);
}, (err) => {
reject(err);
});
});
}
update(id, data: Task): Promise<Task>{
return new Promise((resolve, reject) => {
this.http.put(environment.apiEndpoint + this.api + '/' + id, data)
.map(res => res.json())
.subscribe(res => {
resolve(res);
}, (err) => {
reject(err);
});
});
}
delete(id: string){
return new Promise((resolve, reject) => {
this.http.delete(environment.apiEndpoint + this.api + '/' + id)
.subscribe(res => {
resolve(res);
}, (err) => {
reject(err);
});
});
}
get(id: string): Promise<Task>{
return new Promise((resolve, reject) => {
this.http.get(environment.apiEndpoint + this.api + '/' + id)
.map(res => res.json())
.subscribe(res => {
resolve(res)
}, (err) => {
reject(err);
});
});
}
getAll(): Promise<Task[]>
{
return new Promise((resolve, reject) => {
this.http.get(environment.apiEndpoint + this.api)
.map(res => res.json())
.subscribe(res => {
resolve(res);
}, (err) => {
reject(err);
});
});
}
getOverdueTaskDashboard(): Promise<Task[]>
{
return new Promise((resolve, reject) => {
this.http.get(environment.apiEndpoint + this.api + "/overduetask")
.map(res => res.json())
.subscribe(res => {
resolve(res);
}, (err) => {
reject(err);
});
});
}
getTodoTaskDashboard(): Promise<Number>
{
return new Promise((resolve, reject) => {
this.http.get(environment.apiEndpoint + this.api + "/todotask")
.map(res => res.json())
.subscribe(res => {
resolve(res);
}, (err) => {
reject(err);
});
});
}
getProjectTasks():Promise<any>
{
return new Promise((resolve, reject) => {
this.http.get(environment.apiEndpoint + this.api + "/taskproject")
.map(res => res.json())
.subscribe(res => {
resolve(res);
}, (err) => {
reject(err);
});
});
}
getByUser(): Promise<Task[]>
{
return new Promise((resolve, reject) => {
this.http.get(environment.apiEndpoint + this.api + "/user-tasks")
.map(res => res.json())
.subscribe(res => {
resolve(res);
}, (err) => {
reject(err);
});
});
}
getByUserDashboard(): Promise<Task[]>
{
return new Promise((resolve, reject) => {
this.http.get(environment.apiEndpoint + this.api + "/dashboard")
.map(res => res.json())
.subscribe(res => {
resolve(res);
}, (err) => {
reject(err);
});
});
}
checkTaskName(taskname: string): Promise<boolean> {
return new Promise((resolve, reject) => {
this.http.get(environment.apiEndpoint + this.api + '/checktaskname?name=' + taskname)
.map(res => res.json()).subscribe (res => {
resolve(true);
}, (err) => {
reject(false);
});
});
}
}
<file_sep>/user.service.ts
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import { User } from './user';
import { FormControl } from '@angular/forms';
import { AuthenticationService } from './authentication.service';
import { environment } from '../environments/environment';
import { AuthHttp} from 'angular2-jwt';
interface IUsernameEmailValidator {
}
@Injectable()
export class UserService {
private api: string = "/users";
constructor(private http: AuthHttp, private authenticationService: AuthenticationService) { }
getAll(): Promise<User[]>{
// add authorization header with jwt token
return new Promise((resolve, reject) => {
this.http.get(environment.apiEndpoint + this.api)
.map(res => res.json())
.subscribe(res => {
resolve(res);
}, (err) => {
reject(err);
});
});
}
get(id: string): Promise<User>{
return new Promise((resolve, reject) => {
this.http.get(environment.apiEndpoint + this.api + '/' + id)
.map(res => res.json())
.subscribe(res => {
resolve(res)
}, (err) => {
reject(err);
});
});
}
save(data): Promise<User>{
return new Promise((resolve, reject) => {
this.http.post(environment.apiEndpoint + this.api, data)
.map(res => res.json())
.subscribe(res => {
resolve(res);
}, (err) => {
reject(err);
});
});
}
update(id, data: User): Promise<User>{
return new Promise((resolve, reject) => {
this.http.put(environment.apiEndpoint + this.api + '/' + id, data)
.map(res => res.json())
.subscribe(res => {
resolve(res);
}, (err) => {
reject(err);
});
});
}
delete(id: string){
return new Promise((resolve, reject) => {
this.http.delete(environment.apiEndpoint + this.api + '/' + id)
.subscribe(res => {
resolve(res);
}, (err) => {
reject(err);
});
});
}
checkEmailOnUpdate(email: string, userId: string): Promise<boolean>{
return new Promise((resolve, reject) => {
this.http.get(environment.apiEndpoint + this.api + '/checkemail?email=' + email + '&userId=' + userId)
.map(res => res.json()).subscribe(res => {
resolve(true);
}, (err) => {
reject(false);
});
});
}
changePassword(data: any): Promise<boolean> {
return new Promise((resolve, reject) => {
this.http.post(environment.apiEndpoint + this.api + '/changepassword', data)
.map(res => res.json()).subscribe(res => {
resolve(true);
}, (err) => {
reject(false);
});
});
}
}
<file_sep>/client.ts
export class Client {
_id:string;
name: string;
nif: string;
contact:string;
email:string;
phone_number:number;
type:string;
}
<file_sep>/app.routing.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { RouterModule,Routes } from '@angular/router';
import { ReactiveFormsModule} from '@angular/forms';
import { AppComponent } from './app.component';
import { ProjectsComponent } from './projects/projects.component';
import { ProjectNewComponent } from './project-new/project-new.component';
import { ProjectEditComponent } from './project-edit/project-edit.component';
import { ProjectDeleteComponent } from './project-delete/project-delete.component';
import { ProjectService} from './project.service';
import { HashLocationStrategy, LocationStrategy } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ClientNewComponent } from './client-new/client-new.component';
import { ClientEditComponent } from './client-edit/client-edit.component';
import { ClientDeleteComponent } from './client-delete/client-delete.component';
import { ClientComponent } from './client/client.component';
import { ClientService} from './client.service';
import { ProjectDetailComponent } from './project-detail/project-detail.component';
import { ClientDetailComponent } from './client-detail/client-detail.component';
import { TaskNewComponent } from './task-new/task-new.component';
import { TasksComponent } from './tasks/tasks.component';
import { TaskService } from './task.service';
import { MyTasksComponent } from './my-tasks/my-tasks.component';
import { ProjectTaskComponent } from './project-task/project-task.component';
import { DragulaModule, DragulaService } from '../../node_modules/ng2-dragula/ng2-dragula';
import { FlexLayoutModule } from '@angular/flex-layout';
import { MdSidenavModule} from '@angular/material';
import { BrowserAnimationsModule} from '@angular/platform-browser/animations';
import { MdCardModule,MdButtonModule,MdIconModule,MdIconRegistry} from '@angular/material';
import { MdToolbarModule} from '@angular/material';
import { MdMenuModule} from '@angular/material';
import { MaterialModule } from '@angular/material';
import { MdProgressBarModule} from '@angular/material';
import { MdDialogModule} from '@angular/material';
import { DialogInputComponent } from './dialog-input/dialog-input.component';
import { MdChipsModule} from '@angular/material';
import { HomeComponent } from './home/home.component';
import { ResourceService } from './resource.service';
import { TaskEditComponent } from './task-edit/task-edit.component';
import { TaskDetailComponent } from './task-detail/task-detail.component';
import { TaskDeleteComponent } from './task-delete/task-delete.component';
import { UserComponent } from './user/user.component';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
import { UserService } from './user.service';
import { AuthenticationService } from './authentication.service';
import { UserCreateComponent } from './user-create/user-create.component';
import { UserEditComponent } from './user-edit/user-edit.component';
import { UserDetailComponent } from './user-detail/user-detail.component';
import { UserDeleteComponent } from './user-delete/user-delete.component';
import { PasswordStrengthBarModule } from 'ng2-password-strength-bar';
import { GuardadoComponent } from './guardado/guardado.component';
import { RegisterSuccessComponent } from './register-success/register-success.component';
import { ConfirmComponent } from './confirm/confirm.component';
import { ConfirmFailedComponent } from './confirm-failed/confirm-failed.component';
import { ConfirmSuccessComponent } from './confirm-success/confirm-success.component';
import { AuthGuard } from './auth.guard';
import { AdminGuard} from './admin.guard';
import { HistoricoComponent } from './historico/historico.component';
import { ActivityComponent } from './activity/activity.component';
import { UserPasswordComponent } from './user-password/user-password.component';
import { DashboardComponent } from './dashboard/dashboard.component';
const ROUTES: Routes = [
{ path: '', redirectTo: 'auth/login', pathMatch: 'full' },
{ path: 'auth/login', component: LoginComponent },
{ path: 'auth/confirm', component: ConfirmComponent },
{ path: 'auth/register', component: UserPasswordComponent },
{ path: 'auth/restore-password', component:ConfirmComponent},
{ path: 'success', component: ConfirmSuccessComponent },
{ path: 'failed', component: ConfirmFailedComponent },
{ path: 'home', component:HomeComponent,
children:[
{ path: '', redirectTo: 'dashboard', pathMatch: 'full' },
{ path: 'users', component: UserComponent,canActivate: [AdminGuard] },
{ path: 'user-create', component: UserCreateComponent,canActivate: [AdminGuard] },
{ path: 'user-detail/:id', component: UserDetailComponent,canActivate: [AdminGuard] },
{ path: 'user-edit/:id', component: UserEditComponent,canActivate: [AdminGuard] },
{ path: 'user-delete/:id', component: UserDeleteComponent,canActivate: [AdminGuard] },
{ path: 'projects', component: ProjectsComponent,canActivate: [AdminGuard] },
{ path: 'project-new', component: ProjectNewComponent,canActivate: [AdminGuard] },
{ path: 'project-edit/:id', component: ProjectEditComponent,canActivate: [AdminGuard] },
{ path: 'project-detail/:id', component: ProjectDetailComponent,canActivate: [AdminGuard] },
{ path: 'project-delete/:id', component: ProjectDeleteComponent,canActivate: [AdminGuard] },
{ path: 'client', component: ClientComponent,canActivate: [AdminGuard] },
{ path: 'client-new', component: ClientNewComponent,canActivate: [AdminGuard] },
{ path: 'client-edit/:id', component: ClientEditComponent,canActivate: [AdminGuard] },
{ path: 'client-detail/:id', component: ClientDetailComponent,canActivate: [AdminGuard] },
{ path: 'client-delete/:id', component: ClientDeleteComponent,canActivate: [AdminGuard] },
{ path: 'tasks', component: TasksComponent,canActivate: [AuthGuard] },
{ path: 'task-new', component: TaskNewComponent,canActivate: [AuthGuard] },
{ path: 'task-edit/:id', component: TaskEditComponent,canActivate: [AdminGuard] },
{ path: 'task-detail/:id', component:TaskDetailComponent,canActivate: [AdminGuard] },
{ path: 'task-delete/:id', component: TaskDeleteComponent,canActivate: [AdminGuard] },
{ path: 'my-tasks', component: MyTasksComponent,canActivate: [AuthGuard] },
{ path: 'project-task', component: ProjectTaskComponent,canActivate: [AuthGuard] },
{ path: 'historico/:id', component: HistoricoComponent,canActivate: [AdminGuard] },
{ path: 'activity/:id', component: ActivityComponent,canActivate: [AuthGuard] },
{ path: 'dashboard', component:DashboardComponent, canActivate: [AuthGuard]}
]
}
];
@NgModule({
imports: [
RouterModule.forRoot(ROUTES),
],
exports: [
RouterModule
]
})
export class AppRoutingModule { }
<file_sep>/task.service.spec.ts
import { TestBed, inject } from '@angular/core/testing';
import { Task } from './task.service';
describe('ClientService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [Task]
});
});
it('should ...', inject([Task], (service: Task) => {
expect(service).toBeTruthy();
}));
});
<file_sep>/project.service.spec.ts
import { TestBed, inject } from '@angular/core/testing';
import { Project } from './project.service';
describe('ProjectService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [Project]
});
});
it('should ...', inject([Project], (service: Project) => {
expect(service).toBeTruthy();
}));
});
<file_sep>/README.md
# tfg
Angular TFG
<file_sep>/task.ts
import {Project} from '../app/project';
import {User} from '../app/user';
import {Activity} from '../app/activity';
export class Task
{
_id:string;
name: string;
details: string;
project: Project;
state: string="backlog";
user: Array<User>;
start_date: Date;
end_date: Date;
estimated_time: number;
activities:Array<Activity>=new Array<Activity>();
}
<file_sep>/app.component.ts
import { Component, ViewChild, Optional, OnInit } from '@angular/core';
import { MdMenuTrigger} from '@angular/material';
import { DragulaService} from 'ng2-dragula/ng2-dragula';
import { MdDialog, MdDialogRef} from '@angular/material';
import { DialogInputComponent } from './dialog-input/dialog-input.component';
import { TaskService} from './task.service';
import { ProjectService } from './project.service';
import { Project } from './project';
import { ResourceService } from './resource.service';
import { Resource} from './resource';
import { Router } from '@angular/router';
import { Task } from './task';
import { FormControl, FormGroup, FormArray, FormBuilder, Validators } from '@angular/forms';
import { AuthenticationService } from './authentication.service';
import { TranslateService} from '@ngx-translate/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [DragulaService, TaskService]
})
export class AppComponent implements OnInit {
userLogged: boolean = false;
username: string = "";
constructor(private router: Router, private authenticationService: AuthenticationService, translate: TranslateService) {
// this language will be used as a fallback when a translation isn't found in the current language
translate.setDefaultLang('es');
// the lang to use, if the lang isn't available, it will use the current loader to get them
translate.use('es');
}
ngOnInit() {
if (this.authenticationService.user) {
this.userLogged = true;
this.username = this.authenticationService.user.name;
}
}
logout(){
this.authenticationService.logout();
this.router.navigate(["/auth/login"], {skipLocationChange: true})
}
}
<file_sep>/project.service.ts
import { Injectable } from '@angular/core';
import { Project } from './project';
import { Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';
import { AuthenticationService } from './authentication.service';
import { environment } from '../environments/environment';
import { AuthHttp} from 'angular2-jwt';
@Injectable()
export class ProjectService {
private api: string = "/projects";
constructor(private http: AuthHttp) { }
save(data: Project): Promise<Project>{
return new Promise((resolve, reject) => {
this.http.post(environment.apiEndpoint + this.api, data)
.map(res => res.json())
.subscribe(res => {
resolve(res);
}, (err) => {
reject(err);
});
});
}
update(id, data: Project): Promise<Project>{
return new Promise((resolve, reject) => {
this.http.put(environment.apiEndpoint + this.api + '/' + id, data)
.map(res => res.json())
.subscribe(res => {
resolve(res);
}, (err) => {
reject(err);
});
});
}
delete(id: string){
return new Promise((resolve, reject) => {
this.http.delete(environment.apiEndpoint + this.api + '/' + id)
.subscribe(res => {
resolve(res);
}, (err) => {
reject(err);
});
});
}
get(id: string): Promise<Project>{
return new Promise((resolve, reject) => {
this.http.get(environment.apiEndpoint + this.api + '/' + id)
.map(res => res.json())
.subscribe(res => {
resolve(res)
}, (err) => {
reject(err);
});
});
}
getAll(): Promise<Project[]>{
return new Promise((resolve, reject) => {
this.http.get(environment.apiEndpoint + this.api)
.map(res => res.json())
.subscribe(res => {
resolve(res);
}, (err) => {
reject(err);
});
});
}
getTodoProjectDashboard(): Promise<Number>
{
return new Promise((resolve, reject) => {
this.http.get(environment.apiEndpoint + this.api + "/todoproject")
.map(res => res.json())
.subscribe(res => {
resolve(res);
}, (err) => {
reject(err);
});
});
}
checkProjectName(projectname: string): Promise<boolean> {
return new Promise((resolve, reject) => {
this.http.get(environment.apiEndpoint + this.api + '/checkprojectname?name=' + projectname)
.map(res => res.json()).subscribe (res => {
resolve(true);
}, (err) => {
reject(false);
});
});
}
}
<file_sep>/project.ts
import {Client} from '../app/client';
export class Project {
_id:string;
title: string;
description: string;
repository: string;
client: Client= new Client();
start_date:Date;
ending_date:Date;
technologies:string[];
budget:number;
}
<file_sep>/home.component.ts
import { Component, ViewChild, Optional, OnInit } from '@angular/core';
import { MdMenuTrigger} from '@angular/material';
import { DragulaService} from 'ng2-dragula/ng2-dragula';
import { MdDialog, MdDialogRef} from '@angular/material';
import { DialogInputComponent } from '../dialog-input/dialog-input.component';
import { TaskService} from '../task.service';
import { ProjectService } from '../project.service';
import { Project } from '../project';
import { ResourceService } from '../resource.service';
import { Resource} from '../resource';
import { Router } from '@angular/router';
import { Task } from '../task';
import { FormControl, FormGroup, FormArray, FormBuilder, Validators } from '@angular/forms';
import { User } from '../user';
import { UserService} from '../user.service';
import { AuthenticationService } from '../authentication.service';
import { Globals} from '../globals';
import {TranslateService} from '@ngx-translate/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
providers: [DragulaService]
})
export class HomeComponent {
selected: string;
public tasks: Task[];
public users: User[];
public user: string;
public oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
public firstDate;
public secondDate;
constructor(translate: TranslateService,public router:Router,public globals:Globals,public authenticationService: AuthenticationService, private dragulaService: DragulaService,public userService:UserService, public mdDialog: MdDialog, private taskService: TaskService, ) {
}
ngOnInit(){
this.user = this.authenticationService.user.name;
this.getTasks();
this.globals.title="Gestión";
}
getTasks() {
this.taskService.getAll().then((data) => {
this.tasks = data;
}, (error) => {
console.log(error);
});
}
openDialog() {
let dialog = this.mdDialog.open(DialogInputComponent);
dialog.afterClosed()
.subscribe(selection => {
if (selection) {
this.selected = selection;
} else {
}
});
}
calculateDays(firstDate:Date,secondDate:Date):any{
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24
// Convert both dates to milliseconds
var date1_ms = firstDate.getTime();
var date2_ms = secondDate.getTime();
// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms)
// Convert back to days and return
var result= Math.round(difference_ms/ONE_DAY);
console.log(result);
return result;
}
logout(){
this.authenticationService.logout()
this.router.navigate(["/auth/login"], {skipLocationChange: false})
}
}
export class MyComponent {
@ViewChild(MdMenuTrigger) trigger: MdMenuTrigger;
someMethod() {
this.trigger.openMenu();
}
}
<file_sep>/resource.ts
export class Resource
{
_id:string;
name: string;
surname1: string;
surname2: string;
details: string;
email: string;
phone_number:number;
}
<file_sep>/dashboard.component.ts
import { Component, OnInit,ViewChild } from '@angular/core';
import { Task } from '../task';
import { TaskService} from '../task.service';
import { Globals} from '../globals';
import { DragulaService} from 'ng2-dragula/ng2-dragula';
import { MdDialog, MdDialogRef} from '@angular/material';
import { DialogInputComponent } from '../dialog-input/dialog-input.component';
import { MdMenuTrigger} from '@angular/material';
import { Activity } from '../activity';
import { ActivityService } from '../activity.service';
import { Project } from '../project';
import { ProjectService } from '../project.service';
import { AuthenticationService } from '../authentication.service';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
public tasks:Task[];
public projectTask:string[]=[];
public c;
public n
public pro;
public h:Number;
public task: Task=new Task();
public project: Project=new Project();
public name:String;
public username:Array<String>=new Array<String>();
constructor(translate: TranslateService,private authService: AuthenticationService, private activityService: ActivityService,private globals:Globals,private projectService:ProjectService,private taskService:TaskService,private dragulaService: DragulaService, public mdDialog: MdDialog) { }
ngOnInit() {
this.globals.title = "Dashboard";
if(this.authService.isDeveloper()==true)
{
this.getUserTasks();
}
else{
this.getTasks();
//this.getTodoProjects();
this.getProjectTasks();
}
}
/**
* Obtener número de tareas pendientes y pintar tareas retrasadas en caso de ser el resto de usuarios
*/
getTasks(): void {
this.taskService.getTodoTaskDashboard().then((data) => {
/*
this.c=data.valueOf();
console.log(this.c);
*/
});
this.taskService.getOverdueTaskDashboard().then((data) => {
this.tasks = data;
this.tasks.sort(function(name1, name2) {
if (name1.end_date < name2.end_date) {
return -1;
} else if (name1.end_date > name2.end_date) {
return 1;
} else {
return 0;
}
});
});
}
/**
* Obtener número de tareas pendientes y pintar tareas retrasadas en caso de ser usuario developer
*/
getUserTasks(): void
{
this.taskService.getTodoTaskDashboard().then((data)=>
{
this.c=data.valueOf();
});
this.taskService.getByUserDashboard().then((data) => {
this.tasks = data;
this.tasks.sort(function(name1, name2) {
if (name1.end_date < name2.end_date) {
return -1;
} else if (name1.end_date > name2.end_date) {
return 1;
} else {
return 0;
}
});
});
}
/**
* Obtener tareas pendientes de un proyecto
*/
getProjectTasks()
{
this.taskService.getProjectTasks().then((data) => {
this.projectTask=data;
});
}
/**
* Obtener número de proyectos pendientes
getTodoProjects(): void
{
this.projectService.getTodoProjectDashboard().then((data) => {
this.n=data.valueOf();
console.log(this.n);
});
}
*/
now(fecha:Date):number
{
let v=new Date(fecha);
let f=v.getDate();
let b=new Date();
let r=b.getDate();
if (f < r) {
return -1;
} else if (f > r) {
return 1;
} else {
return 0;
}
}
}
<file_sep>/auth.js
const express = require('express');
const User = require('../models/user');
const createError = require('http-errors');
const passport = require('passport');
const Verify = require('./verify');
const nodemailer = require('nodemailer');
const config = require('../config');
const jwt = require('jsonwebtoken');
let router = express.Router();
let registerRoute = router.route('/register');
registerRoute.post(function(req, res) {
User.register(new User({ username : req.body.username, email: req.body.email, role:req.body.role }),
req.body.password, function(err, user) {
if (err) {
return res.status(500).json({err: err});
}
passport.authenticate('local')(req, res, function () {
let token = Verify.getTemporaryToken(user);
/* res.status(200).json({
token: token
});*/
return res.status(200).send({message: 'user registered', token: token});
});
});
});
let loginRoute = router.route('/login');
loginRoute.post(function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.status(401).json({
err: info
});
}
if (!user.enabled) {
return res.status(432).json({
err: {message : 'user not enabled'}
});
}
req.logIn(user, function(err) {
if (err) {
return res.status(500).json({
err: 'Could not log in user'
});
}
let token = Verify.getToken(user);
let userData = {_id: user._id, username: user.username, email: user.email};
res.status(200).json({
token: token,
user: userData
});
});
})(req,res,next);
});
let checkEmailRoute = router.route('/checkemail');
checkEmailRoute.get(function(req, res, next) {
let email = req.query.email.toLowerCase();
User.findOne({deleted: null, email: email}, (err, user) => {
if (err) {
return next(err);
}
if (user) {
if (user.email === email) {
return res.status(401).json({
err: 'Email already exists'
});
}
}
return res.status(200).send({message: 'email does not exist'});
});
});
let checkUsernameRoute = router.route('/checkusername');
checkUsernameRoute.get(function(req, res, next) {
let username = req.query.username.toLowerCase();
User.findOne({deleted: null, username: username}, (err, user) => {
if (err) {
// return next(createError(500));
return next(err);
}
if (user) {
if (user.username === username) {
return res.status(401).json({
err: 'Username already exists'
});
}
}
return res.status(200).send({message: 'username does not exist'});
});
});
let sendConfirmEmailRoute = router.route('/sendemail');
sendConfirmEmailRoute.post(function(req, res) {
let transporter = nodemailer.createTransport({
host: 'smtp1.servage.net',
port: 465,
secure: true, // secure:true for port 465, secure:false for port 587
auth: {
user: '<EMAIL>',
pass: <PASSWORD>',
}
});
let html = '¡Bienvenid@, ' + req.body.name + '! \n\n Haga clic en el siguiente enlace para confirmar su registro \n\n [[ enlace de confirmación ]]' + req.body.token;
let mailOptions = {
from: '<EMAIL>',
to: req.body.sendTo,
subject: 'Confirmación de registro',
html: '¡Bienvenid@, ' + req.body.name + '! \n\n Haga clic <a href = '+ config.frontendEndpoint + '/#/auth/confirm?token=' + req.body.token + '>aquí</a> para confirmar su registro '
};
transporter.sendMail(mailOptions, function(error, info){
if(error){
console.log(error);
res.json({yo: 'error'});
} else {
console.log('Message sent: ' + info.response);
res.json({yo: info.response});
}
});
});
let confirmAccountRoute = router.route('/confirm');
confirmAccountRoute.put(function(req, res, next) {
let token = req.body.token;
if (token) {
// verifies secret and checks exp
jwt.verify(token, config.secret, function (err, decoded) {
if (err) {
err = new Error('Error in token');
err.status = 401;
return next(err);
} else {
// if everything is good, save to request for use in other routes
// req.decoded = decoded;
// next();
// se extrae el usuario del token
let payload = jwt.decode(token, config.secret);
let userId = payload.doc._id;
User.update({_id: userId}, {
$set: {
enabled: true
}
}, (err) => {
if (err) {
return next(createError(400, err));
}
return res.status(204).send();
});
}
});
}
});
let restorePwdRoute = router.route('/restore-password');
restorePwdRoute.post(function(req, res, next) {
let token = req.body.token;
let newPassword = req.body.newPassword;
if (token) {
// verifies secret and checks exp
jwt.verify(token, config.secret, function (err, decoded) {
if (err) {
err = new Error('Error in token');
err.status = 401;
return next(err);
} else {
// se extrae el usuario del token
let payload = jwt.decode(token, config.secret);
User.findOne({username: payload.name}, (err, user) => {
if (err) {
return next(err);
}
user.setPassword(<PASSWORD>, (err) => {
if (err) {
return next(err);
}
user.save();
return res.status(200).send({message: 'password changed'});
});
});
}
});
}
});
module.exports = router;
<file_sep>/verify.js
const User = require('../models/user');
const jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
const config = require('../config.js');
exports.getToken = function (user) {
let data = {
"name":user.username,
"role":user.role
};
return jwt.sign(data, config.secret, {
expiresIn: 3600
});
};
exports.getTemporaryToken = function (user) {
let data = {
"name":user.username,
"role":user.role
};
return jwt.sign(data, config.secret, {
expiresIn: 1440
});
};
exports.verifyOrdinaryUser = function (req, res, next) {
// check header or url parameters or post parameters for token
let bearer = req.body.token || req.query.token || req.headers['authorization'];
let token = bearer.split(" ")[1].split('"').join('');
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token, config.secret, function (err, decoded) {
if (err) {
err = new Error('You are not authenticated!');
err.status = 401;
return next(err);
} else {
User.findOne({deleted: null, username: decoded.name}, (err, user) => {
if (err) {
return next(err);
}
req.decoded = {
"user": user._id,
"role": user.role,
};
next();
});
}
});
} else {
// if there is no token
// return an error
let err = new Error('No token provided!');
err.status = 403;
return next(err);
}
};
<file_sep>/activity.ts
export class Activity {
_id:string;
hours: number;
commentaries: string;
state: string="backlog";
day:Date;
}
<file_sep>/authentication.service.ts
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { Project } from './project';
import 'rxjs/add/operator/map';
import { JwtHelper } from 'angular2-jwt';
import { environment } from '../environments/environment';
@Injectable()
export class AuthenticationService {
private api: string = "http://localhost:3000/auth";
public token: string;
public user: any;
public pro:Project;
private headers: Headers;
private jwtHelper: JwtHelper = new JwtHelper();
constructor(private http: Http) {
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json');
if(localStorage.getItem('projectAuth') != null){
sessionStorage.setItem('projectAuth', localStorage.getItem('projectAuth'));
}
//Extract user from token
if (sessionStorage.getItem('projectAuth') != null) {
this.extractUser();
}
}
login(username: string, password: string, remember: boolean): Promise<boolean> {
return new Promise((resolve, reject) => {
this.http.post(this.api + '/login', JSON.stringify({ username: username, password: <PASSWORD> }), {headers: this.headers})
.map(res => res.json()).subscribe(res => {
this.token = res.token;
sessionStorage.setItem('projectAuth', this.token);
if (remember){
localStorage.setItem('projectAuth', this.token);
}
this.extractUser();
resolve(true);
}, (err) => {
reject(err);
});
});
}
register(user): Promise<boolean> {
return new Promise((resolve, reject) => {
this.http.post(this.api + '/register', user, {headers: this.headers})
.map(res => res.json()).subscribe(res => {
this.token = res.token;
resolve(true);
});
});
}
sendEmail(username: string, email: string): Promise<boolean> {
return new Promise((resolve, reject) => {
this.http.post(this.api + '/sendemail', JSON.stringify({ name: username, sendTo: email, token: this.token }), {headers: this.headers})
.map(res => res.json()).subscribe(res => {
resolve(true);
});
});
}
confirm(token: string): Promise<boolean> {
return new Promise((resolve, reject) => {
this.http.put(this.api + '/confirm', JSON.stringify({ token: token }), {headers: this.headers})
.map(res => res.json()).subscribe(res => {
resolve(true);
});
});
}
checkUsername(username: string): Promise<boolean> {
return new Promise((resolve, reject) => {
this.http.get(this.api + '/checkusername?username=' + username)
.map(res => res.json()).subscribe (res => {
resolve(true);
}, (err) => {
reject(false);
});
});
}
checkEmail(email: string): Promise<boolean>{
return new Promise((resolve, reject) => {
this.http.get(this.api + '/checkemail?email=' + email)
.map(res => res.json()).subscribe(res => {
resolve(true);
}, (err) => {
reject(false);
});
});
}
public extractUser(){
if (sessionStorage.getItem('projectAuth')) {
this.token = sessionStorage.getItem('projectAuth');
let tokenDecode = this.jwtHelper.decodeToken(this.token);
this.user = {
"name": tokenDecode.name,
"role": tokenDecode.role
};
}
}
restorePassword(newPassword: string, token: string): Promise<boolean> {
return new Promise((resolve, reject) => {
this.http.post(this.api + '/restore-password', {newPassword: newPassword, token: token})
.map(res => res.json()).subscribe(res => {
resolve(true);
});
});
}
isLoggedIn(){
return this.token;
}
isAdmin()
{
if (this.user['role'] == 'Admin') {
return true;
} else {
return false;
}
}
isDeveloper()
{
if (this.user['role'] == 'Developer') {
return true;
} else {
return false;
}
}
logout(): void {
// clear token remove user from local storage to log user out
this.token = undefined;
localStorage.removeItem('projectAuth');
sessionStorage.removeItem('projectAuth');
}
}
<file_sep>/login.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthenticationService } from '../authentication.service';
import {TranslateService} from '@ngx-translate/core';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
public loginForm: FormGroup;
loading: boolean = false;
public error: string;
constructor(translate: TranslateService,public formBuilder: FormBuilder, private router: Router, private authenticationService: AuthenticationService) {
let username = new FormControl('', Validators.required);
let password = new FormControl('', Validators.required);
let remember = new FormControl('');
this.loginForm = formBuilder.group({
'username': username,
'password': <PASSWORD>,
'remember': remember
});
}
ngOnInit() {
}
login() {
this.authenticationService.login(this.loginForm.value.username, this.loginForm.value.password, this.loginForm.value.remember).then((result) => {
console.log('Autenticado correctamente');
this.router.navigate(['/home']);
}, (error) => {
if (401 === error.status){
// login failed
console.log(this.loginForm.value.username, this.loginForm.value.password);
this.error = 'El usuario y/o la contraseña no son correctos';
}
console.log(this.loginForm.value.username, this.loginForm.value.password);
console.log(error);
});
}
}
|
026bc9217d8c4bd89055903095410cb486da86d5
|
[
"JavaScript",
"TypeScript",
"Markdown"
] | 22 |
JavaScript
|
IgnacioArredondo/tfg
|
d4b1fb2c7e237c96dc72c447cedc5e3892d0956b
|
d154164d771a5f556c89405f96a65c6c5a8ee23c
|
refs/heads/master
|
<file_sep>package com.example.skybound.WebServices;
import com.example.skybound.beanResponse.OrderSummary;
import com.example.skybound.beanResponse.PlaceOrder;
import com.example.skybound.beanResponse.ProductRes;
import com.example.skybound.beanResponse.StaffSignInRes;
import com.example.skybound.beanResponse.UserSignInRes;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
public interface ServiceInterface {
/// user signin request
@Multipart
@POST("skybound/user_signin.php")
Call<UserSignInRes> UserSigninCall(
@Part("id") RequestBody id,
@Part("password") RequestBody password
);
/// user staffrequest
@Multipart
@POST("skybound/user_signin.php")
Call<StaffSignInRes> StaffSigninCall(
@Part("id") RequestBody id,
@Part("password") RequestBody password
);
// get products
@Multipart
@POST("skybound/product.php")
Call<ProductRes> getPorduct(
@Part("securecode") RequestBody securecode
);
//place order
@Multipart
@POST("skybound/placeorderapi.php")
Call<PlaceOrder> PlaceOrderCall(
@Part("securecode") RequestBody securecode,
@Part("user_id") RequestBody user_id,
@Part("prod_id") RequestBody prod_id,
@Part("total_price") RequestBody total_price,
@Part("qty") RequestBody qty
);
// get order summery
@Multipart
@POST("skybound/getordersummary.php")
Call<OrderSummary> getOrderSummarycall(
@Part("securecode") RequestBody securecode
);
}
<file_sep>package com.example.skybound.Utility;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.skybound.R;
public class AppUtilits {
public static void displayMessage(Context mContext, String message){
MessageDialog messageDialog = null;
if (messageDialog == null)
messageDialog = new MessageDialog(mContext, message);
messageDialog.displayMessageShow();
}
public static AlertDialog createProgressBar(Context context)
{
LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.progressbar, null, false);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setView(view);
alertDialog.setCancelable(false);
AlertDialog dialog = alertDialog.create();
dialog.show();
return dialog;
}
public void createToaster(Context context, String message, int duration, int icon)
{
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.toaster_layoru, null, false);
Toast toast = new Toast(context);
toast.setView(view);
((TextView)view.findViewById(R.id.toaster_txt_message)).setText(message);
((ImageView)view.findViewById(R.id.toaster_icon)).setImageResource(icon);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setDuration(duration);
toast.show();
}
public static void destroyDialog(AlertDialog dialog)
{
dialog.dismiss();
}
}
<file_sep>package com.example.skybound.WebServices;
import com.example.skybound.BuildConfig;
import com.example.skybound.Utility.Constant;
import com.example.skybound.beanResponse.OrderSummary;
import com.example.skybound.beanResponse.PlaceOrder;
import com.example.skybound.beanResponse.ProductRes;
import com.example.skybound.beanResponse.StaffSignInRes;
import com.example.skybound.beanResponse.UserSignInRes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ServiceWrapper {
private ServiceInterface mServiceInterface;
public ServiceWrapper(Interceptor mInterceptorheader) {
mServiceInterface = getRetrofit(mInterceptorheader).create(ServiceInterface.class);
}
public Retrofit getRetrofit(Interceptor mInterceptorheader) {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient mOkHttpClient = null;
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(Constant.API_CONNECTION_TIMEOUT, TimeUnit.SECONDS);
builder.readTimeout(Constant.API_READ_TIMEOUT, TimeUnit.SECONDS);
// if (BuildConfig.DEBUG)
// builder.addInterceptor(loggingInterceptor);
if (BuildConfig.DEBUG) {
// HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
builder.addInterceptor(loggingInterceptor);
}
mOkHttpClient = builder.build();
Gson gson = new GsonBuilder().create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constant.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(mOkHttpClient)
.build();
return retrofit;
}
/// user signin
public Call<UserSignInRes> UserSigninCall(String id, String password){
return mServiceInterface.UserSigninCall(convertPlainString(id), convertPlainString(password));
}
/// user signin
public Call<StaffSignInRes> StaffSigninCall(String id, String password){
return mServiceInterface.StaffSigninCall(convertPlainString(id), convertPlainString(password));
}
// convert aa param into plain text
public RequestBody convertPlainString(String data){
RequestBody plainString = RequestBody.create(MediaType.parse("text/plain"), data);
return plainString;
}
/// product details
public Call<ProductRes> getProductRes(String securcode){
return mServiceInterface.getPorduct(convertPlainString(securcode));
}
/// place order
public Call<PlaceOrder> PlaceOrderCall(String securecode, String user_id, String prod_id, String total_price, String qty){
return mServiceInterface.PlaceOrderCall(convertPlainString(securecode), convertPlainString(user_id), convertPlainString(prod_id), convertPlainString(total_price), convertPlainString(qty));
}
// get order summery
public Call<OrderSummary> getOrderSummarycall(String securcode){
return mServiceInterface.getOrderSummarycall(convertPlainString(securcode));
}
}
<file_sep>package com.example.skybound.Adapters;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.example.skybound.HomeActivity;
import com.example.skybound.Models.Prod_Model;
import com.example.skybound.Ordersummary.Order_Summary;
import com.example.skybound.Products.ProductDetails;
import com.example.skybound.R;
import com.example.skybound.Utility.AppUtilits;
import com.example.skybound.Utility.NetworkUtility;
import com.example.skybound.WebServices.ServiceWrapper;
import com.example.skybound.beanResponse.PlaceOrder;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class Prod_adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mContext;
private List<Prod_Model> mProdModelList;
private String TAG ="NewProd_adapter";
private int mScrenwith;
public Prod_adapter(Context context, List<Prod_Model> list, int screenwidth ){
mContext = context;
mProdModelList = list;
mScrenwith =screenwidth;
}
private class ProductHolder extends RecyclerView.ViewHolder {
ImageView prod_img;
TextView prod_name,prod_price,prod_stock;
LinearLayout cardView;
public ProductHolder(View itemView) {
super(itemView);
prod_img = (ImageView) itemView.findViewById(R.id.prod_img);
prod_name = (TextView) itemView.findViewById(R.id.prod_name);
prod_price = (TextView) itemView.findViewById(R.id.prod_price);
prod_stock = (TextView) itemView.findViewById(R.id.prod_stock);
cardView = itemView.findViewById(R.id.cardview);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( mScrenwith - (mScrenwith/100*70), LinearLayout.LayoutParams.MATCH_PARENT);
params.setMargins(10,10,10,10);
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_newproduct, parent,false);
Log.e(TAG, " view created ");
return new ProductHolder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final Prod_Model model = mProdModelList.get(position);
Log.e(TAG, " assign value ");
((ProductHolder) holder).prod_name.setText(model.getProd_name());
((ProductHolder) holder).prod_price.setText("Ksh: "+model.getPrice());
((ProductHolder) holder).prod_stock.setText("Stock: "+model.getStock());
Glide.with(mContext)
.load(model.getImg_ulr())
.into(((ProductHolder) holder).prod_img);
// imageview glider lib to get imagge from url
((ProductHolder) holder).prod_img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, model.getStock());
if (model.getStock().equals("0")){
Toast.makeText(mContext, "Item is sold out", Toast.LENGTH_LONG).show();
} else {
final Dialog dialog;
view = LayoutInflater.from(mContext).inflate(R.layout.cart_popup, null, false);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setView(view);
alertDialog.setCancelable(true);
dialog = alertDialog.create();
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
dialog.show();
final Window dialogWindow = dialog.getWindow();
dialogWindow.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
dialogWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
// Log.e(TAG, " prod_id "+String.valueOf(prod_id));
final EditText qty = view.findViewById(R.id.qty);
final EditText amount = view.findViewById(R.id.amount);
final Button ok = view.findViewById(R.id.ok);
ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!(amount.getText().toString().equals("") || amount.getText().toString().equals("0"))) {
if (!(qty.getText().toString().equals("") || qty.getText().toString().equals("0"))) {
if(Integer.valueOf(amount.getText().toString() ) >= Integer.valueOf( model.getPrice())) {
if(Integer.valueOf(qty.getText().toString()) <= Integer.valueOf(model.getStock())){
dialog.cancel();
placeOrder(model.getProd_id(), qty.getText().toString(), amount.getText().toString());
}else{
Toast.makeText(mContext, "Not enough stock remaining", Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(mContext, "Minimum price exceeded", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(mContext, "Please input number of items sold", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(mContext, "Please input cash amount sold for this item", Toast.LENGTH_LONG).show();
}
}
});
}
}
});
}
public void placeOrder(String prod_id, String qty, String amount){
final AlertDialog progressbar = AppUtilits.createProgressBar(mContext);
if (!NetworkUtility.isNetworkConnected(mContext)){
AppUtilits.displayMessage(mContext, mContext.getString(R.string.network_not_connected));
}else {
// Log.e(TAG, " user value "+ SharePreferenceUtils.getInstance().getString(Constant.USER_DATA));
ServiceWrapper service = new ServiceWrapper(null);
Call<PlaceOrder> call = service.PlaceOrderCall("12345", "sampleuser1", prod_id, amount, qty );
call.enqueue(new Callback<PlaceOrder>() {
@Override
public void onResponse(Call<PlaceOrder> call, Response<PlaceOrder> response) {
Log.e(TAG, "reposne is " + response.body().getInformation());
if (response.body() != null && response.isSuccessful()) {
if (response.body().getStatus() == 1) {
AppUtilits.destroyDialog(progressbar);
AppUtilits.displayMessage(mContext, response.body().getMsg());
/* Intent intent = new Intent(mContext, HomeActivity.class);
startActivity(intent);
finish();*/
}else {
AppUtilits.displayMessage(mContext, response.body().getMsg());
}
}else {
AppUtilits.displayMessage(mContext, mContext.getString(R.string.network_error));
}
}
@Override
public void onFailure(Call<PlaceOrder> call, Throwable t) {
Log.e(TAG, " fail delete cart "+ t.toString());
AppUtilits.displayMessage(mContext, mContext.getString(R.string.fail_toplaceorder));
}
});
}
}
@Override
public int getItemCount() {
return mProdModelList.size();
}
}
<file_sep>package com.example.skybound.beanResponse;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class OrderSummary {
@SerializedName("status")
@Expose
private Integer status;
@SerializedName("msg")
@Expose
private String msg;
@SerializedName("Information")
@Expose
private List<Information> information = null;
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public List<Information> getInformation() {
return information;
}
public void setInformation(List<Information> information) {
this.information = information;
}
public class Information {
@SerializedName("id")
@Expose
private String id;
@SerializedName("name")
@Expose
private String name;
@SerializedName("qty")
@Expose
private String qty;
@SerializedName("price")
@Expose
private String price;
@SerializedName("date")
@Expose
private String date;
@SerializedName("subtotal")
@Expose
private String subtotal;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getQty() {
return qty;
}
public void setQty(String qty) {
this.qty = qty;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getSubtotal() {
return subtotal;
}
public void setSubtotal(String subtotal) {
this.subtotal = subtotal;
}
}
}
|
c5a1c6efe40b1b1975d19ebce5733dc09cab61f5
|
[
"Java"
] | 5 |
Java
|
JacqulineMbogo/Skybound
|
5824b149f23e18c19473a88200b477f39b5eb175
|
61ec0893792ffd757d147f9901361079ba1c84d4
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-02-10 21:22
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0004_auto_20160210_2120'),
]
operations = [
migrations.AlterField(
model_name='service',
name='zones',
field=models.ManyToManyField(related_name='services', to='app.Zone'),
),
]
<file_sep>from django.shortcuts import render_to_response
from django.http import HttpResponse
import user_agents
import json
def save (request):
params = request.POST
cookies = request.COOKIES
meta = request.META
useragent = request.META.get('HTTP_USER_AGENT')
result = user_agents.parse(useragent)
isTouch = result.is_touch_capable
res = json.dumps(params)
print(result.browser)
data = {
'params': params,
'COOKIES': cookies,
'META': meta,
'useragent': result
}
# return render_to_response('test.html', data)
return HttpResponse(res)<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-02-10 21:08
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('app', '0002_zone_zone_id'),
]
operations = [
migrations.RemoveField(
model_name='zone',
name='votes',
),
]
<file_sep>from django.db import models
# Create your models here.
class Zone(models.Model):
name = models.CharField(max_length=200)
zone_id = models.CharField(max_length=200, default='')
def __str__(self):
return self.name
class Service(models.Model):
name = models.CharField(max_length=200)
desc = models.CharField(max_length=200, default='')
service_id = models.CharField(max_length=200)
zones = models.ManyToManyField(Zone, related_name="services")
def __str__(self):
return self.name
<file_sep>from django.contrib import admin
# Register your models here.
from .models import Zone
from .models import Service
admin.site.register(Zone)
admin.site.register(Service)<file_sep># -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext
import os
import re
from subprocess import Popen, PIPE
import json
import user_agents
from .models import Service
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
MORDA_PATH = SITE_ROOT + '/../morda/'
def index(request):
services = Service.objects.order_by('name')
cookies = request.COOKIES
meta = request.META
useragent = request.META.get('HTTP_USER_AGENT')
result = user_agents.parse(useragent)
isTouch = result.is_touch_capable
data = {
'services': services
}
return render(request, 'index.html', data, context_instance=RequestContext(request))
def add(request):
params = request.POST
files = request.FILES
data = {'status': 'error'}
settings = []
# Получаем флаги (должны быть вида settings_[имя])
for param in params:
result = re.compile('settings_(.*)').match(param)
if result:
settings.append(result.group(1))
if 'icon' in files:
uploadFile = files['icon']
serviceName = params['service']
extMap = {
'image/svg+xml': 'svg',
'image/png': 'png'
}
if uploadFile.content_type in extMap:
fileExtention = extMap[uploadFile.content_type]
filePath = handle_uploaded_file(uploadFile, serviceName, fileExtention)
optimizeImg(filePath, fileExtention)
moveToDest(filePath, fileExtention, serviceName, settings)
data = {
'status': 'ok',
'imgSrc': filePath
}
else:
data = {
'status': 'error'
}
response = json.dumps(data)
return HttpResponse(response)
def status(request):
os.chdir(MORDA_PATH)
resp, err = Popen('git status', shell=True, stdout=PIPE).communicate()
resp = str(resp, 'utf8')
os.chdir(SITE_ROOT)
changeTemplate = re.compile('\t.*\n')
changedFiles = re.findall(changeTemplate, resp)
paths = []
for filePath in changedFiles:
filePath = re.split('\s+', filePath)[-2:-1][0].replace('\n', '')
paths.append(filePath)
data = {
'files': paths
}
return render(request, 'status.html', data)
def checkout(request):
os.chdir(MORDA_PATH)
os.system('git add -A')
os.system('git checkout -f')
os.chdir(SITE_ROOT)
data = {
'status': 'ok'
}
return HttpResponse(json.dumps(data))
def commit(request):
params = request.POST
files = []
message = 'HOME-0: Добавлены иконки в /all'
for key, val in params.items():
if key == 'commit__message' and val:
message = val
if val == 'on':
files.append(key)
if len(files):
files.insert(0, 'git add')
add_command = ' '.join(files)
os.chdir(MORDA_PATH)
os.system('git stash')
os.system('git pull origin dev')
os.system('git stash pop')
os.system(add_command)
os.system('git commit -m "' + message + '"')
os.chdir(SITE_ROOT)
data = {
'status': 'ok',
'message': message
}
else:
data = {
'status': 'error',
'error': 'nodata'
}
return HttpResponse(json.dumps(data))
# def index(request):
#
# params = request.GET
# meta = request.META
# st = 'HELLO, '
# date = time.strftime('%H:%M, %d %B %Y' ,time.localtime(time.time()))
# data = {
# 'MESSAGE': st,
# 'USER': 'nizhi',
# 'ONLINE': False,
# 'dates': ['123', '324324', '324324', '32432432', '565465', '546546'],
# 'PARAMS': params,
# 'DATE': date,
# 'req': params,
# 'metas': meta
# }
# return render(request, 'index.html', data, context_instance=RequestContext(request))
def test(request):
params = request.POST
cookies = request.COOKIES
meta = request.META
useragent = request.META.get('HTTP_USER_AGENT')
result = user_agents.parse(useragent)
isTouch = result.is_touch_capable
files = os.listdir(SITE_ROOT + '/../tmp/')
print(files)
services = Service.objects.order_by('name')
data = files
# return render(request, 'test.html', data)
return HttpResponse(json.dumps(data))
# Добавить сжатие, нормальные имена, перенос в правильные места
def handle_uploaded_file(file, serviceName, fileExtention):
path = SITE_ROOT + '/../tmp/' + serviceName + '.' + fileExtention
with open(path, 'wb+') as dest:
for chunk in file.chunks():
dest.write(chunk)
return path
# TODO добавить оптимизацию
def optimizeImg(path, ext):
if ext == 'png':
optimizePng(path)
elif ext == 'svg':
optimizeSvg(path)
else:
print('Другое расширение')
return
def optimizeSvg(path):
print('оптимизация svg...')
return
def optimizePng(path):
print('оптимизация png...')
return
def moveToDest(path, fileExtention, serviceName, settings):
isTr = 'turkey' in settings
files = []
for setting in settings:
if setting == 'turkey':
pass
else:
destPath = getDestPath(serviceName, setting, fileExtention, isTr)
os.system('cp ' + path + ' ' + MORDA_PATH + destPath)
def getDestPath(serviceName, setting, extention, isTr):
prefix = '_tr' if isTr else ''
if (setting == 'big'):
return 'tmpl/everything/blocks/common-all/services-main/services-main.inline/' + serviceName + prefix + '.' + extention
elif (setting == 'small'):
return 'tmpl/everything/blocks/common-all/services-all/services-all.inline/' + serviceName + '_small' + prefix + '.' + extention
elif (setting == '404'):
return 'tmpl/white/blocks/404/services/services.inline/service-' + serviceName + prefix + '.' + extention
def minifyPng(path):
ext - 5
|
987d1b7e9094dc8ac7ae70a6290d4d9fe19ff8ec
|
[
"Python"
] | 6 |
Python
|
ZhivotvorevNik/sendIcons
|
b3ebc6c4c87edca56bfd26788b77c6c8f6044fd3
|
ea09c010e86f4bc872aced4091915d311a33c22e
|
refs/heads/master
|
<file_sep>package com.blazemeter.csv;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.Reader;
public class RandomBufferedReader extends BufferedReader {
private final RandomAccessFile raf;
private long markedPosition;
public RandomBufferedReader(Reader in, RandomAccessFile raf) {
super(in);
this.raf = raf;
}
public void seek(long pos) throws IOException {
this.raf.seek(pos);
}
@Override
public int read() throws IOException {
return raf.read();
}
@Override
public void mark(int readAheadLimit) throws IOException {
markedPosition = raf.getFilePointer();
}
@Override
public void reset() throws IOException {
raf.seek(markedPosition);
}
}
<file_sep>package com.blazemeter.api.http;
import com.blazemeter.api.BlazeMeterReport;
import kg.apc.jmeter.reporters.notifier.StatusNotifierCallbackTest;
import net.sf.json.JSONObject;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.junit.Test;
import static org.junit.Assert.*;
public class BlazeMeterHttpUtilsTest {
@Test
public void testFlow() throws Exception {
final StatusNotifierCallbackTest.StatusNotifierCallbackImpl callbackTest = new StatusNotifierCallbackTest.StatusNotifierCallbackImpl();
final String address = "http://ip.jsontest.com/";
BlazeMeterReport report = new BlazeMeterReport();
report.setToken("<PASSWORD>token");
BlazeMeterHttpUtils entity = new BlazeMeterHttpUtils(callbackTest, address, address, report);
assertEquals(callbackTest, entity.getNotifier());
assertEquals(address, entity.getAddress());
assertEquals(address, entity.getDataAddress());
assertEquals(report, entity.getReport());
assertNotNull(entity.getHttpClient());
HttpGet get = entity.createGet(address);
JSONObject response = entity.queryObject(get, 200);
assertEquals("test_token", get.getHeaders("X-Api-Key")[0].getValue());
assertTrue(response.containsKey("ip"));
report.setToken("test:token");
entity = new BlazeMeterHttpUtils(callbackTest, address, address, report);
HttpPost post = entity.createPost(address, "");
entity.queryObject(post, 200);
assertTrue(post.getHeaders("Authorization")[0].getValue().startsWith("Basic "));
assertTrue(response.containsKey("ip"));
}
@Test
public void extractErrorMessageTest() throws Exception {
final StatusNotifierCallbackTest.StatusNotifierCallbackImpl callbackTest = new StatusNotifierCallbackTest.StatusNotifierCallbackImpl();
final String address = "http://ip.jsontest.com/";
BlazeMeterReport report = new BlazeMeterReport();
report.setToken("test_token");
BlazeMeterHttpUtils entity = new BlazeMeterHttpUtils(callbackTest, address, address, report);
String errorResponse = "{\"error\":{\"message\":\"Please, try later!\"}}";
String message = entity.extractErrorMessage(errorResponse);
assertEquals("Please, try later!", message);
errorResponse = "Please, try later!";
assertEquals(errorResponse, entity.extractErrorMessage(errorResponse));
}
}
|
a6b5127ec3744a7e97baeefc3aee18a17f9114fa
|
[
"Java"
] | 2 |
Java
|
briantully/jmeter-bzm-plugins
|
ab443e455652222e4f2fc09124c10b6eb73878e5
|
79dc895108367408e33d48823b1b3e21b7980617
|
refs/heads/master
|
<repo_name>yuuyas222/RSpec_practice_basic<file_sep>/practice.rb
# 基本的な記載
# describe => グループ化
RSpec.describe "四則演算" do
it "1+1は2になること" do #it = exaple
expect(1+1).to eq 2 #前はexpctではなく、should使ってたらしい
end
#複数いれることもできる
it "全部できる" do
expect(1+2).to eq 3
expect(2+2).to eq 4
expect(3+2).to eq 5
expect(4+2).to eq 6
end #テスト失敗した際次のexpectが成功するかわからない
#describeのネスト化
describe "足し算" do
end
describe "引き算" do
end
#context before
describe "#greet" do
context "12歳以下の場合" do
end
context "13歳以上の場合" do
end
#contextは「状況」みたいな意味合い describeと意味合いは同じ
end
#before do..end
describe "#greet" do
before do
@paramas = { name: "太郎" } #example前に必ず呼び出される インスタンス変数使用
end
context "12歳以下の場合" do
end
context "13歳以上の場合" do
end
end
#letのつかいかた
describe "#greet" do
let(:params){{ name: "太郎" }}
context "12歳以下の場合" do
end
context "13歳以上の場合" do
end
#subject
describe "#greet" do
let(:user){ User.new(params) }
let(:params) {{ name: "太郎", age: age } }
subject {user.greet}
context "12歳以下の場合" do
let(:age) { 12 }
it { is_expected.to eq "僕は太郎"}
end
context "13歳以下の場合" do
let(:age) { 13 }
it { is_expected.to eq "僕は太"}
end
end
end
|
6f6b72ed8ad464fd6f96b3e3abcc0696c66e466a
|
[
"Ruby"
] | 1 |
Ruby
|
yuuyas222/RSpec_practice_basic
|
d6eb81ed05467afea3f6a483af6d8e325c433a7f
|
2a0a30e734cc2035eca72696f28a3c5bb0a42444
|
refs/heads/master
|
<file_sep># AnswerAssistant
百万英雄答题助手
## 简介
最近比较火的百万英雄等直播答题软件助手,使用该软件可以实时查询百度,并通过算法推荐答案
## 原理
1. 使用安卓截屏功能,截取指定区域屏幕内容
2. 使用开源OCR识别框架tessract对截图进行文字识别,提取问题与可选答案
3. 调用百度进行问题搜索
## 注意事项
1. 由于要跨进程截取视频直播软件画面,使用悬浮框来进行触发,并且必须使用安卓屏幕录制功能,该功能只在安卓5.0以上系统支持。安卓5.0以下手机无法使用
2. 由于手机分辨率不一致,程序中设定截取指定区域的长宽可能要做一定修改。默认指定区域为:距离屏幕左右1/7宽的间隔,距离屏幕上方1/12高的间隔,
距离屏幕下方3/7高的间隔。可在源码的FileUtil中修改
<file_sep>package name.arche.www.answerassistant.util;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import com.googlecode.tesseract.android.TessBaseAPI;
/**
* Created by arche on 2018/1/11.
*/
public class TessAPIClient {
public enum LANGUAGE {
ENGLISH("eng"),
CHINESE("chi_sim");
private String language;
LANGUAGE(String language) {
this.language = language;
}
public String getLanguage() {
return language;
}
}
private static TessAPIClient sClient;
private TessBaseAPI mTessBaseAPI;
public static TessAPIClient getInstanse() {
if (sClient == null) {
synchronized (TessAPIClient.class) {
if (sClient == null)
sClient = new TessAPIClient();
}
}
return sClient;
}
private TessAPIClient() {
}
public void init(Context context, LANGUAGE language) {
FileUtil.copyFileIfNeed(context, FileUtil.CHI_TESS_DATA);
FileUtil.copyFileIfNeed(context, FileUtil.ENG_TESS_DATA);
if (mTessBaseAPI == null)
mTessBaseAPI = new TessBaseAPI();
mTessBaseAPI.init(FileUtil.SDCARD_PATH, language.getLanguage());
}
public String recognize(Bitmap bitmap) {
if (mTessBaseAPI == null)
return "";
mTessBaseAPI.setImage(bitmap);
return mTessBaseAPI.getUTF8Text();
}
}
<file_sep>package name.arche.www.answerassistant.event;
/**
* Created by arche on 2018/1/12.
*/
public class CloseWebViewEvent {
}
<file_sep>package name.arche.www.answerassistant.event;
/**
* Created by arche on 2018/1/12.
*/
public class ShowAnswerEvent {
private String mAnswer;
public ShowAnswerEvent(String answer) {
mAnswer = answer;
}
public String getAnswer() {
return mAnswer;
}
public void setAnswer(String answer) {
mAnswer = answer;
}
}
<file_sep>package name.arche.www.answerassistant.services;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import name.arche.www.answerassistant.R;
import name.arche.www.answerassistant.bean.Question;
import name.arche.www.answerassistant.event.CloseWebViewEvent;
import name.arche.www.answerassistant.event.ShowAnswerEvent;
import name.arche.www.answerassistant.util.Searcher;
/**
* Created by arche on 2018/1/12.
*/
public class WebViewWindow extends Service {
private static final String TAG = "WebViewWindow";
private WindowManager mWindowManager;
private WindowManager.LayoutParams mLayoutParams;
private View mFloatView;
private WebView mWebView;
private Context mContext;
private static final String HOST_NAME = "http://www.baidu.com/s?tn=ichuner&lm=-1&word=";
private Question mQuestion;
private TextView mAnswer;
@Subscribe
@Override
public void onCreate() {
super.onCreate();
EventBus.getDefault().register(this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mContext = this;
initViews(intent);
return super.onStartCommand(intent, flags, startId);
}
private void initViews(Intent intent) {
if (mWindowManager != null && mFloatView != null){
mWindowManager.removeView(mFloatView);
}
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
int w = display.getWidth();
int h = display.getHeight();
mFloatView = LayoutInflater.from(getApplication()).inflate(R.layout.float_window_webview, null);
mWindowManager = (WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE);
mLayoutParams = new WindowManager.LayoutParams();
mLayoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
mLayoutParams.format = PixelFormat.TRANSLUCENT;
mLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
mLayoutParams.gravity = Gravity.RIGHT | Gravity.BOTTOM;
mLayoutParams.x = 0;
mLayoutParams.y = 0;
mLayoutParams.width = w;
mLayoutParams.height = h / 3;
mAnswer = mFloatView.findViewById(R.id.tv_answer);
mFloatView.findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EventBus.getDefault().post(new CloseWebViewEvent());
}
});
mWebView = mFloatView.findViewById(R.id.wv_search);
mQuestion = (Question) intent.getSerializableExtra("question");
String keyWord = mQuestion != null ? mQuestion.getQuestion() : "";
String url = "www.arche.name";
boolean isKeywordEmpty = TextUtils.isEmpty(keyWord);
if (!isKeywordEmpty) {
try {
url = HOST_NAME + URLEncoder.encode(keyWord, "gb2312") + "&rn=20";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
new AnalyzeAnswersThread().start();
}
Log.e(TAG, "url:" + url);
mWebView.loadUrl(url);
mWebView.setWebViewClient(new WebViewClient());
mWindowManager.addView(mFloatView, mLayoutParams);
}
private class AnalyzeAnswersThread extends Thread {
@Override
public void run() {
// String[] ss = {"老年痴呆症","癫痫症","小儿麻痹症"};
// mQuestion = new Question("阿尔茨海默症又被称为什么?",ss);
String question = mQuestion.getQuestion();
String[] answers = mQuestion.getAnswers();
if (answers.length < 1) {
Log.e(TAG, "检测不到答案");
return;
}
//搜索
long countQuestion = 1;
int numOfAnswer = answers.length > 3 ? 4 : answers.length;
long[] countQA = new long[numOfAnswer];
long[] countAnswer = new long[numOfAnswer];
int maxIndex = 0;
Searcher[] searchQA = new Searcher[numOfAnswer];
Searcher[] searchAnswers = new Searcher[numOfAnswer];
FutureTask[] futureQA = new FutureTask[numOfAnswer];
FutureTask[] futureAnswers = new FutureTask[numOfAnswer];
FutureTask futureQuestion = new FutureTask<Long>(new Searcher(question));
new Thread(futureQuestion).start();
for (int i = 0; i < numOfAnswer; i++) {
searchQA[i] = new Searcher(question + " " + answers[i]);
searchAnswers[i] = new Searcher(answers[i]);
futureQA[i] = new FutureTask<Long>(searchQA[i]);
futureAnswers[i] = new FutureTask<Long>(searchAnswers[i]);
new Thread(futureQA[i]).start();
new Thread(futureAnswers[i]).start();
}
try {
while (!futureQuestion.isDone()) {
}
countQuestion = (Long) futureQuestion.get();
for (int i = 0; i < numOfAnswer; i++) {
while (true) {
if (futureAnswers[i].isDone() && futureQA[i].isDone()) {
break;
}
}
countQA[i] = (Long) futureQA[i].get();
countAnswer[i] = (Long) futureAnswers[i].get();
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
float[] ans = new float[numOfAnswer];
for (int i = 0; i < numOfAnswer; i++) {
ans[i] = (float) countQA[i] / (float) (countQuestion * countAnswer[i]);
maxIndex = (ans[i] > ans[maxIndex]) ? i : maxIndex;
}
//根据pmi值进行打印搜索结果
int[] rank = rank(ans);
Log.e(TAG, "answer:" + answers[maxIndex]);
EventBus.getDefault().post(new ShowAnswerEvent(answers[maxIndex]));
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void showAnswer(ShowAnswerEvent event) {
if (mAnswer != null)
mAnswer.setText("推荐答案:" + event.getAnswer());
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
mWindowManager.removeView(mFloatView);
EventBus.getDefault().unregister(this);
super.onDestroy();
}
private static int[] rank(float[] floats) {
int[] rank = new int[floats.length];
float[] f = Arrays.copyOf(floats, floats.length);
Arrays.sort(f);
for (int i = 0; i < floats.length; i++) {
for (int j = 0; j < floats.length; j++) {
if (f[i] == floats[j]) {
rank[i] = j;
}
}
}
return rank;
}
}
|
7ceec37b3acf56ff7d96f162278fc53db30d6cb7
|
[
"Markdown",
"Java"
] | 5 |
Markdown
|
zArche/AnswerAssistant
|
e81e6cd2fb43842676edc5926099328266c9b57f
|
0cff15f26523f27a71349d9ab43b3597cfdabb60
|
refs/heads/main
|
<file_sep>import styled from 'styled-components';
export const TextDescription = styled.p`
font-size: 13px;
text-align: justify;
@media screen and (min-width: 768px) {
font-size: 16px;
}
`;
export const TextSubtitles = styled.h3`
font-size: 13px;
text-align: initial;
@media screen and (min-width: 768px) {
font-size: 16px;
}
`;
<file_sep>import styled from 'styled-components';
export const ContainerEducation = styled.ul`
list-style: none;
padding: 20px 30px;
`;
export const ContainerRol = styled.div`
margin-top: 11px;
margin-bottom: 7px;
`;
<file_sep>import { library } from '@fortawesome/fontawesome-svg-core';
import {
faGithub,
faLinkedin,
faHtml5,
faCss3,
faJs,
faReact,
faNode,
faDocker,
faFigma,
faGitAlt,
} from '@fortawesome/free-brands-svg-icons';
import {
faEnvelopeOpenText,
faBars,
faTimesCircle,
faLink,
faBrain,
faPalette,
faChalkboardTeacher,
faArrowAltCircleUp
} from '@fortawesome/free-solid-svg-icons';
library.add(
faGithub,
faLinkedin,
faEnvelopeOpenText,
faBars,
faTimesCircle,
faLink,
faHtml5,
faCss3,
faJs,
faReact,
faNode,
faDocker,
faFigma,
faGitAlt,
faBrain,
faPalette,
faChalkboardTeacher,
faArrowAltCircleUp,
);
<file_sep>import React from 'react';
import styled from 'styled-components';
const FooterStyle = styled.footer`
margin-top: 35px;
background-color: #fcfcfc;
padding: 25px 20px;
position: absolute;
font-size: 13px;
text-align: initial;
width: 100vw;
@media screen and (min-width: 768px) {
display: flex;
justify-content: space-evenly;
}
`;
const ContentFooter = styled.div`
margin-bottom: 25px;
line-height: 13px;
@media screen and (min-width: 768px) {
width: 215px;
}
`;
const ParragraphMade = styled.p`
margin-bottom: 7px;
`;
export function Footer() {
return (
<FooterStyle>
<ContentFooter>
<ParragraphMade><strong>Made with love by <NAME></strong></ParragraphMade>
<p>© 2020 PORTFOLIO <NAME>, All Rights Reserved</p>
</ContentFooter>
<ContentFooter>
<p>Currently living in Colombia, Bogotá D.C.</p>
</ContentFooter>
<div>
<p><strong>Email:</strong> <EMAIL></p>
<p><strong>Phone: +</strong>3102139570</p>
</div>
</FooterStyle>
);
}
<file_sep>import React from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { ContainerSection, SectionName, } from '../components/styled/ContainerSection';
import { TextDescription } from '../components/styled/TextSyles';
import {
ContainerListSkills,
ListItemSkills,
TextSkill,
ContainerFlex,
} from '../components/SkillsStyled';
export function Skills() {
return(
<ContainerSection>
<ContainerFlex>
<div>
<SectionName>
Skills
</SectionName>
<TextDescription style={{ paddingRight: 37, paddingLeft: 37 }}>
During my career I learned different technologies and developed soft skills, in this section I share some of the them:
</TextDescription>
</div>
<div>
<ContainerListSkills>
<ListItemSkills>
<FontAwesomeIcon icon={['fab', 'html5']} size="3x" />
<TextSkill>HTML 5</TextSkill>
</ListItemSkills>
<ListItemSkills>
<FontAwesomeIcon icon={['fab', 'css3']} size="3x" />
<TextSkill>CSS 3</TextSkill>
</ListItemSkills>
<ListItemSkills>
<FontAwesomeIcon icon={['fab', 'js']} size="3x" />
<TextSkill>JavaScript</TextSkill>
</ListItemSkills>
<ListItemSkills>
<FontAwesomeIcon icon={['fab', 'react']} size="3x" />
<TextSkill>React Js</TextSkill>
</ListItemSkills>
<ListItemSkills>
<FontAwesomeIcon icon={['fab', 'node']} size="3x" />
<TextSkill>Node Js</TextSkill>
</ListItemSkills>
<ListItemSkills>
<img src="https://res.cloudinary.com/dkcbxnhg0/image/upload/v1614119326/portfolio/mongodb_1_ytirwk.png"/>
<TextSkill>MongoDB</TextSkill>
</ListItemSkills>
<ListItemSkills>
<FontAwesomeIcon icon={['fab', 'docker']} size="3x" />
<TextSkill>Docker</TextSkill>
</ListItemSkills>
<ListItemSkills>
<FontAwesomeIcon icon={['fab', 'figma']} size="3x" />
<TextSkill>Figma</TextSkill>
</ListItemSkills>
<ListItemSkills>
<img src="https://img.icons8.com/ios/50/000000/notion.png"/>
<TextSkill>Notion</TextSkill>
</ListItemSkills>
<ListItemSkills>
<FontAwesomeIcon icon={['fab', 'git-alt']} size="3x" />
<TextSkill>Git</TextSkill>
</ListItemSkills>
<ListItemSkills>
<FontAwesomeIcon icon={['fas', 'brain']} size="3x" />
<TextSkill>Critical thinking</TextSkill>
</ListItemSkills>
<ListItemSkills>
<FontAwesomeIcon icon={['fas', 'palette']} size="3x" />
<TextSkill>Creative</TextSkill>
</ListItemSkills>
<ListItemSkills>
<FontAwesomeIcon icon={['fas', 'chalkboard-teacher']} size="3x" />
<TextSkill>Mentoring</TextSkill>
</ListItemSkills>
</ContainerListSkills>
</div>
</ContainerFlex>
</ContainerSection>
);
}
<file_sep>import React from 'react';
import './App.css';
import './assets/icon';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Nav from './components/Nav';
import Home from './pages/Home';
import { Profile } from './pages/Profile';
import { Projects } from './pages/Projects';
import { Skills } from './pages/Skills';
import { Education } from './pages/Education';
import { Contact } from './pages/Contact';
function App() {
return (
<div className="App">
<Router>
<Nav></Nav>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/profile" component={Profile} />
<Route exact path="/projects" component={Projects} />
<Route exact path="/skills" component={Skills} />
<Route exact path="/education" component={Education} />
<Route exact path="/contact" component={Contact} />
</Switch>
</Router>
</div>
);
}
export default App;
<file_sep>import React, { useState } from 'react';
import { Footer } from '../components/Footer';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { ContainerSection, SectionName } from '../components/styled/ContainerSection';
import {
FormContainer,
InputForm,
LabelForm,
ButtonSend,
ButtomTop,
SucceededForm,
LabelsFlex,
TextArea,
} from '../components/ContactStyled';
import { useForm, ValidationError } from '@formspree/react';
export function Contact() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [message, setMessage] = useState('');
const [state, handleSubmit] = useForm('contactMe');
if(state.succeeded) {
return(
<ContainerSection>
<SucceededForm>
<p>Thanks for contact me</p>
</SucceededForm>
<ButtomTop to="/">
<FontAwesomeIcon icon={'arrow-alt-circle-up'} size="2x" />
</ButtomTop>
<Footer />
</ContainerSection>
);
}
return(
<>
<ContainerSection>
<SectionName>Contact</SectionName>
<div>
<FormContainer onSubmit={handleSubmit}>
<LabelsFlex>
<LabelForm htmlFor="name">
<span>Name</span>
<InputForm
placeholder="Your name"
id="name"
type="text"
name="name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</LabelForm>
<LabelForm htmlFor="email">
<span>Email</span>
<InputForm
placeholder="Your email"
id="email"
type="text"
name="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<ValidationError field="email" prefix="Email" errors={state.errors} />
</LabelForm>
</LabelsFlex>
<span>
<LabelForm htmlFor="message">
<span>Message</span>
<TextArea
as={'textarea'}
style={{ marginLeft: 25 }}
id="message"
type="text"
name="message"
value={message}
onChange={(e) => setMessage(e.target.value)}
rows="15"
cols="32"
placeholder="Hi, Carolina, I would like work with you..."
>
</TextArea>
</LabelForm>
</span>
<ButtonSend type="submit" disabled={state.submitting} >SEND</ButtonSend>
<ValidationError errors={state.errors} />
</FormContainer>
<ButtomTop to="/">
<FontAwesomeIcon icon={'arrow-alt-circle-up'} size="2x" />
</ButtomTop>
</div>
</ContainerSection>
<Footer />
</>
);
}
<file_sep>import styled from 'styled-components';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
export const Name = styled.h1`
font-size: 48px;
margin: 7px 49px;
@media screen and (min-width: 768px) {
font-size: 64px;
};
`;
export const Carrer = styled.h2`
font-size: 16px;
margin: 7px 49px;
@media screen and (min-width: 768px) {
font-size: 24px;
};
`;
export const ContactInfo = styled.span`
display: block;
margin: 7px 49px;
`;
export const ParragrahpContact = styled.p`
display: inline-block;
`;
export const SectionQuoute = styled.section`
display: flex;
margin: 49px;
`;
export const IconMargin = styled(FontAwesomeIcon)`
margin-right: 32px;
`;
export const ParragrahpQuote = styled.blockquote`
p {
text-shadow: 1px 1px 7px black;
line-height: 20px;
margin-bottom: 17px;
}
h4 {
font-weight: 400;
}
@media screen and (min-width: 768px) {
font-size: 24px;
width: 350px;
margin-left: 39px;
};
`;
<file_sep>import styled from 'styled-components';
export const ListProjects = styled.ul`
list-style: none;
padding: 0 5px;
display: grid;
grid-template-columns: repeat(3, 150px);
gap: 15px;
`;
export const ListAnchor = styled.a`
line-height: 0;
color: ${(props) => props.theme.justBlack};
`;
export const ImageProject = styled.img`
width: 100%;
height: 180px;
object-fit: cover;
border-radius: 15px;
`;
export const ProjectOverlay = styled.div``;
export const TitleProject = styled.h3`
font-size: 15px;
margin: 8px 0 0;
`;
<file_sep>import React from 'react';
import styled from 'styled-components';
import { Link } from 'react-router-dom';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { useState } from 'react';
const ContainerHeader = styled.header`
position: fixed;
z-index: 1;
right: 0;
height: 100vh;
width: 50vw;
@media screen and (min-width: 768px) {
width: 30vw;
}
`;
const ButtonIcon = styled.button`
position: fixed;
top: 12.5px;
right: 45px;
padding: 0;
height: 32px;
width: 32px;
background: rgba(255,255,255,0);
border: none;
z-index: 3;
`;
const Container = styled.div`
position: absolute;
right: 0;
padding: 138px 24px;
background-color: #ebf579;
height: inherit;
width: inherit;
z-index: 2;
`;
const ItemsList = styled.ul`
text-align: start;
list-style: none;
font-size: 13px;
font-weight: bold;
`;
const ItemLink = styled(Link)`
text-decoration: none;
color: black;
&:hover &active {
background-color: rgba(255, 255, 255, 0.69);
border-radius: 7px;
padding: 2px 10px;
};
`;
const Item = styled.li`
margin-bottom: 28px;
`;
function Nav() {
const [shown, setShown] = useState(false);
const handleToggleNav = () => {
setShown(true);
};
const handleCloseNav = () => {
setShown(false);
};
return (
<ContainerHeader>
{shown ? (
<ButtonIcon onClick={handleCloseNav}>
<FontAwesomeIcon icon={'times-circle'} size="2x" />
</ButtonIcon>
) : (
<ButtonIcon onClick={handleToggleNav}>
<FontAwesomeIcon icon={'bars'} size="2x"/>
</ButtonIcon>
)}
{shown ? (
<Container>
<ItemsList className="nav">
<Item><ItemLink onClick={handleCloseNav} to="/">Home</ItemLink></Item>
<Item><ItemLink onClick={handleCloseNav} to="/profile">Profile</ItemLink></Item>
<Item><ItemLink onClick={handleCloseNav} to="/projects">Projects</ItemLink></Item>
<Item><ItemLink onClick={handleCloseNav} to="/skills">Skills</ItemLink></Item>
<Item><ItemLink onClick={handleCloseNav} to="/education">Education</ItemLink></Item>
<Item><ItemLink onClick={handleCloseNav} to="/contact">Contact</ItemLink></Item>
</ItemsList>
</Container>
) : (null)}
</ContainerHeader>
);
}
export default Nav;
<file_sep>import React from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
Name,
Carrer,
ContactInfo,
ParragrahpContact,
SectionQuoute,
IconMargin,
ParragrahpQuote,
} from '../components/HomeStyled';
import { Section } from '../components/MainStyled';
function Home() {
return(
<Section>
<Name> Carolina <br/> Salazar </Name>
<Carrer> Front End Developer </Carrer>
<ContactInfo>
<IconMargin icon={['fab', 'github']} size="2x"/>
<FontAwesomeIcon icon={['fab', 'linkedin']} size="2x"/>
</ContactInfo>
<ContactInfo>
<IconMargin icon={'envelope-open-text'} size="2x"/>
<ParragrahpContact>Contact me</ParragrahpContact>
</ContactInfo>
<SectionQuoute>
<figure>
<img
srcSet="https://res.cloudinary.com/dkcbxnhg0/image/upload/v1610402784/portfolio/cover_pasyhb.svg 414w"
sizes="(max-width: 414px) 414px,
768px"
src="https://res.cloudinary.com/dkcbxnhg0/image/upload/v1614292739/portfolio/homeIpad_bbjwua.png"
alt="Imagen de cover para el home"
/>
</figure>
<ParragrahpQuote>
<p>
{/* eslint-disable-next-line */}
"If you can't love yourself, how in the hell you gonna love somebody else"
</p>
<h4>RuPaul</h4>
</ParragrahpQuote>
</SectionQuoute>
</Section>
);
}
export default Home;
<file_sep>import React from 'react';
import styled from 'styled-components';
const StyledSection = styled.main`
width: 100%;
padding-top: 40px;
max-width: 100vw;
display: flex;
flex-direction: column;
align-items: baseline;
text-align: initial;
@media screen and (min-width: 768px) {
grid-column-start: 2;
min-height: 100vh;
max-width: calc(100vw - 250px);
}
`;
export function Section({ children }) {
return (
<StyledSection>
{children}
</StyledSection>
);
}
<file_sep>import styled from 'styled-components';
import { Link } from 'react-router-dom';
export const FormContainer = styled.form`
display: flex;
flex-direction: column;
align-items: center;
`;
export const LabelForm = styled.label`
display: flex;
align-items: center;
font-size: 13px;
font-weight: bold;
margin-bottom: 43px;
@media screen and (min-width: 768px) {
font-size: 16px;
}
`;
export const InputForm = styled.input`
background: rgba(229, 229, 229, 0.12);
border-radius: 7px;
padding: 8px 10px;
width: 208px;
border: none;
margin-left: 42px;
border-bottom: 1px solid ${(props) => props.theme.graySolid};
&:focus {
outline-color: ${(props) => props.theme.primaryColor};
}
`;
export const ButtonSend = styled.button`
padding: 10px 26px;
border-radius: 7px;
border: none;
background-color: ${(props) => props.theme.primaryColor};
font-size: 13px;
font-weight: bold;
&:hover {
background-color: ${(props) => props.theme.hoverPrimary};
border: 1px solid ${(props) => props.theme.primaryColor};
}
&:focus {
outline: none;
}
`;
export const ButtomTop = styled(Link)`
position: relative;
right: -35%;
z-index: 1;
text-decoration: revert;
color: black;
`;
export const SucceededForm = styled.div`
display: flex;
justify-content: center;
align-items: center;
height: 80vh;
background-repeat: no-repeat;
`;
export const LabelsFlex = styled.span`
@media screen and (min-width: 768px) {
display: flex;
flex-wrap: wrap;
width: 634px;
justify-content: space-between;
}
`;
export const TextArea = styled(InputForm)`
@media screen and (min-width: 768px) {
width: 537px;
}
`;
<file_sep>import React from 'react';
import {
PhotoAboutMe,
ContainerAboutMe,
TextAboutMe,
} from '../components/ProfileStyled';
export function Profile() {
return (
<ContainerAboutMe>
<figure>
<PhotoAboutMe
srcSet="https://res.cloudinary.com/dkcbxnhg0/image/upload/v1610402819/portfolio/aboutme_pevhwq.jpg 414w"
sizes="(max-width: 414px) 414px,
768px"
src="https://res.cloudinary.com/dkcbxnhg0/image/upload/v1614295576/portfolio/aboutmeIpad_esh328.png"
alt="Profile photo Carolina"
/>
</figure>
<div>
<TextAboutMe>
Hi, my name is <NAME>, I live in Bogotá I am FullStack Developer and also I have a Master in Energy Sustainability, I found a passion in design and developed web, I am searching challenges in web programming.
</TextAboutMe>
<TextAboutMe>
My previous experience was in the program Top for Make It Real where I build two applications with integration the BackEnd and FrontEnd in JavaScript.
</TextAboutMe>
<TextAboutMe>
I like to work in group, many times I stand out for my leadership and my structuring at the moment for developing a project.
</TextAboutMe>
</div>
</ContainerAboutMe>
);
}
|
749e64bf4d447941418fcccb5a52849d9f14fcd2
|
[
"JavaScript"
] | 14 |
JavaScript
|
carosalazar28/Website-2021
|
c13c3a8b594f762970065479962a365406b10868
|
2aa44ad13eb38fbffcb1661e31e42fb086b2a7fd
|
refs/heads/master
|
<file_sep>import sys
from collections import defaultdict
import bpemb
import re
fname = sys.argv[1] #e.g., selectedUDT-v2.1/UD_English/dev or test or train
lang = sys.argv[2] #English ##source language type
ftype = sys.argv[3] #e.g., dev ## wich text
context_N = int(sys.argv[4]) #N-char context
try:
nk_tokens = int(sys.argv[5])
except:
nk_tokens = 9999
# lang = "English"
# fname = "selectedUDT-v2.1/UD_{}/dev".format(lang)
# ftype = "dev"
# merge_N = 500 # vocabulary size
# context_N = 20
# nk_tokens = 10
WBEGIN = '<w>'
WEND = '</w>'
LC = '<lc>'
RC = '<rc>'
def readFile(fname):
with open(fname, "r") as f:
fc = f.read()
fc = fc.split("\n")
return fc
# input is list of tuples: [(sentence, surface_form, lemma)]
# output is source and target file
def write_data_to_files(data, fName):
with open(fName + '-sources', "w") as s:
with open(fName + '-targets', "w") as t:
for context, surface_form, lemma, in data:
cs = context.split("<SURFACE_FORM>")
lc = cs[0].split(" ")
lc = lc[-min(context_N, len(lc)):] # ['<s>', 'a', 'p', 'p', '']
lc_out = chas2trigram(lc, 'l')
rc = cs[1].split(" ")
rc = rc[:min(context_N, len(rc))] # [ '', '<s>', 'a', 'p', 'p']
rc_out = chas2trigram(rc, 'r')
surface_form = " ".join(re.compile('.{1}').findall(surface_form))
surface_form = chas2trigram(surface_form)
a = "{} {} {} {} {} {} {}\n".format(WBEGIN, lc_out, LC, surface_form, RC, rc_out, WEND)
s.write(a)
lemma = chas2trigram(" ".join([l for l in lemma]))
t.write("{} {} {}\n".format(WBEGIN, lemma, WEND))
# t.write("{} {} {}\n".format(WBEGIN, " ".join([l for l in lemma]), WEND))
def chas2trigram(sent, direction='none'):
sent_out_list = []
# split sentence into word list, word are
sent = " ".join(sent)
sent = re.split("<s>", sent)
for w in sent: # w, e.g, " a p p "
trigram_list = []
w = w.strip()
w = ''.join(c for c in w.split())
if len(w) == 0:
continue
if len(w) < 3:
trigram_list.append(w)
else:
for i in range(len(w)-2):
trigram_list.append(w[i:i+3])
sent_out_list.append(trigram_list)
sent_out = []
for item in sent_out_list:
item = " ".join(tri for tri in item)
sent_out.append(item)
sent_out = " <s> ".join(sent_out)
if direction == 'l':
sent_out = sent_out + " <s>"
elif direction == 'r':
sent_out = "<s> " + sent_out
else:
pass
return sent_out
if __name__ == '__main__':
data = readFile(fname)
surface_form2lemma = defaultdict(list)
surface_form2sent = defaultdict(list)
count = 0
for i, line in enumerate(data):
try:
lc = line.split("\t")
surface_form = lc[0]
lemma = lc[1]
POS = lc[2]
sentence = lc[3]
# omit examples with empty lemma
if lemma == "":
continue
# omit examples whose lemma contain "0987654321-/"
if any([True if d in lemma else False for d in "0987654321-/"]):
continue
if count < (nk_tokens*1000):
surface_form2lemma[surface_form].append(lemma)
surface_form2sent[surface_form].append((sentence, lemma))
count += 1
else:
break
except:
pass
data = []
surface_form_list = []
for surface_form, lemmas in surface_form2lemma.items():
if surface_form not in surface_form_list:
surface_form_list.append(surface_form)
for sentence, lemma in surface_form2sent[surface_form]:
data.append((sentence, surface_form, lemma))
write_data_to_files(data, "{}".format(ftype))
<file_sep>import sys
from collections import defaultdict
import random
# flag=0
fname = sys.argv[1]
lang = sys.argv[2]
ftype = sys.argv[3]
n = int(sys.argv[4])
try:
nk_tokens = int(sys.argv[5])
except:
nk_tokens = 9999
# flag = 1
# flag=0
# fname = "selectedUDT-v2.1/UD_English/train"
# lang = "English"
# ftype = "train"
# n = 20
# nk_tokens = 10
WBEGIN = '<w>'
WEND = '</w>'
LC = '<lc>'
RC = '<rc>'
def readFile(fname):
with open(fname, "r") as f:
fc = f.read()
fc = fc.split("\n")
return fc
def write_data_to_files(data, fName):
with open(fName + '-sources', "w") as s:
with open(fName + '-targets', "w") as t:
for context, surface_form, lemma, in data:
s.write("{} {} {}\n".format(WBEGIN, trim_input(context, n, " ".join([l for l in surface_form])), WEND))
t.write("{} {} {}\n".format(WBEGIN, " ".join([l for l in lemma]), WEND))
def trim_input(inp, n, surface_form):
if n > 0:
cs = inp.split("<SURFACE_FORM>")
lc = cs[0].split(" ")
lc = " ".join(lc[-min(n, len(lc)):])
rc = cs[1].split(" ")
rc = " ".join(rc[:min(n, len(rc))])
return "{} {} {} {} {}".format(lc, LC, surface_form, RC, rc)
else:
return "{} {} {} {} {}".format( LC, surface_form, RC)
if __name__ == '__main__':
data = readFile(fname)
surface_form2lemma = defaultdict(list)
surface_form2sent = defaultdict(list)
selected_dno = []
count = 0
for i, line in enumerate(data):
try:
lc = line.split("\t")
surface_form = lc[0]
lemma = lc[1]
POS = lc[2]
sentence = lc[3]
if lemma == "":
continue
# omit examples whose lemma contain "0987654321-/"
if any([True if d in lemma else False for d in "0987654321-/"]):
continue
if count < (nk_tokens*1000):
surface_form2lemma[surface_form].append(lemma)
surface_form2sent[surface_form].append((sentence, lemma))
count += 1
else:
break
except:
pass
data = []
surface_form_list = []
for surface_form, lemmas in surface_form2lemma.items():
for sentence, lemma in surface_form2sent[surface_form]:
data.append((sentence, surface_form, lemma))
write_data_to_files(data, "{}".format(ftype))
<file_sep>#!/bin/bash
UD_directory=selectedUDT-v2.1 #change for other versions
languages="English Arabic Turkish Spanish Indonesian" # list of languages to process
N=( $1 ) # N context
for n in "${N[@]}"
do
for lang in ${languages}
do
targetDir=../data-full/${lang}-char-${N}-context
mkdir -p ${targetDir}
python3 format-char.py $UD_directory/UD_${lang}/train ${lang} train ${n}
mv train-* ${targetDir}/.
python3 format-char.py $UD_directory/UD_${lang}/dev ${lang} dev ${n}
mv dev-* ${targetDir}/.
python3 format-char.py $UD_directory/UD_${lang}/test ${lang} test ${n}
mv test-* ${targetDir}/.
targetDir=../data-lite/${lang}-char-${N}-context-lite
mkdir -p ${targetDir}
python3 format-char.py $UD_directory/UD_${lang}/train ${lang} train ${n} 10
mv train-* ${targetDir}/.
python3 format-char.py $UD_directory/UD_${lang}/dev ${lang} dev ${n} 3
mv dev-* ${targetDir}/.
python3 format-char.py $UD_directory/UD_${lang}/test ${lang} test ${n}
mv test-* ${targetDir}/.
done
done
<file_sep>#!/bin/bash
types= "100-bpe-20-context
500-bpe-20-context
1000-bpe-20-context
3000-bpe-20-context
5000-bpe-20-context
char-20-context
trigram-20-context
morfessor-20-context
morfessorall-20-context"
languages="English Arabic Turkish Spanish Indonesian"
for type in ${types}
do
echo $type
for lang in ${languages}
do
echo ${lang}-${type}
mkdir -p data-lite/${lang}-${type}-lite/data-pp/
mkdir -p data-full/${lang}-${type}/data-pp/
echo "Starting dp"
onmt_preprocess \
-train_src data-lite/${lang}-${type}-lite/train-sources\
-train_tgt data-lite/${lang}-${type}-lite/train-targets \
-valid_src data-lite/${lang}-${type}-lite/dev-sources \
-valid_tgt data-lite/${lang}-${type}-lite/dev-targets \
-src_seq_length 75 \
-tgt_seq_length 75 \
-save_data data-lite/${lang}-${type}-lite/data-pp/${lang}-${type}-lite
onmt_preprocess \
-train_src data-full/${lang}-${type}/train-sources\
-train_tgt data-full/${lang}-${type}/train-targets \
-valid_src data-full/${lang}-${type}/dev-sources \
-valid_tgt data-full/${lang}-${type}/dev-targets \
-src_seq_length 75 \
-tgt_seq_length 75 \
-save_data data-full/${lang}-${type}/data-pp/${lang}-${type}
echo "End of dp"
done
done<file_sep>cd representation
sh format-bpe.sh 100 20
sh format-bpe.sh 500 20
sh format-bpe.sh 1000 20
sh format-bpe.sh 3000 20
sh format-bpe.sh 5000 20
sh format-bpeall.sh 100 20
sh format-bpeall.sh 500 20
sh format-bpeall.sh 1000 20
sh format-bpeall.sh 3000 20
sh format-bpeall.sh 5000 20
#sh format-char.sh 20
#sh format-morfessor.sh 20
#sh format-morfessorall.sh 20
#sh format-trigram.sh 20
<file_sep>merge_N=$1 #500
n_context=$2 #20
UD_directory=selectedUDT-v2.1 # origianl data sources
languages="English Arabic Turkish Spanish Indonesian" # list of languages to process
for lang in ${languages}
do
echo $lang
targetDir=../data-full/${lang}-${merge_N}-bpe-${n_context}-context
mkdir -p ${targetDir}
python3 format-bpe.py $UD_directory/UD_${lang}/train ${lang} train ${merge_N} ${n_context}
mv train-* ${targetDir}/.
python3 format-bpe.py $UD_directory/UD_${lang}/dev ${lang} dev ${merge_N} ${n_context}
mv dev-* ${targetDir}/.
python3 format-bpe.py $UD_directory/UD_${lang}/test ${lang} test ${merge_N} ${n_context}
mv test-* ${targetDir}/.
# for lite
targetDir2=../data-lite/${lang}-${merge_N}-bpe-${n_context}-context-lite
mkdir -p ${targetDir2}
python3 format-bpe.py $UD_directory/UD_${lang}/train ${lang} train ${merge_N} ${n_context} 10
mv train-* ${targetDir2}/.
python3 format-bpe.py $UD_directory/UD_${lang}/dev ${lang} dev ${merge_N} ${n_context} 3
mv dev-* ${targetDir2}/.
python3 format-bpe.py $UD_directory/UD_${lang}/test ${lang} test ${merge_N} ${n_context}
mv test-* ${targetDir2}/.
done
<file_sep>export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
modelDir=$1 # given the dictionary name of model, likes models-char
type=$2 #500-bpe-20-context
languages=$3
batch_size=60
burn_in_for_n_epochs=10
patience=10 # early_stopping_n_epochs
val_every_n_epochs=1
for lang in ${languages}
do
datadir=${lang}-${type}
mkdir -p ${modelDir}/${lang}-${type}/
steps_of_an_epoch=($(wc -l ./data-full/${datadir}/train-sources))
#use the first 10 epochs as a burn-in period
validBurnIn=$((steps_of_an_epoch *${burn_in_for_n_epochs} / ${batch_size}))
# early stopping with patience 10
early_stopping_steps=$((steps_of_an_epoch *${patience} / ${batch_size}))
# validate every epoch
val_steps=$((steps_of_an_epoch *${val_every_n_epochs}/ ${batch_size}))
echo "Sarting training, steps_of_an_epoch:"
echo ${val_steps}
echo "validBurnIn steps"
echo ${validBurnIn}
onmt_train -data data-full/${datadir}/data-pp/${datadir}\
--save_model ${modelDir}/${datadir}/${lang}-${type}\
--save_checkpoint_steps 3000000\
--encoder_type brnn\
--decoder_type rnn\
--enc_layers 2\
--dec_layers 2\
--rnn_type GRU\
--batch_size 60\
--src_word_vec_size 300\
--tgt_word_vec_size 300\
--rnn_size 100\
--optim "adadelta" \
--dropout 0.2\
--early_stopping 10\
--valid_steps ${val_steps}\
--warmup_steps ${validBurnIn}\
--train_steps 3000000\
--report_every ${steps_of_an_epoch} \
--gpu_ranks 0 2>&1 | tee ${modelDir}/${datadir}/train-log-${lang}-${type}.txt
echo "End of training"
done
<file_sep>sh train-gpu-lite.sh models-bpe 100-bpe-20-context Englsih
sh train-gpu-lite.sh models-bpe 100-bpe-20-context Turkish
sh train-gpu-lite.sh models-bpe 100-bpe-20-context Spanish
sh train-gpu-lite.sh models-bpe 100-bpe-20-context Arabic
sh train-gpu-lite.sh models-bpe 100-bpe-20-context Indonesian
sh train-gpu-lite.sh models-bpe 500-bpe-20-context Englsih
sh train-gpu-lite.sh models-bpe 500-bpe-20-context Turkish
sh train-gpu-lite.sh models-bpe 500-bpe-20-context Spanish
sh train-gpu-lite.sh models-bpe 500-bpe-20-context Arabic
sh train-gpu-lite.sh models-bpe 500-bpe-20-context Indonesian
sh train-gpu-lite.sh models-bpe 1000-bpe-20-context Englsih
sh train-gpu-lite.sh models-bpe 1000-bpe-20-context Turkish
sh train-gpu-lite.sh models-bpe 1000-bpe-20-context Spanish
sh train-gpu-lite.sh models-bpe 1000-bpe-20-context Arabic
sh train-gpu-lite.sh models-bpe 1000-bpe-20-context Indonesian
sh train-gpu-lite.sh models-bpe 3000-bpe-20-context Englsih
sh train-gpu-lite.sh models-bpe 3000-bpe-20-context Turkish
sh train-gpu-lite.sh models-bpe 3000-bpe-20-context Spanish
sh train-gpu-lite.sh models-bpe 3000-bpe-20-context Arabic
sh train-gpu-lite.sh models-bpe 3000-bpe-20-context Indonesian
sh train-gpu-lite.sh models-bpe 5000-bpe-20-context Englsih
sh train-gpu-lite.sh models-bpe 5000-bpe-20-context Turkish
sh train-gpu-lite.sh models-bpe 5000-bpe-20-context Spanish
sh train-gpu-lite.sh models-bpe 5000-bpe-20-context Arabic
sh train-gpu-lite.sh models-bpe 5000-bpe-20-context Indonesian
sh train-gpu-lite.sh models-bpeall 100-bpeall-20-context Englsih
sh train-gpu-lite.sh models-bpeall 100-bpeall-20-context Turkish
sh train-gpu-lite.sh models-bpeall 100-bpeall-20-context Spanish
sh train-gpu-lite.sh models-bpeall 100-bpeall-20-context Arabic
sh train-gpu-lite.sh models-bpeall 100-bpeall-20-context Indonesian
sh train-gpu-lite.sh models-bpeall 500-bpeall-20-context Englsih
sh train-gpu-lite.sh models-bpeall 500-bpeall-20-context Turkish
sh train-gpu-lite.sh models-bpeall 500-bpeall-20-context Spanish
sh train-gpu-lite.sh models-bpeall 500-bpeall-20-context Arabic
sh train-gpu-lite.sh models-bpeall 500-bpeall-20-context Indonesian
sh train-gpu-lite.sh models-bpeall 1000-bpeall-20-context Englsih
sh train-gpu-lite.sh models-bpeall 1000-bpeall-20-context Turkish
sh train-gpu-lite.sh models-bpeall 1000-bpeall-20-context Spanish
sh train-gpu-lite.sh models-bpeall 1000-bpeall-20-context Arabic
sh train-gpu-lite.sh models-bpeall 1000-bpeall-20-context Indonesian
sh train-gpu-lite.sh models-bpeall 3000-bpeall-20-context Englsih
sh train-gpu-lite.sh models-bpeall 3000-bpeall-20-context Turkish
sh train-gpu-lite.sh models-bpeall 3000-bpeall-20-context Spanish
sh train-gpu-lite.sh models-bpeall 3000-bpeall-20-context Arabic
sh train-gpu-lite.sh models-bpeall 3000-bpeall-20-context Indonesian
sh train-gpu-lite.sh models-bpeall 5000-bpeall-20-context Englsih
sh train-gpu-lite.sh models-bpeall 5000-bpeall-20-context Turkish
sh train-gpu-lite.sh models-bpeall 5000-bpeall-20-context Spanish
sh train-gpu-lite.sh models-bpeall 5000-bpeall-20-context Arabic
sh train-gpu-lite.sh models-bpeall 5000-bpeall-20-context Indonesian
|
72228f38fbba220a5fac557e1b1735813a6caa62
|
[
"Python",
"Shell"
] | 8 |
Python
|
chuyi1787/diss-final
|
e95ffa2f352831acac2fac55a6ce52b5e685833f
|
b392ef411d5cbdcb08090415ec3659f5261addfc
|
refs/heads/master
|
<file_sep>package com.hbase.conn;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.HTablePool;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
import com.hbase.dao.HBaseDao;
import com.hbase.dao.HBaseDaoImpl;
public class TestConn {
public static void main(String[] args) throws ClassNotFoundException, FileNotFoundException, SQLException, IOException, ParseException {
System.out.println("开始TestConn");
//
// HBaseDao dao = new HBaseDaoImpl();
// String[] qualifiers = {"career","Num1","Num2","titles","role"};
// String[] values ={"ball","3","33","2 times","student"};
// dao.insertRow("users", "Curry", "info", qualifiers, values);
//
// List<String> list = new HBaseDaoImpl().select("pcmd", "455115331818171015", "info", "mainPhone");
// System.out.println("role="+list);
//
// List<String> list1 = new HBaseDaoImpl().select("pcmd", "455115331818171015", "info", "S_lon");
// System.out.println("role="+list1);
//
// dao.close();
im();
TestConn.ouput();
}
/**
* @param args
* @throws IOException
* @throws SQLException
* @throws FileNotFoundException
* @throws ClassNotFoundException
* @throws ParseException
*/
public static void im( )
throws ClassNotFoundException, FileNotFoundException, SQLException, IOException, ParseException {
System.out.println("开始TestConn");
HBaseDao dao = new HBaseDaoImpl();
String[] qualifiers = {"career","Num","titles","role"};
String[] values ={"ball","4","1 times","boy"};
dao.insertRow("users", "Curry", "info", qualifiers, values);
dao.close();
// HBaseConf hBaseConn = new HBaseConf();
// Configuration myConf = hBaseConn.getConfiguration();
//
//
// HTablePool pool = new HTablePool();
//// HTableInterface userTable = new HTable(myConf, "users");
// HTableInterface userTable = pool.getTable("users");
//
// TableName tableName = userTable.getName();
// System.out.println("tableName="+tableName);
//
// List<Put> list = new ArrayList<>();
// //add data
// Put p = new Put(Bytes.toBytes("Bing"));//row key, primary
// byte[] family = Bytes.toBytes("info");
// p.add(family, Bytes.toBytes("gender"), Bytes.toBytes("0male"));//column family,column,value
// p.add(family, Bytes.toBytes("password"), Bytes.toBytes("0123abc"));//column family,column,value
// p.add(family, Bytes.toBytes("email"), Bytes.toBytes("<EMAIL>"));//column family,column,value
// list.add(p);
//
// Put p2 = new Put(Bytes.toBytes("Bing"));//row key, primary
// p2.add(family, Bytes.toBytes("gender"), Bytes.toBytes("1femal"));//column family,column,value
// p2.add(family, Bytes.toBytes("password"), Bytes.toBytes("1456789"));//column family,column,value
// p2.add(family, Bytes.toBytes("email"), Bytes.toBytes("<EMAIL>"));//column family,column,value
// list.add(p2);
//
// userTable.put(list);
//
//
//
// userTable.close();
System.out.println(" HBase TestConn结束");
}
public static void ouput()
throws ClassNotFoundException, FileNotFoundException, SQLException, IOException, ParseException {
System.out.println("开始TestConn ouput");
HBaseConf hBaseConf = new HBaseConf();
Configuration myConf = hBaseConf.getConfiguration();
HTableInterface userTable = new HTable(myConf, "users");
List<Get> list = new ArrayList<>();
byte[] family = Bytes.toBytes("info");
Get g = new Get(Bytes.toBytes("JayLi"));//row key, primary
g.addFamily(family);
g.setMaxVersions();
list.add(g);
Get g2 = new Get(Bytes.toBytes("Kobe"));//row key, primary
g2.addFamily(family);
g2.setMaxVersions();
list.add(g2);
Get g3 = new Get(Bytes.toBytes("Curry"));//row key, primary
g3.addFamily(family);
g3.setMaxVersions();
list.add(g3);
Result[] result = userTable.get(list);
for (Result rs : result) {
// List<Cell> list2 = rs.listCells();//get data and name
Cell[] list2 = rs.rawCells();//get data and name
for (Cell cell : list2) {
String family1 = Bytes.toString(CellUtil.cloneFamily(cell));
String row = Bytes.toString(CellUtil.cloneRow(cell));
String name = Bytes.toString(CellUtil.cloneQualifier(cell));
String value = Bytes.toString(CellUtil.cloneValue(cell));
System.out.println("family="+family1+",row="+row+":"+name+"="+value);
}
}
userTable.close();
System.out.println(" HBase TestConn结束");
}
}
<file_sep>define([
'underscore',
'backbone',
'marionette',
"tpl!views/partials/common/common_t/nodatetime.tpl",
], function(_, Backbone, Marionette, nodatetimeTpl) {
"use strict";
var NoDateTimeView = Marionette.ItemView.extend({
template: nodatetimeTpl,
initialize: function() {
console.log('init nodatetime view');
},
});
return NoDateTimeView;
});<file_sep>//var url_submit='http://120.26.59.151/PreDealSys2/complaintInfo';
//var url_result="http://172.16.58.3/yee/result.html";
//var url_code="http://172.16.58.3/app/code";
var url_submit='/PreDealSys2/complaintInfo';
var url_result="/PreDealSys2/webAPP/result.html";
var url_code="/PreDealSys2/code";
window.onload=function(){
var userData={};
userData.tel="";
userData.datetime=null;
userData.date=null;
userData.time=null;
userData.type=null;
userData.event=null;
userData.lat=null;
userData.lon=null;
userData.msg="";
userData.code=null;
userData.gpsLon=null;
userData.gpsLat=null;
userData.area="";
userData.loc="";
var types=[{val:1,txt:"4G"},{val:2,txt:"3G"},{val:3,txt:"2G"}];
var events=[{val:1001,txt:"无信号"},{val:1002,txt:"掉话"},{val:1003,txt:"话音断续不清晰"},{val:1004,txt:"数据连接异常"},{val:1005,txt:"其他"}];
var inputTel=document.getElementById("tel");
var inputDate=document.getElementById("date");
var inputTime=document.getElementById("time");
var inputType=document.getElementById("types");
var inputEvent=document.getElementById("events");
var inputLoc=document.getElementById("loc-text");
var btnLoc=document.getElementById("loc-btn");
var inputMsg=document.getElementById("msg");
var inputCode=document.getElementById("code");
var imgCode=document.getElementById("img-code");
var btnSubmit=document.getElementById("submit");
var loadingPage=document.getElementById("loading-page");
var mapPage=document.getElementById("map-page");
var mapContainer=document.getElementById("mapContainer");
var mapBtn=document.getElementById("set-loc");
var mapHiddenBtn=document.getElementById("hide-map");
var map=null;
var userPoint=null;
var marker=null;
var tempLng=null;
var tempLat=null;
inputType.bind=function(arr){
var content="";
var item;
var i;
for (i=0;i<arr.length;i++) {
item="<option value='"+arr[i].val+"'>"+arr[i].txt+"</option>";
content+=item;
}
this.innerHTML=content;
};
inputEvent.bind=function(arr){
var content="";
var item;
var i;
for (i=0;i<arr.length;i++) {
item="<option value='"+arr[i].val+"'>"+arr[i].txt+"</option>";
content+=item;
}
this.innerHTML=content;
};
initData();
inputType.bind(types);
inputEvent.bind(events);
//进入页面后先刷新一次验证码,以用于将当前验证码存入后台session中
imgCode.src="/PreDealSys2/code?"+Math.random();
// imgCode.addEventListener("click",function(e){
// function createCode(){
// imgCode.src="/PreDealSys2/code?"+Math.random();
// console.log(imgCode.src);
// }
// },false)
inputTel.addEventListener("input",function(e){
userData.tel=this.value;
},false);
inputDate.addEventListener("input",function(e){
userData.datetime=this.value;
var datetime=userData.datetime.split("T");
var yMd=datetime[0].split("-");
var Hm=datetime[1].split(":");
userData.datetimeObj=new Date(parseInt(yMd[0]),parseInt(yMd[1])-1,parseInt(yMd[2]),parseInt(Hm[0]),parseInt(Hm[1]));
if(Date.parse(userData.datetimeObj)>Date.parse(userData.nowObj)){
alert("不能选取超前日期");
userData.datetime=inputDate.value=userData.nowObj.format("yyyy-MM-ddTHH:mm");
}
},false);
// inputTime.addEventListener("input",function(e){
// userData.time=this.value;
// },false);
inputMsg.addEventListener("input",function(e){
userData.msg=this.value;
},false);
inputCode.addEventListener("input",function(e){
userData.code=this.value;
},false);
inputType.addEventListener("change",function(e){
userData.type=this.value;
},false);
inputEvent.addEventListener("change",function(e){
userData.event=this.value;
},false);
btnSubmit.addEventListener("click",function(e){
if(userData.tel.length!=11 || userData.tel.charAt(0) != 1){
alert("请输入正确的手机号码");
return;
}
if(userData.lon==null || userData.lat ==null){
alert("请核对投诉地点");
return;
}
if(!(108.29209227 <= userData.lon && userData.lon <= 116.37915993)|| !(28.92430194 <= userData.lat && userData.lat <= 33.43608273)){
alert("投诉仅限湖北省内,请核对投诉地点");
return;
}
if(userData.code == null){
alert("请输入验证码");
return;
}
/*
sssssssssssssssssssssssss
*/
loadingPage.style.display="block";
//后台持续运行却不反馈时,页面会持续在加载中的状态,这里需要对这一状态做一个限时,时限暂定为30秒
var setTime = setTimeout(function(){
alert('数据库连接超时!');
loadingPage.style.display="none";
location.reload();
},30000)
userData.date=userData.datetime.split("T")[0];
userData.time=userData.datetime.split("T")[1];
//alert(JSON.stringify(userData));
var xhr=new XMLHttpRequest();
xhr.onload=function(e){
if(xhr.status>=200 && xhr.status<300 || xhr.status==304){
var data=JSON.parse(xhr.responseText);
if(data.result==0){
window.location.replace(url_result+"?complaint_id="+data.complaint_id);
}else{
loadingPage.style.display="none";
alert(data.text);
clearTimeout(setTime);
}
}else{
loadingPage.style.display="none";
alert('error:'+xhr.status);
clearTimeout(setTime);
}
};
xhr.open("post",url_submit,true);
xhr.send(JSON.stringify(userData));
},false);
btnLoc.addEventListener("click",function(e){
mapPage.style.display="block";
initLocation();
},false);
mapHiddenBtn.addEventListener("click",function(e){
mapPage.style.display="none";
},false);
mapBtn.addEventListener("click",function(e){
mapPage.style.display="none";
userData.lat=tempLat;
userData.lon=tempLng;
//转换百度经纬度变为gps经纬度
function translateCallback(data){
if(data.status === 0) {
var BPoint = [];
BPoint[0] = Point;
BPoint[1] = data.points[0];
var GPSPoint = {};
GPSPoint.lng = 2*BPoint[0].lng - BPoint[1].lng;
GPSPoint.lat = 2*BPoint[0].lat - BPoint[1].lat;
userData.gpsLon=GPSPoint.lng.toFixed(6);
userData.gpsLat=GPSPoint.lat.toFixed(6);
}
}
var Point = new BMap.Point(tempLng,tempLat);
var convertor = new BMap.Convertor();
var pointArr = [];
pointArr.push(Point);
convertor.translate(pointArr, 1, 5, translateCallback);
// var alterUserPoint = new BMap.Point(userData.lon-0.009,userData.lat+0.012);
// map.centerAndZoom(alterUserPoint,15);
var tempPoint=new BMap.Point(userData.lon,userData.lat);
var geoc = new BMap.Geocoder();
geoc.getLocation(tempPoint, function(rs){
userData.loc=rs.address;
userData.area=rs.addressComponents.city+" "+rs.addressComponents.district;
inputLoc.value=rs.address;
});
},false);
initMap();
function initLocation(){
if(userPoint==null){
/*****************************/
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(pos){
tempLng=pos.coords.longitude;
tempLat=pos.coords.latitude;
userPoint=new BMap.Point(tempLng,tempLat);
map.centerAndZoom(userPoint,15);
marker.setPosition(userPoint);
},function(err){//浏览器无法获取地点,通过IP进行定位
console.log(err);
var myCity=new BMap.LocalCity();
myCity.get(function(rs){
tempLng=rs.center.lng;
tempLat=rs.center.lat;
userPoint=new BMap.Point(rs.center.lng,rs.center.lat);
map.centerAndZoom(userPoint, 15);
marker.setPosition(userPoint);
});
},{
timeout:2500,
maximunAge:60000
});
}
/*****************************/
userPoint=new BMap.Point(114.219986,30.599018);
marker=new BMap.Marker(userPoint);
map.addOverlay(marker);
map.centerAndZoom(userPoint,14);
}
}
function initMap(){
if(map==null){
map=new BMap.Map("mapContainer");
/**************************************添加联想搜索*******************************************/
var ac=new BMap.Autocomplete({
"input":"loc-text",
"location":map
});
var myValue;
ac.addEventListener("onconfirm",function(e){
console.log(e);
var _value = e.item.value;
myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
/*************************************/
userData.loc=myValue;
userData.area=_value.city+" "+_value.district;
/*************************************/
setPlace();
});
function setPlace(){
function myFun(){
userPoint = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
console.log(userPoint);
/***********************************************/
userData.lat=tempLat=userPoint.lat;
userData.lon=tempLng=userPoint.lng;
//用于百度与gps经纬度转换的函数
function translateCallback(data){
if(data.status === 0) {
var BPoint = [];
BPoint[0] = Point;
BPoint[1] = data.points[0];
var GPSPoint = {};
GPSPoint.lng = 2*BPoint[0].lng - BPoint[1].lng;
GPSPoint.lat = 2*BPoint[0].lat - BPoint[1].lat;
userData.gpsLon=GPSPoint.lng.toFixed(6);
userData.gpsLat=GPSPoint.lat.toFixed(6);
}
}
var Point = new BMap.Point(userPoint.lng,userPoint.lat);
var convertor = new BMap.Convertor();
var pointArr = [];
pointArr.push(Point);
convertor.translate(pointArr, 1, 5, translateCallback);
/***********************************************/
// map.centerAndZoom(userPoint, 16);
var alterUserPoint = new BMap.Point(userData.lon-0.009,userData.lat+0.012);
if(!marker){
marker=new BMap.Marker(userPoint);//在这里已经定义了marker为BMap形式的点了
map.addOverlay(marker);
map.centerAndZoom(userPoint,16);
var centerPoint = map.getCenter();
console.log(centerPoint);
}else{
marker.setPosition(userPoint); //添加标注
map.centerAndZoom(userPoint, 16);
var centerPoint = map.getCenter();
console.log(centerPoint);
}
}
var local = new BMap.LocalSearch(map, { //智能搜索
onSearchComplete: myFun
});
local.search(myValue);
}
/***********************************添加定位控件*************************************/
var geolocationControl = new BMap.GeolocationControl({offset:new BMap.Size(10,70)});
geolocationControl.addEventListener("locationSuccess",function(e){
userPoint=e.point;
tempLng=e.point.lng;
tempLat=e.point.lat;
marker.setPosition(userPoint);
});
geolocationControl.addEventListener("locationError",function(e){
alert(e.message);
});
map.addControl(geolocationControl);
/*********************************添加点击处理*************************************************/
map.addEventListener("click",function(e){
userPoint=e.point;
tempLng=e.point.lng;
tempLat=e.point.lat;
marker.setPosition(new BMap.Point(tempLng,tempLat));
});
}
}
function initData(){
var now=new Date();
userData.nowObj=now;
userData.datetime=inputDate.value=now.format("yyyy-MM-ddTHH:mm");
userData.type=types[0].val;
userData.event=events[0].val;
}
};<file_sep>package com.homer.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import com.homer.bean.BaseResp;
import com.homer.dao.DBManager;
/*
*
* */
public class SendMsgServlet extends BaseServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
super.doPost(req, resp);
PrintWriter pw=resp.getWriter();
BaseResp bean=null;
String result=null;
JSONObject params=JSONObject.fromObject(readJson(req));
try {
result=addMsg(params);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
bean=new BaseResp(-1,e.getMessage());
result=JSONObject.fromObject(bean).toString();
}finally{
pw.write(result);
pw.flush();
pw.close();
try {
DBManager.getInstance().disConnect();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private String addMsg(JSONObject params) throws ClassNotFoundException, SQLException{
String sqlQuerySeq="SELECT work_order_seq FROM complaint_records WHERE complaint_id="+params.getString("complaint_id");
ResultSet rs = DBManager.getInstance().executeQuery(sqlQuerySeq);
rs.next();
int workOrderSeq=rs.getInt("work_order_seq");
Date now=new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String sql="INSERT INTO message_records(complaint_id,work_order_seq,message_time,message_content,message_type,message_leaver) VALUES("+
params.getString("complaint_id")+","+workOrderSeq+",'"+sdf.format(now)+"','"+params.getString("msg")+"',1,'Ͷ���û�"+params.getString("tel")+"')";
DBManager.getInstance().executeUpdate(sql);
return JSONObject.fromObject(new BaseResp(0, "ok")).toString();
}
}
<file_sep>define(['backbone',
'models/cell_performance_statistic_info',
],
function(Backbone, CellPerformanceStatisticInfo) {
var CellPerformanceStatisticInfoCollection = Backbone.Collection.extend({
model: CellPerformanceStatisticInfo,
initialize: function(options){
this.urlRoot = 'statistic_by_cell_performance.html';
this.url = this.urlRoot;
}
});
return CellPerformanceStatisticInfoCollection;
});<file_sep>define([
'underscore',
'backbone',
'marionette',
"tpl!views/partials/common/common_t/stationerrorStatistic.tpl",
], function(_, Backbone, Marionette, stationerrorStatisticTpl) {
"use strict";
var StationErrorStatisticView = Marionette.ItemView.extend({
template: stationerrorStatisticTpl,
initialize: function() {
console.log('init stationerrorStatistic view');
},
});
return StationErrorStatisticView;
});<file_sep>define(['backbone',
'models/phone_statistic_info',
],
function(Backbone, PhoneStatisticInfo) {
var PhoneStatisticInfoCollection = Backbone.Collection.extend({
model: PhoneStatisticInfo,
initialize: function(options){
this.urlRoot = 'statistic_by_phonenumber.html';
this.url = this.urlRoot;
}
});
return PhoneStatisticInfoCollection;
});<file_sep>driver=com.mysql.jdbc.Driver
url=jdbc:mysql://172.16.31.10:3306/appdata?useUnicode=true&characterEncoding=utf8
user=root
pass=<PASSWORD>
<file_sep>define([
'backbone'
], function(Backbone) {
"use strict";
var StationerrorCount = Backbone.Model.extend({
});
return StationerrorCount;
});<file_sep>package com.sys.util;
public class MyFilePath {
//实验室内部环境路径
public final static String mysql_conectionProperties = "H:\\FEFJay\\myEclipseWorkSpace\\PreDealSys\\src\\mysql\\mysql_conection.properties";
public final static String TCPropertiesPath = "H:\\FEFJay\\myEclipseWorkSpace\\PreDealSys\\src\\com\\sys\\util\\TC.properties";
public final static String HBasePropertiesPath = "H:\\FEFJay\\myEclipseWorkSpace\\PreDealSys\\src\\my_hbase\\hbase_Properties.txt";
//传输局服务器上的路径
// public final static String mysql_conectionProperties = "/root/workspace/TS_test20151103/src/mysql/mysql_conection.properties";
// public final static String TCPropertiesPath = "/root/workspace/TS_test20151103/src/TC.properties";
// public final static String HBasePropertiesPath = "/root/workspace/TS_test20151103/src/my_hbase/hbase_Properties.txt";
}
<file_sep>define([
'underscore',
'backbone',
'marionette',
"tpl!views/partials/common/common_t/phoneStatistic.tpl",
], function(_, Backbone, Marionette, phoneStatisticTpl) {
"use strict";
var PhoneStatisticView = Marionette.ItemView.extend({
template: phoneStatisticTpl,
initialize: function() {
console.log('init phoneStatistic view');
},
});
return PhoneStatisticView;
});<file_sep>var url_getList='/PreDealSys2/queryComplaint';
var url_info='/PreDealSys2/webAPP/info.html';
var url_navigate="/PreDealSys2/webAPP/navigate.html";
var url_register="/PreDealSys2/webAPP/register.html";
var tel=window.location.search.split('=')[1].split('&')[0];
var validateCode=window.location.search.split('=')[2];
function createArticle(article){
var node = document.createElement('li');
node.innerHTML='<div class="item">时间:'+
article.datetime+'</div><div class="item">类型:'+
article.typeWord+'</div><div class="item">地区:'+
article.loc+'</div><div class="item">状态:'+
article.stateWord+'</div><div class="detail item">详细信息 ></div>';
node.id=article.id;
return node;
}
function createAriticles(articleArray){
var content='';
var article='';
for(var i=0;i<articleArray.length;i++){
article="<li id='"+articleArray[i].id+"'><div class='item'>时间:"+
articleArray[i].datetime+"</div><div class='item'>类型:"+
articleArray[i].typeWord+"</div><div class='item'>地区:"+
articleArray[i].loc+"</div><div class='item'>状态:"+
articleArray[i].stateWord+"</div><div class='detail item'>详细信息 ></div></li>";
content+=article;
}
return content;
}
window.onload=function(){
var listview=document.getElementById("main");
var isActive=true;
var index=0;
var number=10;
loadFirst();
listview.addEventListener("scroll",function(e){
if(this.scrollTop<(this.scrollHeight-this.offsetHeight-10) && isActive){
isActive=false;
loadMore();
}
},false);
listview.addEventListener("click",function(e){;
if(e.target.parentNode.id!="" && e.target.parentNode.id!="main"){
window.location.href=url_info+"?tel="+tel+"&complaint_id="+e.target.parentNode.id;
}
},false);
document.getElementById("btn-back").addEventListener("click",function(e){
window.location.href=url_navigate;
},false);
function loadMore(){
var xhr_loadMore=new XMLHttpRequest();
xhr_loadMore.onreadystatechange=function(){
if(xhr_loadMore.readyState==4){
if((xhr_loadMore.status>=200&&xhr_loadMore.status<300) || xhr_loadMore.status==304){
var data=JSON.parse(xhr_loadMore.responseText);
if(data.result>=0){
for(var i=0;i<data.data.length;i++){
listview.appendChild(createArticle(data.data[i]));
}
isActive=true;
index+=data.data.length;
}else{
alert(data.text);
}
}
}
}
xhr_loadMore.open("get",url_getList+"?tel="+tel+"&index="+index+"&number="+number+"&code="+validateCode,true);
xhr_loadMore.send(null);
}
function loadFirst(){
var xhr_load=new XMLHttpRequest();
xhr_load.onreadystatechange=function(){
if(xhr_load.readyState==4){
if((xhr_load.status>=200&&xhr_load.status<300) || xhr_load.status==304){
var data=JSON.parse(xhr_load.responseText);
if(data.result>=0){
for(var i=0;i<data.data.length;i++){
listview.innerHTML=createAriticles(data.data);
}
isActive=true;
index+=data.data.length;
}else{
alert(data.text);
window.location.replace(url_register);
}
}
}
}
xhr_load.open("get",url_getList+"?tel="+tel+"&index="+index+"&number="+number+"&code="+validateCode,true);
xhr_load.send(null);
}
};<file_sep>package com.hbase.cityReached;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;
public class a {
/**
* @param args
*/
public static void main(String[] args) {
LinkedHashMap<String, Integer> cityCountMap = new LinkedHashMap<String, Integer>();
cityCountMap.put("鄂州", 1);
cityCountMap.put("恩施", 2);
cityCountMap.put("黄冈", 3);
cityCountMap.put("黄石", 4);
cityCountMap.put("江汉", 5);
cityCountMap.put("荆门", 16);
cityCountMap.put("荆州", 7);
cityCountMap.put("十堰", 8);
cityCountMap.put("随州", 9);
cityCountMap.put("武汉", 10);
cityCountMap.put("咸宁", 11);
cityCountMap.put("襄樊", 12);
cityCountMap.put("孝感", 13);
cityCountMap.put("宜昌", 14);
String city = "荆门";
if (cityCountMap.containsKey(city)) {
int count = cityCountMap.get(city);
count ++;
cityCountMap.put(city, count);
}
Set<String> keySet = cityCountMap.keySet();
Iterator<String> it = keySet.iterator();
while (it.hasNext()) {
String string = (String) it.next();
System.out.println(string+"="+cityCountMap.get(string));
}
}
}
<file_sep>package com.yl.util;
/**
* 工具类,判断参数是否为空
* @author yl
*
*/
public class ObjectsIsEmpty{
/**
* 判断传入参数是否为空,若为空则返回true,不为空则返回false
* @return
*/
public static boolean isEmpty(Object ...args) {
//循环判断传入参数是否为空,若为空直接返回true
//若前台传入数据有该字段但是没有赋值则为"";若前台传入数据没有该字段则为null
for (int i = 0; i < args.length; i++) {
if (null == args[i] || "".equals(args[i])) {
return true;
}
}
return false;
}
}<file_sep>package com.pcmd.imp;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
/*
* 数据库的设计:
* 1.rowkey的设计
* 首先对电话号码对9取余,得到的标志位放在首位,这个标志位的作用是作为散列用的
* 然后用11位的最大数99999999999减去电话号码,这么做的作用是使得位数统一,同时也具有散列电话号码的作用!
* 其次将得到的结果进行翻转。
* 最后加上150530这种格式的日期,也就是说整个rowkey字段长度为18位!
*
* 2.family设计
* 坚持只用一个family的原则不动摇
* 同时降低字段的耦合程度,这么做的好处是可以在后期很容易的添加新的字段
* 每个号码每天保存的版本数量为1000个话单。
* 时间戳是使用的通话开始时刻的时间戳
*
*
* 3.程序设计思路
* 按照甲方要求,对170个字段后面的数据进行了重新计算,分别计算了开始时刻和结束时刻的话单信息
* 我们需要这个程序在每个小时进行一次采集,采集的时候要求HDFS不在写入的状态,同时使用脚本传入日期时间参数,程序根据日期时间参数进行导入操作
* 例如15042502.gz,我们传入15042502的参数,那么就对所有文件夹下的这个文件进行提取操作
*/
public class PCMDHBaseHour {
public static List<Path> delete_path = new ArrayList<Path>();
public static final String HDFS_PATH = "hdfs://master:8020/pcmd";//hdfs://whcsj01:9000/
/*内部类
* 继承Hadoop的mapreduce程序中的Mapper
* */
static class LoadPCMD extends Mapper<LongWritable, Text, ImmutableBytesWritable, Put> {
private static HashMap<String,String> hm = new HashMap<String,String>();
static byte[] family = Bytes.toBytes("info");//http://www.importnew.com/3912.html
/**
* 重载初始化方法
* 打开全局文件,保存基站信息到hashmap中。等到进行 定位 的时候调用基站信息。
* 该方式是调用基站信息文件。文件放在HDFS中。
* @Override
* */
protected void setup(Context context) throws IOException {
Path[] cacheFiles=DistributedCache.getLocalCacheFiles(context.getConfiguration()); //获取保存基站信息文件的目录
if(cacheFiles!=null&&cacheFiles.length>0){//如果目录不为空,则继续执行
String line;
String tokens[];
BufferedReader br = new BufferedReader(new FileReader(cacheFiles[0].toString()));//读取目录下的文件,该目录下只有基站的信息一个文件
try{
while ((line = br.readLine())!=null)//遍历文件,一行行来读取数据
{
tokens=line.split(";");//每一行数据都是以逗号作为分隔符,这是原始文件里面采用的分割方式
if(tokens.length==4){
hm.put(tokens[0], tokens[1]+";"+tokens[2]+";"+tokens[3]);//第一个元素话单的ID作为键,后面三个是ecp、bts、cell值
}
}
}finally {
br.close();
}
}
}
/*
* 重载map方法
*
* 我们的HBase保存话单数据不用进行reduce,只进行map操作。因为reduce的目的就是为了把相同key的数据重新整合,然后再存储,以减少存储空间等。
*
* @see org.apache.hadoop.mapreduce.Mapper#map(KEYIN, VALUEIN, org.apache.hadoop.mapreduce.Mapper.Context)
* @Override
*/
public void map(LongWritable offset, Text value, Context context) throws IOException {
try {
String line = value.toString(); //value就是一条完整的话单记录,包含317个字段
String a[] = line.split(";");//一条完整的话单记录,包含317个字段,分为数组。原始文件中就是以逗号为分隔符的字符串。
if(a.length==317&&a[6].length()<=11){//话单的第7个字段(数组是0开始,是数组的下标6)就是电话号码
//构造一个rowkey。
//要考虑不同的rowkey是存储在不同的regionServer里面,也就是不同的rowkey保存在不同的机器上。
//如果所有的rowkey都一样,那数据都保存在一个机器里,那么就会导致负载不均衡,爆仓。所以要使得rowkey尽可能的分散,尽可能地不同。
long phone = Long.parseLong(a[6]);//取出电话号码
long flag = phone%9;//对电话号码取余数,第一位始终为0-8的数。
//电话号码进行反转,还要保证电话号码部分为11位!不是11位要进行补齐,超过11位到要舍去!补齐的办法使用99999999999 减去电话号码部分
long key_phone = 99999999999L - phone;//这样做到目的是控制长度为11位!
StringBuffer sb = new StringBuffer(key_phone+"");//这个SB为电话号码
String fan_keyphone = sb.reverse().toString();//key_phone反转。所有的电话号码都是1开头,如果不反转,那么得到的都是8开头的key,还是达不到散列目的。
SimpleDateFormat df =new SimpleDateFormat("yy");
String year = df.format(new Date());//提取出年份
String row =flag+ fan_keyphone+year+a[69];//后面接上日期。所以一个rowkey= 电话号码取余数的结果(0-8+修正后反转的电话号码 +年月日(如“160605”)。
//每个电话号码以天为单位构成一个rowkey。也就是说,一个一样的电话号码,在一天内的话单,都会生成一个一样的rowkey。
//以下是话单的基本信息
String ID=a[1];
String starttime=a[2];
String calDurtime=a[3];
String mainPhone=a[6];
String startPhone=a[21];
String MessageL=a[50];
String endPhone=a[51];
String date=a[69];
String callStartTime=a[83];
String comePhonetime=a[101];
String start_cell = a[168]+","+a[169]+","+a[179];//其中第一位为基站编号bts,第二位为基站扇区cell,第三位为基站ECP
String start_ecio = a[173];
String start_dis = a[177];
String end_cell = a[243]+","+a[243+1]+","+a[254];//结束的时候的主要基站
String end_ecio = a[248];
String end_dis = a[252];
String event = a[30]+","+a[28]+","+a[48]+","+a[37]+","+a[38];//这个字段记录着当前话单的状态信息
String load_time = System.currentTimeMillis()/1000+"";//这个字段记录该条记录插入的时间
//现在需要对通话建立时的基站和通话结束时的基站进行统计和计算
//思路是这样的,我们得到初始基站和结束基站的一个二维数组,交给函数dingwei去处理,这个函数返回一个double类型的数组,第一个元素表示使用的几点定位,后面2个元素为经纬度,平均ecio值和平均距离
//开始的时候的基站数组和结束的时候的基站数组cellS cellE
String cellS[][]=new String[6][3];
String cellE[][]=new String[6][3];
//对cellS赋值
// +1 +8 +4 +7 +2
cellS[0][0]=a[182]+","+a[182+1]+","+a[182+8];
cellS[0][1]=a[182+7];
cellS[0][2]=a[182+2];
cellS[1][0]=a[194]+","+a[194+1]+","+a[194+8];
cellS[1][1]=a[194+7];
cellS[1][2]=a[194+2];
cellS[2][0]=a[206]+","+a[206+1]+","+a[206+8];
cellS[2][1]=a[206+7];
cellS[2][2]=a[206+2];
cellS[3][0]=a[218]+","+a[218+1]+","+a[218+8];
cellS[3][1]=a[218+7];
cellS[3][2]=a[218+2];
cellS[4][0]=a[230]+","+a[230+1]+","+a[230+8];
cellS[4][1]=a[230+7];
cellS[4][2]=a[230+2];
////////////////////
//添加主基站信息
cellS[5][0]=a[168]+","+a[169]+","+a[179];
cellS[5][1]=a[177];
cellS[5][2]=a[173];
////////////////////
//对cellE进行赋值
cellE[0][0]=a[257]+","+a[257+1]+","+a[257+8];
cellE[0][1]=a[257+7];
cellE[0][2]=a[257+2];
cellE[1][0]=a[269]+","+a[269+1]+","+a[269+8];
cellE[1][1]=a[269+7];
cellE[1][2]=a[269+2];
cellE[2][0]=a[281]+","+a[281+1]+","+a[281+8];
cellE[2][1]=a[281+7];
cellE[2][2]=a[281+2];
cellE[3][0]=a[293]+","+a[293+1]+","+a[293+8];
cellE[3][1]=a[293+7];
cellE[3][2]=a[293+2];
cellE[4][0]=a[305]+","+a[305+1]+","+a[305+8];
cellE[4][1]=a[305+7];
cellE[4][2]=a[305+2];
//这个是结束到时候的主要基站!!
cellE[5][0]=a[243]+","+a[243+1]+","+a[254];
cellE[5][1]=a[252];
cellE[5][2]=a[248];
//现在分别将cellS cellE这2个二维数组传给函数dingwei,返回一个double类型的数组
double[] jingweiS = dingwei(cellS);
double[] jingweiE = dingwei(cellE);
byte[] bRowKey = Bytes.toBytes(row);//对rowkey转化为字节数组
ImmutableBytesWritable rowKey = new ImmutableBytesWritable(bRowKey);//将rowkey转化为ImmutableBytesWritable类型数据
SimpleDateFormat sdf = new SimpleDateFormat("yy/MM/dd ss");
//获取话单创建的年月日 时间戳的秒数目
String dataS=year+"/"+a[69].substring(0,a[69].length()-2)+"/"+a[69].substring(a[69].length()-2, a[69].length())+" "+a[2].substring(0, a[2].length()-1);
long timestamp = 0;
try {
Date date1 = sdf.parse(dataS);
timestamp = date1.getTime();//转为时间戳毫秒
} catch (ParseException e) {
e.printStackTrace();
}
if(timestamp<0)
{
timestamp =1;
}
Put p = new Put(bRowKey);//创建一个具有特定行键的put操作对象,可以往HBase数据库插入一行数据。HBase中一行就是一个put操作。put对象中的参数要求都是字节数组,所以需要转化。
//第一个参数family是列簇名,第二个参数是列名称,第三个参数是值
p.add(family, Bytes.toBytes("ID"),timestamp, Bytes.toBytes(ID));
p.add(family, Bytes.toBytes("starttime"),timestamp, Bytes.toBytes(starttime));
p.add(family, Bytes.toBytes("calDurtime"),timestamp, Bytes.toBytes(calDurtime));
p.add(family, Bytes.toBytes("mainPhone"),timestamp, Bytes.toBytes(mainPhone));
p.add(family, Bytes.toBytes("startPhone"),timestamp, Bytes.toBytes(startPhone));
p.add(family, Bytes.toBytes("MessageL"),timestamp, Bytes.toBytes(MessageL));
p.add(family, Bytes.toBytes("endPhone"),timestamp, Bytes.toBytes(endPhone));
p.add(family, Bytes.toBytes("date"),timestamp, Bytes.toBytes(date));
p.add(family, Bytes.toBytes("callStartTime"),timestamp, Bytes.toBytes(callStartTime));
p.add(family, Bytes.toBytes("comePhonetime"),timestamp, Bytes.toBytes(comePhonetime));
p.add(family, Bytes.toBytes("event"),timestamp, Bytes.toBytes(event));
p.add(family, Bytes.toBytes("start_cell"),timestamp, Bytes.toBytes(start_cell));
p.add(family, Bytes.toBytes("end_cell"),timestamp, Bytes.toBytes(end_cell));
if(start_ecio.length()!=0) {
p.add(family, Bytes.toBytes("start_ecio"),timestamp, Bytes.toBytes(""+Double.parseDouble(start_ecio)/(-2)));
}else {
p.add(family, Bytes.toBytes("start_ecio"),timestamp, Bytes.toBytes("0"));
}
if(start_dis.length()!=0)
{
p.add(family, Bytes.toBytes("start_dis"),timestamp, Bytes.toBytes(""+Double.parseDouble(start_dis)*0.6*15.4));
}else
{
p.add(family, Bytes.toBytes("start_dis"),timestamp, Bytes.toBytes("0"));
}
if(end_ecio.length()!=0)
{
p.add(family, Bytes.toBytes("end_ecio"),timestamp, Bytes.toBytes(""+Double.parseDouble(end_ecio)/(-2)));
}else
{
p.add(family, Bytes.toBytes("end_ecio"),timestamp, Bytes.toBytes("0"));
}
if(end_dis.length()!=0)
{
p.add(family, Bytes.toBytes("end_dis"),timestamp, Bytes.toBytes(""+Double.parseDouble(end_dis)*0.6*15.4));
}else
{
p.add(family, Bytes.toBytes("end_dis"),timestamp, Bytes.toBytes("0"));
}
p.add(family, Bytes.toBytes("load_time"),timestamp, Bytes.toBytes(load_time));
p.add(family, Bytes.toBytes("time"),timestamp, Bytes.toBytes(timestamp+""));
if(jingweiS==null)
{
p.add(family, Bytes.toBytes("S_point"),timestamp, Bytes.toBytes("0"));
p.add(family, Bytes.toBytes("S_lon"),timestamp, Bytes.toBytes("0"));
p.add(family, Bytes.toBytes("S_lat"),timestamp, Bytes.toBytes("0"));
p.add(family, Bytes.toBytes("S_ecio"),timestamp, Bytes.toBytes("0"));
p.add(family, Bytes.toBytes("S_dis"),timestamp, Bytes.toBytes("0"));
}else
{
p.add(family, Bytes.toBytes("S_point"),timestamp, Bytes.toBytes(jingweiS[0]+""));
p.add(family, Bytes.toBytes("S_lon"),timestamp, Bytes.toBytes(jingweiS[1]+""));
p.add(family, Bytes.toBytes("S_lat"),timestamp, Bytes.toBytes(jingweiS[2]+""));
p.add(family, Bytes.toBytes("S_ecio"),timestamp, Bytes.toBytes(jingweiS[3]+""));
p.add(family, Bytes.toBytes("S_dis"),timestamp, Bytes.toBytes(jingweiS[4]+""));
}
if(jingweiE==null)
{
p.add(family, Bytes.toBytes("E_point"),timestamp, Bytes.toBytes("0"));
p.add(family, Bytes.toBytes("E_lon"),timestamp, Bytes.toBytes("0"));
p.add(family, Bytes.toBytes("E_lat"),timestamp, Bytes.toBytes("0"));
p.add(family, Bytes.toBytes("E_ecio"),timestamp, Bytes.toBytes("0"));
p.add(family, Bytes.toBytes("E_dis"),timestamp, Bytes.toBytes("0"));
}else
{
p.add(family, Bytes.toBytes("E_point"),timestamp, Bytes.toBytes(jingweiE[0]+""));
p.add(family, Bytes.toBytes("E_lon"),timestamp, Bytes.toBytes(jingweiE[1]+""));
p.add(family, Bytes.toBytes("E_lat"),timestamp, Bytes.toBytes(jingweiE[2]+""));
p.add(family, Bytes.toBytes("E_ecio"),timestamp, Bytes.toBytes(jingweiE[3]+""));
p.add(family, Bytes.toBytes("E_dis"),timestamp, Bytes.toBytes(jingweiE[4]+""));
}
//到这里一条话单需要存进HBase数据库的就都添加完毕,29 items
context.write(rowKey, p);//把这个put写进HBase数据库。一行一行得写入hbase数据库
}//end of if
}catch (InterruptedException e) {
e.printStackTrace();
}
}
/*
* 定位函数
* 根据传进来的接入基站和释放基站的信息,进行综合定位。返回一个数组,数组里面包含了定位的经纬度和平均距离、平均ecio等信息
* */
private static double[] dingwei(String[][] cellOut) {
// TODO Auto-generated method stub
//首先对这个二维数组进行去重!
HashMap<String,String> cellmap= new HashMap<String,String>();
for(int i=0;i<6;i++)
{
if(!cellOut[i][0].equals("0,0,0")){
cellmap.put(cellOut[i][0].split(",")[0], cellOut[i][0]+";"+cellOut[i][1]+";"+cellOut[i][2]);
}
}
//创建数组用来存放存在基站信息的cell
String[][] pcmd_cell=new String[6][4];
Iterator iter=cellmap.keySet().iterator();
int count=0;//看是几点定位!
double[] jingwei = new double[2];
double ecio = 0;
while(iter.hasNext())
{
String mapkey= (String) iter.next();
String pcmd_info=cellmap.get(mapkey);
String jizhan_info=hm.get(pcmd_info.split(";")[0]);//
if(jizhan_info!=null){
pcmd_cell[count][0]=pcmd_info.split(";")[0];
pcmd_cell[count][1]=pcmd_info.split(";")[1];
pcmd_cell[count][2]=pcmd_info.split(";")[2];
pcmd_cell[count][3]=jizhan_info;
count++;
}
}
if(count>=3)
{
double P[][] = new double[3][2];
double D[] = new double[3];
double xinhao=Double.parseDouble(pcmd_cell[0][2]);//对信号赋初始值
for(int i =0 ; i<3 ; i++)
{
//System.out.println(pcmd_cell[i][3]);
P[i][0]=Double.parseDouble(pcmd_cell[i][3].split(";")[0]);
P[i][1]=Double.parseDouble(pcmd_cell[i][3].split(";")[1]);
D[i]=Double.parseDouble(pcmd_cell[i][1])*0.6*15.4;
if(xinhao>=Double.parseDouble(pcmd_cell[i][2]))//改为大于等于到时候
{
xinhao=Double.parseDouble(pcmd_cell[i][2]);
}
}
jingwei = point3(P[0], P[1] , P[2], D[0], D[1], D[2]);
xinhao=(-xinhao)/2;
double dis =(D[0]+D[1]+D[2])/3;
double[] recall = new double[5];
recall[0] = 3;
recall[1] = jingwei[0];
recall[2] = jingwei[1];
recall[3] = xinhao;
recall[4] = dis;
return recall;
}
//此时使用2点定位
if(count==2)
{
double P[][] = new double[2][2];
double D[] = new double[2];
double A[] = new double[2];
double xinhao=Double.parseDouble(pcmd_cell[0][2]);
for (int i = 0;i<2;i++)
{
P[i][0]=Double.parseDouble(pcmd_cell[i][3].split(";")[0]);
P[i][1]=Double.parseDouble(pcmd_cell[i][3].split(";")[1]);
D[i]=Double.parseDouble(pcmd_cell[i][1])*0.6*15.4;
A[i]=Double.parseDouble(pcmd_cell[i][3].split(";")[2]);
if(xinhao>=Double.parseDouble(pcmd_cell[i][2]))
{
xinhao=Double.parseDouble(pcmd_cell[i][2]);
}
}
xinhao=(-xinhao)/2;
jingwei = point2(P[0], P[1], D[0], D[1], A[0], A[1]);
double dis =(D[0]+D[1])/2;
double[] recall = new double[5];
recall[0] = 2;
recall[1] = jingwei[0];
recall[2] = jingwei[1];
recall[3] = xinhao;
recall[4] = dis;
return recall;
}
//单点定位
if(count==1)
{
double P[]=new double[2];
P[0]=Double.parseDouble(pcmd_cell[0][3].split(";")[0]);
P[1]=Double.parseDouble(pcmd_cell[0][3].split(";")[1]);
double D=Double.parseDouble(pcmd_cell[0][1])*0.6*15.4;
double A=Double.parseDouble(pcmd_cell[0][3].split(";")[2]);
double xinhao=Double.parseDouble(pcmd_cell[0][2]);
jingwei= point1(P, A, D);
xinhao=(-xinhao)/2;
double dis =D;
double[] recall = new double[5];
recall[0] = 1;
recall[1] = jingwei[0];
recall[2] = jingwei[1];
recall[3] = xinhao;
recall[4] = dis;
return recall;
}
return null;
}
/**
* 三点定位函数
* */
public static double[] point3(double P1[], double P2[], double P3[], double D1, double D2, double D3)
{
//最终结果存在jingwei中
double jingwei[] = new double[2];
double p1[] = P1;
double p2[] = P2;
double p3[] = P3;
double d1 = D1;
double d2 = D2;
double d3 = D3;
//以p1为原点,则p2为
double n1[]={0,0};
double n2[]={(p2[0]-p1[0])*111500*0.8605,(p2[1]-p1[1])*111500};//相对坐标
double n3[]={(p3[0]-p1[0])*111500*0.8605,(p3[1]-p1[1])*111500};
//判断三点定位是属于哪种情况
//基站p1 和p2的距离
double jizhan12=Math.sqrt((n2[0]-n1[0])*(n2[0]-n1[0])+(n2[1]-n1[1])*(n2[1]-n1[1]));
//1. 两点相离
if(jizhan12>d1+d2)//以p1为原点,p1、p2连线方向r1和r2处点的中心点为接入位置
{
//
// System.out.println(p1[0]+"\t"+p1[1]);
// System.out.println(p2[0]+"\t"+p2[1]);
// System.out.println(p3[0]+"\t"+p3[1]);
// System.out.println(d1);
// System.out.println(d2);
// System.out.println(d3);
//
//p1 p2 所在直线与两圆交点在平面坐标上的表示
double pointA[] = {(d1 / jizhan12) * ((p2[0]-p1[0]) * 111500 * 0.8605),
(d1 / jizhan12) * (p2[1]-p1[1]) * 111500};
double pointB[] = {((jizhan12 - d2) / jizhan12) * ((p2[0]-p1[0]) * 111500 * 0.8605),
((jizhan12 - d2) / jizhan12) * (p2[1]-p1[1]) * 111500};
//p1 p2所在直线与两圆交点的经纬度坐标表示
double p_jingweiA[] = {p1[0] + pointA[0]/(111500 * 0.8605), p1[1] + pointA[1]/111500};
double p_jingweiB[] = {p1[0] + pointB[0]/(111500 * 0.8605), p1[1] + pointB[1]/111500};
//最终所求点的经纬度坐标表示
jingwei[0] = (0.5) * (p_jingweiA[0] + p_jingweiB[0]);
jingwei[1] = (0.5) * (p_jingweiA[1] + p_jingweiB[1]);
}
//2.两圆相含,以p1为原点,p2到p1连线延长线方向,r1远处为接入位置
else if(d1>(jizhan12+d2)||d2>(jizhan12+d1))
{
if( d2 > (jizhan12 + d1) )
{
//接入位置的平面坐标表示
double point1[] = {-(d1 / jizhan12) * ((p2[0]-p1[0]) * 111500 * 0.8605),
-(d1 / jizhan12) * (p2[1]-p1[1]) * 111500};
//接入位置经纬度表示
double p_jingwei1[] = {p1[0] + point1[0] / (111500 * 0.860), p1[1] + point1[1] / 111500};
jingwei = p_jingwei1;
}
if( d1 > (jizhan12 + d2))
{
//接入位置的平面坐标表示
double point2[] = {((d2 + jizhan12) / jizhan12) * ((p2[0]-p1[0]) * 111500 * 0.8605),
((d2 + jizhan12) / jizhan12) * (p2[1]-p1[1]) * 111500};
//接入位置经纬度表示
double p_jingwei2[] = {p1[0] + point2[0] / (111500 * 0.860), p1[1] + point2[1] / 111500};
jingwei = p_jingwei2;
}
}
//3.正常情况,用p1 p2 来选点,p3 来定位;
else
{
//现在开始进行计算
double m=n2[0];
double n=n2[1];
double A=m*m+n*n+d1*d1-d2*d2;
double B=1/(2*n);
double C=(-1)*2*m;
double a=1+B*B*C*C;
double b=2*A*B*B*C;
double c=A*A*B*B-d1*d1;
double d=b*b-4*a*c;
double x[]={(-b+Math.sqrt(d))/(2*a),(-b-Math.sqrt(d))/(2*a)};
double y[]={B*(C*x[0]+A),B*(C*x[1]+A)};
double dian1[]={p1[0]+x[0]/(111500*0.8605),p1[1]+y[0]/111500};
double dian2[]={p1[0]+x[1]/(111500*0.8605),p1[1]+y[1]/111500};
//System.out.println(dian1[0]+" "+dian1[1]);
//System.out.println(dian2[0]+" "+dian2[1]);
double deta1=Math.sqrt((x[0]-n3[0])*(x[0]-n3[0])+(y[0]-n3[1])*(y[0]-n3[1]));
double deta2=Math.sqrt((x[1]-n3[0])*(x[1]-n3[0])+(y[1]-n3[1])*(y[1]-n3[1]));
//System.out.println(deta1+" "+deta2);
if(Math.abs(deta1-d3)>Math.abs(deta2-d3))
{
jingwei=dian2;
}
else
{
jingwei=dian1;
}
//System.out.println(jingwei[0]+" "+jingwei[1]);
}
return jingwei;
}
/*
* 两点定位函数
* */
public static double[] point2(double P1[], double P2[], double D1, double D2, double A1, double A2)
{
double p1[] = P1;
double p2[] = P2;
double d1 = D1;
double d2 = D2;
double a1 = A1;//p1 方位角
double a2 = A2;//p2 方位角
double result[] = new double[2];//用来存储结果
//以P1为原点
double n1[] = {0, 0};
double n2[] = {(p2[0] - p1[0]) * 111500 * 0.8605, (p2[1] - p1[1]) * 111500};
//基站P1 P2 的距离
double jizhan12 = Math.sqrt((n2[0] - n1[0]) * (n2[0]-n1[0]) + (n2[1] - n1[1]) * (n2[1] - n1[1]));
//System.out.println(jizhan12);
//System.out.println(d1 + d2);
//------------------1.两圆相离----------------------------
if(jizhan12 > d1+d2)//以p1为原点,p1、p2连线方向r1和r2处点的中心点为接入位置
{
//p1 p2 所在直线与两圆交点在平面坐标上的表示
double pointA[] = {(d1 / jizhan12) * (n2[0] - n1[0]),
(d1 / jizhan12) * (n2[1] - n1[1])};
double pointB[] = {((jizhan12 - d2) / jizhan12) * (n2[0] - n1[0]),
((jizhan12 - d2) / jizhan12) * (n2[1] - n1[1])};
//p1 p2所在直线与两圆交点的经纬度坐标表示
double p_jingweiA[] = {p1[0] + pointA[0]/(111500 * 0.8605), p1[1] + pointA[1]/111500};
double p_jingweiB[] = {p1[0] + pointB[0]/(111500 * 0.8605), p1[1] + pointB[1]/111500};
//最终所求点的经纬度坐标表示
result[0] = 0.5 * (p_jingweiA[0] + p_jingweiB[0]);
result[1] = 0.5 * (p_jingweiA[1] + p_jingweiB[1]);
//System.out.println(result[0] + " " + result[1]);
}
//------------------------------2.两圆相含-------------------------------
//以p1为原点,p2到p1连线延长线方向,r1远处为接入位置
else if(d1>(jizhan12+d2)||d2>(jizhan12+d1))
{
if( d2 > (jizhan12 + d1) )
{
//接入位置的平面坐标表示
double point1[] = {-(d1 / jizhan12) * ((p2[0]-p1[0]) * 111500 * 0.8605),
-(d1 / jizhan12) * (p2[1]-p1[1]) * 111500};
//接入位置经纬度表示
double p_jingwei1[] = {p1[0] + point1[0] / (111500 * 0.860), p1[1] + point1[1] / 111500};
result = p_jingwei1;
//System.out.println(result[0] + " " + result[1]);
}
if( d1 > (jizhan12 + d2))
{
//接入位置的平面坐标表示
double point2[] = {((d2 + jizhan12) / jizhan12) * ((p2[0]-p1[0]) * 111500 * 0.8605),
((d2 + jizhan12) / jizhan12) * (p2[1]-p1[1]) * 111500};
//接入位置经纬度表示
double p_jingwei2[] = {p1[0] + point2[0] / (111500 * 0.860), p1[1] + point2[1] / 111500};
result = p_jingwei2;
//System.out.println(result[0] + " " + result[1]);
}
}
//----------------------------3.两圆相交-------------------------------
else
{
//先求出两圆的交点
double m=n2[0];
double n=n2[1];
double A=m*m+n*n+d1*d1-d2*d2;
double B=1/(2*n);
double C=(-1)*2*m;
double a=1+B*B*C*C;
double b=2*A*B*B*C;
double c=A*A*B*B-d1*d1;
double d=b*b-4*a*c;
//交点
double x[]={(-b+Math.sqrt(d))/(2*a),(-b-Math.sqrt(d))/(2*a)};
double y[]={B*(C*x[0]+A),B*(C*x[1]+A)};
double w11 = 0;//方位角P1G1
double detax1 = x[0];
double detay1 = y[0];
if (detax1 > 0 && detay1 > 0)//第一象限
{
w11 = Math.atan(detay1 / detax1);
}
if (detax1 < 0 && detay1 > 0)//第二象限
{
w11 = Math.atan(detay1 / detax1) + 180;
}
if (detax1 < 0 && detay1 < 0)//第三象限
{
w11 = Math.atan(detay1 / detax1) + 180;
}
if (detax1 > 0 && detay1 < 0)//第四象限
{
w11 = Math.atan(detay1 / detax1) + 360;
}
if (detax1 == 0 && detay1 > 0)
{
w11 = 90;
}
if (detax1 == 0 && detay1 < 0)
{
w11 = 270;
}
double w21 = 0;//方位角P1G2
double detax2 = x[1];
double detay2 = y[1];
if (detax2 > 0 && detay2 > 0)//第一象限
{
w21 = Math.atan(detay2 / detax2);
}
if (detax2 < 0 && detay2 > 0)//第二象限
{
w21 = Math.atan(detay2 / detax2) + 180;
}
if (detax2 < 0 && detay2 < 0)//第三象限
{
w21 = Math.atan(detay2 / detax2) + 180;
}
if (detax2 > 0 && detay2 < 0)//第四象限
{
w21 = Math.atan(detay2 / detax2) + 360;
}
if (detax2 == 0 && detay2 > 0)
{
w21 = 90;
}
if (detax2 == 0 && detay2 < 0)
{
w21 = 270;
}
double w12 = 0;//方位角P2G1
double detax3 = x[0] - ((p2[0] - p1[0]) * 111500 * 0.8605);
double detay3 = y[0] - ((p2[1] - p1[1]) * 111500);
if (detax3 > 0 && detay3 > 0)//第一象限
{
w12 = Math.atan(detay3 / detax3);
}
if (detax3 < 0 && detay3 > 0)//第二象限
{
w12 = Math.atan(detay3 / detax3) + 180;
}
if (detax3 < 0 && detay3 < 0)//第三象限
{
w12 = Math.atan(detay3 / detax3) + 180;
}
if (detax3 > 0 && detay3 < 0)//第四象限
{
w12 = Math.atan(detay3 / detax3) + 360;
}
if (detax3 == 0 && detay3 > 0)
{
w12 = 90;
}
if (detax3 == 0 && detay3 < 0)
{
w12 = 270;
}
double w22 = 0;//方位角P2G2
double detax4 = x[1] - ((p2[0] - p1[0]) * 111500 * 0.8605);
double detay4 = y[1] - ((p2[1] - p1[1]) * 111500);
if (detax4 > 0 && detay4 > 0)//第一象限
{
w22 = Math.atan(detay4 / detax4);
}
if (detax4 < 0 && detay4 > 0)//第二象限
{
w22 = Math.atan(detay4 / detax4) + 180;
}
if (detax4 < 0 && detay4 < 0)//第三象限
{
w22 = Math.atan(detay4 / detax4) + 180;
}
if (detax4 > 0 && detay4 < 0)//第四象限
{
w22 = Math.atan(detay4 / detax4) + 360;
}
if (detax4 == 0 && detay4 > 0)
{
w22 = 90;
}
if (detax4 == 0 && detay4 < 0)
{
w22 = 270;
}
//选点
if (Math.abs((w11 + w12) - (a1 + a2)) <= Math.abs((w21 + w22) - (a1 + a2)))
{
result[0] = x[0] / (111500 * 0.86) + p1[0];
result[1] = y[0] / 111500 + p1[1];
//System.out.println(result[0] + " " + result[1]);
}
result[0] = x[1] / (111500 * 0.86) + p1[0];
result[1] = y[1] / 111500 + p1[1];
//System.out.println(result[0] + " " + result[1]);
}
return result;
}
/*
* 单点定位函数
*
* */
public static double[] point1(double P1[], double A, double D1)
{
double angle = 0;// 定义一个角度,下面会赋值为随机数
Random random = new Random();
angle = random.nextDouble() * 120 - 60;//角度取[-60, 60]之间的随机值
//System.out.println(angle);
double result[] = new double [2];// 存储结果
double p1[] = P1;// 基站坐标
double a = A;// 基站方位角
double d1 = D1;// 基站接入距离
//在直角坐标系中假设接入点坐标为(x, y),那么可以求得其值并计算出相应经纬度坐标
double x = 0;//直角坐标系横坐标
double y = 0;//直角坐标系横坐标
y = d1 * Math.cos(a + angle) / 11500;
x = d1 * Math.sin(a + angle) /(11150 * Math.cos(0.5 * (y + p1[1])));
//转换成经纬度
result[0] = x + p1[0];
result[1] = y + p1[1];
//System.out.println(result[0] + " " + result[1]);
return result;
}
}
/**
*该函数是主函数,接受参数是含两个参数的数组(表名称pcmd,文件名称如“15052812”格式是“年月日时”yymmddhh。是8位数字)
* */
public static Job createSubmittableJob(Configuration conf, String[] args) throws IOException, URISyntaxException {
String tableName = args[0];//获取HBase的表名称,就是要把数据都存储在这个表里面
//在这里进行输入判断!
String inputStr = args[1];//要存进数据库的pcmd话单名称,格式是“年月日时”yymmddhh。是8位数字。
Path inputDir1 = null;
Path inputDir2= null;
Path inputDir3= null;
Path inputDir4= null;
Path inputDir5= null;
Path inputDir9= null;
Path inputDir10= null;
Path inputDir12= null;
Path inputDir13= null;
if(inputStr.length()!=8)
{
System.out.println("输入格式不对,请输入例如15042502的格式数据");
System.exit(0);
}else
//hdfs://master:8020//data/pcmd/omp1/15050106*
//hdfs://master:8020/data/pcmd/omp1/15050106*
{
//hdfs://master:8020//data/pcmd/omp1/*
//判断这个路径下面是否存在文件
inputDir1 = new Path(HDFS_PATH+"/omp1/"+inputStr+".gz");
inputDir2 = new Path(HDFS_PATH+"/omp2/"+inputStr+".gz");
inputDir3 = new Path(HDFS_PATH+"/omp3/"+inputStr+".gz");
inputDir4 = new Path(HDFS_PATH+"/omp4/"+inputStr+".gz");
inputDir5 = new Path(HDFS_PATH+"/omp5/"+inputStr+".gz");
inputDir9 = new Path(HDFS_PATH+"/omp9/"+inputStr+".gz");
inputDir10 = new Path(HDFS_PATH+"/omp10/"+inputStr+".gz");
inputDir12 = new Path(HDFS_PATH+"/omp12/"+inputStr+".gz");
inputDir13 = new Path(HDFS_PATH+"/omp13/"+inputStr+".gz");
}
//Path inputDir = new Path(args[1]);
JobConf jconf = new JobConf();
jconf.setJar("PCMDHBaseHour.jar");
Job job = new Job(conf, "PCMDHBaseHour"); //创建Job实例,后面为取名字
DistributedCache.addCacheFile(new URI(HDFS_PATH+"/pcmd/jizhan"), job.getConfiguration());
job.setJarByClass(LoadPCMD.class);//加载Mapper操作所在的类
FileSystem fs1 = FileSystem.get(URI.create(HDFS_PATH+"/omp1/"), conf);
if(fs1.exists(inputDir1))
{
FileInputFormat.addInputPath(job, inputDir1);
delete_path.add(inputDir1);
}
FileSystem fs2 = FileSystem.get(URI.create(HDFS_PATH+"/omp2/"), conf);
if(fs2.exists(inputDir2))
{
FileInputFormat.addInputPath(job, inputDir2);
delete_path.add(inputDir2);
}
FileSystem fs3 = FileSystem.get(URI.create(HDFS_PATH+"/omp3/"), conf);
if(fs3.exists(inputDir3))
{
FileInputFormat.addInputPath(job, inputDir3);
delete_path.add(inputDir3);
}
FileSystem fs4 = FileSystem.get(URI.create(HDFS_PATH+"/omp4/"), conf);
if(fs4.exists(inputDir4))
{
FileInputFormat.addInputPath(job, inputDir4);
delete_path.add(inputDir4);
}
FileSystem fs5 = FileSystem.get(URI.create(HDFS_PATH+"/omp5/"), conf);
if(fs5.exists(inputDir5))
{
FileInputFormat.addInputPath(job, inputDir5);
delete_path.add(inputDir5);
}
FileSystem fs9 = FileSystem.get(URI.create(HDFS_PATH+"/omp9/"), conf);
if(fs9.exists(inputDir9))
{
FileInputFormat.addInputPath(job, inputDir9);
delete_path.add(inputDir9);
}
FileSystem fs10 = FileSystem.get(URI.create(HDFS_PATH+"/omp10/"), conf);
if(fs10.exists(inputDir10))
{
FileInputFormat.addInputPath(job, inputDir10);
delete_path.add(inputDir10);
}
FileSystem fs12 = FileSystem.get(URI.create(HDFS_PATH+"/omp12/"), conf);
if(fs12.exists(inputDir12))
{
FileInputFormat.addInputPath(job, inputDir12);
delete_path.add(inputDir12);
}
FileSystem fs13 = FileSystem.get(URI.create(HDFS_PATH+"/omp13/"), conf);
if(fs13.exists(inputDir13))
{
FileInputFormat.addInputPath(job, inputDir13);
delete_path.add(inputDir13);
}
job.setInputFormatClass(TextInputFormat.class);//设置输入的类型
job.setMapperClass(LoadPCMD.class);//设置map的类型
// ++++ insert into table directly using TableOutputFormat ++++
// ++++ 使用TableOutputFormat 直接插入表中++++
TableMapReduceUtil.initTableReducerJob(tableName, null, job);//使用工具对job适当配置
job.setNumReduceTasks(0);//这个reduce个数和region的数量有关,我们可以在创建表的时候设置region的数量
TableMapReduceUtil.addDependencyJars(job);
return job;
}
/**********************************************************************
* 测试main函数
* @param 表名称pcmd,文件名称如“15100119”格式是“年月日时”yymmddhh。是8位数字
* @author root
* @return void
*
******************************************************************/
public static void main(String[] args) throws Exception {
Configuration conf = HBaseConfiguration.create();//获取配置文件
Job job = createSubmittableJob(conf, args);//系统输入的参数,表名称(“pcmd”)和pcmd文件名称(如“15052812”)。创建一个job任务
if(job.waitForCompletion(true))//执行job任务,结束后会返回一个boolean结果
{
if(delete_path.size()>0)
{
for(Path a:delete_path)
{
FileSystem fs = FileSystem.get(URI.create(HDFS_PATH+"/"), conf);
if(fs.delete(a))
{
System.out.println(a.toString()+"删除成功!");
}
}
}
}
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}<file_sep>define(['backbone',
'models/cell_info_type3',
],
function(Backbone, CellInfoType3) {
var CellInfoType3Collection = Backbone.Collection.extend({
model: CellInfoType3,
initialize: function(options){
this.urlRoot = 'cell_info_type3.html';
this.url = this.urlRoot + '?complaint_item_id=' + options.id;
}
});
return CellInfoType3Collection;
});<file_sep>define([
'backbone'
], function(Backbone) {
"use strict";
var ComplaintItem = Backbone.Model.extend({
});
return ComplaintItem;
});<file_sep>package com.yl.service;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.customer.isSatisfied.AutoDispatchOrders;
import com.customer.isSatisfied.FeedbackPreDealtResult;
import com.customer.isSatisfied.SysCode;
import com.homer.servlet.ValidateCode;
import com.jay.mysql.util.MyDBManager;
import com.mysql.jdbc.PreparedStatement;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.user.complain.ComplaintInfoSys;
import com.yl.util.DBConnUtil;
import com.yl.util.ObjectsIsEmpty;
import mysql.mysql_DML;
import net.sf.json.JSONObject;
public class ComplaintInfo_20160824 extends HttpServlet {
private String tel = "";//用户手机号
private String date = "";//问题发生日期
private String time = "";//问题发生时间
private int complaint_type = 0;//投诉类型编码2G;3G
private String loc = "";//问题发生地点
private String area = "";//问题地点队对应的地区
private float lon = 0;//问题地点gps经度
private float lat = 0;//问题地点gps纬度
private float baidu_lon = 0;//问题地点百度经度
private float baidu_lat = 0;//问题地点百度纬度
private String msg = "";//留言
private int event = 0;//故障现象
private String code = "";//验证码
private String serverCode = "";
private int result = 0;//结果编码
private int complaint_source = 1;//投诉来源,1表示手机网页投诉
private int complaint_id = 0;//投诉编号
private int pre_deal_result_id = 0;//预处理结果编号
private String abnormal_text = "";//预处理结果
private String message_leaver = "";//留言人
private String message_time = "";//留言时间
private String message_content = "";//留言内容
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Access-Control-Allow-Origin","*");
String result = "";
try {
result = complaintInfo(request, response);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PrintWriter out = response.getWriter();
out.println(result);
out.flush();
out.close();
}
/* 发送:
{
"tel":"18171406899",
"date":"2015-10-01",
"time":"20:00",
"type":1,
"loc":"武汉市华科",
"area":"武汉市洪山区",
"event":2,
"msg":"我要留言",
"code":"asff",
"lon":"114.4202",
"lat":"30.51533"
}
* 投诉信息录入,post
* @param request
* @param response
* @return
* @throws ParseException
* @throws SQLException
* @throws ClassNotFoundException
*/
public String complaintInfo(HttpServletRequest request, HttpServletResponse response)
throws ParseException, ClassNotFoundException, SQLException, FileNotFoundException, IOException {
/**
* 1.获取前台传入数据,判断数据是否为空,校验数据格式
*/
//定义json对象
JSONObject resultJsonObject = new JSONObject();
JSONObject jsonObject = new JSONObject();
jsonObject = readJson(request);
//从json对象中获取前台传入数据
tel = jsonObject.getString("tel");
date = jsonObject.getString("date");
time = jsonObject.getString("time");
complaint_type = jsonObject.getInt("type");
loc = jsonObject.getString("loc");
area = jsonObject.getString("area");
lat = (float) jsonObject.getDouble("gpsLat");
baidu_lon = (float) jsonObject.getDouble("lon");
baidu_lat = (float) jsonObject.getDouble("lat");
lon = (float) jsonObject.getDouble("gpsLon");
event = jsonObject.getInt("event");
msg = jsonObject.getString("msg");
code = jsonObject.getString("code");
serverCode = (String)request.getSession().getAttribute("code");
System.out.println("serverCode="+serverCode);
if(serverCode==null || serverCode.length()<1 || !(code.toLowerCase()).equals(serverCode.toLowerCase())){
resultJsonObject.put("result", -1);
resultJsonObject.put("text", "验证码有误,请确认后重新输入!");
return resultJsonObject.toString();
}
ValidateCode valid = new ValidateCode();
System.out.println("valid code="+valid.getValidCodeString());
if (tel.length() != 11 || !tel.startsWith("1")) {
resultJsonObject.put("result", -1);
resultJsonObject.put("text", "请输入正确的电信手机号码");
return resultJsonObject.toString();
}
// 检测输入的经纬度是否在湖北省内或省边界附近,不在就报错退出
if (!(108.29209227 <= lon && lon <= 116.37915993)) {
resultJsonObject.put("result", -1);
resultJsonObject.put("text", "投诉仅限湖北省内,请核对投诉地点");
return resultJsonObject.toString();
}
if (!(28.92430194 <= lat && lat <= 33.43608273)) {
resultJsonObject.put("result", -1);
resultJsonObject.put("text", "投诉仅限湖北省内,请核对投诉地点");
return resultJsonObject.toString();
}
SimpleDateFormat sdDateFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdDateFormat2 = new SimpleDateFormat("HH:mm");
SimpleDateFormat sdDateFormat3 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
date = sdDateFormat.format(sdDateFormat.parse(date));
time = sdDateFormat2.format(sdDateFormat2.parse(time));
//整合投诉时间
String call_time= sdDateFormat3.format(sdDateFormat3.parse(date.concat(" ").concat(time)));
String complaint_time= sdDateFormat3.format(new Date());
//创建数据库连接
DBConnUtil dbConnUtil = new DBConnUtil();
Connection conn = DBConnUtil.getConn();
PreparedStatement pstmt = null;
//获取工位所在城市
String workStationCity = getWorkStationCity(loc);
/**
* 3.验证通过后将投诉信息写入表complaint_records,得到预处理投诉ID
*/
String remote_ip = getRemoteAddress(request);
String sql = "INSERT INTO complaint_records(complaint_tele_num,pheno_code,complaint_type,call_time," +
"complaint_time,complaint_position,complaint_area,gps_lon," +
"gps_lat,baidu_lon, baidu_lat,message,complaint_source,complaint_ip,work_station_city)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
boolean update_flag = dbConnUtil.updateData(sql, conn, pstmt, tel, event, complaint_type,call_time, complaint_time,
loc, area, lon, lat,baidu_lon, baidu_lat, msg, complaint_source, remote_ip,workStationCity);
if (!update_flag) {
result = -1;
resultJsonObject.put("result", result);
resultJsonObject.put("text", "投诉信息录入失败!");
return resultJsonObject.toString();
}
//查询最大行数
String sqlString = "SELECT MAX(complaint_id) FROM complaint_records";
ArrayList<String> list = dbConnUtil.selectData(sqlString, conn, pstmt);
if (null == list || list.isEmpty()) {
result = -1;
resultJsonObject.put("result", result);
resultJsonObject.put("text", "投诉编号查询失败!");
return resultJsonObject.toString();
}
complaint_id = Integer.parseInt(list.get(0).split("\t")[0]);
/**
* 4.调用预处理接口,将预处理结果insert表pre_deal_result_records
* 并将对应的pre_deal_result_id更新到投诉记录表中
*/
JSONObject jCOmplaintInfo = new JSONObject();
jCOmplaintInfo.put("complaint_phone", tel);
jCOmplaintInfo.put("occur_time", call_time);
jCOmplaintInfo.put("complaint_time", complaint_time);
jCOmplaintInfo.put("location", loc);
jCOmplaintInfo.put("longitude", lon);
jCOmplaintInfo.put("latitude", lat);
jCOmplaintInfo.put("staff_id", "二期系统web投诉调用");
jCOmplaintInfo.put("net_type", complaint_type);
jCOmplaintInfo.put("pheno_option", complaint_type);
jCOmplaintInfo.put("pheno_description", msg);
jCOmplaintInfo.put("pheno_always", 1); //默认投诉现象是长期的1,0为短期
jCOmplaintInfo.put("search_time_range", 6); //默认搜索时间范围是6小时
jCOmplaintInfo.put("search_radius", 1000);//默认搜索半径是1000米
// 这里需要和一期的预处理系统连起来,如果预处理结果生成失败,则输出状态handle_status=-1;
//存预处理结果信息
ComplaintInfoSys complaintSys1 = new ComplaintInfoSys();
String preDealResult = null; //存预处理结果信息
try {
preDealResult = complaintSys1.complaintInfoSys1(jCOmplaintInfo);
} catch (IOException e) {
System.out.println("获取预处理结果失败");
//预处理失败 handle_status=-1
String updateSql = "UPDATE complaint_records SET handle_status = ? WHERE complaint_id = ?";
boolean updateflag = dbConnUtil.updateData(updateSql, conn, pstmt, SysCode.HandleStatus_handlingFailedCode, complaint_id);
e.printStackTrace();
}
//读取预处理结果
JSONObject jPreDealResult = new JSONObject();
jPreDealResult = JSONObject.fromObject(preDealResult);
String mainCauseString = jPreDealResult.getString("main_reason");
String secCauseString = jPreDealResult.getString("assisted_reason");
int mainCauseCode = jPreDealResult.getInt("mainCauseCode");
int secCauseCode = jPreDealResult.getInt("secCauseCode");
String abnormal_text = jPreDealResult.getString("excuse");//主次原因和6项预处理结果的字符串拼接,异常概览内容
String geogCell= jPreDealResult.getString("geogCell");//6项预处理结果
String alarm= jPreDealResult.getString("alarm");
String BSPerf= jPreDealResult.getString("BSPerf");
String callEvent= jPreDealResult.getString("callEvent");
String callQuality= jPreDealResult.getString("callQuality");
String callDis= jPreDealResult.getString("callDis");
System.out.println("手机投诉函数*************"+BSPerf);
// //---------------------------------------------------------------------------------------------------------------------------------
// //这里是为了演示方便,暂时不调用预处理系统。直接根据电话号码最后一位数字,来决定预处理的结果是否有故障。20160511之后,这里要恢复调用预处理系统。目前有5种处理结果。
// long key = 0;
// String reply_text = "尊敬的" + tel + "用户,您好。";
// try {
// key = Long.parseLong(tel) % 5;
// } catch (Exception e) {
// result = -1;
// resultJsonObject.put("result", result);
// resultJsonObject.put("text", "预处理出错!获取故障回复口径有问题!");
//
// return resultJsonObject.toString();
// }
//
// String mainCauseString = null;
// String secCauseString = null;
// String cause = null;
// int mainCauseCode = 0;
// int secCauseCode = 0;
// switch ((int)key) {
// case 1: cause = "处理发生异常,无法预判" ;
// mainCauseString = "无法预判";
// secCauseString = "无法预判";
// mainCauseCode = -2;
// secCauseCode = -2;
// reply_text += "系统暂时无法处理您的投诉,已转人工处理。请耐心等候。";
// break;
//
// case 2: cause = "主要原因:网优问题,次要原因:网优问题。预处理中间结果:经过查询处理,本次投诉无异常内容! " +
// "投诉预判原因6项子标签分析结果: 1、地理关联小区:Rich; 2、关联小区故障:Health; 3、关联小区性能:RSSI; " +
// "4、话单异常事件:Abnormal_other; 5、话单信号质量:Thin; 6、话单接入距离:Inside.";
// mainCauseString = "网优问题";
// secCauseString = "网优问题";
// mainCauseCode = 2;
// secCauseCode = 2;
// reply_text += "经核实,您反映的地点目前网络覆盖待优化,我们会将您反映的问题立即转交相关部门处理,给您带来不便敬请谅解!";
// break;
//
// case 3: cause = "主要原因:建设问题,次要原因:无。预处理中间结果: 1、最近小区距离用户约580.0米。覆盖质量一般。 " +
// "投诉预判原因6项子标签分析结果: 1、地理关联小区:Poor 2、关联小区故障:Health 3、关联小区性能:Good 4、话单异常事件:无话单 5、话单信号质量:无话单6、话单接入距离:无话单" ;
// mainCauseString = "建设问题";
// secCauseString = "无";
// mainCauseCode = 5;
// secCauseCode = 0;
// reply_text += "经核实,您反映的地方目前网络覆盖正在建设中,我们会将您反映的问题立即转交相关部门并督促尽快解决,给您带来不便敬请谅解!";
// break;
//
// case 4: cause = "主要原因:维护问题,次要原因:无。预处理中间结果:经过查询处理,本次投诉无异常内容! " +
// "投诉预判原因6项子标签分析结果: 1、地理关联小区:Rich; 2、关联小区故障:Weak; 3、关联小区性能:RSSI; " +
// "4、话单异常事件:Abnormal_other; 5、话单信号质量:Thin; 6、话单接入距离:Inside.";
// mainCauseString = "维护问题";
// secCauseString = "无";
// mainCauseCode = 1;
// secCauseCode = 0;
// reply_text += "经核实,您反映地点的覆盖基站发生了告警,导致信号差,我们的工作人员正在抢修中,给您带来不便敬请谅解!";
// break;
//
// case 5: cause = "主要原因:无明显故障,次要原因:无。预处理中间结果:经过查询处理,本次投诉无异常内容! " +
// "投诉预判原因6项子标签分析结果: 1、地理关联小区:Rich; 2、关联小区故障:Health; 3、关联小区性能:Good; " +
// "4、话单异常事件:Normal; 5、话单信号质量:Thick; 6、话单接入距离:Inside.";
// mainCauseString = "无明显故障";
// secCauseString = "无";
// mainCauseCode = 6;
// secCauseCode = 0;
// reply_text += "经核实,您反映的地点目前网络覆盖处于正常状态,建议您可以尝试进行开关机或换机换卡测试一下。";
// break;
//
// default:cause = "主要原因:无明显故障,次要原因:无。预处理中间结果:经过查询处理,本次投诉无异常内容! " +
// "投诉预判原因6项子标签分析结果: 1、地理关联小区:Rich; 2、关联小区故障:Health; 3、关联小区性能:Good; " +
// "4、话单异常事件:Normal; 5、话单信号质量:Thick; 6、话单接入距离:Inside.";
// mainCauseString = "无明显故障";
// secCauseString = "无";
// mainCauseCode = 6;
// secCauseCode = 0;
// reply_text += "经核实,您反映的地点目前网络覆盖处于正常状态,建议您可以尝试进行开关机或换机换卡测试一下。";
// break;
// }
// int testDataFlag = mainCauseCode;
//
// //-------------------------------------------------------------------------------------------------------
//
//
//判定预处理结果是否有故障。因为预处理结果标签组合只有13组,所以可以穷举。
int has_error=-1;
if (mainCauseCode == 6 &&secCauseCode==0) {//无故障
has_error = 0;
} else if(secCauseCode == -2 && mainCauseCode == -2){//系统无法判断
has_error = -1;
}else { //有故障
has_error = 1;
}
//查询主次原因和回复口径的对应表,得到回复口径.在一期系统。
String reply_text = "尊敬的" + tel + "用户,您好。";
String sqlReplyText = "select message from dict_reply_msg where reply_msg_id=(select reply_msg_id from cause_reply_msg " +
"where mainCause_code="+mainCauseCode+" and secCause_code="+secCauseCode+")";
mysql_DML dml = new mysql_DML();
Connection connection = dml.myConnection();
ArrayList<String> replyList = dml.selectMysql(sqlReplyText, connection);
if (replyList == null || replyList.isEmpty()) {
System.out.println("获取回复口径出错!");
resultJsonObject.put("result", -1);
resultJsonObject.put("text", "根据预处理结果获取回复口径出错!");
return resultJsonObject.toString();
}
connection.close();
reply_text += replyList.get(0).trim();//回复口径
int handle_status = 0;
if (preDealResult != null && preDealResult.length() > 0) {//预处理成功。还要识别有无故障,有故障直接派单handle_status=1,无故障人工派单handle_status=2。
//更新预处理到结果表。
String insertsql = "INSERT INTO pre_deal_result_records (complaint_id,abnormal_text,has_error," +
"main_cause_code,sec_cause_code,main_cause_text,sec_cause_text,geogCell,alarm,BSPerf,callEvent,callQuality,callDis)" +
" VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)";
boolean insertflag = dbConnUtil.updateData(insertsql, conn, pstmt, complaint_id, abnormal_text, has_error,
mainCauseCode,secCauseCode,mainCauseString,secCauseString,geogCell,alarm,BSPerf,callEvent,callQuality,callDis);
if (!insertflag) {
result = -1;
resultJsonObject.put("result", result);
resultJsonObject.put("text", "预处理结果插入失败!");
return resultJsonObject.toString();
}
//查询预处理结果最大行数
String sqlString1 = "SELECT MAX(pre_deal_result_id) FROM pre_deal_result_records";
ArrayList<String> list1 = dbConnUtil.selectData(sqlString1, conn, pstmt);
if (null == list1 || list1.isEmpty()) {
result = -1;
resultJsonObject.put("result", result);
resultJsonObject.put("text", "该投诉对应的预处理结果编号查询失败!");
return resultJsonObject.toString();
}
pre_deal_result_id = Integer.parseInt(list1.get(0).split("\t")[0]);
//更新表complaint_records,增加回复口径reply_text
if (has_error == 1) {//有故障,需要系统直接自动派单3
handle_status = SysCode.HandleStatus_needDispatchBySysCode;
}else if (has_error == 0){//无故障,由服务台处理是否派单2
handle_status = SysCode.HandleStatus_needDispatchByHandCode;
}else {//程序异常
handle_status = SysCode.HandleStatus_handlingFailedCode;
}
String updateString1 = "UPDATE complaint_records SET pre_deal_result_id = ?, reply_text=?,handle_status=? WHERE complaint_id = ?";
boolean updateflag = dbConnUtil.updateData(updateString1, conn, pstmt, pre_deal_result_id,reply_text,handle_status, complaint_id);
if (!updateflag) {
result = -1;
resultJsonObject.put("result", result);
resultJsonObject.put("text", "更新complaint_records.pre_deal_result_id失败!");
return resultJsonObject.toString();
}
//5.更新留言记录表
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
message_time = simpleDateFormat.format(new Date());
message_content = "投诉发起";
message_leaver = "投诉用户" + tel;
int messageType = 1;//1:用户提交,2-系统答复
String updateString3 = "INSERT INTO message_records (complaint_id, message_time, message_content,message_type, message_leaver) VALUES (?,?,?,?,?)";
boolean update_flag3 = dbConnUtil.updateData(updateString3, conn, pstmt, complaint_id, message_time,message_content, messageType, message_leaver);
if (!update_flag3) {
result = -1;
resultJsonObject.put("result", result);
resultJsonObject.put("text", "留言记录信息录入失败!");
return resultJsonObject.toString();
}
} else {
//预处理失败 handle_status=-1
handle_status =SysCode.HandleStatus_handlingFailedCode;
String updateSql = "UPDATE complaint_records SET handle_status = ? WHERE complaint_id = ?";
boolean updateflag = dbConnUtil.updateData(updateSql, conn, pstmt, handle_status, complaint_id);
if (!updateflag) {
result = -1;
resultJsonObject.put("result", result);
resultJsonObject.put("text", "更新complaint_records.handle_status失败!");
return resultJsonObject.toString();
}
}
conn.close();
resultJsonObject.put("result", 0);
resultJsonObject.put("text", "提交成功!");
resultJsonObject.put("complaint_id", complaint_id);
resultJsonObject.put("reply_text", reply_text);
System.out.println("预处理成功,返回结果...");
return resultJsonObject.toString();
}
/******************************************************
* 传进参数:投诉用户输入的城市字符串
* 返回值:与用户投诉的匹配的工位城市名称
* 功能说明:返回工位所在城市
* @param req
* @return
*****************************************************/
private String getWorkStationCity(String loc) {
System.out.println("投诉地点="+loc);
String[] cityArray = {"黄冈","黄石","荆门","荆州","鄂州","十堰","随州","武汉","孝感","咸宁","襄阳","宜昌","恩施","林区","潜江","天门","仙桃"};//17个城市
String tempCity = "未知城市";
for (String city : cityArray) {
if (loc.contains(city)) {
tempCity = city;
break;
}
}
return tempCity;
}
/******************************************************
* 传进参数:前端的HttpServletRequest请求
* 返回值:传进来的请求内容,转为json对象的结果
* 功能说明:string 变成 json 对象,返回Jason对象
* @param req
* @return
*****************************************************/
protected JSONObject readJson(HttpServletRequest req){
StringBuffer json = new StringBuffer();
String line = null;
try {
BufferedReader reader = req.getReader();
while((line = reader.readLine()) != null) {
System.out.println(line);
json.append(line);
}
}
catch(Exception e) {
System.out.println(e.toString());
}
JSONObject jsonObj = JSONObject.fromObject(json.toString());
return jsonObj;
}
/*******************************************************************************
* 传进参数:前端的HttpServletRequest请求
* 返回值:请求者的ip
* 功能说明:获取发送请求的IP
** @author yl
*******************************************************************************/
private String getRemoteAddress(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.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
<file_sep>define(['backbone',
'models/map/b_district_info',
],
function(Backbone, BDistrictInfo) {
var BDistrictInfoCollection = Backbone.Collection.extend({
model: BDistrictInfo,
initialize: function(options){
// this.urlRoot = 'cell_info.html';
// this.url = this.urlRoot + '?complaint_item_id=' + options.id;
}
});
return BDistrictInfoCollection;
});<file_sep>//var url_getPreResult='http://120.26.59.151/yi/queryPre';
//var url_feedback='http://172.16.31.10/PreDealSys2/feedbackOnPreDealtResult';
//var url_navigate="http://120.26.59.151/yee/navigate.html";
var url_getPreResult='/PreDealSys2/queryPre';
var url_feedback='/PreDealSys2/feedbackOnPreDealtResult';
var url_navigate="/PreDealSys2/webAPP/navigate.html";
var id=window.location.search.split("=")[1];
window.onload=function(){
var btnSatisfy=document.getElementById('satisfy');
var btnUnsatisfy=document.getElementById('unsatisfy');
var pContent=document.getElementById('content');
var xhr_getPreResult=new XMLHttpRequest();
xhr_getPreResult.onload=function(e){
if(xhr_getPreResult.status>=200 && xhr_getPreResult.status<300 || xhr_getPreResult.status==304){
pContent.innerHTML=JSON.parse(xhr_getPreResult.responseText).preDealResult;
btnUnsatisfy.addEventListener('click',unSatisfy,false);
btnSatisfy.addEventListener("click",satisfy,false);
}
};
xhr_getPreResult.open('get',url_getPreResult+window.location.search,true);
xhr_getPreResult.send(null);
function satisfy(){
var data={};
data.complaint_id=id;
data.is_satisfied=1;
var xhr_satisfy=new XMLHttpRequest();
xhr_satisfy.onload=function(e){
if(xhr_satisfy.status>=200 && xhr_satisfy.status<300 || xhr_satisfy.status==304){
//do something
var result=JSON.parse(xhr_satisfy.responseText);
if(result.result<0){
alert(result.text);
return;
}
alert(result.text);
window.location.replace(url_navigate);
}
};
xhr_satisfy.open('post',url_feedback,true);
xhr_satisfy.send(JSON.stringify(data));
}
function unSatisfy(){
var data={};
data.complaint_id=id;
data.is_satisfied=-1;
var xhr_unSatisfy=new XMLHttpRequest();
xhr_unSatisfy.onload=function(e){
if(xhr_unSatisfy.status>=200 && xhr_unSatisfy.status<300 || xhr_unSatisfy.status==304){
//do something
var result=JSON.parse(xhr_unSatisfy.responseText);
if(result.result<0){
alert(result.text);
return;
}
alert(result.text);
window.location.replace(url_navigate);
}
};
xhr_unSatisfy.open('post',url_feedback,true);
xhr_unSatisfy.send(JSON.stringify(data));
}
};<file_sep>define([
'backbone'
], function(Backbone) {
"use strict";
var CellInfoType3 = Backbone.Model.extend({
});
return CellInfoType3;
});<file_sep>define([
'underscore',
'backbone',
'marionette',
"tpl!views/partials/common/common_t/sideWrapper.tpl",
], function(_, Backbone, Marionette, sideWrapperTpl) {
"use strict";
var SideWrapperView = Marionette.ItemView.extend({
template: sideWrapperTpl,
initialize: function() {
console.log('init sideWrapper view');
},
});
return SideWrapperView;
});
<file_sep>define([
'backbone'
], function(Backbone) {
"use strict";
var StatisticByGeography = Backbone.Model.extend({
initialize: function(options){
this.urlRoot = 'statistic_by_geography.html';
this.url = this.urlRoot;
}
});
return StatisticByGeography;
});<file_sep>define([
'backbone'
], function(Backbone) {
"use strict";
var ComplaintInfo = Backbone.Model.extend({
defaults: {
"staff_id": "",
"complaint_phone": "",
"location": "",
"longitude": "",
"latitude": "",
"pheno_option": "",
"pheno_description": "",
"complaint_time": "",
"occur_time": "",
"search_radius": "500",
"pheno_always": "1",
"search_time_range": "2",
"net_type":"1"
},
validation: {
staff_id:{
required: false,
msg: "请填写员工编号"
},
complaint_phone:{
required: false,
length: 11,
range: [12345678901,23456789012],
msg: "请正确填写电话号码"
},
pheno_option:{
required: true
},
pheno_always:{
required: true
},
net_type:{
required: true
},
occur_time:{
required: true,
msg: "请填写问题发生时间"
},
pheno_description:{
required: false,
maxLength: 50,
msg: "输入字数在50字以内"
},
location:{
// required: true
},
longitude:{
required: false,
range: [108.438, 116.120],
msg: '请保证输入地址位于湖北省内'
},
latitude:{
required: false,
range: [29.143, 33.258],
msg: '请保证输入地址位于湖北省内'
},
search_radius:{
required: true,
range: [500,5000],
msg: '请保证搜索半径在500-5000米范围内'
},
search_time_range:{
required: true,
range: [2,24],
msg: '请保证搜索时间范围在2-24小时内'
},
},
initialize: function(options){
this.urlRoot = 'complaint_info.html';
this.url = this.urlRoot;
//'?complaint_item_id=' + options.id
}
});
return ComplaintInfo;
});<file_sep>package domain;
import java.io.Serializable;
public class Grid implements Serializable{
private String gridId;
private double longitude;
private double latitude;
private double ecio;
private short num;
public String getGridId() {
return gridId;
}
public void setGridId(String gridId) {
this.gridId = gridId;
}
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 double getEcio() {
return ecio;
}
public void setEcio(double ecio) {
this.ecio = ecio;
}
public short getNum() {
return num;
}
public void setNum(short num) {
this.num = num;
}
@Override
public String toString() {
return "Grid [gridId=" + gridId + ", longitude=" + longitude
+ ", latitude=" + latitude + ", ecio=" + ecio + ", num=" + num
+ "]";
}
@Override
public int hashCode() {//这个函数是用来判断2个对象是否相等的
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(ecio);
result = prime * result + (int) (temp ^ (temp >>> 32));//右移一位
result = prime * result + ((gridId == null) ? 0 : gridId.hashCode());//
temp = Double.doubleToLongBits(latitude);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(longitude);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + num;
return result;
}
@Override
public boolean equals(Object obj) {//重写equals 方法
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Grid other = (Grid) obj;
if (Double.doubleToLongBits(ecio) != Double//如果ecio相同
.doubleToLongBits(other.ecio))
return false;
if (gridId == null) {
if (other.gridId != null)
return false;
} else if (!gridId.equals(other.gridId))
return false;
if (Double.doubleToLongBits(latitude) != Double
.doubleToLongBits(other.latitude))
return false;
if (Double.doubleToLongBits(longitude) != Double
.doubleToLongBits(other.longitude))
return false;
if (num != other.num)
return false;
return true;
}
}
<file_sep>define([
'underscore',
'backbone',
'marionette',
'highcharts',
'collection/grid_statistic_info_collection',
'collection/phone_statistic_info_collection',
'collection/station_error_statistic_info_collection',
'collection/cell_performance_statistic_info_collection',
'models/complaint_statistic_data',
'models/statistic_by_date',
'models/statistic_by_datetime',
'models/statistic_by_geography',
'models/statistic_by_prejudging_reason',
'views/partials/common/gridStatistic',
'views/partials/common/phoneStatistic',
'views/partials/common/stationerrorStatistic',
'views/partials/common/cellperformanceStatistic',
'views/partials/common/nocity',
'views/partials/common/nodate',
'views/partials/common/noreason',
'views/partials/common/nodatetime',
"tpl!views/partials/common/common_t/phoneStatisticInfo.tpl",
"tpl!views/partials/common/common_t/phoneStatisticInfoTitle.tpl",
"tpl!views/partials/common/common_t/gridStatisticInfo.tpl",
"tpl!views/partials/common/common_t/gridStatisticInfoTitle.tpl",
"tpl!views/partials/common/common_t/stationerrorStatisticInfo.tpl",
"tpl!views/partials/common/common_t/stationerrorStatisticInfoTitle.tpl",
"tpl!views/partials/common/common_t/cellperformanceStatisticInfo.tpl",
"tpl!views/partials/common/common_t/cellperformanceStatisticInfoTitle.tpl",
"tpl!views/partials/common/common_t/noChildMessage.tpl",
"tpl!views/partials/common/common_t/infoItemList.tpl",
], function(_, Backbone, Marionette, highcharts, GridStatisticInfoCollection, PhoneStatisticInfoCollection, StationErrorStatisticInfoCollection, CellPerformanceStatisticInfoCollection, ComplaintStatisticData,
StatisticByDate, StatisticByDateTime, StatisticByGeography, StatisticByPrejudgingReason,
GridStatisticView, PhoneStatisticView, StationErrorStatisticView, CellPerformanceStatisticView,
NoCityView, NoDateView, NoReasonView, NoDateTimeView,
phoneStatisticInfoTpl, phoneStatisticInfoTitleTpl, gridStatisticInfoTpl, gridStatisticInfoTitleTpl,
stationerrorStatisticInfoTpl, stationerrorStatisticInfoTitleTpl, cellperformanceStatisticInfoTpl, cellperformanceStatisticInfoTitleTpl, noChildMessageTpl, infoItemListTpl) {
"use strict";
var EmptyView = Backbone.Marionette.ItemView.extend({
template: noChildMessageTpl,
className: "noChildMessage",
initialize: function(options){
this.message = options.message;
},
onShow: function(){
this.$('.alert-message').html(this.message);
$('.alert-message').parents('table').removeClass('table-bordered');
}
});
var GridStatisticInfoView = Backbone.Marionette.ItemView.extend({
tagName: 'tr',
template: gridStatisticInfoTpl,
});
var GridStatisticInfoCollectionView = Backbone.Marionette.CollectionView.extend({
tagName: 'table',
className: "table table-bordered grid-statistic-info-table",
childView: GridStatisticInfoView,
emptyView: EmptyView,
emptyViewOptions: {
message: "无法查询得到投诉栅格信息"
},
gridStatisticInfoTitle : gridStatisticInfoTitleTpl,
onRender: function(){
if(this.collection.isEmpty()===false){
this.$el.prepend(this.gridStatisticInfoTitle);
}
}
});
var PhoneStatisticInfoView = Backbone.Marionette.ItemView.extend({
tagName: 'tr',
template: phoneStatisticInfoTpl,
});
var PhoneStatisticInfoCollectionView = Backbone.Marionette.CollectionView.extend({
tagName: 'table',
className: "table table-bordered phone-statistic-info-table",
childView: PhoneStatisticInfoView,
emptyView: EmptyView,
emptyViewOptions: {
message: "无法查询得到投诉号码信息"
},
phoneStatisticInfoTitle : phoneStatisticInfoTitleTpl,
onRender: function(){
if(this.collection.isEmpty()===false){
this.$el.prepend(this.phoneStatisticInfoTitle);
}
}
});
var StationErrorStatisticInfoView = Backbone.Marionette.ItemView.extend({
tagName: 'tr',
template: stationerrorStatisticInfoTpl,
});
var StationErrorStatisticInfoCollectionView = Backbone.Marionette.CollectionView.extend({
tagName: 'table',
className: "table table-bordered station-error-statistic-info-table",
childView: StationErrorStatisticInfoView,
emptyView: EmptyView,
emptyViewOptions: {
message: "无法查询得到故障小区信息"
},
stationerrorStatisticInfoTitle : stationerrorStatisticInfoTitleTpl,
onRender: function(){
if(this.collection.isEmpty()===false){
this.$el.prepend(this.stationerrorStatisticInfoTitle);
}
}
});
var CellPerformanceStatisticInfoView = Backbone.Marionette.ItemView.extend({
tagName: 'tr',
template: cellperformanceStatisticInfoTpl,
});
var CellPerformanceStatisticInfoCollectionView = Backbone.Marionette.CollectionView.extend({
tagName: 'table',
className: "table table-bordered station-error-statistic-info-table",
childView: CellPerformanceStatisticInfoView,
emptyView: EmptyView,
emptyViewOptions: {
message: "无法查询得到性能预警小区信息"
},
cellperformanceStatisticInfoTitle : cellperformanceStatisticInfoTitleTpl,
onRender: function(){
if(this.collection.isEmpty()===false){
this.$el.prepend(this.cellperformanceStatisticInfoTitle);
}
}
});
var InfoItemListView = Marionette.LayoutView.extend({
template: infoItemListTpl,
regions: {
gridStatisticResultWrapper: '#gridStatisticResult',
phoneStatisticResultWrapper: '#phoneStatisticResult',
stationerrorStatisticResultWrapper: '#stationerrorStatisticResult',
cellperformanceStatisticResultWrapper: '#cellperformanceStatisticResult',
gridStatisticWrapper: '#gridStatistic',
phoneStatisticWrapper: '#phoneStatistic',
stationerrorStatisticWrapper: '#stationerrorStatistic',
cellperformanceStatisticWrapper: '#cellperformanceStatistic',
cityComplaintWrapper: '#cityComplaint',
complaintNumWrapper: '#complaintNum',
preJudgingReasonWrapper: '#preJudgingReason',
},
events:{
'click #timeSubmit': 'searchDateComplaintStatisticData',
'click #datetimeSubmit': 'searchDateTimeComplaintStatisticData',
},
initialize: function(options) {
console.log('init infoItemList view');
this.now = options.now;
if(this.now.substring(5,7)-1==0){
this.oneMonthAgo = this.now.substring(0,3)+(this.now.substring(3,4)-1+"")+this.now.substring(4,5)+"12"+this.now.substring(7,10);
this.oneMonthAgotime = this.now.substring(0,3)+(this.now.substring(3,4)-1+"")+this.now.substring(4,5)+"12"+this.now.substring(7,16);
}
else if(this.now.substring(5,7)==10){
this.oneMonthAgo = this.now.substring(0,5)+"09"+this.now.substring(7,10);
this.oneMonthAgotime = this.now.substring(0,5)+"09"+this.now.substring(7,16);
}
else{
this.oneMonthAgo = this.now.substring(0,6)+(this.now.substring(6,7)-1+"")+this.now.substring(7,10);
this.oneMonthAgotime = this.now.substring(0,6)+(this.now.substring(6,7)-1+"")+this.now.substring(7,16);
}
},
onRender: function(){
},
onShow: function(){
var startTime = this.oneMonthAgo.substring(0,10);
var endTime = this.now.substring(0,10);
$('#startTime').val(startTime);
$('#endTime').val(endTime);
var startDateTime = this.oneMonthAgotime.substring(0,10)+'T'+this.oneMonthAgotime.substring(11,16);
var endDateTime = this.now.substring(0,10)+'T'+this.now.substring(11,16);
$('#startDateTime').val(startDateTime);
$('#endDateTime').val(endDateTime);
/* this.searchComplaintStatisticData();*/
},
searchDateComplaintStatisticData: function(){
var self = this;
var startTime = $('#startTime').val();
var endTime = $('#endTime').val();
startTime = startTime.substring(0,10);
endTime = endTime.substring(0,10);
/*this.complaintStatisticData = new ComplaintStatisticData();
this.complaintStatisticData.fetch({
data: {"start_time":startTime,"end_time":endTime},
success: function(data){
console.log(data);
self.data = data.toJSON();
self.drawGridColumn();
self.drawExcusePie();
}
});*/
this.statisticByDate = new StatisticByDate();
this.statisticByDate.fetch({
data: {"start_time":startTime,"end_time":endTime},
success: function(data){
console.log(data);
self.data = data.toJSON();
// if(self.data !== null){
if(data.get('data') !== undefined){
self.drawComplaintNum();
}
else{
self.complaintNumWrapper.show(new NoDateView());
}
}
});
this.statisticByGeography = new StatisticByGeography();
this.statisticByGeography.fetch({
data: {"start_time":startTime,"end_time":endTime},
success: function(data){
console.log(data);
self.data = data.toJSON();
if(data.get('data') !== undefined){
self.drawCityComplaint();
}
else{
self.cityComplaintWrapper.show(new NoCityView());
/* $('#nocityResult').html('无法查询得到按行政区统计投诉次数结果');*/
}
/* if(self.data.get('result')=== "-1"){
$('#nocityResult').html("无行政区投诉次数统计结果");
}
else{*/
/* } */
}
});
this.gridStatisticInfoCollection = new GridStatisticInfoCollection();
this.gridStatisticInfoCollection.fetch({
data: {"start_time":startTime,"end_time":endTime},
success: function(data){
console.log(data);
self.gridStatisticWrapper.show(new GridStatisticView());
var a = self.gridStatisticInfoCollection.shift();
if(a !== undefined){
$('#N').html(a.get('N'));
}
else{
$('#N').html("0");
}
self.gridStatisticResultWrapper.show(new GridStatisticInfoCollectionView({
collection: self.gridStatisticInfoCollection
}));
}
});
this.phoneStatisticInfoCollection = new PhoneStatisticInfoCollection();
this.phoneStatisticInfoCollection.fetch({
data: {"start_time":startTime,"end_time":endTime},
success: function(data){
console.log(data);
self.phoneStatisticResultWrapper.show(new PhoneStatisticInfoCollectionView({
collection: self.phoneStatisticInfoCollection
}));
self.phoneStatisticWrapper.show(new PhoneStatisticView());
}
});
this.statisticByPrejudgingReason = new StatisticByPrejudgingReason();
this.statisticByPrejudgingReason.fetch({
data: {"start_time":startTime,"end_time":endTime},
success: function(data){
console.log(data);
self.data = data.toJSON();
if(data.get('excuse_pie') !== undefined){
self.drawPrejudgingReason();
}
else{
self.preJudgingReasonWrapper.show(new NoReasonView());
/* $('#noreasonResult').html('无法查询得到按预判原因统计投诉次数结果');*/
}
}
});
this.stationerrorStatisticInfoCollection = new StationErrorStatisticInfoCollection();
this.stationerrorStatisticInfoCollection.fetch({
data: {"start_time":startTime,"end_time":endTime},
success: function(data){
console.log(data);
self.stationerrorStatisticWrapper.show(new StationErrorStatisticView());
var a = self.stationerrorStatisticInfoCollection.shift();
if(a !== undefined){
$('#N_station').html(a.get('N'));
}
else{
$('#N_station').html("0");
}
self.stationerrorStatisticResultWrapper.show(new StationErrorStatisticInfoCollectionView({
collection: self.stationerrorStatisticInfoCollection
}));
}
});
this.cellperformanceStatisticInfoCollection = new CellPerformanceStatisticInfoCollection();
this.cellperformanceStatisticInfoCollection.fetch({
data: {"start_time":startTime,"end_time":endTime},
success: function(data){
console.log(data);
self.cellperformanceStatisticWrapper.show(new CellPerformanceStatisticView());
var a = self.cellperformanceStatisticInfoCollection.shift();
if(a !== undefined){
$('#N_cell').html(a.get('N'));
}
else{
$('#N_cell').html("0");
}
self.cellperformanceStatisticResultWrapper.show(new CellPerformanceStatisticInfoCollectionView({
collection: self.cellperformanceStatisticInfoCollection
}));
}
});
},
searchDateTimeComplaintStatisticData: function(){
var self = this;
var startDateTime = $('#startDateTime').val();
var endDateTime = $('#endDateTime').val();
startDateTime = startDateTime.substring(0,10)+' '+startDateTime.substring(11,16);
endDateTime = endDateTime.substring(0,10)+' '+endDateTime.substring(11,16);;
this.statisticByDateTime = new StatisticByDateTime();
this.statisticByDateTime.fetch({
data: {"start_time":startDateTime,"end_time":endDateTime},
success: function(data){
console.log(data);
self.data = data.toJSON();
// if(self.data !== null){
/* if(data.get('data') !== undefined){*/
self.drawTimeComplaintNum();
/* }*/
/* else{
self.datecomplaintNumWrapper.show(NoDateTimeView());*/
/* $('#nodateResult').html('无法查询得到按时刻统计投诉次数结果');*/
/* } */
}
});
},
/*drawGridColumn: function(){
$('#gridCharts').highcharts({
chart: {
type: 'column',
margin: [ 50, 70, 50, 70]
},
title: {
text: '根据被投诉次数排列的Top10基站',
verticalAlign: 'top',
},
subtitle: {
// text: 'Source: WorldClimate.com'
},
xAxis: {
categories: this.data.grid_column.categories
},
yAxis: {
min: 0,
title: {
text: '被投诉次数'
}
},
legend: {
enabled: false
},
tooltip: {
pointFormat: '该基站被投诉有: <b>{point.y} 次</b>',
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0,
dataLabels: {
enabled: true
}
}
},
series: [{
name: '',
data: this.data.grid_column.data
}, ],
credits: {
enabled: false
},
});
},
drawExcusePie:function(){
$('#excusePie').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
margin: [ 50, 30, 50, 30]
},
title: {
text: '投诉原因统计饼型图',
align: 'center',
verticalAlign: 'top',
},
tooltip: {
pointFormat: '{series.name}: <b>{point.y}</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
format: '<b>{point.name}</b>: {point.percentage:.1f} %'
}
}
},
series: [{
type: 'pie',
name: '投诉次数',//
data: this.data.excuse_pie
}],
credits: {
enabled: false
},
});
},*/
drawTimeComplaintNum:function(){
$('#cityComplaint').empty();
$('#gridStatistic').empty();
$('#gridStatisticResult').empty();
$('#phoneStatistic').empty();
$('#phoneStatisticResult').empty();
$('#preJudgingReason').empty();
$('#stationerrorStatistic').empty();
$('#stationerrorStatisticResult').empty();
$('#cellperformanceStatistic').empty();
$('#cellperformanceStatisticResult').empty();
$('#complaintNum').highcharts({
title: {
text: '按发生时刻统计投诉次数结果',
x: -20 //center
},
subtitle: {
},
xAxis: {
categories: this.data.categories
},
yAxis: {
title: {
text: '被投诉次数'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
pointFormat: '该时段投诉次数: <b>{point.y} 次</b>',
/*valueSuffix: '次'*/
},
legend: {
enabled: false
/*layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0*/
},
series: [{
name: '',
data: this.data.data
}],
credits: {
enabled: false
},
})
},
drawComplaintNum:function(){
$('#complaintNum').highcharts({
title: {
text: '按日统计投诉次数结果',
x: -20 //center
},
subtitle: {
},
xAxis: {
categories: this.data.categories
},
yAxis: {
title: {
text: '被投诉次数'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
pointFormat: '本日投诉次数: <b>{point.y} 次</b>',
/*valueSuffix: '次'*/
},
legend: {
enabled: false
/*layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0*/
},
series: [{
name: '',
data: this.data.data
}],
credits: {
enabled: false
},
})
},
drawCityComplaint:function(){
$('#cityComplaint').highcharts({
chart: {
type: 'column',
margin: [ 50, 70, 50, 70]
},
title: {
text: '按行政区统计投诉次数结果',
verticalAlign: 'top',
},
subtitle: {
// text: 'Source: WorldClimate.com'
},
xAxis: {
categories: this.data.categories
},
yAxis: {
min: 0,
title: {
text: '被投诉次数'
}
},
legend: {
enabled: false
},
tooltip: {
pointFormat: '该城市投诉次数为: <b>{point.y} 次</b>',
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0,
dataLabels: {
enabled: true
}
}
},
series: [{
name: '',
data: this.data.data
}, ],
credits: {
enabled: false
},
});
},
drawPrejudgingReason:function(){
$('#preJudgingReason').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
margin: [ 50, 30, 50, 30]
},
title: {
text: '按预判原因统计投诉次数结果',
align: 'center',
verticalAlign: 'top',
},
tooltip: {
pointFormat: '{series.name}: <b>{point.y}</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
format: '<b>{point.name}</b>: {point.percentage:.1f} %'
}
}
},
series: [{
type: 'pie',
name: '投诉次数',//
data: this.data.excuse_pie
}],
credits: {
enabled: false
},
});
}
});
return InfoItemListView;
});
<file_sep>define([
'underscore',
'backbone',
'marionette',
"tpl!views/partials/common/common_t/nocity.tpl",
], function(_, Backbone, Marionette, nocityTpl) {
"use strict";
var NoCityView = Marionette.ItemView.extend({
template: nocityTpl,
initialize: function() {
console.log('init nocity view');
},
});
return NoCityView;
});<file_sep>define([
'underscore',
'backbone',
'marionette',
'backbone_modelbinder',
'views/partials/common/header',
'cookie',
"tpl!views/login/login_t/login.tpl",
], function(_, Backbone, Marionette, ModelBinder, HeaderView, Cookie, loginTpl) {
"use strict";
var UserInfo = Backbone.Model.extend({
defaults: {
// "user_name": "asdfas",
// "user_password": "<PASSWORD>",
},
initialize: function(options){
this.urlRoot = 'login.html';
this.url = this.urlRoot;
}
});
var LoginView = Backbone.Marionette.LayoutView.extend({
template: loginTpl,
model: new UserInfo(),
regions: {
header: '#header',
},
events: {
'click #userSubmit': 'postUserInfo',
},
initialize: function(options) {
// this._modelBinder = new Backbone.ModelBinder();
//全局设置请求头,为了保证能够以正确编码方式读取汉字
(function(){
// Store the native, default sync method, we'll wrap this.
Backbone._nativeSync = Backbone.sync;
// Create our default options object
Backbone.defaultSyncOptions = {};
// Ever so gingerly wrap the native sync
// in a method that combines options
Backbone.sync = function( method, model, options) {
Backbone._nativeSync( method, model,
_.extend( {}, Backbone.defaultSyncOptions, options ) );
};
})();
// then just set the options:
Backbone.defaultSyncOptions = { headers: { "Content-Type":"application/json; charset=utf-8",
"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" } };
},
onShow: function(){
this.header.show(new HeaderView());
$('.account').remove();
Cookie.check();
// this._modelBinder.bind(this.model, this.el);
// // 调试modelbinder用
// this.model.bind('change', function () {
// $('#modelData').html(JSON.stringify(this.toJSON()));
// });
// this.model.trigger('change');
},
//现在登录大概思路已经清楚,通过登录页发送数据到后台,返回验证结果
//如果正确则设置cookie,否则重新输入
//在home页判断页面是否有cookie,如果有则读取,否则则跳转到登录页
//现在情况:set、get cookie操作已经ok,每个view页面js代码还没有写
postUserInfo: function(){
var self = this;
this.model.save(
{
user_name: $("#userName").val(),
user_password: $("[password]").val(),
},
{
success: function(data){
if(data.get('result')==1){
var user_name = $("#userName").val();
Cookie.set('username',user_name);
window.close();
window.open('#home');
// window.location.assign('#home');
// Backbone.history.navigate('home', {trigger: true});
console.log(data);}
else{
// Cookie.check();
alert(data.get('text'));
// console.log('success');
}
},
error: function(data){
console.log('11');
// window.location.assign('#home');
// self.setCookie('username','liuwei',7);
// Cookie.set('user','liuwei',7);
// self.checkCookie('username');
alert("通信失败,请您检查网络连接!");
}
// wait:true
});
},
});
return LoginView;
});
// url=jdbc:mysql://192.168.88.180:3306/dianx //之前连接的数据库地址
<file_sep>define([
'underscore',
'backbone',
'marionette',
"tpl!views/partials/common/common_t/gridStatistic.tpl",
], function(_, Backbone, Marionette, gridStatisticTpl) {
"use strict";
var GridStatisticView = Marionette.ItemView.extend({
template: gridStatisticTpl,
initialize: function() {
console.log('init gridStatistic view');
},
});
return GridStatisticView;
});<file_sep>package mysql;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.rmi.ConnectIOException;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class ImportPreJudgeCause {
private static String FilePath = "D:\\FEFJay\\myEclipseWorkSpace\\TS\\src\\mysql\\PreJudgeCause.txt";
/**这个类是为了导入投诉预判的6个子项标签和主辅原因的对应关系编码
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
Map<Integer, String> oriMap = new HashMap<Integer, String>();
System.out.println("Reading file...");
oriMap = loadFile();
System.out.println("读取到"+oriMap.size()+"行origMap="+oriMap);
Map<Integer, ArrayList<String>> tempMap = new HashMap<Integer, ArrayList<String>>();
tempMap = fillMap(oriMap);
System.out.println("把空内容赋值为noItem后新的集合"+tempMap.size()+"行tempMap="+tempMap);
insertData(tempMap);
}
//插入数据库
private static void insertData(Map<Integer, ArrayList<String>> tempMap) throws FileNotFoundException, IOException {
if (tempMap == null || tempMap.isEmpty()) {
return;
}
System.out.println("执行插入数据操作!");
String sql = "insert into dict_cause(geogCell,alarms,netPerf,callEvent,callQuality,callDis,mainCause,secCause,main_secCause) values ";
String insertSQl = "";
for (int i = 0; i < tempMap.size(); i++) {
ArrayList<String> list = tempMap.get(i);
String[] lineArray = new String[8];
list.toArray(lineArray);
String[] c = code(lineArray);
showArray(c);
System.out.println(i);
insertSQl += "("+Integer.parseInt(c[0])+","+Integer.parseInt(c[1])+","+Integer.parseInt(c[2])+","+Integer.parseInt(c[3])+","+Integer.parseInt(c[4])
+","+Integer.parseInt(c[5])+","+Integer.parseInt(c[6])+","+Integer.parseInt(c[7])+","+Integer.parseInt(c[6]+c[7])+"),";
}//end of for
sql += insertSQl;
sql = sql.substring(0,sql.length()-1);
System.out.println("sql="+sql);
mysql_DML dml = new mysql_DML();
Connection con = dml.myConnection();
String f=dml.insertdata(sql, con);
if (f.length() > 0) {
System.out.println("success:插入成功!");
} else {
System.out.println("error:插入错误!");
}
}
//导入源文件
public static Map<Integer, String> loadFile() throws IOException{
Map<Integer, String> oriMap = new HashMap<Integer, String>();
FileReader fReader = new FileReader(new File(FilePath));
BufferedReader reader = new BufferedReader(fReader);
String line = reader.readLine();
int index = 0;
while (line!= null) {
oriMap.put(index++, line);
line = reader.readLine();
}
return oriMap;
}
//把空的内容转为noItem
public static Map<Integer, ArrayList<String>> fillMap(Map<Integer, String> oriMap) throws IOException{
Map<Integer, ArrayList<String>> tempMap = new HashMap<Integer, ArrayList<String>>();
Set<Integer> it = oriMap.keySet();
int key = 0;
for (Integer integer : it) {
ArrayList<String> lineList = new ArrayList<String>();
String[] array = new String[8];
array = oriMap.get(integer).split("\t");
// System.out.print("array大小="+array.length+":");
// showArray(array);
for (String string : array) {
if (string == null || string.isEmpty()) {
lineList.add("noItem");
}else {
lineList.add(string);
}
}
if (lineList.size() == 7) {
lineList.add("noItem");
}
// System.out.println("读取到lineList="+lineList);
tempMap.put(key++, lineList);
}
return tempMap;
}
//打印字符串数组
public static void showArray(String[] o){
//System.out.println();
for (String object : o) {
if (object == null || object.isEmpty()) {
System.out.print(" * ");
} else {
System.out.print(object+" ");
}
}
System.out.println();
}
//编码函数,把中文编码为数字
public static String[] code(String[] lineArray){
if (lineArray == null || lineArray.length == 0) {
System.out.println("error:需要编码的行为空!");
return null;
}
if (lineArray.length != 8) {
System.out.println("error:需要编码的行数不为8!");
return null;
}
//原始的6个子项标签类型
String [][] o = {{"RICH","POOR"},
{"WEAK","HEALTH"},
{"rssi","block","SLEEP","GOOD"},
{"nocall","normal","abnormal_ecp","abnormal_user","abnormal_other"},
{"noItem","thin","thick"},
{"noItem","onedge","inside"},
{"noItem","维护","网优","核心侧","用户侧","建设","无明显异常"},
{"noItem","维护","网优","核心侧","用户侧","建设","无明显异常"}};
String[] codeLine = new String[lineArray.length];
String word = "";
for (int i = 0; i < lineArray.length; i++) {
word = lineArray[i];
for (int j = 0; j < o[i].length; j++) {
if (word.equals(o[i][j])) {
if (i==0 || i==1 ||i==2) {
codeLine[i] = (i+1)+"0"+(j+1);
} else if(i==3||i==4||i==5){
codeLine[i] = (i+1)+"0"+j;
}else {
codeLine[i] = ""+j;
}
}
}
}
return codeLine;
}
}
<file_sep>package com.system.main;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import mysql.mysql_DML;
import com.related.alarms.QueryAlarms;
import com.related.calls.QueryCalls;
import com.related.cells.QueryCallCells;
import com.related.cells.QueryLonLatCells;
import com.related.grids.QueryGrids;
import com.related.perf.QueryPerf;
import com.user.complain.ComplaintInfo;
public class SysProcessController {
private static Logger logger = Logger.getLogger(SysProcessController.class);
/**********************************************************************************************************
* 方法名:systemProcess 功能:用于控制整个后台系统程序流程,调用话单和地理路线的函数进行处理
* 传入参数:该次投诉的编号record_id,以及数据库连接参数
* 返回值:布尔值变量,标记系统处理情况,无话单无经纬度则为false,否则只要有经纬度或者有话单都是true
* 其他说明:该方法调用系统函数的执行,包括数据库的操作等。然后根据返回值情况处理点灯的流程。 Author:JayLi
*
* @throws ParseException
* @throws SQLException
* @throws ClassNotFoundException
* @throws IOException
* @throws FileNotFoundException
****************************************************************************************************/
public boolean systemProcess(String record_id, mysql_DML dml,Connection conn) throws FileNotFoundException, IOException,
ClassNotFoundException, SQLException, ParseException {
logger.info("进入系统流程控制函数systemProcess...");
boolean isCorrect = false; // 标记系统处理情况,无话单无经纬度则为false,否则只要有经纬度或者有话单都是true
boolean geogFlag = false; // 标记有无经纬度处理流程,有则true,无则false
boolean callFlag = false; // 标记有无话单处理流程,有则true,无则false
// ---------------------------------------------地理路线------------------------------------------------------
logger.info("进入地理路线...");
String sqlString = "select call_lon, call_lat from pre_deal_records where record_id = "
+ Integer.parseInt(record_id);
ArrayList<String> arrayList = dml.selectMysql(sqlString, conn); // arrayList一定不会为空或者无数据,因为数据库默认这两列值是0
double call_lon = Double.parseDouble(arrayList.get(0).split("\t")[0]);
double call_lat = Double.parseDouble(arrayList.get(0).split("\t")[1]);
if (arrayList != null && !arrayList.isEmpty() && call_lat != 0
&& call_lon != 0) { // 有地理经纬度输入
geogFlag = true;
// 1.地理路线关联小区
long T1 = System.currentTimeMillis();
QueryLonLatCells rCells1 = new QueryLonLatCells();
HashMap<String, String> cellMap = rCells1.findRelatedCellsByLonLat(
record_id, dml, conn);
long T2 = System.currentTimeMillis();
System.out.println("地理路线调用rCells.findRelatedCellsByLonLat耗时="
+ (T2 - T1) / 1000.0 + "s");
if (cellMap != null && cellMap.size() != 0) {// 有经纬度,也找到了关联小区
geogFlag = true; // 标记是有经纬度,有地理小区的处理
boolean flagCell = rCells1.insertRelatedCellsByLonLat(
record_id, cellMap, dml, conn);
long T3 = System.currentTimeMillis();
System.out.println("地理路线调用rCells.insertRelatedCellsByLonLat耗时="
+ (T3 - T2) / 1000.0 + "s");
if (flagCell) {
logger.info("success:成功查找地理关联小区!");
} else {
logger.info("error:查找地理关联小区失败!");
}
// 2.地理路线关联栅格
QueryGrids rGrids1 = new QueryGrids();
long T4 = System.currentTimeMillis();
ArrayList<String> relatedGrid = rGrids1.findGridByLocation(
record_id, dml, conn);
long T5 = System.currentTimeMillis();
System.out.println("地理路线调用rGrids.findGridByLocation耗时="
+ (T5 - T4) / 1000.0 + "s");
if (relatedGrid != null && relatedGrid.size() != 0) {
rGrids1.insertRelatedGrid(record_id, relatedGrid, dml, conn);
long T6 = System.currentTimeMillis();
System.out.println("地理路线调用rGrids.insertRelatedGrid耗时="
+ (T6 - T5) / 1000.0 + "s");
logger.info("success:成功找到关联栅格!");
} else {
logger.info("error:根据地理经纬度查找关联栅格失败!");
}
} else { // 有经纬度,但是找不到关联小区
geogFlag = false;
// 有经纬度,但是找不到关联小区,更新标签结果表为poor值102
dml.updatedata("update pre_judge_label set geogCell=102 where record_id = "
+ Integer.parseInt(record_id));
}
} else { // 无地理经纬度输入
geogFlag = false;
// 无经纬度,更新标签结果表为rich值101
dml.updatedata("update pre_judge_label set geogCell=101 where record_id = "
+ Integer.parseInt(record_id));
}
// --------------------------------------------话单路线----------------------------------------------------
logger.info("话单查询...");
QueryCalls rCalls = new QueryCalls();
ArrayList<Map<String, String>[]> callMaps = new ArrayList<Map<String, String>[]>();// 存放查pcmd数据库的结果
long t2 = System.currentTimeMillis();
callMaps = rCalls.queryRealatedCalls(record_id, dml, conn);
long t3 = System.currentTimeMillis();
System.out.println("查询关联话单: " + (t3 - t2) + "ms");
logger.info("calMaps: " + callMaps.size());
int len = 0;
for (Map<String, String>[] a : callMaps) {
if (a.length > 0) {
len = a.length;
break;
}
}
if (len > 0) {// 有话单
callFlag = true;
long t4 = System.currentTimeMillis();
// 1.插入话单
String rString = rCalls.insertRelatedCallsRs(record_id, dml, conn,
callMaps);
long t5 = System.currentTimeMillis();
System.out.println("插入关联话单: " + (t5 - t4) + "ms");
if (!rString.equals("success")) {
logger.info("插入关联话单信息失败 ");
callFlag = false;
}
// 2.插入话单小区
QueryCallCells rCells = new QueryCallCells();
ArrayList<String> cell_list = new ArrayList<String>();// 关联小区结果列表
long t6 = System.currentTimeMillis();
cell_list = rCells.queryRelatedCellsPCMD(record_id, dml, conn);// 关联小区分析查询
long t7 = System.currentTimeMillis();
System.out.println("关联小区分析: " + (t7 - t6) + "ms");
long t8 = System.currentTimeMillis();
String cString = rCells.insertRelatedCellsRsPCMD(record_id, dml,
conn, cell_list);// 插入关联小区到数据库
long t9 = System.currentTimeMillis();
System.out.println("插入关联小区: " + (t9 - t8) + "ms");
} else { // 无话单
callFlag = false;
// 无话单,更新标签结果表里与话单关联的三个字段
dml.updatedata("update pre_judge_label set callEvent=405,callQuality=500,callDis=600 where record_id="
+ Integer.parseInt(record_id));
}
// ----------------------------------------------综合地理和话单路线----------------------------------------------------
// 根据有无地理经纬度、有无话单,得出系统流程的最终结果
if (geogFlag || callFlag) { // 有地理经纬度,或者有话单,则一定有关联小区处理结果,此时可以查故障和性能
isCorrect = true;
// 查询related_cells表得到话单和地理路线去重后的小区列表
String cellString = "SELECT DISTINCT ecp, bts,cell,location FROM related_cells WHERE record_id = "
+ Integer.parseInt(record_id);
ArrayList<String> cellArrayList = dml.selectMysql(cellString, conn);
if (cellArrayList.isEmpty()) {
logger.info("没有关联小区!故障和性能信息终止查询!");
// 没有调用告警和性能查询函数,需要把标签结果补插进去
dml.updatedata("update pre_judge_label set alarms=202,BSPerf=304 where record_id="
+ Integer.parseInt(record_id));
} else {
logger.info("有关联小区!故障和性能信息开始查询...");
// 基站故障查询
QueryAlarms rAlarms = new QueryAlarms();
String alarmString = rAlarms.queryRelatedAlarms(record_id, dml,
conn, cellArrayList);// 关联小区故障分析
// 基站性能查询
QueryPerf rPerf = new QueryPerf();
String perfString = rPerf.queryRelatedPerf(record_id, dml,
conn, cellArrayList);// 关联小区性能分析
}
} else { // 无经纬度,且无话单
isCorrect = false;
// 没有调用告警和性能查询函数,需要把标签结果补插进去
dml.updatedata("update pre_judge_label set alarms=202,BSPerf=304 where record_id="
+ Integer.parseInt(record_id));
}
logger.info("退出系统流程控制函数!");
return isCorrect;
}
/**
* @param args
* @throws ParseException
* @throws SQLException
* @throws IOException
* @throws ClassNotFoundException
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException,
ClassNotFoundException, IOException, SQLException, ParseException {
mysql_DML dml = new mysql_DML();
Connection conn = dml.myConnection();
SysProcessController sController = new SysProcessController();
boolean f = sController.systemProcess("942", dml, conn);
System.out.println(f);
}
}
<file_sep>package pre_deal;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import service.GridService;
@Controller
public class SystemSettingGetInfo {
@Autowired
private static Logger logger = Logger.getLogger(SystemSettingGetInfo.class);
private GridService gridService;
private String search_r;
private String search_t;
private String init_lon;
private String init_lat;
public static String TCpath = MyFilePath.TCPropertiesPath;
public void initParam(String paramFile) throws FileNotFoundException, IOException
{
Properties props = new Properties();
props.load(new FileInputStream(paramFile));
search_r = props.getProperty("search_r");
search_t = props.getProperty("search_t");
init_lon = props.getProperty("init_lon");
init_lat = props.getProperty("init_lat");
}
// **1. 获取前一次的系统参数,即默认值
@RequestMapping(value = "/getting_parameters", method = RequestMethod.GET, produces = "charset=utf-8")
@ResponseBody
public String getting_parameters(HttpServletRequest request,HttpServletResponse response) throws IOException{
logger.info("进入获取系统参数函数setting_parameters");
Properties props = new Properties();
props.load(new FileInputStream(TCpath));
String relatedCellCount= props.getProperty("cellDensityThreshold");
String relatedCellDistance = props.getProperty("search_r");
String errorSearchTime = props.getProperty("alarm_timerange");
String PCMASearchTime = props.getProperty("search_t");
String ECIOThinThreshold = props.getProperty("ECIOThinThreshold");
int PCMDHour = Integer.parseInt(PCMASearchTime) / 3600; //把秒转为小时
int alarmHour = Integer.parseInt(errorSearchTime) / 3600; //把秒转为小时
JSONObject jResult = new JSONObject();
jResult.put("relatedCellCount",relatedCellCount);
jResult.put("relatedCellDistance",relatedCellDistance);
jResult.put("errorSearchTime", alarmHour);
jResult.put("PCMASearchTime",PCMDHour);
jResult.put("ECIOThinThreshold",ECIOThinThreshold);
logger.info("获取系统参数jResult="+jResult.toString());
logger.info("退出获取系统参数函数setting_parameters");
return jResult.toString();
}
}
<file_sep>package com.homer.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import com.homer.bean.BaseResp;
import com.homer.bean.ComplaintObj;
import com.homer.bean.QueryComplaintResp;
import com.homer.dao.DBManager;
/*
* 获取基本投诉信息
* */
public class QueryServletOld extends BaseServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
super.doGet(req, resp);
PrintWriter pw=resp.getWriter();
BaseResp bean=null;
String result=null;
String index=req.getParameter("index");
String number=req.getParameter("number");
String tel=req.getParameter("tel");
try {
result=query(index,number,tel);
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
bean=new BaseResp(-1, e.getMessage());
result=JSONObject.fromObject(bean).toString();
}finally{
pw.write(result);
pw.flush();
pw.close();
try {
DBManager.getInstance().disConnect();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private String query(String tel) throws ClassNotFoundException, SQLException{
String sql="SELECT * FROM complaint_records WHERE complaint_tele_num="+tel+" ORDER BY complaint_id DESC";
ResultSet rs=DBManager.getInstance().executeQuery(sql);
ArrayList<ComplaintObj> data=new ArrayList<ComplaintObj>();
ComplaintObj obj=null;
Timestamp time=null;
Date date = null;
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
while(rs.next()){
time = rs.getTimestamp("complaint_time");
date = new Date(time.getTime());
obj = new ComplaintObj();
obj.setId(rs.getInt("complaint_id"));
obj.setDatetime(sdf.format(date));
obj.setLoc(rs.getString("complaint_area"));
obj.setType(rs.getInt("complaint_type"));
obj.setTypeWord(rs.getInt("complaint_type"));
obj.setState(rs.getInt("deal_result"));
obj.setStateWord(rs.getInt("deal_result"));
data.add(obj);
}
QueryComplaintResp resp = new QueryComplaintResp(0, "ok", data);
return JSONObject.fromObject(resp).toString();
}
private String query(String index, String number, String tel)
throws ClassNotFoundException, SQLException
{
String sql = (new StringBuilder("SELECT * FROM complaint_records WHERE complaint_tele_num=")).append(tel).append(" ORDER BY complaint_id DESC LIMIT ").append(index).append(",").append(number).toString();
ResultSet rs = DBManager.getInstance().executeQuery(sql);
ArrayList<ComplaintObj> data = new ArrayList();
ComplaintObj obj = null;
Timestamp time = null;
Date date = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
while(rs.next())
{
time = rs.getTimestamp("complaint_time");
date = new Date(time.getTime());
obj = new ComplaintObj();
obj.setId(rs.getInt("complaint_id"));
obj.setDatetime(sdf.format(date));
obj.setLoc(rs.getString("complaint_area"));
obj.setType(rs.getInt("complaint_type"));
obj.setTypeWord(rs.getInt("complaint_type"));
obj.setState(rs.getInt("deal_result"));
obj.setStateWord(rs.getInt("deal_result"));
data.add(obj);
}
QueryComplaintResp resp = new QueryComplaintResp(0, "ok", data);
return JSONObject.fromObject(resp).toString();
}
}
<file_sep>package com.homer.bean;
import java.util.ArrayList;
public class QueryComplaintResp extends BaseResp{
private ArrayList<ComplaintObj> data;
public QueryComplaintResp(int result, String text,
ArrayList<ComplaintObj> data) {
super(result, text);
this.data = data;
}
public ArrayList<ComplaintObj> getData() {
return data;
}
public void setData(ArrayList<ComplaintObj> data) {
this.data = data;
}
}
<file_sep>driver=com.mysql.jdbc.Driver
url=jdbc:mysql://192.168.0.11:3306/dianx?useUnicode=true&characterEncoding=utf8
user=whcsj
pass=<PASSWORD>
<file_sep>define([
'backbone'
], function(Backbone) {
"use strict";
var GridStatisticInfo = Backbone.Model.extend({
});
return GridStatisticInfo;
});<file_sep>driver=com.mysql.jdbc.Driver
#url=jdbc:mysql://192.168.0.11:3306/dianx
url=jdbc:mysql://localhost:3306/dianx
user=root
pass=<file_sep>'use strict';
var ASSETS_DIR = './assets/';
var UGLIFY_BANNER = '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %> - ' +
'Author: <%= pkg.author %> */\n\n';
var PATHS = {
tplAll: 'application/views/templates/**/*.tpl',
lessAll: ASSETS_DIR + 'less/**/*.less',
lessCompile: [ASSETS_DIR + 'less/app.less', ASSETS_DIR + 'less/common.less'],
lessDir: ASSETS_DIR + 'less',
css: ASSETS_DIR + 'css/*.css',
cssDir: ASSETS_DIR + 'css/',
jsAll: [
ASSETS_DIR + 'scripts/**/*.js',
'!' + ASSETS_DIR + 'scripts/require.js',
'!' + ASSETS_DIR + 'scripts/lib/**/*.js'
],
cssImagesDir: ASSETS_DIR + 'css/images/'
};
var gulp = require('gulp'),
plugins = require('gulp-load-plugins')(),
stylish = require('jshint-stylish'),
browserSync = require('browser-sync'),
util = require('./config/util'),
path = require('path');
/* 开发相关任务 */
// JS代码检查
gulp.task('jshint', function() {
return gulp.src(PATHS.jsAll)
.pipe(plugins.jshint())
.pipe(plugins.jshint.reporter(stylish));
});
// 浏览器自动同步代码
gulp.task('browser-sync', function() {
browserSync({
proxy: {
host: 'localhost/aibishe'
}
// files: [PATHS.lessAll, PATHS.jsAll]
});
});
gulp.task('bs-reload', function () {
browserSync.reload();
});
// 监视文件变化
gulp.task('watch', function () {
gulp.watch(PATHS.lessAll, ['less']);
gulp.watch(PATHS.jsAll, ['bs-reload']);
gulp.watch(PATHS.tplAll, ['bs-reload']);
});
// 编译LESS
gulp.task('less', function () {
return gulp.src(PATHS.lessCompile, {base: PATHS.lessDir})
.pipe(plugins.less().on('error', plugins.util.log))
.pipe(gulp.dest(PATHS.cssDir))
.pipe(browserSync.reload({stream: true}));
});
gulp.task('sprite', function() {
// 合并雪碧图的目录
var category = ['common'];
category.forEach(function(name) {
gulp.src(PATHS.cssImagesDir + name + '/*.png')
.pipe(plugins.spritesmith({
imgPath: 'sprites/' + name + '_sprite.png',
imgName: name + '_sprite.png',
cssName: name + '_sprite.css',
padding: 2,
cssOpts: {
cssSelector: function(item) {
return util.cssClassFilter(name, item);
}
}
}))
.pipe(gulp.dest(PATHS.cssDir + 'sprites'));
});
});
/* 开发相关任务end */
gulp.task('default', ['jshint', 'less', 'browser-sync', 'watch'], function() {
// gulp.watch(PATHS.lessAll, ['less']);
// gulp.watch(PATHS.jsAll, ['bs-reload']);
});
<file_sep>define(['backbone',
'models/grid_statistic_info',
],
function(Backbone, GridStatisticInfo) {
var GridStatisticInfoCollection = Backbone.Collection.extend({
model: GridStatisticInfo,
initialize: function(options){
this.urlRoot = 'statistic_by_geography_TOPN.html';
this.url = this.urlRoot;
}
});
return GridStatisticInfoCollection;
});<file_sep>define([
'underscore',
'backbone',
'marionette',
'collection/complaint_item_collection',
"tpl!views/partials/common/common_t/infoItemSearch.tpl",
"tpl!views/partials/search/search_t/complaintItem.tpl",
"tpl!views/partials/search/search_t/complaintItemTitle.tpl",
"tpl!views/partials/search/search_t/noChildMessage.tpl",
], function(_, Backbone, Marionette, ComplaintItemCollection,
infoItemSearchTpl, complaintItemTpl, complaintItemTitleTpl, noChildMessageTpl) {
"use strict";
var EmptyView = Backbone.Marionette.ItemView.extend({
template: noChildMessageTpl,
});
var ComplaintItemView = Backbone.Marionette.ItemView.extend({
tagName: "li",
className: "info-wrapper clearfix",
template: complaintItemTpl,
triggers:{
"click #itemDetail": "itemDetail"
},
});
var ComplaintItemCollectionView = Backbone.Marionette.CollectionView.extend({
tagName: 'ul',
className: "info-list clearfix",
childView: ComplaintItemView,
emptyView: EmptyView,
complaintItemTitle: complaintItemTitleTpl,
onShow: function(){
if(this.collection.length!==0){
this.count = this.collection.toJSON()[0].count;
this.$el.prepend(this.complaintItemTitle);
this.$el.find('#complaintCount').html(this.count);
}
},
});
var InfoItemSearchView = Backbone.Marionette.LayoutView.extend({
template: infoItemSearchTpl,
events:{
"click #searchButton": "searchComplaintItem",
},
regions:{
complaintListRegion: "#complaintItemList"
},
initialize: function(options) {
console.log('init infoItemSearch view');
},
onShow: function(){
console.log(this.model.toJSON());
var searchText;
$('#startTime').val(this.model.get('start_time'));
$('#endTime').val(this.model.get('end_time'));
//页面默认显示Model中的信息
if(this.model.get('search_type')==="station"){
$('[href=#station]').tab('show');
searchText = this.model.get('search_text').split(',');
$('#ECP').val(searchText[0]);
$('#BTS').val(searchText[1]);
}
else if(this.model.get('search_type')==="longlat"){
$('[href=#longlat]').tab('show');
searchText = this.model.get('search_text').split(',');
$('#longitude').val(searchText[0]);
$('#latitude').val(searchText[1]);
$('#radius').val(searchText[2]);
}
else{
$('[href=#phone]').tab('show');
$('#phoneNumber').val(this.model.get('search_text'));
}
//默认执行查询,如果searchText没有值,则后台返回最新的投诉信息
//this.searchComplaintItem();
},
//执行查询操作
searchComplaintItem: function(){
var self = this;
//判读search_type,并取到相应searchText
var searchType = $('.search-text .nav .active').attr("value");
var searchText;
if (searchType === "phone"){
searchText = $('#phoneNumber').val();
}
else if (searchType === "station"){
searchText = $('#ECP').val() + ',' + $('#BTS').val();
}
else if (searchType === "longlat"){
searchText = $('#longitude').val() + ',' + $('#latitude').val()+ ',' + $('#radius').val();
}
//读取时间
var startTime, endTime;
startTime = $('#startTime').val();
endTime = $('#endTime').val();
//传递查询输入数据到home.js,防止再次进入查询页面输入数据丢失
this.model.set('search_type',searchType);
this.model.set('search_text',searchText);
this.model.set('start_time',startTime);
this.model.set('end_time',endTime);
this.trigger('passSearchInfo',this.model);
//更改时间格式,以便按照接口要求给后台争取的时间格式
startTime = startTime.substring(0,10)+' '+startTime.substring(11,16);
endTime = endTime.substring(0,10)+' '+endTime.substring(11,16);
this.complaintItemCollection = new ComplaintItemCollection();
//page做分页用
this.page = 1;
this.data = {"search_type":searchType,"search_text":searchText,
"start_time":startTime, "end_time":endTime, "page":this.page};
//获取查询到的投诉信息
this.complaintItemCollection.fetch({
data: self.data,
success: function(data){
console.log(data);
self.complaintItemCollectionView = new ComplaintItemCollectionView({
collection: self.complaintItemCollection
});
self.complaintListRegion.show(self.complaintItemCollectionView);
//点击“查看详情”按钮触发
self.complaintItemCollectionView.on('childview:itemDetail', function(args){
self.trigger('getItemDetail',args,self.model);
});
$('#searchType').html(self.model.get('search_type'));
$('#searchText').html(self.model.get('search_text'));
$('#startClock').html(startTime);
$('#endClock').html(endTime);
self.displayMore();
},
// error: function(data,resp,options){
// alert(resp.responseText);
// }
});
},
//“加载更多”按钮的功能
displayMore: function(){
var self = this;
this.count = this.complaintItemCollection.toJSON()[0].count;
this.pageCount = Math.ceil(this.count/10);
if(this.pageCount>1){
$('#displayMore').show();
}
$('#displayMore').on('click',function(){
self.page++;
if(self.page<=self.pageCount){
var complaintItemPage = new ComplaintItemCollection();
self.data.page = self.page;
complaintItemPage.fetch({
data: self.data,
success: function(data){
self.complaintItemCollection.add(data.models);
self.complaintItemCollectionView.render();
},
error: function(data,resp,options){
alert(resp.responseText);
}
});
if(self.page==self.pageCount){
$('#displayMore').hide();
}
}
else{
$('#displayMore').hide();
}
});
}
});
return InfoItemSearchView;
});
<file_sep>define([
'underscore',
'backbone',
'marionette',
'cookie',
"tpl!views/partials/common/common_t/header.tpl",
], function(_, Backbone, Marionette, Cookie, headerTpl) {
"use strict";
var HeaderView = Marionette.ItemView.extend({
template: headerTpl,
events: {
// "click #logout": "logOut",
},
initialize: function() {
console.log('init header view');
},
onShow: function(){
$("#logout").click(function(){
Cookie.clear('username');
window.close();
window.open('#login');
});
}
// logOut:function(){
// Cookie.clear('username');
// window.close();
// window.open('#login');
// }
});
return HeaderView;
});
<file_sep>package com.related.alarms;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;
import mysql.mysql_DML;
import org.apache.log4j.Logger;
import com.sys.util.MyFilePath;
public class QueryAlarms{
private static Logger logger = Logger.getLogger(QueryAlarms.class);
private String search_r;
private String search_t;
private String init_lon;
private String init_lat;
private String alarm_timerange;
private String AlarmLevel;
private String range_type;
private int alarm_rsCode = 10;
private int alarm_rsColorCode = 20;
private int alarm_rsnum = 0;
public static String path = MyFilePath.TCPropertiesPath;
public int getAlarm_rsCode() {
return alarm_rsCode;
}
public void setAlarm_rsCode(int alarm_rsCode) {
this.alarm_rsCode = alarm_rsCode;
}
public int getAlarm_rsColorCode() {
return alarm_rsColorCode;
}
public void setAlarm_rsColorCode(int alarm_rsColorCode) {
this.alarm_rsColorCode = alarm_rsColorCode;
}
public int getAlarm_rsnum() {
return alarm_rsnum;
}
public void setAlarm_rsnum(int alarm_rsnum) {
this.alarm_rsnum = alarm_rsnum;
}
public void initParam(String paramFile) throws FileNotFoundException, IOException{
Properties props = new Properties();
props.load(new FileInputStream(paramFile));
search_r = props.getProperty("search_r");
search_t = props.getProperty("search_t");
alarm_timerange = props.getProperty("alarm_timerange");
range_type = props.getProperty("range_type");
AlarmLevel = props.getProperty("alarmlevel");
}
/*
* 函数名:queryRelatedAlarmsPCMD
* 参数:record_id dml conn
* 返回值:list
* 功能:根据关联小区列表查询出该关联小区的故障信息并插入数据库
* Author:yl
* UpdateDate:2015/8/28
*/
public String queryRelatedAlarms(String record_id, mysql_DML dml, Connection conn, ArrayList<String> cell_list)
throws FileNotFoundException, IOException, ClassNotFoundException, SQLException, ParseException{
logger.info("调用queryRelatedAlarmsPCMD函数");
long t7 = System.currentTimeMillis();
initParam(path);
if (cell_list == null) {
logger.info("在im_cell_info中查询结果为空");
return "error";
}
//查询pre_deal_record表获得问题发生时间和当前时间
String sql_pre_deal_record = "select call_time ,complaint_time from pre_deal_records where record_id = " + Integer.parseInt(record_id)+ " limit 0, 1";
logger.info("查询pre_deal_record的语句: " + sql_pre_deal_record);
ArrayList<String> list = dml.selectMysql(sql_pre_deal_record, conn);
if (list.isEmpty()) {
logger.info("没有该投诉信息!");
return "没有该投诉信息!请核对后查询。";
}
String ca_time = list.get(0).split("\t")[0];//问题时间
String com_time = list.get(0).split("\t")[1];//当前时间
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sd1 = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
SimpleDateFormat sd2= new SimpleDateFormat("yyyy-MM-dd HH:59:59");
String call_time = sd.format(sd.parse(ca_time));
String curr_time = sd.format(sd.parse(com_time));
long time_stamp = sd.parse(call_time).getTime()/1000 - (Long.parseLong(alarm_timerange) / 3600 - 1) * 3600;//问题发生时间的前N-1小时的时间戳
long time_stamp1 = sd.parse(call_time).getTime()/1000;
Date time =new Date(time_stamp * 1000);
Date time1 =new Date(time_stamp1 * 1000);
String time_before = sd1.format(time);
String time_after = sd2.format(time1);
//----------------------------------获取关联小区列表----------------------------------------
int alarm_rsnum = 0;//故障信息数目
int max_code = 0;//记录alarm_code最大值,便于确定alarm_rscode
int i = 1;
int count = 0;
String insert_related_alarms = "insert into related_alarms(record_id,call_time,curr_time,query_range,ecp,bts,cell," +
"location,alarm_type,alarm_start_time,alarm_clear_time,alarm_code,specific_problem,alarmtext,alarmlevel) VALUES ";
//有关联小区信息,根据结果查询该小区的故障告警信息
System.out.println("小区总数是="+cell_list.size());
for (String s:cell_list){
int ecp = Integer.parseInt(s.split("\t")[0]);
int bts = Integer.parseInt(s.split("\t")[1]);
int cell = Integer.parseInt(s.split("\t")[2]);
String location = s.split("\t")[3];
//获取这个关联小区所在的城市
ArrayList<String> cityList = dml.selectMysql("select city from im_cell_info where bts=" + bts + " and ecp = " +ecp + " and cell = " + cell, conn);
if (cityList.isEmpty()) {
logger.info("error:根据ecp="+ecp+" and bts="+bts+" and cell="+cell+"无法确定其所在城市!");
continue;
}
String city = cityList.get(0).split("\t")[0];
if (city.equals("武汉")) { //基站故障表里面的“武汉”分为多个局,还要根据ecp细分
switch (ecp) {
case 4: city = "武汉12局"; break;
case 5: city = "武汉13局"; break;
case 11: city = "武汉1局"; break;
case 12: city = "武汉2局"; break;
default: break;
}
}
if (city.equals("天门") || city.equals("潜江") || city.equals("仙桃")){//基站故障表里没有“天门/潜江/仙桃”,只有他们对应的江汉,要转化
city = "江汉";
}
logger.info("根据关联小区ecp=" + ecp + ",cityname=" + city + "查找relatedAlarms可以准确匹配故障!");
//根据城市名称和bts查询基站的故障,按更新时间降序排序
String sql_im_hw_alarms2 = "select * from (select * from im_hw_alarms WHERE equipname=" + bts + " and cityname = '" + city+ "'"
+ " and update_date between '" + time_before + "' and '" + time_after + "' ORDER BY update_date DESC ) im_hw_alarms";
logger.info("查找第"+i+"个话单关联小区故障的sql语句="+sql_im_hw_alarms2);
ArrayList<String> alarmlist2 = dml.selectMysql(sql_im_hw_alarms2, conn);
if (alarmlist2.isEmpty()) {
logger.info("故障表中查询结果为空");
max_code = 10;
continue;
}
logger.info("找到第"+(i)+"个话单关联小区故障="+alarmlist2);
for (String string2 : alarmlist2) {//同一个小区可能有多个故障
String [] alarmarray2 = string2.split("\t");
String alarm_cleartime = alarmarray2[13];//故障清除时间
String specific_problem2 = alarmarray2[30];//故障内容
String alarm_level2 = alarmarray2[8];//告警级别
String alarm_type2 = alarmarray2[16];//故障类型
int alarm_code = 10;
if(!(alarm_level2.equals(AlarmLevel)) && !(alarm_type2.equals("EQUIPMENT_MALFUNCTION"))){
alarm_code = 20;
}
//根据“城市+bts”查找im_hw_alarms,获取最新的一条故障信息,按故障时间升序
String sql_im_hw_alarms1 = "select * from (select * from im_hw_alarms WHERE equipname=" + bts + " and cityname = '" + city+ "'"
+ " and update_date between '" + time_before + "' and '" + time_after + "' ORDER BY starttime ASC ) im_hw_alarms";
logger.info("查找第"+i+"个话单关联小区故障的sql语句="+sql_im_hw_alarms1);
ArrayList<String> alarmlist1 = dml.selectMysql(sql_im_hw_alarms1, conn);
if (alarmlist1.isEmpty()) {
logger.info("故障表中查询结果为空");
max_code = 10;
continue;
}
logger.info("找到第"+(i)+"个话单关联小区故障="+alarmlist1);
for (String string : alarmlist1) {
String [] alarmarray = string.split("\t");
int id = Integer.parseInt(record_id);
int query_range = Integer.parseInt(alarm_timerange) / 3600;//查询时间范围,小时
String alarm_starttime = alarmarray[5];//故障发生时间
String alarmtext = alarmarray[6];//故障具体内容
String alarm_level = alarmarray[8];//告警级别
// String alarm_cleartime = alarmarray[13];//故障清除时间
String alarm_type = alarmarray[16];//故障类型
String specific_problem = alarmarray[30];//故障内容
if(!(alarm_level.equals(AlarmLevel)) && !(alarm_type.equals("EQUIPMENT_MALFUNCTION"))){
alarm_code = 20;
}
if (alarm_code > 10 && specific_problem.equals(specific_problem2)) { //有故障。经过判断后,如果是和投诉关联的故障则把故障信息入库。
alarm_rsnum += 1;
insert_related_alarms += "(" + Integer.parseInt(record_id) + ",'" + call_time + "','" + curr_time +
"'," + query_range + "," + ecp + "," + bts + "," + cell + ",'" + location
+ "','" + alarm_type + "','" + alarm_starttime + "','" + alarm_cleartime
+ "'," + alarm_code + ",'" + specific_problem + "' , '" + alarmtext + "' , '" + alarm_level + "'),";
logger.info("第"+i+"个插入related_alarms的语句: " + insert_related_alarms);
count ++;
}
if (alarm_code > max_code) {
max_code = alarm_code;
}
i++;
logger.info("故障结果编码alarm_rscode="+max_code);
} //for
}//for
}//退出for循环,小区列表
//一次性把所有故障信息添加到related_alarms数据库
if(count > 0){ //如果count==0,不执行插入数据库操作,无故障信息
logger.info("把所有故障信息添加到related_alarms数据库sql语句="+insert_related_alarms.substring(0, insert_related_alarms.length() - 1));
dml.insertdata(insert_related_alarms.substring(0, insert_related_alarms.length() - 1), conn);
}
//-----------------------------更新标签pre_judge_label里面的alarms字段-------------------------------------------
int alarmsLabel = 202; //基站故障分析标签,weak=201,health=202
if (alarm_rsnum > 0) {
alarmsLabel = 201;//有故障,则为weak201
}else {
alarmsLabel = 202;//无故障为health202
}
boolean flagLabel = dml.updatedata("update pre_judge_label set alarms="+alarmsLabel+" where record_id=" + Integer.parseInt(record_id));
if (flagLabel) {
logger.info("succeess:成功更新pre_judge_label里面alarms!");
}else {
logger.info("error:更新pre_judge_label里面alarms失败!");
}
//----------------------追加字段alarm_rscode,alarm_rsnum到pre_deal_records中-------------------------------
int alarmcode = 10;
String sqlString = "select alarm_code from related_alarms where record_id = " + Integer.parseInt(record_id);
ArrayList<String> alarmArrayList = dml.selectMysql(sqlString, conn);
if (alarmArrayList.isEmpty()) {
alarmcode = 10;
}else {
alarmcode = Integer.parseInt(alarmArrayList.get(0).split("\t")[0]);
}
logger.info("/n " + alarmcode + "***********/n");
String update_pre_deal_records = "update pre_deal_records SET alarm_rscode = " + alarmcode + ", alarm_rsnum = " + alarm_rsnum +
" WHERE record_id = " + Integer.parseInt(record_id);
boolean flag1 = dml.updatedata(update_pre_deal_records);
if (!flag1) {
logger.info("Error!更新失败。");
}else {
logger.info("Success!更新成功。");
}
//----------------------追加字段alarm_colorcode到pre_deal_results中------------------------------------------
String sql1 = "select colorcode from dict_result WHERE category = 'ALM' and rscode = " + alarmcode;
logger.info(sql1);
ArrayList<String> colorlist = dml.selectMysql(sql1, conn);
if (colorlist.isEmpty()) {
logger.info("\ndict_result表查询失败");
return "查询数据字典失败!";
}
int alarm_colorcode = Integer.parseInt(colorlist.get(0).split("\t")[0]);//获得颜色编码
String update_pre_deal_results = "update pre_deal_results SET alarm_colorcode = " + alarm_colorcode + " WHERE record_id = " +
Integer.parseInt(record_id);
boolean flag2 = dml.updatedata(update_pre_deal_results);
if (!flag2) {
logger.info("Error!更新失败。");
}else {
logger.info("Success!更新成功。");
}
long t8 = System.currentTimeMillis();
System.out.println("关联小区分析: "+(t8-t7)/1000.0 + "s");
return "success";
}
/*********************************************************************************
* 根据找关联小区故障结果编码编码,确定找关联小区故障结果的颜色
* rscode meaning colorCode color
* 40 故障持续。关联基站在问题时刻有告警,且当前时刻仍然存在. 50 red
30 现行故障。关联基站在问题时刻无告警,但当前时刻有告警。 40 yellow
20 故障恢复。关联基站在问题时刻有告警,当前时刻故障已清除。 30 Blue
10 无故障。关联基站在问题时刻无告警。 20 green
*******************************************************************************/
public String getAlarmRSColor(){
int alarmRSCode = getAlarm_rsCode();
String color = "";
switch (alarmRSCode) {
case 20: setAlarm_rsColorCode(50); color = "red"; break;
case 10: setAlarm_rsColorCode(20); color = "green"; break;
default: setAlarm_rsColorCode(20); color = "green"; break;
}
return color;
}
/***************************************************
* 测试查找关联小区的故障
* @throws IOException
* @throws FileNotFoundException
* @throws SQLException
* @throws ClassNotFoundException
* @throws NumberFormatException
* @throws ParseException
* ************************************************/
public static void main(String[] args) throws FileNotFoundException, IOException, NumberFormatException, ClassNotFoundException, SQLException, ParseException{
QueryAlarms qAlarms = new QueryAlarms();
mysql_DML dml = new mysql_DML();
Connection conn = dml.myConnection();
String cellString = "SELECT DISTINCT ecp, bts,cell,location FROM related_cells WHERE record_id = 850";
ArrayList<String> cellArrayList = dml.selectMysql(cellString, conn);
System.out.println("查找故障开始");
String aString=qAlarms.queryRelatedAlarms("850", dml, conn, cellArrayList);
System.out.println(aString);
}
}<file_sep>package pre_deal;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import myquery.Query;
import mysql.mysql_DML;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.hadoop.hbase.thrift.TBoundedThreadPoolServer.Args;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.yecht.Data.Str;
import cell_info.Find_Cell;
import domain.Grid;
import service.GridService;
@Controller
public class ComplaintQuery {
@Autowired
private static Logger logger = Logger.getLogger(ComplaintQuery.class);
private GridService gridService;
//1.输入“手机号码”和“出问题时间的范围(始末)”,返回所有投诉ID
// url:xxx/search_by_phone,
// type: "GET",
// data: {"searchType": "phone",
// "search_text" : "13163335678",
// "start_time": "2015-05-07 02:02",
// "end_time" : "2015-08-07 02:02"}
// 或 //2.输入“基站编号”和"出问题时间范围",返回所有投诉ID
// data: {"searchType": "station",
// "search_text : "13,1014", //ECP,BTS
// "start_time": "2015-05-07 02:02"
// "end_time" : "2015-08-07 02:02"}
// 或 //3.输入“投诉地点(转为经纬度)”和"出问题时间范围",返回所有投诉ID
// data: {"searchType": "longlat",
// "search_text : "114.407,30.513,12", //longitude,latitude,radius
// "start_time": "2015-05-07 02:02",
// "end_time" : "2015-08-07 02:02"}
// 或 //4.只输入"出问题时间范围",返回最近100条投诉信息的投诉ID
// data: {"searchType": "longlat"或"station"或"phone"
// "search_text : ""
// "start_time": "2015-05-07 02:02",
// "end_time" : "2015-08-07 02:02"}
// PS: "searchType"可选的类型有phone、location、longlat
//
// response: [{
// "cause": "原因定位:基站4_33_XXX 故障。",
// "suggestion": "后续操作建议:XXX,结单处理。",
// "No":1,
// "count":100,
// "complaint_item_id" : "34",
// "complaint_phone" : "13163335678",
// "location": "华中科技大学东校区",
// "longitude": "114.40776",
// "latitude": "30.51415",
// "pheno_option": "无信号",
// "pheno_description": "XXXXXXX",
// "complaint_time": "2015-06-18 05:00",
// "occur_time": "2015-06-18 05:00"}]
/****************************************************************************************************
* 主查询函数,解析前台传进来的URL,返回投诉信息
*/
@RequestMapping(value = "/search_by_phone",method = RequestMethod.GET)
@ResponseBody
public String search_by_phone(HttpServletRequest request, HttpServletResponse response)
throws ParseException, FileNotFoundException, ClassNotFoundException, IOException, SQLException{
//从前台传进的URL提取参数
String searchType = URLDecoder.decode(request.getParameter("search_type"), "UTF-8");
String searchText = URLDecoder.decode(request.getParameter("search_text"), "UTF-8");
String start_time = URLDecoder.decode(request.getParameter("start_time"), "UTF-8");
String end_time = URLDecoder.decode(request.getParameter("end_time"), "UTF-8");
logger.info("从request解析得到的字符串:searchType="+searchType+"\tsearchText="+searchText+"\tstart_time="
+start_time+"\tend_time="+end_time);
int searchTypeID = 0;//用于保存查询类型编号
if (!searchText.equals("") && !searchText.equals(",") && !searchText.equals(",,")) {
if (searchType.equals("phone")) {
searchTypeID = 1; //电话查询编号为1
}
if (searchType.equals("station")) {
searchTypeID = 2; //基站查询编号为2
}
if (searchType.equals("longlat")){
searchTypeID = 3; //经纬度查询编号为3
}
} else { //只输入查询时间,编号为4
searchTypeID = 4;
}
//根据不同编号,调用对应的查询函数获得投诉单ID号
ArrayList<String> complaintIDList = new ArrayList<String>();
switch (searchTypeID) {
case 1: complaintIDList = searchByPhoneNumber(searchText, start_time, end_time); break;
case 2: complaintIDList = searchByCell(searchText, start_time, end_time); break;
case 3: complaintIDList = searchByLongLat(searchText, start_time, end_time); break;
case 4: complaintIDList = searchByTime(start_time, end_time); break;
default:complaintIDList = null; break;//异常情况,赋值为空。表示找不到投诉单号
}
//检查是否找到结果,若无则打印信息且退出
int count = 0;
if (complaintIDList == null || complaintIDList.isEmpty()) {
logger.info("查询无结果!请核对输入信息!");
return "查询无结果!请核对输入信息!";
}else {
count = complaintIDList.size(); //count表示此次查询含有的投诉信息条数
logger.info("找到"+count+"条投诉信息!");
}
//根据投诉单号,通过Json数组返回查询结果信息
JSONArray jsonArray = new JSONArray();
mysql_DML dml = new mysql_DML();
Connection conn = dml.myConnection();
for (int index = 0; index < count; index++) {
JSONObject jsonObject = new JSONObject();
int id = Integer.parseInt(complaintIDList.get(index).trim());//陈骏的mysql函数里面返回list每个元素后面默认加了制表符,故此处要去掉再解析为整数
//找建议信息,即异常概览内容
String sqlsuggestion = "select abnormal_overview,mainCause_code,secCause_code from pre_deal_records where record_id="+id;
logger.info("查询投诉结果原因语句:"+sqlsuggestion);
ArrayList<String> listsuggestion = dml.selectMysql(sqlsuggestion, conn);//只用一个id查询,所以list中只有一个元素,即只有一行
logger.info("查询投诉结果原因="+listsuggestion);
String suggestion = " 异常概览:";
String cause = "";//用于主原因和辅原因
if (listsuggestion.isEmpty()) {
suggestion += "无异常信息";
cause = "无异常信息";
}else {
String[] data = listsuggestion.get(0).split("\t");
if (data.length != 0) {
suggestion += data[0];
//查询主辅原因
ArrayList<String> causeMain = dml.selectMysql("select meaning from dict_system where seq between 16 and 36 and code="
+Integer.parseInt(data[1]), conn);
String mainCauseString = causeMain.get(0).split("\t")[0];
ArrayList<String> causeSec = dml.selectMysql("select meaning from dict_system where seq between 16 and 36 and code="
+Integer.parseInt(data[2]), conn);
String secCauseString = causeSec.get(0).split("\t")[0];
cause = "主原因:"+mainCauseString+", 辅原因:"+secCauseString;
} else {
suggestion += "无异常信息";
cause = "无异常信息";
}
}
//No表示当前是第几条投诉信息
int No = index + 1;
//查询pre_deal_records投诉信息数据库
String sql = "select pre_deal_joint_id,phone,call_location,call_lon,call_lat,pheno_code," +
"pheno_description,complaint_time,call_time from pre_deal_records where record_id = " + id;
logger.info("查询投诉信息语句:"+sql);
ArrayList<String> list = dml.selectMysql(sql, conn);//只用一个id查询,所以list中只有一个元素,即只有一行
if (list.size() != 0) {
String[] a = list.get(0).split("\t");
if (a[1].equals("12345678901")) { //没有电话号码
a[1] = "无";
}
jsonObject.put("cause", cause);
jsonObject.put("suggestion", suggestion);
jsonObject.put("No", No);
jsonObject.put("count", count);
jsonObject.put("complaint_item_id", id);
jsonObject.put("display_complaint_item_id", a[0]);
jsonObject.put("complaint_phone", a[1]);
jsonObject.put("location", a[2]);
jsonObject.put("longitude", a[3]);
jsonObject.put("latitude", a[4]);
jsonObject.put("pheno_option", getPheno_optionWords(a[5]));
jsonObject.put("pheno_description", a[6]);
jsonObject.put("complaint_time", a[7]);
jsonObject.put("occur_time", a[8]);
jsonArray.add(jsonObject);
logger.info("投诉ID"+id+"查询结果如下:\ncause="+cause+"\nsuggestion="+suggestion+"\nNo="+No+
"\ncount="+count+"\ncomplaint_item_id="+a[0]+"\ncomplaint_phone="+a[1]
+"\nlocation="+a[2]+"\nlongitude="+a[3]+"\nlatitude="+a[4]+"\npheno_option="+a[5]
+"\npheno_description="+a[6]+"\ncomplaint_time="+a[7]+"\noccur_time="+a[8]+"\n");
} else {
logger.info("函数循环第"+(index+1)+"次查询投诉ID号"+id+"无投诉信息!!");
return "查询无投诉信息!";
}
}//end of for
conn.close();
logger.info("最终返回给前台的信息:"+jsonArray.toString());
return(jsonArray.toString()) ;
}
/*********************************************************************************************************
* 1.输入“手机号码”和“出问题时间的范围(始末)”,查询complaint_info表,返回所有投诉ID
*/
public ArrayList<String> searchByPhoneNumber(String searchText, String startTime, String endTime)
throws FileNotFoundException, IOException, ClassNotFoundException, SQLException{
logger.info("进入searchByPhoneNumber函数,调用了电话查询函数!...");
//检查电话位数是否有误,有则退出
String checkPhone = checkPhoneNumbre(searchText);
if (!checkPhone.split("\t")[0].equals("true")) {
logger.info("error:输入的手机号码有误!");
return null;
}
logger.info("");
String phoneNumber = checkPhone.split("\t")[1];//提取电话号码,防止有+86的情况出现
mysql_DML dml = new mysql_DML();
Connection conn = dml.myConnection();
String sql = "select record_id from pre_deal_records where phone ='" + phoneNumber
+ "' and call_time between '" + startTime + "' and '" + endTime + "' order by record_id DESC";
logger.info("电话查询函数查询语句:"+sql);
ArrayList<String> resultList = dml.selectMysql(sql, conn);
if (resultList.isEmpty()) {
logger.info("根据电话号码查找pre_deal_records表无record_id,即此次查询无结果!");
return null;
}
conn.close();
logger.info("退出searchByPhoneNumber函数.");
return resultList;
}
//****************************判断电话号码的正误*****************************
private String checkPhoneNumbre(String searchText) {
String phoneNum = searchText;
//手机号码不足11位,报错并退出
if (phoneNum.length() < 11) {
logger.info("error:输入的电话号码不足11位!");
return false+"\t"+phoneNum;
}
//处理手机号码前面带有“+86”字样的号码,前台不能识别加号“+”,只能返回一个空格
int a = Integer.parseInt(searchText.trim().charAt(0)+"");//电话号码第1位
// logger.info("a="+a);
int b = Integer.parseInt(searchText.trim().charAt(1)+"");//电话号码第2位
char c = searchText.trim().charAt(2);//电话号码第3位
if (searchText.length()==14 && a==8 && b==6) { //电话格式“+86xxxxxxxxxxx”
phoneNum = searchText.substring(3); //取出searchText里的号码,覆盖掉phoneNum原来的值
}
if(searchText.length()==15 && a==8 && b==6 && c==' ' ){//电话格式“+86 xxxxxxxxxxx”
phoneNum = searchText.substring(4); //取出searchText里的号码,覆盖掉phoneNum原来的值
}
//手机号码超过11位,报错且退出
if (phoneNum.length() > 11) {
logger.info("error:输入的电话号码超过了11位!");
return false+"\t"+phoneNum;
}
//取出手机号码的前三位
int p = Integer.parseInt(phoneNum.charAt(0)+"");//电话号码第1位
int n = Integer.parseInt(phoneNum.charAt(1)+"");//电话号码第2位
int m = Integer.parseInt(phoneNum.charAt(2)+"");//电话号码第3位
//手机号码不是1开头,报错退出
if (p != 1) {
logger.info("error:输入的电话号码超过了11位!");
return false+"\t"+phoneNum;
}
// //检查是否为电信133、153、180、181、189、177开头号码,不是则退出
// boolean flag1 = (n==3&&m==3)||(n==5&&m==3)||(n==8&&m==0)||(n==8&&m==1)||(n==8&&m==9)||(n==7&&m==7);
// if (flag1) {
// return true+"\t"+phoneNum;
// }else {
// logger.info("error:输入的电话号码不是电信号!");
// return false+"\t"+phoneNum;
// }
return true+"\t"+phoneNum;
}
/****************************************************************************************************
* 2.输入“基站编号”和"出问题时间范围",查询cell_info_result表,返回所有投诉ID
*/
public ArrayList<String> searchByCell(String searchText, String startTime, String endTime)
throws FileNotFoundException, IOException, ClassNotFoundException, SQLException{
logger.info("调用了基站查询searchByCell函数!");
String[] cell = new String[2];
cell = searchText.split(",");
if (cell.length != 2) {
return null;
}
//判断基站编号是否为有效数值
int ECP = 0;
int BTS = 0;
try{
ECP = Integer.parseInt(cell[0]);
}catch (NumberFormatException e) {
logger.info("error:基站编号ECP必须是整数!");
return null;
}
if (ECP <= 0) {
logger.info("error:基站编号ECP必须是正整数!");
return null;
}
try{
BTS = Integer.parseInt(cell[1]);
}catch (NumberFormatException e) {
logger.info("error:基站编号 BTS必须是整数!");
return null;
}
if (BTS <= 0) {
logger.info("error:基站编号BTS必须是正整数!");
return null;
}
mysql_DML dml = new mysql_DML();
Connection conn = dml.myConnection();
//子查询,结合两张表pre_deal_records和related_cells查询结果
String sql = "select record_id from pre_deal_records where call_time between '" + startTime
+ "' and '" + endTime + "' AND record_id IN (select record_id from related_cells "
+ " where ecp = " + ECP + " and bts = " + BTS + ") order by record_id DESC";
ArrayList<String> resultList = dml.selectMysql(sql, conn);
conn.close();
if (resultList.isEmpty()) {
return null;
}
return resultList;
}
/****************************************************************************************************
* 3.输入“投诉经纬度、半径(单位km)”和"出问题时间范围",返回所有投诉ID
*/
public ArrayList<String> searchByLongLat(String searchText, String startTime, String endTime)
throws FileNotFoundException, IOException, ClassNotFoundException, SQLException{
logger.info("调用了经纬度查询函数!");
String[] lonLatRadius = new String[3];
lonLatRadius = searchText.split(",");
if (lonLatRadius.length != 3) {
return null;
}
double lon = Double.parseDouble(lonLatRadius[0]);
double lat = Double.parseDouble(lonLatRadius[1]);
double radius = Double.parseDouble(lonLatRadius[2]);//从前台传进来的搜索半径单位是km
//检测输入的经纬度是否在湖北省内或省边界附近,不在就报错退出
if (!(108.29209227 <= lon && lon <= 116.37915993)) {
logger.info("error:输入“经度”不在湖北省境内!");
return null;
}
if (!(28.92430194 <= lat && lat <= 33.43608273)) {
logger.info("error:输入“纬度 ”不在湖北省境内!");
return null;
}
if (radius < 0) {
logger.info("error:搜索半径不能是负数!");
return null;
}
radius *= 1000; //单位千米化为米,以米为单位计算,可以减少误差
double coslat = Math.cos(lat * Math.PI / 180.0);//纬度的余弦值
double latOffset = radius * 360 / 40008080; //纬度偏移量。地球经度周长=40008080m,要求radius单位是m
double lonOffset = radius * 360 / (40075700 * coslat);//经度偏移量。地球赤道周长=40075700m
mysql_DML dml = new mysql_DML();
Connection conn = dml.myConnection();
String sql = "select record_id, call_lon, call_lat from pre_deal_records where call_lon >= " + (lon - lonOffset)
+ " and call_lon <= " + (lon + lonOffset) + " and call_lat >= " + (lat - latOffset)
+ " and call_lat <= " + (lat + latOffset) + " and call_time between '" + startTime
+ "' and '" + endTime + "' order by record_id DESC";
ArrayList<String> complaintList = dml.selectMysql(sql, conn);//获取满足条件的投诉信息,元素是行
if (complaintList==null || complaintList.isEmpty()) {
return null;
}
ArrayList<String> resultList = new ArrayList<String>();
for (String string : complaintList) {
double lon1 = Double.parseDouble(string.split("\t")[1]);//每行的经度
double lat1 = Double.parseDouble(string.split("\t")[2]);//每行的纬度
//1°经度长度=111321.4*cos(lat)米,1°纬度长度=111133.6米
double dist = Math.sqrt((lon - lon1) * (lon - lon1) * 111321.4 * coslat * 111321.4 * coslat
+ (lat - lat1) * (lat - lat1) * 111133.6 * 111133.6 );
//找出搜索半径以内的投诉单ID号
if (dist <= radius) {
resultList.add(string.split("\t")[0]);
}
}
conn.close();
return resultList;
}
/*******************************************************************************************************
* 4.只输入"出问题时间范围",返回最近100条投诉信息的投诉ID
* @throws IOException
* @throws FileNotFoundException
* @throws SQLException
* @throws ClassNotFoundException
* @throws ParseException
*/
public ArrayList<String> searchByTime(String startTime,String endTime)
throws FileNotFoundException, IOException, ClassNotFoundException, SQLException, ParseException {
logger.info("调用时间查询searchByTime函数");
// long startTime1 = Long.parseLong(startTime);
// long endTime1 = Long.parseLong(endTime);
// if (endTime1 >= startTime1){//查询时间区间要有效
// return null;
// }
int displayNum = 100;
mysql_DML dml = new mysql_DML();
Connection conn = dml.myConnection();
String sql = "select record_id from pre_deal_records where call_time between '"
+ startTime + "' and '" + endTime + "' order by record_id DESC limit 0," + displayNum;
logger.info("时间函数查询语句="+sql);
ArrayList<String> resultList = dml.selectMysql(sql, conn);
if (resultList.isEmpty()) {
return null;
}
conn.close();
return resultList;
}
/******************************************************************************************
* 解析投诉信息的现象描述,把编号换为文字
* "1001":无信号,"1002":有信号无法呼叫,"1003":掉话,"1004":话音断续不清晰,"1005":短信收发异常,"1006":单向使能异常
*/
private String getPheno_optionWords(String numString){
String wordString = "无现象描述";
if (numString.equals("1001")) {
wordString = "无信号";
}
if (numString.equals("1002")) {
wordString = "有信号无法呼叫";
}
if (numString.equals("1003")) {
wordString = "掉话";
}
if (numString.equals("1004")) {
wordString = "话音断续不清晰";
}
if (numString.equals("1005")) {
wordString = "短信收发异常";
}
if (numString.equals("1006")) {
wordString = "单向使能异常";
}
return wordString;
}
}
<file_sep>define([
'underscore',
'backbone',
'marionette',
'bmap_api',
"tpl!views/map/map_t/setLocation.tpl",
], function(_, Backbone, Marionette, BMap, setLocationTpl) {
"use strict";
var LoginView = Backbone.Marionette.LayoutView.extend({
template: setLocationTpl,
regions: {
},
events: {
},
initialize: function(options) {
},
onShow: function(){
},
});
return LoginView;
});
<file_sep>define([
'backbone'
], function(Backbone) {
"use strict";
var ComplaintInfoGet = Backbone.Model.extend({
defaults: {
"complaint_phone": "",
"location": "",
"longitude": "",
"latitude": "",
"pheno_option": "",
"pheno_description": "",
"complaint_time": "",
"occur_time": ""
},
validation: {
complaint_phone:{
required: true,
length: 11,
range: [12345678901,23456789012],
msg: "请正确填写电话号码"
},
location:{
// required: true
},
pheno_option:{
required: true
},
occur_time:{
required: true,
msg: "请填写问题发生时间"
},
pheno_description:{
required: false,
maxLength: 50,
msg: "输入字数在50字以内"
},
longitude:{
required: false,
range: [108.438, 116.120],
msg: '请保证输入地址位于湖北省内'
},
latitude:{
required: false,
range: [29.143, 33.258],
msg: '请保证输入地址位于湖北省内'
}
},
initialize: function(options){
this.urlRoot = 'complaint_info_get.html';
this.url = this.urlRoot + '?complaint_info_id=' + options.id;
}
});
return ComplaintInfoGet;
});<file_sep>package com.yl.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.Properties;
import javax.mail.Flags.Flag;
import sun.awt.SunHints.Value;
public class DBConnUtil{
//定义数据库连接信息
private static String JDBC_DRIVER = "";
private static String JDBC_URL = "";
private static String JDBC_PASS = "";
private static String JDBC_USER ="";
static{
InputStream is = null;
try {
//加载database.properties文件
is= DBConnUtil.class.getClassLoader().getResourceAsStream("database.properties");
Properties properties = new Properties();
properties.load(is);
JDBC_DRIVER = properties.getProperty("jdbcDriver");
JDBC_URL = properties.getProperty("jdbcUrl");
JDBC_PASS = properties.getProperty("jdbcPass");
JDBC_USER = properties.getProperty("jdbcUser");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if (is != null) {
try {
is.close();//关闭is
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
}
/**
* 建立连接的方法
* @throws ClassNotFoundException
* @throws SQLException
*/
public static Connection getConn() throws ClassNotFoundException, SQLException {
Connection conn = null;
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASS);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
/**
* 关闭连接(用于增、删、改、查)
*/
public static void closeAll(PreparedStatement pstmt,Connection conn) {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* @author yl
* @throws ClassNotFoundException
* @throws SQLException
* @date 2016-1-18
* 查询数据
*/
public ArrayList<String> selectData(String sql, Connection conn, PreparedStatement pstmt, Object ...args)
throws ClassNotFoundException, SQLException {
//用来存结果的list
ArrayList<String> list = new ArrayList<String>();
ResultSet rs = null;
//加载驱动程序
Class.forName(JDBC_DRIVER);
if (!sql.toLowerCase().startsWith("select")) {
return null;
}
try {
pstmt = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
pstmt.setObject(i + 1, args[i]);
}
System.out.println(pstmt);
rs = pstmt.executeQuery();//执行sql语句
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();//取得查询结果的行数
while (rs.next()) {
String result = "";
for (int i = 0; i < columnCount; i++) {
result += rs.getString(i + 1) + "\t";
}
list.add(result);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
//关闭resultset
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return list;
}
/**
* 增,删,改操作
* @author yl
* @date 2016-1-27
*/
public boolean updateData(String sql,Connection conn, PreparedStatement pstmt, Object ...args) {
boolean result = false;
int flag = 0;//标记preparestatement对象pstmt执行的结果,如果为0则表示executeUpdate()执行有问题
//ResultSet rs = null;
try {
pstmt = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);//预处理
//设置参数
for (int i = 0; i < args.length; i++) {
pstmt.setObject(i + 1 , args[i]);
}
//经过预处理和赋值后的sql语句
System.out.println(sql);
flag = pstmt.executeUpdate();
// rs = pstmt.getGeneratedKeys();
// if (rs.next()) {
// System.out.println("**error**");
// }
// int num = rs.getInt(1);
// System.out.println("*****" + num);
if (flag == 0) {
result = false;
return result;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = false;
return result;
}
result = true;
return result;
}
}<file_sep>package com.homer.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import com.homer.bean.BaseResp;
import com.homer.bean.Msg;
import com.homer.bean.QueryMsgResp;
import com.homer.dao.DBManager;
/*
* 查看留言
* */
public class QueryMsgServlet extends BaseServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
super.doGet(req, resp);
PrintWriter pw = resp.getWriter();
BaseResp bean=null;
String result=null;
String complaintId=req.getParameter("complaint_id");
try {
result=query(complaintId);
System.out.println(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
bean=new BaseResp(-1, e.getMessage());
result=JSONObject.fromObject(bean).toString();
}finally{
pw.write(result);
pw.flush();
pw.close();
try {
DBManager.getInstance().disConnect();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private String query(String complaintId) throws ClassNotFoundException, SQLException{
String sql="SELECT * FROM message_records WHERE complaint_id="+complaintId;
ResultSet rs=DBManager.getInstance().executeQuery(sql);
ArrayList<Msg> msgs=new ArrayList<Msg>();
Msg msg=null;
Timestamp time=null;
Date date = null;
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
while(rs.next()){
System.out.println("next");
date=new Date(rs.getTimestamp("message_time").getTime());
msg=new Msg(sdf.format(date), rs.getString("message_content"),
rs.getInt("message_type"));
msgs.add(msg);
}
QueryMsgResp resp = new QueryMsgResp(0, "ok", msgs);
return JSONObject.fromObject(resp).toString();
}
}
<file_sep>package com.complaint.statistic;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mysql.mysql_DML;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import com.related.alarms.RelatedAlarms;
import com.sys.util.MyFilePath;
public class StatisticByGeoTopN extends HttpServlet {
private static Logger logger = Logger.getLogger(StatisticByGeoTopN.class);
private String search_r;
private String search_t;
private String init_lon;
private String init_lat;
private String alarm_timerange;
private String perf_timerange;
private String range_type;
private String cellDensityThreshold;
private String AlarmLevel;
private String N;
public static String path = MyFilePath.TCPropertiesPath;
public void initParam(String paramFile) throws FileNotFoundException, IOException{
Properties props = new Properties();
props.load(new FileInputStream(paramFile));
search_r = props.getProperty("search_r");
search_t = props.getProperty("search_t");
init_lon = props.getProperty("init_lon");
init_lat = props.getProperty("init_lat");
alarm_timerange = props.getProperty("alarm_timerange");
perf_timerange = props.getProperty("perf_timerange");
range_type = props.getProperty("range_type");
AlarmLevel = props.getProperty("alarmlevel");
cellDensityThreshold = props.getProperty("cellDensityThreshold");
N = props.getProperty("N");
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Access-Control-Allow-Origin", "*");
String result = "";
try {
result = statistic_by_geography_TOPN(request, response);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PrintWriter out = response.getWriter();
out.println(result);
out.flush();
out.close();
}
/*
* author:yl
* date:2015.12.1
*
url : xxx/statistic_by_geography_TOPN.html,
type:"GET",
data: {"start_time": "2015-11-30",
"end_time" : "2015-12-01 "}
response: [{N: 10},
{order_num:21,
longitude: 143.555,
latitude: 32.456,
complaint_times:1,
}]
*/
public String statistic_by_geography_TOPN(HttpServletRequest request,HttpServletResponse response) throws ParseException, ClassNotFoundException, FileNotFoundException, SQLException, IOException
{
response.setCharacterEncoding("UTF-8");
String start_time = URLDecoder.decode(request.getParameter("start_time"), "UTF-8");
String end_time = URLDecoder.decode(request.getParameter("end_time"), "UTF-8");
initParam(path);
//创建数据库连接
mysql_DML dml = new mysql_DML();
Connection conn = dml.myConnection();//创建连接,后面记得关闭连接
//返回给前端的数据
JSONArray jsonArray = new JSONArray();
SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String s_time = sDateFormat.format(sDateFormat.parse(start_time));
String e_time = sDateFormat.format(sDateFormat.parse(end_time));
int count = 0;//投诉记录次数,默认为0
String grid_id = "";
int idmin = 0;
int idmax = 0;
String sqlString1 = "SELECT record_id FROM pre_deal_records WHERE DATE(complaint_time) BETWEEN '" +
s_time + "' AND '" + e_time + "'";
ArrayList<String> recordidArrayList = dml.selectMysql(sqlString1, conn);
if (recordidArrayList.isEmpty()) {
return (jsonArray.toString());
}else {
idmin = Integer.parseInt(recordidArrayList.get(0).split("\t")[0]);
idmax = Integer.parseInt(recordidArrayList.get(recordidArrayList.size() - 1).split("\t")[0]);
}
//统计某一天投诉记录的总次数
String sqlString = "SELECT grid_id, COUNT(*) AS num FROM related_grids WHERE " +
"record_id >= " + idmin + " AND record_id <= " + idmax +" GROUP BY grid_id " +
" ORDER BY num DESC limit 0," +
Integer.parseInt(N);
logger.info(sqlString);
JSONObject jb = new JSONObject();
ArrayList<String> countArrayList = dml.selectMysql(sqlString, conn);
if (countArrayList.isEmpty()) {
count = 0;
return (jsonArray.toString());
}else {
//表头
JSONObject jsonObject = new JSONObject();
jsonObject.put("N", N);
jsonArray.add(jsonObject);
int i = 1;
String lon = "";
String lat = "";
for(String s : countArrayList){
grid_id = s.split("\t")[0];
//根据grid_id查询经纬度
String sqlString2 = "SELECT gps_lon,gps_lat FROM grid_info WHERE grid_x = " +
Integer.parseInt(grid_id.split("\\^")[0]) +
" AND grid_y = " + Integer.parseInt(grid_id.split("\\^")[1]) ;
logger.info(sqlString2);
ArrayList<String> list = dml.selectMysql(sqlString2, conn);
if (list.isEmpty()) {
continue;
}else {
lon = list.get(0).split("\t")[0];
lat = list.get(0).split("\t")[1];
}
count = Integer.parseInt(s.split("\t")[1]);
jb.put("order_num", i);
jb.put("longitude", lon);
jb.put("latitude", lat);
jb.put("complaint_times", count);
jsonArray.add(jb);
i ++;
}
}
logger.info("这是返回的话单信息的Json数据格式: " + jsonArray.toString());
logger.info("\n退出statistic_by_geography_TOPN函数");
conn.close();
return (jsonArray.toString());
}
}
<file_sep>package com.order.query;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.jay.mysql.MysqlDML;
public class StatsOrderNumDay extends HttpServlet {
private static final long serialVersionUID = 1L;
//重写父类的doGet()方法
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("doget转dopost");
doPost(req,resp);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Access-Control-Allow-Origin", "*");
// //解决跨域问题
// response.setHeader("Pragma", "no-cache");
// response.setHeader("Cache-Control", "no-cache");
//// response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1/*");
// response.setHeader("Access-Control-Allow-Origin", "*");//所有协议、域名、端口都可以访问
// response.setDateHeader("Expires", 0);
//
String result ="";
try {
result = statsOrderNumDay(request,response);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PrintWriter pw=response.getWriter();
pw.println(result);
pw.flush();
pw.close();
}
/***********************************************************************************************************************
*传进参数格式 {“startDate”:2016-07-05,“endDate”:2016-07-11,“area”:“全省”}
返回值格式 {“result”:0,”resultText”: {“2016-07-05”:50, “2016-07-06”:11, “2016-07-07”:24, “2016-07-08”:56, “2016-07-09”:55, “2016-07-10”:113, “2016-07-11”:87 }}
或{“result”:-1,”resultText”:failed}
功能说明:按投诉日期统计一周内每天的工单(发生)数量,含当天
* Author:JayLi
* @throws ParseException
*****************************************************************************************************************/
public String statsOrderNumDay(HttpServletRequest request,HttpServletResponse response)
throws FileNotFoundException, IOException, ClassNotFoundException, SQLException, ParseException {
System.out.println("调用statsOrderNumDay");
//解析传进来的参数
String callback = null;
String startDate = null;
String endDate = null;
String area = null;
JSONObject jReturn = new JSONObject();
try {
callback = request.getParameter("callback");
startDate = request.getParameter("startDate");
endDate =request.getParameter("endDate");
area =request.getParameter("area");
} catch (Exception e) {
jReturn.put("result", -1);
jReturn.put("resultText", "url参数异常");
return(callback+"("+jReturn.toString()+")");
}
if (startDate==null || "".equals(startDate)) {
jReturn.put("result", -1);
jReturn.put("resultText", "统计开始时间"+startDate+"错误");
return(callback+"("+jReturn.toString()+")");
}
if (endDate==null || "".equals(endDate)) {
jReturn.put("result", -1);
jReturn.put("resultText", "统计开始时间"+startDate+"错误");
return(callback+"("+jReturn.toString()+")");
}
//正则表达式匹配时间格式
Pattern pattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");
Matcher matcher1 = pattern.matcher(startDate);
Matcher matcher2 = pattern.matcher(endDate);
if (!matcher1.matches()) {
jReturn.put("result", -1);
jReturn.put("resultText", "统计开始时间"+startDate+"错误");
return(callback+"("+jReturn.toString()+")");
}
if (!matcher2.matches()) {
jReturn.put("result", -1);
jReturn.put("resultText", "统计结束时间"+endDate+"错误");
return(callback+"("+jReturn.toString()+")");
}
String[] cities = {"武汉","宜昌","荆门","黄冈","黄石","荆州","十堰","随州","孝感","咸宁","襄阳","恩施","林区","潜江","天门","仙桃","鄂州"};
int citySeq = 0;//标记查询类型类型是否需要分地区查询,全省则不用分地区查询,其他城市则要分地区,不存在的地区则报错返回。1是全省,2是其他城市,0是地区有错。
int areaID = 0;
if ("全省".equals(area)) {
citySeq = 1;
}else {
for (String city : cities) {
areaID++;
if (city.equals(area)) {
citySeq = 2;
break;
}
}
}
//判断输入的地区是否正确
if (citySeq == 0) {
jReturn.put("result", -1);
jReturn.put("resultText", "输入的地区"+area+"错误");
return(callback+"("+jReturn.toString()+")");
}
MysqlDML dml = MysqlDML.getInstance();
Connection conn = dml.getMyConnection();
JSONObject jsonObject = new JSONObject();
String sqlOrder = null;
if (citySeq== 1) {//全省
sqlOrder = "SELECT DATE(create_time) AS date,COUNT(*) AS num FROM work_order_info " +
"WHERE DATE(create_time) BETWEEN DATE('"+startDate+"') AND DATE('"+endDate+"') " +
"GROUP BY date ORDER BY date; " ;
}else {//其他城市
sqlOrder = "SELECT DATE(create_time) AS date,COUNT(*) AS num FROM work_order_info " +
"WHERE DATE(create_time) BETWEEN DATE('"+startDate+"') AND DATE('"+endDate+"') AND area_id=" +areaID+
" GROUP BY date ORDER BY date; " ;
}
ArrayList<String> orderList = dml.selectData(sqlOrder, conn);
// if (orderList == null || orderList.isEmpty()) {
// System.out.println("查询时间"+startDate+"到"+endDate+"内无工单记录");
// jReturn.put("result", -1);
// jReturn.put("resultText", "查询时间"+startDate+"到"+endDate+"内无工单记录");
// conn.close();
// return(callback+"("+jReturn.toString()+")");
// }
//保存统计结果
for (String orderlist : orderList) {
String[] orderArray = orderlist.split("\t");
String date = orderArray[0];
String num = orderArray[1];
jsonObject.put(date, Integer.parseInt(num));
}
jReturn.put("result", 0);
jReturn.put("resultText", jsonObject.toString());
System.out.println("结果="+jReturn.toString());
conn.close();
return(callback+"("+jReturn.toString()+")");
}
}
<file_sep>package pre_deal;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.Principal;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import my_hbase.Get_Hbase;
import myquery.Gets_HBase;
import myquery.Query;
import mysql.mysql_DML;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import cell_info.Find_Cell;
import domain.Grid;
import service.GridService;
@Controller
public class ComplaintStatistic{
private static Logger logger = Logger.getLogger(ComplaintStatistic.class);
@Autowired
private GridService gridService;
private String search_r;
private String search_t;
private String init_lon;
private String init_lat;
private String alarm_timerange;
private String perf_timerange;
private String range_type;
private String cellDensityThreshold;
private String AlarmLevel;
private String N;
public static String path = MyFilePath.TCPropertiesPath;
public void initParam(String paramFile) throws FileNotFoundException, IOException{
Properties props = new Properties();
props.load(new FileInputStream(paramFile));
search_r = props.getProperty("search_r");
search_t = props.getProperty("search_t");
init_lon = props.getProperty("init_lon");
init_lat = props.getProperty("init_lat");
alarm_timerange = props.getProperty("alarm_timerange");
perf_timerange = props.getProperty("perf_timerange");
range_type = props.getProperty("range_type");
AlarmLevel = props.getProperty("alarmlevel");
cellDensityThreshold = props.getProperty("cellDensityThreshold");
N = props.getProperty("N");
}
/*
* author:yl
* date:2015.12.1
*
url:xxx/statistic_by_date.html,
type: "GET",
data: {"start_time": "2015-11-30",
"end_time" : "2015-12-01 "}
response: {"categories":["2015/11/28","2015/11/29","2015/11/30","2015/12/01","2015/12/02"],
"data":[123,224,25,223,324]
}
*/
@RequestMapping(value = "/statistic_by_date", method = RequestMethod.GET, produces = "charset=utf-8")
@ResponseBody
public String statistic_by_date(HttpServletRequest request,HttpServletResponse response) throws ParseException, ClassNotFoundException, FileNotFoundException, SQLException, IOException
{
logger.info("\n调用statistic_by_date函数");
response.setCharacterEncoding("UTF-8");
String start_time = URLDecoder.decode(request.getParameter("start_time"), "UTF-8");
String end_time = URLDecoder.decode(request.getParameter("end_time"), "UTF-8");
initParam(path);
//创建数据库连接
mysql_DML dml = new mysql_DML();
Connection conn = dml.myConnection();//创建连接,后面记得关闭连接
//返回给前端的数据
JSONObject jsonObject = new JSONObject();
//存储结果的动态数组
ArrayList<String> categoriesList = new ArrayList<String>();
ArrayList<Integer> dataList = new ArrayList<Integer>();
SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String s_time = sDateFormat.format(sDateFormat.parse(start_time));
String e_time = sDateFormat.format(sDateFormat.parse(end_time));
String day_after = "";
for(int i = 0; ;i ++){
if (day_after.equals(e_time)) {
break;
}
//获取某一天的后i天
Calendar calendar = Calendar.getInstance();
Date date = sDateFormat.parse(s_time);
calendar.setTime(date);
int day = calendar.get(Calendar.DATE);
calendar.set(Calendar.DATE, day + i);
day_after = sDateFormat.format(calendar.getTime());//开始时间后面的第i天
logger.info(s_time + "后面第" + i + "天是" + day_after);
int count = 0;//投诉记录次数,默认为0
//统计某一天投诉记录的总次数
String sqlString = "SELECT count(*) FROM pre_deal_records WHERE DATE(complaint_time) = ' " +
day_after + "'";
ArrayList<String> countArrayList = dml.selectMysql(sqlString, conn);
if (countArrayList.isEmpty()) {
count = 0;
}else {
count = Integer.parseInt(countArrayList.get(0).split("\t")[0]);
}
categoriesList.add(day_after);
dataList.add(count);
}
jsonObject.put("categories", categoriesList);
jsonObject.put("data", dataList);
logger.info("这是返回的话单信息的Json数据格式: " + jsonObject.toString());
logger.info("\n退出statistic_by_date函数");
conn.close();
return (jsonObject.toString());
}
/*
* author:yl
* date:2015.12.1
*
url:xxx/statistic_by_datetime.html,
type: "GET",
data: {"start_time": "2015-11-30 20:00",
"end_time" : "2015-12-01 20:00"}
response: {"categories":["2015/11/28","2015/11/29","2015/11/30","2015/12/01","2015/12/02"],
"data":[123,224,25,223,324]
}
*/
@RequestMapping(value = "/statistic_by_datetime", method = RequestMethod.GET, produces = "charset=utf-8")
@ResponseBody
public String statistic_by_datetime(HttpServletRequest request,HttpServletResponse response) throws ParseException, ClassNotFoundException, FileNotFoundException, SQLException, IOException
{
response.setCharacterEncoding("UTF-8");
String start_time = URLDecoder.decode(request.getParameter("start_time"), "UTF-8");
String end_time = URLDecoder.decode(request.getParameter("end_time"), "UTF-8");
initParam(path);
logger.info("取到的数据:" + start_time + " " + end_time);
String start_time1 = start_time.substring(0, 14) + "00";
String end_time1 = end_time.substring(0, 14) + "00";
//创建数据库连接
mysql_DML dml = new mysql_DML();
Connection conn = dml.myConnection();//创建连接,后面记得关闭连接
//返回给前端的数据
JSONObject jsonObject = new JSONObject();
//存储结果的动态数组
ArrayList<String> categoriesList = new ArrayList<String>();
ArrayList<Integer> dataList = new ArrayList<Integer>();
SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:00");
String s_hour = sDateFormat.format(sDateFormat.parse(start_time1));
String e_hour = sDateFormat.format(sDateFormat.parse(end_time1));
logger.info("格式转换后:" + s_hour + " " + e_hour);
String hour_before = "";
String hour_after = "";
for(int i = 0; ;i ++){
if (hour_after.equals(e_hour)) {
break;
}
//获取某个时间的后i个小时
long time_stamp = sDateFormat.parse(s_hour).getTime()/1000 + i * 3600;
long time_stamp1 = sDateFormat.parse(s_hour).getTime()/1000 + (i + 1) * 3600;
Date time =new Date(time_stamp * 1000);
Date time1 =new Date(time_stamp1 * 1000);
hour_before = sDateFormat.format(time);
hour_after = sDateFormat.format(time1);
logger.info("往后推" + i + "个小时:" + hour_before + " " + hour_after);
int count = 0;//投诉记录次数,默认为0
//统计某一天投诉记录的总次数
String sqlString = "SELECT count(*) FROM pre_deal_records WHERE complaint_time BETWEEN ' " +
hour_before + "'" + " AND '" + hour_after + "'";
ArrayList<String> countArrayList = dml.selectMysql(sqlString, conn);
if (countArrayList.isEmpty()) {
count = 0;
}else {
count = Integer.parseInt(countArrayList.get(0).split("\t")[0]);
}
categoriesList.add(hour_before);
dataList.add(count);
}
jsonObject.put("categories", categoriesList);
jsonObject.put("data", dataList);
logger.info("这是返回的话单信息的Json数据格式: " + jsonObject.toString());
logger.info("\n退出statistic_by_datetime函数");
conn.close();
return (jsonObject.toString());
}
/*
* author:yl
* date:2015.12.1
*
url : xxx/statistic_by_geography.html,
type:"GET",
data: {"start_time": "2015-011-30",
"end_time" : "2015-12-01 "}
response: {"categories":["武汉","宜昌","荆州","荆门","黄冈"],
"data":[123,224,25,223,324]
}
*/
@RequestMapping(value = "/statistic_by_geography", method = RequestMethod.GET, produces = "charset=utf-8")
@ResponseBody
public String statistic_by_geography(HttpServletRequest request,HttpServletResponse response) throws ParseException, ClassNotFoundException, FileNotFoundException, SQLException, IOException
{
response.setCharacterEncoding("UTF-8");
String start_time = URLDecoder.decode(request.getParameter("start_time"), "UTF-8");
String end_time = URLDecoder.decode(request.getParameter("end_time"), "UTF-8");
initParam(path);
//创建数据库连接
mysql_DML dml = new mysql_DML();
Connection conn = dml.myConnection();//创建连接,后面记得关闭连接
//返回给前端的数据
JSONObject jsonObject = new JSONObject();
SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String s_time = sDateFormat.format(sDateFormat.parse(start_time));
String e_time = sDateFormat.format(sDateFormat.parse(end_time));
String area = "";
//每个地区的被投诉次数
int cwuhan = 0;
int cshiyan = 0;
int chuangshi = 0;
int censhi = 0;
int chuanggang = 0;
int cyichang = 0;
int cxiangyang = 0;
int cjingmen = 0;
int cxianning = 0;
int csuizhou = 0;
int cjingzhou = 0;
int cezhou = 0;
int cxiaogan = 0;
//存储结果的动态数组
ArrayList<String> categoriesList = new ArrayList<String>();
ArrayList<Integer> dataList = new ArrayList<Integer>();
categoriesList.add("武汉");
categoriesList.add("十堰");
categoriesList.add("黄石");
categoriesList.add("恩施");
categoriesList.add("黄冈");
categoriesList.add("孝感");
categoriesList.add("宜昌");
categoriesList.add("襄阳");
categoriesList.add("荆门");
categoriesList.add("咸宁");
categoriesList.add("随州");
categoriesList.add("荆州");
categoriesList.add("鄂州");
//统计某一天投诉记录的总次数
String sqlString = "SELECT call_location FROM pre_deal_records WHERE DATE(complaint_time) BETWEEN ' " +
s_time + "'" + " AND '" + e_time + "'";
ArrayList<String> locationArrayList = dml.selectMysql(sqlString, conn);
if (locationArrayList.isEmpty()) {
return (jsonObject.toString());
}else {
for (String s : locationArrayList) {
area = s.split("\t")[0];
if (area.contains("武汉")) {
cwuhan ++;
continue;
}else if (area.contains("十堰")) {
cshiyan ++;
continue;
}else if (area.contains("黄石")) {
chuangshi ++;
continue;
}else if (area.contains("恩施")) {
censhi ++;
continue;
}else if (area.contains("黄冈")) {
chuanggang ++;
continue;
}else if (area.contains("孝感")) {
cxiaogan ++;
continue;
}else if (area.contains("宜昌")) {
cyichang ++;
continue;
}else if (area.contains("襄阳")) {
cxiangyang ++;
continue;
}else if (area.contains("荆门")) {
cjingmen ++;
continue;
}else if (area.contains("咸宁")) {
cxianning ++;
continue;
}else if (area.contains("随州")) {
csuizhou ++;
continue;
}else if (area.contains("荆州")) {
cjingzhou ++;
continue;
}else if (area.contains("鄂州")) {
cezhou ++;
continue;
}else {
continue;
}
}
}
dataList.add(cwuhan);
dataList.add(cshiyan);
dataList.add(chuangshi);
dataList.add(censhi);
dataList.add(chuanggang);
dataList.add(cxiaogan);
dataList.add(cyichang);
dataList.add(cxiangyang);
dataList.add(cjingmen);
dataList.add(cxianning);
dataList.add(csuizhou);
dataList.add(cjingzhou);
dataList.add(cezhou);
jsonObject.put("categories", categoriesList);
jsonObject.put("data", dataList);
logger.info("这是返回的话单信息的Json数据格式: " + jsonObject.toString());
logger.info("\n退出statistic_by_geography函数");
conn.close();
return (jsonObject.toString());
// //在related_cells中选出被投诉次数前十的小区
// String sqlString2 = "SELECT location,COUNT(*) AS location FROM related_cells WHERE record_id >=" + id_min + " and " +
// "record_id <= " + id_max + " GROUP BY location ORDER BY location DESC LIMIT 0,10";
}
/*
* author:yl
* date:2015.12.1
*
url : xxx/statistic_by_geography_TOPN.html,
type:"GET",
data: {"start_time": "2015-11-30",
"end_time" : "2015-12-01 "}
response: [{N: 10},
{order_num:21,
longitude: 143.555,
latitude: 32.456,
complaint_times:1,
}]
*/
@RequestMapping(value = "/statistic_by_geography_TOPN", method = RequestMethod.GET, produces = "charset=utf-8")
@ResponseBody
public String statistic_by_geography_TOPN(HttpServletRequest request,HttpServletResponse response) throws ParseException, ClassNotFoundException, FileNotFoundException, SQLException, IOException
{
response.setCharacterEncoding("UTF-8");
String start_time = URLDecoder.decode(request.getParameter("start_time"), "UTF-8");
String end_time = URLDecoder.decode(request.getParameter("end_time"), "UTF-8");
initParam(path);
//创建数据库连接
mysql_DML dml = new mysql_DML();
Connection conn = dml.myConnection();//创建连接,后面记得关闭连接
//返回给前端的数据
JSONArray jsonArray = new JSONArray();
SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String s_time = sDateFormat.format(sDateFormat.parse(start_time));
String e_time = sDateFormat.format(sDateFormat.parse(end_time));
int count = 0;//投诉记录次数,默认为0
String grid_id = "";
int idmin = 0;
int idmax = 0;
String sqlString1 = "SELECT record_id FROM pre_deal_records WHERE DATE(complaint_time) BETWEEN '" +
s_time + "' AND '" + e_time + "'";
ArrayList<String> recordidArrayList = dml.selectMysql(sqlString1, conn);
if (recordidArrayList.isEmpty()) {
return (jsonArray.toString());
}else {
idmin = Integer.parseInt(recordidArrayList.get(0).split("\t")[0]);
idmax = Integer.parseInt(recordidArrayList.get(recordidArrayList.size() - 1).split("\t")[0]);
}
//统计某一天投诉记录的总次数
String sqlString = "SELECT grid_id, COUNT(*) AS num FROM related_grids WHERE " +
"record_id >= " + idmin + " AND record_id <= " + idmax +" GROUP BY grid_id " +
" ORDER BY num DESC limit 0," +
Integer.parseInt(N);
logger.info(sqlString);
JSONObject jb = new JSONObject();
ArrayList<String> countArrayList = dml.selectMysql(sqlString, conn);
if (countArrayList.isEmpty()) {
count = 0;
return (jsonArray.toString());
}else {
//表头
JSONObject jsonObject = new JSONObject();
jsonObject.put("N", N);
jsonArray.add(jsonObject);
int i = 1;
String lon = "";
String lat = "";
for(String s : countArrayList){
grid_id = s.split("\t")[0];
//根据grid_id查询经纬度
String sqlString2 = "SELECT gps_lon,gps_lat FROM grid_info WHERE grid_x = " +
Integer.parseInt(grid_id.split("\\^")[0]) +
" AND grid_y = " + Integer.parseInt(grid_id.split("\\^")[1]) ;
logger.info(sqlString2);
ArrayList<String> list = dml.selectMysql(sqlString2, conn);
if (list.isEmpty()) {
continue;
}else {
lon = list.get(0).split("\t")[0];
lat = list.get(0).split("\t")[1];
}
count = Integer.parseInt(s.split("\t")[1]);
jb.put("order_num", i);
jb.put("longitude", lon);
jb.put("latitude", lat);
jb.put("complaint_times", count);
jsonArray.add(jb);
i ++;
}
}
logger.info("这是返回的话单信息的Json数据格式: " + jsonArray.toString());
logger.info("\n退出statistic_by_geography_TOPN函数");
conn.close();
return (jsonArray.toString());
}
/*
url : xxx/statistic_by_phonenumber.html,
type:"GET",
data: {"start_time": "2015-11-30",
"end_time" : "2015-12-01 "}
response: [{ order_num:21,
complaint_times:1,
phone:xxx,
main_reason:"XXX"}]
*/
@RequestMapping(value = "/statistic_by_phonenumber", method = RequestMethod.GET, produces = "charset=utf-8")
@ResponseBody
public String statistic_by_phonenumber(HttpServletRequest request,HttpServletResponse response) throws ParseException, ClassNotFoundException, FileNotFoundException, SQLException, IOException
{
response.setCharacterEncoding("UTF-8");
String start_time = URLDecoder.decode(request.getParameter("start_time"), "UTF-8");
String end_time = URLDecoder.decode(request.getParameter("end_time"), "UTF-8");
initParam(path);
//创建数据库连接
mysql_DML dml = new mysql_DML();
Connection conn = dml.myConnection();//创建连接,后面记得关闭连接
//返回给前端的数据
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String s_time = sDateFormat.format(sDateFormat.parse(start_time));
String e_time = sDateFormat.format(sDateFormat.parse(end_time));
int count = 0;//投诉记录次数,默认为0
int i = 0;
String phone = "";
String sqlString1 = "SELECT phone , COUNT(*) AS phone FROM pre_deal_records WHERE DATE(complaint_time) " +
"BETWEEN '" + s_time + "' AND '" + e_time + "' GROUP BY phone ORDER BY COUNT(*) DESC";
ArrayList<String> phoneArrayList = dml.selectMysql(sqlString1, conn);
if (phoneArrayList.isEmpty()) {
return (jsonArray.toString());
}else {
for (String string : phoneArrayList) {
i ++;
phone = string.split("\t")[0];
count = Integer.parseInt(string.split("\t")[1]);
jsonObject.put("order_num", i);
jsonObject.put("complaint_times", count);
jsonObject.put("phone", phone);
//查询该手机号的主原因分布
int main_cause_code = 0;//主原因代码
String maincause = "";//主原因
String sqlString = "SELECT DISTINCT mainCause_code FROM pre_deal_records WHERE phone = '" +
phone + "'";
logger.info(sqlString);
ArrayList<String> causeList = dml.selectMysql(sqlString, conn);
System.out.println(causeList + "%%%%%%");
if (causeList.isEmpty()) {
maincause = "";
jsonObject.put("main_reason", maincause);
}else {
for (String string2 : causeList) {
main_cause_code = Integer.parseInt(string2.split("\t")[0]);
switch (main_cause_code) {
case 0:
maincause += "无;";
break;
case 1:
maincause += "维护问题;";
break;
case 2:
maincause += "网优问题;";
break;
case 3:
maincause += "核心侧问题;";
break;
case 4:
maincause += "用户侧问题;";
break;
case 5:
maincause += "建设问题;";
break;
case -2:
maincause += "预判结果主辅原因无法判断;";
break;
default:
maincause += "无明显异常;";
break;
}
}
jsonObject.put("main_reason", maincause);
}
jsonArray.add(jsonObject);
}
}
System.out.println("这是返回的话单信息的Json数据格式: " + jsonArray.toString());
logger.info("\n退出statistic_by_phonenumber函数");
conn.close();
return (jsonArray.toString());
}
/*
* author:yl
* date:2015.12.1
*
url : xxx/statistic_by_station_error.html,
type:"GET",
data: {"start_time": "2015-11-30",
"end_time" : "2015-12-01 "}
response: [{N: 10},
{station_mark:"XXX",
name: "XXX",
city: “武汉”,
complaint_times:1}]
*/
@RequestMapping(value = "/statistic_by_station_error", method = RequestMethod.GET, produces = "charset=utf-8")
@ResponseBody
public String statistic_by_station_error(HttpServletRequest request,HttpServletResponse response) throws ParseException, ClassNotFoundException, FileNotFoundException, SQLException, IOException
{
response.setCharacterEncoding("UTF-8");
String start_time = URLDecoder.decode(request.getParameter("start_time"), "UTF-8");
String end_time = URLDecoder.decode(request.getParameter("end_time"), "UTF-8");
initParam(path);
//创建数据库连接
mysql_DML dml = new mysql_DML();
Connection conn = dml.myConnection();//创建连接,后面记得关闭连接
//返回给前端的数据
JSONArray jsonArray = new JSONArray();
SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String s_time = sDateFormat.format(sDateFormat.parse(start_time));
String e_time = sDateFormat.format(sDateFormat.parse(end_time));
String markString = "";
String city = "";
String location = "";
int count = 0;//投诉记录次数,默认为0
String sqlString1 = "SELECT CONCAT_WS('_',ecp,bts,cell),COUNT(CONCAT_WS('_',ecp,bts,cell)) AS num " +
"FROM related_alarms WHERE DATE(curr_time) BETWEEN '" + s_time + "' AND '" + e_time + "' " +
"GROUP BY CONCAT_WS('_',ecp,bts,cell) ORDER BY num DESC limit 0," + Integer.parseInt(N);
logger.info(sqlString1);
ArrayList<String> alarmArrayList = dml.selectMysql(sqlString1, conn);
if (alarmArrayList.isEmpty()) {
return (jsonArray.toString());
}else {
//表头
JSONObject jsonObject = new JSONObject();
jsonObject.put("N", N);
jsonArray.add(jsonObject);
JSONObject jb = new JSONObject();
for (String string : alarmArrayList) {
markString = string.split("\t")[0];
count = Integer.parseInt(string.split("\t")[1]);
jb.put("station_mark", markString);
jb.put("complaint_times", count);
//查询该基站的city和location
String sqlString = "SELECT city, location FROM im_cell_info WHERE ecp = " +
Integer.parseInt(markString.split("_")[0]) + " and bts = " +
Integer.parseInt(markString.split("_")[1]) + " and cell = " +
Integer.parseInt(markString.split("_")[2]);
ArrayList<String> list = dml.selectMysql(sqlString, conn);
if (list.isEmpty()) {
city = "";
location = "";
}else {
city = list.get(0).split("\t")[0];
location = list.get(0).split("\t")[1];
}
jb.put("city", city);
jb.put("name", location);
jsonArray.add(jb);
}
}
logger.info("这是返回的话单信息的Json数据格式: " + jsonArray.toString());
logger.info("\n退出statistic_by_station_error函数");
conn.close();
return (jsonArray.toString());
}
/*
* author:yl
* date:2015.12.1
*
url : xxx/statistic_by_cell_performance.html,
type:"GET",
data: {"start_time": "2015-11-30",
"end_time" : "2015-12-01 "}
response: [{N: 10},
{station_mark:"XXX",
name: "XXX",
city: “武汉”,
complaint_times:1}]
*/
@RequestMapping(value = "/statistic_by_cell_performance", method = RequestMethod.GET, produces = "charset=utf-8")
@ResponseBody
public String statistic_by_cell_performance(HttpServletRequest request,HttpServletResponse response) throws ParseException, ClassNotFoundException, FileNotFoundException, SQLException, IOException
{
response.setCharacterEncoding("UTF-8");
String start_time = URLDecoder.decode(request.getParameter("start_time"), "UTF-8");
String end_time = URLDecoder.decode(request.getParameter("end_time"), "UTF-8");
initParam(path);
//创建数据库连接
mysql_DML dml = new mysql_DML();
Connection conn = dml.myConnection();//创建连接,后面记得关闭连接
//返回给前端的数据
JSONArray jsonArray = new JSONArray();
SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String s_time = sDateFormat.format(sDateFormat.parse(start_time));
String e_time = sDateFormat.format(sDateFormat.parse(end_time));
String markString = "";
String city = "";
String location = "";
int count = 0;//投诉记录次数,默认为0
String sqlString1 = "SELECT CONCAT_WS('_',ecp,bts,cell),COUNT(CONCAT_WS('_',ecp,bts,cell)) AS num " +
"FROM related_perf WHERE warning_date BETWEEN '" + s_time + "' AND '" + e_time + "' " +
"GROUP BY CONCAT_WS('_',ecp,bts,cell) ORDER BY num DESC limit 0," + Integer.parseInt(N);
logger.info(sqlString1);
ArrayList<String> alarmArrayList = dml.selectMysql(sqlString1, conn);
if (alarmArrayList.isEmpty()) {
return (jsonArray.toString());
}else {
//表头
JSONObject jsonObject = new JSONObject();
jsonObject.put("N", N);
jsonArray.add(jsonObject);
JSONObject jb = new JSONObject();
for (String string : alarmArrayList) {
markString = string.split("\t")[0];
count = Integer.parseInt(string.split("\t")[1]);
jb.put("station_mark", markString);
jb.put("complaint_times", count);
//查询该基站的city和location
String sqlString = "SELECT city, location FROM im_cell_info WHERE ecp = " +
Integer.parseInt(markString.split("_")[0]) + " and bts = " +
Integer.parseInt(markString.split("_")[1]) + " and cell = " +
Integer.parseInt(markString.split("_")[2]);
ArrayList<String> list = dml.selectMysql(sqlString, conn);
if (list.isEmpty()) {
city = "";
location = "";
}else {
city = list.get(0).split("\t")[0];
location = list.get(0).split("\t")[1];
}
jb.put("city", city);
jb.put("name", location);
jsonArray.add(jb);
}
}
logger.info("这是返回的话单信息的Json数据格式: " + jsonArray.toString());
logger.info("\n退出statistic_by_station_error函数");
conn.close();
return (jsonArray.toString());
}
// url:xxx/statistic_by_prejudging_reason.html,
// type: "GET",
// data: {"start_time": "2015-11-30",
// "end_time" : "2015-12-01 "}
//
// response: [ {"name":"基站故障","y":14},
// {"name":"基站故障","y":14},
// {"name":"基站故障","y":14},
// {"name":"基站故障","y":14}]
/********************************************************************************************
*方法名:statisticMainCause
*传入参数:{"startTime":2015-12-01,"endTime":2015-12-08}
*response: [ {"name":"维护问题","y":14},
// {"name":"网优问题","y":14},
// {"name":"建设问题","y":14},
// {"name":"核心侧","y":14},
// {"name":"用户侧","y":14},
// {"name":"无异常","y":14}]
16 pre_jgR_maint 1 维护问题
17 pre_jgR_netOpt 2 网优问题
18 pre_jgR_coreNet 3 核心侧问题
19 pre_jgR_user 4 用户侧问题
20 pre_jgR_const 5 建设问题
21 pre_jgR_norm 6 无明显异常
-2 数据不足,无法预判
*功能说明:统计 预判原因分布,各类预判主原因的次数和占比。
*author:JayLi
* @throws IOException
* @throws SQLException
* @throws ClassNotFoundException
* @throws FileNotFoundException
*******************************************************************************************/
@RequestMapping(value = "/statistic_by_prejudging_reason",method = RequestMethod.GET)
@ResponseBody
public String statistic_by_prejudging_reason(HttpServletRequest request, HttpServletResponse response)
throws FileNotFoundException, ClassNotFoundException, SQLException, IOException{
String startTime = URLDecoder.decode(request.getParameter("start_time"), "UTF-8");
String endTime = URLDecoder.decode(request.getParameter("end_time"), "UTF-8");
mysql_DML dml = new mysql_DML();
Connection conn = dml.myConnection();
int maintCount = 0;
int netOptCount = 0;
int coreNetCount = 0;
int userCount = 0;
int constructCount = 0; //统计建设问题出现次数
int normCount = 0;
int sum = 0;
double maintRate = 0;
double netOptRate = 0;
double coreNetRate = 0;
double userRate = 0;
double constructRate = 0;
double normRate = 0;
//从pre_deal_records中选出主要原因(不用统计辅助原因)的次数和类型
String sqlMainCause = "select mainCause_code, count(*) as numberOfTimes from pre_deal_records where " +
"call_time between '"+startTime+"' and '"+endTime+"' group by mainCause_code order by mainCause_code asc";
System.out.println("统计主原因语句sqlMainCause="+sqlMainCause);
ArrayList<String> mainCauseList = dml.selectMysql(sqlMainCause, conn);
System.out.println("统计主原因结果mainCauseList="+mainCauseList);
if (mainCauseList.isEmpty()) {
System.out.println("无投诉记录!");
return "[]";
}
for (String string : mainCauseList) {
String[] causeArray = string.split("\t");
if (causeArray.length != 2) { //每一行都有“主原因和次数”两个元素,若不够2个则数据异常,要过滤掉
continue;
}
int mainCauseNum = Integer.parseInt(causeArray[0]);
//记录每种主原因出现次数
switch (mainCauseNum) {
case 1: maintCount = Integer.parseInt(causeArray[1]); sum += Integer.parseInt(causeArray[1]); break;
case 2: netOptCount= Integer.parseInt(causeArray[1]); sum += Integer.parseInt(causeArray[1]); break;
case 3: coreNetCount= Integer.parseInt(causeArray[1]); sum += Integer.parseInt(causeArray[1]); break;
case 4: userCount= Integer.parseInt(causeArray[1]); sum += Integer.parseInt(causeArray[1]); break;
case 5: constructCount= Integer.parseInt(causeArray[1]); sum += Integer.parseInt(causeArray[1]); break;
case 6: normCount = Integer.parseInt(causeArray[1]); sum += Integer.parseInt(causeArray[1]); break;
default: System.out.println("此次不纳入统计: 主原因结果mainCause="+causeArray[0] + ",次数="+causeArray[1]); break;
}
}
System.out.println("各个主原因出现次数:总次数="+sum+",维护="+maintCount+",网优="+netOptCount+",核心侧="+coreNetCount
+",用户侧="+userCount+",建设="+constructCount+",无异常="+normCount);
//计算每个主原因的比重
maintRate = maintCount * 1.0 / sum ; //乘以1.0目的是转为浮点数计算,做除法就不会省去小数
netOptRate = netOptCount * 1.0 / sum ;
coreNetRate = coreNetCount * 1.0 / sum ;
userRate = userCount * 1.0 / sum ;
constructRate = constructCount * 1.0 / sum ;;
normRate = normCount * 1.0 / sum ;
System.out.println("各个主原因出现比例:维护="+maintRate+",网优="+netOptRate+",核心侧="+coreNetRate
+",用户侧="+userRate+",建设="+constructRate+",无异常="+normRate);
//返回前台数据 {"name":"基站故障","y":14}
JSONArray jArray = new JSONArray();
//1维护
JSONObject j1 = new JSONObject();
j1.put("name", "维护问题");
j1.put("y", maintCount);
jArray.add(j1);
//2网优
JSONObject j2 = new JSONObject();
j2.put("y", netOptCount);
j2.put("name", "网优问题");
jArray.add(j2);
//3核心侧
JSONObject j3 = new JSONObject();
j3.put("y", coreNetCount);
j3.put("name", "核心侧问题");
jArray.add(j3);
//4用户侧
JSONObject j4 = new JSONObject();
j4.put("y", userCount);
j4.put("name", "用户侧问题");
jArray.add(j4);
//5建设
JSONObject j5 = new JSONObject();
j5.put("y", constructCount);
j5.put("name", "建设问题");
jArray.add(j5);
//6无异常
JSONObject j6 = new JSONObject();
j6.put("y", normCount);
j6.put("name", "无异常");
jArray.add(j6);
JSONObject jreturn = new JSONObject();
jreturn.put("excuse_pie", jArray);
conn.close();
System.out.println("统计主要原因返回结果jreturn="+jreturn.toString());
return jreturn.toString();
}
}<file_sep>define([
'underscore',
'backbone',
'marionette',
"tpl!views/partials/common/common_t/callInfo.tpl",
"tpl!views/partials/common/common_t/CFCModal.tpl",
], function(_, Backbone, Marionette, callInfoTpl, CFCModalTpl) {
"use strict";
var CallInfoView = Backbone.Marionette.ItemView.extend({
tagName: "tr",
// className: "table",
template: callInfoTpl,
CFCTemplate: CFCModalTpl,
events:{
"click #CFC_CFCQ": "toggleCFCModal"
},
CFCMap:{
"1": "normal call",
"2": "dropped call",
"3": "origination failed-subscriber",
"4": "termination failed-subscriber",
"5": "origination failed-ECP",
"6": "termination failed-ECP",
"7": "origination failed-DCS/network",
"8": "termination failed-DCS/network",
"9": "origination failed-cell",
"10": "termination failed-cell",
"11": "origination failed-network element independent",
"12": "termination failed-network element independent",
"13": "call failed-network element independent",
"14": "Short Message Service (SMS)",
"15": "Origination failed due to RNC",
"16": "Termination failed due to RNC",
"17": "origination failed-network/PCF",
"18": "termination failed-network/PCF",
"19": "Normal ANSI 41 Call Delivery",
"20": "Outbound Call Failure",
"21": "ANSI 41 Signaling Failure",
"22": "Abandoned Calls",
"25": "DO VoIP to 1X Circuit Voice' Handoff Failed",
"26": "IOS Origination Setup Failed",
},
CFCQMap:{
"1": "Call answered and ended normally",
"2": "Call unanswered and ended normally",
"3": "Called party was busy",
"4": "Unanswered call (alert timeout) from cell",
"5": "Handoff to another MSC",
"6": "Reacquired on analog",
"7": "Termination abandon",
"8": "No page response for terminating call",
"9": "Inter-DCS hard handoff to analog",
"10": "Soft handoff to another DCS",
"11": "Concurrent feature activation completed",
"12": "SMS call on Idle Traffic channel",
"13": "SMS call on Busy Traffic channel",
"14": "SMS call on Paging channel",
"15": "SMS call on Access channel",
"16": "Tandem call",
"17": "Intra-DCS Hard Handoff to Analog",
"18": "RLP Timeout",
"21": "RP_CLOSED",
"22": "Mobile Inactivity Timeout",
"23": "Called party mobile was inactive",
"100": "Dropped call",
"101": "Mobile powered down",
"102": "Packet pipe disconnect",
"103": "Cell Stable Clear",
"104": "Cell shutdown - handoff complete timeout",
"105": "DCS failure",
"106": "Lost Call",
"107": "Zero pre-pay account balance",
"108": "Speech handler protocol failure",
"109": "Release Confirmation Failure",
"110": "Kill Call",
"111": "Miscellaneous Dropped Calls",
"112": "Bearer Path Failure at RNC",
"113": "Call ended because of redirection during IBLM feature execution for mobile origination cenario.",
"115": "Call ended because of redirection during DBSR feature execution for mobile rigination scenario.",
"200": "Origination inhibited",
"201": "ESN mismatch (Fraud)",
"202": "Stolen Mobile",
"203": "Roamer attempt denied",
"204": "Zero pre-pay account balance",
"205": "Unassigned number",
"206": "Misdialed number",
"300": "Termination Inhibited",
"301": "ESN mismatch (Fraud)",
"302": "Stolen Mobile",
"303": "Roamer attempt denied",
"304": "Zero pre-pay account balance",
"305": "Unassigned number",
"401": "ECP-related failure",
"402": "Unauthorized 3G HSPD attempt",
"403": "Database failure",
"404": "Secondary Treatment failure/blocking",
"500": "No idle speech handlers",
"501": "Speech handler request failure",
"502": "Speech handler activation failure",
"503": "Speech handler protocol failure",
"504": "Speech handler - packet pipe frame connectivity error",
"505": "Packet pipe connection failure",
"506": "Service option rejected",
"507": "DCS network blocked",
"508": "Remote trunk congestion",
"509": "PSTN Data Path (PDP) setup failure",
"510": "Other DCS/Network failure",
"511": "No NPH Resource Available",
"512": "No SIP Resource Available",
"513": "PH Activation Failure",
"514": "RTP Setup Failure",
"515": "RTP Protocol Failure",
"516": "SIP Local Failure",
"517": "No Network Route",
"518": "No ATM PSU-PSU Connectivity",
"519": "No IPSHO PSU-PSU Connectivity",
"520": "ATM Overload",
"521": "IPSHO Overload",
"522": "SIP Inter-working Failure",
"523": "No Idle Trunk",
"600": "Traffic channel confirmation failure",
"601": "Traffic channel activation failure",
"602": "Traffic channel unavailable",
"603": "Packet pipe blocked",
"604": "Walsh code unavailable",
"605": "Back-Haul Server (BHS) blocked",
"606": "Power control overload",
"607": "No speech handler assigned",
"608": "Alert confirmation failure",
"609": "Internal cell processing error",
"610": "Multi-Link Group (MLG) blocked",
"611": "Origination SO renegotiation from EVRC-B to EVRC has failed",
"612": "Origination SO renegotiation from EVRC-NW to EVRC has failed",
"700": "Network resource shortage",
"701": "Invalid teleservice ID",
"702": "Mobile not found",
"703": "SMS delivery postponed",
"704": "SMS service not supported",
"705": "Other SMS failure",
"800": "Successful ANSI 41 Call Delivery",
"820": "Outbound Call Setup Failure",
"830": "Access Denied",
"831": "Timeout",
"840": "Calling Party Disconnect Before LocationRequest/RoutingReq uest INV Sent",
"841": "Calling Party Disconnect After LocationRequest INV Sent",
"842": "Calling Party Disconnect After RoutingRequest INV Sent",
"843": "Calling Party Disconnect After LocationRequest ReturnResult with TLDN Received",
"844": "Calling Party Disconnect After RoutingRequest ReturnResult with TLDN Received",
"1503": "Internal RNC communication failure",
"1504": "No FSRM available",
"1505": "TP request failure",
"1507": "TP protocol failure",
"1704": "A10/A11 Failure",
"2510": "A21 Origination message cannot be processed",
"2520": "DO VoIP to 1X Circuit Voice Handoff Digit Analysis Failed",
"2530": "DO VoIP to 1X Circuit Voice Handoff - Service Option cannot be selected",
"2540": "DO VoIP to 1X Circuit Voice Handoff - Primary Cellcannot be identified",
"2550": "DO VoIP to 1X Circuit Voice Handoff - Primary Cell unable to setup HO",
"2560": "DO VoIP to 1X Circuit Voice Handoff - Speech Handler Failures",
"2570": "DO VoIP to 1X Circuit Voice Handoff - Cell Failed to Setup Traffic Channel",
"2580": "DO VoIP to 1X Circuit Voice Handoff Aborted by DO System",
"2601": "IOS Call Setup Failed due to RAN or Mobile",
"2801": "IOS Call Dropped due to RAN or Mobile",
"2901": "IOS Hard Handoff Failed due to RAN or Mobile",
},
toggleCFCModal: function(){
// this.model.toJSON()
$('#modalCFCDialog').html(CFCModalTpl);
var CFCMessage = this.CFCMap[this.model.get('CFC_CFCQ').split(",")[0]];
var CFCQMessage = this.CFCQMap[this.model.get('CFC_CFCQ').split(",")[1]];
$('#CFCMessage').html(CFCMessage);
$('#CFCQMessage').html(CFCQMessage);
$('#modalCFCDialog').modal('toggle');
}
});
return CallInfoView;
});<file_sep>define([
'underscore',
'backbone',
'marionette',
'backbone_modelbinder',
'models/parameters',
'models/parameters_getting',
"tpl!views/partials/common/common_t/setting.tpl",
], function(_, Backbone, Marionette, ModelBinder, Parameters, ParametersGetting, settingTpl) {
"use strict";
var SetOperationView = Marionette.ItemView.extend({
template: settingTpl,
model2: new ParametersGetting(),
events:{
"click #settingSubmit": "setParameter",
},
initialize: function() {
console.log('init setting view');
this.model = new Parameters();
//加入判断是否valid的必要代码
// this._modelBinder = new Backbone.ModelBinder();
// Backbone.Validation.bind(this, {
// valid: function (view, attr, selector) {
// var $el = view.$('[name=' + attr + ']'),
// $group = $el.closest('.form-group');
// $group.removeClass('has-error');
// $group.find('.help-block').html('').addClass('hidden');
// },
// invalid: function (view, attr, error, selector) {
// var $el = view.$('[name=' + attr + ']'),
// $group = $el.closest('.form-group');
// $group.addClass('has-error');
// $group.find('.help-block').html(error).removeClass('hidden');
// }
// });
this.model2.fetch({
success: function(data){
$("[name='relatedCellCount'][value="+data.get('relatedCellCount')+"]").attr("checked",true);
$("[name='relatedCellDistance']").val(data.get('relatedCellDistance'));
// $("[name='relatedCellDistance'][value="+data.get('relatedCellDistance')+"]").attr("checked",true);
$("[name='errorSearchTime']").val(data.get('errorSearchTime'));
// $("[name='errorSearchTime'][value="+data.get('errorSearchTime')+"]").attr("checked",true);
$("[name='PCMASearchTime']").val(data.get('PCMASearchTime'));
// $("[name='PCMASearchTime'][value="+data.get('PCMASearchTime')+"]").attr("checked",true);
$("[name='ECIOThinThreshold'][value="+data.get('ECIOThinThreshold')+"]").attr("checked",true);
}
});
},
// onShow:function(){
// var bindings = {
// relatedCellCount: '[name=relatedCellCount]',
// relatedCellDistance: '[name=relatedCellDistance]',
// errorSearchTime: '[name=errorSearchTime]',
// PCMASearchTime:'[name=PCMASearchTime]',
// ECIOThinThreshold:'[name=ECIOThinThreshold]',
// };
// this._modelBinder.bind(this.model, this.el, bindings);
// },
setParameter: function(){
// console.log("1");
var data = {};
data.relatedCellCount = $("[name='relatedCellCount']:checked").val();
data.relatedCellDistance = $("[name='relatedCellDistance']").val();
data.errorSearchTime = $("[name='errorSearchTime']").val();
data.PCMASearchTime = $("[name='PCMASearchTime']").val();
data.ECIOThinThreshold = $("[name='ECIOThinThreshold']:checked").val();
if(data.relatedCellDistance<500||data.relatedCellDistance>5000){
$('.cell-wrapper span').removeClass('hidden').html("请保证关联小区距离范围在500-5000米区间内");
$('.cell-wrapper').addClass('has-error');
if(data.errorSearchTime<2||data.errorSearchTime>24){
$('.error-wrapper span').removeClass('hidden').html("请保证故障查询时间范围在2-24小时内");
$('.error-wrapper').addClass('has-error');
if(data.PCMASearchTime<2||data.PCMASearchTime>24){
$('.PCMA-wrapper span').removeClass('hidden').html("请保证话单查询时间范围在2-24小时内");
$('.PCMA-wrapper').addClass('has-error');
}
else{
$('.PCMA-wrapper span').addClass('hidden');
$('.PCMA-wrapper').removeClass('has-error');
}
}
else if(data.PCMASearchTime<2||data.PCMASearchTime>24){
$('.error-wrapper span').addClass('hidden');
$('.error-wrapper').removeClass('has-error');
$('.PCMA-wrapper span').removeClass('hidden').html("请保证话单查询时间范围在2-24小时内");
$('.PCMA-wrapper').addClass('has-error');
}
else{
$('.error-wrapper span').addClass('hidden');
$('.error-wrapper').removeClass('has-error');
$('.PCMA-wrapper span').addClass('hidden');
$('.PCMA-wrapper').removeClass('has-error');
}
}
// if(this.model.isValid(true))
else if(data.errorSearchTime<2||data.errorSearchTime>24){
$('.cell-wrapper span').addClass('hidden');
$('.cell-wrapper').removeClass('has-error');
$('.error-wrapper span').removeClass('hidden').html("请保证故障查询时间范围在2-24小时内");
$('.error-wrapper').addClass('has-error');
if(data.PCMASearchTime<2||data.PCMASearchTime>24){
$('.PCMA-wrapper span').removeClass('hidden').html("请保证话单查询时间范围在2-24小时内");
$('.PCMA-wrapper').addClass('has-error');
}
else{
$('.PCMA-wrapper span').addClass('hidden');
$('.PCMA-wrapper').removeClass('has-error');
}
}
// $('.error-wrapper span').addClass('hidden');
// $('.error-wrapper').removeClass('has-error');
else if(data.PCMASearchTime<2||data.PCMASearchTime>24){
$('.cell-wrapper span').addClass('hidden');
$('.cell-wrapper').removeClass('has-error');
$('.error-wrapper span').addClass('hidden');
$('.error-wrapper').removeClass('has-error');
$('.PCMA-wrapper span').removeClass('hidden').html("请保证话单查询时间范围在2-24小时内");
$('.PCMA-wrapper').addClass('has-error');
}
// $('.PCMA-wrapper span').addClass('hidden');
// $('.PCMA-wrapper').removeClass('has-error');
else{
this.model.save({
relatedCellCount: data.relatedCellCount,
relatedCellDistance: data.relatedCellDistance,
errorSearchTime: data.errorSearchTime,
PCMASearchTime: data.PCMASearchTime,
ECIOThinThreshold: data.ECIOThinThreshold,
}, {
success: function(data) {
alert("保存成功");
}
},{wait:true});
$('.cell-wrapper span').addClass('hidden');
$('.cell-wrapper').removeClass('has-error');
$('.error-wrapper span').addClass('hidden');
$('.error-wrapper').removeClass('has-error');
$('.PCMA-wrapper span').addClass('hidden');
$('.PCMA-wrapper').removeClass('has-error');
}
}
});
return SetOperationView;
});
<file_sep>define([''], function() {
"use strict";
var Cookie = function(){
}
// var set = function(c_name,value,expiredays)
var set = function(c_name,value)
{
// var exdate=new Date()
// exdate.setDate(exdate.getDate()+expiredays)
// document.cookie=c_name+ "=" +escape(value)+
// ((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
var exp = new Date();
exp.setTime(exp.getTime() + 60 * 1000 * 120);//设置过期时间为分钟
document.cookie = c_name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}
// var setvalue = function(c_name,value)
// {
// // var exdate=new Date()
// // exdate.setDate(exdate.getDate()+expiredays)
// // document.cookie=c_name+ "=" +escape(value)+
// // ((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
// var exp = new Date();
// exp.setTime(exp.getTime() + 60 * 1000 * 120);//设置过期时间为分钟
// document.cookie = c_name + "=" + value + ";expires=" + exp.toGMTString();
// }
var get = function(c_name)
{
if (document.cookie.length>0)
{
var c_start=document.cookie.indexOf(c_name + "=")
if (c_start!=-1)
{
c_start=c_start + c_name.length+1
var c_end=document.cookie.indexOf(";",c_start)
if (c_end==-1) c_end=document.cookie.length
return unescape(document.cookie.substring(c_start,c_end))
}
}
return ""
}
var check = function()
{
var username = this.get('username');
if (username!=null && username!=""){
// {alert('Welcome again '+username+'!')}//cookie中含有username字段时进行的操作
// window.location.assign('#home');
alert('欢迎回来!'+username);
window.close();
window.open('#home');
}
// else
// {
// username=prompt('Please enter your name:',"")
// if (username!=null && username!="")
// {
// // set('username',username,0.1)
// set('username',username)
// }
// }
}
var homecheck = function()
{
var username = this.get('username');
if (username!=null && username!=""){
// {alert('Welcome again '+username+'!')}//cookie中含有username字段时进行的操作
// window.location.assign('#home');
// alert('欢迎回来!'+username);
}
else
{
// window.location.assign('#login');
// Backbone.history.navigate('login', {trigger: true});
alert('您的登录信息已过期,请重新登录!');
window.close();
window.open('#login');
}
}
var clear = function(c_name)//通过设置过期时间为过去的时间,达到删除指定cookie的目的
{
var date = new Date();
date.setTime(date.getTime() - 10000);
document.cookie = c_name + "=a;expires="+date.toGMTString();
}
return {
Cookie: Cookie,
set: set,
get: get,
check: check,
homecheck: homecheck,
clear: clear,
// setvalue: setvalue
};
});<file_sep>define(['backbone',
'models/stationerror_count',
],
function(Backbone, StationerrorCount) {
var StationerrorCountCollection = Backbone.Collection.extend({
model: StationerrorCount,
initialize: function(options){
this.urlRoot = 'getting_station_error.html';
this.url = this.urlRoot;
}
});
return StationerrorCountCollection;
});<file_sep>jdbcDriver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://192.168.0.11:3306/appdata?useUnicode=true&characterEncoding=utf8
jdbcPass=<PASSWORD>
jdbcUser=whcsj<file_sep>define([
'underscore',
'backbone',
'marionette',
"tpl!views/partials/common/common_t/nodate.tpl",
], function(_, Backbone, Marionette, nodateTpl) {
"use strict";
var NoDateView = Marionette.ItemView.extend({
template: nodateTpl,
initialize: function() {
console.log('init nodate view');
},
});
return NoDateView;
});<file_sep>define([
'backbone'
], function(Backbone) {
"use strict";
var CellPerformanceAlert = Backbone.Model.extend({
});
return CellPerformanceAlert;
});<file_sep>var require = {
baseUrl: 'assets/scripts',
waitSeconds: 0,
// urlArgs: 'v=' + window.JS_VERSION || '',
paths: {
//lib
jquery: 'lib/jquery/jquery-2.1.1.min',
// bmap_api_home: 'lib/components/apiv2.0.min',
// bmap_api_new: 'lib/components/apiv2.0.087.min',
bmap_api: 'lib/components/apiv2.0.087.min',
// bmap_api: 'lib/components/api.offline.min',
cookie: 'lib/components/cookie',
clipboard: 'lib/components/clipboard',
// zeroclipboard: 'lib/components/ZeroClipboard.min',
// zclip: 'lib/components/jquery.zclip.min',
// heatmap: 'lib/components/heatmap.min',
bootstrap: 'lib/components/bootstrap.min',
highcharts: 'lib/components/highcharts.src',
// partials
bmap: 'views/partials/components/bmap',
// bmap_square_overlay: 'views/partials/components/bmap_square_overlay',
bmap_draw_district: 'views/partials/components/bmap_draw_district',
bmap_search_address: 'views/partials/components/bmap_search_address',
// Backbone
underscore: 'lib/mvc/underscore.min',
backbone: 'lib/mvc/backbone.min',
marionette: 'lib/mvc/backbone.marionette',
backbone_paginator: 'lib/mvc/backbone.paginator.min',
backbone_validation: 'lib/mvc/backbone.validation',
backbone_modelbinder: 'lib/mvc/backbone.modelbinder',
backgrid: 'lib/mvc/backgrid',
backgrid_paginator: 'lib/mvc/backgrid-paginator',
text: 'lib/mvc/text',
tpl: 'lib/mvc/underscore-tpl',
},
shim: {
bootstrap: {deps: ['jquery']},
datetimepicker: {deps: ['jquery']},
marionette: {deps: ['backbone']},
backbone_paginator: {deps: ['backbone']},
backbone_validation: {deps: ['backbone']},
backbone_modelbinder: {deps: ['backbone']},
backgrid: {deps: ['backbone','underscore'],exports: 'Backgrid'},
backgrid_paginator: {deps: ['backbone','underscore','backgrid','backbone_paginator'],exports: 'Paginator'},
tpl: {deps: ['text']},
bmap_api: {exports: 'BMap'},
// bmap_api_new: {exports: 'BMap'},
zeroclipboard: {exports: 'ZeroClipboard'},
zclip: {exports: 'ZClip'},
}
};
<file_sep>define([
'underscore',
'backbone',
'marionette',
'cookie',
'views/partials/common/header',
'views/partials/common/sideWrapper',
'views/partials/common/infoItemList',
'views/partials/common/infoItemSearch',
'views/partials/common/inputInfoItem',
'views/partials/common/itemJudgeResult',
'views/partials/common/judgeAssistant',
'views/partials/common/setting',
'views/partials/common/dateInspection',
'views/partials/common/alterPassword',
'views/partials/common/positionSelect',
'models/complaint_info',
'models/complaint_info_get',
'models/search_info',
"tpl!views/home/home_t/home.tpl",
], function(_, Backbone, Marionette, Cookie, HeaderView, SideWrapperView,
InfoItemListView, InfoItemSearchView, InputInfoItemView,
ItemJudgeResultView, JudgeAssistantView, SettingView, DateInspectionView, AlterPasswordView, PSelectView,
ComplaintInfo, ComplaintInfoGet, SearchInfo, homeTpl) {
"use strict";
var HomeView = Backbone.Marionette.LayoutView.extend({
template: homeTpl,
regions: {
header: '#header',
sideWrapper: '#sideWrapper',
mapInfoWrapper: '#mapInfoWrapper',
},
events: {
'click #inputMenu': 'showInputView',
'click #searchMenu': 'showSearchView',
'click #listMenu': 'showListView',
'click #settingMenu': 'showSettingView',
'click #inspectionMenu': 'showInspectionView',
'click #alterpasswordMenu': 'showAlertView',
},
initialize: function(options) {
//全局设置请求头,为了保证能够以正确编码方式读取汉字
(function(){
// Store the native, default sync method, we'll wrap this.
Backbone._nativeSync = Backbone.sync;
// Create our default options object
Backbone.defaultSyncOptions = {};
// Ever so gingerly wrap the native sync
// in a method that combines options
Backbone.sync = function( method, model, options) {
Backbone._nativeSync( method, model,
_.extend( {}, Backbone.defaultSyncOptions, options ) );
};
})();
// then just set the options:
Backbone.defaultSyncOptions = { headers: { "Content-Type":"application/json; charset=utf-8",
"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" } };
},
onShow: function(){
Cookie.homecheck();
this.currentTime = this.getCurentTime();
//只是用来测试,能够直接进入投诉结果页
// this.complaintInfo = new ComplaintInfo();
//用来存储搜索页的search数据,当渲染搜索页加载此数据
this.now = this.currentTime.substring(0,10)+'T'+this.currentTime.substring(11,16);
if(this.now.substring(5,7)-1==0){
this.oneMonthAgo = this.now.substring(0,3)+(this.now.substring(3,4)-1+"")+this.now.substring(4,5)+"12"+this.now.substring(7,16);
}
else if(this.now.substring(5,7)==10){
this.oneMonthAgo = this.now.substring(0,5)+"09"+this.now.substring(7,16);
}
else{
this.oneMonthAgo = this.now.substring(0,6)+(this.now.substring(6,7)-1+"")+this.now.substring(7,16);
}
this.searchInfo = new SearchInfo({start_time:this.oneMonthAgo,end_time:this.now});
var headerView = new HeaderView();
this.header.show(headerView);
// headerView.on('logOut',function(){
// Cookie.clear('username');
// window.close();
// window.open('#login');
// });
this.sideWrapper.show(new SideWrapperView());
// this.complaintInfo.set({
// "complaint_item_id": 132,
// "complaint_time":"2015-07-26 07:51",
// "occur_time":"2015-08-24 10:49",
// "pheno_option":"PH1001",
// "location":"武汉高铁站",
// "longitude":"114.260848",
// "latitude":"30.625334",
// "complaint_phone":"18971473689",
// "pheno_description":"没有信号"
// });
this.showInputView();
// this.showJudgeResult('132');
// this.showSearchView();
// this.showListView();
// this.showSettingView();
// setInterval(this.countSecond(),5000);
// setInterval(console.log('11'),5000);
},
showInputView: function(){
// function count(){
// this.countSecond();
var self = this;
var lng = Cookie.get('lng');
var lat = Cookie.get('lat');
var str = Cookie.get('location');
console.log(str);
var str1 = unescape(str.replace(/\u/g, "%u"));
console.log(str1);
var self = this;
var currentTime = this.getCurentTime();
var complaintInfo = new ComplaintInfo({complaint_time:currentTime,
occur_time:currentTime, pheno_option:"PH1001", staff_id:Cookie.get('staff_id'),
complaint_phone:Cookie.get('complaint_phone'), location:Cookie.get('location'),
longitude:Cookie.get('lng'), latitude:Cookie.get('lat')});
// , search_radius:Cookie.get('search_radius'),search_time_range:Cookie.get('search_time_range')
var inputInfoItemView = new InputInfoItemView({
model: complaintInfo
});
self.inputInfoItemView = inputInfoItemView;
this.mapInfoWrapper.show(inputInfoItemView);
inputInfoItemView.on('setLocation',function(){
var staff_id = inputInfoItemView.el.getElementsByTagName("input")[0].value;
var complaint_phone = inputInfoItemView.el.getElementsByTagName("input")[1].value;
var position = inputInfoItemView.el.getElementsByTagName("input")[2].value;
var longitude = inputInfoItemView.el.getElementsByTagName("input")[3].value;
var latitude = inputInfoItemView.el.getElementsByTagName("input")[4].value;
var search_radius = inputInfoItemView.el.getElementsByTagName("input")[5].value;
var search_time_range = inputInfoItemView.el.getElementsByTagName("input")[7].value;
Cookie.set('staff_id',staff_id);
Cookie.set('complaint_phone',complaint_phone);
Cookie.set('search_radius',search_radius);
Cookie.set('search_time_range',search_time_range);
// complaintInfo.set('staff_id',Cookie.get('staff_id'));
// complaintInfo.set('complaint_phone',Cookie.get('complaint_phone'));
// complaintInfo.set('search_radius',Cookie.get('search_radius'));
// complaintInfo.set('search_time_range',Cookie.get('search_time_range'));
var pSelectView = new PSelectView({position:position, longitude:longitude, latitude:latitude});
self.mapInfoWrapper.show(pSelectView);
pSelectView.on('backHome',function(){
// var n_complaintInfo = new ComplaintInfo({location:Cookie.get('location'),
// longitude:Cookie.get('lng'), latitude:Cookie.get('lat')});
// var n_inputInfoItemView = new InputInfoItemView({
// model: complaintInfo
// });
// self.mapInfoWrapper.show(n_inputInfoItemView);
// complaintInfo.set('location',Cookie.get('location'));
// complaintInfo.set('longitude',Cookie.get('lng'));
// complaintInfo.set('latitude',Cookie.get('lat'));
// self.mapInfoWrapper.show(self.inputInfoItemView);
// self.mapInfoWrapper.show(inputInfoItemView);
// history.go(0);
location.reload();
// location.href='#home';
});
});
inputInfoItemView.on('showComplaintResult', function(){
Cookie.clear('staff_id');
Cookie.clear('complaint_phone');
Cookie.clear('location');
Cookie.clear('lng');
Cookie.clear('lat');
Cookie.clear('search_radius');
Cookie.clear('search_time_range');
if (complaintInfo.get('complaint_phone')===""&&complaintInfo.get('location')===""&&
(complaintInfo.get('longitude')===""||complaintInfo.get('latitude')==="")) {
$('.longlat-wrapper span').removeClass('hidden').html("投诉号码、地点、经纬度必须输入至少一项");
$('.phone-wrapper').addClass('has-error');
$('.location-wrapper').addClass('has-error');
$('.longlat-wrapper').addClass('has-error');
}
else{
if (this.model.isValid(true)){
console.log('save complaintInfo');
if (complaintInfo.get('complaint_phone')===""){
complaintInfo.set('complaint_phone',"12345678901");
}
complaintInfo.save(null,{
success: function(){
//self.showJudgeResult(complaintInfo.get('complaint_item_id'));
window.open("#complaint/" + complaintInfo.get('complaint_item_id'));
},
error: function(data,resp,options){
alert(resp.responseText);
}
}, {wait:true});
}
}
});
inputInfoItemView.on('showInputView', function(){
// alert('1');
$('#inputMenu').trigger('click');
});
// }
// count();
},
showSearchView: function(){
var self = this;
var infoItemSearchView = new InfoItemSearchView({
model: this.searchInfo
});
this.mapInfoWrapper.show(infoItemSearchView);
//防止再次进入查询页面输入数据丢失
infoItemSearchView.on('passSearchInfo',function(searchInfo){
self.searchInfo.set('search_type',searchInfo.get('search_type'));
self.searchInfo.set('search_text', searchInfo.get('search_text'));
self.searchInfo.set('start_time', searchInfo.get('start_time'));
self.searchInfo.set('end_time', searchInfo.get('end_time'));
});
//点击“查看详情”按钮触发
infoItemSearchView.on('getItemDetail', function(args){
console.log(args.model);
var complaintSearchInfo = new ComplaintInfo();
complaintSearchInfo.set({
"complaint_item_id": args.model.get('complaint_item_id'),
"complaint_time":args.model.get('complaint_time'),
"occur_time":args.model.get('occur_time'),
"pheno_option":args.model.get('pheno_option'),
"location":args.model.get('location'),
"longitude":args.model.get('longitude'),
"latitude":args.model.get('latitude'),
"complaint_phone":args.model.get('complaint_phone'),
"pheno_description":args.model.get('pheno_description')});
// self.showJudgeResult(complaintSearchInfo.get('complaint_item_id'),'search');
window.open("#complaint/" + complaintSearchInfo.get('complaint_item_id'));
});
},
showListView: function(){
var currentTime = this.getCurentTime();
this.mapInfoWrapper.show(new InfoItemListView({'now':currentTime}));
// this.mapInfoWrapper.show(new InfoItemListView());
},
showSettingView: function(){
//修改地址栏显示
// Backbone.history.navigate('home');
this.mapInfoWrapper.show(new SettingView());
},
showInspectionView: function(){
var currentTime = this.getCurentTime();
this.mapInfoWrapper.show(new DateInspectionView({'now':currentTime}));
},
showAlertView:function(){
this.mapInfoWrapper.show(new AlterPasswordView());
},
showJudgeResult: function(complaintItemId,type){
var self = this;
var complaintInfoGet = new ComplaintInfoGet({id: complaintItemId});
complaintInfoGet.fetch({
success: function(data) {
// console.log(data);
//显示投诉结果页
var itemJudgeResultView = new ItemJudgeResultView({
model: complaintInfoGet
});
//用来判断结果页的“返回“按钮退回的页面
if(type===undefined){
type = 'input';
}
self.mapInfoWrapper.show(itemJudgeResultView);
if(type==='search'){
$('#back').attr('id','backSearch');
}
itemJudgeResultView.on('showInputView', function(args){
self.showInputView();
});
itemJudgeResultView.on('showSearchView', function(args){
self.showSearchView();
});
},
error: function(){
console.log('error');
}
}, {wait:true});
},
getCurentTime: function(){
var now = new Date();
var year = now.getFullYear(); //年
var month = now.getMonth() + 1; //月
var day = now.getDate(); //日
var hh = now.getHours(); //时
var mm = now.getMinutes(); //分
var clock = year + "-";
if(month < 10)
clock += "0";
clock += month + "-";
if(day < 10)
clock += "0";
clock += day + " ";
if(hh < 10)
clock += "0";
clock += hh + ":";
if (mm < 10) clock += '0';
clock += mm;
return(clock);
},
countSecond: function()
{
// function timedCount()
// {
// Cookie.
// setTimeout(timedCount(),1000)
// }
// timedCount();
// alert("jj");
// console.log("dsda");
}
});
return HomeView;
});
<file_sep>define(['backbone',
'models/performance_count',
],
function(Backbone, PerformanceCount) {
var PerformanceCountCollection = Backbone.Collection.extend({
model: PerformanceCount,
initialize: function(options){
this.urlRoot = 'getting_performance_indicator.html';
this.url = this.urlRoot;
}
});
return PerformanceCountCollection;
});<file_sep>define([
'backbone'
], function(Backbone) {
"use strict";
var CallCount = Backbone.Model.extend({
});
return CallCount;
});<file_sep>package com.hbase.cityReached;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
public class CityReached {
/**
* @param args
* @throws IOException
* @throws SQLException
* @throws FileNotFoundException
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws ClassNotFoundException, FileNotFoundException, SQLException, IOException {
CityReached cityReached = new CityReached();
long endTime = 1463245814;
System.out.println("e="+endTime);
long startTime = 1460645614;
System.out.println("s="+startTime);
// cityReached.getCityReached("18908699003",startTime,endTime);
Connection conn = MyDBManager.getInstance().getConnection();
PreparedStatement pst = null;
String sql="select seq from hbase_phone_cities where phone=? limit 1";
ArrayList<String> list = cityReached.getAllPhones("/data/jay/jayEclipseWorkspace/TS_test20151103/src/com/hbase/cityReached/phoneSource");
int seq=0;
for (String phone : list) {
seq=0;
System.out.println(phone);
ResultSet resultSet = MyDBManager.getInstance().selectData(sql, new Object[]{phone}, conn, pst);
try {
if (resultSet.next()) {
seq = resultSet.getInt("seq");
}
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("seq="+seq);
if (seq == 0) {
cityReached.getCityReached(phone,startTime,endTime,conn);
}
}
conn.close();
}
/*
* 加载文件,获取原始的8000个电话号码
* */
public ArrayList<String> getAllPhones(String filePath){
ArrayList<String> phoneList = new ArrayList<String>();
File file = new File(filePath);
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = null;
try {
while ((line=reader.readLine()) != null) {
//System.out.println(line);
phoneList.add(line.trim());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return phoneList;
}
/*
*0 输入手机号码、始末的时间的时间戳,找错这个电话号码的所有话单记录
* 返回其对象
* */
public void getCityReached(String phone, long startTime, long endTime,Connection conn){
ArrayList<Map<String, String>[]> value = null;
// try {
// value = Gets_HBase.pcmd_query(phone, startTime, endTime);
// } catch (ClassNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (FileNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
HashSet<String> set = new HashSet<String>();
int count=0;
for (Map<String, String>[] maps : value) {//该号码的所有话单
for (Map<String, String> map : maps) {//一条话单
System.out.println("map="+map);
String cityName = cell2City(map.get("start_cell"),conn);
String date = map.get("date");
String oneRecord = cityName+","+date;
System.out.println(++count+":"+oneRecord);
set.add(oneRecord); //自动去重同一个城市同一天的情况,得到的结果一定是互不相同的(如在同一个城市不同日期)
}//for
}//for
//把一个电话号码的结果保存到数据库
store2DB(phone,set,conn);
}
/*1 把小区转为所在的城市
* */
//start_cell=117,2,11(bts,cell,ecp)
private String cell2City(String start_cell,Connection conn) {
String cityName = null;
String[] cellStrings = start_cell.split(",");
int ecp = Integer.parseInt(cellStrings[2]);
int bts = Integer.parseInt(cellStrings[0]);
int cell = Integer.parseInt(cellStrings[1]);
if (ecp == 2) {
ecp = 9;
}
//查找数据库获取基站的城市
String sql = "SELECT city FROM im_cell_info WHERE ecp=? AND bts=? AND cell=?";
MyDBManager myManager = MyDBManager.getInstance();
PreparedStatement pst = null;
ResultSet resultSet = myManager.selectData(sql, new Object[]{ecp,bts,cell}, conn, pst);
try {
if (resultSet.next()) {
cityName = resultSet.getString("city");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (cityName == null || "".equals(cityName)) {
cityName = "DB无此小区所在城市";
}
return cityName;
}
/*2 保存到数据库
* */
private void store2DB(String phone,HashSet<String> set, Connection conn) {
// if (set ==null || set.isEmpty()) {
// return;
// }
LinkedHashMap<String, Integer> cityCountMap = new LinkedHashMap<String, Integer>();
cityCountMap.put("鄂州", 0);
cityCountMap.put("恩施", 0);
cityCountMap.put("黄冈", 0);
cityCountMap.put("黄石", 0);
cityCountMap.put("江汉", 0);
cityCountMap.put("荆门", 0);
cityCountMap.put("荆州", 0);
cityCountMap.put("十堰", 0);
cityCountMap.put("随州", 0);
cityCountMap.put("武汉", 0);
cityCountMap.put("咸宁", 0);
cityCountMap.put("襄樊", 0);
cityCountMap.put("孝感", 0);
cityCountMap.put("宜昌", 0);
if (set !=null && !set.isEmpty()) {
for (String string : set) { //set的元素是:cityName+","+date
if (string ==null || string.length() ==0) {
continue;
}
String city = string.split(",")[0];
if (cityCountMap.containsKey(city)) {//计数
int count = cityCountMap.get(city);
count ++;
cityCountMap.remove(city);
cityCountMap.put(city, count);
}
}//for
}
//存到数据库
MyDBManager myManager = MyDBManager.getInstance();
PreparedStatement pstm = null;
StringBuffer sBuffer= new StringBuffer();
//插入到横表,所有城市作为横标题
sBuffer.append("insert into hbase_phone_cities(phone,e_zhou,en_shi,huang_gang,huang_shi,jiang_han,jing_men,jing_zhou,shi_yan,sui_zhou,wu_han,xian_ning,xiang_fan,xiao_gan,yi_chang) values ");
sBuffer.append("('"+phone+"',");
Set<String> citySet = cityCountMap.keySet();
Iterator<String> it = citySet.iterator();
while (it.hasNext()) {
String cityName = (String) it.next();
int count = cityCountMap.get(cityName);
sBuffer.append(count+",");
}
sBuffer.delete(sBuffer.length()-1, sBuffer.length());//去掉最后一个逗号,
sBuffer.append(")");
//提交数据库,开始执行插入操作
try {
conn.setAutoCommit(false);
pstm = conn.prepareStatement("");
pstm.addBatch(sBuffer.toString());//手动提交
pstm.executeBatch();
conn.commit();
conn.setAutoCommit(true);//提交完成后回复现场将Auto commit,还原为true,
} catch (SQLException e) {
e.printStackTrace();
try {
if (!conn.isClosed()) {
conn.rollback();// 4,当异常发生执行catch中SQLException时,记得要rollback(回滚);
System.out.println("插入失败,回滚!");
conn.setAutoCommit(true);
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
<file_sep>define([
'backbone'
], function(Backbone) {
"use strict";
var StatisticByDateTime = Backbone.Model.extend({
initialize: function(options){
this.urlRoot = 'statistic_by_datetime.html';
this.url = this.urlRoot;
}
});
return StatisticByDateTime;
});<file_sep>define([
'underscore',
'backbone',
'marionette',
'cookie',
"tpl!views/partials/common/common_t/lonlatShow.tpl",
], function(_, Backbone, Marionette, Cookie, lonlatShowTpl) {
"use strict";
var LonlatShowView = Marionette.ItemView.extend({
template: lonlatShowTpl,
events: {
},
initialize: function() {
console.log('init lonlatshow view');
},
onShow: function(){
}
});
return LonlatShowView;
});
<file_sep>package com.order.query;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.jay.mysql.MysqlDML;
public class StatsOrderArea extends HttpServlet {
private static final long serialVersionUID = 1L;
//重写父类的doGet()方法
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("doget转dopost");
doPost(req,resp);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Access-Control-Allow-Origin", "*");
// //解决跨域问题
// response.setHeader("Pragma", "no-cache");
// response.setHeader("Cache-Control", "no-cache");
//// response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1/*");
// response.setHeader("Access-Control-Allow-Origin", "*");//所有协议、域名、端口都可以访问
// response.setDateHeader("Expires", 0);
//
//编写处理post请求的响应信息
String result ="";
try {
result = statsOrderArea(request,response);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PrintWriter pw=response.getWriter();
pw.println(result);
pw.flush();
pw.close();
}
/***********************************************************************************************************************
*传进参数格式 {“startDate”:2016-07-05,“endDate”:2016-07-11,“area”:“全省”}
返回值格式 {“result”:0,”resultText”:
{“phoneWeb”: {“武汉”:50, “仙桃”:11, “天门”:24, “潜江”:56, “孝感”:55, “黄冈”:113, “黄石”:87,“鄂州”:23, “咸宁”:23,
“随州”:23, “荆门”:23, “荆州”:23, “宜昌”:23, “襄阳”:23, “十堰”:23, “恩施”:23, “林区”:23 },
“controlCenter”:{“武汉”:50, “仙桃”:11, “天门”:24, “潜江”:56, “孝感”:55, “黄冈”:113, “黄石”:87 ,“鄂州”:23, “咸宁”:23,
“随州”:23, “荆门”:23, “荆州”:23, “宜昌”:23, “襄阳”:23, “十堰”:23, “恩施”:23, “林区”:23 }}}
或{“result”:-1,”resultText”:failed}
功能说明:当前账号管理下,(投诉时间发生在)最近一周的全部工单,按工单状态和来源分类统计
工单状态编码 10待审核(默认状态),20.待派单 30.待接单 40.处理中 50.已回复 61.已确认 62.已确认-服务台结单 0.已删除 -1.已清除(不作显示但需要记录)
* Author:JayLi
* @throws ParseException
*****************************************************************************************************************/
public String statsOrderArea(HttpServletRequest request,HttpServletResponse response)
throws FileNotFoundException, IOException, ClassNotFoundException, SQLException, ParseException {
System.out.println("调用statsOrderArea");
//解析传进来的参数
String callback = null;
String startDate = null;
String endDate = null;
String area = null;
JSONObject jReturn = new JSONObject();
try {
callback = request.getParameter("callback");
startDate = request.getParameter("startDate");
endDate =request.getParameter("endDate");
area =request.getParameter("area");
} catch (Exception e) {
jReturn.put("result", -1);
jReturn.put("resultText", "url参数异常");
return(callback+"("+jReturn.toString()+")");
}
if (startDate==null || "".equals(startDate)) {
jReturn.put("result", -1);
jReturn.put("resultText", "统计开始时间"+startDate+"错误");
return(callback+"("+jReturn.toString()+")");
}
if (endDate==null || "".equals(endDate)) {
jReturn.put("result", -1);
jReturn.put("resultText", "统计开始时间"+startDate+"错误");
return(callback+"("+jReturn.toString()+")");
}
//正则表达式匹配时间格式
Pattern pattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");
Matcher matcher1 = pattern.matcher(startDate);
Matcher matcher2 = pattern.matcher(endDate);
if (!matcher1.matches()) {
jReturn.put("result", -1);
jReturn.put("resultText", "统计开始时间"+startDate+"错误");
return(callback+"("+jReturn.toString()+")");
}
if (!matcher2.matches()) {
jReturn.put("result", -1);
jReturn.put("resultText", "统计结束时间"+endDate+"错误");
return(callback+"("+jReturn.toString()+")");
}
// 0 1 3 5 7 9 11 13 15
String[] cities = {"武汉","宜昌","荆门","黄冈","黄石","荆州","十堰","随州","孝感","咸宁","襄阳","恩施","林区","潜江","天门","仙桃","鄂州"};
int citySeq = 0;//标记查询类型类型是否需要分地区查询,全省则不用分地区查询,其他城市则要分地区,不存在的地区则报错返回。1是全省,2是其他城市,0是地区有错。
if ("全省".equals(area)) {
citySeq = 1;
}else {
for (String city : cities) {
if (city.equals(area)) {
citySeq = 2;
break;
}
}
}
//判断输入的地区是否正确
if (citySeq == 0) {
jReturn.put("result", -1);
jReturn.put("resultText", "输入的地区"+area+"错误");
return(callback+"("+jReturn.toString()+")");
}
MysqlDML dml = MysqlDML.getInstance();
Connection conn = dml.getMyConnection();
JSONObject jObjPhone = new JSONObject();
JSONObject jObjControlCenter = new JSONObject();
String sqlOrder = null;
int fromPhone = 1;
int fromControlCenter = 2;
if (citySeq == 1) {//全省
//1.1查询手机网页的数据
sqlOrder = "SELECT work_order_info.area_id,COUNT(work_order_info.area_id) AS num " +
"FROM work_order_info LEFT JOIN complaint_records " +
"ON work_order_info.complaint_id=complaint_records.complaint_id" +
" WHERE DATE(work_order_info.create_time) BETWEEN DATE('"+startDate+"') AND DATE('"+endDate+"') " +
"AND complaint_records.complaint_source=" +fromPhone+
" AND work_order_info.deal_status IN(10,20,30,40,50) " +
"GROUP BY work_order_info.area_id ORDER BY work_order_info.area_id; " ;
ArrayList<String> orderList = dml.selectData(sqlOrder, conn);
// if (orderList == null || orderList.isEmpty()) {
// System.out.println("查询时间"+startDate+"到"+endDate+"内无工单记录");
// jReturn.put("result", -1);
// jReturn.put("resultText", "查询时间"+startDate+"到"+endDate+"内无工单记录");
// conn.close();
// return(callback+"("+jReturn.toString()+")");
// }
//保存统计结果,防止统计结果有些城市没有数据,会漏掉的情况,用map设定初始值就不会漏了,没有的时候就是用初始值0
HashMap<Integer, Integer> statusMap = new LinkedHashMap<Integer, Integer>();
statusMap.put(0, 0);
statusMap.put(1, 0);
statusMap.put(2, 0);
statusMap.put(3, 0);
statusMap.put(4, 0);
statusMap.put(5, 0);
statusMap.put(6, 0);
statusMap.put(7, 0);
statusMap.put(8, 0);
statusMap.put(9, 0);
statusMap.put(10, 0);
statusMap.put(11, 0);
statusMap.put(12, 0);
statusMap.put(13, 0);
statusMap.put(14, 0);
statusMap.put(15, 0);
statusMap.put(16, 0);
//保存到map,注意从数据库拿到的城市id比数组cities的下标大1,所以要减去1才能匹配数组下标
for (String orderlist : orderList) {
String[] orderArray = orderlist.split("\t");
String area_id= orderArray[0];
String num = orderArray[1];
if (Integer.parseInt(area_id)>0&&Integer.parseInt(area_id)<18) {
statusMap.put(Integer.parseInt(area_id)-1, Integer.parseInt(num));
}
}
//保存到json中,键是城市的中文名
for (Iterator<Integer> iterator = statusMap.keySet().iterator(); iterator.hasNext();) {
int index = (Integer) iterator.next();
jObjPhone.put(cities[index], statusMap.get(index));
}
//1.2查询服务台的数据
sqlOrder = "SELECT work_order_info.area_id,COUNT(work_order_info.area_id) AS num " +
"FROM work_order_info LEFT JOIN complaint_records " +
"ON work_order_info.complaint_id=complaint_records.complaint_id" +
" WHERE DATE(work_order_info.create_time) BETWEEN DATE('"+startDate+"') AND DATE('"+endDate+"') " +
"AND complaint_records.complaint_source=" +fromControlCenter+
" AND work_order_info.deal_status IN(10,20,30,40,50) " +
"GROUP BY work_order_info.area_id ORDER BY work_order_info.area_id; " ;
orderList = dml.selectData(sqlOrder, conn);
// if (orderList == null || orderList.isEmpty()) {
// System.out.println("查询时间"+startDate+"到"+endDate+"内无工单记录");
// jReturn.put("result", -1);
// jReturn.put("resultText", "查询时间"+startDate+"到"+endDate+"内无工单记录");
// conn.close();
// return(callback+"("+jReturn.toString()+")");
// }
//保存统计结果,防止统计结果有些城市没有数据,会漏掉的情况,用map设定初始值就不会漏了,没有的时候就是用初始值0
statusMap = new LinkedHashMap<Integer, Integer>();
statusMap.put(0, 0);
statusMap.put(1, 0);
statusMap.put(2, 0);
statusMap.put(3, 0);
statusMap.put(4, 0);
statusMap.put(5, 0);
statusMap.put(6, 0);
statusMap.put(7, 0);
statusMap.put(8, 0);
statusMap.put(9, 0);
statusMap.put(10, 0);
statusMap.put(11, 0);
statusMap.put(12, 0);
statusMap.put(13, 0);
statusMap.put(14, 0);
statusMap.put(15, 0);
statusMap.put(16, 0);
//保存到map,注意从数据库拿到的城市id比数组cities的下标大1,所以要减去1才能匹配数组下标
for (String orderlist : orderList) {
String[] orderArray = orderlist.split("\t");
String area_id= orderArray[0];
String num = orderArray[1];
if (Integer.parseInt(area_id)>0&&Integer.parseInt(area_id)<18) {
statusMap.put(Integer.parseInt(area_id)-1, Integer.parseInt(num));
}
}
//保存到json中,键是城市的中文名
for (Iterator<Integer> iterator = statusMap.keySet().iterator(); iterator.hasNext();) {
int index = (Integer) iterator.next();
jObjControlCenter.put(cities[index], statusMap.get(index));
}
}else {//其他城市。目前不支持其他城市查询分公司的工单数量。
jReturn.put("result", -1);
jReturn.put("resultText", "该功能暂时还未开放,目前支持全省查询");
conn.close();
return(callback+"("+jReturn.toString()+")");
}
//把手机网页数据和服务台数据分开存储
JSONObject jResult = new JSONObject();
jResult.put("phoneWeb", jObjPhone.toString() );
jResult.put("controlCenter", jObjControlCenter.toString() );
//返回结果
jReturn.put("result", 0);
jReturn.put("resultText", jResult.toString());
System.out.println("结果="+jResult.toString());
conn.close();
return(callback+"("+jReturn.toString()+")");
}
}
<file_sep>define([
'backbone'
], function(Backbone) {
"use strict";
var ParametersGetting = Backbone.Model.extend({
initialize: function(options){
this.urlRoot = 'getting_parameters.html';
this.url = this.urlRoot;
}
});
return ParametersGetting;
});<file_sep>define([
'underscore',
'backbone',
'marionette',
'cookie',
'views/partials/components/bmap',
"tpl!views/partials/common/common_t/positionSelect.tpl",
],function(_,Backbone, Marionette, Cookie, BmapView, positionSelectTpl){
"use strict";
var SelectView = Backbone.Marionette.LayoutView.extend({
template: positionSelectTpl,
triggers:{
"click #ensure": "backHome",
},
initialize: function(options){
this.position = options.position;
this.lng = options.longitude;
this.lat = options.latitude;
},
onShow:function(){
// alert(position);
if(this.lng==""){
$('#lng').val(114.210587);
}
else{
$('#lng').val(this.lng);
}
if(this.lat==""){
$('#lat').val(30.602564);
}
else{
$('#lat').val(this.lat);
}
Cookie.set('lng',this.lng);
Cookie.set('lat',this.lat);
var mapOptions = {
mapType: BMAP_NORMAL_MAP,
minZoom: 13,
maxZoom: 18,
enableMapClick:false
};
this.map = new BMap.Map("container", mapOptions); //设置卫星图为底图BMAP_PERSPECTIVE_MAP
var map = this.map;
var initPoint = new BMap.Point(114.4435, 30.5297); // 创建点坐标
this.initPoint = initPoint;
map.centerAndZoom(initPoint, 18); // 初始化地图,设置中心点坐标和地图级别。
map.enableScrollWheelZoom(); // 启用滚轮放大缩小。
map.enableKeyboard(); // 启用键盘操作。
// map.enableContinuousZoom(); //启用连续缩放效果
map.disableDoubleClickZoom(); //禁用双击放大效果
// ----- control -----
map.addControl(new BMap.NavigationControl()); //地图平移缩放控件
map.addControl(new BMap.ScaleControl()); //地图比例尺控件
// this.searchAddress = new SearchAddress({map:map});
// this.searchAddress.showPlaceSuggestion();//加入输入提示
// this.searchAddress.setLocation("华中科技大学");
// 创建地址解析器实例
var myGeo = new BMap.Geocoder();
// map.clearOverlays();
// 将地址解析结果显示在地图上,并调整地图视野
if(this.position==""){
this.position = "武汉市硚口区古田四路56号";
}
myGeo.getPoint(this.position, function(point){
if (point) {
map.centerAndZoom(point, 18);
map.addOverlay(new BMap.Marker(point));
console.log(point);
}
else{
alert("未找到相应地点");
}
}, "湖北省");
this.positionInfo();
this.bindInfoWindow();
// var position = document.URL.substring(34);
// this.listenKey();
},
bindInfoWindow: function(){
var self = this;
var map = this.map;
// var location = self.position;
// alert(position);
map.addEventListener('click', function(e){
map.clearOverlays();
map.addOverlay(new BMap.Marker(e.point));
var info = new BMap.InfoWindow('', {width: 260});
var projection = this.getMapType().getProjection();
var zoomLevel = map.getZoom();
var zoomStr = "地图级别:"+ zoomLevel;
var lngLat = e.point;
var lngLatStr = "<br />经纬度:" + lngLat.lng + ", " + lngLat.lat;
var worldCoordinate = projection.lngLatToPoint(lngLat);
var worldCoordStr = "<br />平面坐标:" + worldCoordinate.x + ", " + worldCoordinate.y;
var pixelCoordinate = new BMap.Pixel(Math.floor(worldCoordinate.x * Math.pow(2, this.getZoom() - 18)),
Math.floor(worldCoordinate.y * Math.pow(2, this.getZoom() - 18)));
var pixelCoordStr = "<br />像素坐标:" + pixelCoordinate.x + ", " + pixelCoordinate.y;
var tileCoordinate = new BMap.Pixel(Math.floor(pixelCoordinate.x / 256),
Math.floor(pixelCoordinate.y / 256));
var tileCoordStr = "<br />图块坐标:" + tileCoordinate.x + ", " + tileCoordinate.y;
var viewportCoordinate = map.pointToPixel(lngLat);
var viewportCoordStr = "<br />可视区域坐标:" + viewportCoordinate.x + ", " + viewportCoordinate.y;
var overlayCoordinate = map.pointToOverlayPixel(lngLat);
var overlayCoordStr = "<br />覆盖物坐标:" + overlayCoordinate.x + ", " + overlayCoordinate.y;
var tileCoordLngLat = projection.pointToLngLat({x:tileCoordinate.x*Math.pow(2,13),
y:tileCoordinate.y*Math.pow(2,13)});
var tileCoordLngLatStr = "<br />图块坐标反推经纬度:" + tileCoordLngLat.lng + ", " + tileCoordLngLat.lat;
//将百度经纬度转化为实际经纬度
var WGSLngLatStr;
function translateCallback(data){
if(data.status === 0) {
var BPoint = [];
BPoint[0] = Point;
BPoint[1] = data.points[0];
var GPSPoint = {};
GPSPoint.lng = 2*BPoint[0].lng - BPoint[1].lng;
GPSPoint.lat = 2*BPoint[0].lat - BPoint[1].lat;
WGSLngLatStr = "<br />实际经纬度:" + GPSPoint.lng.toFixed(6) + ", " + GPSPoint.lat.toFixed(6);
// info.setContent(zoomStr + lngLatStr + worldCoordStr + pixelCoordStr + tileCoordStr +
// viewportCoordStr + overlayCoordStr + WGSLngLatStr);
info.setContent(zoomStr + lngLatStr + WGSLngLatStr);
var positioninfo = "经度:"+GPSPoint.lng.toFixed(6)+'\u000d'+"纬度:"+GPSPoint.lat.toFixed(6)+'\u000d'+"是否确定选取该地点?";
// var position = confirm(positioninfo);
// if(position){
Cookie.set('lng',GPSPoint.lng.toFixed(6));
Cookie.set('lat',GPSPoint.lat.toFixed(6));
// document.getElementById("bmapWrapper").addEventListener('click', function(){
$('#lng').val(GPSPoint.lng.toFixed(6));
$('#lat').val(GPSPoint.lat.toFixed(6));
// });
}
}
var Point = new BMap.Point(lngLat.lng,lngLat.lat);
var convertor = new BMap.Convertor();
var pointArr = [];
pointArr.push(Point);
convertor.translate(pointArr, 1, 5, translateCallback);
// map.openInfoWindow(info, lngLat);
});
},
positionInfo: function(){
var self = this;
var map = this.map;
var geoc = new BMap.Geocoder();
map.addEventListener("click", function(e){
var pt = e.point;
geoc.getLocation(pt, function(rs){
var addComp = rs.addressComponents;
var location = addComp.city + addComp.district + addComp.street + addComp.streetNumber;
// alert(location);
Cookie.set('location',location);
});
});
}
});
return SelectView;
})
<file_sep>package web;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import domain.Grid;
import service.GridService;
@Controller
public class Ued{
@Autowired
private GridService gridService;
@RequestMapping(value = "/ued_complaint_info",method = RequestMethod.POST)
@ResponseBody
public String complaint_info(@RequestBody String jobj){
// public String complaint_info(@RequestBody String request) {
// System.out.println(request);
// JSONObject jb=new JSONObject();
//将json格式的字符串转换为json对象,并取得该对象的“userName”属性值
// String o=(String)jb.fromObject(request).get("type");
//
// String o=(String)jobj.get("type");
// System.out.println(o);
// request.setCharacterEncoding("UTF-8");
// String name = request.getParameter("name");
//
// JSONArray jsons = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put("complaint_item_id","588");
// return(jobj) ;
return(jsonObject.toString());
// String i = "this is an error";
// return(i);
}
@RequestMapping(value = "/ued_complaint_info_post",method = RequestMethod.POST)
@ResponseBody
public String complaint_info_post(@RequestBody String jobj){
JSONObject jsonObject = new JSONObject();
jsonObject.put("state","1");
// return(jsonObject.toString());
String i = "this is an error";
return(i);
}
@RequestMapping(value = "/ued_complaint_info_get",method = RequestMethod.GET)
@ResponseBody
public String complaint_info_get(HttpServletRequest request) throws IOException {
String str = URLDecoder.decode(request.getParameter("complaint_info_id"),"UTF-8");
JSONObject jsonObject = new JSONObject();
jsonObject.put("complaint_item_id",str);
jsonObject.put("display_complaint_item_id",str);
jsonObject.put("staff_id",str);
jsonObject.put("complaint_time","2015-07-26 07:51");
jsonObject.put("occur_time","2015-07-26 07:51");
jsonObject.put("pheno_option","PH1001");
jsonObject.put("location","武汉高铁站");
jsonObject.put("longitude","114.260848");
jsonObject.put("latitude","30.625334");
jsonObject.put("complaint_phone","18971473689");
jsonObject.put("pheno_description","没有信号");
jsonObject.put("pheno_always","0");
jsonObject.put("search_time_range","4");
// return(jobj) ;
return(jsonObject.toString());
// String i = "this is an error";
// return(i);
}
@RequestMapping(value = "/ued_cell_info",method = RequestMethod.GET)
@ResponseBody
public String cell_info(HttpServletRequest request) throws IOException {
// System.out.println(request);
String str = URLDecoder.decode(request.getParameter("complaint_item_id"),"UTF-8");
System.out.println(str);
JSONArray jsons = new JSONArray();
JSONObject jsob = new JSONObject();
jsob.put("longitude", 114.111);
jsob.put("latitude", 30.575);
jsob.put("radius",5);
jsob.put("cell_density","yellow");
jsons.add(jsob);
for(int j=0;j<2;j++){
JSONObject jsonObject = new JSONObject();
jsonObject.put("type", 1);
jsonObject.put("ECP", 21);
jsonObject.put("BTS",1014);
jsonObject.put("CELL",1);
jsonObject.put("cell_name","土产仓库");
jsonObject.put("distance",815);
jsonObject.put("search_type","地点");
jsons.add(jsonObject);
}
return(jsons.toString()) ;
}
@RequestMapping(value = "/ued_grid_info",method = RequestMethod.GET)
@ResponseBody
public String grid_info(HttpServletRequest request) throws IOException {
// System.out.println(request);
String str = URLDecoder.decode(request.getParameter("complaint_item_id"),"UTF-8");
System.out.println(str);
JSONArray jsons = new JSONArray();
JSONObject jsob = new JSONObject();
jsob.put("longitude", 114.111);
jsob.put("latitude", 30.575);
jsob.put("cover_quality","green");
jsob.put("call_load","red");
jsons.add(jsob);
for(int j=0;j<2;j++){
JSONObject jsonObject = new JSONObject();
jsonObject.put("grid_id", "Zf645");
jsonObject.put("call_count", 21);
jsonObject.put("average_ecio","-8");
jsons.add(jsonObject);
}
return(jsons.toString()) ;
}
@RequestMapping(value = "/ued_station_error",method = RequestMethod.GET)
@ResponseBody
public String station_error(HttpServletRequest request) throws IOException {
// System.out.println(request);
String str = URLDecoder.decode(request.getParameter("complaint_item_id"),"UTF-8");
System.out.println(str);
JSONArray jsons = new JSONArray();
JSONObject jsob = new JSONObject();
jsob.put("trouble_time", "XX");
jsob.put("complain_time", "XX");
jsob.put("duration", 12);
jsob.put("trouble_alert","blue");
jsons.add(jsob);
for(int j=0;j<2;j++){
JSONObject jsonObject = new JSONObject();
jsonObject.put("BSC", 4);
jsonObject.put("station_id", 21);
jsonObject.put("CELL",5);
jsonObject.put("station_name","XXX");
jsonObject.put("trouble_type", "osx");
jsonObject.put("trouble_start_time", "2015-06-18 12:00");
jsonObject.put("trouble_end_time", "2015-06-18 12:00");
jsonObject.put("trouble_desc", "MIAgent=1,MMSI=1,Service=11_0,ServiceMember=H248-0-6-0;PoolType=H248DS:PoolId=0:PoolMemberId=1:CompId=PMCPI:Resource_type=cpiMGCFailedAddRequest:switchHealth");
jsons.add(jsonObject);
}
return(jsons.toString()) ;
}
@RequestMapping(value = "/ued_cell_performance_alert",method = RequestMethod.GET)
@ResponseBody
public String cell_performance_alert(HttpServletRequest request) throws IOException {
// System.out.println(request);
String str = URLDecoder.decode(request.getParameter("complaint_item_id"),"UTF-8");
System.out.println(str);
JSONArray jsons = new JSONArray();
JSONObject jsob = new JSONObject();
jsob.put("trouble_time", "xx");
jsob.put("duration", 12);
jsob.put("performance_alert","red");
jsons.add(jsob);
JSONObject jsonObject = new JSONObject();
jsonObject.put("BSC", 4);
jsonObject.put("station_id", 21);
jsonObject.put("CELL",8);
jsonObject.put("station_name","XXX");
jsonObject.put("trouble_date", "2015-06-18 12:00");
jsonObject.put("trouble_hour", "5");
jsonObject.put("performance_text", "呼叫建立成功率预警");
jsonObject.put("congestion", 101);
jsonObject.put("succ_rate", 94);
jsonObject.put("drop_rate", 6);
jsonObject.put("rssi", -50);
jsons.add(jsonObject);
jsonObject.put("BSC", 4);
jsonObject.put("station_id", 21);
jsonObject.put("CELL",8);
jsonObject.put("station_name","XXX");
jsonObject.put("trouble_date", "2015-06-18 12:00");
jsonObject.put("trouble_hour", "5");
jsonObject.put("performance_text", "呼叫建立成功率预警");
jsonObject.put("congestion", 99);
jsonObject.put("succ_rate", 94);
jsonObject.put("drop_rate", 6);
jsonObject.put("rssi", -50);
jsons.add(jsonObject);
jsonObject.put("BSC", 4);
jsonObject.put("station_id", 21);
jsonObject.put("CELL",8);
jsonObject.put("station_name","XXX");
jsonObject.put("trouble_date", "2015-06-18 12:00");
jsonObject.put("trouble_hour", "5");
jsonObject.put("performance_text", "呼叫建立成功率预警");
jsonObject.put("congestion", 102);
jsonObject.put("succ_rate", 94);
jsonObject.put("drop_rate", 6);
jsonObject.put("rssi", -50);
jsons.add(jsonObject);
return(jsons.toString()) ;
}
@RequestMapping(value = "/ued_call_info",method = RequestMethod.GET)
@ResponseBody
public String call_info(HttpServletRequest request) throws IOException {
// System.out.println(request);
String str = URLDecoder.decode(request.getParameter("complaint_item_id"),"UTF-8");
System.out.println(str);
JSONArray jsons = new JSONArray();
JSONArray jsons_call = new JSONArray();
JSONObject jsob = new JSONObject();
jsob.put("per_page", 15);
jsob.put("total_entries", 200);
jsob.put("total_page", 14);
jsob.put("page", 1);
jsons.add(jsob);
JSONObject jsoc = new JSONObject();
jsoc.put("trouble_time","XX");
jsoc.put("duration",12);
jsoc.put("unusual_event","red");
jsoc.put("signal_quality","yellow");
jsons_call.add(jsoc);
for(int j=0;j<10;j++){
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", j);
jsonObject.put("call_date", 318);
jsonObject.put("call_time", "21:24:22");
jsonObject.put("link_seconds","00:00:20");
jsonObject.put("event_type", "短信接收成功");
jsonObject.put("call_station","麦德龙");
jsonObject.put("call_ecio", "-10.5");
jsonObject.put("call_pilot_num", "2");
jsonObject.put("call_distance", "20");
jsonObject.put("release_station","麦德龙");
jsonObject.put("release_ecio", "-10.0");
jsonObject.put("release_pilot_num", "3");
jsonObject.put("release_distance", "30");
jsonObject.put("CFC_CFCQ", "2,13");
jsons_call.add(jsonObject);
}
for(int j=10;j<20;j++){
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", j);
jsonObject.put("call_date", 318);
jsonObject.put("call_time", "21:24:22");
jsonObject.put("link_seconds","00:00:20");
jsonObject.put("event_type", "短信接收成功");
jsonObject.put("call_station","麦德龙");
jsonObject.put("call_ecio", "-10.5");
jsonObject.put("call_pilot_num", "2");
jsonObject.put("call_distance", "20");
jsonObject.put("release_station","麦德龙");
jsonObject.put("release_ecio", "-10.0");
jsonObject.put("release_pilot_num", "3");
jsonObject.put("release_distance", "30");
jsonObject.put("CFC_CFCQ", "3,22");
jsons_call.add(jsonObject);
}
jsons.add(jsons_call);
return(jsons.toString()) ;
}
@RequestMapping(value = "/ued_light_info",method = RequestMethod.GET)
@ResponseBody
public String light_info(HttpServletRequest request) throws IOException {
// System.out.println(request);
String str = URLDecoder.decode(request.getParameter("complaint_item_id"),"UTF-8");
System.out.println(str);
JSONObject jsonObject = new JSONObject();
jsonObject.put("database_state", "1");
jsonObject.put("excuse", "基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。基站4_33_XXX 故障。11111222223333adfsfsafdadfasfk';asdkf;'askf;'lakdsf;'lsakf';laskdf';sakf';lsakdf';ldsak");
jsonObject.put("suggestion", "XXX,结单处理。");
jsonObject.put("cell_density","yellow");
jsonObject.put("grid_quality", "green");
jsonObject.put("call_load", "red");
jsonObject.put("cover_quality", "green");
jsonObject.put("station_check","red");
jsonObject.put("trouble_alert","blue");
jsonObject.put("performance_alert", "red");
jsonObject.put("call_quality", "yellow");
jsonObject.put("unusual_event", "red");
jsonObject.put("signal_quality", "yellow");
jsonObject.put("error", "greenXXXXXXXXXXXXXXXXXXXXXXX");
return(jsonObject.toString()) ;
}
@RequestMapping(value = "/ued_search_by_phone",method = RequestMethod.GET)
@ResponseBody
public String search_by_phonet(HttpServletRequest request) throws IOException {
// System.out.println(request);
String str = URLDecoder.decode(request.getParameter("search_text"),"UTF-8");
System.out.println(str);
JSONArray jsons = new JSONArray();
for(int j=0;j<3;j++){
JSONObject jsonObject = new JSONObject();
jsonObject.put("cause", "原因定位:基站4_33_XXX 故障。");
jsonObject.put("suggestion", "后续操作建议:XXX,结单处理。");
jsonObject.put("state","已处理");
jsonObject.put("complaint_item_id", "34");
jsonObject.put("complaint_phone", "13163335678");
jsonObject.put("location", "华中科技大学东校区");
jsonObject.put("longitude","114.40776");
jsonObject.put("latitude","30.51415");
jsonObject.put("pheno_option", "无信号");
jsonObject.put("pheno_description", "XXXXXXX");
jsonObject.put("complaint_time", "2015-06-18 05:00");
jsonObject.put("occur_time", "2015-06-18 05:00");
jsonObject.put("count", "3");
jsonObject.put("No", "3");
jsons.add(jsonObject);
}
return(jsons.toString()) ;
}
@RequestMapping(value = "/ued_complaint_statistic_data",method = RequestMethod.GET)
@ResponseBody
public String complaint_statistic_data(HttpServletRequest request) throws IOException {
// System.out.println(request);
String str = URLDecoder.decode(request.getParameter("start_time"),"UTF-8");
System.out.println(str);
// str = URLDecoder.decode(request.getParameter("end_time"),"UTF-8");
// System.out.println(str);
JSONObject responseObj = new JSONObject();
JSONObject gridObject = new JSONObject();
int[] categoryArr = new int[]{100,101,102,103,104,100,101,102,103,104};
int[] dataArr = new int[]{123,94,85,73,64,55,43,34,28,26};
JSONArray jsons = new JSONArray();
JSONObject jsonItem = new JSONObject();
jsonItem.put("name", "基站故障");
jsonItem.put("y", 14);
jsons.add(jsonItem);
jsonItem.put("name", "信号覆盖弱");
jsonItem.put("y", 28);
jsons.add(jsonItem);
jsonItem.put("name", "关联基站性能差");
jsonItem.put("y", 37);
jsons.add(jsonItem);
jsonItem.put("name", "其他原因");
jsonItem.put("y", 42);
jsons.add(jsonItem);
gridObject.put("categories", categoryArr);
gridObject.put("data", dataArr);
responseObj.put("grid_column", gridObject);
responseObj.put("excuse_pie", jsons);
return(responseObj.toString()) ;
}
@RequestMapping(value = "/ued_setting_parameters",method = RequestMethod.GET)
@ResponseBody
public String setting_parameters_get(HttpServletRequest request) throws IOException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("relatedCellCount", "3");
jsonObject.put("relatedCellDistance", "1000m");
jsonObject.put("performanceSearchTime", "6h");
jsonObject.put("errorSearchTime", "12h");
jsonObject.put("PCMASearchTime", "6h");
return(jsonObject.toString()) ;
}
@RequestMapping(value = "/ued_setting_parameters",method = RequestMethod.POST)
@ResponseBody
String setting_parameters_post(@RequestBody String request){
System.out.println(request);
JSONObject jb=new JSONObject();
String complaint_phone = (String)jb.fromObject(request).get("PCMASearchTime");
String location = (String)jb.fromObject(request).get("location");
JSONObject jsonObject = new JSONObject();
jsonObject.put("state", "success");
return(jsonObject.toString()) ;
}
@RequestMapping(value = "/ued_login",method = RequestMethod.POST)
@ResponseBody
String logint(@RequestBody String request){
System.out.println(request);
JSONObject jb=new JSONObject();
String complaint_phone = (String)jb.fromObject(request).get("PCMASearchTime");
String location = (String)jb.fromObject(request).get("location");
JSONObject jsonObject = new JSONObject();
jsonObject.put("state", "success");
return(jsonObject.toString()) ;
}
}
<file_sep>package com.hbase.cityReached;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class PrepStmCommitRollback {
public static void main(String args[]) {
Connection con = null;
PreparedStatement pstm = null;
MyDBManager myPStatement = MyDBManager.getInstance();
try {
// 1. 建立与数据库的连接
con = myPStatement.getConnection();
// 2. 执行sql语句
// 1).先创建PreparedStatement语句(发送slq请求):
String sql = "insert into userInfo(userId,userName,userPassword,userGrade) values(?,?,?,?)";
pstm = con.prepareStatement(sql);
con.setAutoCommit(false);//1,首先把Auto commit设置为false,不让它自动提交
for (int i = 0; i < 10; i++) {
// 2) 设置sql语句1
pstm.setInt(1, 33);
pstm.setString(2,"wangqin");
pstm.setString(3, "c++");
pstm.setDouble(4, 78);
// 3) 将一组参数添加到此 PreparedStatement 对象的批处理命令中。
pstm.addBatch();
}
// 4) 将一批参数提交给数据库来执行,如果全部命令执行成功,则返回更新计数组成的数组。
int[] count = pstm.executeBatch();
System.out.println("插入成功!");
// 若成功执行完所有的插入操作,则正常结束
con.commit();//2,进行手动提交(commit)
System.out.println("提交成功!");
con.setAutoCommit(true);//3,提交完成后回复现场将Auto commit,还原为true,
} catch (SQLException e) {
e.printStackTrace();
try {
// 若出现异常,对数据库中所有已完成的操作全部撤销,则回滚到事务开始状态
if(!con.isClosed()){
con.rollback();//4,当异常发生执行catch中SQLException时,记得要rollback(回滚);
System.out.println("插入失败,回滚!");
con.setAutoCommit(true);
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}finally{
try {
pstm.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*
* 方法一 耗时22s
* 总结:方法一和方法二很类同,唯一不同的是方法一采用的是“insert into tb (...) values(...),(...)...;”的方式执行插入操作,
方法二则是“insert into tb (...) values (...);insert into tb (...) values (...);...”的方式,要不是测试,我也不知道两者差别是如此之大!
*/
public static void insert(Connection conn) {
// 开时时间
Long begin = System.currentTimeMillis();
// sql前缀
String prefix = "INSERT INTO tb_big_data (count, create_time, random) VALUES ";
try {
// 保存sql后缀
StringBuffer suffix = new StringBuffer();
// 设置事务为非自动提交
conn.setAutoCommit(false);
// Statement st = conn.createStatement();
// 比起st,pst会更好些
PreparedStatement pst = conn.prepareStatement("");
// 外层循环,总提交事务次数
for (int i = 1; i <= 100; i++) {
// 第次提交步长
for (int j = 1; j <= 10000; j++) {
// 构建sql后缀
suffix.append("(" + j * i + ", SYSDATE(), " + i * j * Math.random() + "),");
}
// 构建完整sql
String sql = prefix + suffix.substring(0, suffix.length() - 1);
// 添加执行sql
pst.addBatch(sql);
// 执行操作
pst.executeBatch();
// 提交事务
conn.commit();
// 清空上一次添加的数据
suffix = new StringBuffer();
}
// 关闭连接
pst.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
// 结束时间
Long end = System.currentTimeMillis();
// 耗时
System.out.println("cast : " + (end - begin) / 1000 + " s");
}
/*
* 方法二 耗时111s
*/
public static void insertRelease(Connection conn) {
Long begin = System.currentTimeMillis();
String sql = "INSERT INTO tb_big_data (count, create_time, random) VALUES (?, SYSDATE(), ?)";
try {
conn.setAutoCommit(false);
PreparedStatement pst = conn.prepareStatement(sql);
for (int i = 1; i <= 100; i++) {
for (int k = 1; k <= 10000; k++) {
pst.setLong(1, k * i);
pst.setLong(2, k * i);
pst.addBatch();
}
pst.executeBatch();
conn.commit();
}
pst.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
Long end = System.currentTimeMillis();
System.out.println("cast : " + (end - begin) / 1000 + " ms");
}
} <file_sep>package pre_deal;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import myquery.Query;
import mysql.mysql_DML;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.sun.xml.bind.v2.runtime.Name;
import cell_info.Find_Cell;
import domain.Grid;
import service.GridService;
@Controller
public class RelatedAlarms {
@Autowired
private static Logger logger = Logger.getLogger(RelatedAlarms.class);
private GridService gridService;
private String search_r;
private String search_t;
private String init_lon;
private String init_lat;
private String alarm_timerange;
private String AlarmLevel;
private String range_type;
private int alarm_rsCode = 10;
private int alarm_rsColorCode = 20;
private int alarm_rsnum = 0;
public static String path = MyFilePath.TCPropertiesPath;
public int getAlarm_rsCode() {
return alarm_rsCode;
}
public void setAlarm_rsCode(int alarm_rsCode) {
this.alarm_rsCode = alarm_rsCode;
}
public int getAlarm_rsColorCode() {
return alarm_rsColorCode;
}
public void setAlarm_rsColorCode(int alarm_rsColorCode) {
this.alarm_rsColorCode = alarm_rsColorCode;
}
public int getAlarm_rsnum() {
return alarm_rsnum;
}
public void setAlarm_rsnum(int alarm_rsnum) {
this.alarm_rsnum = alarm_rsnum;
}
public void initParam(String paramFile) throws FileNotFoundException,
IOException {
Properties props = new Properties();
props.load(new FileInputStream(paramFile));
search_r = props.getProperty("search_r");
search_t = props.getProperty("search_t");
alarm_timerange = props.getProperty("alarm_timerange");
range_type = props.getProperty("range_type");
AlarmLevel = props.getProperty("alarmlevel");
}
/*
* 函数名:queryRelatedAlarmsPCMD 参数:record_id dml conn 返回值:list
* 功能:根据关联小区列表查询出该关联小区的故障信息并插入数据库 Author:yl UpdateDate:2015/8/28
*/
public String queryRelatedAlarms(String record_id, mysql_DML dml,
Connection conn, ArrayList<String> cell_list)
throws FileNotFoundException, IOException, ClassNotFoundException,
SQLException, ParseException {
logger.info("调用queryRelatedAlarms函数");
initParam(path);
if (cell_list == null) {
logger.info("在im_cell_info中查询结果为空");
return "error";
}
// 查询pre_deal_record表获得问题发生时间和当前时间
String sql_pre_deal_record = "select call_time,complaint_time from pre_deal_records where record_id = "
+ Integer.parseInt(record_id) + " limit 0, 1";
logger.info("查询pre_deal_record的语句: " + sql_pre_deal_record);
ArrayList<String> list = dml.selectMysql(sql_pre_deal_record, conn);
if (list.isEmpty()) {
logger.info("没有该投诉信息!");
return "没有该投诉信息!请核对后查询。";
}
String ca_time = list.get(0).split("\t")[0];// 问题时间
String com_time = list.get(0).split("\t")[1];// 当前时间
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sd1 = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
SimpleDateFormat sd2 = new SimpleDateFormat("yyyy-MM-dd HH:59:59");
String call_time = sd.format(sd.parse(ca_time));
String curr_time = sd.format(sd.parse(com_time));
long time_stamp = sd.parse(call_time).getTime() / 1000
- (Long.parseLong(alarm_timerange) / 3600 - 1) * 3600;// 问题发生时间的前N-1小时的时间戳
long time_stamp1 = sd.parse(call_time).getTime() / 1000;
Date time = new Date(time_stamp * 1000);
Date time1 = new Date(time_stamp1 * 1000);
String time_before = sd1.format(time);
String time_after = sd2.format(time1);
// ----------------------------------获取关联小区列表----------------------------------------
int alarm_rsnum = 0;// 故障信息数目
int max_code = 0;// 记录alarm_code最大值,便于确定alarm_rscode
int i = 1;
String insert_related_alarms = "insert into related_alarms(record_id,call_time,curr_time,query_range,ecp,bts,cell,"
+ "location,alarm_type,alarm_start_time,alarm_clear_time,alarm_code,specific_problem,alarmtext,alarmlevel) VALUES ";
// 有关联小区信息,根据结果查询该小区的故障告警信息
for (String s : cell_list) {
int ecp = Integer.parseInt(s.split("\t")[0]);
int bts = Integer.parseInt(s.split("\t")[1]);
int cell = Integer.parseInt(s.split("\t")[2]);
String location = s.split("\t")[3];
// 获取这个关联小区所在的城市
ArrayList<String> cityList = dml.selectMysql("select city from im_cell_info where bts=" + bts
+ " and ecp = " + ecp + " and cell = "+ cell, conn);
if (cityList.isEmpty()) {
logger.info("error:根据ecp=" + ecp + " and bts=" + bts+ " and cell=" + cell + "无法确定其所在城市!");
continue;
}
String city = cityList.get(0).split("\t")[0];
if (city.equals("武汉")) { // 基站故障表里面的“武汉”分为多个局,还要根据ecp细分
switch (ecp) {
case 4:city = "武汉12局";break;
case 5:city = "武汉13局";break;
case 11:city = "武汉1局";break;
case 12:city = "武汉2局";break;
default:break;
}
}
if (city.equals("天门") || city.equals("潜江") || city.equals("仙桃")) {// 基站故障表里没有“天门/潜江/仙桃”,只有他们对应的江汉,要转化
city = "江汉";
}
logger.info("根据关联小区ecp=" + ecp + ",cityname=" + city+ "查找relatedAlarms可以去匹配故障!");
// 根据“城市+bts”查找im_hw_alarms,获取最新的一条故障信息
int alarm_code = 10;
String sql_im_hw_alarms1 = "select starttime,alarmtext,alarmlevel,cleartime,alarmnetype,specific_problem from im_hw_alarms WHERE equipname=" + bts
+ " and cityname = '" + city+ "'"+ " and update_date between '" + time_before + "' and '" + time_after+ "' ORDER BY starttime ASC ";
logger.info("查找第" + i + "个话单关联小区故障的sql语句=" + sql_im_hw_alarms1);
ArrayList<String> alarmlist1 = dml.selectMysql(sql_im_hw_alarms1,conn);
if (alarmlist1 == null || alarmlist1.isEmpty()) {
logger.info("故障表中查询结果为空");
max_code = 10;
continue;
}
logger.info("找到第" + (i) + "个关联小区故障=" + alarmlist1);
for (String string : alarmlist1) {
String[] alarmarray = string.split("\t");
int id = Integer.parseInt(record_id);
int query_range = Integer.parseInt(alarm_timerange) / 3600;// 查询时间范围,小时
// String alarm_starttime = alarmarray[5];// 故障发生时间
// String alarmtext = alarmarray[6];// 故障具体内容
// String alarm_level = alarmarray[8];// 告警级别
// String alarm_cleartime = alarmarray[13];// 故障清除时间
// String alarm_type = alarmarray[16];// 故障类型
// String specific_problem = alarmarray[30];// 故障内容
String alarm_starttime = alarmarray[0];//\u6545\u969c\u53d1\u751f\u65f6\u95f4
String alarmtext = alarmarray[1];//\u6545\u969c\u5177\u4f53\u5185\u5bb9
String alarm_level = alarmarray[2];//\u544a\u8b66\u7ea7\u522b
String alarm_cleartime = alarmarray[3];//\u6545\u969c\u6e05\u9664\u65f6\u95f4
String alarm_type = alarmarray[4];//\u6545\u969c\u7c7b\u578b
String specific_problem = alarmarray[5];//\u6545\u969c\u5185\u5bb9
// if (!(alarm_level.equals(AlarmLevel)) && !(alarm_type.equals("EQUIPMENT_MALFUNCTION"))) {
// alarm_code = 20;
// }
alarm_code = 20;
if (alarm_code > 10) { // 有故障。经过判断后,如果是和投诉关联的故障则把故障信息入库。
alarm_rsnum++;
insert_related_alarms += "(" + Integer.parseInt(record_id)
+ ",'" + call_time + "','" + curr_time + "',"
+ query_range + "," + ecp + "," + bts + "," + cell
+ ",'" + location + "','" + alarm_type + "','"
+ alarm_starttime + "','" + alarm_cleartime + "',"
+ alarm_code + ",'" + specific_problem + "','"
+ alarmtext + "','" + alarm_level + "'),";
logger.info("第" + i + "个插入related_alarms的语句: "+ insert_related_alarms);
}
if (alarm_code > max_code) {
max_code = alarm_code;
}
i++;
if(alarm_rsnum>10){
break;
}
logger.info("故障结果编码alarm_rscode=" + max_code);
logger.info("alarm_rsnum=" + alarm_rsnum);
}//for
}//for
logger.info("alarm_rsnum=" + alarm_rsnum);
// 一次性把所有故障信息添加到related_alarms数据库
if (alarm_rsnum > 0) { // 如果count==0,不执行插入数据库操作,无故障信息
logger.info("把所有故障信息添加到related_alarms数据库sql语句="
+ insert_related_alarms.substring(0,
insert_related_alarms.length() - 1));
dml.insertdata(
insert_related_alarms.substring(0,
insert_related_alarms.length() - 1), conn);
}
// -----------------------------更新标签pre_judge_label里面的alarms字段-------------------------------------------
int alarmsLabel = 202; // 基站故障分析标签,weak=201,health=202
if (alarm_rsnum > 0) {
alarmsLabel = 201;// 有故障,则为weak201
} else {
alarmsLabel = 202;// 无故障为health202
}
boolean flagLabel = dml.updatedata("update pre_judge_label set alarms="
+ alarmsLabel + " where record_id="
+ Integer.parseInt(record_id));
if (flagLabel) {
logger.info("succeess:成功更新pre_judge_label里面alarms!");
} else {
logger.info("error:更新pre_judge_label里面alarms失败!");
}
// ----------------------追加字段alarm_rscode,alarm_rsnum到pre_deal_records中-------------------------------
int alarmcode = 10;
// String sqlString =
// "select alarm_code from related_alarms where record_id = " +
// Integer.parseInt(record_id);
// ArrayList<String> alarmArrayList = dml.selectMysql(sqlString, conn);
if (alarm_rsnum < 1) {
alarmcode = 10;
} else {
alarmcode = 20;
}
String update_pre_deal_records = "update pre_deal_records SET alarm_rscode = "
+ alarmcode
+ ", alarm_rsnum = "
+ alarm_rsnum
+ " WHERE record_id = " + Integer.parseInt(record_id);
boolean flag1 = dml.updatedata(update_pre_deal_records);
if (!flag1) {
logger.info("Error!更新失败。");
} else {
logger.info("Success!更新成功。");
}
// ----------------------追加字段alarm_colorcode到pre_deal_results中------------------------------------------
String sql1 = "select colorcode from dict_result WHERE category = 'ALM' and rscode = "
+ alarmcode;
logger.info(sql1);
ArrayList<String> colorlist = dml.selectMysql(sql1, conn);
if (colorlist.isEmpty()) {
logger.info("\ndict_result表查询失败");
return "查询数据字典失败!";
}
int alarm_colorcode = Integer.parseInt(colorlist.get(0).split("\t")[0]);// 获得颜色编码
String update_pre_deal_results = "update pre_deal_results SET alarm_colorcode = "
+ alarm_colorcode
+ " WHERE record_id = "
+ Integer.parseInt(record_id);
boolean flag2 = dml.updatedata(update_pre_deal_results);
if (!flag2) {
logger.info("Error!更新失败。");
} else {
logger.info("Success!更新成功。");
}
return "success";
}
/*********************************************************************************
* 根据找关联小区故障结果编码编码,确定找关联小区故障结果的颜色 rscode meaning colorCode color 40
* 故障持续。关联基站在问题时刻有告警,且当前时刻仍然存在. 50 red 30 现行故障。关联基站在问题时刻无告警,但当前时刻有告警。 40
* yellow 20 故障恢复。关联基站在问题时刻有告警,当前时刻故障已清除。 30 Blue 10 无故障。关联基站在问题时刻无告警。 20
* green
*/
public String getAlarmRSColor() {
int alarmRSCode = getAlarm_rsCode();
String color = "";
switch (alarmRSCode) {
// case 40: setAlarm_rsColorCode(50); color = "red"; break;
// case 30: setAlarm_rsColorCode(40); color = "yellow"; break;
case 20:
setAlarm_rsColorCode(50);
color = "red";
break;
case 10:
setAlarm_rsColorCode(20);
color = "green";
break;
default:
setAlarm_rsColorCode(20);
color = "green";
break;
}
return color;
}
// url:xxx/station_error,
// type: "GET",
// data: {"complaint_item_id" : "1011"}
//
// response: [{trouble_time:"XXX",
// complain_time:"XXX",
// duration:12,
// trouble_alert: "red"},
// {BSC: 4,
// station_id:21,
// CELL:XXX,
// station_name:"XXX",
// trouble_type:"oss",
// trouble_start_time: "2015-06-18 05:00",
// trouble_end_time: "2015-06-18 05:00",
// trouble_desc: " 故障描述故障描述故障描述"}]
// 如果没有故障信息
//
// response: [{trouble_time:"XXX",
// complain_time:"XXX",
// duration:12,
// trouble_alert: "red"}]
@RequestMapping(value = "/station_error", method = RequestMethod.GET)
@ResponseBody
public String station_error(HttpServletRequest request,
HttpServletResponse response) throws FileNotFoundException,
ClassNotFoundException, IOException, SQLException, ParseException {
logger.info("\n调用station_error函数");
response.setCharacterEncoding("UTF-8");
String record_id = URLDecoder.decode(
request.getParameter("complaint_item_id"), "UTF-8");
initParam(path);// 加载配置文件
// 创建数据库连接
mysql_DML dml = new mysql_DML();
Connection conn = dml.myConnection();
String response_result = null;// 存储结果的字符串
String trouble_time = null;
String complain_time = null;
String time_before = "";
String time_after = "";
JSONArray responsejsons = new JSONArray();
JSONObject jsb = new JSONObject();
// --------------------查找结果表related_alarms得到需要的数据-----------------------------
String alarmcolor = null;// 点灯的颜色
String sql1 = "select alarm_rscode, call_time, complaint_time from pre_deal_records where record_id = "
+ Integer.parseInt(record_id);
ArrayList<String> list1 = dml.selectMysql(sql1, conn);
if (list1.isEmpty()) {
logger.info("此投诉单号没有对应的故障告警信息!");
// 返回查找条件
jsb.put("trouble_occur_time", "");
jsb.put("complain_time", "");
jsb.put("trouble_end_time", "");
jsb.put("trouble_alert", "");
responsejsons.add(jsb);
response_result = responsejsons.toString();
return response_result;
} else {
logger.info("此投诉单有对应的故障信息");
int alarm_rscode = Integer.parseInt(list1.get(0).split("\t")[0]);
SimpleDateFormat sDateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
trouble_time = sDateFormat.format(sDateFormat.parse(list1.get(0)
.split("\t")[1]));
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sd1 = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
SimpleDateFormat sd2 = new SimpleDateFormat("yyyy-MM-dd HH:59:59");
long time_stamp = sd.parse(trouble_time).getTime() / 1000
- (Long.parseLong(search_t) / 3600 - 1) * 3600;// 问题发生时间的前N-1小时的时间戳
long time_stamp1 = sd.parse(trouble_time).getTime() / 1000;
Date time = new Date(time_stamp * 1000);
Date time1 = new Date(time_stamp1 * 1000);
time_before = sd1.format(time);
time_after = sd2.format(time1);
complain_time = sDateFormat.format(sDateFormat.parse(list1.get(0)
.split("\t")[2]));
switch (alarm_rscode) {
case 40:
alarmcolor = Color.$50;// red
break;
// case 30:
// alarmcolor = Color.$40;//yellow
// break;
// case 20:
// alarmcolor = Color.$30;//Blue
// break;
default:
alarmcolor = Color.$20;// green
break;
}
}
// 20160414修改
// String sql =
// "select DISTINCT record_id,call_time,curr_time,query_range,ecp,bts,cell,location,"
// +
// "alarm_type,alarm_start_time,alarm_clear_time,alarm_code,specific_problem,alarmlevel from related_alarms"
// + " where record_id = " + Integer.parseInt(record_id);
String sql = "select DISTINCT record_id,call_time,curr_time,query_range,ecp,bts,cell,location,"
+ "alarm_type,alarm_start_time,alarm_clear_time,alarm_code,alarmtext,alarmlevel from related_alarms"
+ " where record_id = " + Integer.parseInt(record_id);
logger.info("故障告警查询语句 " + sql);
ArrayList<String> list = dml.selectMysql(sql, conn);
if (list.isEmpty()) {
logger.info("此投诉单号没有对应的故障告警信息!");
// 返回查找条件
jsb.put("trouble_occur_time", time_before);
jsb.put("complain_time", complain_time);
jsb.put("trouble_end_time", time_after);
jsb.put("trouble_alert", alarmcolor);
responsejsons.add(jsb);
response_result = responsejsons.toString();
return response_result;
} else {
// 返回查找条件
jsb.put("trouble_occur_time", time_before);
jsb.put("complain_time", complain_time);
jsb.put("trouble_end_time", time_after);
jsb.put("trouble_alert", alarmcolor);
responsejsons.add(jsb);
// 输出Json格式数据的故障信息
JSONObject jsob = new JSONObject();
for (String s : list) {
if (!(s.split("\t")[13].equals(AlarmLevel))
&& !(s.split("\t")[8].equals("EQUIPMENT_MALFUNCTION"))) {
jsob.put("BSC", s.split("\t")[4]);
jsob.put("station_id", s.split("\t")[5]);
jsob.put("CELL", s.split("\t")[6]);
jsob.put("station_name", s.split("\t")[7]);
jsob.put("trouble_type", s.split("\t")[8]);
jsob.put("trouble_start_time", s.split("\t")[9]);
jsob.put("trouble_end_time", s.split("\t")[10]);
jsob.put("trouble_desc", s.split("\t")[12]);
jsob.put("alarmlevel", s.split("\t")[13]);
responsejsons.add(jsob);
}
}
response_result = responsejsons.toString();
}
logger.info("这是返回的故障告警信息的Json数据格式: " + response_result.toString());
logger.info("退出station_error函数");
conn.close();
return response_result;
}
}<file_sep>package com.homer.bean;
public class QueryPreResp extends BaseResp {
private String preDealResult;
public QueryPreResp(int result, String text, String preDealResult) {
super(result, text);
this.preDealResult = preDealResult;
}
public String getPreDealResult() {
return preDealResult;
}
public void setPreDealResult(String preDealResult) {
this.preDealResult = preDealResult;
}
}
<file_sep># TS
This repository is created for storing the project of TS_test. created on github at 2017-01-12 09:15:00.
<file_sep>package my_hbase;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Map;
public class test_hbase {
/**
* @param args
* @throws IOException
* @throws SQLException
* @throws FileNotFoundException
* @throws ClassNotFoundException
* @throws ParseException
*/
public static void main(String[] args)
throws ClassNotFoundException, FileNotFoundException, SQLException, IOException, ParseException {
System.out.println("开始查找HBase话单");
Gets_HBase gHBase = new Gets_HBase();
ArrayList<Map<String, String>[]> value = gHBase.pcmd_query("18171406899", 1443697442, 1443697444);
System.out.println("查找HBase话单结束");
for (Map<String,String >[] a:value)
{
for (Map b:a)
{
System.out.println(b.toString());
}
// for (String key : a.keySet()) {
// System.out.println("key= "+ key + " and value= " + map.get(key));
// }
}
//System.out.print(value);
// Date a = new Date(1431649500000l);
// Date b = new Date(1431663900000l);
// SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd");
// String dBegin = sm.format(a);
// String dEnd = sm.format(b);
// Date x = sm.parse(dBegin);
// Date y = sm.parse(dEnd);
//// //Date dEnd = new Date(b.getYear(),b.getMonth(),b.getDay());
// System.out.println(x+" "+y);
// System.out.println(q.findDates(x, y));
}
}
<file_sep>define([
'backbone'
], function(Backbone) {
"use strict";
var StatisticByPrejudgingReason = Backbone.Model.extend({
initialize: function(options){
this.urlRoot = 'statistic_by_prejudging_reason.html';
this.url = this.urlRoot;
}
});
return StatisticByPrejudgingReason;
});<file_sep>define([
'backbone'
], function(Backbone) {
"use strict";
var PerformanceCount = Backbone.Model.extend({
});
return PerformanceCount;
});<file_sep>function ScrollLoadList(id,arr,template,callback){
var element=document.getElementById(id);
var isActive=true;
var scrollHeight;
this.updateView=function(){
isActive=true;
scrollHeight=element.scrollHeight;
};
element.addEventListener("scroll",load,false);
function load(e){
if(this.scrollTop==(this.scrollHeight-this.offsetHeight) && isActive){
isActive=false;
callback();
}
}
}<file_sep>package com.hbase.cityReached;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Properties;
/*java防SQL注入,最简单的办法是杜绝SQL拼接,SQL注入攻击能得逞是因为在原有SQL语句中加入了新的逻辑,
如果使用PreparedStatement来代替Statement来执行SQL语句,其后只是输入参数,SQL注入攻击手段将无效,
这是因为PreparedStatement不允许在不同的插入时间改变查询的逻辑结构 ,大部分的SQL注入已经挡住了。
*/
public class MyDBManager {
// private String driver="com.mysql.jdbc.Driver";
// private String url="jdbc:mysql://172.16.58.3:3306/PreDealSys2?useUnicode=true&characterEncoding=utf8";
// private String user="root";
// private String pass="<PASSWORD>";
private String driver=null;
private String url=null;
private String user=null;
private String pass=null;
private String mysqlConfFilePath="/mysql.properties";
private static MyDBManager instance;
/*单例模式获取一个对象*/
private MyDBManager(){
}
public static MyDBManager getInstance(){
if(instance==null){
instance = new MyDBManager();
}
return instance;
}
//数据库连接配置文件
public void initParam(String paramFile) throws FileNotFoundException, IOException{
Properties props = new Properties();
props.load(new FileInputStream(paramFile));
driver = props.getProperty("driver");
url = props.getProperty("url");
user = props.getProperty("user");
pass = props.getProperty("pass");
}
/*1.
* 获取数据库链接对象函数
*/
public Connection getConnection() {
try {
//获取SqlPreStatement类所在的路径
String path = MyDBManager.class.getResource("")+"";
path = path.substring(5, path.length());
// System.out.println("I wonder\n"+path);
initParam(path+mysqlConfFilePath);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//1 加载数据库驱动
try {
Class.forName(this.driver);
} catch (ClassNotFoundException e) {
System.out.println("error:加载数据库驱动 发生异常");
e.printStackTrace();
}
//2 获取数据库连接
String url = this.url;
String user = this.user;
String password = <PASSWORD>;
Connection conn = null;
try {
conn = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
System.out.println("error:获取数据库链接对象发生异常");
e.printStackTrace();
}
return conn;
}
// /*2. select查询函数1
// 参考sql = "select id,loginName,email from "+tableName+" where id=? and name=?";
// * 传进参数:需要预编译的sql语句,占位符对应的参数
// * 返回值: 以行为元素(每一行的列与列之间用分号;隔开)的线性表
// */
// public ArrayList<String> selectData(String sql, Object[] conditionValues, Connection conn){
// if(!sql.toLowerCase().startsWith("select")){
// System.out.println("ERROR:输入的SQL查询语句有误,请核对!");
// return null;
// }
//
// //7.执行预编译sql语句
// PreparedStatement preStatement = null;
// try {
// preStatement = conn.prepareStatement(sql);
// } catch (SQLException e) {
// System.out.println("error:预编译异常");
// e.printStackTrace();
// }
//
// //8.添加条件的值
// for (int i=0;i<conditionValues.length;i++) {
// try {
// preStatement.setObject(i+1, conditionValues[i]);
// } catch (SQLException e) {
// System.out.println("error:添加条件值,取代预编译语句中的占位符发生异常");
// e.printStackTrace();
// }
// }
//
// //9.执行mysql的操作,得到结果集
// ArrayList<String> list = new ArrayList<String>();
// ResultSet resultSet=null;
// try {
// resultSet = preStatement.executeQuery();
// } catch (SQLException e) {
// System.out.println("error:执行预编译后的sql语句发生异常");
// e.printStackTrace();
// }
// ResultSetMetaData rsmd = null;
// try {
// rsmd = resultSet.getMetaData();
// } catch (SQLException e) {
// System.out.println("error:获取结果集对象的相关数据发生异常");
// e.printStackTrace();
// }
// int columnCount = 0;
// try {
// columnCount = rsmd.getColumnCount();
// } catch (SQLException e) {
// System.out.println("error:获取结果集对象的列数目发生异常");
// e.printStackTrace();
// }
//
// String line = "";
// try {
// while(resultSet.next())
// {
// for (int i =0 ; i< columnCount ; i++){
// line += resultSet.getString(i+1) + ";"; //每一行的列与列之间的数据用分号隔开
// }
// line = line.substring(0, line.length()-1); //去掉最后一列数据后面的那个分号
// list.add(line);//获取得到的值,作为list的元素存储,这样就可以遍历获取得到
// line = "";//清空之前的行,以保存下一行数据
// }
// } catch (SQLException e) {
// System.out.println("error:将查询结果一行一行添加到ArrayList发生异常");
// e.printStackTrace();
// }
//
// //关闭相关连接
// try {
// resultSet.close();
// } catch (SQLException e) {
// System.out.println("error:关闭查询结果集对象发生异常");
// e.printStackTrace();
// }
// try {
// preStatement.close();
// } catch (SQLException e) {
// System.out.println("error:关闭mysql预编译对象发生异常");
// e.printStackTrace();
// }
//
// return list;
//
// }
//
/*
* 3.select
* 返回查询结果集合ResultSet
* */
public ResultSet selectData(String sql, Object[] conditionValues, Connection conn,PreparedStatement preStatement){
if(!sql.toLowerCase().startsWith("select")){
System.out.println("ERROR:输入的SQL查询语句有误,请核对!");
return null;
}
//7.执行预编译sql语句
try {
preStatement = conn.prepareStatement(sql);
} catch (SQLException e) {
System.out.println("error:预编译异常");
e.printStackTrace();
return null;
}
//8.添加条件的值
for (int i=0;i<conditionValues.length;i++) {
try {
preStatement.setObject(i+1, conditionValues[i]);
} catch (SQLException e) {
System.out.println("error:添加条件值,取代预编译语句中的占位符发生异常");
e.printStackTrace();
return null;
}
}
//9.执行mysql的操作,得到结果集
ResultSet resultSet=null;
try {
resultSet = preStatement.executeQuery();
} catch (SQLException e) {
System.out.println("error:执行预编译后的sql语句发生异常");
e.printStackTrace();
return null;
}
return resultSet;
}
/*4.insert插入数据函数1
* 传进参数:需要预编译的插入sql语句,占位符对应的参数。参考:String sql = "insert into person(name,age,description)values(?,?,?)";
* 返回值: 此次操作受影响的行数
*/
public int insertData(String sql, Object[] insertValues, Connection conn){
//检查sql语句是否是插入语句
if(!sql.toLowerCase().startsWith("insert")){
System.out.println("ERROR:输入的SQL插入语句有误,请核对!");
return -1;
}
//检查SQL语句占位符数目和插入值数目是否相等
int count = 0;
int valueNum = insertValues.length;
for (int i=0; i < sql.length();i++) {
if (sql.charAt(i) == '?') {
count++;
}
}
if (count != valueNum) {
System.out.println("ERROR:插入的列占位符数目和插入数据数目不一致,请核对!");
return -1;
}
//7.执行预编译sql语句
PreparedStatement preStatement = null;
try {
preStatement = conn.prepareStatement(sql);
} catch (SQLException e) {
System.out.println("error:预编译异常");
e.printStackTrace();
}
//8.添加条件的值
for (int i=0;i<valueNum;i++) {
try {
preStatement.setObject(i+1, insertValues[i]);
} catch (SQLException e) {
System.out.println("error:添加条件值,取代预编译语句中的占位符发生异常");
e.printStackTrace();
}
}
//9.执行mysql的操作,得到受影响行数
int result=0;
try {
result = preStatement.executeUpdate();
} catch (SQLException e) {
System.out.println("error:执行预编译后的sql语句发生异常");
e.printStackTrace();
}
//关闭相关连接
try {
preStatement.close();
} catch (SQLException e) {
System.out.println("error:关闭mysql预编译对象发生异常");
e.printStackTrace();
}
return result;
}
/*5.insert插入数据函数2
* 传进参数:需要预编译的插入sql语句,占位符对应的参数。参考:String sql = "insert into person(name,age,description)values(?,?,?)";
* 返回值:插入的数据在表中的第几行数
*/
public int insertData(String sql, Object[] insertValues, String tableName,String columnName,Connection conn){
//检查sql语句是否是插入语句
if(!sql.toLowerCase().startsWith("insert")){
System.out.println("ERROR:输入的SQL插入语句有误,请核对!");
return -1;
}
//检查SQL语句占位符数目和插入值数目是否相等
int count = 0;
int valueNum = insertValues.length;
for (int i=0; i < sql.length();i++) {
if (sql.charAt(i) == '?') {
count++;
}
}
if (count != valueNum) {
System.out.println("ERROR:插入的列占位符数目和插入数据数目不一致,请核对!");
return -1;
}
//7.执行预编译sql语句
PreparedStatement preStatement = null;
try {
preStatement = conn.prepareStatement(sql);
} catch (SQLException e) {
System.out.println("error:预编译异常");
e.printStackTrace();
}
//8.添加条件的值
for (int i=0;i<valueNum;i++) {
try {
preStatement.setObject(i+1, insertValues[i]);
} catch (SQLException e) {
System.out.println("error:添加条件值,取代预编译语句中的占位符发生异常");
e.printStackTrace();
}
}
//9.执行mysql的操作
try {
preStatement.executeUpdate();;
} catch (SQLException e) {
System.out.println("error:执行预编译后的sql语句发生异常");
e.printStackTrace();
}
//获取插入数据库的最新记录的行数
String str = "select MAX("+columnName+") from "+tableName;
PreparedStatement pStatement=null;
int value = 0;
try {
pStatement = conn.prepareStatement(str);
pStatement.executeQuery();
ResultSet rs = pStatement.getResultSet();
if(rs.next()){
value= rs.getInt(1);
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//关闭相关连接
try {
pStatement.close();
preStatement.close();
} catch (SQLException e) {
System.out.println("error:关闭mysql预编译对象发生异常");
e.printStackTrace();
}
return (value);
}
/*7.update更新数据库
* 传进参数:占位符对应的参数。数据库连接。
* 返回值: 此次操作受影响的行数
*/
public int updateData(Object[] updateAndConditionValues, PreparedStatement preStatement, Connection conn){
int valueNum = updateAndConditionValues.length;
//8.添加值取代占位符,包括需要更新的值,以及条件值
try {
for (int i=0;i<valueNum;i++) {
preStatement.setObject(i+1, updateAndConditionValues[i]);
}
} catch (SQLException e) {
System.out.println("error:添加条件值,取代预编译语句中的占位符发生异常");
e.printStackTrace();
}
//9.执行mysql的操作,得到受影响行数
int result=0;
try {
result = preStatement.executeUpdate();;
} catch (SQLException e) {
System.out.println("error:执行预编译后的sql语句发生异常");
e.printStackTrace();
}
return result;
}
/*8.update更新数据库
* 传进参数:需要预编译的插入sql语句,占位符对应的参数。参考:String sql = "update person set name=?,age=?,description=? where id=?";
* 返回值: 此次操作受影响的行数
*/
public int updateData(String sql,Object[] updateAndConditionValues,PreparedStatement preStatement, Connection conn){
//检查sql语句是否是插入语句
if(!sql.toLowerCase().startsWith("update")){
System.out.println("ERROR:输入的SQL更新语句有误,请核对!");
return -1;
}
// //检查SQL语句占位符数目和插入值数目是否相等
int count = 0;
int valueNum = updateAndConditionValues.length;
for (int i=0; i < sql.length();i++) {
if (sql.charAt(i) == '?') {
count++;
}
}
if (count != valueNum) {
System.out.println("ERROR:插入的列占位符数目和插入数据数目不一致,请核对!");
return -1;
}
try {
preStatement = conn.prepareStatement(sql);
} catch (SQLException e1) {
System.out.println("预编译错!");
e1.printStackTrace();
}
//8.添加值取代占位符,包括需要更新的值,以及条件值
try {
for (int i=0;i<valueNum;i++) {
preStatement.setObject(i+1, updateAndConditionValues[i]);
}
} catch (SQLException e) {
System.out.println("error:添加条件值,取代预编译语句中的占位符发生异常");
e.printStackTrace();
}
//9.执行mysql的操作,得到受影响行数
int result=0;
try {
result = preStatement.executeUpdate();;
} catch (SQLException e) {
System.out.println("error:执行预编译后的sql语句发生异常");
e.printStackTrace();
}
return result;
}
/*8.delete删除数据库的行
* 传进参数:需要预编译的插入sql语句,占位符对应的参数。参考:String sql = "delete from person where id=?";
* 返回值: 此次操作受影响的行数
*/
public int deleteData(String sql, Object[] conditionValues, Connection conn, PreparedStatement preStatement){
//检查sql语句是否是插入语句
if(!sql.toLowerCase().startsWith("delete")){
System.out.println("ERROR:输入的SQL删除语句有误,请核对!");
return -1;
}
//检查SQL语句占位符数目和插入值数目是否相等
int count = 0;
int valueNum = conditionValues.length;
for (int i=0; i < sql.length();i++) {
if (sql.charAt(i) == '?') {
count++;
}
}
if (count != valueNum) {
System.out.println("ERROR:插入的列占位符数目和插入数据数目不一致,请核对!");
return -1;
}
//7.执行预编译sql语句
try {
preStatement = conn.prepareStatement(sql);
} catch (SQLException e) {
System.out.println("error:预编译异常");
e.printStackTrace();
}
//8.添加值取代占位符,条件值
for (int i=0;i<valueNum;i++) {
try {
preStatement.setObject(i+1, conditionValues[i]);
} catch (SQLException e) {
System.out.println("error:添加条件值,取代预编译语句中的占位符发生异常");
e.printStackTrace();
}
}
//9.执行mysql的操作,得到受影响行数
int result=0;
try {
result = preStatement.executeUpdate();;
} catch (SQLException e) {
System.out.println("error:执行预编译后的sql语句发生异常");
e.printStackTrace();
}
return result;
}
}
<file_sep>'use strict';
var util = require('util');
/**
* 自动合成CSS雪碧图的CSS类过滤器
* @param {String} prefix 类名前缀
* @param {String} item 原始CSS类名
* @return {String} 最终的CSS类名
*/
exports.cssClassFilter = function(prefix, item) {
var conf = require('./css-sprites-config.json'),
cssName = util.format('.%s-%s', prefix, item.name),
result = cssName,
origin, parent;
if (item.name.indexOf('-hover') >= 0) {
origin = item.name.replace('-hover', '');
cssName = util.format('%s-%s:hover, %s-%s.active',
prefix, origin, prefix, origin);
// cssName = prefix + originalName + ':hover,' + prefix + originalName + '.active';
if (conf.hover.hasOwnProperty(item.name)) {
parent = conf.hover[item.name];
cssName += util.format(', .%s:hover %s', parent, cssName);
cssName += util.format(', .%s.active %s', parent, cssName);
}
} else if (conf.active.hasOwnProperty(item.name) &&
item.name.indexOf('-active') >= 0) {
result = util.format('.%s-%s', prefix, item.name.replace('-active', '.active'));
}
return result;
};
<file_sep>define([
'backbone'
], function(Backbone) {
"use strict";
var SearchInfo = Backbone.Model.extend({
defaults: {
"search_type":"",
"search_text":"",
"start_time":"",
"end_time":""
},
initialize: function(options){
this.urlRoot = '';
}
});
return SearchInfo;
});<file_sep>define(['backbone',
'models/station_error_statistic_info',
],
function(Backbone, StationErrorStatisticInfo) {
var StationErrorStatisticInfoCollection = Backbone.Collection.extend({
model: StationErrorStatisticInfo,
initialize: function(options){
this.urlRoot = 'statistic_by_station_error.html';
this.url = this.urlRoot;
}
});
return StationErrorStatisticInfoCollection;
});<file_sep>define([
'underscore',
'backbone',
'marionette',
'backbone_modelbinder',
'backbone_validation',
'bmap_api',
'cookie',
'views/partials/common/positionSelect',
"tpl!views/partials/common/common_t/inputInfoItem.tpl",
], function(_, Backbone, Marionette, ModelBinder, Validation, BMap, Cookie, PSelectView, inputInfoItemTpl) {
"use strict";
var InputInfoItemView = Marionette.ItemView.extend({
template: inputInfoItemTpl,
triggers:{
"click #itemSubmit": "showComplaintResult",
"click #reInput": "showInputView",
'click #setLocation': "setLocation"
},
events: {
'click #refreshTime': 'refreshTime',
// 'click #refreshPage': 'refreshPage',
// 'click #setLocation': 'setLocation',
},
initialize: function() {
console.log('init inputInfoItem view');
this._modelBinder = new Backbone.ModelBinder();
Backbone.Validation.bind(this, {
valid: function (view, attr, selector) {
var $el = view.$('[name=' + attr + ']'),
$group = $el.closest('.form-group');
$group.removeClass('has-error');
$group.find('.help-block').html('').addClass('hidden');
},
invalid: function (view, attr, error, selector) {
var $el = view.$('[name=' + attr + ']'),
$group = $el.closest('.form-group');
$group.addClass('has-error');
$group.find('.help-block').html(error).removeClass('hidden');
}
});
},
onShow: function(){
// $('#staffId').val(Cookie.get('staff_id'));
// $('#itemCallNum').val(Cookie.get('complaint_phone'));
// $('#search_radius').val(Cookie.get('search_radius'));
// $('#search_time_range').val(Cookie.get('search_time_range'));
//显示获取到的地图信息
// 调试modelbinder用
// this.model.bind('change', function () {
// $('#modelData').html(JSON.stringify(this.toJSON()));
// });
// this.model.trigger('change');
//设置modelbinder
//转换时间格式,YY:MM:DDThh:mm:ss->YY:MM:DD hh:mm:ss
var timeConverter = function (direction, value) {
var tmp;
if (direction === Backbone.ModelBinder.Constants.ViewToModel) {
tmp = value.substring(0,10)+' '+value.substring(11,16);
return tmp;
}
else {
if(value){
tmp = value.substring(0,10)+'T'+value.substring(11,16);
}
return tmp;
}
};
var bindings = {
staff_id: '[name=staff_id]',
complaint_phone: '[name=complaint_phone]',
// complaint_phone: '#itemCallNum',
location: '[name=location]',
longitude:'[name=longitude]',
latitude:'[name=latitude]',
pheno_option:'[name=pheno_option]',
pheno_description:'[name=pheno_description]',
complaint_time:{selector:'[name=complaint_time]'},
occur_time:{selector:'[name=occur_time]', converter: timeConverter},
pheno_always:'[name=pheno_always]',
search_radius:'[name=search_radius]',
search_time_range: '[name=search_time_range]',
net_type: '[name=complaint_type_option]'
};
this._modelBinder.bind(this.model, this.el, bindings);
this.showPlaceSuggestion();
// this.pselectView = new PSelectView();
// setInterval(alert("sada"),5000);
// this.countSecond();
// $('#suggestId').val(Cookie.get('location'));
// $('#lng').val(Cookie.get('lng'));
// $('#lat').val(Cookie.get('lat'));
// setTimeout($('#suggestId').val(Cookie.get('location')),1000);
// $('#suggestId').val(Cookie.get('location'));
// this.refreshPage();
// $('#staffId').val(Cookie.get('staff_id'));
// $('#itemCallNum').val(Cookie.get('complaint_phone'));
// $('#search_radius').val(Cookie.get('search_radius'));
// $('#search_time_range').val(Cookie.get('search_time_range'));
// if(Cookie.get('search_radius')==""){
// $('#search_radius').val("500");
// }
// if(Cookie.get('search_time_range')==""){
// $('#search_time_range').val("2");
// }
},
showPlaceSuggestion: function(){
var self = this;
this.map = new BMap.Map("l-map");
// 百度地图API功能
var ac = new BMap.Autocomplete({
"input" : "suggestId", "location" : this.map
});
// <input type="text" name="locationTemp" style="display:hidden"/>
$('[name=locationTemp]').val(Cookie.get('location'));
$('#lng').val(Cookie.get('lng'));
$('#lat').val(Cookie.get('lat'));
// $('[name=location]').val("sdaffdas");
setTimeout("$('[name=location]').val($('[name=locationTemp]').val());",100);
ac.addEventListener("onhighlight", function(e) { //鼠标放在下拉列表上的事件
var str = "";
var _value = e.fromitem.value;
var value = "";
if (e.fromitem.index > -1) {
value = _value.province + _value.city + _value.district + _value.street + _value.business;
}
str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;
value = "";
if (e.toitem.index > -1) {
_value = e.toitem.value;
value = _value.province + _value.city + _value.district + _value.street + _value.business;
}
str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
document.getElementById("searchResultPanel").innerHTML = str;
});
ac.addEventListener("onconfirm", function(e) { //鼠标点击下拉列表后的事件
var _value = e.item.value;
self.myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
document.getElementById("searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + self.myValue;
self.model.set('location',self.myValue);
self.setPlace();
});
},
setPlace: function(){
var self = this;
function myFun(){
var pp = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
self.longlatTransform(pp);
}
var local = new BMap.LocalSearch(this.map, { //智能搜索
onSearchComplete: myFun
});
local.search(this.myValue);
},
setLocation: function(){
var self = this;
var str = $('#suggestId').val();
return str;
// 百度地图搜索地址功能,两个不同的例子
// var map = new BMap.Map("l-map");
// map.centerAndZoom(new BMap.Point(114.307, 30.556), 11);
// var options = {
// onSearchComplete: function(results){
// // 判断状态是否正确
// if (local.getStatus() == BMAP_STATUS_SUCCESS){
// var s = [];
// for (var i = 0; i < results.getCurrentNumPois(); i ++){
// s.push(results.getPoi(i).title + ", " + results.getPoi(i).address);
// }
// document.getElementById("r-result").innerHTML = s.join("<br/>");
// }
// }
// };
// var local = new BMap.LocalSearch(map, options);
// local.search(this.model.get('location'));
// var map = new BMap.Map("l-map"); // 创建Map实例
// map.centerAndZoom(new BMap.Point(114.307, 30.556), 10);
// var local = new BMap.LocalSearch(map, {
// renderOptions: { panel: "r-result"},
// pageCapacity:5
// });
// local.search(this.model.get('location'));
// var staffId = $('#staffId').val();
// var itemCallNum = $('#itemCallNum').val();
// var search_radius = $('#search_radius').val();
// var earch_time_range = $('#earch_time_range').val();
// var itemPheno = $('#itemPheno').val();
// Cookie.set('staffId',staffId);
// Cookie.set('itemCallNum',itemCallNum);
// Cookie.set('search_radius',search_radius);
// Cookie.set('earch_time_range',earch_time_range);
// Cookie.set('itemPheno',itemPheno);
// window.open('#pselect/'+str,'_blank','height=500,width=800,top=100,left=100');
// this.pselectView.setLocation(str);
// 创建地址解析器实例
// var myGeo = new BMap.Geocoder();
// 将地址解析结果显示在地图上,并调整地图视野
// myGeo.getPoint(this.model.get('location'), function(Point){
// if (Point) {
// // map.centerAndZoom(point, 16);
// // map.addOverlay(new BMap.Marker(point));
// console.log(Point);
// self.longlatTransform(Point);
// }
// else{
// alert("未找到相应地点");
// }
// }, "武汉市");
},
longlatTransform: function(Point){
var self = this;
//将百度经纬度转化为实际经纬度
function translateCallback(data){
if(data.status === 0) {
var BPoint = [];
BPoint[0] = Point;
BPoint[1] = data.points[0];
var GPSPoint = {};
GPSPoint.lng = 2*BPoint[0].lng - BPoint[1].lng;
GPSPoint.lat = 2*BPoint[0].lat - BPoint[1].lat;
$('[name=longitude]').val(GPSPoint.lng.toFixed(6));
self.model.set('longitude',$('[name=longitude]').val());
$('[name=latitude]').val(GPSPoint.lat.toFixed(6));
self.model.set('latitude',$('[name=latitude]').val());
}
}
var convertor = new BMap.Convertor();
var pointArr = [];
pointArr.push(Point);
convertor.translate(pointArr, 1, 5, translateCallback);
},
refreshTime: function(){
var now = new Date();
var year = now.getFullYear(); //年
var month = now.getMonth() + 1; //月
var day = now.getDate(); //日
var hh = now.getHours(); //时
var mm = now.getMinutes(); //分
var clock = year + "-";
if(month < 10)
clock += "0";
clock += month + "-";
if(day < 10)
clock += "0";
clock += day + " ";
if(hh < 10)
clock += "0";
clock += hh + ":";
if (mm < 10) clock += '0';
clock += mm;
// return(clock);
this.model.set('complaint_time',clock);
this.model.set('occur_time',clock);
},
getLnglat: function(){
var lng = Cookie.get('lng');
var lat = Cookie.get('lat');
alert(lng+lat);
},
countSecond: function(){
// var str = Cookie.get('location');
// function timedCount()
// {
$('#suggestId').val(Cookie.get('location'));
$('#lng').val(Cookie.get('lng'));
$('#lat').val(Cookie.get('lat'));
// setTimeout(timedCount(),15000);
// }
// timedCount();
// alert("jj");
// console.log("dsda");
},
refreshPage: function(){
// window.location.reload();
// window.open('#home');
$('#suggestId').val(Cookie.get('location'));
$('#lng').val(Cookie.get('lng'));
$('#lat').val(Cookie.get('lat'));
}
});
return InputInfoItemView;
});
// 获取某个view中el元素某个class的值
// inputInfoItemView.el.getElementsByTagName("input")[4].value<file_sep>define([
'underscore',
'backbone',
'marionette',
'bmap_api'], function(_, Backbone, Marionette) {
"use strict";
var DistrictOverlay = Backbone.View.extend({
colors:{
"0": "#FF7F50", //coral
"1": "#A52A2A", //brown
"2": "#337AB7", //blue
"3": "#FFA500", //orange
"4": "#31708F", //dark blue
"5": "#3C763D", //green
"6": "#C38A22", //brown yellow
"7": "#000080", //navy
"8": "#FF0000", //red
"9": "#800080", //purple
"10": "#CD853F", //peru
"11": "#D8BFD8", //thistle
"12": "#00FF7F", //springgreen
"13": "#AFEEEE", //paleturquoise
"14": "#CD853F", //peru
"15": "#D8BFD8", //thistle
"16": "#00FF7F", //springgreen
"17": "#AFEEEE", //paleturquoise
},
initialize: function(options){
var self = this;
this.map = options.map;
var map = this.map;
this.getBoundary("","white",1);
for(var i=0;i<this.collection.length;i++){
this.getBoundary(this.collection.models[i].get('district'),this.colors[i],0);//获取行政区划
}
//添加文字标签
function addLabel(){
self.addLabel();
}
var t = window.setInterval(addLabel,3000);
this.i = 0;
//因为百度api没有襄阳的行政区划,故自己添加
$.get("assets/scripts/data/xiangyang.txt", function(result){
var ply = new BMap.Polygon(result, {strokeColor:"white", strokeWeight:1,
strokeOpacity:0.5, fillColor:"blue", fillOpacity:0.7}); //建立多边形覆盖物
map.addOverlay(ply); //添加覆盖物
});
},
getBoundary: function(str,color,type){
var bdary = new BMap.Boundary();
var map = this.map;
var self = this;
bdary.get("湖北省"+str, function(rs){ //获取行政区域
var count = rs.boundaries.length; //行政区域的点有多少个
if (count === 0) {
alert('未能获取'+str+'行政区域');
return ;
}
var pointArray = [];
var ply = [];
for (var i = 0; i < count; i++) {
if(type===0){
//地城样式
ply[i] = new BMap.Polygon(rs.boundaries[i], {strokeColor:"white", strokeWeight:1,
strokeOpacity:0.5, fillColor:color, fillOpacity:0.7}); //建立多边形覆盖物
}
else if(type===1){
//湖北省样式
ply[i] = new BMap.Polyline(rs.boundaries[i], {strokeColor:"black", strokeWeight:2,
strokeOpacity:1, strokeStyle:"dashed"});
}
map.addOverlay(ply[i]); //添加覆盖物
// pointArray = pointArray.concat(ply.getPath());
ply[i].addEventListener("click", function(e){
// console.log(str);
// var point = e.point;
self.addWindow(str,e.point);
});
}
// map.setViewport(pointArray); //调整视野
});
},
addLabel: function(){
var map = this.map;
var point = new BMap.Point(114.287123,30.522732);
var point1 = new BMap.Point(113.652416,30.898295);//孝感
var opts = {
position : point, // 指定文本标注所在的地理位置
offset : new BMap.Size(-100, -5) //设置文本偏移量
};
var opts1 = {
position : point1, // 指定文本标注所在的地理位置
offset : new BMap.Size(-100, -5) //设置文本偏移量
};
var str;
var str1;
if(this.i<=254){
this.i++;
}
else{
this.i = 0;
}
switch(this.i%3){
case 0:
str = "武汉市</br>基站总数:200";
str1 = "孝感市</br>基站总数:100";
break;
case 1:
str = "武汉市</br>退服基站总数:20";
str1 = "孝感市</br>退服基站总数:30";
break;
case 2:
str = "武汉市</br>2G/3G/4G基站退服数:2/6/4";
str1 = "孝感市</br>2G/3G/4G基站退服数:1/2/4";
break;
default:
str = "武汉市</br>Errotr";
str1 = "孝感市</br>Errotr";
break;
}
var label = new BMap.Label(str, opts); // 创建文本标注对象
var label1 = new BMap.Label(str1, opts1); // 创建文本标注对象
label.setStyle({
color : "black",
fontSize : "12px",
minWidth: "200px",
height : "45px",
lineHeight : "20px",
fontFamily:"微软雅黑",
border:"1px black solid"
});
label1.setStyle({
color : "black",
fontSize : "12px",
minWidth: "200px",
height : "45px",
lineHeight : "20px",
fontFamily:"微软雅黑",
border:"1px black solid"
});
map.addOverlay(label);
map.addOverlay(label1);
},
addWindow: function(str,point){
var map = this.map;
var opts = {
width : 200, // 信息窗口宽度
height: 100, // 信息窗口高度
title : str , // 信息窗口标题
};
var infoWindow = new BMap.InfoWindow(point.lng+','+point.lat, opts); // 创建信息窗口对象
map.openInfoWindow(infoWindow,point); //开启信息窗口
}
});
return DistrictOverlay;
});<file_sep>define(['backbone',
'backbone_paginator',
'models/call_info',
],
function(Backbone, PageableCollection, CallInfo) {
var CallInfoCollection = Backbone.PageableCollection.extend({
// model: CallInfo,
mode: "client",
initialize: function(options){
this.urlRoot = 'call_info.html';
this.url = this.urlRoot + '?complaint_item_id=' + options.id;
}
});
return CallInfoCollection;
});
<file_sep>define(['backbone',
'models/station_error',
],
function(Backbone, StationError) {
var StationErrorCollection = Backbone.Collection.extend({
model: StationError,
initialize: function(options){
this.urlRoot = 'station_error.html';
this.url = this.urlRoot + '?complaint_item_id=' + options.id;
}
});
return StationErrorCollection;
});
<file_sep>define([
'backbone',
'marionette',
'views/root',
'views/home/home',
'views/login/login',
'views/map/map',
'views/partials/common/positionSelect',
], function(Backbone, Marionette, RootView, HomeView, LoginView, MapView, PositionSelectView) {
"use strict";
var AppController = Marionette.Controller.extend({
initialize: function() {
this.rootView = new RootView();
this.region = this.rootView.getRegion('main');
},
goHomePage: function() {
var homeView = new HomeView();
this.region.show(homeView);
homeView.showInputView();
},
goSelectPage: function(){
// alert("111");
var selectView = new PositionSelectView();
this.region.show(selectView);
// alert("222");
},
goLoginPage: function() {
var loginView = new LoginView();
this.region.show(loginView);
},
goComplaintPage: function(id){
var homeView = new HomeView();
this.region.show(homeView);
homeView.showJudgeResult(id);
},
goMapPage: function(){
var mapView = new MapView();
this.region.show(mapView);
// homeView.showJudgeResult(id);
},
});
return AppController;
});
<file_sep>// Decompiled by DJ v3.12.12.96 Copyright 2011 <NAME> Date: 2016-04-23 20:08:22
// Home Page: http://members.fortunecity.com/neshkov/dj.html http://www.neshkov.com/dj.html - Check often for new version!
// Decompiler options: packimports(3)
// Source File Name: ComplaintObj.java
package com.homer.bean;
public class ComplaintObj
{
public ComplaintObj(int id, String datetime, int type, String loc, int state)
{
this.id = id;
this.datetime = datetime;
this.type = type;
this.loc = loc;
this.state = state;
}
public ComplaintObj()
{
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getDatetime()
{
return datetime;
}
public void setDatetime(String datetime)
{
this.datetime = datetime;
}
public int getType()
{
return type;
}
public void setType(int type)
{
this.type = type;
}
public String getTypeWord()
{
return typeWord;
}
public void setTypeWord(String typeWord)
{
this.typeWord = typeWord;
}
public void setTypeWord(int state)
{
if(type == 1)
typeWord = "4G\u6570\u636E\u6295\u8BC9";
else
if(type == 2)
typeWord = "3G\u6570\u636E\u6295\u8BC9";
else
if(type == 3)
typeWord = "2G\u8BED\u97F3\u6295\u8BC9";
else
typeWord = "\u672A\u77E5\u7C7B\u578B";
}
public String getLoc()
{
return loc;
}
public void setLoc(String loc)
{
this.loc = loc;
}
public int getState()
{
return state;
}
public void setState(int state)
{
this.state = state;
}
public String getStateWord()
{
return stateWord;
}
public void setStateWord(String stateWord)
{
this.stateWord = stateWord;
}
public void setStateWord(int type)
{
if(type == 0)
stateWord = "\u6295\u8BC9\u5904\u7406\u4E2D";
else if(type == 1)
stateWord = "\u6295\u8BC9\u5904\u7406\u5DF2\u7ED3\u675F";
else
stateWord = "\u5F02\u5E38\uFF01\u672A\u77E5\u72B6\u6001";
}
private int id;
private String datetime;
private int type;
private String typeWord;
private String loc;
private int state;
private String stateWord;
}
<file_sep>package my_hbase;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Map;
public class test_hbase {
/**
* @param args
* @throws IOException
* @throws SQLException
* @throws FileNotFoundException
* @throws ClassNotFoundException
* @throws ParseException
*/
public static void main(String[] args)
throws ClassNotFoundException, FileNotFoundException, SQLException, IOException, ParseException {
System.out.println("开始查找HBase话单");
//15327263799
ArrayList<Map<String, String>[]> value = Gets_HBase.pcmd_query("18171406899", 1443697442, 1443697444);
// ArrayList<Map<String, String>[]> value = Gets_HBase.pcmd_query("15327263799", 1475317477, 1475317479);
System.out.println("查找HBase话单结束");
for (Map<String,String >[] a:value)
{
for (Map<?, ?> b:a)
{
System.out.println(b.toString());
}
}
}
}
<file_sep>package com.hbase.dao;
import java.util.List;
import java.util.Map;
import org.apache.hadoop.hbase.client.Put;
public interface HBaseDao {
public void init(String tableName);
public void insertRow(String tableName,String rowkey,String family,String[] qualifiers,String[] values);
public void insertPut(String tableName,String rowkey,Put put);
public Map<String,List<String>> select(String tableName, String rowkey, String family, String[] qualifiers);
public List<String> select(String tableName, String rowkey, String family, String qualifier);
public void update();
public void delete();
public void close();
}
<file_sep>package pre_deal;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import myquery.Query;
import mysql.mysql_DML;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import cell_info.Find_Cell;
import domain.Grid;
import service.GridService;
@Controller
public class RelatedCells{
@Autowired
private static Logger logger = Logger.getLogger(RelatedCells.class);
private GridService gridService;
private String search_r;
private String search_t;
private String init_lon;
private String init_lat;
private String cellDensityThreshold;
private int cell_rsCode = 40; //默认没有找到小区
private int cell_rsColorCode = 10;
private String cell_rsColorType = "white";
private static String path = MyFilePath.TCPropertiesPath;
public int getCell_rsCode() {
return cell_rsCode;
}
public void setCell_rsCode(int cell_rsCode) {
this.cell_rsCode = cell_rsCode;
}
public int getCell_rsColorCode() {
return cell_rsColorCode;
}
public void setCell_rsColorCode(int cell_rsColorCode) {
this.cell_rsColorCode = cell_rsColorCode;
}
public String getCell_rsColorType() {
return cell_rsColorType;
}
public void setCell_rsColorType(String cell_rsColorType) {
this.cell_rsColorType = cell_rsColorType;
}
private void initParam(String paramFile) throws FileNotFoundException, IOException
{
Properties props = new Properties();
props.load(new FileInputStream(paramFile));
search_r = props.getProperty("search_r");
search_t = props.getProperty("search_t");
init_lon = props.getProperty("init_lon");
init_lat = props.getProperty("init_lat");
cellDensityThreshold = props.getProperty("cellDensityThreshold");
}
/*
* 函数名:queryRelatedCellsPCMD
* 参数:record_id,dml,connection
* 返回值:关联小区列表
* 功能:根据话单查询关联小区信息
* Author:yl
* Update date:2015/8/27
*/
public ArrayList<String> queryRelatedCellsPCMD(String record_id, mysql_DML dml, Connection conn) throws FileNotFoundException, IOException, ClassNotFoundException, SQLException, ParseException
{
ArrayList<String> cell_list = new ArrayList<String>();//关联小区结果列表
// String sql = "select * from related_calls where record_id = " + Integer.parseInt(record_id) +
// " and call_event_code = " + 30 + " ORDER BY call_date DESC, call_time DESC";
String sql = "select * from related_calls where record_id = " + Integer.parseInt(record_id) +
" ORDER BY call_date DESC, call_time DESC limit 0,20";
ArrayList<String> list = dml.selectMysql(sql, conn);
if (list.isEmpty()) {
logger.info("在related_calls中查询结果为空");
return null;
}
// int i = 0;//counter
for (String s : list) {
int bts = Integer.parseInt(s.split("\t")[8]);
int cell = Integer.parseInt(s.split("\t")[9]);
int ecp = Integer.parseInt(s.split("\t")[7]);
String distance = s.split("\t")[23];
String call_ecio = s.split("\t")[15];
if (ecp == 2) {
ecp = 9;
}
int end_bts = Integer.parseInt(s.split("\t")[21]);
int end_cell = Integer.parseInt(s.split("\t")[22]);
int end_ecp = Integer.parseInt(s.split("\t")[20]);
String end_distance = s.split("\t")[24];
String end_call_ecio = s.split("\t")[19];
if (end_ecp == 2) {
end_ecp = 9;
}
String sql1 = "select ecp, bts, cell, location from im_cell_info where bts = " + bts +
" and cell = " + cell + " and ecp = " + ecp;
logger.info("查询关联小区的语句: " + sql1);
ArrayList<String> listrelatedcells = dml.selectMysql(sql1, conn);
if (listrelatedcells.isEmpty()) {
logger.info("在im_cell_info中查询结果为空");
continue;
}
cell_list.add(listrelatedcells.get(0) + distance + "\t" + call_ecio);
String sql2 = "select ecp, bts, cell, location from im_cell_info where bts = " + end_bts +
" and cell = " + end_cell + " and ecp = " + end_ecp;
logger.info("查询关联小区的语句: " + sql2);
ArrayList<String> endrelatedcells = dml.selectMysql(sql1, conn);
if (endrelatedcells.isEmpty()) {
logger.info("在im_cell_info中查询结果为空");
continue;
}
cell_list.add(endrelatedcells.get(0) + end_distance + "\t" + end_call_ecio);
System.out.println(endrelatedcells.get(0) + end_distance + "\t" + end_call_ecio);
}//for
//去重
HashSet<String> set = new HashSet<String>();
for (String string : cell_list) {
set.add(string);
}
ArrayList<String> list2 = new ArrayList<String>();
for (String string : set) {
list2.add(string);
}
cell_list=list2;
return cell_list;
}
/*
* 函数名:insertRelatedCellsRs
* 参数:record_id,dml,connection
* 返回值:无
* 功能:将结果插入数据库
* Author:yl
* Update date:2015/8/27
*/
public String insertRelatedCellsRsPCMD(String record_id, mysql_DML dml, Connection conn, ArrayList<String> cellInfo)
throws FileNotFoundException, IOException, ClassNotFoundException, SQLException, ParseException
{
logger.info("\n调用insertRelatedCellsRs函数");
if (cellInfo == null) {
logger.info("在im_cell_info中查询结果为空");
return "error";
}
int totalcells = cellInfo.size();//关联基站数目
int id = Integer.parseInt(record_id);
int query_type = 3;//表示按照第3种查询条件找到的
double query_radius = 0;//搜索半径,在话单查询条件下为0
double distance = 0;
double ecio = 0;
int linkcount = 1;
String insert_related_cells = "insert into related_cells (record_id, query_type, query_radius, ecp, bts, cell, location, " +
"distance,avg_ecio,linkCount ) VALUES";
int count = 0;
for(String s : cellInfo){
int ecp = Integer.parseInt(s.split("\t")[0]);
int bts = Integer.parseInt(s.split("\t")[1]);
int cell = Integer.parseInt(s.split("\t")[2]);
String location = s.split("\t")[3];
distance = Double.parseDouble(s.split("\t")[4]);
ecio = Double.parseDouble(s.split("\t")[5]);
insert_related_cells += "(" + id + "," + query_type + "," + query_radius + "," + ecp + "," + bts + "," + cell + ",'"
+ location + "'," + distance + "," + ecio + "," + linkcount + "),";
count ++;
}
if(count > 0){
logger.info("插入数据的语句: " + insert_related_cells.substring(0, insert_related_cells.length() - 1));
String flag = dml.insertdata(insert_related_cells.substring(0, insert_related_cells.length() - 1), conn);
if (flag.isEmpty()) {
logger.info("\nError!插入失败。");
}else {
logger.info("\nSuccess!插入成功。");
}
}
return "success";
}
/***************************************************1111*********************************************************
* 根据投诉ID,查找pre_deal_records表获得经纬度,再搜索一定范围内,获得相关联基站的经纬度,结果保存在map中(键==“经度,纬度”,值==“1”或“2”)
* @throws IOException
* @throws SQLException
* @throws ClassNotFoundException
* @throws FileNotFoundException
* @throws NumberFormatException
*/
public HashMap<String,String> findRelatedCellsByLonLat(String record_id, mysql_DML dml, Connection conn)
throws NumberFormatException, FileNotFoundException, ClassNotFoundException, SQLException, IOException {
logger.info("进入findRelatedCellsByLonLat函数...");
initParam(path);
String sql = "select call_lon,call_lat from pre_deal_records where record_id = " + record_id;
logger.info("根据投诉ID"+record_id+"找pre_deal_records表");
ArrayList<String> result_list = dml.selectMysql(sql, conn);//用result_list存根据投诉单号在pre_deal_records中查询出的结果
if(result_list.isEmpty()){
logger.info("error:从pre_deal_records表中查询无结果!退出!" );
return null; //退出
}
String data = result_list.get(0);
logger.info("从pre_deal_records中找到该条记录="+data);
//调用查找基站函数查找关联小区。关联小区cellMap的键值对:键==“经度,纬度”,值==“1”或“2”
Find_Cell findCell = new Find_Cell();
HashMap<String,String> cellMap = findCell.cell_info(Double.parseDouble(data.split("\t")[0]),Double.parseDouble(data.split("\t")[1]),
Double.parseDouble(search_r)); //fc.cell_info(经度,纬度,搜索半径)
if(cellMap.size() == 0){//找不到周边关联小区
logger.info("根据地理经纬度信息找到0个关联基站!此处应转向话单查询...退出方法" );
setCell_rsCode(40);
setCell_rsColorCode(10);
setCell_rsColorType("white");
return null;
}
logger.info("根据投诉ID"+record_id+"从经纬度信息上找到"+cellMap.size()+"个关联基站的经纬度信息="+cellMap);
logger.info("退出 findRelatedCellsByLonLat函数");
return cellMap;
}
/********************************************************************************************************
* 把找到的关联小区/基站插入到数据库
根据关联基站的经纬度查询im_cell_info,并将结果存到数据库related_cells中
* @throws IOException
* @throws FileNotFoundException
* @throws SQLException
* @throws ClassNotFoundException
*/
public boolean insertRelatedCellsByLonLat(String record_id, HashMap<String,String> cellMap, mysql_DML dml, Connection conn)
throws FileNotFoundException, IOException, ClassNotFoundException, SQLException{
logger.info("进入insertRelatedCells函数...");
initParam(path);
String sql = "select * from pre_deal_records where record_id = " + Integer.parseInt(record_id);
ArrayList<String> result_list = dml.selectMysql(sql, conn);//用result_list存根据投诉单号在pre_deal_records中查询出的结果
if (result_list == null) {
dml.updatedata("update pre_judge_label set geogCell=101 where record_id = " + Integer.parseInt(record_id));
logger.info("error:根据投诉单号="+record_id+"在pre_deal_records中查询无结果");
return false;
}
String data = result_list.get(0);//取出该条投诉记录(一整行)
//根据关联基站的经纬度查询im_cell_info,并将结果存到数据库related_cells中
if (cellMap == null || cellMap.isEmpty()) {
dml.updatedata("update pre_judge_label set geogCell=101 where record_id = " + Integer.parseInt(record_id));
logger.info("error:关联小区列表cellMap="+cellMap+"为空!无地理关联基站!");
return false;
}
//关联小区cellMap的键值对:键==“经度,纬度”,值==“1”或“2”
logger.info("刚传进函数的关联小区原始集合有"+cellMap.size()+"个cellMap="+cellMap);
//---------------------------------------------筛选出覆盖方向匹配的小区-------------------------------------------------------
//cellMap里面包含所有的备选小区,筛选出覆盖方向匹配的小区
//计算备选小区i到投诉地点的方位角βi,小区天线方位角αi与βi之差绝度值δi小于60度,即认定该小区覆盖方向匹配
double[] clientLonLat = {Double.parseDouble(data.split("\t")[3]), Double.parseDouble(data.split("\t")[4])}; //客户投诉地点的经纬度
Map<String,String> matchCellMap = new TreeMap<String, String>();
Set<String> it = cellMap.keySet();//关联小区cellMap的键值对:键==“经度,纬度”,值==“1”或“2”
for(String s:it){ //根据投诉经纬度和范围找到 关联基站的经纬度,然后用该基站经纬度获取详细基站信息插入related_cells表
String lon = s.split(",")[0];
String lat = s.split(",")[1];
double[] BSLonLat = {Double.parseDouble(lon), Double.parseDouble(lat)}; //基站的经纬度
double azimuthClient = getAzimuth(BSLonLat, clientLonLat); //获取该小区和客户的方位角
if (azimuthClient == -1) {
logger.info("error:获取该小区与投诉地点的方位角出错!退出此次循环,继续进行下一次!");
continue;
}
String cell_sql = "select dir_angle,ecp,bts,cell,location from im_cell_info where gps_lon=" + lon + " and gps_lat=" + lat;
logger.info("根据关联基站的经纬度查基站方位角的sql语句="+cell_sql);
ArrayList<String> relatedCells = dml.selectMysql(cell_sql, conn);
if (relatedCells == null || relatedCells.isEmpty()) {
logger.info("gps_lon=" + lon + ",gps_lat=" + lat+"在im_cell_info中查询无基站信息");
continue;
}
logger.info("gps_lon=" + lon + ",gps_lat=" + lat+"在im_cell_info中查询结果="+relatedCells);
for (int i = 0; i < relatedCells.size(); i++) { //遍历三个小区的方位角
String[] azimuthArray = relatedCells.get(i).split("\t");//数组里面依次存:方位角,ecp,bts,cell,location
double azimuthCell = Double.parseDouble(azimuthArray[0]);//取出小区的方位角
double coverAngle = Math.abs(azimuthClient - azimuthCell); //求出两个方位角的的差的绝对值,即覆盖夹角
logger.info("对小区ecp="+azimuthArray[1]+",bts="+azimuthArray[2]+",cell="+azimuthArray[3]+"方位角信息:azimuthClient=" + azimuthClient + ",azimuthCell=" + azimuthCell+",coverAngle="+coverAngle);
if (coverAngle < 90) { //允许覆盖方向匹配的小区有重叠
//算出投诉地点和该基站的距离
double dis = Math.sqrt((Double.parseDouble(data.split("\t")[3])-BSLonLat[0])*(Double.parseDouble(data.split("\t")[3])-BSLonLat[0])*111500*0.8605*111500*0.8605
+ (Double.parseDouble(data.split("\t")[4])-BSLonLat[1])*(Double.parseDouble(data.split("\t")[4])-BSLonLat[1])*111500*111500 );
dis = (int)dis; //dis取整数
logger.info("找到一个覆盖夹角匹配小区,距离dis="+dis);
//关联小区matchCellMap的键值对:键==“经度,纬度,投诉地点方位角,覆盖夹角,ecp,bts,cell,位置”,值==“距离”
matchCellMap.put(lon+","+lat+","+azimuthClient+","+coverAngle+","+azimuthArray[1]+","+azimuthArray[2]+","+azimuthArray[3]+","+azimuthArray[4], dis+"");
}
}//end of for
}//end of for
logger.info("第一步,筛选出来的覆盖夹角匹配小区集合"+matchCellMap.size()+"个matchCellMap="+matchCellMap);
double firstDisLabel = 0; //用于判断地理关联小区标签,地理最近的关联小区的最小距离。只取第一个值。
boolean isLabel = true; //控制只取第一个距离。
if (matchCellMap != null && !matchCellMap.isEmpty()) {
//-------------------------------------------根据距离由小到大进行排序-----------------------------------------------------
//matchCellMap得到的小区都是匹配覆盖夹角的小区,接下来根据距离由小到大进行排序
Map<String, String> sortedMap = new LinkedHashMap<String, String>();
sortedMap = sortMapByValue(matchCellMap);
logger.info("第二步,匹配小区按距离排序结果有"+sortedMap.size()+"个小区sortedMap="+sortedMap);
//-------------------------------取出符合要求的小区:最近一个覆盖方向匹配的小区+搜索半径内前4个覆盖方向匹配的小区<=5-----------------------------
//关联小区matchCellMap的键值对:键==“经度,纬度,投诉地点方位角,覆盖夹角,ecp,bts,cell,位置”,值==“距离”
HashMap<String,String> chosenMap = new LinkedHashMap<String, String>();
Set<String> kSetsorted = sortedMap.keySet();
int sortedMapLenght = sortedMap.size();
if (sortedMapLenght <= 5) {
for (String key : kSetsorted) {
chosenMap.put(key, sortedMap.get(key));
}
}else {
Iterator<String> iterator = kSetsorted.iterator();
String key = "";
int count = 0;
for (int i = 0; i < 5; i++) { //控制只选择前5个
if (count > 4) { //count统计除了第一个外的小区,大于4(0.1.2.3.4)说明已经添加5个,要退出
break;
}
key = iterator.next();
double d = Double.parseDouble(sortedMap.get(key));
if (d <= Double.parseDouble(this.search_r) ) {
chosenMap.put(key, sortedMap.get(key));
count++;
}
}//end of for
}
logger.info("第三步,按条件筛选得到小区个数="+chosenMap.size()+",这些小区集合chosenMap="+chosenMap);
//-----------------------------------把关联基站信息插入related_cells表--------------------------------------------------
//关联小区matchCellMap的键值对:键==“经度,纬度,投诉地点方位角,覆盖夹角,ecp,bts,cell,位置”,值==“距离”
Set<String> ite_chosen = chosenMap.keySet();
int count = 0; //标示是否有内容需要入库
String insert_sql = "INSERT into related_cells(record_id,query_type,query_radius,ecp,bts,cell,location,distance,azimuthClient,coverAngle) VALUES";
for(String s:ite_chosen){ //根据投诉经纬度和范围找到 关联基站的经纬度,然后用该基站经纬度获取详细基站信息插入related_cells表
String[] cellArray = s.split(",");
String lon = cellArray[0];
String lat = cellArray[1];
String query_type = cellMap.get(lon+","+lat);//范围内1,范围外2
double dis = Double.parseDouble(chosenMap.get(s));//投诉地点到小区的距离
if (isLabel) { //用于判断地理关联小区标签,地理最近的关联小区的最小距离。只取第一个值。
firstDisLabel = dis;
isLabel = false;
}
String sql_value = "("+Integer.parseInt(record_id)+","+Integer.parseInt(query_type)+","+Double.parseDouble(search_r)+","
+ Integer.parseInt(cellArray[4])+","+Integer.parseInt(cellArray[5])+","+Integer.parseInt(cellArray[6])+",'"
+cellArray[7]+"',"+dis+","+Double.parseDouble(cellArray[2])+","+Double.parseDouble(cellArray[3])+"),";
insert_sql += sql_value;
logger.info("用基站经纬度获取详细基站信息插入related_cells表 循环次数: "+(count++));
}//for结束所有基站循环
//去掉末尾逗号,一次性插入所有信息
insert_sql = insert_sql.substring(0, insert_sql.length() - 1);
logger.info("插入related_cells的语句=" + insert_sql);
if (count > 0) {
String valuse = dml.insertdata(insert_sql, conn);
if (valuse.length() > 0){
logger.info("success:成功插入关联小区信息到related_cells表!");
}else {
logger.info("error:插入关联小区信息到related_cells表失败!");
}
}else {
logger.info("没有关联小区信息可入库!");
}
}//end of if (matchCellMap != null && !matchCellMap.isEmpty())
//-------------------------------------更新数据库字段------------------------------------------------------------------
int cellNum = cellMap.size()*3; //统计找到的小区数目,使用刚刚进入函数的原始集合cellMap(存基站的经纬度,map大小就是基站的数量),小区是基站数的3倍
logger.info("cellNum="+cellNum);
//--------------------------------更新pre_judge_label里面的geogCell字段---------------------------------------------
int geogCellLabel = 101;//地理关联小区标签poor=102,rich=101,无经纬度=101
if (cellNum <= 1 || firstDisLabel > Double.parseDouble(search_r)) {
geogCellLabel = 102;//poor
}else {
geogCellLabel = 101;//rich
}
//更新pre_judge_label里面的geogCell和alarms字段
boolean flagLabel = dml.updatedata("update pre_judge_label set geogCell="+geogCellLabel+" where record_id = " + Integer.parseInt(record_id));
if (flagLabel) {
logger.info("succeess:成功更新pre_judge_label里面的geogCell!");
}else {
logger.info("error:更新pre_judge_label里面的geogCell失败!");
}
//---------------更新pre_deal_records里面的cell_rsnum和cell_rscode字段---------------
logger.info("找到关联小区总数目cell_rsnum="+cellNum ); //找到的关联小区数目
setAllCellRSCode(cellNum,Integer.parseInt(record_id), dml, conn);//对此投诉单号找到的关联小区结果进行编码
String sql1 = "update pre_deal_records set cell_rsnum=" + cellNum+",cell_rscode=" + getCell_rsCode()
+" where record_id=" + Integer.parseInt(record_id);
logger.info("更新pre_deal_records里面的cell_rsnum和cell_rscode字段sql1="+sql1 );
boolean flag = dml.updatedata(sql1);
if (flag) {
logger.info("succeess:成功更新pre_deal_records里面的cell_rsnum和cell_rscode");
}else {
logger.info("error:更新pre_deal_records里面的cell_rsnum和cell_rscode字段失败!");
}
//-----------------------更新pre_deal_results的cell_colorcode字段-----------------
String sql2 = "update pre_deal_results SET cell_colorcode = "+ getCell_rsColorCode() + " where record_id = " +
Integer.parseInt(record_id);
boolean fString = dml.updatedata(sql2);
if (fString) {
logger.info("succeess:成功更新pre_deal_results的cell_colorcode字段!");
}else {
logger.info("error:更新pre_deal_results的cell_colorcode字段失败!");
}
logger.info("退出 insertRelatedCells函数\n");
return true;
}
/******************************************************************************************
* 根据找到的小区数量cell_rsnum,进行编码,得到对应的cell_rscode,用于最后的点灯处理
* 类型 rscode meaning colorcode
* CELL 10 搜索范围内无小区,最近小区距离>=2km 50(red)
CELL 20 搜索范围内小区数量=<3 OR 搜索范围外最近小区距离< 2km 40(yellow)
CELL 30 搜索范围内小区数量>3 20(green)
CELL 40 无投诉地址/经纬度 10(white)
* @throws IOException
* @throws SQLException
* @throws FileNotFoundException
* @throws ClassNotFoundException
*/
private void setAllCellRSCode(int num,int record_id, mysql_DML dml, Connection conn)
throws ClassNotFoundException, FileNotFoundException, SQLException, IOException {
String cell_sql = "select query_type,distance from related_cells where record_id=" + record_id+" and query_type<>3";//根据投诉单号找基站结果表
ArrayList<String> list = dml.selectMysql(cell_sql, conn);
logger.info("setAllCellRSCode:基站结果表 list = "+ list);
if (list.isEmpty()) {
logger.info("error:投诉单号="+record_id+"在related_cells中查询无结果");
return;
}
int cell_rsnum2 = num;
int queryType = Integer.parseInt(list.get(0).split("\t")[0]);
double dis = Double.parseDouble(list.get(0).split("\t")[1]);
logger.info("关联小区密度阈值="+ cellDensityThreshold+"个");
if (queryType == 1 && cell_rsnum2 > Integer.parseInt(cellDensityThreshold)) {
setCell_rsCode(30);
setCell_rsColorCode(20);
setCell_rsColorType("green");
}else if(queryType == 1 && 1 <= cell_rsnum2 && cell_rsnum2 <= Integer.parseInt(cellDensityThreshold)){
setCell_rsCode(20);
setCell_rsColorCode(40);
setCell_rsColorType("yellow");
}else if (queryType == 2) { //从related_cells只获得一条记录
if (dis < 2 * Integer.parseInt(search_r)) {
setCell_rsCode(20);
setCell_rsColorCode(40);
setCell_rsColorType("yellow");
}else { //dis >= 2 * Integer.parseInt(search_r)
setCell_rsCode(10);
setCell_rsColorCode(50);
setCell_rsColorType("red");
}
}else { //cell_rsnum2 == 0,即该投诉单号无关联基站
setCell_rsCode(40);
setCell_rsColorCode(10);
setCell_rsColorType("white");
}
}
/**********************************************************************************************
* 方法名:getAzimuth
* 传入参数:基站的经、纬度double类型数组,投诉地点的经、纬度double类型数组
* 返回值:投诉地点相对于基站的方位角,double类型
* 说明:求方位角,返回值为-1则是异常情况
* Author:JayLi
**********************************************************************************************/
private double getAzimuth(double[] BSLonLat, double[] clientLonLat) {
logger.info("进入求方位角函数...");
if (BSLonLat.length != 2) {
logger.info("error:求方位角时输入的基站经纬度有误!请重新输入!退出方法!");
return -1;
}
if (clientLonLat.length != 2) {
logger.info("error:求方位角时输入的投诉地点经纬度有误!请重新输入!退出方法!");
return -1;
}
double azimuth = 0.0; //方位角
double BSLon = BSLonLat[0];
double BSlat = BSLonLat[1];
double clientLon = clientLonLat[0];
double clientLat = clientLonLat[1];
//检测输入的经纬度是否在湖北省内或省边界附近,不在就报错退出
if (!(108.29209227 <= BSLon && BSLon <= 116.37915993)) {
logger.info("error:输入基站的“经度”不在湖北省境内!退出方法!");
return -1;
}
if (!(28.92430194 <= BSlat && BSlat <= 33.43608273)) {
logger.info("error:输入基站的“纬度 ”不在湖北省境内!退出方法!");
return -1;
}
if (!(108.29209227 <= clientLon && clientLon <= 116.37915993)) {
logger.info("error:输入投诉地点的“经度”不在湖北省境内!退出方法!");
return -1;
}
if (!(28.92430194 <= clientLat && clientLat <= 33.43608273)) {
logger.info("error:输入投诉地点的“纬度 ”不在湖北省境内!退出方法!");
return -1;
}
//以基站经纬度为原点建立坐标,纵轴指向正北方向,横轴指向正东方向。先不讨论投诉地点在哪个象限,先求得到基站-用户连线和正北方向(纵轴)的夹角,然后再讨论所在象限即可得到最终方位角。
if (BSlat == clientLat) { //纬度相同,求正切值时会分母为0,无意义,故需要分类讨论
if (clientLon > BSLon) { //投诉地点在横轴正半轴情况
azimuth = 90;
}
if (clientLon < BSLon) { //投诉地点在横轴负半轴情况
azimuth = 270;
}
if (clientLon == BSLon) { //投诉地点就在基站底下,两者经纬度相同。设为0。
azimuth = 0;
}
}else{ //纬度不相同,求正切值时会分母不会为0
//先求得到基站-用户连线和正北方向(纵轴)的夹角,默认是在第1区域
azimuth = Math.atan2(Math.abs(BSLon-clientLon) * 111500 * 0.8605, Math.abs(BSlat-clientLat) * 111500);
azimuth = Math.toDegrees(azimuth); //将弧度 转为 度数
azimuth = Double.parseDouble(String.format("%.2f", azimuth)); //保留两位小数
//根据方位角定义,按照纵正半轴即正北方向起,顺时针转,把坐标平面分为4个区域,依次为1,2,3,4区域
if (clientLon > BSLon && clientLat > BSlat) { //投诉地点在第1区域(第一象限)
//azimuth = azimuth;
}else if (clientLon >= BSLon && clientLat < BSlat) { //投诉地点在第2区域(第四象限),包含在纵轴负半轴情况
azimuth = 180 - azimuth;
}
else if (clientLon < BSLon && clientLat < BSlat) { //投诉地点在第3区域(第三象限)
azimuth = 180 + azimuth;
}else if (clientLon <= BSLon && clientLat > BSlat) { //投诉地点在第4区域(第二象限),包含在纵轴正半轴情况
azimuth = 360 - azimuth;
}else { //不在以上其他区域,程序异常
logger.info("error:程序异常!退出方法!");
return -1; //报错,退出
}
}
logger.info("方位角="+azimuth);
return azimuth;
}
/************************************************************************
* 函数名:sortMapByValue
* 传入参数:键和值是字符串类型的集合,Map<String, String> oriMap
* 返回值:键和值是字符串类型的集合,Map<String, String> sortedMap
* 说明:使用 Map按value进行由小到大排序
* Author:JayLi
* @return
******************************************************************/
private Map<String, String> sortMapByValue(Map<String, String> oriMap) {
Map<String, String> sortedMap = new LinkedHashMap<String, String>();
if (oriMap == null || oriMap.isEmpty()) {
return null;
}
List<Map.Entry<String, String>> entryList = new ArrayList<Map.Entry<String, String>>(oriMap.entrySet());
Collections.sort(entryList, new Comparator<Map.Entry<String, String>>() {
public int compare(Map.Entry<String, String> entry1,Map.Entry<String, String> entry2) {
return (int) (Double.parseDouble(entry1.getValue())-Double.parseDouble(entry2.getValue()));
}
}); //一个内部类,重写比较方法
//排完序后,按照新的顺序写入map
Iterator<Map.Entry<String, String>> iter = entryList.iterator();
Map.Entry<String, String> tmpEntry = null;
while (iter.hasNext()) {
tmpEntry = iter.next();
sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
}
return sortedMap;
}
// url:xxx/cell_info_type3,
// type: "GET",
// data: {"complaint_item_id" : "1011"}
//
// response:[{trouble_time:XXX,
// duration:XXX,},
// {type: 1,
// ECP: 13,
// BTS:1014,
// CELL:1,
// cell_name:"土产仓库",
// distance: 815,
// linkCount:30,
// average_ecio:-7.5}]
//
@RequestMapping(value = "/cell_info_type3",method = RequestMethod.GET)
@ResponseBody
public String cell_info_type3(HttpServletRequest request,HttpServletResponse response)
throws IOException, ParseException, ClassNotFoundException, SQLException
{
logger.info("调用cell_info函数");
//取配置文件
initParam(path);
String record_id =URLDecoder.decode(request.getParameter("complaint_item_id"),"UTF-8");
mysql_DML dml = new mysql_DML();
Connection conn = dml.myConnection();
//--------------------输出Json格式数据给前台-------------------------
JSONArray jsons = new JSONArray();
JSONObject jsonObject = new JSONObject();
JSONObject jsonObjSearchCondition = new JSONObject();
//-----------------返回查找关联小区的条件:问题发生的经纬度和搜索半径,以及最终结果点灯颜色------------
String sql1 = "select call_time, search_time_range from pre_deal_records where record_id = " + Integer.parseInt(record_id);
logger.info("根据投诉ID"+Integer.parseInt(record_id)+"找pre_deal_records表sql="+sql1);
ArrayList<String> result_list = dml.selectMysql(sql1, conn);//用result_list存根据投诉单号在pre_deal_records中查询出的结果
String[] data = result_list.get(0).split("\t");
String sql2 = "select cell_colorcode from pre_deal_results where record_id = " + Integer.parseInt(record_id);
int cell_densitycode = 0;
String cell_density = "";
ArrayList<String> codeList = dml.selectMysql(sql2, conn);
if (codeList.isEmpty()) {
cell_densitycode = 10;
}
cell_densitycode = Integer.parseInt(codeList.get(0).split("\t")[0]);
switch (cell_densitycode) {
case 10:
cell_density = Color.$10;
break;
case 20:
cell_density = Color.$20;
break;
case 30:
cell_density = Color.$30;
break;
case 40:
cell_density = Color.$40;
break;
default:
cell_density = Color.$50;
break;
}
String occur_time = data[0];
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sd1 = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
SimpleDateFormat sd2= new SimpleDateFormat("yyyy-MM-dd HH:59:59");
long time_stamp = sd.parse(occur_time).getTime()/1000 - (Long.parseLong(search_t) / 3600 - 1) * 3600;//问题发生时间的前N-1小时的时间戳
long time_stamp1 = sd.parse(occur_time).getTime()/1000;
Date time =new Date(time_stamp * 1000);
Date time1 =new Date(time_stamp1 * 1000);
String time_before = sd1.format(time);
String time_after = sd2.format(time1);
// System.out.println("time_before:" + time_before + " &&&&&&&&&&&&&&&& " + "time_after" + time_after );
jsonObjSearchCondition.put("trouble_occur_time", time_before);
jsonObjSearchCondition.put("trouble_end_time", time_after);
jsons.add(jsonObjSearchCondition);
//----------------------------返回关联小区列表-------------------------------------
String sqlType3 = "SELECT record_id, query_type, query_radius, ecp, bts, cell, location,AVG(distance ),SUM(linkCount),AVG(avg_ecio) FROM " +
"related_cells WHERE record_id="+Integer.parseInt(record_id) + " and query_type=3 GROUP BY bts ORDER BY AVG(distance) ";
logger.info("查找是否有类型3关联小区sql语句=" + sqlType3);
ArrayList<String> listType3 = dml.selectMysql(sqlType3, conn);//listType3用来保存根据投诉单号查询到的关联基站列表
String sql = "";
int size_type3 = 0;
DecimalFormat df = new DecimalFormat("0");
DecimalFormat df1 = new DecimalFormat("0.0");
//返回话单关联小区信息
if (!listType3.isEmpty()) { //有类型3基站
logger.info("找到投诉ID" + Integer.parseInt(record_id)+"类型3关联小区="+listType3);
for(String s : listType3){
String[] cellType3 = s.split("\t");
jsonObject.put("type", cellType3[1]);
jsonObject.put("ECP", cellType3[3]);
jsonObject.put("BTS", cellType3[4]);
jsonObject.put("CELL", cellType3[5]);
jsonObject.put("cell_name", cellType3[6]);
jsonObject.put("distance", df.format(Double.parseDouble(cellType3[7])));
jsonObject.put("linkCount", cellType3[8]);
jsonObject.put("average_ecio", df1.format(Double.parseDouble(cellType3[9])));
jsons.add(jsonObject); //类型3基站保存在Json数组第一位
}
}
logger.info("返回的关联小区信息的Json数据格式=" + jsons.toString());
logger.info("退出cell_info函数");
conn.close();
return jsons.toString();
}
//********************地理关联小区***********************************
@RequestMapping(value = "/cell_info",method = RequestMethod.GET)
@ResponseBody
public String cell_info(HttpServletRequest request,HttpServletResponse response)
throws IOException, ParseException, ClassNotFoundException, SQLException
{
logger.info("调用cell_info函数");
//取配置文件
initParam(path);
String record_id =URLDecoder.decode(request.getParameter("complaint_item_id"),"UTF-8");
mysql_DML dml = new mysql_DML();
Connection conn = dml.myConnection();
//--------------------输出Json格式数据给前台-------------------------
JSONArray jsons = new JSONArray();
JSONObject jsonObject = new JSONObject();
JSONObject jsonObjSearchCondition = new JSONObject();
//-----------------返回查找关联小区的条件:问题发生的经纬度和搜索半径,以及最终结果点灯颜色------------
String sql1 = "select phone,call_lon,call_lat,cell_rsnum from pre_deal_records where record_id = " + Integer.parseInt(record_id);
logger.info("根据投诉ID"+Integer.parseInt(record_id)+"找pre_deal_records表sql="+sql1);
ArrayList<String> result_list = dml.selectMysql(sql1, conn);//用result_list存根据投诉单号在pre_deal_records中查询出的结果
String[] data = result_list.get(0).split("\t");
setAllCellRSCode(Integer.parseInt(data[3]),Integer.parseInt(record_id), dml, conn);
String sql2 = "select cell_colorcode from pre_deal_results where record_id = " + Integer.parseInt(record_id);
int cell_densitycode = 0;
String cell_density = "";
ArrayList<String> codeList = dml.selectMysql(sql2, conn);
if (codeList.isEmpty()) {
cell_densitycode = 10;
}
cell_densitycode = Integer.parseInt(codeList.get(0).split("\t")[0]);
switch (cell_densitycode) {
case 10:
cell_density = Color.$10;
break;
case 20:
cell_density = Color.$20;
break;
case 30:
cell_density = Color.$30;
break;
case 40:
cell_density = Color.$40;
break;
default:
cell_density = Color.$50;
break;
}
jsonObjSearchCondition.put("longitude", data[1]);
jsonObjSearchCondition.put("latitude", data[2]);
jsonObjSearchCondition.put("radius", search_r);
jsonObjSearchCondition.put("phone", data[0]);
jsonObjSearchCondition.put("cell_density", cell_density);
jsons.add(jsonObjSearchCondition);
//----------------------------返回关联小区列表-------------------------------------
String sql = "";
DecimalFormat df = new DecimalFormat("0");
DecimalFormat df1 = new DecimalFormat("0.0");
sql = "select query_type,ecp,bts,cell,location,distance,azimuthClient,coverAngle from related_cells where record_id = " + Integer.parseInt(record_id)
+ " and (query_type=1 or query_type=2) order by distance asc, coverAngle asc, cell asc";
logger.info("关联小区定位查询语句=" + sql);
ArrayList<String> geoglist = dml.selectMysql(sql, conn);//list用来保存根据投诉单号查询到的关联基站列表
if(geoglist.isEmpty()){
logger.info("在related_cells中找不到此投诉单号的记录!");
return jsons.toString();
}
//返回地理关联小区信息
for(String s : geoglist){
jsonObject.put("type", s.split("\t")[0]);
jsonObject.put("ECP", s.split("\t")[1]);
jsonObject.put("BTS", s.split("\t")[2]);
jsonObject.put("CELL", s.split("\t")[3]);
jsonObject.put("cell_name", s.split("\t")[4]);
jsonObject.put("distance", df.format(Double.parseDouble(s.split("\t")[5])));
jsonObject.put("azimuth", s.split("\t")[6]);
jsonObject.put("coverAngle", s.split("\t")[7]);
jsons.add(jsonObject);
}
logger.info("返回的关联小区信息的Json数据格式=" + jsons.toString());
logger.info("退出cell_info函数");
conn.close();
return jsons.toString();
}
}<file_sep>define([
'backbone'
], function(Backbone) {
"use strict";
var ComplaintStatisticData = Backbone.Model.extend({
initialize: function(options){
this.urlRoot = 'complaint_statistic_data.html';
this.url = this.urlRoot;
}
});
return ComplaintStatisticData;
});<file_sep>package com.pcmd.query;
/*
Describe:
2015-8-29
Gets_HBase.java
author:GOC
*/
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.log4j.Logger;
import com.hbase.conn.HBaseConf;
public class Gets_HBase {
private static Logger logger = Logger.getLogger(Gets_HBase.class);
public static void main(String[] args)
throws FileNotFoundException, ClassNotFoundException, SQLException, IOException {
//Thu Oct 15 02:00:16 CST 2015 (2015-10-15 02:00:16)
// pcmd_query("18186648844",1444845616,1444845618);
// pcmd_query("18186648844", 1508004016L, 1508004018L);
//Thu Oct 15 02:00:14 CST 2015 (2015-10-15 02:00:14)
pcmd_query("13397184818",1444845614,1444849616);
}
// 这个类用来展示查询结果,包含PCMD话单查询,基站信息查询,栅格信息查询等三种查询
// 1.进行pcmd话单查询并显示
public static List<Date> findDates(Date dBegin, Date dEnd) {
List<Date> lDate = new ArrayList<Date>();
lDate.add(dBegin);
Calendar calBegin = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
calBegin.setTime(dBegin);
Calendar calEnd = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
calEnd.setTime(dEnd);
// 测试此日期是否在指定日期之后
while (dEnd.after(calBegin.getTime())) {
// 根据日历的规则,为给定的日历字段添加或减去指定的时间量
calBegin.add(Calendar.DAY_OF_MONTH, 1);
lDate.add(calBegin.getTime());
}
return lDate;
}
public static ArrayList<Map<String, String>[]> pcmd_query(String phone, long start_time, long end_time)
throws ClassNotFoundException, FileNotFoundException, SQLException, IOException {
// 使用 phone 生成电话号码,使用时间来生成date日期,这里的时间为unix时间
// SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd" );
HBaseConf hbaseConn = new HBaseConf();
Configuration conf = hbaseConn.getConfiguration();
HTable table = new HTable(conf, "pcmd"); // 在传输局机房的参数,部署过去要改回来(1/3)
Date start_date = new Date(start_time * 1000);
Date end_date = new Date(end_time * 1000);
logger.info("调试_1:"+start_date+" "+end_date);
List<Date> lDate = findDates(start_date, end_date);
logger.info("调试_2:"+lDate);
SimpleDateFormat df = new SimpleDateFormat("yyMMdd");
List<String> day = new ArrayList<String>();
for (Date date : lDate) {
day.add(df.format(date));
}
ArrayList<String> rowkey = new ArrayList<String>();
long flag = Long.parseLong(phone) % 9;// 保证第一位始终为0-8的数,加上反转的电话号码。
long key_phone = 99999999999l - Long.parseLong(phone);// 这样做到目的是控制长度为11位!
StringBuffer sb = new StringBuffer(key_phone + "");// 这个SB为电话号码
String fan_keyphone = sb.reverse().toString();// key_phone反转
// rowkey.add("001215495918150501");
for (String s : day) {
logger.info(flag + fan_keyphone + s);
rowkey.add(flag + fan_keyphone + s);
}
// -----------------------------生成rowkey 完成----------------------
// 使用get(list<Get>)进行数据读取操作
List<Get> gets = new ArrayList<Get>();
for (String key : rowkey) {
Get get = new Get(Bytes.toBytes(key));
get.addFamily(Bytes.toBytes("info"));
get.setMaxVersions();
get.setTimeRange(start_time * 1000, end_time * 1000);
gets.add(get);
}
logger.info("get前面");
Result[] res1 = table.get(gets);
logger.info("get后面");
ArrayList<Map<String, String>[]> map_list = new ArrayList<Map<String, String>[]>();
for (Result res : res1) {
Cell[] cells = res.rawCells();
if (cells.length < 1) {
continue;
}
logger.info("话单数量:" + cells.length / 29);
Map[] map = new Map[cells.length / 29];// 创建一个map数组,这个map数组里存放信息
for (int i = 0; i < map.length; i++) // 创建每一个User对象
{
HashMap<String, String> hm = new HashMap<String, String>();
for (int j = 0; j < cells.length; j++) {
if ((j - i) % map.length == 0) {
hm.put(Bytes.toString(CellUtil.cloneQualifier(cells[j])),
Bytes.toString(CellUtil.cloneValue(cells[j])));
}
}
map[i] = hm;
}
map_list.add(map);
for (Map abc : map) {
logger.info(abc);
}
}
table.close();
// logger.info(map_list.get(4)[0].get("callStartTime"));
return map_list;
}
}
/*
* 455115331818171015 column=info:E_dis, timestamp=1508004017000, value=0
455115331818171015 column=info:E_ecio, timestamp=1508004017000, value=0
455115331818171015 column=info:E_lat, timestamp=1508004017000, value=0
455115331818171015 column=info:E_lon, timestamp=1508004017000, value=0
455115331818171015 column=info:E_point, timestamp=1508004017000, value=0
455115331818171015 column=info:ID, timestamp=1508004017000, value=3197562187
455115331818171015 column=info:MessageL, timestamp=1508004017000, value=0
455115331818171015 column=info:S_dis, timestamp=1508004017000, value=64.68
455115331818171015 column=info:S_ecio, timestamp=1508004017000, value=-4.5
455115331818171015 column=info:S_lat, timestamp=1508004017000, value=30.013659383586866
455115331818171015 column=info:S_lon, timestamp=1508004017000, value=114.4547930333709
455115331818171015 column=info:S_point, timestamp=1508004017000, value=1.0
455115331818171015 column=info:calDurtime, timestamp=1508004017000, value=0
455115331818171015 column=info:callStartTime, timestamp=1508004017000, value=0
455115331818171015 column=info:comePhonetime, timestamp=1508004017000, value=0
455115331818171015 column=info:date, timestamp=1508004017000, value=1015
455115331818171015 column=info:endPhone, timestamp=1508004017000, value=0
455115331818171015 column=info:end_cell, timestamp=1508004017000, value=0,0,0
455115331818171015 column=info:end_dis, timestamp=1508004017000, value=0.0
455115331818171015 column=info:end_ecio, timestamp=1508004017000, value=-0.0
455115331818171015 column=info:event, timestamp=1508004017000, value=6,2,0,14,704
455115331818171015 column=info:load_time, timestamp=1508004017000, value=1483706764
455115331818171015 column=info:mainPhone, timestamp=1508004017000, value=18186648844
455115331818171015 column=info:startPhone, timestamp=1508004017000, value=0
455115331818171015 column=info:start_cell, timestamp=1508004017000, value=485,3,12
455115331818171015 column=info:start_dis, timestamp=1508004017000, value=64.68
455115331818171015 column=info:start_ecio, timestamp=1508004017000, value=-4.5
455115331818171015 column=info:starttime, timestamp=1508004017000, value=72177
455115331818171015 column=info:time, timestamp=1508004017000, value=1508004017000
* */
// {calDurtime=34380, callStartTime=844849, date=0430, time=1430407699,
// comePhonetime=0, event=33,2,1,1,1, S_lat=30.569665635651702,
// ID=2793431939, end_cell=1117,2,4, MessageL=0, startPhone=#777,
// starttime=844999, start_cell=1117,2,4, E_point=2.0,
// S_lon=114.21407458066876, E_ecio=-5.5, load_time=1440836706,
// E_lat=30.569665635651702, E_lon=114.21407458066876,
// S_dis=443.52, E_dis=443.52, mainPhone=18040548789, S_point=2.0, endPhone=0,
// S_ecio=-5.5}
<file_sep>define([
'underscore',
'backbone',
'marionette',
'bmap_draw_district',
'bmap_search_address',
'collection/map/b_district_info_collection',
"tpl!views/partials/components/com_t/bmap.tpl",
], function(_, Backbone, Marionette, DistrictOverlay, SearchAddress, BDistrictInfoCollection, bmapTpl) {
"use strict";
var BmapView = Backbone.Marionette.LayoutView.extend({
template: bmapTpl,
initialize: function(options){
},
onShow: function(){
var mapOptions = {
mapType: BMAP_NORMAL_MAP,
minZoom: 13,
maxZoom: 16,
enableMapClick:false
};
this.map = new BMap.Map("container", mapOptions); //设置卫星图为底图BMAP_PERSPECTIVE_MAP
var map = this.map;
var initPoint = new BMap.Point(114.4435, 30.5297); // 创建点坐标
this.initPoint = initPoint;
map.centerAndZoom(initPoint, 16); // 初始化地图,设置中心点坐标和地图级别。
map.enableScrollWheelZoom(); // 启用滚轮放大缩小。
map.enableKeyboard(); // 启用键盘操作。
// map.enableContinuousZoom(); //启用连续缩放效果
map.disableDoubleClickZoom(); //禁用双击放大效果
// ----- control -----
map.addControl(new BMap.NavigationControl()); //地图平移缩放控件
map.addControl(new BMap.ScaleControl()); //地图比例尺控件
//----- maker -----
// this.addCabinMarker(initPoint); //标定地图默认中心
// this.bindInfoWindow(); //绑定单击地图,触发显示点击点信息的窗口
// this.addGridLayer(); //采用添加图层的方式绘制网络覆盖栅格
this.drawGridListener(); //采用描点的方式绘制网络覆盖栅格
// this.drawStation();//绘制武汉市基站
this.searchAddress = new SearchAddress({map:map});
this.searchAddress.showPlaceSuggestion();//加入输入提示
//绘制武汉市县区级行政区划
var bDistrictCollection = new BDistrictInfoCollection();
var dataroot="assets/scripts/data/b_district_info.json";
// $.getJSON(dataroot, function(data){
// bDistrictCollection.set(data);
// var districtOverlay = new DistrictOverlay({map:map,collection:bDistrictCollection});//添加行政区划
// });
//绘制湖北省地市级行政区划
var aDistrictCollection = new BDistrictInfoCollection();
dataroot="assets/scripts/data/a_district_info.json";
$.getJSON(dataroot, function(data){
aDistrictCollection.set(data);
// var districtOverlay = new DistrictOverlay({map:map,collection:aDistrictCollection});//添加行政区划
});
},
//标定地图某点
addCabinMarker: function(point) {
var map = this.map;
var cabinIcon = new BMap.Icon("assets/css/bmap/images/cabin.png", new BMap.Size(32, 37));
var cabinMarkerOptions = {
icon: cabinIcon,
enableDragging: true,
draggingCursor: "move",
title: "地图默认中心"
};
var cabinMarker = new BMap.Marker(point, cabinMarkerOptions);
cabinMarker.setAnimation(BMAP_ANIMATION_DROP);
map.addOverlay(cabinMarker);
cabinMarker.addEventListener("dragend", function(e) {
console.log(e.point.lng+','+e.point.lat);
});
},
//标注基站
drawStation: function(){
var map = this.map;
var dataroot="assets/scripts/station.json";
$.getJSON(dataroot, function(data){
// console.log(data);
var points = []; // 添加海量点数据
for (var i = 0; i < data.length; i++) {
points.push(new BMap.Point(data[i].lng, data[i].lat));
}
var options = {
// size: BMAP_POINT_SIZE_SMALL,
// shape: BMAP_POINT_SHAPE_STAR,
color: '#d340c3'
};
var pointCollection = new BMap.PointCollection(points, options); // 初始化PointCollection
pointCollection.addEventListener('click', function (e) {
alert('单击点的坐标为:' + e.point.lng + ',' + e.point.lat); // 监听点击事件
});
map.addOverlay(pointCollection); // 添加Overlay
});
},
drawGridListener: function(){
var map = this.map;
var self = this;
map.addEventListener("zoomend",function(){
self.drawSignalGrid();
});
map.addEventListener("dragend", function() {
self.drawSignalGrid();
});
},
//采用描点的方式绘制网络覆盖栅格
drawSignalGrid: function(){
var map = this.map;
var zoom = 0.01;
//判断放大级别,设置zoom值
switch(map.getZoom()){
case 14:
zoom = 0.01;
break;
case 15:
zoom = 0.005;
break;
case 16:
zoom = 0.0025;
break;
default:
map.clearOverlays();
return null;
}
var center = map.getCenter();
//获取可视区域
var bs = map.getBounds(); //获取可视区域
this.bssw = bs.getSouthWest(); //可视区域左下角
this.bsne = bs.getNorthEast(); //可视区域右上角
this.bssw.lng = this.bssw.lng.toFixed(3);
this.bssw.lat = this.bssw.lat.toFixed(3);
this.bsne.lng = this.bsne.lng.toFixed(3);
this.bsne.lat = this.bsne.lat.toFixed(3);
console.log("当前地图可视范围是:" + this.bssw.lng + "," + this.bssw.lat + "到" + this.bsne.lng + "," + this.bsne.lat);
map.clearOverlays();
for (var x = this.bssw.lng-zoom; x < this.bsne.lng; x = x + zoom) {
for (var y = this.bssw.lat-zoom; y < this.bsne.lat; y = y + zoom) {
var rectangle = new BMap.Polygon([
new BMap.Point(x,y),
new BMap.Point(x+zoom,y),
new BMap.Point(x+zoom,y+zoom),
new BMap.Point(x,y+zoom)
], {strokeColor:"blue", strokeWeight:0.5, strokeStyle:"dashed", strokeOpacity:0.5, fillColor:"red" , fillOpacity:0.3}); //创建矩形
map.addOverlay(rectangle); //增加矩形
}
}
},
//采用添加图层的方式绘制网络覆盖栅格
addGridLayer: function(){
var map = this.map;
this.tileLayer = new BMap.TileLayer();
this.tileLayer.getTilesUrl = function(tileCoord, zoom) {
var x = tileCoord.x - 3108; //根据瓦片坐标和百度坐标得来
var y = tileCoord.y - 871;
var url = './assets/gridtile/' + zoom + '/tile' + x + '_' + y + '.png'; //根据当前坐标,选取合适的瓦片图
return url;
};
map.addTileLayer(this.tileLayer);
},
addGrid: function(){
this.addGridLayer();
console.log('addTileLayer');
},
deleteGrid: function(){
this.map.removeTileLayer(this.tileLayer);
console.log('deleteTileLayer');
},
addStation: function(){
this.drawStation();
console.log('addStation');
},
deleteStation: function(){
// this.map.removeTileLayer(this.tileLayer);
// console.log('deleteStation');
this.map.clearOverlays();
},
setLocation: function(){
var str = $('#searchText').val();
this.searchAddress.setLocation(str);
},
//绑定单击地图,触发显示点击点信息的窗口
bindInfoWindow: function(){
var map = this.map;
map.addEventListener('click', function(e){
var info = new BMap.InfoWindow('', {width: 260});
var projection = this.getMapType().getProjection();
var zoomLevel = map.getZoom();
var zoomStr = "地图级别:"+ zoomLevel;
var lngLat = e.point;
var lngLatStr = "<br />经纬度:" + lngLat.lng + ", " + lngLat.lat;
var worldCoordinate = projection.lngLatToPoint(lngLat);
var worldCoordStr = "<br />平面坐标:" + worldCoordinate.x + ", " + worldCoordinate.y;
var pixelCoordinate = new BMap.Pixel(Math.floor(worldCoordinate.x * Math.pow(2, this.getZoom() - 18)),
Math.floor(worldCoordinate.y * Math.pow(2, this.getZoom() - 18)));
var pixelCoordStr = "<br />像素坐标:" + pixelCoordinate.x + ", " + pixelCoordinate.y;
var tileCoordinate = new BMap.Pixel(Math.floor(pixelCoordinate.x / 256),
Math.floor(pixelCoordinate.y / 256));
var tileCoordStr = "<br />图块坐标:" + tileCoordinate.x + ", " + tileCoordinate.y;
var viewportCoordinate = map.pointToPixel(lngLat);
var viewportCoordStr = "<br />可视区域坐标:" + viewportCoordinate.x + ", " + viewportCoordinate.y;
var overlayCoordinate = map.pointToOverlayPixel(lngLat);
var overlayCoordStr = "<br />覆盖物坐标:" + overlayCoordinate.x + ", " + overlayCoordinate.y;
var tileCoordLngLat = projection.pointToLngLat({x:tileCoordinate.x*Math.pow(2,13),
y:tileCoordinate.y*Math.pow(2,13)});
var tileCoordLngLatStr = "<br />图块坐标反推经纬度:" + tileCoordLngLat.lng + ", " + tileCoordLngLat.lat;
//将百度经纬度转化为实际经纬度
var WGSLngLatStr;
function translateCallback(data){
if(data.status === 0) {
var BPoint = [];
BPoint[0] = Point;
BPoint[1] = data.points[0];
var GPSPoint = {};
GPSPoint.lng = 2*BPoint[0].lng - BPoint[1].lng;
GPSPoint.lat = 2*BPoint[0].lat - BPoint[1].lat;
WGSLngLatStr = "<br />实际经纬度:" + GPSPoint.lng.toFixed(6) + ", " + GPSPoint.lat.toFixed(6);
info.setContent(zoomStr + lngLatStr + worldCoordStr + pixelCoordStr + tileCoordStr +
viewportCoordStr + overlayCoordStr + WGSLngLatStr);
}
}
var Point = new BMap.Point(lngLat.lng,lngLat.lat);
var convertor = new BMap.Convertor();
var pointArr = [];
pointArr.push(Point);
convertor.translate(pointArr, 1, 5, translateCallback);
map.openInfoWindow(info, lngLat);
});
},
});
return BmapView;
});<file_sep>define(['backbone',
'models/cell_performance_alert',
],
function(Backbone, CellPerformanceAlert) {
var CellPerformanceAlertCollection = Backbone.Collection.extend({
model: CellPerformanceAlert,
initialize: function(options){
this.urlRoot = 'cell_performance_alert.html';
this.url = this.urlRoot + '?complaint_item_id=' + options.id;
}
});
return CellPerformanceAlertCollection;
});
<file_sep>define([
'underscore',
'backbone',
'marionette',
'cookie',
'collection/call_count_collection',
'collection/performance_count_collection',
'collection/stationerror_count_collection',
"tpl!views/partials/common/common_t/callCount.tpl",
"tpl!views/partials/common/common_t/callCountTitle.tpl",
"tpl!views/partials/common/common_t/performanceCount.tpl",
"tpl!views/partials/common/common_t/performanceCountTitle.tpl",
"tpl!views/partials/common/common_t/stationerrorCount.tpl",
"tpl!views/partials/common/common_t/stationerrorCountTitle.tpl",
"tpl!views/partials/common/common_t/noChildMessage.tpl",
"tpl!views/partials/common/common_t/dateInspection.tpl",
], function(_, Backbone, Marionette, Cookie, CallCountCollection, PerformanceCountCollection, StationerrorCountCollection,
callCountTpl, callCountTitleTpl, performanceCountTpl, performanceCountTitleTpl,
stationerrorCountTpl, stationerrorCountTitleTpl, noChildMessageTpl, inspectionTpl) {
"use strict";
var EmptyView = Backbone.Marionette.ItemView.extend({
template: noChildMessageTpl,
className: "noChildMessage",
initialize: function(options){
this.message = options.message;
},
onShow: function(){
this.$('.alert-message').html(this.message);
$('.alert-message').parents('table').removeClass('table-bordered');
}
});
var PerformanceCountView = Backbone.Marionette.ItemView.extend({
tagName: 'tr',
template: performanceCountTpl,
onRender: function(){
// this.$el.prepend(this.cellInfoTitle);
this.$('#total').html("总计");
}
});
var PerformanceCountCollectionView = Backbone.Marionette.CollectionView.extend({
tagName: 'table',
className: "table table-bordered performance-count-table",
childView: PerformanceCountView,
emptyView: EmptyView,
emptyViewOptions: {
message: "无法得到性能指标条数的统计信息"
},
performanceCountTitle : performanceCountTitleTpl,
onRender: function(){
if(this.collection.isEmpty()===false){
this.$el.prepend(this.performanceCountTitle);
}
}
});
var StationerrorCountView = Backbone.Marionette.ItemView.extend({
tagName: 'tr',
template: stationerrorCountTpl,
onRender: function(){
// this.$('#time').html("总计");
}
});
var StationerrorCountCollectionView = Backbone.Marionette.CollectionView.extend({
tagName: 'table',
className: "table table-bordered stationerror-count-table",
childView: StationerrorCountView,
emptyView: EmptyView,
emptyViewOptions: {
message: "无法得到告警信息条数的统计信息"
},
stationerrorCountTitle : stationerrorCountTitleTpl,
onRender: function(){
if(this.collection.isEmpty()===false){
this.$el.prepend(this.stationerrorCountTitle);
}
}
});
var CallCountView = Backbone.Marionette.ItemView.extend({
tagName: 'tr',
template: callCountTpl,
});
var CallCountCollectionView = Backbone.Marionette.CollectionView.extend({
tagName: 'table',
className: "table table-bordered call-count-table",
childView: CallCountView,
emptyView: EmptyView,
emptyViewOptions: {
message: "无法得到话单数量的统计信息"
},
callCountTitle : callCountTitleTpl,
onRender: function(){
if(this.collection.isEmpty()===false){
this.$el.prepend(this.callCountTitle);
}
}
});
var InspectionView = Marionette.LayoutView.extend({
template: inspectionTpl,
regions: {
callCountRegion: '#callCount',
performanceCountRegion: '#performanceCount',
stationerrorCountRegion: '#stationerrorCount',
},
events:{
'click #timeSubmit': 'inspectionByDate',
},
initialize: function(options) {
console.log('init inspection view');
this.now = options.now;
},
onShow: function(){
// $("#timeSubmit").click(function(){
// document.getElementById("title1").style.display = "block";
// document.getElementById("title2").style.display = "block";
// document.getElementById("title3").style.display = "block";
// });
var inspectionTime = this.now.substring(0,10);
$('#inspectionTime').val(inspectionTime);
},
inspectionByDate: function(){
var self = this;
var inspectionTime = $('#inspectionTime').val();
inspectionTime = inspectionTime.substring(0,10);
this.callCountCollection = new CallCountCollection();
this.callCountCollection.fetch({
data: {"inspection_time":inspectionTime},
success: function(data){
console.log(data);
self.callCountRegion.show(new CallCountCollectionView({
collection: self.callCountCollection
}));
document.getElementById("title1").style.display = "block";
}
});
this.performanceCountCollection = new PerformanceCountCollection();
this.performanceCountCollection.fetch({
data: {"inspection_time":inspectionTime},
success: function(data){
console.log(data);
self.performanceCountRegion.show(new PerformanceCountCollectionView({
collection: self.performanceCountCollection
}));
document.getElementById("title2").style.display = "block";
}
});
this.stationerrorCountCollection = new StationerrorCountCollection();
this.stationerrorCountCollection.fetch({
data: {"inspection_time":inspectionTime},
success: function(data){
console.log(data);
self.stationerrorCountRegion.show(new StationerrorCountCollectionView({
collection: self.stationerrorCountCollection
}));
document.getElementById("title3").style.display = "block";
}
});
}
// logOut:function(){
// Cookie.clear('username');
// window.close();
// window.open('#login');
// }
});
return InspectionView;
});
<file_sep>package mysql;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.util.Date;
import java.sql.SQLException;
public class ClearOutdatedData {
public static void clearOutdatedData() throws FileNotFoundException, ClassNotFoundException, SQLException, IOException, ParseException{
long duration = 45; //设置过时的天数,duration天前的数据要被清除。单位是 天
mysql_DML dml = new mysql_DML();
Connection conn = dml.myConnection();
String sqlGetLatestUpdate_date = "select update_date from im_hw_alarms order by update_date desc limit 0,1 ;";//获取插入告警故障数据的最新时间update_date(最后一次插入故障数据的时间)
System.out.println("最后一次插入告警数据的时间的sql语句="+sqlGetLatestUpdate_date);
ArrayList<String> latestUpdate_dateList = dml.selectMysql(sqlGetLatestUpdate_date, conn);
System.out.println("查找最后一次插入告警数据的时间结果="+latestUpdate_dateList);
if (latestUpdate_dateList.isEmpty()) { //最后一次插入告警数据没有记录时间,退出函数
System.out.println("error:最后一次插入告警数据没有记录时间!");
return ;
}
String latestUpdate_date = latestUpdate_dateList.get(0).split("\t")[0]; //最后一次插入告警数据的时间,格式是yyyy-MM-dd HH:mm:ss
System.out.println("最后一次插入告警数据的时间="+latestUpdate_date.substring(0,latestUpdate_date.length()-2));
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date latestUpdate_dateDate = format.parse(latestUpdate_date); //将时间字符串转为long格式
long latestUpdate_dateLong = latestUpdate_dateDate.getTime(); //最后一次插入告警数据的时间戳。单位是 毫秒ms
long timeB4DurationLong = latestUpdate_dateLong - duration * 24 * 60 * 60 * 1000;//得到duration天前的时间戳。单位是 毫秒ms
String timeB4Duration = format.format(timeB4DurationLong);//距离最后一次插入告警数据duration天前的时间,格式是yyyy-MM-dd HH:mm:ss
System.out.println(timeB4Duration+"前的数据将被删除!");
String sqlClearOutdatedData = "DELETE FROM im_hw_alarms WHERE update_date < '"+timeB4Duration+"';";
System.out.println("删除过时的告警数据sql语句="+sqlClearOutdatedData);
boolean f = dml.deleteData(sqlClearOutdatedData);
if (f) {
System.out.println("success:成功删除过时的告警数据!");
}else {
System.out.println("error:删除过时的告警数据失败!");
}
}
/**
* @param args
* @throws ParseException
* @throws IOException
* @throws SQLException
* @throws ClassNotFoundException
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException, ClassNotFoundException, SQLException, IOException, ParseException {
clearOutdatedData();
}
}
<file_sep> define([
'underscore',
'backbone',
'marionette',
'backbone_paginator',
'backgrid',
'backgrid_paginator',
'views/partials/common/callInfoView',
'collection/grid_info_collection',
'collection/call_info_collection',
'collection/cell_info_collection',
'collection/cell_info_type3_collection',
'collection/station_error_collection',
'collection/cell_performance_alert_collection',
"tpl!views/partials/common/common_t/judgeAssistant.tpl",
"tpl!views/partials/common/common_t/noChildMessage.tpl",
"tpl!views/partials/common/common_t/gridInfo.tpl",
"tpl!views/partials/common/common_t/gridInfoTitle.tpl",
"tpl!views/partials/common/common_t/cellInfo.tpl",
"tpl!views/partials/common/common_t/cellInfoTitle.tpl",
"tpl!views/partials/common/common_t/callInfo.tpl",
"tpl!views/partials/common/common_t/cellInfoType3.tpl",
"tpl!views/partials/common/common_t/cellInfoType3Title.tpl",
"tpl!views/partials/common/common_t/callInfoTitle.tpl",
"tpl!views/partials/common/common_t/callInfoMessage.tpl",
"tpl!views/partials/common/common_t/stationError.tpl",
"tpl!views/partials/common/common_t/stationErrorTitle.tpl",
"tpl!views/partials/common/common_t/cellAlert.tpl",
"tpl!views/partials/common/common_t/cellAlertTitle.tpl",
], function(_, Backbone, Marionette, PageableCollection, Backgrid, Paginator, CallInfoView, GridInfoCollection, CallInfoCollection, CellInfoCollection, CellInfoType3Collection,
StationErrorCollection, CellPerformanceAlertCollection,
judgeAssistantTpl, noChildMessageTpl, gridInfoTpl, gridInfoTitleTpl, cellInfoTpl, cellInfoTitleTpl, callInfoTpl, cellInfoType3Tpl, cellInfoType3TitleTpl, callInfoTitleTpl, callInfoMessageTpl,
stationErrorTpl, stationErrorTitleTpl, cellAlertTpl, cellAlertTitleTpl) {
"use strict";
var EmptyView = Backbone.Marionette.ItemView.extend({
template: noChildMessageTpl,
className: "noChildMessage",
initialize: function(options){
this.message = options.message;
},
onShow: function(){
this.$('.alert-message').html(this.message);
$('.alert-message').parents('table').removeClass('table-bordered');
}
});
var GridInfoView = Backbone.Marionette.ItemView.extend({
tagName: 'tr',
template: gridInfoTpl,
});
var GridInfoCollectionView = Backbone.Marionette.CollectionView.extend({
tagName: 'table',
className: "table table-bordered grid-info-table",
childView: GridInfoView,
emptyView: EmptyView,
emptyViewOptions: {
message: "周边无栅格信息"
},
gridInfoTitle : gridInfoTitleTpl,
onRender: function(){
if(this.collection.isEmpty()===false){
this.$el.prepend(this.gridInfoTitle);
}
}
});
var CellInfoView = Backbone.Marionette.ItemView.extend({
tagName: "tr",
template: cellInfoTpl,
typeMap:{
'1': '搜索半径内小区',
'2': '搜索半径外最近小区',
'3': '话单关联小区',
},
onRender: function(){
// this.$el.prepend(this.cellInfoTitle);
this.$('#cellInfoType').html(this.typeMap[this.model.get('type')]);
}
});
var CellInfoCollectionView = Backbone.Marionette.CollectionView.extend({
tagName: 'table',
className: "table table-bordered cell-info-table",
childView: CellInfoView,
emptyView: EmptyView,
emptyViewOptions: {
message: "周边无投诉关联小区信息"
},
cellInfoTitle : cellInfoTitleTpl,
onRender: function(){
if(this.collection.isEmpty()===false){
this.$el.prepend(this.cellInfoTitle);
}
}
});
var CellInfoType3View = Backbone.Marionette.ItemView.extend({
tagName: "tr",
template: cellInfoType3Tpl,
typeMap:{
'1': '搜索半径内小区',
'2': '搜索半径外最近小区',
'3': '话单关联小区',
},
onRender: function(){
// this.$el.prepend(this.cellInfoTitle);
this.$('#cellInfoType').html(this.typeMap[this.model.get('type')]);
}
});
var CellInfoType3CollectionView = Backbone.Marionette.CollectionView.extend({
tagName: 'table',
className: "table table-bordered cell-info-table",
childView: CellInfoType3View,
emptyView: EmptyView,
emptyViewOptions: {
message: "周边无投诉关联小区信息"
},
cellInfoType3Title : cellInfoType3TitleTpl,
onRender: function(){
if(this.collection.isEmpty()===false){
this.$el.prepend(this.cellInfoType3Title);
}
}
});
var StationErrorView = Backbone.Marionette.ItemView.extend({
tagName: "tr",
template: stationErrorTpl,
});
var StationErrorCollectionView = Backbone.Marionette.CollectionView.extend({
tagName: 'table',
className: "table table-bordered station-error-table",
childView: StationErrorView,
emptyView: EmptyView,
emptyViewOptions: {
message: "周边基站无故障告警"
},
stationErrorTitle : stationErrorTitleTpl,
onRender: function(){
if(this.collection.isEmpty()===false){
this.$el.prepend(this.stationErrorTitle);
}
}
});
var CellAlertView = Backbone.Marionette.ItemView.extend({
tagName: "tr",
template: cellAlertTpl,
onShow: function(){
if(this.model.get('congestion')>200){
this.$('#congestion').addClass('note');
}
if(this.model.get('call_amount')<0.5){
this.$('#call_amount').addClass('note');
}
if(this.model.get('city')==='黄石'||this.model.get('city')==='黄冈'||this.model.get('city')==='鄂州'||this.model.get('city')==='咸宁'){
if(this.model.get('rssi')>-85&&this.model.get('rssi')<0){
this.$('#rssi').addClass('note');
}}
else{
if(this.model.get('rssi')>-70&&this.model.get('rssi')<0){
this.$('#rssi').addClass('note');
}
}
}
});
var CellAlertCollectionView = Backbone.Marionette.CollectionView.extend({
tagName: 'table',
className: "table table-bordered cell-alert-table",
childView: CellAlertView,
emptyView: EmptyView,
emptyViewOptions: {
message: "周边基站无性能预警"
},
cellAlertTitle : cellAlertTitleTpl,
onRender: function(){
if(this.collection.isEmpty()===false){
this.$el.prepend(this.cellAlertTitle);
}
}
});
// var CallInfoView = Backbone.Marionette.ItemView.extend({
// tagName: "tr",
// // className: "table",
// template: callInfoTpl,
// });
var CallInfoCollectionView = Backbone.Marionette.CollectionView.extend({
tagName: 'table',
className: "table table-bordered call-info-table",
childView: CallInfoView,
callInfoMessage: callInfoMessageTpl,
callInfoTitle : callInfoTitleTpl,
onRender: function(){
},
onShow: function(){
if(this.collection.isEmpty()===false){
this.$el.prepend(this.callInfoTitle);
}
else{
$('#callInfoCount').html('0');
$('#paginator').hide();
}
}
});
var JudgeAssistantView = Backbone.Marionette.LayoutView.extend({
template: judgeAssistantTpl,
regions: {
cellInfoRegion: '#cellInfo',
cellInfoType3Region: '#cellInfoType3',
gridInfoRegion: '#gridInfo',
stationErrorRegion: '#stationError',
cellPerformanceAlertRegion: '#cellPerformanceAlert',
callInfoRegion: '#callInfo',
},
events:{
},
initialize: function(options) {
console.log('init judgeAssistant view');
this.complaintItemId = options.complaintItemId;
},
onShow: function(){
self =this;
this.callInfoState = "unusual";
$('[name=callDisplayType][value=unusual]').attr('checked',true);
var callDisplayType = $('[name=callDisplayType]:checked').val();
$('#callInfoName').html("异常话单");
$('[name=callDisplayType]:first').on('change',function(){
$('#callInfoName').html("话单");
self.callInfoState = "all";
self.showCallInfo();
});
$('[name=callDisplayType]:last').on('change',function(){
$('#callInfoName').html("异常话单");
self.callInfoState = "unusual";
self.showCallInfo();
});
this.gridInfoCollection = new GridInfoCollection({id: this.complaintItemId});
this.gridInfoCollection.fetch({
success: function(data){
console.log(data);
var a = self.gridInfoCollection.shift();
if(a !== undefined){
$('#exist1').html('依据 { 经度=');
$('#exist2').html(' , 纬度=');
$('#exist3').html('话务热度为');
$('#exist4').html('覆盖水平为');
$('#exist5').html(' } ');
$('#longitude3').html(a.get('longitude'));
$('#latitude3').html(a.get('latitude'));
switch(a.get('call_load')){
case "red":
$('#call_load').html("高话务(前30%的栅格)");
break;
case "yellow":
$('#call_load').html("中等话务(50%)");
break;
default:
$('#call_load').html("低话务(最后20%的栅格)");
break;
}
switch(a.get('cover_quality')){
case "red":
$('#cover_quality').html("弱覆盖(最后20%的栅格)");
break;
case "yellow":
$('#cover_quality').html("一般覆盖");
break;
default:
$('#cover_quality').html("良好覆盖(前30%的栅格)");
break;
}
}
else {
$('#exist1').html('无法依据经纬度');
$('#exist3').html('无话务');
$('#exist4').html('无覆盖');
}
self.gridInfoRegion.show(new GridInfoCollectionView({
collection: self.gridInfoCollection
}));
$('#GridInfoCount').html(data.length);
}
});
this.cellInfoCollection = new CellInfoCollection({id: this.complaintItemId});
this.cellInfoCollection.fetch({
success: function(data){
console.log(data);
var b = self.cellInfoCollection.shift();
$('#longitude1').html(b.get('longitude'));
$('#latitude1').html(b.get('latitude'));
$('#radius').html(b.get('radius'));
switch(b.get('cell_density')){
case "white":
$('#cell_density').html("无投诉地址/经纬度");
break;
case "red":
$('#cell_density').html("无关联小区");
break;
case "yellow":
$('#cell_density').html("搜索范围内小区数量小于系统设定阈值 OR 搜索范围外最近小区距离大于搜索半径的2倍");
break;
default:
$('#cell_density').html("搜索范围内小区数量大于系统设定阈值");
break;
}
self.cellInfoRegion.show(new CellInfoCollectionView({
collection: self.cellInfoCollection
}));
$('#CellInfoCount').html(data.length);
}
});
this.cellInfoType3Collection = new CellInfoType3Collection({id: this.complaintItemId});
this.cellInfoType3Collection.fetch({
success: function(data){
console.log(data);
var b = self.cellInfoType3Collection.shift();
$('#trouble_occur_time1').html(b.get('trouble_occur_time'));
$('#trouble_end_time1').html(b.get('trouble_end_time'));
self.cellInfoType3Region.show(new CellInfoType3CollectionView({
collection: self.cellInfoType3Collection
}));
$('#CellInfoCount2').html(data.length);
}
});
this.stationErrorCollection = new StationErrorCollection({id: this.complaintItemId});
this.stationErrorCollection.fetch({
success: function(data){
console.log(data);
console.log(data.toJSON());
var c = self.stationErrorCollection.shift();
$('#trouble_occur_time2').html(c.get('trouble_occur_time'));
$('#trouble_end_time2').html(c.get('trouble_end_time'));
$('#complain_time1').html(c.get('complain_time'));
switch(c.get('trouble_alert')){
case "green":
$('#trouble_alert').html("问题搜索时段无故障");
break;
default:
$('#trouble_alert').html("问题搜索时段有故障");
break;
}
self.stationErrorRegion.show(new StationErrorCollectionView({
collection: self.stationErrorCollection
}));
$('#StationErrorCount').html(data.length);
}
});
this.cellPerformanceAlertCollection = new CellPerformanceAlertCollection({id: this.complaintItemId});
this.cellPerformanceAlertCollection.fetch({
success: function(data){
console.log(data);
var d = self.cellPerformanceAlertCollection.shift();
$('#trouble_time2').html(d.get('trouble_time'));
switch(d.get('performance_alert')){
case "red":
$('#performance_alert').html("性能劣化。关联基站在问题时段有性能预警");
break;
default:
$('#performance_alert').html("性能正常。关联基站在问题时段无性能预警");
break;
}
self.cellPerformanceAlertRegion.show(new CellAlertCollectionView({
collection: self.cellPerformanceAlertCollection
}));
$('#PerformanceAlertCount').html(data.length);
}
});
this.showCallInfo();
},
showCallInfo: function(){
self = this;
this.callInfoCollection = new CallInfoCollection({id: this.complaintItemId});
var paginator = new Backgrid.Extension.Paginator({
collection: this.callInfoCollection
});
$("#paginator").html(paginator.render().$el);
this.callInfoCollection.fetch({
data: {callInfoState: self.callInfoState},
success: function(data){
console.log(data);
var e = self.callInfoCollection.shift();
$('#trouble_occur_time3').html(e.get('trouble_occur_time'));
$('#trouble_end_time3').html(e.get('trouble_end_time'));
switch(e.get('unusual_event')){
case "red":
$('#unusual_event').html("关联时段内,话单记录存在异常/失败事件");
break;
case "green":
$('#unusual_event').html("关联时段内,无异常话单事件");
break;
default:
$('#unusual_event').html("无话单记录");
break;
}
switch(e.get('signal_quality')){
case "red":
$('#signal_quality').html("关联时段内,话单内的接入/释放主信号ECIO<-15");
break;
case "yellow":
$('#signal_quality').html("关联时段内,话单内的接入/释放主信号ECIO between [-9,-15]");
break;
case "green":
$('#signal_quality').html("关联时段内,所有话单的话单内的接入/释放主信号ECIO >-9");
break;
default:
$('#signal_quality').html("无话单记录");
break;
}
$('#callInfoCount').html(data.state.totalRecords);
self.callInfoRegion.show(new CallInfoCollectionView({
collection: self.callInfoCollection
}));
}
});
}
});
return JudgeAssistantView;
});
<file_sep>define([
'backbone'
], function(Backbone) {
"use strict";
var LightInfo = Backbone.Model.extend({
initialize: function(options){
this.urlRoot = 'light_info.html';
this.url = this.urlRoot + '?complaint_item_id=' + options.id;
}
});
return LightInfo;
});<file_sep>define(['bmap_api'], function() {
"use strict";
// 创建div元素,作为自定义覆盖物的容器
var div = document.createElement("div");
div.style.position = "absolute";
// div.id = "ssss";
// 可以根据参数设置元素外观
div.style.width = 60 + "px";
div.style.height = 60 + "px";
div.style.backgroundColor = "#000";
div.style.opacity = 0.5;
// 定义自定义覆盖物的构造函数
var PngOverlay = function(initPoint, strength, zoom){
this._initPoint = initPoint;
this._strength = strength;
this._zoom = zoom;
};
// 继承API的BMap.Overlay
PngOverlay.prototype = new BMap.Overlay();
// 实现初始化方法
PngOverlay.prototype.initialize = function(map) {
// 保存map对象实例
this._map = map;
// 将div添加到覆盖物容器中
map.getPanes().markerPane.appendChild(div);
// 需要将div元素作为方法的返回值,当调用该覆盖物的show、
// hide方法,或者对覆盖物进行移除时,API都将操作此元素。
return div;
};
// 实现绘制方法
PngOverlay.prototype.draw = function() {
// 根据地理坐标转换为像素坐标,并设置给容器
var position = this._map.pointToOverlayPixel(this._initPoint);
div.style.left = position.x + "px";
div.style.top = position.y + "px";
console.log(position);
};
return {
PngOverlay: PngOverlay
};
});
|
208252ec1dd7397be2d846a0fe5ed22bdd67d8c8
|
[
"JavaScript",
"Java",
"Markdown",
"INI"
] | 98 |
Java
|
FEFJay/TS
|
5d7925c01367aeb9eea13a0e86b95f261f9f7d6b
|
69ecf4b1f1ddbd853f7c1a74f1ea5647e0234e0e
|
refs/heads/master
|
<repo_name>vlasovmichael/javascript-password-generator<file_sep>/gulpfile.js
'use strict';
var gulp = require('gulp'),
autoprefixer = require('autoprefixer'),
nunjucksRender = require('gulp-nunjucks-render'),
livereload = require('gulp-livereload'),
connect = require('gulp-connect'),
sass = require('gulp-sass'),
postcss = require('gulp-postcss'),
notify = require('gulp-notify'),
fileinclude = require('gulp-file-include'),
rigger = require('gulp-rigger'),
// mainBowerFiles = require('gulp-main-bower-files'),
// spritesmith = require('gulp.spritesmith'),
svgSprite = require("gulp-svg-sprites"),
clean = require('gulp-clean')
// sourcemaps = require('gulp-sourcemaps')
// server connect
gulp.task('connect', function() {
connect.server({
root: 'build',
livereload: true
});
});
// Image Task
gulp.task('img', function(){
gulp.src('src/img/**/*')
// .pipe(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true }))
.pipe(gulp.dest('build/img'))
.pipe(connect.reload());
});
// sass
gulp.task('sass', function () {
var processors = [
autoprefixer({browsers: ['last 10 versions'], cascade: false}),
];
return gulp.src('src/sass/*.scss')
// .pipe(sourcemaps.init())
.pipe(sass({outputStyle: 'compact'}).on('error', sass.logError)) // nested, expanded, compact, compressed
.pipe(postcss(processors))
// .pipe(sourcemaps.write('../maps'))
.pipe(gulp.dest('build/css'))
.pipe(connect.reload());
});
// bower main files
gulp.task('main-bower-files', function() {
return gulp.src('bower_components/jquery/dist/jquery.min.js')
// .pipe(mainBowerFiles([[filter, ]options][, callback]))
.pipe(gulp.dest('src/js'));
});
// html
gulp.task('html', function () {
gulp.src('src/*.html')
.pipe(fileinclude({
prefix: '@@',
basepath: '@file'
}))
.pipe(nunjucksRender({
path: 'src'
}))
.pipe(gulp.dest('build/'))
.pipe(connect.reload());
});
// js
gulp.task('js', function () {
gulp.src('src/js/*.js')
// .pipe(rigger())
.pipe(gulp.dest('build/js'))
.pipe(connect.reload());
});
// svg sprites
gulp.task('svgSprite', function () {
return gulp.src('src/img/svg/*.svg')
.pipe(svgSprite({
mode: "symbols",
preview: false,
svg: {
symbols : "sprite.svg"
}
}))
.pipe(gulp.dest("src/img"))
.pipe(connect.reload());
});
// fonts
gulp.task('fonts', function() {
gulp.src('src/fonts/**/*')
.pipe(gulp.dest('build/fonts'))
.pipe(connect.reload());
});
// clean
gulp.task('clean', function () {
return gulp.src('build', {read: false})
.pipe(clean());
});
// watch
gulp.task('watch', function () {
gulp.watch('src/img/**/*', ['img'])
gulp.watch('src/fonts/**/*', ['fonts'])
gulp.watch('src/*.html', ['html'])
gulp.watch('src/layouts/*.html', ['html'])
gulp.watch('src/img/svg/*.svg', ['svgSprite'])
gulp.watch('src/js/*.js', ['js'])
gulp.watch('src/sass/**/*.scss', ['sass'])
gulp.watch('src/bower_components/jquery/dist/jquery.min.js', ['main-bower-files'])
})
// default
gulp.task('default', ['connect', 'html', 'sass', 'js', 'img', 'svgSprite', 'fonts', 'watch']);
|
687c2cf1983ce568085dfd3bfaf7116483085bef
|
[
"JavaScript"
] | 1 |
JavaScript
|
vlasovmichael/javascript-password-generator
|
3b3ef74556ba3bd3f8559dde660c6c657e220cb3
|
1ef16ba32f5fc17b471b11b8782d61f7e862e1c6
|
refs/heads/master
|
<file_sep>/**
* Data Transfer Objects.
*/
package org.trytodo.newspaper.service.dto;
<file_sep>/**
* JPA domain objects.
*/
package org.trytodo.newspaper.domain;
<file_sep>/**
* Locale specific code.
*/
package org.trytodo.newspaper.config.locale;
|
b96fd355d81d79e935bf4089df5631d4623d72a0
|
[
"Java"
] | 3 |
Java
|
babuwant2do/newspaper
|
7bbfd7991889fa02413c2a1f90e7652c643aac61
|
c84e30dfcbce596a3dbdaecda51f55b737f74629
|
refs/heads/main
|
<file_sep>## Input Genomic FASTA File
inputFile = 'genomic.fna'
# Input File Formatting (Removing of "\n" and headers)
# Reference to (https://stackoverflow.com/questions/11968998/remove-lines-that-contain-certain-string)
tempFile = 'tempGenomic.txt'
removeChar = ['>']
with open(inputFile) as oldfile, open(tempFile, 'w') as newfile:
for line in oldfile:
if not any(removeChar in line for removeChar in removeChar):
line = line.replace('\n', '')
newfile.write(line)
a = open(tempFile, 'r')
a = a.read()
# Input Sequence
inputSequence = input("Enter sequence: ")
# Brute Force Method
i = 0
j = 0
# cnt_Brute counts the number of comparisons for Brute Force
cnt_Brute = 0
occurOnceFlag = 0 # To check if there is at least once occurrence
while i < len(a):
# To check for the first character of the input sequence & file
cnt_Brute += 1
if a[i] == inputSequence[j]:
# Increase the index of the sequence to check for the next character
j = j + 1
else:
cnt_Brute += 1
if j > 0:
i = i - j
# To re-check for the input sequence
j = 0
cnt_Brute += 1
if j == len(inputSequence):
# Bringing the index of input sequence back to 0 to check for other match sequence in the file
j = 0
print("(BRUTE FORCE)There is an occurrence at position:", ((i + 2) - len(inputSequence)))
# i is incremented to increase the position of the character in the Genome file
occurOnceFlag = 1
if (i == len(a) - 1 and occurOnceFlag == 0): # When there is COMPLETELY no occurence
print("(BRUTE FORCE)There is no occurrence for your input: " + inputSequence)
i += 1
# KMP
i,j=1,0
l=[]
l.append(0)
# cnt_KMP counts the number of comparisons for KMP
cnt_KMP=0
while i<len(inputSequence):
cnt_KMP+=1
if inputSequence[i]==inputSequence[j]:
l.append(1+j)
i+=1
j+=1
else:
cnt_KMP+=1
if j!=0:
j=l[j-1]
else:
l.append(0)
i+=1
# Re-initailising i and j
i = 0
j = 0
occurOnceFlag=0 #To check if there is at least once occurence
# Main KMP algorithm
while (i < len(a)):
cnt_KMP+=1
if a[i] == inputSequence[j]:
i += 1
j += 1
cnt_KMP+=1
if j == len(inputSequence):
print("(KMP)There is an occurrence at position:", (i - j + 1))
i = i + len(inputSequence) - 1
occurOnceFlag=1
j = l[j - 1]
elif i < len(a) and inputSequence[j] != a[i]:
cnt_KMP+=1
if j != 0:
j = l[j - 1]
else:
i += 1
#When there is COMPLETELY no occurence
if(i == len(a) and occurOnceFlag == 0):
print("(KMP)There is no occurence for your input: " + inputSequence)
# <NAME>
# To calculate the maximum number of repetitions in inputSequence
maximum = 1
# cnt_Boyer counts the number of comparisons for Boyer Moore
cnt_Boyer = 0
for k in range(0, len(inputSequence)):
cnt = 1
while (k + 1 < len(inputSequence) and inputSequence[k] == inputSequence[k + 1]):
cnt += 1
k += 1
cnt_Boyer += 1
if cnt > maximum:
maximum = cnt
Count_A1 = 0
Count_A2 = 0
Count_G1 = 0
Count_G2 = 0
Count_T1 = 0
Count_T2 = 0
Count_C1 = 0
Count_C2 = 0
star = len(inputSequence)
l = []
# Making the prerequisite table for <NAME>
for i in range(0, len(inputSequence)):
cnt_Boyer += 1
off = len(inputSequence) - i - maximum
if inputSequence[i] == 'A':
Count_A1 = max(1, off)
Count_A2 += 1
elif inputSequence[i] == 'G':
Count_G1 = max(1, off)
Count_G2 += 1
elif inputSequence[i] == 'T':
Count_T1 = max(1, off)
Count_T2 += 1
elif inputSequence[i] == 'C':
Count_C1 = max(1, off)
Count_C2 += 1
if Count_A2 == 0:
l.append(0)
else:
l.append(Count_A1)
if Count_G2 == 0:
l.append(0)
else:
l.append(Count_G1)
if Count_T2 == 0:
l.append(0)
else:
l.append(Count_T1)
if Count_C2 == 0:
l.append(0)
else:
l.append(Count_C1)
l.append(star)
i = 0
# %%
i = 0
occurOnceFlag = 0 # To check if there is at least once occurence
# Main code for <NAME>
while i < len(a) - len(inputSequence) + 1:
j = len(inputSequence) - 1
while j >= 0:
cnt_Boyer += 1
if (inputSequence[j] == a[i + j]):
j -= 1
if j == -1:
print("(BOYAR MOORE)There is an occurrence at position: ", i + 1)
occurOnceFlag = 1
i += len(inputSequence)
else:
cnt_Boyer += 1
if a[i + j] == 'A' and Count_A1 != 0:
i += (l[0])
elif a[i + j] == 'G' and Count_G1 != 0:
i += (l[1])
elif a[i + j] == 'T' and Count_T1 != 0:
i += (l[2])
elif a[i + j] == 'C' and Count_C1 != 0:
i += (l[3])
else:
i += (l[4])
break
if (occurOnceFlag == 0):
print("(<NAME>)There is no occurence for your input: " + inputSequence)
|
71626e0095f78b40801c8f3644f3b1bad6a81871
|
[
"Python"
] | 1 |
Python
|
Abhigyan14/Substring-Search-Algo
|
1a2a6eb1519d99f87a37ab84e6ce10cbcdee708c
|
4651e7a87da4bf79cd514b78ea7e521a3c25a877
|
refs/heads/master
|
<repo_name>yashtiwari22/Native-Dev<file_sep>/src/Header/Header.js
import React from 'react';
import Moon from '../image/moon-fill.svg';
import Sun from '../image/brightness-high.svg';
import Native from '../image/Native-Developers.jpg'
import $ from 'jquery';
import Section from '../Section/Section';
import './Header.css';
function Header() {
const [icon,setIcon]=React.useState("1");
React.useEffect(()=>{
$("#moon").on("click",function(){
$("body").toggleClass("bw");
})
},[])
const handleIcon=()=>{
if(icon==="1"){
setIcon("2")
}else{
setIcon("1")
}
}
return (
<>
<div className="container-fluid nav_bg" style={{minWidth:'100%'}}>
<div className="row" >
<nav className="navbar navbar-expand-lg navbar-light bg-light" >
<div className="container-fluid">
<img className="logo" style={{ height: '50px' }} src={Native} />
<div className="collapse navbar-collapse" id="navbarSupportedContent" >
<ul class=" navb navbar-nav ml-auto mb-2 mb-lg-0" >
<li className="nav-item pr-5">
<a aria-current="page" href="#">Home</a>
</li>
<li className="nav-item pr-5">
<a href="#">Services</a>
</li>
<li className="nav-item pr-5">
<a href="#">About</a>
</li>
<li className="nav-item pr-5">
<a href="#">Contact</a>
</li>
<li className="nav-item pr-3" style={{ display: 'flex', alignItems: 'center' }}>
<img src={icon=="1" ? Sun:Moon} onClick={handleIcon} id="moon"/>
</li>
</ul>
</div>
</div>
</nav>
</div>
</div>
</>
)
}
export default Header;
|
631c1f23f0b05520c43e45e8850ec96f2849dbea
|
[
"JavaScript"
] | 1 |
JavaScript
|
yashtiwari22/Native-Dev
|
a77eca6f0473474980585f657cb3e43f5f62fa04
|
131ed0f613af333bf5d54245ec3865d096053de8
|
refs/heads/master
|
<repo_name>phoenixstar7/topcoder<file_sep>/atcoder/codefesta_2015/qa_d.cpp
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int N, M;
int X[100000];
bool possible(int t) {
int right = 0;
for (int i = 0; i < M; ++i) {
int d = X[i] - (right + 1);
if (d > t) {
return false;
}
if (d > 0) {
right = max(X[i] + max(0, (t - d) / 2), right + 1 + max(0, t - d));
} else {
right = max(right, X[i] + t);
}
}
return right >= N;
}
int main(int argc, char *argv[])
{
cin >> N >> M;
for (int i = 0; i < M; ++i) {
cin >> X[i];
}
int low = -1, high = N * 2;
while (high - low > 1) {
int med = (low + high) / 2;
if (possible(med)) {
high = med;
} else {
low = med;
}
}
cout << high << endl;
return 0;
}
<file_sep>/atcoder/arc_043/b.cpp
// B.
#include <iostream>
#include <algorithm>
#include <sstream>
using namespace std;
const int MOD = 1000000007;
int main(int argc, char *argv[])
{
int N, D[100000], dp[6][100000] = {};
cin >> N;
for (int i = 0; i < N; ++i) {
cin >> D[i];
dp[0][i] = 1;
}
if (N > 3000) {
cout << "-1" << endl;
return 0;
}
sort(D, D + N);
for (int i = 1; i <= 3; ++i) {
for (int j = 0; j < N; ++j) {
for (int k = 0; k < j; ++k) {
if (D[k] * 2 > D[j]) {
break;
}
dp[i][j] = (dp[i][j] + dp[i - 1][k]) % MOD;
}
}
}
int ans = 0;
for (int i = 0; i < N; ++i) {
ans = (ans + dp[3][i]) % MOD;
}
cout << ans << endl;
return 0;
}
<file_sep>/yukicoder_0xx/60.cpp
#include <iostream>
#include <algorithm>
#include <sstream>
#include <vector>
using namespace std;
typedef long long LL;
class BIT {
std::vector<LL> bit;
int size;
public:
BIT() { }
BIT(int sz) { init(sz); }
void init(int sz) {
bit.resize((size = sz) + 1);
}
LL sum(int i) {
LL s = 0;
while (i > 0) {
s += bit[i];
i -= i & -i;
}
return s;
}
void add(int i, LL x) {
if (i == 163) {
++i;
--i;
}
while (i <= size) {
bit[i] += x;
i += i & -i;
}
}
};
class RangedSUM {
BIT high;
BIT low;
public:
RangedSUM() { }
RangedSUM(int sz) : high(sz), low(sz) { }
void init(int sz) {
high.init(sz);
low.init(sz);
}
void add(int start, int end, LL value) {
low.add(start, (start - 1) * -value);
high.add(start, value);
low.add(end + 1, end * value);
high.add(end + 1, -value);
}
LL sum(int start, int end) {
return low.sum(end) + high.sum(end) * end - low.sum(start - 1) - high.sum(start - 1) * (start - 1);
}
};
int main(int argc, char *argv[])
{
RangedSUM rsum[1024];
for (int i = 0; i < 1024; ++i) {
rsum[i].init(1024);
}
int ex[100000], ey[100000], ehp[100000];
int N, K;
cin >> N >> K;
for (int i = 0; i < N; ++i) {
cin >> ex[i] >> ey[i] >> ehp[i];
ex[i] += 512, ey[i] += 512;
}
for (int i = 0; i < K; ++i) {
int ax, ay, w, h, d;
cin >> ax >> ay >> w >> h >> d;
ax += 512, ay += 512;
int ex = min(1020, ax + w);
for (int y = ay; y <= min(1020, ay + h); ++y) {
rsum[y].add(ax, ex, d);
}
}
LL ans = 0;
for (int i = 0; i < N; ++i) {
ans += max(0LL, ehp[i] - rsum[ey[i]].sum(ex[i], ex[i]));
}
cout << ans << endl;
return 0;
}
<file_sep>/atcoder/abc_034/c.cpp
// C.
#include <iostream>
#include <sstream>
#include <cstdio>
#include <cstring>
using namespace std;
static const int MOD = 1000000007;
struct modll {
long long x;
modll() { }
modll(long long _x) : x(_x) { }
operator int() const { return (int)x; }
modll operator+(const modll &r) { return (x + r.x) % MOD; }
modll operator+=(const modll &r) { return x = (x + r.x) % MOD; }
modll operator-(const modll &r) { return (x + MOD - r.x) % MOD; }
modll operator-=(const modll &r) { return x = (x + MOD - r.x) % MOD; }
modll operator*(const modll &r) { return (x * r.x) % MOD; }
modll operator*(int r) { return (x * r) % MOD; }
modll operator*=(const modll &r) { return x = (x * r.x) % MOD; }
modll inverse() {
modll r = 1;
modll a = x;
int b = MOD - 2;
while (b) {
if (b & 1) {
r *= a;
}
a *= a;
b >>= 1;
}
return r;
}
};
int main(int argc, char *argv[])
{
int W, H;
cin >> W >> H;
--W, --H;
modll ans = 1;
for (int i = H + 1; i <= W + H; ++i) {
ans *= i;
}
for (int i = 1; i <= W; ++i) {
ans *= modll(i).inverse();
}
cout << ans << endl;
return 0;
}
<file_sep>/srm_7xx/srm_716/ConstructLCS.cpp
// BEGIN CUT HERE
/*
SRM 716 Div1 Easy (250)
PROBLEM STATEMENT
A string S is a subsequence of a string T if we can obtain S from T by erasing some (possibly all or none) of its characters. For example, "000" is a subsequence of "01010".
The longest common subsequence (LCS) of two strings A and B is a string C that is a subsequence of each of them and has the largest length among all strings with this property. Let f(A,B) be the length of the LCS of strings A and B. For example, we have f("101", "111000") = 2, f("101", "110011") = 3, and f("00", "1111") = 0.
You are given three small positive integers ab, bc, and ca.
Please find three strings A, B, C such that:
Each of the strings contains only the characters '0' and '1'.
The length of each string is between 1 and 1,000, inclusive.
f(A, B) = ab
f(B, C) = bc
f(C, A) = ca
Return a string formed as follows: A + " " + B + " " + C.
(I.e., the returned string should contain the three strings A, B, C, separated by single spaces.)
You may assume that a solution always exist.
If there are multiple solutions you may return any of them.
DEFINITION
Class:ConstructLCS
Method:construct
Parameters:int, int, int
Returns:string
Method signature:string construct(int ab, int bc, int ca)
CONSTRAINTS
-ab will be between 1 and 50, inclusive.
-bc will be between 1 and 50, inclusive.
-ca will be between 1 and 50, inclusive.
EXAMPLES
0)
3
4
2
Returns: "101 1010101 1111"
The returned string corresponds to the following solution:
A = "1111"
B = "101"
C = "1010101"
We can easily verify that the only LCS of A and B is "11", the only LCS of B and C is "101", and the only LCS of C and A is "1111".
1)
7
4
4
Returns: "10101010 1010101 1011"
There are other solutions like: A = "1110000", B = "1110000", C = "0000".
2)
8
7
8
Returns: "110101001011 010101101 10101010"
3)
8
6
7
Returns: "110101010 10101010 1111010"
4)
15
17
19
Returns: "000100101101111011000 11110111010011101010 100100001010101001010101000011111"
5)
50
50
50
Returns: "11111111111111111111111111111111111111111111111111 11111111111111111111111111111111111111111111111111 11111111111111111111111111111111111111111111111111"
*/
// END CUT HERE
#include <algorithm>
#include <cmath>
#include <numeric>
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <cstring>
using namespace std;
typedef pair<int, int> II;
class ConstructLCS {
public:
string construct(int ab, int bc, int ca) {
int abc[3] = { ab,bc,ca };
sort(abc, abc + 3);
II v[3];
v[0].first = abc[2];
v[1].first = abc[0];
v[1].second = abc[1] - abc[0];
v[2].first = abc[2];
v[2].second = abc[1] - abc[0];
int seq[3] = { 0,1,2 };
do {
if (min(v[seq[0]].first, v[seq[1]].first) + min(v[seq[0]].second, v[seq[1]].second) == ab &&
min(v[seq[1]].first, v[seq[2]].first) + min(v[seq[1]].second, v[seq[2]].second) == bc &&
min(v[seq[2]].first, v[seq[0]].first) + min(v[seq[2]].second, v[seq[0]].second) == ca) {
break;
}
} while (next_permutation(seq, seq + 3));
string ans;
for (int i = 0; i < 3; ++i) {
if (i) {
ans += " ";
}
ans += string(v[seq[i]].first, '0');
ans += string(v[seq[i]].second, '1');
}
return ans;
}
// BEGIN CUT HERE
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
public:
void run_test(int Case) {
int n = 0;
// test_case_0
if ((Case == -1) || (Case == n)){
int Arg0 = 3;
int Arg1 = 4;
int Arg2 = 2;
string Arg3 = "101 1010101 1111";
verify_case(n, Arg3, construct(Arg0, Arg1, Arg2));
}
n++;
// test_case_1
if ((Case == -1) || (Case == n)){
int Arg0 = 7;
int Arg1 = 4;
int Arg2 = 4;
string Arg3 = "10101010 1010101 1011";
verify_case(n, Arg3, construct(Arg0, Arg1, Arg2));
}
n++;
// test_case_2
if ((Case == -1) || (Case == n)){
int Arg0 = 8;
int Arg1 = 7;
int Arg2 = 8;
string Arg3 = "110101001011 010101101 10101010";
verify_case(n, Arg3, construct(Arg0, Arg1, Arg2));
}
n++;
// test_case_3
if ((Case == -1) || (Case == n)){
int Arg0 = 8;
int Arg1 = 6;
int Arg2 = 7;
string Arg3 = "110101010 10101010 1111010";
verify_case(n, Arg3, construct(Arg0, Arg1, Arg2));
}
n++;
// test_case_4
if ((Case == -1) || (Case == n)){
int Arg0 = 15;
int Arg1 = 17;
int Arg2 = 19;
string Arg3 = "000100101101111011000 11110111010011101010 100100001010101001010101000011111";
verify_case(n, Arg3, construct(Arg0, Arg1, Arg2));
}
n++;
// test_case_5
if ((Case == -1) || (Case == n)){
int Arg0 = 50;
int Arg1 = 50;
int Arg2 = 50;
string Arg3 = "11111111111111111111111111111111111111111111111111 11111111111111111111111111111111111111111111111111 11111111111111111111111111111111111111111111111111";
verify_case(n, Arg3, construct(Arg0, Arg1, Arg2));
}
n++;
}
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
ConstructLCS ___test;
___test.run_test(-1);
}
// END CUT HERE
<file_sep>/atcoder/arc_070/d.cpp
// D.
#include <iostream>
#include <algorithm>
#include <numeric>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <set>
#include <map>
using namespace std;
int main(int argc, char *argv[]) {
int N, K;
cin >> N >> K;
vector<int> A(N);
for (int i = 0; i < N; ++i) {
cin >> A[i];
}
int ans = 0;
if (K <= 400) {
for (int i = 0; i < N; ++i) {
int f[2][400] = { 1 };
int p = 0, q = 1;
for (int j = 0; j < N; ++j) {
if (i == j) {
continue;
}
int m = K - A[j];
for (int k = 0; k < K; ++k) {
if (f[p][k]) {
f[q][k] = 1;
if (k < m) {
f[q][k + A[j]] = 1;
}
}
}
p = !p, q = !q;
}
int u = accumulate(&(f[p][0]) + max(0, K - A[i]), &(f[p][0]) + K, 0);
if (!u) {
++ans;
}
}
}
cout << ans << endl;
return 0;
}
<file_sep>/atcoder/agc_017/a.cpp
// A.
#include <iostream>
#include <algorithm>
#include <sstream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long LL;
int main(int argc, char *argv[])
{
int n, p;
cin >> n >> p;
LL dp[2][2] = {1};
for (int i = 0; i < n; ++i) {
int a;
cin >> a;
if (a % 2) {
dp[(i % 2) ^ 1][0] = dp[i % 2][0] + dp[i % 2][1];
dp[(i % 2) ^ 1][1] = dp[i % 2][0] + dp[i % 2][1];
} else {
dp[(i % 2) ^ 1][0] = dp[i % 2][0] * 2;
dp[(i % 2) ^ 1][1] = dp[i % 2][1] * 2;
}
}
cout << dp[n % 2][p] << endl;
return 0;
}
|
df29c083387c6d2a6526a66c8b4fcd0f90bc4738
|
[
"C++"
] | 7 |
C++
|
phoenixstar7/topcoder
|
c564fef4e1a9859b75dd81c9f8bb834c33b76bc2
|
d2e19a65b26586d5a8a6bbcf3f60f5f13b820322
|
refs/heads/master
|
<file_sep>package callbacks;
/**
* Interface definition: CallbackServer.
*
* @author OpenORB Compiler
*/
public class _CallbackServerStub extends org.omg.CORBA.portable.ObjectImpl
implements CallbackServer
{
static final String[] _ids_list =
{
"IDL:callbacks/CallbackServer:1.0"
};
public String[] _ids()
{
return _ids_list;
}
private final static Class _opsClass = callbacks.CallbackServerOperations.class;
/**
* Operation sayHello
*/
public void sayHello()
{
while(true)
{
if (!this._is_local())
{
org.omg.CORBA.portable.InputStream _input = null;
try
{
org.omg.CORBA.portable.OutputStream _output = this._request("sayHello",true);
_input = this._invoke(_output);
return;
}
catch(org.omg.CORBA.portable.RemarshalException _exception)
{
continue;
}
catch(org.omg.CORBA.portable.ApplicationException _exception)
{
String _exception_id = _exception.getId();
throw new org.omg.CORBA.UNKNOWN("Unexpected User Exception: "+ _exception_id);
}
finally
{
this._releaseReply(_input);
}
}
else
{
org.omg.CORBA.portable.ServantObject _so = _servant_preinvoke("sayHello",_opsClass);
if (_so == null)
continue;
callbacks.CallbackServerOperations _self = (callbacks.CallbackServerOperations) _so.servant;
try
{
_self.sayHello();
return;
}
finally
{
_servant_postinvoke(_so);
}
}
}
}
/**
* Operation register
*/
public void register(callbacks.CallbackClient client)
{
while(true)
{
if (!this._is_local())
{
org.omg.CORBA.portable.InputStream _input = null;
try
{
org.omg.CORBA.portable.OutputStream _output = this._request("register",true);
callbacks.CallbackClientHelper.write(_output,client);
_input = this._invoke(_output);
return;
}
catch(org.omg.CORBA.portable.RemarshalException _exception)
{
continue;
}
catch(org.omg.CORBA.portable.ApplicationException _exception)
{
String _exception_id = _exception.getId();
throw new org.omg.CORBA.UNKNOWN("Unexpected User Exception: "+ _exception_id);
}
finally
{
this._releaseReply(_input);
}
}
else
{
org.omg.CORBA.portable.ServantObject _so = _servant_preinvoke("register",_opsClass);
if (_so == null)
continue;
callbacks.CallbackServerOperations _self = (callbacks.CallbackServerOperations) _so.servant;
try
{
_self.register( client);
return;
}
finally
{
_servant_postinvoke(_so);
}
}
}
}
}
<file_sep>package common;
import java.awt.Color;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.ArrayList;
import javax.swing.ImageIcon;
public interface ClientInterface extends Remote
{
public void printMessage(Message message) throws RemoteException;
public String giveYourName() throws RemoteException;
public void printClients(ArrayList<ClientInterface> clients) throws RemoteException;
public void ServerMessage(String message) throws RemoteException;
public ImageIcon getYourAvatar() throws RemoteException;
public Color giveColor() throws RemoteException;
}
<file_sep>package chat.impl;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.omg.CORBA.ORB;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;
import chat.ChatChannel;
import chat.ChatClient;
import chat.ChatServerPOA;
import chat.Message;
public class Server extends ChatServerPOA {
private ArrayList<ChatClient> clients;
private HashMap<ChatClient,String> clientsChannels;
public Server(String[] args)
{
try{
clients = new ArrayList<>();
clientsChannels = new HashMap<>();
ORB orb = ORB.init(args, null);
POA rootPOA = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
System.out.println(InetAddress.getLocalHost().getHostName());
byte[] id = rootPOA.activate_object(this);
org.omg.CORBA.Object ref = rootPOA.id_to_reference(id);
String ior = orb.object_to_string(ref);
System.out.println(ior);
PrintWriter writer = new PrintWriter("server_ior.txt");
writer.print(ior);
writer.close();
rootPOA.the_POAManager().activate();
orb.run();
}
catch (Exception e)
{
e.printStackTrace();
}
}
@Override
public void register(ChatClient client)
{
clients.add(client);
updateClients();
}
@Override
public void remove(ChatClient client)
{
clientsChannels.remove(client);
if(!clientsChannels.isEmpty())
updateClients();
}
private void updateClients()
{
String[] chans = getChannels();
for(String chan : chans)
{
ArrayList<ChatClient> clientsToSend = new ArrayList<>();
for(Map.Entry<ChatClient, String> entry : clientsChannels.entrySet())
{
if(entry.getValue().equals(chan))
clientsToSend.add(entry.getKey());
}
ChatClient[] st = new ChatClient[clientsToSend.size()];
for(ChatClient cli : clientsToSend)
{
cli.updateClientList(clientsToSend.toArray(st));
}
}
}
@Override
public void sendMessage(Message message)
{
if(message.isForAll())
{
for (Map.Entry<ChatClient, String> entry : clientsChannels.entrySet())
{
if(entry.getValue().equals(clientsChannels.get(message.getSender())))
{
entry.getKey().printMessage(message);
}
}
}
else
{
ArrayList<ChatClient> clis = new ArrayList<>(Arrays.asList(message.getTargets()));
for(ChatClient c : clientsChannels.keySet())
{
if(clis.contains(c) || c.equals(message.getSender()))
{
c.printMessage(message);
}
}
}
}
@Override
public void createChannel(ChatClient client, String name) {
// TODO Auto-generated method stub
}
@Override
public void joinChannel(ChatClient client, ChatChannel channel) {
// TODO Auto-generated method stub
}
@Override
public String[] getChannels() {
ArrayList<String> chans = new ArrayList<>();
for (String s : clientsChannels.values()) {
if(!chans.contains(s))
chans.add(s);
}
String[] str = new String[chans.size()];
return chans.toArray(str);
}
@Override
public void registerChannel(ChatClient client, String channel)
{
clientsChannels.put(client,channel);
updateClients();
}
public static void main(String[] args) {
new Server(args);
}
}
<file_sep>#Fri Apr 06 12:55:40 CEST 2018
org.eclipse.core.runtime=2
org.eclipse.platform=4.6.3.v20170301-0400
<file_sep>package mini_chat_udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class ClientUDP {
public ClientUDP() {
try {
InetAddress address = InetAddress.getByName("localhost");
DatagramSocket socket = new DatagramSocket();
byte[] buffer = "Bonjour serveur".getBytes();
DatagramPacket sendPacket = new DatagramPacket(buffer, buffer.length, address, ServerUDP.PORT);
buffer = new byte[256];
DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length, address, ServerUDP.PORT);
socket.send(sendPacket);
System.out.println("Waiting...");
socket.receive(receivePacket);
System.out.println(new String(receivePacket.getData()));
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
new ClientUDP();
}
}
<file_sep>package chat.impl;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JColorChooser;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import chat.ChatClient;
import chat.Message;
public class ClientGUY extends JFrame implements Observer
{
/**
*
*/
private static final long serialVersionUID = 1L;
private Client client;
private JTextPane pane;
private JTextField text;
private JList<ChatClient> group2;
private String name;
private ImageIcon image;
private String channel;
public ClientGUY(String[] args)
{
name = JOptionPane.showInputDialog(this,"What's your name ?");
Color color = JColorChooser.showDialog(null, "Give me a color", Color.BLACK);
if(name == null)
System.exit(0);
if(name.equals(""))
name = new String("Guest");
selectImage();
client = new Client(name, args,color,image);
selectChannel();
BuildUI();
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
setTitle("Client - "+name);
client.registerObserver(this);
}
private void selectChannel()
{
String[] channels = client.getChannelsFromServer();
ChannelFrame ch = new ChannelFrame(channels);
client.channel = ch.name;
}
private void selectImage()
{
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
try
{
image = new ImageIcon(ImageIO.read(file));
}
catch (IOException e)
{
e.printStackTrace();
}
}
else
{
image = null;
}
}
private void BuildUI()
{
getContentPane().setLayout(new BorderLayout());
text = new JTextField();
getContentPane().add(text, BorderLayout.SOUTH);
text.grabFocus();
JScrollPane scroll;
pane = new JTextPane();
pane.setEditable(false);
scroll = new JScrollPane(pane);
getContentPane().add(scroll, BorderLayout.CENTER);
group2 = new JList<>();
group2.setCellRenderer(new ClientCellRenderer());
scroll = new JScrollPane(group2);
scroll.setPreferredSize(new Dimension(200, 1000));
getContentPane().add(scroll, BorderLayout.EAST);
addListeners();
}
private void addListeners() {
text.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent ev) {
if (ev.getKeyCode() == KeyEvent.VK_ENTER)
{
if(!text.getText().equals(""))
{
ArrayList<ChatClient> tos = new ArrayList<>(group2.getSelectedValuesList());
Message message = client.createMessage(text.getText(),client.cref, tos);
client.sendMessage(message);
}
text.setText("");
text.grabFocus();
}
}
});
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
closeWindow();
}
});
}
private void closeWindow()
{
client.shutdown();
System.exit(0);
}
@Override
public void update(Message message)
{
try {
printToPane(pane, message);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
@SuppressWarnings("deprecation")
public void printToPane(JTextPane tp, Message message) throws BadLocationException
{
StyleContext sc = StyleContext.getDefaultStyleContext();
chat.Color col = message.getColor();
Color color = new Color(col.getR(), col.getG(), col.getB());
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, color);
aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);
Date date = new Date();
int len = tp.getDocument().getLength();
tp.setCaretPosition(len);
tp.setCharacterAttributes(aset, false);
if(message.isForAll())
tp.getDocument().insertString(len, date.getHours()+":"+date.getMinutes()+" "+message.getSender().getName()+" => "+message.getMessage()+"\n", aset);
else
{
ArrayList<String> names= new ArrayList<>();
for(ChatClient cliI : message.getTargets())
names.add(cliI.getName());
tp.getDocument().insertString(len, date.getHours()+":"+date.getMinutes()+" "+message.getSender().getName()+" to "+names+" => "+message.getMessage()+"\n", aset);
}
}
@Override
public void update(ChatClient[] clients)
{
group2.setListData(clients);
repaint();
}
@SuppressWarnings("deprecation")
@Override
public void update(String message)
{
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.black);
aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);
Date date = new Date();
int len = pane.getDocument().getLength();
pane.setCaretPosition(len);
pane.setCharacterAttributes(aset, false);
try {
pane.getDocument().insertString(len, date.getHours()+":"+date.getMinutes()+" SERVER => "+message+"\n", aset);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new ClientGUY(args);
}
}
<file_sep>package corba_chat.impl;
import java.io.BufferedReader;
import java.io.FileReader;
import org.omg.CORBA.ORB;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;
import corba_chat.ChatClient;
import corba_chat.ChatClientHelper;
import corba_chat.ChatClientPOA;
import corba_chat.ChatServer;
import corba_chat.ChatServerHelper;
public class ChatClientImpl extends ChatClientPOA {
private ChatClientFrame frm ;
private String userName ;
private ORB orb ;
private ChatClient stub ;
private ChatServer server ;
public ChatClientImpl(ChatClientFrame f, String userName, String[] args) {
frm = f ;
this.userName = userName ;
try {
// Initialisation et démarrage de l'ORB :
// l'appel ą orb.run() étant bloquant, on l'exécute dans un Thread.
orb = ORB.init(args, null) ;
Thread orbThread = new Thread(new Runnable() {
@Override
public void run() {
orb.run() ; // !!! bloquant !!! donc dans un thread
}
}) ;
orbThread.start() ;
// creation de la référence CORBA sur l'implémentation du client
POA rootPOA = POAHelper.narrow(orb.resolve_initial_references("RootPOA")) ;
rootPOA.the_POAManager().activate() ;
org.omg.CORBA.Object ref = rootPOA.servant_to_reference(this);
stub = ChatClientHelper.narrow(ref);
// lecture de l'IOR du serveur
BufferedReader br = new BufferedReader(new FileReader("server_ior.txt")) ;
String ior = br.readLine() ;
br.close() ;
// récupération de la référence sur le serveur (ą partir de son IOR)
org.omg.CORBA.Object o = orb.string_to_object(ior) ;
server = ChatServerHelper.narrow(o) ;
server.register(stub) ;
frm.setTitle(userName + " is connected") ;
} catch (Exception e) {
e.printStackTrace() ;
}
}
@Override
public void addMSG(String msg) {
System.out.println(userName + " adding msg : " + msg);
frm.appendMsg(msg) ;
}
public void sendToAll(String msg) {
try {
server.sendToAll(msg, stub) ;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void unRegister() {
try {
server.unRegister(stub) ;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public String getUserName() {
System.out.println(userName + " sending user name !");
return userName ;
}
@Override
public void updateConnectedUsers(String[] names) {
System.out.println(userName + " updating connected user names !");
frm.users.setListData(names) ;
}
}
<file_sep>package callbacks;
/**
* Holder class for : CallbackServer
*
* @author OpenORB Compiler
*/
final public class CallbackServerHolder
implements org.omg.CORBA.portable.Streamable
{
/**
* Internal CallbackServer value
*/
public callbacks.CallbackServer value;
/**
* Default constructor
*/
public CallbackServerHolder()
{ }
/**
* Constructor with value initialisation
* @param initial the initial value
*/
public CallbackServerHolder(callbacks.CallbackServer initial)
{
value = initial;
}
/**
* Read CallbackServer from a marshalled stream
* @param istream the input stream
*/
public void _read(org.omg.CORBA.portable.InputStream istream)
{
value = CallbackServerHelper.read(istream);
}
/**
* Write CallbackServer into a marshalled stream
* @param ostream the output stream
*/
public void _write(org.omg.CORBA.portable.OutputStream ostream)
{
CallbackServerHelper.write(ostream,value);
}
/**
* Return the CallbackServer TypeCode
* @return a TypeCode
*/
public org.omg.CORBA.TypeCode _type()
{
return CallbackServerHelper.type();
}
}
<file_sep>package chat;
/**
* chat/ChatClientPOA.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from chat.idl
* vendredi 23 mars 2018 10 h 33 CET
*/
public abstract class ChatClientPOA extends org.omg.PortableServer.Servant
implements chat.ChatClientOperations, org.omg.CORBA.portable.InvokeHandler
{
// Constructors
private static java.util.Hashtable _methods = new java.util.Hashtable ();
static
{
_methods.put ("getName", new java.lang.Integer (0));
_methods.put ("updateClientList", new java.lang.Integer (1));
_methods.put ("printMessage", new java.lang.Integer (2));
_methods.put ("getColor", new java.lang.Integer (3));
_methods.put ("shutdown", new java.lang.Integer (4));
_methods.put ("getImage", new java.lang.Integer (5));
}
public org.omg.CORBA.portable.OutputStream _invoke (String $method,
org.omg.CORBA.portable.InputStream in,
org.omg.CORBA.portable.ResponseHandler $rh)
{
org.omg.CORBA.portable.OutputStream out = null;
java.lang.Integer __method = (java.lang.Integer)_methods.get ($method);
if (__method == null)
throw new org.omg.CORBA.BAD_OPERATION (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE);
switch (__method.intValue ())
{
case 0: // chat/ChatClient/getName
{
String $result = null;
$result = this.getName ();
out = $rh.createReply();
out.write_string ($result);
break;
}
case 1: // chat/ChatClient/updateClientList
{
chat.ChatClient clients[] = chat.ChatClientPackage.clientsHelper.read (in);
this.updateClientList (clients);
out = $rh.createReply();
break;
}
case 2: // chat/ChatClient/printMessage
{
chat.Message message = chat.MessageHelper.read (in);
this.printMessage (message);
out = $rh.createReply();
break;
}
case 3: // chat/ChatClient/getColor
{
chat.Color $result = null;
$result = this.getColor ();
out = $rh.createReply();
chat.ColorHelper.write (out, $result);
break;
}
case 4: // chat/ChatClient/shutdown
{
this.shutdown ();
out = $rh.createReply();
break;
}
case 5: // chat/ChatClient/getImage
{
org.omg.CORBA.Any $result = null;
$result = this.getImage ();
out = $rh.createReply();
out.write_any ($result);
break;
}
default:
throw new org.omg.CORBA.BAD_OPERATION (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE);
}
return out;
} // _invoke
// Type-specific CORBA::Object operations
private static String[] __ids = {
"IDL:chat/ChatClient:1.0"};
public String[] _all_interfaces (org.omg.PortableServer.POA poa, byte[] objectId)
{
return (String[])__ids.clone ();
}
public ChatClient _this()
{
return ChatClientHelper.narrow(
super._this_object());
}
public ChatClient _this(org.omg.CORBA.ORB orb)
{
return ChatClientHelper.narrow(
super._this_object(orb));
}
} // class ChatClientPOA
<file_sep>package common;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.Date;
public interface Parrot extends Remote {
public void repeat(String msg) throws RemoteException;
public Date watTime() throws RemoteException;
public void register(ClientInterface client) throws RemoteException;
}
<file_sep>import java.awt.Color;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import common.ClientInterface;
import common.Message;
import common.ServerInterface;
public class Client implements ClientInterface
{
public ClientInterface stub;
public ServerInterface serv;
private String name;
private ImageIcon image;
public ArrayList<Observer> obs;
public Color color;
public Client(String name, ClientGUY clientGUY, ImageIcon image)
{
this.name = name;
this.image = image;
obs = new ArrayList<>();
color = Color.black;
obs.add(clientGUY);
try {
stub = (ClientInterface) UnicastRemoteObject.exportObject(this, 0) ;
serv = (ServerInterface) Naming.lookup("rmi://localhost/Server");
serv.register(stub);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void printMessage(Message message) throws RemoteException
{
notifyObservers(message);
}
private void notifyObservers(Message message)
{
try {
for(Observer o : obs)
o.update(message);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void sendMessage(Message message)
{
try
{
if(message.isForAll())
serv.sendMessageToAll(message);
else
{
serv.sendWhisper(message);
}
}
catch (RemoteException e)
{
e.printStackTrace();
}
}
@Override
public String giveYourName() throws RemoteException
{
return name;
}
public void registerObserver(Observer o)
{
obs.add(o);
}
public void shutdown()
{
try {
serv.remove(stub);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void printClients(ArrayList<ClientInterface> clients) throws RemoteException
{
for(Observer o : obs)
o.update(clients);
}
@Override
public void ServerMessage(String message) throws RemoteException
{
for(Observer o : obs)
o.update(message);
}
public ImageIcon getYourAvatar() throws RemoteException {
return image;
}
@Override
public Color giveColor() {
return color;
}
}
<file_sep>package chat;
/**
* chat/_ChatChannelStub.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from chat.idl
* vendredi 23 mars 2018 10 h 33 CET
*/
public class _ChatChannelStub extends org.omg.CORBA.portable.ObjectImpl implements chat.ChatChannel
{
// Type-specific CORBA::Object operations
private static String[] __ids = {
"IDL:chat/ChatChannel:1.0"};
public String[] _ids ()
{
return (String[])__ids.clone ();
}
private void readObject (java.io.ObjectInputStream s) throws java.io.IOException
{
String str = s.readUTF ();
String[] args = null;
java.util.Properties props = null;
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props);
try {
org.omg.CORBA.Object obj = orb.string_to_object (str);
org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate ();
_set_delegate (delegate);
} finally {
orb.destroy() ;
}
}
private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException
{
String[] args = null;
java.util.Properties props = null;
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props);
try {
String str = orb.object_to_string (this);
s.writeUTF (str);
} finally {
orb.destroy() ;
}
}
} // class _ChatChannelStub
<file_sep>import java.rmi.RemoteException;
import java.util.ArrayList;
import common.ClientInterface;
import common.Message;
public interface Observer
{
public void update(Message message) throws RemoteException;
public void update(ArrayList<ClientInterface> clients);
public void update(String message);
}
<file_sep>package universite;
/**
* universite/Fac.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from universite.ild
* vendredi 9 mars 2018 15 h 23 CET
*/
public interface Fac extends FacOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity
{
} // interface Fac
<file_sep>package chat.MessagePackage;
/**
* chat/MessagePackage/clientsHolder.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from chat.idl
* vendredi 23 mars 2018 10 h 33 CET
*/
public final class clientsHolder implements org.omg.CORBA.portable.Streamable
{
public chat.ChatClient value[] = null;
public clientsHolder ()
{
}
public clientsHolder (chat.ChatClient[] initialValue)
{
value = initialValue;
}
public void _read (org.omg.CORBA.portable.InputStream i)
{
value = chat.MessagePackage.clientsHelper.read (i);
}
public void _write (org.omg.CORBA.portable.OutputStream o)
{
chat.MessagePackage.clientsHelper.write (o, value);
}
public org.omg.CORBA.TypeCode _type ()
{
return chat.MessagePackage.clientsHelper.type ();
}
}
<file_sep>package tests_threads;
public class ThreadImplements implements Runnable{
private long delay;
public ThreadImplements(long delay)
{
this.delay = delay;
}
@Override
public void run()
{
for (int i = 0; i < 10; i++)
{
System.out.println(Thread.currentThread().getName()+" "+i);
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
Thread t1 = new Thread(new ThreadImplements(100)),
t2 = new Thread(new ThreadImplements(300));
t1.start();
t2.start();
}
}
<file_sep>import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.Date;
import common.ClientInterface;
import common.Parrot;
public class ParrotImpl implements Parrot
{
public ClientInterface client;
public ParrotImpl()
{
try
{
String name = "Guy";
Parrot stub = (Parrot)UnicastRemoteObject.exportObject(this,0);
Registry registry = LocateRegistry.createRegistry(1099);
registry.rebind(name, stub);
System.out.println("Guy is listening.");
}
catch(Exception e)
{
e.printStackTrace();
}
}
@Override
public void repeat(String msg) throws RemoteException {
System.out.println("Repeating "+msg);
}
@Override
public Date watTime() throws RemoteException {
Date date = new Date();
System.out.println("I'm giving the date "+date);
return date;
}
public static void main(String[] args) {
new ParrotImpl();
}
@Override
public void register(ClientInterface client) throws RemoteException
{
this.client = client;
client.showYourName();
}
}
<file_sep>package universite.application;
import java.io.BufferedReader;
import java.io.FileReader;
import org.omg.CORBA.ORB;
import universite.Etudiant;
import universite.Fac;
import universite.FacHelper;
import universite.EtudiantPackage.Resultat;
public class ClientUniversite {
public static void main(String[] args) throws Exception {
ORB orb = ORB.init(args, null) ;
BufferedReader br = new BufferedReader(new FileReader("ior.txt")) ;
String ior = br.readLine() ;
br.close() ;
org.omg.CORBA.Object o = orb.string_to_object(ior) ;
Fac fac = FacHelper.narrow(o) ;
fac.ajouterEtudiant("Guy");
fac.ajouterEtudiant("Billy");
fac.ajouterEtudiant("Jacky");
fac.ajouterEtudiant("Nicolas");
fac.ajouterEtudiant("Bertran");
fac.ajouterEtudiant("<NAME>");
for(Etudiant etu : fac.listerEtudiants())
{
System.out.println(etu.nom() +" -> "+etu.numCarte());
etu.ajouterNoteDans((int)(Math.random()*20), "Crypto");
etu.ajouterNoteDans((int)(Math.random()*20), "Anglais");
etu.ajouterNoteDans((int)(Math.random()*20), "SD");
etu.ajouterNoteDans((int)(Math.random()*20), "AA");
System.out.println("Moyenne : "+etu.moyenne());
System.out.println("Résultats : ");
for(Resultat r : etu.listeResultats())
{
System.out.println(r.matiere+" => "+r.note);
}
System.out.println("============================");
}
}
}
<file_sep>package multi_clients_theads;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
public class Client extends Thread{
private Socket socket;
private PrintWriter out;
private BufferedReader in;
private OutputStream outImage;
private InputStream inImage;
private ArrayList<Observer> observers;
public Client(String name)
{
try {
observers = new ArrayList<>();
socket = new Socket("localhost", Server.PORT);
out = new PrintWriter(socket.getOutputStream());
out.println(name);
out.flush();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.start();
} catch (IOException e) {
e.printStackTrace();
}
}
public Client(String name, byte[] imageSize, byte[] byteArray)
{
try {
observers = new ArrayList<>();
socket = new Socket("localhost", Server.PORT);
out = new PrintWriter(socket.getOutputStream());
out.println(name);
out.flush();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
outImage = socket.getOutputStream();
inImage = socket.getInputStream();
this.start();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMessage(String message)
{
out.println(message);
out.flush();
}
@Override
public void run()
{
try {
String message = new String();
while((message = in.readLine()) != null)
{
notifyObeservers(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void register(Observer o)
{
observers.add(o);
}
private void notifyObeservers(String message)
{
for(Observer o : observers)
o.update(message);
}
}
<file_sep>package chat;
/**
* chat/ColorPOA.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from chat.idl
* vendredi 23 mars 2018 10 h 33 CET
*/
public abstract class ColorPOA extends org.omg.PortableServer.Servant
implements chat.ColorOperations, org.omg.CORBA.portable.InvokeHandler
{
// Constructors
private static java.util.Hashtable _methods = new java.util.Hashtable ();
static
{
_methods.put ("getR", new java.lang.Integer (0));
_methods.put ("getG", new java.lang.Integer (1));
_methods.put ("getB", new java.lang.Integer (2));
}
public org.omg.CORBA.portable.OutputStream _invoke (String $method,
org.omg.CORBA.portable.InputStream in,
org.omg.CORBA.portable.ResponseHandler $rh)
{
org.omg.CORBA.portable.OutputStream out = null;
java.lang.Integer __method = (java.lang.Integer)_methods.get ($method);
if (__method == null)
throw new org.omg.CORBA.BAD_OPERATION (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE);
switch (__method.intValue ())
{
case 0: // chat/Color/getR
{
int $result = (int)0;
$result = this.getR ();
out = $rh.createReply();
out.write_long ($result);
break;
}
case 1: // chat/Color/getG
{
int $result = (int)0;
$result = this.getG ();
out = $rh.createReply();
out.write_long ($result);
break;
}
case 2: // chat/Color/getB
{
int $result = (int)0;
$result = this.getB ();
out = $rh.createReply();
out.write_long ($result);
break;
}
default:
throw new org.omg.CORBA.BAD_OPERATION (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE);
}
return out;
} // _invoke
// Type-specific CORBA::Object operations
private static String[] __ids = {
"IDL:chat/Color:1.0"};
public String[] _all_interfaces (org.omg.PortableServer.POA poa, byte[] objectId)
{
return (String[])__ids.clone ();
}
public Color _this()
{
return ColorHelper.narrow(
super._this_object());
}
public Color _this(org.omg.CORBA.ORB orb)
{
return ColorHelper.narrow(
super._this_object(orb));
}
} // class ColorPOA
<file_sep>package chat;
/**
* chat/MessagePOA.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from chat.idl
* vendredi 23 mars 2018 10 h 33 CET
*/
public abstract class MessagePOA extends org.omg.PortableServer.Servant
implements chat.MessageOperations, org.omg.CORBA.portable.InvokeHandler
{
// Constructors
private static java.util.Hashtable _methods = new java.util.Hashtable ();
static
{
_methods.put ("getSender", new java.lang.Integer (0));
_methods.put ("isForAll", new java.lang.Integer (1));
_methods.put ("getTargets", new java.lang.Integer (2));
_methods.put ("getMessage", new java.lang.Integer (3));
_methods.put ("getColor", new java.lang.Integer (4));
}
public org.omg.CORBA.portable.OutputStream _invoke (String $method,
org.omg.CORBA.portable.InputStream in,
org.omg.CORBA.portable.ResponseHandler $rh)
{
org.omg.CORBA.portable.OutputStream out = null;
java.lang.Integer __method = (java.lang.Integer)_methods.get ($method);
if (__method == null)
throw new org.omg.CORBA.BAD_OPERATION (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE);
switch (__method.intValue ())
{
case 0: // chat/Message/getSender
{
chat.ChatClient $result = null;
$result = this.getSender ();
out = $rh.createReply();
chat.ChatClientHelper.write (out, $result);
break;
}
case 1: // chat/Message/isForAll
{
boolean $result = false;
$result = this.isForAll ();
out = $rh.createReply();
out.write_boolean ($result);
break;
}
case 2: // chat/Message/getTargets
{
chat.ChatClient $result[] = null;
$result = this.getTargets ();
out = $rh.createReply();
chat.MessagePackage.clientsHelper.write (out, $result);
break;
}
case 3: // chat/Message/getMessage
{
String $result = null;
$result = this.getMessage ();
out = $rh.createReply();
out.write_string ($result);
break;
}
case 4: // chat/Message/getColor
{
chat.Color $result = null;
$result = this.getColor ();
out = $rh.createReply();
chat.ColorHelper.write (out, $result);
break;
}
default:
throw new org.omg.CORBA.BAD_OPERATION (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE);
}
return out;
} // _invoke
// Type-specific CORBA::Object operations
private static String[] __ids = {
"IDL:chat/Message:1.0"};
public String[] _all_interfaces (org.omg.PortableServer.POA poa, byte[] objectId)
{
return (String[])__ids.clone ();
}
public Message _this()
{
return MessageHelper.narrow(
super._this_object());
}
public Message _this(org.omg.CORBA.ORB orb)
{
return MessageHelper.narrow(
super._this_object(orb));
}
} // class MessagePOA
<file_sep>package chat;
/**
* chat/ChatClientOperations.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from chat.idl
* vendredi 23 mars 2018 10 h 33 CET
*/
public interface ChatClientOperations
{
String getName ();
void updateClientList (chat.ChatClient[] clients);
void printMessage (chat.Message message);
chat.Color getColor ();
void shutdown ();
org.omg.CORBA.Any getImage ();
} // interface ChatClientOperations
<file_sep>package chat;
/**
* chat/ColorHolder.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from chat.idl
* vendredi 23 mars 2018 10 h 33 CET
*/
public final class ColorHolder implements org.omg.CORBA.portable.Streamable
{
public chat.Color value = null;
public ColorHolder ()
{
}
public ColorHolder (chat.Color initialValue)
{
value = initialValue;
}
public void _read (org.omg.CORBA.portable.InputStream i)
{
value = chat.ColorHelper.read (i);
}
public void _write (org.omg.CORBA.portable.OutputStream o)
{
chat.ColorHelper.write (o, value);
}
public org.omg.CORBA.TypeCode _type ()
{
return chat.ColorHelper.type ();
}
}
<file_sep>package chat;
/**
* chat/_ChatServerStub.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from chat.idl
* vendredi 23 mars 2018 10 h 33 CET
*/
public class _ChatServerStub extends org.omg.CORBA.portable.ObjectImpl implements chat.ChatServer
{
public void register (chat.ChatClient client)
{
org.omg.CORBA.portable.InputStream $in = null;
try {
org.omg.CORBA.portable.OutputStream $out = _request ("register", true);
chat.ChatClientHelper.write ($out, client);
$in = _invoke ($out);
return;
} catch (org.omg.CORBA.portable.ApplicationException $ex) {
$in = $ex.getInputStream ();
String _id = $ex.getId ();
throw new org.omg.CORBA.MARSHAL (_id);
} catch (org.omg.CORBA.portable.RemarshalException $rm) {
register (client );
} finally {
_releaseReply ($in);
}
} // register
public void registerChannel (chat.ChatClient client, String channel)
{
org.omg.CORBA.portable.InputStream $in = null;
try {
org.omg.CORBA.portable.OutputStream $out = _request ("registerChannel", true);
chat.ChatClientHelper.write ($out, client);
$out.write_string (channel);
$in = _invoke ($out);
return;
} catch (org.omg.CORBA.portable.ApplicationException $ex) {
$in = $ex.getInputStream ();
String _id = $ex.getId ();
throw new org.omg.CORBA.MARSHAL (_id);
} catch (org.omg.CORBA.portable.RemarshalException $rm) {
registerChannel (client, channel );
} finally {
_releaseReply ($in);
}
} // registerChannel
public void remove (chat.ChatClient client)
{
org.omg.CORBA.portable.InputStream $in = null;
try {
org.omg.CORBA.portable.OutputStream $out = _request ("remove", true);
chat.ChatClientHelper.write ($out, client);
$in = _invoke ($out);
return;
} catch (org.omg.CORBA.portable.ApplicationException $ex) {
$in = $ex.getInputStream ();
String _id = $ex.getId ();
throw new org.omg.CORBA.MARSHAL (_id);
} catch (org.omg.CORBA.portable.RemarshalException $rm) {
remove (client );
} finally {
_releaseReply ($in);
}
} // remove
public void sendMessage (chat.Message message)
{
org.omg.CORBA.portable.InputStream $in = null;
try {
org.omg.CORBA.portable.OutputStream $out = _request ("sendMessage", true);
chat.MessageHelper.write ($out, message);
$in = _invoke ($out);
return;
} catch (org.omg.CORBA.portable.ApplicationException $ex) {
$in = $ex.getInputStream ();
String _id = $ex.getId ();
throw new org.omg.CORBA.MARSHAL (_id);
} catch (org.omg.CORBA.portable.RemarshalException $rm) {
sendMessage (message );
} finally {
_releaseReply ($in);
}
} // sendMessage
public void createChannel (chat.ChatClient client, String name)
{
org.omg.CORBA.portable.InputStream $in = null;
try {
org.omg.CORBA.portable.OutputStream $out = _request ("createChannel", true);
chat.ChatClientHelper.write ($out, client);
$out.write_string (name);
$in = _invoke ($out);
return;
} catch (org.omg.CORBA.portable.ApplicationException $ex) {
$in = $ex.getInputStream ();
String _id = $ex.getId ();
throw new org.omg.CORBA.MARSHAL (_id);
} catch (org.omg.CORBA.portable.RemarshalException $rm) {
createChannel (client, name );
} finally {
_releaseReply ($in);
}
} // createChannel
public void joinChannel (chat.ChatClient client, chat.ChatChannel channel)
{
org.omg.CORBA.portable.InputStream $in = null;
try {
org.omg.CORBA.portable.OutputStream $out = _request ("joinChannel", true);
chat.ChatClientHelper.write ($out, client);
chat.ChatChannelHelper.write ($out, channel);
$in = _invoke ($out);
return;
} catch (org.omg.CORBA.portable.ApplicationException $ex) {
$in = $ex.getInputStream ();
String _id = $ex.getId ();
throw new org.omg.CORBA.MARSHAL (_id);
} catch (org.omg.CORBA.portable.RemarshalException $rm) {
joinChannel (client, channel );
} finally {
_releaseReply ($in);
}
} // joinChannel
public String[] getChannels ()
{
org.omg.CORBA.portable.InputStream $in = null;
try {
org.omg.CORBA.portable.OutputStream $out = _request ("getChannels", true);
$in = _invoke ($out);
String $result[] = chat.ChatServerPackage.channelsHelper.read ($in);
return $result;
} catch (org.omg.CORBA.portable.ApplicationException $ex) {
$in = $ex.getInputStream ();
String _id = $ex.getId ();
throw new org.omg.CORBA.MARSHAL (_id);
} catch (org.omg.CORBA.portable.RemarshalException $rm) {
return getChannels ( );
} finally {
_releaseReply ($in);
}
} // getChannels
// Type-specific CORBA::Object operations
private static String[] __ids = {
"IDL:chat/ChatServer:1.0"};
public String[] _ids ()
{
return (String[])__ids.clone ();
}
private void readObject (java.io.ObjectInputStream s) throws java.io.IOException
{
String str = s.readUTF ();
String[] args = null;
java.util.Properties props = null;
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props);
try {
org.omg.CORBA.Object obj = orb.string_to_object (str);
org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate ();
_set_delegate (delegate);
} finally {
orb.destroy() ;
}
}
private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException
{
String[] args = null;
java.util.Properties props = null;
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props);
try {
String str = orb.object_to_string (this);
s.writeUTF (str);
} finally {
orb.destroy() ;
}
}
} // class _ChatServerStub
<file_sep>package multi_clients_theads;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.ByteBuffer;
import javax.imageio.ImageIO;
public class ClientRunnable implements Runnable {
private Socket client;
private Server server;
private String name;
private BufferedReader in;
private InputStream inImage;
private PrintWriter out;
private BufferedImage outImage;
public ClientRunnable(Socket socket, Server server) {
client = socket;
this.server = server;
try {
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
inImage = client.getInputStream();
name = in.readLine();
// image = ImageIO.read(new ByteArrayInputStream(imageAr));
// System.out.println("Received " + image.getHeight() + "x" + image.getWidth());
out = new PrintWriter(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try
{
String message = new String();
while((message = in.readLine()) != null)
{
server.sendMessage("%from%"+name+"%/from%"+message);
}
}
catch (IOException e)
{
System.out.println("C'est la merde putain");
}
finally
{
System.out.println("Client deconnected");
server.removeClient(this);
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void sendMessage(String message)
{
out.println(message);
out.flush();
}
public String getName()
{
return name;
}
}
<file_sep>package accumulator_impl;
import accumulator.AccumulatorPOA;
public class AccumulatorImpl extends AccumulatorPOA
{
private int total;
public AccumulatorImpl()
{
total = 0;
}
@Override
public void add(int number)
{
total += number;
System.out.println("Total : "+total);
}
}
<file_sep>package chat;
/**
* chat/ChatServerPOA.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from chat.idl
* vendredi 23 mars 2018 10 h 33 CET
*/
public abstract class ChatServerPOA extends org.omg.PortableServer.Servant
implements chat.ChatServerOperations, org.omg.CORBA.portable.InvokeHandler
{
// Constructors
private static java.util.Hashtable _methods = new java.util.Hashtable ();
static
{
_methods.put ("register", new java.lang.Integer (0));
_methods.put ("registerChannel", new java.lang.Integer (1));
_methods.put ("remove", new java.lang.Integer (2));
_methods.put ("sendMessage", new java.lang.Integer (3));
_methods.put ("createChannel", new java.lang.Integer (4));
_methods.put ("joinChannel", new java.lang.Integer (5));
_methods.put ("getChannels", new java.lang.Integer (6));
}
public org.omg.CORBA.portable.OutputStream _invoke (String $method,
org.omg.CORBA.portable.InputStream in,
org.omg.CORBA.portable.ResponseHandler $rh)
{
org.omg.CORBA.portable.OutputStream out = null;
java.lang.Integer __method = (java.lang.Integer)_methods.get ($method);
if (__method == null)
throw new org.omg.CORBA.BAD_OPERATION (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE);
switch (__method.intValue ())
{
case 0: // chat/ChatServer/register
{
chat.ChatClient client = chat.ChatClientHelper.read (in);
this.register (client);
out = $rh.createReply();
break;
}
case 1: // chat/ChatServer/registerChannel
{
chat.ChatClient client = chat.ChatClientHelper.read (in);
String channel = in.read_string ();
this.registerChannel (client, channel);
out = $rh.createReply();
break;
}
case 2: // chat/ChatServer/remove
{
chat.ChatClient client = chat.ChatClientHelper.read (in);
this.remove (client);
out = $rh.createReply();
break;
}
case 3: // chat/ChatServer/sendMessage
{
chat.Message message = chat.MessageHelper.read (in);
this.sendMessage (message);
out = $rh.createReply();
break;
}
case 4: // chat/ChatServer/createChannel
{
chat.ChatClient client = chat.ChatClientHelper.read (in);
String name = in.read_string ();
this.createChannel (client, name);
out = $rh.createReply();
break;
}
case 5: // chat/ChatServer/joinChannel
{
chat.ChatClient client = chat.ChatClientHelper.read (in);
chat.ChatChannel channel = chat.ChatChannelHelper.read (in);
this.joinChannel (client, channel);
out = $rh.createReply();
break;
}
case 6: // chat/ChatServer/getChannels
{
String $result[] = null;
$result = this.getChannels ();
out = $rh.createReply();
chat.ChatServerPackage.channelsHelper.write (out, $result);
break;
}
default:
throw new org.omg.CORBA.BAD_OPERATION (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE);
}
return out;
} // _invoke
// Type-specific CORBA::Object operations
private static String[] __ids = {
"IDL:chat/ChatServer:1.0"};
public String[] _all_interfaces (org.omg.PortableServer.POA poa, byte[] objectId)
{
return (String[])__ids.clone ();
}
public ChatServer _this()
{
return ChatServerHelper.narrow(
super._this_object());
}
public ChatServer _this(org.omg.CORBA.ORB orb)
{
return ChatServerHelper.narrow(
super._this_object(orb));
}
} // class ChatServerPOA
<file_sep>package common;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface ServerInterface extends Remote
{
public void register(ClientInterface client) throws RemoteException;
public void sendMessageToAll(Message message) throws RemoteException;
public void remove(ClientInterface client) throws RemoteException;
public void sendWhisper(Message message) throws RemoteException;
}
|
1162a25ceb43cf95ace242b8913a565d0b8be596
|
[
"Java",
"INI"
] | 28 |
Java
|
CamilleINGOUF/SystemesDistribues
|
9214976bed066adf3337eda1757a2140946c9886
|
b8d6002dbbfe1d56f5e8ce5e14c4eacb61641aee
|
refs/heads/master
|
<repo_name>malder85/-_-<file_sep>/classwork/chess.py
class Piece:
def __init__(self, color, place):
self.color = color
self.place = place
self.moves = []
self.takes = []
self.target = ""
def __repr__(self):
return f"----------------\n" \
f"color: {self.color}\n" \
f"place:{self.place}\n" \
f"target:{self.target}\n" \
f"moves:{self.moves}\n" \
f"takes:{self.takes}\n" \
f"----------------"
def get_moves(self):
raise Exception("must override in child class")
def get_takes(self):
raise Exception("must override in child class")
def new_target(self):
raise Exception("must override in child class")
class Pawn(Piece):
def __init__(self, color, place):
super().__init__(color, place)
self.moves = self.get_moves()
self.takes = self.get_takes()
self.target = self.new_target()
def get_moves(self):
place_number = int(self.place[-1])
if self.color == "white":
new_place = self._get_cell_up(self.place) if place_number < 8 else self.place
else:
new_place = self._get_cell_down(self.place) if place_number > 1 else self.place
return [new_place]
def _get_cell_up(self, place):
place_number = int(place[-1])
new_number = place_number + 1
new_place = place.replace(str(place_number), str(new_number))
return new_place
def _get_cell_down(self, place):
place_number = int(place[-1])
new_number = place_number - 1
new_place = place.replace(str(place_number), str(new_number))
return new_place
def _get_cell_left(self, place):
place_symbol = place[0]
new_symbol = chr(ord(place_symbol) - 1)
new_place = place.replace(place_symbol, new_symbol)
return new_place
def _get_cell_right(self, place):
place_symbol = place[0]
new_symbol = chr(ord(place_symbol) + 1)
new_place = place.replace(place_symbol, new_symbol)
return new_place
def get_takes(self):
takes = []
place_symbol = self.place[0]
place_number = int(self.place[-1])
if self.color == "white":
new_number = place_number + 1 if place_number < 8 else place_number
if place_symbol != "A":
left_symbol = chr(ord(place_symbol) - 1)
left_place = self.place.replace(place_symbol, left_symbol)
new_place = left_place.replace(str(place_number), str(new_number))
takes.append(new_place)
if place_symbol != "H":
right_symbol = chr(ord(place_symbol) + 1)
right_place = self.place.replace(place_symbol, right_symbol)
new_place = right_place.replace(str(place_number), str(new_number))
takes.append(new_place)
return takes
def new_target(self):
return "A1"
class Queen(Piece):
def __init__(self, color, place):
super().__init__(color, place)
self.moves = self.get_moves()
self.takes = self.get_takes()
self.target = self.new_target()
def get_moves(self):
return []
def get_takes(self):
return []
def new_target(self):
return "A1"
pawn = Pawn('white', 'E2')
print(pawn)
<file_sep>/classwork/7work.py
# позиционное использование
# points_tuple = ((1, 2), (-2, 4), (0, -6))
# print(points_tuple[0])
# использование по имени
points_dict = {"A": (1, 2),
"B": (-2, 4),
"C": (0, -6)}
print(points_dict["A"])
# добавляем еще одну точку (point_D)
point_D = (3, 5)
points_dict["D"] = point_D
points_dict.update({"D1": point_D})
# d2 = {"D2": point_D}
# points_dict.update(d2)
# print(points_dict)
test_point = (5, 7)
if points_dict.get("D2") is None:
points_dict["D2"] = test_point
print((points_dict))
value = points_dict["A"]
print((value))
for key in points_dict:
print(key, points_dict[key])
print(list(points_dict.keys()))
print(list(points_dict.values()))
<file_sep>/classwork/levelup.py
# import calendar
# print(calendar.month(2020, 9))
# a = "geeksforgeeks"
#
# b = list(a)
# print(b)
# print((1 + 3)**2)
# print("hello \"world\"")
#
# print(input("what is your name? : "))
# a = input("Введите первое число : ")
# b = input("Введите второе число : ")
# print(int(a) + int(b))
# name = input('Ваше имя? : ')
# print(list(name))
# name = input('Введите ваше имя: ' )
# count = input('Сколько раз вывести Ваше имя?: ' )
#
# print( name * int(count ))
# name = input("Как тебя зовут, друг? : ")
# print ("Пошёл ты нахуй, " + name)
# test = "string"
# test2 = 3
# print(test * test2)
# a = 55
# a-=25
# print(a)
password = input("Введи пароль, дорогуша: ")
if password == "123":
print("Верный пароль, милости просим))")
pogoda = input("Какая погода?(жарко, снег, дождь): ")
time = input("Время суток(утро, день, вечер, ночь): ")
print("Привет")
if pogoda == "снег":
print("Одевайся теплее, на улице идет снег")
if time == "Утро":
print("Позавтракала хоть?")
elif time == "ночь":
print("Красиво, когда ночью идёт снег")
else:
print("И гуляй на здоровье")
if pogoda == "дождь":
print("Возьми зонт, на улице дождь")
if time == "ночь":
print("Ночью, в дождь, не стоит идти")
elif time == "Утро":
print("Позавтракала хоть?")
else:
print("И гуляй на здоровье")
if pogoda == "жарко":
print("На улице жара")
if time == "ночь":
print("Днем будет вообще жопа")
elif time == "утро":
print("Кушать и на пляж?")
elif time == "вечер":
print("Срочно пивка холодненького!")
else:
print("Лучше поспать под кондёром")
print("Удачи")
else:
print("Пароль не верный. Давай, досвиданья!")
<file_sep>/Homework/homework5.py
# 2. Дано целое число (int). Определить сколько нулей в конце этого числа.
numb = 251026000
numb_str = str(numb)
numb_str = numb_str[::-1]
my_list = []
x = 0
for symbol in numb_str:
if symbol == "0":
my_list.append(symbol)
else:
break
my_result = my_list.count("0")
print(my_result)
######################################################
# 3. Даны списки my_list_1 и my_list_2. Создать список my_result в который вначале поместить четные элементы
# из my_list_1 и потом нечетные элементы из my_list_2.
my_list_1 = ["qwerty"]
my_list_2 = ["asdfgh"]
my_result = []
for symbol in my_list_1:
my_result.append(symbol[::2])
for symbol in my_list_2:
my_result.append(symbol[1::2])
print(my_result)
#####################################################
# 4. Дан список my_list.Создать список new_list у которого первый элемент из my_list стоит на последнем месте.Если
# my_list[1, 2, 3, 4], то new_list[2, 3, 4, 1]
my_list = [1, 2, 3, 4]
new_list = []
new_list = my_list
new_list.append(new_list.pop(0))
print(new_list)
######################################################
# 5.Дан список my_list. В ЭТОМ списке первый элемент переставить на последнее место. [1,2,3,4] -> [2,3,4,1].
# Пересоздавать список нельзя!
my_list = [1, 2, 3, 4]
for symbol in my_list:
my_list.insert(4, 1)
my_list.remove(1)
break
print(my_list)
######################################################
# 7. Дана строка my_str. Разделите эту строку на пары из двух символов и поместите эти пары в список. Если строка
# содержит нечетное количество символов, пропущенный второй символ последней пары должен быть заменен
# подчеркиванием ('_'). Примеры: 'abcd' -> ['ab', 'cd'], 'abc' -> ['ab', 'c_']
my_str = "abc"
len_my_str = int(len(my_str))
my_str1 = f"['{my_str[0:2]}', '{my_str[2:]}']"
my_str2 = f"['{my_str[0:2]}', '{my_str[2:]}_']"
if len_my_str % 2 == 0:
print(my_str1)
else:
print(my_str2)
#######################################################
# 8. Дана строка my_str в которой символы не повторяются и два символа l_limit, r_limit, которые точно находятся
# в этой строке. Причем l_limit левее чем r_limit. В переменную sub_str поместить часть строки между этими символами.
# my_str = "My_long str", l_limit = "o", r_limit = "t" -> sub_str = "ng s"
my_str = "My_long str"
l_limit = my_str.find("o")
r_limit = my_str.find("t")
sub_str = my_str[l_limit + 1: r_limit]
print(sub_str)
<file_sep>/classwork/homework9.py
# 1) функции передаем полный путь к файлу в виде строки в формате "./path/to/file/filename.ext",
# где точка означает текущую директорию.
# (Это универсальный способ задать путь. Пользователи виндовс можете почитать это:
# https://stackoverflow.com/questions/2953834/windows-path-in-python)
# Функция возвращает два параметра: название файла и путь к папке.
# Пример использования:
# filename, folder_path = first_function(path)
#
import os
def name_and_path(path):
full_path = os.path.join(name, path)
result = name_and_path("C:\\Users\\User\\PycharmProjects\\-_-\\classwork\\classwork10.py")
#######################################################
# 2) функции передаем полный путь к папке в виде строки в формате "./path/to/folder",
# где точка означает текущую директорию.
# Функция возвращает список ФАЙЛОВ из этой папки. Т.к. listdir возвращает файлы и подпапки,
# то такой функционал иногда нужен.
# Напомню, что есть метод os.path.isfile(path) который возвращает True, если path указывает на файл.
# И обратите внимание на "Щелчек Таноса" из классной работы. Мы там склеиваем путь с помощью os.path.join()
# Пример использования:
# files = second_function(path)
# Значение по умолчанию - текущая папка. Т.е. second_function() вернет файлы из текущей папки.
# import os
# def get_files(path):
# files = []
# values = os.listdir(path)
# for value in values:
# full_path = os.path.join(path, value)
# if os.path.isfile(full_path):
# files.append(full_path)
# return files
#
# results = get_files("C:\\Users\\User\\PycharmProjects\\-_-\\classwork")
#####################################################
# 3) функции передаем полный путь к папке в виде строки в формате "./path/to/folder",
# где точка означает текущую директорию.
# Функция возвращает СЛОВАРЬ в формате: {"files": [список ФАЙЛОВ из папки], "folders": [список ПОДПАПОК из папки]}.
# Пример использования:
# path_dict = third_function(path)
# Значение по умолчанию - текущая папка. Т.е. third_function() вернет словарь с файлами и подпапками из текущей папки.
# def ret_dict<file_sep>/classwork/classwork9.py
# def modify_string_and_print(my_string: str, symbol="*", number=3):
# my_string = f"{symbol * number}{my_string}{symbol * number}"
# print(my_string)
# return (my_string)
#
# def create_lines_under_above_string(my_string, symbol="*"):
# add_str = symbol * len(my_string)
# new_str = f"{add_str}\n{my_string}\n{add_str}"
# print(new_str)
# mod_str = modify_string_and_print(("Some string"))
#
# create_lines_under_above_string(mod_str, "#")
# modify_string_and_print("Some string")
# modify_string_and_print("Some string", "$")
# modify_string_and_print("Some string", "%", 5)
# modify_string_and_print(number=5, my_string="Some string", symbol=".")
# def my_func(*args, **kwargs):
# print(args)
# print(kwargs)
#
# my_func(1, "234", (1, 3, 4), {"qwe": 1, "asd": 4}, qwe=1, asd=4)
# file = open("README.md", 'r')
# lines = file.read()
# print(lines)
# file.close()
#
# with open("README.md", 'r') as file:
# lines = file.read()
# print(lines)
# print("Hello")
#
# with open('test.txt', 'w') as file:
# file.write('Hello!')
# file.writelines(["asd", 'sdf'])
import os
def create_folder(path):
try:
os.mkdir(path)
except FileExistsError:
pass
def save_file(filename, path, data):
filename_with_pat = os.path.join(path, filename)
with open(filename_with_pat, 'w') as file:
file.write(data)
create_folder('tmp')
alphabet = [chr(numb) for numb in range(ord('a'), ord('z') + 1)]
print(alphabet)
alphabet = "".join(alphabet)
print(alphabet)
save_string_to_file('alphabet.txt', 'tmp', alphabet)
for symbol in alphabet:
save_string_to_file(f'{symbol}.txt', 'tmp', alphabet.replace((symbol, symbol.upper())))
<file_sep>/classwork/newfile.py
# def add(num1, num2=1):
# sum = num1 + num2
# return sum
# result = add(3, 4)
# print(result)
# result_new = add(10, 5)
# print(result_new)
import os
res = os.listdir()
print(res)<file_sep>/classwork/utils.py
def get_distance(point_1, point_2) -> float:
distance = ((point_2[0] - point_1[0]) ** 2 + (point_2[1] - point_1[1]) ** 2) ** 0.5
return distance
def get_area_gerone(point_1, point_2, point_3) -> float:
a = get_distance(point_1, point_2)
b = get_distance(point_1, point_3)
c = get_distance(point_2, point_3)
p = (a + b + c) / 2
area = (p * (p - a) * (p - b) * (p - c)) ** 0.5
return area
if __name__ == "__main__":
assert abs(get_distance((0, 4), (3, 0)) - 5.0) < 0.01
print("OK")<file_sep>/Homework/homework7.py
# 1) Создать список из 20 случайных целых чисел в диапазоне от 1 до 100.
# Задание можно выполнить и через обычный цикл и через генератор списков.
import random
result = []
cnt = 0
while cnt != 20:
random_list = random.randrange(1, 100)
result.append(random_list)
cnt += 1
print(result)
################################################################
# 3) Создать функцию my_print, которая принимает строку и печатает ее
# с тремя символами * вначале и в конце строки.
# Пример:
# my_str = 'I'm the string'
# Печатает ***I'm the string***
def my_print(val):
print(f"***{val}***")
return val
my_print("I'm the string")
#################################################################
# 4)Создать функцию my_print, которая принимает строку и печатает ее
# с символами * НАД и ПОД строкой. КОЛИЧЕСТВО СИМВОЛОВ * РАВНО КОЛИЧЕСТВУ СИМВОЛОВ В СТРОКЕ
# Пример:
# my_str = 'I'm the string'
# Печатает
# **************
# I'm the string
# **************
def my_print(val):
val = str(val)
print(f"{len(val) * '*'}")
print(f"{val}")
print(f"{len(val) * '*'}")
return val
my_print("I'm the string")
##################################################################
# 5) То же, что 4, но ответ должен выглядеть так:
# ********************
# ***I'm the string***
# ********************
def my_print(val):
val = str(val)
val = f"{'***'}{val}{'***'}"
print(f"{len(val) * '*'}")
print(f"{val}")
print(f"{len(val) * '*'}")
return val
my_print("I'm the string")
<file_sep>/Homework/homework6.py
# 1. Дан список строк my_list. Создать новый список в который поместить
# элементы из my_list по следующему правилу:
# Если строка стоит на нечетном месте в my_list, то ее заменить на
# перевернутую строку. "qwe" на "ewq".
# Если на четном - оставить без изменения.
# Задание сделать с использованием enumerate.
my_list = ["qwe", "123", "asd", "zxc"]
my_list_new = []
for index, value in enumerate(my_list):
if index % 2:
my_list_new.append(value[::-1])
else:
my_list_new.append(value)
print(my_list_new)
#######################################################
# 4. Дан список my_list в котором могум быть как строки так и целые числа.
# Создать новый список в который поместить только строки из my_list.
my_list = ["qwerty", 12345, "asdfg", 67890]
my_list_new = []
for index, value in enumerate(my_list):
if type(value) == str:
my_list_new.append(value)
else:
pass
print(my_list_new)
#########################################################
# 5. Дана строка my_str. Вывести символы, которые встречаются в строке только один раз.
my_str = "qweoppiuytrewasdfghjkllkjgfxcvbnmmnbvcxz"
my_set = set(my_str)
for value in my_set:
print(value)
#########################################################
# 6. Даны две строки, вывести те символы, которые есть в обеих строках.
my_str_1 = "1234567890qwertyzxcvbnm, +-*/"
my_str_2 = "13579asdfghjkl;'+*zxcbnm,./"
set_1 = set(my_str_1)
set_2 = set(my_str_2)
uniq_set = set_1.intersection(set_2)
print(uniq_set)
##########################################################
# 8. Описать с помощью словаря следующую структуру для конкретного человека (можно придумать):
# Фамилия
# Имя
# Возраст
# Проживание
# Страна
# Город
# Улица
# Работа
# Наличие
# Должность
person = {"Фамилия": "Шаповалов",
"Имя": "Сергей",
"Возраст": 35,
"Проживание": {
"Страна": "Украина",
"Город": "Днепр",
"Улица": "Свердлова",
},
"Работа": {
"Наличие": "Да",
"Должность": "Водитель"
}
}
print(person)
##########################################################
# 9. Описать с помощью словаря следующую структуру (рецепт ненастоящего торта, придумать и указать граммы для продуктов):
tortik = {"Коржи": {
"Мука": 500,
"Молоко": 300,
"Масло": 150,
"Яйцо": 6,
},
"Крем": {
"Сахар": 250,
"Масло": 100,
"Ваниль": 20,
"Сметана": 600,
},
"Глазурь": {
"Какао": 80,
"Сахар": 100,
"Масло": 50,
}
}
print(tortik)
<file_sep>/Homework/work4.py
# value = [1,2,3,4,5]
# value = tuple(value)
# print(type(value))
# values = [1, 2, 3, 4, 5]
# result = []
# for value in values[::-1]:
# result.append(value)
# print(result)
# values = [1, 2, 3, 4, 5]
# new_value = values
# new_value.append(6)
# print(values)
# values = [0] * 6
# values[0] = 1
# print(values)
# value = 0
# values = [value] * 6
# value = 1
# print(values)
# my_list = [0]
# values = [my_list.copy()] * 3
# my_list.append(1)
# print(values)
# count = 10
# while count > 0:
# print("test")
# count -=1
# my_str = "fuckyou"
# my_list = []
# for symbol in my_str[::2]:
# my_list.append(symbol)
# print(my_list)
# count = 10
# exit_flag = True
# while exit_flag:
# count -= 1
# if count > 0:
# exit_flag = False
# print("test")
# 1) У вас есть список my_list с значениями типа int. Распечатать те значения, которые больше 100. Задание выполнить с помощью цикла for.
# my_list = [1, 3, 5, 7, 9, 121, 170, 55, 490]
# for count in my_list:
# if count > 100:
# print(count)
######################################################################
# 2) У вас есть список my_list с значениями типа int, и пустой список my_results. Добавить в my_results те значения, которые больше 100. Распечатать список my_results. Задание выполнить с помощью цикла for.
# my_list = [1, 3, 5, 834, 7, 9, 121, 170, 55, 490]
# my_result = []
# for count in my_list:
# if count > 100:
# my_result.append(count)
# print(my_result)
######################################################################
# 3) У вас есть список my_list с значениями типа int. Если в my_list количество элементов меньше 2, то в конец добавить значение 0.
# Если количество элементов больше или равно 2, то добавить сумму последних двух элементов. Количество элементов в списке можно получить с помощью функции len(my_list)
# my_list = [-5, -3, -1, 1, 3, 5, 834, 7, 9, 121, 170, 55, 490]
# if len(my_list) < 2:
# my_list.append(0)
# print(my_list)
# else:
# new_my_list = my_list[-1] + my_list[-2]
# my_list.append(new_my_list)
# print(my_list)
#######################################################################
# 4) Пользователь вводит value - число с запятой (например 3.14) с клавиатуры. Вы приводите это value к типу float и выводите результат выражения value ** -1.
# Написать программу, которая вычисляет данное выражение и корректно обрабатывает возможные исключения.
try:
value = input("Введите float число")
value = float(value)
print(value ** -1)
except ZeroDivisionError:
print("Вы ввели 0. это не годится")
except ValueError:
print("Число с запятой не подходит. Воспользуйтесь точкой ")
<file_sep>/classwork/7work2.py
# import string
# import random
# from random import randint
#
# letters = string.ascii_letters
#
# print(letters)
#
# some_int = randint(2, 9)
# print(some_int)
# ФУНКЦИИ
# def имя функции(параметры, если надо):
# блок кода
# print()
def print_something():
print("hello, world!!!!")
def print_dict(some_dict):
for key in some_dict:
print(f"'{key}': {some_dict[key]}")
points_dict = {"A": (1, 2),
"B": (-2, 4),
"C": (0, -6)}
print_dict(points_dict)<file_sep>/classwork/classwork14.py
from person import Person
person_john = Person("John", "01/03/1984", "male")
print(person_john.name)
class Student(Person):
def chage_name(self):
if "student" not in self.name:
self.name = "student" + self.name
class Employer(Person):
def chage_name(self):
if "Employer" not in self.name:
self.name = "Employer" + self.name
student_john = Student("John", "01/03/1984", "male")
employer_jane = Employer("Jane", "21/10/2001", "female")
print(student_john.name, student_john.get_age())
student_john.chage_name()
print(student_john.name)
employer_jane.chage_name()
print(employer_jane.name)<file_sep>/classwork/classwork8.py
# import os
# from utils import get_distance, get_area_gerone
point_A = (10, 1)
point_B = (10, 2)
dist_A_B = get_distance(point_A, point_B)
print(dist_A_B)
point_A = (10, 1)
point_B = (10, 2)
point_C = (9, 1)
area_a_b_c = get_area_gerone(point_A, point_B, point_C)
assert abs(area_a_b_c - 0.5) < 0.001 #если True, то программа идет дальше(проверка). abc - модуль
assert abs(get_area_gerone((0, 0), (0, 4), (3, 0)) - 6.0) < 0.001
assert abs(get_distance((0, 4), (3, 0)) - 5.0) < 0.01
print(area_a_b_c)
print(os.listdir()) #печатаем наши директории
some = ["homework7", "homework8", "homework"]
my_str = "$$$".join(some)
print(my_str)
|
5b6b770428fc0d86f165a153025c46bc6a94227c
|
[
"Python"
] | 14 |
Python
|
malder85/-_-
|
9ecad4ee75f55055988ac9fe25deafb98d516d0f
|
646334731dd723ee78bb888a035be68616a2088f
|
refs/heads/master
|
<repo_name>Reji-Samuel/SalesForceDeveloper<file_sep>/force-app/main/default/aura/CarTile/CarTileController.js
({
onCarClick : function(component, event, helper) {
var car=component.get("v.car");
var selectedCar=component.getEvent("onCarSelect");
selectedCar.setParams({"carId":car.Id});
selectedCar.fire();
var appEvent=$A.get("e.c:CarSelectedApplicationEvent");
if(appEvent){
appEvent.setParams({"car":car,});
appEvent.fire();
}
else{
}
}
})<file_sep>/force-app/main/default/lwc/showModal/showModal.js
import { LightningElement, track, api } from "lwc";
import ImperativeReturnCase from "@salesforce/apex/PopulateDataTable.returnCase";
import SendStringifiedSelection from "@salesforce/apex/PopulateDataTable.buildResourceObject";
export default class ShowModal extends LightningElement {
@track bshowModal = false;
@api recordId;
@track columns = [
{ label: "CaseNumber", fieldName: "CaseNumber", type: "text" },
{ label: "Status", fieldName: "Status", type: "text" },
{ label: "Priority", fieldName: "Priority", type: "text" }
];
@track data;
@track error;
@track theSelectRow = [];
openModal() {
this.bshowModal = true;
}
closeModal() {
this.bshowModal = false;
}
searchModal() {
ImperativeReturnCase()
.then(result => {
this.data = result;
})
.catch(error => {
this.error = error;
});
}
getSelectRow(event) {
console.log("selection Event");
this.theSelectRow = event.detail.selectedRows;
}
saveModal() {
console.log("The selected rows :" + JSON.stringify(this.theSelectRow));
SendStringifiedSelection({
updateStr:JSON.stringify(this.theSelectRow)
});
}
}
<file_sep>/force-app/main/default/aura/BeerListComponent/BeerListComponentController.js
({
showInfo: function(component, event, helper) {
var eventSource = event.getSource();
var beerObj = eventSource.get("v.name");
var bName = eventSource.get("v.value");
component.set("v.beerId", beerObj);
$A.createComponent(
"c:BeerDetails",
{
beerId: beerObj,
beerName: bName
},
function(beerDetails, status, errorMessage) {
if (status === "SUCCESS") {
component.find("overLayLib").showCustomModal({
header: "Beer Details",
body: beerDetails,
footer: "Footer",
showCloseButton: true,
closeCallback: function() {}
});
} else if (status === "INCOMPLETE") {
console.log("No response from server or client is offline");
} else if (status === "ERROR") {
console.log("Error:" + errorMessage);
}
}
);
},
addToCart: function(component, event, helper) {
var eventSource=event.getSource();
var beerId=eventSource.get('v.name');
var index=eventSource.get('v.value');
var selectedBeer=component.get('v.recordList')[index];
var addToCartEvent=component.getEvent('AddToCart');
addToCartEvent.setParams({
beerRecord:selectedBeer
});
addToCartEvent.fire();
}
});<file_sep>/force-app/main/default/aura/CartDetail/CartDetailController.js
({
doInit: function(component, event, helper) {
var pageReference = component.get("v.pageReference");
if (pageReference) {
var state = pageReference.state;
if (state.c__cartId) {
// component.set('v.cartItemList',state.cartId);
//
var action = component.get("c.getCartItems");
action.setParams({
'CartId':state.c__cartId
});
action.setCallback(this, function(response) {
var stateResponse=response.getState();
if (stateResponse === "SUCCESS" || stateResponse === "DRAFT") {
var resultData=response.getReturnValue();
var items=[];
for(var key in resultData ){
items.push(resultData[key]) ;
}
component.set('v.cartItemList',items);
} else if (stateResponse === "INCOMPLETE") {
} else if (stateResponse === "ERROR") {
var errors = response.getError();
if (errors || errors[0].pageMessage) {
console.log("Page Error" + errors[0].pageMessage);
}
} else {
}
});
$A.enqueueAction(action);
} else {
component.set("v.cartItemList", []);
}
}
},
homePage: function(component, event, helper) {
var pageReference = component.find("navigation");
var pageReferenceNav = {
type: "standard__navItemPage",
attributes: {
apiName: "Beer_Explorer__c"
}
};
pageReference.navigate(pageReferenceNav, true);
}
});<file_sep>/force-app/main/default/aura/BeerDetails/BeerDetailsController.js
({
onOrder: function(component, event, helper) {
var navService = component.find("navService");
var pageReferenceNav = {
type: "standard__component",
attributes: {
componentName: "c__CreateBeerOrder"
},
state: {
c__beerId: component.get("v.beerId")
}
};
navService.navigate(pageReferenceNav);
}
});<file_sep>/force-app/main/default/aura/CarSearchResult/CarSearchResultHelper.js
({
onSearch : function(component,helper) {
helper.callServer(component,"c.getCars",
function(response){
if(response.length >0){
component.set("v.cars",response);
component.set("v.carFound",true);
}
else{
component.set("v.carFound",false);
}
},{
carTypeId:component.get("v.carTypeIdComponent")
});
},
doSearch : function(component,event,helper){
var params=event.getParam('arguments');
if (params){
component.set("v.carTypeIdComponent",params.carTypeId);
helper.onSearch(component,helper);
}
},
frameSelectedCar : function(component,event,helper){
component.set("v.selectedCarId",event.getParam("carId"));
}
})<file_sep>/force-app/main/default/aura/CarSearchResult/CarSearchResultController.js
({
doInit : function(component, event, helper) {
helper.onSearch(component,helper);
},
doSearch : function(component,event,helper){
helper.doSearch(component,event,helper);
},
frameSelectedCar : function(component,event,helper){
helper.frameSelectedCar(component,event,helper);
}
})<file_sep>/force-app/main/default/aura/campingList/campingListHelper.js
({
createItem : function(component,Item) {
var action=component.get("c.saveItem");
action.setParams({
"item":Item
});
action.setCallback(this,function(response){
var state = response.getState();
if(state==="SUCCESS"){
var newItems=component.get("v.items");
newItems.push(response.getReturnValue());
component.set("v.items",newItems);
}
});
$A.enqueueAction(action);
component.set("v.newItem",{ 'sobjectType': 'Camping_Item__c','Name': '','Quantity__c': 0,
'Price__c': 0,'Packed__c': false });
}
})<file_sep>/force-app/main/default/aura/CarSearch/CarSearchController.js
({
doFormSubmit : function(component, event, helper) {
var carTypeIdFromChoice=event.getParam("carTypeId");
var carSearchResultComp= component.find("carSearchResult");
var carSearchCmpResult=carSearchResultComp.searchCars(carTypeIdFromChoice);
}
})<file_sep>/force-app/main/default/aura/AddCarExperience/AddCarExperienceHelper.js
({
onInit : function(component, event, helper) {
component.find("service").getNewRecord("Car_Experience__c",null,false,$A.getCallback(function(){
var rec=component.get("v.carExperience");
var error=component.get("v.recordError");
var car=component.get("v.car");
if(error || (rec === null)){
console.log("Error initialising the record template: "+ error);
}
else{
component.set("v.carExperience.Car__c",car.Id);
}
}));
}
})<file_sep>/force-app/main/default/aura/CreateBeerOrder/CreateBeerOrderController.js
({
doInit: function(component, event, helper) {
var pageReference = component.get("v.pageReference");
if (pageReference) {
var state = pageReference.state;
component.set("v.beerId", state.c__beerId);
component.find("recordEditor").reloadRecord();
}
component.find("newRecordCreator").getNewRecord(
"Beer_Order__c",
null,
false,
$A.getCallback(function() {
var rec = component.get("v.newRecordObject");
var error = component.get("v.newRecordError");
if (error || rec === null) {
console.log("Error initializing record template: " + error);
} else {
console.log("Record template initialized: " + rec.sobjectType);
}
})
);
},
handleSubmit: function(component, event, helper) {
var beerRecord = component.get("v.simpleRecord");
console.log("beerRecord Price", beerRecord.Price__c);
var quantity = component.get("v.beerOrder.Ordered_Quantity__c");
console.log("Ordered price ", quantity);
var totalPrice = parseInt(beerRecord.Price__c) * parseInt(quantity);
console.log(" totalPrice ", totalPrice);
var isValid = helper.validateForm(component, event, helper);
if (component.get("v.beerOrder.Billing_Same_As_Shipping__c")) {
component.set(
"v.beerOrder.Billing_Street__c",
component.get("v.beerOrder.Shipping_Street__c")
);
component.set(
"v.beerOrder.Billing_City__c",
component.get("v.beerOrder.Shipping_City__c")
);
component.set(
"v.beerOrder.Billing_Country__c",
component.get("v.beerOrder.Shipping_Country__c")
);
component.set(
"v.beerOrder.Billing_State__c",
component.get("v.beerOrder.Shipping_State__c")
);
component.set(
"v.beerOrder.Billing_Postal_Code__c",
component.get("v.beerOrder.Shipping_Postal_Code__c")
);
}
if (!isValid) return;
var userId = $A.get("$SObjectType.CurrentUser.Id");
//alert(userId);
component.set("v.beerOrder.Beer_Ordered__c", component.get("v.beerId"));
component.set("v.beerOrder.Ordered_By__c", userId);
component.set("v.beerOrder.Order_Amount__c", parseInt(totalPrice));
var beerQnty = component.get("v.simpleRecord.Remaining_Quantity__c");
var remainingQnty = parseInt(beerQnty) - parseInt(quantity);
if (remainingQnty < 0) {
var lowStockToast = $A.get("e.force:showToast");
lowStockToast.setParams({
title: "Low Stock warning.",
message: "The Remaining stock is :"+beerQnty +" ,Kindly revise the order.",
type: "warning"
});
lowStockToast.fire();
} else {
component.find("newRecordCreator").saveRecord(function(saveResult) {
if (saveResult.state === "SUCCESS" || saveResult.state === "DRAFT") {
var resultsToast = $A.get("e.force:showToast");
resultsToast.setParams({
title: "Order Placed",
message:
"Your Order has been successfully placed." + saveResult.recordId,
type: "success"
});
resultsToast.fire();
helper.updateBeerQty(component, event, quantity, saveResult.recordId);
} else if (saveResult.state === "INCOMPLETE") {
console.log("User is offline, device doesn't support drafts.");
} else if (saveResult.state === "ERROR") {
console.log(
"Problem saving contact, error: " + JSON.stringify(saveResult.error)
);
var resultsToast = $A.get("e.force:showToast");
resultsToast.setParams({
title: "Error While Placing Your Order.",
message: JSON.stringify(saveResult.error),
type: "success"
});
resultsToast.fire();
} else {
console.log(
"Unknown problem, state: " +
saveResult.state +
", error: " +
JSON.stringify(saveResult.error)
);
}
});
}
}
});
|
6148fb99eb0c6c80d590fc0a0f0908b479a133c8
|
[
"JavaScript"
] | 11 |
JavaScript
|
Reji-Samuel/SalesForceDeveloper
|
6b0f51ff86bc82aa6d2ff0efec7a243eb67661ec
|
80be6a33bdcb27225ff911672b3b8fef9c31e739
|
refs/heads/master
|
<file_sep>import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
String input = new Scanner(System.in).nextLine();
Queue<Integer> first = new PriorityQueue<>();
for (String elem : input.split(" "))
first.add(Integer.parseInt(elem));
input = new Scanner(System.in).nextLine();
Queue<Integer> second = new PriorityQueue<>();
for (String elem : input.split(" "))
second.add(Integer.parseInt(elem));
int moves = 0;
while (true)
{
if (first.isEmpty())
{
System.out.println("second " + moves);
break;
}
else if (second.isEmpty())
{
System.out.println("first " + moves);
break;
}
else if (moves >= 106)
{
System.out.println("botva");
break;
}
else
{
int topFirst = first.poll(),
topSecond = second.poll();
if (topFirst < topSecond)
{
first.offer(topFirst);
first.offer(topSecond);
}
else
{
second.offer(topFirst);
second.offer(topSecond);
}
++moves;
}
}
}
}
|
1ea6d3591f752298e02cd43f7e56930833a6a964
|
[
"Java"
] | 1 |
Java
|
marikhdkv/Drunkard
|
6d0e40ceb7bb03ffe97b361aa07774c82e90f62a
|
ce756749920a33eeb29205f117fcbc10f0ea7c95
|
refs/heads/master
|
<file_sep>package com.fanbo.kai.zhihu_funny.di.module;
import android.content.Context;
import android.support.v4.app.Fragment;
import com.fanbo.kai.zhihu_funny.di.annotation.PerFragment;
import dagger.Module;
import dagger.Provides;
/**
* Created by Kai on 2017/1/20.
* Email: <EMAIL>
*/
@Module
public class FragmentModule {
private Fragment fragment;
public FragmentModule(Fragment fragment) {
this.fragment = fragment;
}
@PerFragment
@Provides
Context provideActivity() {
return fragment.getActivity();
}
}
<file_sep>package com.fanbo.kai.zhihu_funny.utils.reduce;
/**
* Created by HK on 2017/1/25.
* Email: <EMAIL>.
*/
public interface ReduceFunc<F,T> {
T apply(F currentElement, T origin);
}
<file_sep>package com.fanbo.kai.zhihu_funny.presenter;
import com.fanbo.kai.zhihu_funny.model.Section;
import com.fanbo.kai.zhihu_funny.presenter.base.BasePresenter;
import com.fanbo.kai.zhihu_funny.presenter.contract.ContentContract;
import com.fanbo.kai.zhihu_funny.presenter.contract.ContentContract.Presenter;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
/**
* Created by HK on 2017/1/25.
* Email: <EMAIL>.
*/
public class ContentPresenter extends BasePresenter<ContentContract.View> implements Presenter {
private List<Integer> storyIds = new ArrayList<>();
@Inject
public ContentPresenter() {
}
@Override
public void initContentData(int sectionId) {
httpRequest(funnyApi.getSectionById(sectionId), response -> {
storyIds.addAll(Lists.transform(response.getStories(), Section.Story::getId));
fetchContentBody();
});
}
private void fetchContentBody() {
httpRequestWithLoading(funnyApi.getNewsById(storyIds.get(0)), response -> mView.showContent(response.getBody()));
}
}
<file_sep>package com.fanbo.kai.zhihu_funny.utils;
/**
* Created by Kai on 2017/1/21.
* Email: <EMAIL>
*/
public class Constants {
public static final String SECTION_ID = "section_id";
}
<file_sep>package com.fanbo.kai.zhihu_funny.view.base;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import butterknife.ButterKnife;
/**
* Created by HK on 2017/1/24.
* Email: <EMAIL>.
*/
public abstract class RecyclerViewBaseHolder<D> extends RecyclerView.ViewHolder {
public RecyclerViewBaseHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public abstract void populate(D item);
}
<file_sep>package com.fanbo.kai.zhihu_funny.model;
import com.fanbo.kai.zhihu_funny.model.base.BaseModel;
/**
* Created by HK on 2017/1/25.
* Email: <EMAIL>.
*/
public class News extends BaseModel{
private String body;
private String title;
private String image;
public String getBody() {
return body;
}
public String getTitle() {
return title;
}
public String getImage() {
return image;
}
}
<file_sep>package com.fanbo.kai.zhihu_funny.di.module;
import android.app.Activity;
import dagger.Module;
/**
* Created by Kai on 2017/1/20.
* Email: <EMAIL>
*/
@Module
public class ActivityModule {
private Activity activity;
public ActivityModule(Activity activity) {
this.activity = activity;
}
}
<file_sep>package com.fanbo.kai.zhihu_funny.presenter.base;
import android.app.Activity;
import com.fanbo.kai.zhihu_funny.model.base.ApiResponseFunc1;
import com.fanbo.kai.zhihu_funny.model.base.BaseModel;
import com.fanbo.kai.zhihu_funny.model.db.DbManager;
import com.fanbo.kai.zhihu_funny.network.FunnyApi;
import com.fanbo.kai.zhihu_funny.utils.ExceptionHelper;
import com.fanbo.kai.zhihu_funny.view.base.BaseView;
import com.fanbo.kai.zhihu_funny.view.widget.dialog.ProgressSubscriber;
import javax.inject.Inject;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;
/**
* Created by Kai on 2017/1/20.
* Email: <EMAIL>
*/
public class BasePresenter<T extends BaseView> implements BasePresenterInterface<T>, RxSubscribeInterface {
protected T mView;
protected CompositeSubscription mCompositeSubscription;
@Inject
protected FunnyApi funnyApi;
@Inject
protected DbManager dbManager;
@Override
public void attachView(T view) {
mView = view;
}
@Override
public void unAttachView() {
unSubscribe();
mView = null;
}
@Override
public void addSubscription(Subscription subscription) {
if (mCompositeSubscription == null) {
mCompositeSubscription = new CompositeSubscription();
}
mCompositeSubscription.add(subscription);
}
@Override
public void unSubscribe() {
if (mCompositeSubscription != null) {
mCompositeSubscription.unsubscribe();
}
}
/**
* presenter层发网络请求
* */
protected <P extends BaseModel> void httpRequest(Observable<P> observable, final RequestListener<P> listener) {
Subscription subscribe = observable
.map(new ApiResponseFunc1<P>())
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(listener::onSuccess, ExceptionHelper::handleException);
addSubscription(subscribe);
}
/**
* presenter层发网络请求,封装了loading动画,错误提示等
* */
protected <P extends BaseModel> void httpRequestWithLoading(Observable<P> observable, final RequestListener<P> listener) {
Subscription subscribe = observable
.map(new ApiResponseFunc1<P>())
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new ProgressSubscriber<>(listener::onSuccess, (Activity) mView));
addSubscription(subscribe);
}
protected interface RequestListener<P extends BaseModel>{
void onSuccess(P response);
}
}
<file_sep>package com.fanbo.kai.zhihu_funny.model.db;
import com.fanbo.kai.zhihu_funny.FunnyApp;
import com.fanbo.kai.zhihu_funny.model.DaoMaster;
import com.fanbo.kai.zhihu_funny.model.DaoSession;
import org.greenrobot.greendao.database.Database;
/**
* Created by HK on 2017/1/24.
* Email: <EMAIL>.
*/
public class DbManager {
private final static String DB_NAME = "funny.db";
// /data/data/com.fanbo.kai.zhihu_funny/databases
private DaoSession daoSession;
public DbManager() {
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(FunnyApp.getAppContext(), DB_NAME);
Database db = helper.getWritableDb();
daoSession = new DaoMaster(db).newSession();
}
public DaoSession getDaoSession() {
return daoSession;
}
}
<file_sep>apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'
apply plugin: 'me.tatarka.retrolambda'
apply plugin: 'org.greenrobot.greendao'
android {
compileSdkVersion 24
buildToolsVersion '25.0.2'
defaultConfig {
applicationId "com.fanbo.kai.zhihu_funny"
minSdkVersion 18
targetSdkVersion 24
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
manifestPlaceholders = [
UMENG_CHANNEL_VALUE: "umeng"
]
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
greendao{
schemaVersion 1
}
buildTypes {
debug {
shrinkResources false
zipAlignEnabled false
minifyEnabled false
buildConfigField "boolean", "LOG_DEBUG", "true"
versionNameSuffix "-debug"
}
release {
shrinkResources true
zipAlignEnabled true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
buildConfigField "boolean", "LOG_DEBUG", "false"
applicationVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.apk')) {
def fileName = "ZhihuFunny_${variant.productFlavors[0].name}_v${defaultConfig.versionName}_${releaseTime()}.apk"
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
}
}
// 友盟多渠道打包
productFlavors {
funny {}
wandoujia {}
baidu {}
tecent {}
qihoo360 {}
xiaomi {}
productFlavors.all { flavor ->
flavor.manifestPlaceholders = [UMENG_CHANNEL_VALUE: name]
}
}
lintOptions {
disable 'MissingTranslation', 'ExtraTranslation'
abortOnError false
}
}
def releaseTime() {
return new Date().format("yyyy-MM-dd", TimeZone.getTimeZone("UTC"))
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:24.1.0'
testCompile 'junit:junit:4.12'
//ui
compile 'com.android.support:design:24.2.1'
compile 'com.android.support:recyclerview-v7:24.2.1'
compile 'com.jcodecraeer:xrecyclerview:1.3.2'
//rx
compile 'io.reactivex:rxjava:1.1.0'
compile 'io.reactivex:rxandroid:1.1.0'
//network
compile 'com.google.code.gson:gson:2.4'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'com.squareup.okhttp3:okhttp:3.4.2'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.2'
compile 'com.github.bumptech.glide:okhttp3-integration:1.4.0@aar'
//db
compile 'org.greenrobot:greendao:3.2.0'
//di
compile 'com.google.dagger:dagger:2.0.2'
apt 'com.google.dagger:dagger-compiler:2.0.2'
compile 'com.jakewharton:butterknife:8.2.1'
apt 'com.jakewharton:butterknife-compiler:8.2.1'
provided 'org.glassfish:javax.annotation:10.0-b28'
//图片
compile 'com.github.bumptech.glide:glide:3.7.0'
//友盟统计
compile 'com.umeng.analytics:analytics:latest.integration'
//Android工具类
compile 'com.blankj:utilcode:1.3.4'
compile 'com.google.guava:guava:19.0'
}
<file_sep>package com.fanbo.kai.zhihu_funny.model.base;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by HK on 2017/1/23.
* Email: <EMAIL>.
*/
public class BaseModel implements Parcelable{
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
}
}
<file_sep>package com.fanbo.kai.zhihu_funny.model;
import android.os.Parcel;
import com.fanbo.kai.zhihu_funny.model.base.BaseModel;
import java.util.List;
/**
* Created by HK on 2017/1/24.
* Email: <EMAIL>.
*/
public class Sections extends BaseModel {
private List<Section> data;
public List<Section> getData() {
return data;
}
public static class Section implements android.os.Parcelable {
private int id;
private String description;
private String name;
private String thumbnail;
public int getId() {
return id;
}
public String getDescription() {
return description;
}
public String getName() {
return name;
}
public String getThumbnail() {
return thumbnail;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(this.id);
dest.writeString(this.description);
dest.writeString(this.name);
dest.writeString(this.thumbnail);
}
public Section() {
}
protected Section(Parcel in) {
this.id = (int) in.readValue(Long.class.getClassLoader());
this.description = in.readString();
this.name = in.readString();
this.thumbnail = in.readString();
}
public static final Creator<Section> CREATOR = new Creator<Section>() {
@Override
public Section createFromParcel(Parcel source) {
return new Section(source);
}
@Override
public Section[] newArray(int size) {
return new Section[size];
}
};
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeTypedList(this.data);
}
public Sections() {
}
protected Sections(Parcel in) {
this.data = in.createTypedArrayList(Section.CREATOR);
}
public static final Creator<Sections> CREATOR = new Creator<Sections>() {
@Override
public Sections createFromParcel(Parcel source) {
return new Sections(source);
}
@Override
public Sections[] newArray(int size) {
return new Sections[size];
}
};
}
<file_sep>package com.fanbo.kai.zhihu_funny.model.base;
import com.fanbo.kai.zhihu_funny.exceptions.ApiException;
import rx.functions.Func1;
/**
* Created by HK on 2017/1/23.
* Email: <EMAIL>.
*/
public class ApiResponseFunc1<T> implements Func1<BaseModel, T> {
private ApiException exception;
@Override
public T call(BaseModel baseModel) {
return (T) baseModel;
}
}
<file_sep>package com.fanbo.kai.zhihu_funny.model;
import android.os.Parcel;
import com.fanbo.kai.zhihu_funny.model.base.BaseModel;
import java.util.Date;
import java.util.List;
/**
* Created by HK on 2017/1/25.
* Email: <EMAIL>.
*/
public class Section extends BaseModel{
private String name;
private int timestamp;
private List<Story> stories;
public List<Story> getStories() {
return stories;
}
public static class Story implements android.os.Parcelable {
private int id;
private Date date;
private String display_date;
private String title;
private List<String> images;
public int getId() {
return id;
}
public Date getDate() {
return date;
}
public String getDisplay_date() {
return display_date;
}
public String getTitle() {
return title;
}
public List<String> getImages() {
return images;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.id);
dest.writeLong(this.date != null ? this.date.getTime() : -1);
dest.writeString(this.display_date);
dest.writeString(this.title);
dest.writeStringList(this.images);
}
public Story() {
}
protected Story(Parcel in) {
this.id = in.readInt();
long tmpDate = in.readLong();
this.date = tmpDate == -1 ? null : new Date(tmpDate);
this.display_date = in.readString();
this.title = in.readString();
this.images = in.createStringArrayList();
}
public static final Creator<Story> CREATOR = new Creator<Story>() {
@Override
public Story createFromParcel(Parcel source) {
return new Story(source);
}
@Override
public Story[] newArray(int size) {
return new Story[size];
}
};
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeString(this.name);
dest.writeInt(this.timestamp);
dest.writeTypedList(this.stories);
}
public Section() {
}
protected Section(Parcel in) {
this.name = in.readString();
this.timestamp = in.readInt();
this.stories = in.createTypedArrayList(Story.CREATOR);
}
public static final Creator<Section> CREATOR = new Creator<Section>() {
@Override
public Section createFromParcel(Parcel source) {
return new Section(source);
}
@Override
public Section[] newArray(int size) {
return new Section[size];
}
};
}
<file_sep>package com.fanbo.kai.zhihu_funny.presenter.base;
import rx.Subscription;
/**
* Created by Kai on 2017/1/20.
* Email: <EMAIL>
*/
public interface RxSubscribeInterface {
void addSubscription(Subscription subscription);
void unSubscribe();
}
<file_sep>package com.fanbo.kai.zhihu_funny.view.base;
/**
* Created by Kai on 2017/1/20.
* Email: <EMAIL>
*/
public interface BaseView {
void showToast(String message);
}
<file_sep>package com.fanbo.kai.zhihu_funny.presenter.base;
/**
* Created by Kai on 2017/1/20.
* Email: <EMAIL>
*/
public interface BasePresenterInterface<T> {
void attachView(T view);
void unAttachView();
}
|
05cd79ebc7ec3b98b883d18fcc5c4468a34b2bfc
|
[
"Java",
"Gradle"
] | 17 |
Java
|
sherlockHK/zhihu_funny
|
908ccd2ccd7c8f60b68ab2f2528f7d1d88f21cb2
|
bd9f01ed4ad426e280fdfef86b6e3a6330b919ea
|
refs/heads/master
|
<repo_name>appcelerator-modules/ti.paint<file_sep>/ios/documentation/changelog.md
# Change Log
<pre>
v1.4.1 Added support for touchstart, touchend, touchcancel, touchmove [MOD-2070]
v1.4.0 Updated project with 64bit binary support [TIMOB-18092]
v1.3 Rewrote rendering algorithm to allow for a number of enhancements:
- Retina display support [MOD-636]
- Fix erratic sharpening of previous drawings [MOD-635]
- Smooth erasing identical to how Paint behaves on Android
- Improved multi-touch drawing performance
- Quadratic smoothing of lines
v1.2 Fixed percent width visual defects [MOD-348]
Improved multi-touch drawing performance
v1.1 Added multi-touch support [MOD-243]
Added "image" property to the paint view. See example and documentation to find out more.
v1.0 Initial Release
<file_sep>/ios/documentation/paintView.md
# Ti.Paint.PaintView
## Description
A _Ti.Paint_ module object which is a view for painting in.
## Functions
### clear()
Clears the paint view.
## Properties
### strokeWidth[double]
Controls the width of the strokes.
### strokeColor[string]
Controls the color of the strokes.
### strokeAlpha[int]
Controls the opacity of the strokes.
### eraseMode[boolean]
Controls if the strokes are in "erase mode" -- that is, any existing paint will be erased.
### image[string]
Loads an image (by its URL) directly in to the paint view so that it can be drawn on and erased.
## Events
### touchcancel
Fired when a touch event is interrupted by the device.
### touchend
Fired when a touch event is completed.
### touchmove
Fired as soon as the device detects movement of a touch.
### touchstart
Fired as soon as the device detects a touch gesture.<file_sep>/README.md
ti.paint [](https://travis-ci.org/appcelerator-modules/ti.paint)
=======
This is the Paint Module for Titanium.
Interested in contributing? Read the [contributors/committer's](https://wiki.appcelerator.org/display/community/Home) guide.
## Legal
This module is Copyright (c) 2010-2015 by Appcelerator, Inc. All Rights Reserved. Usage of this module is subject to
the Terms of Service agreement with Appcelerator, Inc.
<file_sep>/windows/CMakeLists.txt
# Titanium Windows Native Module - ti.paint
#
# Copyright (c) 2017 Axway All Rights Reserved.
# Licensed under the terms of the Apache Public License.
# Please see the LICENSE included with this distribution for details.
cmake_minimum_required(VERSION 3.0.0)
if(${CMAKE_SYSTEM_NAME} STREQUAL "Windows10")
set(PLATFORM win10)
elseif(${CMAKE_SYSTEM_NAME} STREQUAL "WindowsPhone")
set(PLATFORM phone)
add_definitions("-DPHONE")
elseif(${CMAKE_SYSTEM_NAME} STREQUAL "WindowsStore")
set(PLATFORM store)
else()
message(FATAL_ERROR "This app supports Store / Phone only.")
endif()
project(TiPaint)
set(TiPaint_VERSION 0.1.0)
set(WINDOWS_SOURCE_DIR "C:/ProgramData/Titanium/mobilesdk/win32/8.0.0.GA/windows")
SET(CMAKE_FIND_LIBRARY_PREFIXES "")
SET(CMAKE_FIND_LIBRARY_SUFFIXES ".lib" ".dll")
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE ON)
option(TiPaint_DISABLE_TESTS "Disable compiling the tests" OFF)
set_property(GLOBAL PROPERTY USE_FOLDERS ON)
get_filename_component(APPCELERATOR_CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake ABSOLUTE)
list(INSERT CMAKE_MODULE_PATH 0 ${APPCELERATOR_CMAKE_MODULE_PATH})
find_package(HAL REQUIRED)
find_package(TitaniumKit REQUIRED)
find_package(LayoutEngine REQUIRED)
find_package(TitaniumWindows_UI REQUIRED)
find_package(JavaScriptCore REQUIRED)
enable_testing()
set(SOURCE_TiPaint
include/TiPaint.hpp
src/TiPaint.cpp
include/TiPaintView.hpp
src/TiPaintView.cpp
)
source_group(TiPaint FILES ${SOURCE_TiPaint})
set(CMAKE_CXX_VISIBILITY_PRESET hidden)
set(CMAKE_VISIBILITY_INLINES_HIDDEN 1)
add_library(TiPaint SHARED
${SOURCE_TiPaint}
)
include(GenerateExportHeader)
generate_export_header(TiPaint)
target_compile_definitions(TiPaint PRIVATE TiPaint_EXPORTS)
target_include_directories(TiPaint PUBLIC
${PROJECT_SOURCE_DIR}/include
$<TARGET_PROPERTY:HAL,INTERFACE_INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:TitaniumKit,INTERFACE_INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:LayoutEngine,INTERFACE_INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:TitaniumWindows_UI,INTERFACE_INCLUDE_DIRECTORIES>
)
target_link_libraries(TiPaint
JavaScriptCore
HAL
TitaniumKit
LayoutEngine
TitaniumWindows_UI
)
set_target_properties(TiPaint PROPERTIES VS_WINRT_COMPONENT TRUE)
set_property(TARGET TiPaint APPEND_STRING PROPERTY LINK_FLAGS_DEBUG "/OPT:NOREF /OPT:NOICF")
if (NOT TiPaint_DISABLE_TESTS)
add_subdirectory(test)
endif()
set_property(TARGET TiPaint PROPERTY VERSION ${TiPaint_VERSION})
set_property(TARGET TiPaint PROPERTY SOVERSION 0)
set_property(TARGET TiPaint PROPERTY INTERFACE_TiPaint_MAJOR_VERSION 0)
set_property(TARGET TiPaint APPEND PROPERTY
COMPATIBLE_INTERFACE_STRING TiPaint_MAJOR_VERSION
)
install(TARGETS TiPaint EXPORT TiPaint_Targets
LIBRARY DESTINATION lib
ARCHIVE DESTINATION lib
RUNTIME DESTINATION bin
INCLUDES DESTINATION include
)
export(EXPORT TiPaint_Targets
FILE "${CMAKE_BINARY_DIR}/TiPaint_Targets.cmake"
)
configure_file(cmake/TiPaint_Config.cmake
"${CMAKE_BINARY_DIR}/TiPaint_Config.cmake"
COPYONLY
)
include(CMakePackageConfigHelpers)
write_basic_package_version_file(
"${CMAKE_BINARY_DIR}/TiPaint_ConfigVersion.cmake"
VERSION ${TiPaint_VERSION}
COMPATIBILITY AnyNewerVersion
)
export(PACKAGE TiPaint)
<file_sep>/windows/src/TiPaint.cpp
/**
* Titanium Windows - ti.paint
*
* Copyright (c) 2017 by Axway All Rights Reserved.
* Licensed under the terms of the Apache Public License.
* Please see the LICENSE included with this distribution for details.
*/
#include "TiPaint.hpp"
#include "TiPaintView.hpp"
namespace Ti
{
Paint::Paint(const JSContext& js_context) TITANIUM_NOEXCEPT
: Titanium::Module(js_context, "ti.paint"),
paintView__(JSExport<Ti::PaintView>::Class())
{
TITANIUM_LOG_DEBUG("Ti::Paint::ctor Initialize");
}
void Paint::JSExportInitialize()
{
JSExport<Paint>::SetClassVersion(1);
JSExport<Paint>::SetParent(JSExport<Titanium::Module>::Class());
TITANIUM_ADD_FUNCTION(Paint, createPaintView);
}
TITANIUM_FUNCTION(Paint, createPaintView)
{
ENSURE_OPTIONAL_OBJECT_AT_INDEX(parameters, 0);
auto paintView_obj = get_context().CreateObject(paintView__).CallAsConstructor(parameters);
Titanium::Module::applyProperties(parameters, paintView_obj);
return paintView_obj;
}
}
<file_sep>/windows/include/TiPaintView.hpp
/**
* Titanium Windows - ti.paint
*
* Copyright (c) 2017 by Axway All Rights Reserved.
* Licensed under the terms of the Apache Public License.
* Please see the LICENSE included with this distribution for details.
*/
#ifndef _TIPAINTVIEW_HPP_
#define _TIPAINTVIEW_HPP_
#include "TiPaint_EXPORT.h"
#include "Titanium/UI/View.hpp"
#include "Titanium/detail/TiBase.hpp"
namespace Ti
{
using namespace HAL;
using namespace Windows::Foundation;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Media;
class TIPAINT_EXPORT PaintView : public Titanium::UI::View, public JSExport<PaintView>
{
public:
PaintView(const JSContext&) TITANIUM_NOEXCEPT;
virtual void postCallAsConstructor(const JSContext& js_context, const std::vector<JSValue>& arguments) override;
virtual ~PaintView() = default;
PaintView(const PaintView&) = default;
PaintView& operator=(const PaintView&) = default;
#ifdef TITANIUM_MOVE_CTOR_AND_ASSIGN_DEFAULT_ENABLE
PaintView(PaintView&&) = default;
PaintView& operator=(PaintView&&) = default;
#endif
static void JSExportInitialize();
TITANIUM_PROPERTY_DEF(strokeWidth);
TITANIUM_PROPERTY_IMPL_DEF(double, strokeWidth);
TITANIUM_PROPERTY_DEF(strokeColor);
TITANIUM_PROPERTY_IMPL_READONLY_DEF(std::string, strokeColor);
virtual void set_strokeColor(const std::string& color) TITANIUM_NOEXCEPT;
TITANIUM_PROPERTY_DEF(strokeAlpha);
TITANIUM_PROPERTY_IMPL_READONLY_DEF(int, strokeAlpha);
virtual void set_strokeAlpha(const int& color) TITANIUM_NOEXCEPT;
TITANIUM_PROPERTY_DEF(eraseMode);
TITANIUM_PROPERTY_IMPL_DEF(bool, eraseMode);
TITANIUM_PROPERTY_DEF(image);
TITANIUM_PROPERTY_IMPL_DEF(std::string, image);
TITANIUM_FUNCTION_DEF(clear);
private:
#pragma warning(push)
#pragma warning(disable : 4251)
double strokeWidth__;
std::string strokeColor__;
int strokeAlpha__;
bool eraseMode__;
std::string image__;
std::uint32_t inputId__;
Point inputStart__;
Point inputEnd__;
Brush^ strokeBrush__{ nullptr };
Canvas^ canvas__{ nullptr };
#pragma warning(pop)
};
}
#endif // _TIPAINTVIEW_HPP_
<file_sep>/windows/src/TiPaintView.cpp
/**
* Titanium Windows - ti.paint
*
* Copyright (c) 2017 by Axway All Rights Reserved.
* Licensed under the terms of the Apache Public License.
* Please see the LICENSE included with this distribution for details.
*/
#include "TiPaintView.hpp"
#include "TitaniumWindows/UI/WindowsViewLayoutDelegate.hpp"
namespace Ti
{
using namespace Windows::Devices::Input;
using namespace Windows::UI::Core;
PaintView::PaintView(const JSContext& js_context) TITANIUM_NOEXCEPT
: Titanium::UI::View(js_context),
strokeWidth__(6),
strokeColor__("black"),
strokeAlpha__(255),
eraseMode__(false),
image__("")
{
TITANIUM_LOG_DEBUG("Ti::Paint::View::ctor Initialize");
}
void PaintView::postCallAsConstructor(const JSContext& js_context, const std::vector<JSValue>& arguments)
{
Titanium::UI::View::postCallAsConstructor(js_context, arguments);
canvas__ = ref new Windows::UI::Xaml::Controls::Canvas();
canvas__->Background = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::Colors::Transparent);
inputId__ = 0;
strokeBrush__ = ref new Windows::UI::Xaml::Media::SolidColorBrush(TitaniumWindows::UI::WindowsViewLayoutDelegate::ColorForName(strokeColor__));
canvas__->PointerPressed += ref new Windows::UI::Xaml::Input::PointerEventHandler(
[=](Platform::Object ^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ e) {
const auto p = e->GetCurrentPoint(canvas__);
inputStart__ = p->Position;
const auto type = e->Pointer->PointerDeviceType;
if (type == PointerDeviceType::Touch || type == PointerDeviceType::Pen || type == PointerDeviceType::Mouse && p->Properties->IsLeftButtonPressed) {
inputId__ = p->PointerId;
e->Handled = true;
}
}
);
canvas__->PointerMoved += ref new Windows::UI::Xaml::Input::PointerEventHandler(
[=](Platform::Object ^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ e) {
if (e->Pointer->PointerId == inputId__) {
const auto p = e->GetCurrentPoint(canvas__);
inputEnd__ = p->Position;
if (std::sqrt(std::pow((inputEnd__.X - inputStart__.X), 2) + std::pow((inputEnd__.Y - inputStart__.Y), 2)) > 1.0) {
auto line = ref new Windows::UI::Xaml::Shapes::Line();
line->X1 = inputEnd__.X;
line->Y1 = inputEnd__.Y;
line->X2 = inputStart__.X;
line->Y2 = inputStart__.Y;
line->StrokeThickness = strokeWidth__;
line->StrokeStartLineCap = PenLineCap::Round;
line->StrokeEndLineCap = PenLineCap::Round;
if (get_eraseMode()) {
line->Stroke = canvas__->Background;
} else {
line->Stroke = strokeBrush__;
}
canvas__->Children->Append(line);
inputStart__ = inputEnd__;
}
}
}
);
canvas__->PointerReleased += ref new Windows::UI::Xaml::Input::PointerEventHandler(
[=](Platform::Object ^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ e) {
inputId__ = 0;
e->Handled = true;
}
);
Titanium::UI::View::setLayoutDelegate<TitaniumWindows::UI::WindowsViewLayoutDelegate>();
layoutDelegate__->set_defaultHeight(Titanium::UI::LAYOUT::FILL);
layoutDelegate__->set_defaultWidth(Titanium::UI::LAYOUT::FILL);
layoutDelegate__->set_autoLayoutForHeight(Titanium::UI::LAYOUT::FILL);
layoutDelegate__->set_autoLayoutForWidth(Titanium::UI::LAYOUT::FILL);
getViewLayoutDelegate<TitaniumWindows::UI::WindowsViewLayoutDelegate>()->setComponent(canvas__, nullptr, false);
}
void PaintView::JSExportInitialize()
{
JSExport<PaintView>::SetClassVersion(1);
JSExport<PaintView>::SetParent(JSExport<Titanium::UI::View>::Class());
TITANIUM_ADD_PROPERTY(PaintView, strokeWidth);
TITANIUM_ADD_PROPERTY(PaintView, strokeColor);
TITANIUM_ADD_PROPERTY(PaintView, strokeAlpha);
TITANIUM_ADD_PROPERTY(PaintView, eraseMode);
TITANIUM_ADD_PROPERTY(PaintView, image);
TITANIUM_ADD_FUNCTION(PaintView, clear);
}
TITANIUM_PROPERTY_READWRITE(PaintView, double, strokeWidth);
TITANIUM_PROPERTY_GETTER(PaintView, strokeWidth)
{
return get_context().CreateNumber(get_strokeWidth());
}
TITANIUM_PROPERTY_SETTER(PaintView, strokeWidth)
{
TITANIUM_ASSERT(argument.IsNumber());
set_strokeWidth(static_cast<double>(argument));
return true;
}
TITANIUM_PROPERTY_READ(PaintView, std::string, strokeColor);
TITANIUM_PROPERTY_GETTER(PaintView, strokeColor)
{
return get_context().CreateString(get_strokeColor());
}
TITANIUM_PROPERTY_SETTER(PaintView, strokeColor)
{
TITANIUM_ASSERT(argument.IsString());
set_strokeColor(static_cast<std::string>(argument));
return true;
}
void PaintView::set_strokeColor(const std::string& color) TITANIUM_NOEXCEPT
{
strokeColor__ = color;
auto brushColor = TitaniumWindows::UI::WindowsViewLayoutDelegate::ColorForName(strokeColor__);
brushColor.A = static_cast<char>(strokeAlpha__);
strokeBrush__ = ref new Windows::UI::Xaml::Media::SolidColorBrush(brushColor);
}
TITANIUM_PROPERTY_READ(PaintView, int, strokeAlpha);
TITANIUM_PROPERTY_GETTER(PaintView, strokeAlpha)
{
return get_context().CreateNumber(get_strokeAlpha());
}
TITANIUM_PROPERTY_SETTER(PaintView, strokeAlpha)
{
TITANIUM_ASSERT(argument.IsNumber());
set_strokeAlpha(static_cast<int>(argument));
return true;
}
void PaintView::set_strokeAlpha(const int& alpha) TITANIUM_NOEXCEPT
{
strokeAlpha__ = alpha;
set_strokeColor(strokeColor__);
}
TITANIUM_PROPERTY_READWRITE(PaintView, bool, eraseMode);
TITANIUM_PROPERTY_GETTER(PaintView, eraseMode)
{
return get_context().CreateBoolean(get_eraseMode());
}
TITANIUM_PROPERTY_SETTER(PaintView, eraseMode)
{
TITANIUM_ASSERT(argument.IsBoolean());
set_eraseMode(static_cast<bool>(argument));
return true;
}
TITANIUM_PROPERTY_READWRITE(PaintView, std::string, image);
TITANIUM_PROPERTY_GETTER(PaintView, image)
{
return get_context().CreateString(get_image());
}
TITANIUM_PROPERTY_SETTER(PaintView, image)
{
TITANIUM_ASSERT(argument.IsString());
set_image(static_cast<std::string>(argument));
layoutDelegate__->set_backgroundImage(get_image());
return true;
}
TITANIUM_FUNCTION(PaintView, clear)
{
canvas__->Children->Clear();
return get_context().CreateUndefined();
}
}
<file_sep>/windows/cmake/FindJavascriptCore.cmake
# FindJavaScriptCore
# Author: <NAME>
#
# Copyright (c) 2017 by Axway All Rights Reserved.
# Licensed under the terms of the Apache Public License.
# Please see the LICENSE included with this distribution for details.
# Author: <NAME>
# Created: 2014.12.02
if (${CMAKE_SYSTEM_VERSION} MATCHES "^10.0")
set(PLATFORM win10)
elseif(${CMAKE_SYSTEM_NAME} STREQUAL "WindowsPhone")
set(PLATFORM phone)
elseif(${CMAKE_SYSTEM_NAME} STREQUAL "WindowsStore")
set(PLATFORM store)
else()
message(FATAL_ERROR "This app supports Store / Phone only.")
endif()
set(JavaScriptCore_ARCH "x86")
if(CMAKE_GENERATOR MATCHES "^Visual Studio .+ ARM$")
set(JavaScriptCore_ARCH "arm")
endif()
# Taken and slightly modified from build's JavaScriptCore_Targets.cmake file
# INTERFACE_INCLUDE_DIRECTORIES is modified to point to our pre-packaged include dir for module
# Create imported target JavaScriptCore
add_library(JavaScriptCore SHARED IMPORTED)
set_target_properties(JavaScriptCore PROPERTIES
COMPATIBLE_INTERFACE_STRING "JavaScriptCore_MAJOR_VERSION"
INTERFACE_JavaScriptCore_MAJOR_VERSION "0"
)
set_target_properties(JavaScriptCore PROPERTIES
IMPORTED_IMPLIB "${WINDOWS_SOURCE_DIR}/lib/JavaScriptCore/${PLATFORM}/${JavaScriptCore_ARCH}/JavaScriptCore.lib"
IMPORTED_LOCATION "${WINDOWS_SOURCE_DIR}/lib/JavaScriptCore/${PLATFORM}/${JavaScriptCore_ARCH}/JavaScriptCore.dll"
)
<file_sep>/android/src/ti/modules/titanium/paint/PaintModule.java
/**
* Ti.Paint Module
* Copyright (c) 2010-2013 by Appcelerator, Inc. All Rights Reserved.
* Please see the LICENSE included with this distribution for details.
*/
package ti.modules.titanium.paint;
import org.appcelerator.kroll.KrollModule;
import org.appcelerator.kroll.annotations.Kroll;
@Kroll.module(name = "Paint", id = "ti.paint")
public class PaintModule extends KrollModule {
public PaintModule() {
super();
}
}
<file_sep>/windows/documentation/changelog.md
# Change Log
<pre>
1.0.0 Initial Windows Release
<file_sep>/windows/include/TiPaint.hpp
/**
* Titanium Windows - ti.paint
*
* Copyright (c) 2017 by Axway All Rights Reserved.
* Licensed under the terms of the Apache Public License.
* Please see the LICENSE included with this distribution for details.
*/
#ifndef _TIPAINT_HPP_
#define _TIPAINT_HPP_
#include "TiPaint_EXPORT.h"
#include "Titanium/Module.hpp"
#include "Titanium/detail/TiBase.hpp"
namespace Ti
{
using namespace HAL;
class TIPAINT_EXPORT Paint : public Titanium::Module, public JSExport<Paint>
{
public:
Paint(const JSContext&) TITANIUM_NOEXCEPT;
virtual ~Paint() = default;
Paint(const Paint&) = default;
Paint& operator=(const Paint&) = default;
#ifdef TITANIUM_MOVE_CTOR_AND_ASSIGN_DEFAULT_ENABLE
Paint(Paint&&) = default;
Paint& operator=(Paint&&) = default;
#endif
static void JSExportInitialize();
TITANIUM_FUNCTION_DEF(createPaintView);
private:
JSClass paintView__;
};
}
#endif // _TIPAINT_HPP_
|
0ff99ae525a5ca8d3b6330a4b396398532cfb591
|
[
"Markdown",
"Java",
"CMake",
"C++"
] | 11 |
Markdown
|
appcelerator-modules/ti.paint
|
9e3f763baac51f94dcd7582f8782defae929fd4c
|
e1d726720a27d739ece110ac101141cbb3e38cd3
|
refs/heads/master
|
<file_sep>/* unit test for shuffle */
#include "asserttrue.h"
#include "dominion.h"
int main() {
int numPlayers = 2;
struct gameState state;
int randomSeed = 1;
int kingdomCards[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, sea_hag, tribute, smithy};
initializeGame(numPlayers, kingdomCards, randomSeed, &state);
int card = state.deck[0][5];
shuffle(0, &state);
if (state.deck[0][3] == card) {
asserttrue(1,0);
/*asserttrue(state.deck[0][5], card);*/
/* Note to self: there is something odd about how this shuffles...*/
}
else {
asserttrue(0,0);
}
}
<file_sep>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
const char range[] = {'[', '(', '{', ' ', 'a', 'x', '}', ')', ']'};
/* This function generates a random char and returns it.*/
/* reall we want this to generate 9 characters...*/
char inputChar() {
int max = sizeof(range)/sizeof(range[0]); /*because ascii is beautiful */
//printf("max is %d\n", max);
int rando = rand() % (max + 1);
//printf("rando was %d\n",rando);
return (char)(range[rando]);
}
/* I need ATLEAST 96!/(96-9)! = iterations to ensure exit status is achieved for "c"... */
/* for "s" we need 26!/(25-7)! = */
/* holy crap independent events, (96!/(96-9)!)*(26!/(26-7)!) = 1559819890146044259532800000 */
/* that is unrealistic, so lets do something */
char *inputString() {
/* so we are going to limit to just lowercase */
/* which means tc max is 25!/(25-6)! = 127512000 which is 1/2 an int so we guud */
int max = 25;
char str[6] = {93,93,93,93,93,'\0'};
char *str_ptr = str;
int i = 0;
for(i=0;i<5;i++) {
str[i] = (char) ((rand() % (max+1)) + 97);
}
return str_ptr;
}
void testme()
{
int tcCount = 0;
char *s;
char c;
int state = 0;
while (1)
{
tcCount++;
c = inputChar();
s = inputString();
printf("Iteration %d: c = %c, s = %s, state = %d\n", tcCount, c, s, state);
if (c == '[' && state == 0) state = 1;
if (c == '(' && state == 1) state = 2;
if (c == '{' && state == 2) state = 3;
if (c == ' ' && state == 3) state = 4;
if (c == 'a' && state == 4) state = 5;
if (c == 'x' && state == 5) state = 6;
if (c == '}' && state == 6) state = 7;
if (c == ')' && state == 7) state = 8;
if (c == ']' && state == 8) state = 9;
if (s[0] == 'r' && s[1] == 'e'
&& s[2] == 's' && s[3] == 'e'
&& s[4] == 't' && s[5] == '\0'
&& state == 9)
{
printf("error ");
exit(200);
}
}
}
int main(int argc, char *argv[])
{
srand(time(NULL));
testme();
return 0;
}
<file_sep>/* random test for adventurer */
#include "asserttrue.h"
#include "dominion.h"
#include <string.h>
#include <stdlib.h>
#include <time.h>
/* Reveal cards from your deck until you reveal 2 Treasure cards. Put those
* Treasure cards into your hand and discard the other revealed cards. */
#define MIN_HAND 5
#define ONE_TURN_GAMES 2
#define RANDOM_TURN_GAMES 2
#define RANDOM_GAME_RANDOM_TURNS 2/* MAX VALUE */
#define IS_TREASURE (cardDrawn == copper || cardDrawn == silver || cardDrawn == gold)
//extern int count[2]; /* yes... im bad */
int total = 0;
int count = 0;
int main() {
int numPlayers = 2; //? test this?
struct gameState state; // no
struct gameState ref;
struct gameState run2;
int randomSeed = 1; //hmm
srand(time(NULL));
int kingdomCards[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, sea_hag, tribute, smithy};
//initializeGame(numPlayers, kingdomCards, randomSeed, &state);
int drawntreasure = 0; //used to count how many treasures have been drawn
int drawntreasure1 = 0;
int card = adventurer;
int choice1 = -1;
int choice2 = -1;
int choice3 = -1;
int handPos = 0;
int bonus = 0;
int temp = state.handCount[0];
int cardDrawn = 0;
asserttrue(0, ( initializeGame(numPlayers, kingdomCards, randomSeed, &state) ), "InitilizeGame called, state");
asserttrue(0, ( initializeGame(numPlayers, kingdomCards, randomSeed, &run2) ), "InitilizeGame called, run2");
//asserttrue(0, ( initializeGame(numPlayers, kingdomCards, randomSeed, &ref) ), "InitilizeGame called, ref");
drawntreasure = 0;
asserttrue(state.handCount[0], MIN_HAND , "(state.handcount, #ofcards in min hand?), hmm");
state.hand[0][0] = card;
state.hand[1][0] = card;
run2.hand[0][0] = card;
run2.hand[1][0] = card;
temp = state.handCount[0];
asserttrue(state.numPlayers, numPlayers, "(state.numplayers, numplayers), still numplayer issue");
memcpy(&ref, &state, sizeof(struct gameState)); /* hmm resulted in this */
cardAdventurer(card, choice1, choice2, choice3, &state, 0, &bonus);
cardAdventurer(card, choice1, choice2, choice3, &run2, 0, &bonus);
asserttrue(run2.supplyCount[0], state.supplyCount[0], "hmm checking manually supply count?");
asserttrue(isequalgamestate(&run2, &run2), 0, "Checking if gamestat structs are still the same, (2nd run, and 1st run)");
/* Okay lets loop... dumb looping but, looping */
int i = 0; /* lets play 20 games, just test the next move as adventrurer */
struct gameState one_turn_ref1;
struct gameState one_turn_ref2;
ref.hand[0][0] = card;
ref.hand[1][0] = card;
/* OKAY SO THERE IS something i cant figure out going on with numPlayers */
/* manually setting this, so i dont just fail over and over, already dinged once */
ref.numPlayers = numPlayers;
asserttrue(ref.numPlayers, numPlayers, "(ref.numplayers, numplayers), because idk");
memcpy(&one_turn_ref1, &ref, sizeof(struct gameState));
memcpy(&one_turn_ref2, &ref, sizeof(struct gameState));
//count treasures
int existing_treasures =0;
int existing_treasures1 = 0;
int km = 0;
for (km = 0; km < one_turn_ref1.handCount[0]; km++)
{
cardDrawn = one_turn_ref1.hand[0][km];
if (IS_TREASURE)
{
existing_treasures++;
}
}
for (km = 0; km < one_turn_ref1.handCount[0]; km++)
{
cardDrawn = one_turn_ref1.hand[0][km];
if (IS_TREASURE)
{
existing_treasures1++;
}
}
int kl = 0;
for (i = 0; i < ONE_TURN_GAMES; i++) {
/* build turn */
drawntreasure = 0;
drawntreasure1 = 0;
bonus = 0;
handPos = 0;
cardAdventurer(card, choice1, choice2, choice3, &one_turn_ref1, handPos, &bonus);
bonus = 0;
handPos = 0; /* shouldnt need to this but whatevs */
cardAdventurer(card, choice1, choice2, choice3, &one_turn_ref2, handPos, &bonus);
asserttrue(isequalgamestate(&one_turn_ref1, &one_turn_ref2), 0, "checking one turn to another, i know, why?");
for (kl = 0; kl < one_turn_ref1.handCount[0]; kl++)
{
cardDrawn = one_turn_ref1.hand[0][kl];
if (IS_TREASURE)
{
drawntreasure++;
}
}
asserttrue(drawntreasure, (2+existing_treasures), "(drawntreasure, 2+existing treasures), checking that # of treasures is correct");
for (kl = 0; kl < one_turn_ref2.handCount[0]; kl++)
{
cardDrawn = one_turn_ref2.hand[0][kl];
if (IS_TREASURE)
{
drawntreasure1++;
}
}
asserttrue(drawntreasure1, (2+existing_treasures1), "(drawntreasure, 2+existing treasures), checking that # of treasures is correct");
}
asserttrue(i, ONE_TURN_GAMES, "did we complete the one_turn_games?");
memcpy(&one_turn_ref1, &ref, sizeof(struct gameState));
memcpy(&one_turn_ref2, &ref, sizeof(struct gameState));
int j = 0;
int rando = 1;
int game_rando = rand() % RANDOM_TURN_GAMES + 1;
for (i = 0; i < game_rando; i++) {
/*get a random nnumber */
rando = rand() % RANDOM_GAME_RANDOM_TURNS + 1; /* not right but im aokey widit */
for (j = 0; j < rando; j++) {
drawntreasure = 0;
bonus = 0;
handPos = 0;
cardAdventurer(card, choice1, choice2, choice3, &one_turn_ref1, handPos, &bonus);
bonus = 0;
handPos = 0; /* shouldnt need to this but whatevs */
cardAdventurer(card, choice1, choice2, choice3, &one_turn_ref2, handPos, &bonus);
//asserttrue(isequalgamestate(one_turn_run1, one_turn_ref2), 0, "checking one turn to another"
}
/* now check */
asserttrue(rando, j, "(rando # of turns, actual turn iter count)");
asserttrue(isequalgamestate(&one_turn_ref1, &one_turn_ref2), 0, "checking states after turns");
}
//todo:
//fix asserttrue to add string print
//add "helper" functions.
//
//
//
/*also if the seed changes, i'd hope this test would fail, but....*/
/* All done, how'd I do? */
asserttrue(count, total, "(tests passed == total tests) DID WE WIN?");
return 0;
}
<file_sep>CFLAGS = -Wno-implicit -fpic -coverage -lm
SHELL:=/bin/bash
rngs.o: rngs.h rngs.c
gcc -c rngs.c -g $(CFLAGS)
dominion.o: dominion.h dominion.c rngs.o
gcc -c dominion.c -g $(CFLAGS)
playdom: dominion.o playdom.c
gcc -o playdom playdom.c -g dominion.o rngs.o $(CFLAGS)
#To run playdom you need to entere: ./playdom <any integer number> like ./playdom 10*/
testDrawCard: testDrawCard.c dominion.o rngs.o
gcc -o testDrawCard -g testDrawCard.c dominion.o rngs.o $(CFLAGS)
badTestDrawCard: badTestDrawCard.c dominion.o rngs.o
gcc -o badTestDrawCard -g badTestDrawCard.c dominion.o rngs.o $(CFLAGS)
testBuyCard: testDrawCard.c dominion.o rngs.o
gcc -o testDrawCard -g testDrawCard.c dominion.o rngs.o $(CFLAGS)
testAll: dominion.o testSuite.c
gcc -o testSuite testSuite.c -g dominion.o rngs.o $(CFLAGS)
interface.o: interface.h interface.c
gcc -c interface.c -g $(CFLAGS)
runtests: testDrawCard
./testDrawCard &> unittestresult.out
gcov dominion.c >> unittestresult.out
cat dominion.c.gcov >> unittestresult.out
unittestresults.out: all
rm -f unittestresults.out
$(foreach a, $(Tests), gcc -o testing asserttrue.c $(a) -g dominion.o rngs.o $(CFLAGS) ; \
./testing &> unittestresults.out ;)
gcov dominion.c >> unittestresults.out
cat dominion.c.gcov >> unittestresults.out
echo $(Tests)
#Tests = cardtest4.c
Tests:=$(shell ls | egrep '*test[0-9]+.c' | sort -n )
asserttrue.o: asserttrue.h asserttrue.c
gcc -c asserttrue.c -g $(CFLAGS)
randomtestcard1: randomtestcard1.c dominion.o rngs.o asserttrue.o
gcc -o randomtestcard1 -g randomtestcard1.c dominion.o rngs.o asserttrue.o $(CFLAGS)
randomtestcard2: randomtestcard2.c dominion.o rngs.o asserttrue.o
gcc -o randomtestcard2 -g randomtestcard2.c dominion.o rngs.o asserttrue.o $(CFLAGS)
randomtestadventurer: randomtestadventurer.c dominion.o rngs.o asserttrue.o
gcc -o randomtestadventurer -g randomtestadventurer.c dominion.o rngs.o asserttrue.o $(CFLAGS)
randomtestcard1.out: randomtestcard1
./randomtestcard1 >> randomtestcard1.out
gcov -c -b randomtestcard1.c >> randomtestcard1.out
cat randomtestcard1.c.gcov >> randomtestcard1.out
randomtestcard2.out: randomtestcard2
./randomtestcard2 >> randomtestcard2.out
gcov -c -b randomtestcard2.c >> randomtestcard2.out
cat randomtestcard2.c.gcov >> randomtestcard2.out
randomtestadventurer.out: randomtestadventurer
./randomtestadventurer >> randomtestadventurer.out
gcov -c -b randomtestadventurer.c >> randomtestadventurer.out
cat randomtestadventurer.c.gcov >> randomtestadventurer.out
randomtester0: randomtestadventurer randomtestadventurer.out
@echo "COMPILING & RUNNING ADVENTURER TESTS"
randomtester1: randomtestcard1 randomtestcard1.out
@echo "COMPILING & RUNNING COUNCIL ROOM TESTS"
randomtester2: randomtestcard2 randomtestcard2.out
@echo "COMPILING & RUNNING SMITHY TESTS"
randomtestall: randomtester0 randomtester1 randomtester2
@echo "COMPILING ALL RANDOM TESTER"
#I was planning on making a one command to rule them all but...
#time -p bash -c 'make clean && make randomtester0 && tail -n $(($(cat randomtestadventurer.c.gcov | wc -l)+15)) randomtestadventurer.out | head'
#time -p bash -c 'make clean && make randomtester1 && tail -n $(($(cat randomtestcard1.c.gcov | wc -l)+15)) randomtestcard1.out | head'
#time -p bash -c 'make clean && make randomtester2 && tail -n $(($(cat randomtestcard2.c.gcov | wc -l)+15)) randomtestcard2.out | head'
player: player.c interface.o
gcc -o player player.c -g dominion.o rngs.o interface.o $(CFLAGS)
all: playdom player testDrawCard testBuyCard badTestDrawCard
clean:
rm -f *.o playdom.exe playdom player player.exe *.gcov *.gcda *.gcno *.so testDrawCard testDrawCard.exe
rm -f randomtestcard1 randomtestcard2 randomtestadventurer
cleaner: clean
rm -f *.out
<file_sep>/* unit test for council_room */
#include "asserttrue.h"
#include "dominion.h"
int main() {
int numPlayers = 2;
struct gameState state;
int randomSeed = 1;
int kingdomCards[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, sea_hag, tribute, smithy};
initializeGame(numPlayers, kingdomCards, randomSeed, &state);
int card = council_room;
int choice1 = -1;
int choice2 = -1;
int choice3 = -1;
int handPos = 0;
int bonus = 0;
int temp = state.handCount[0];
/*testing smithy */
cardCouncilRoom(card, choice1, choice2, choice3, &state, handPos, &bonus);
asserttrue(state.discardCount[0], 1);
asserttrue(state.handCound[0], temp - 1);
/*Sorry but someone put Fargo S03 on and <NAME> is just murdering my childhood innocence...*/
}
<file_sep>/* unit test initialize game function */
#include "asserttrue.h"
#include "dominion.h"
#include <stdlib.h>
#include <stdio.h>
int main() {
asserttrue(0,0);
int numPlayers = 2;
int kingdomCards[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, sea_hag, tribute, smithy};
int randomSeed = 1;
struct gameState state;
/* 2 player game */
initializeGame(numPlayers, kingdomCards, randomSeed, &state);
asserttrue(state.numPlayers, numPlayers);
asserttrue(state.supplyCount[curse], 10);
asserttrue(state.supplyCount[estate], 8);
asserttrue(state.supplyCount[duchy], 8);
asserttrue(state.supplyCount[province], 8);
asserttrue(state.supplyCount[copper], 46);
asserttrue(state.supplyCount[silver], 40);
asserttrue(state.supplyCount[gold], 30);
asserttrue(state.supplyCount[council_room], -1);
asserttrue(state.supplyCount[feast], -1);
asserttrue(state.supplyCount[gardens], 8);
asserttrue(state.supplyCount[mine], 10);
asserttrue(state.supplyCount[remodel], -1);
asserttrue(state.supplyCount[smithy], 10);
asserttrue(state.supplyCount[village], 10);
asserttrue(state.supplyCount[baron], -1);
asserttrue(state.supplyCount[great_hall], -1);
asserttrue(state.supplyCount[minion], 10);
asserttrue(state.supplyCount[steward], -1);
asserttrue(state.supplyCount[tribute], 10);
asserttrue(state.supplyCount[ambassador], -1);
asserttrue(state.supplyCount[outpost], -1);
asserttrue(state.supplyCount[salvager], -1);
asserttrue(state.supplyCount[sea_hag], 10);
asserttrue(state.supplyCount[treasure_map], -1);
asserttrue(state.embargoTokens[0], 0);
asserttrue(state.outpostPlayed, 0);
asserttrue(state.outpostTurn, 0);
asserttrue(state.whoseTurn, 0);
asserttrue(state.phase, 0);
asserttrue(state.numActions, 1);
asserttrue(state.coins, 4);
asserttrue(state.numBuys, 1);
asserttrue(state.hand[0][0], 4);
asserttrue(state.handCount[0], 5);
asserttrue(state.deck[0][0], 1);
asserttrue(state.deckCount[0], 5);
asserttrue(state.discard[0][0], 0);
asserttrue(state.discardCount[0], 0);
asserttrue(state.playedCards, 0); /* error here? unintialized... */
asserttrue(state.playedCardCount, 0);
}
<file_sep>CFLAGS = -Wall -fpic -coverage -lm
build: clean all
all:
gcc -o testme testme.c
clean:
rm -f *.o testme *.gcov *.gcda *.gcno *.so *.out
<file_sep>/* random test for SMITHY */
#include "asserttrue.h"
#include "dominion.h"
#include <string.h>
#include <time.h>
#include <stdlib.h>
/* Reveal cards from your deck until you reveal 2 Treasure cards. Put those
* Treasure cards into your hand and discard the other revealed cards. */
#define MIN_HAND 5
#define ONE_TURN_GAMES 2
#define RANDOM_TURN_GAMES 2
#define RANDOM_GAME_RANDOM_TURNS 2 /* MAX VALUE */
#define IS_TREASURE (cardDrawn == copper || cardDrawn == silver || cardDrawn == gold)
int count = 0;/* yes... im bad */
int total = 0;
int main() {
int numPlayers = 2; //? test this?
srand(time(NULL)); //reset rng?
struct gameState state; // no
int randomSeed = 1; //hmm
int kingdomCards[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, sea_hag, tribute, smithy};
//initializeGame(numPlayers, kingdomCards, randomSeed, &state);
int drawntreasure = 0; //used to count how many treasures have been drawn
int card = smithy;
int choice1 = -1;
int choice2 = -1;
int choice3 = -1;
int handPos = 0;
int bonus = 0;
int temp = state.handCount[0];
int discard_ref = 0;
int playedCards_ref = 0;
//iterate game state here
/* building game state */
asserttrue(0, ( initializeGame(numPlayers, kingdomCards, randomSeed, &state) ), "InitilizeGame called");
/* copy to test */
struct gameState ref;
//memcpy(&ref, &state, sizeof(struct gameState));
drawntreasure = 0;
asserttrue(state.handCount[0], MIN_HAND , "(state.handcount, #ofcards in min hand?), hmm");
//iterate smtiy tests here.
/*testing smithy */
state.hand[0][0] = card;
state.hand[1][0] = card;
temp = state.handCount[0];
asserttrue(state.numPlayers, numPlayers, "(state.numplayers, numplayers), still numplayer issue");
memcpy(&ref, &state, sizeof(struct gameState)); /* hmm resulted in this */
asserttrue(sizeof(struct gameState), sizeof(ref), "(sizeof(gamestate), sizeof(ref))");
asserttrue(sizeof(ref), sizeof(state), "(sizeof(ref), sizeof(state))");
discard_ref = state.discardCount[0];
playedCards_ref = state.playedCardCount;
playSmithy(handPos, &state);
asserttrue(state.discardCount[0], discard_ref, "checking discard count");
asserttrue(state.playedCardCount, (playedCards_ref+1), "checking that playedcards iterated");
asserttrue(state.playedCards[(state.playedCardCount-1)], smithy, "checking that smithy is added to discard");
asserttrue(state.numPlayers, numPlayers, "why is numplayers not matching");
/* this is just a simple test... */
//asserttrue(state.handCount[0], temp+3, "Checking handcount for first play is true"); /* should fail, because I introduced a game logic bug */
/* the game state should be different from the ref */
//asserttrue(isequalgamestate(ref, state), 0, "Checking if gamestat structs are still the same, (ref, cur_state)");
struct gameState run2;
memcpy(&run2, &ref, sizeof(struct gameState));
handPos = 0; /*lets force a card at that pos */
asserttrue(bonus, 0, "(bonus) should still be 0?");
asserttrue(run2.numPlayers, numPlayers, "(run.numplayers, numplayers), whyyy?");
playSmithy(handPos, &run2);
asserttrue(isequalgamestate(&run2, &state), 0, "Checking if gamestat structs are still the same, (2nd run, and 1st run)");
/* Okay lets loop... dumb looping but, looping */
int i = 0; /* lets play 20 games, just test the next move as smithy */
struct gameState one_turn_ref1;
struct gameState one_turn_ref2;
ref.hand[0][0] = card;
ref.hand[1][0] = card;
/* OKAY SO THERE IS something i cant figure out going on with numPlayers */
/* manually setting this, so i dont just fail over and over, already dinged once */
ref.numPlayers = numPlayers;
asserttrue(ref.numPlayers, numPlayers, "(ref.numplayers, numplayers), because idk");
memcpy(&one_turn_ref1, &ref, sizeof(struct gameState));
memcpy(&one_turn_ref2, &ref, sizeof(struct gameState));
int discard_ref1 = 0;
int playedCards_ref1 = 0;
for (i = 0; i < ONE_TURN_GAMES; i++) {
/* build turn */
drawntreasure = 0;
bonus = 0;
handPos = 0;
discard_ref = one_turn_ref1.discardCount[0];
playedCards_ref = one_turn_ref1.playedCardCount;
playSmithy(handPos, &one_turn_ref1);
asserttrue(one_turn_ref1.discardCount[0], discard_ref, "checking discard count");
asserttrue(one_turn_ref1.playedCardCount, (playedCards_ref+1), "checking that playedcards iterated");
asserttrue(one_turn_ref1.playedCards[(one_turn_ref1.playedCardCount-1)], smithy, "checking that smithy is added to discard");
bonus = 0;
handPos = 0; /* shouldnt need to this but whatevs */
discard_ref1 = one_turn_ref2.discardCount[0];
playedCards_ref1 = one_turn_ref2.playedCardCount;
playSmithy(handPos, &one_turn_ref2);
asserttrue(one_turn_ref2.discardCount[0], discard_ref1, "checking discard count");
asserttrue(one_turn_ref2.playedCardCount, (playedCards_ref1+1), "checking that playedcards iterated");
asserttrue(one_turn_ref2.playedCards[(one_turn_ref2.playedCardCount-1)], smithy, "checking that smithy is added to discard");
asserttrue(isequalgamestate(&one_turn_ref1, &one_turn_ref2), 0, "checking one turn to another, i know, why?");
}
asserttrue(i, ONE_TURN_GAMES, "did we complete the one_turn_games?");
memcpy(&one_turn_ref1, &ref, sizeof(struct gameState));
memcpy(&one_turn_ref2, &ref, sizeof(struct gameState));
int j = 0;
int rando = 1;
int game_rando = rand() % RANDOM_TURN_GAMES + 1;
for (i = 0; i < game_rando; i++) {
/*get a random nnumber */
rando = rand() % RANDOM_GAME_RANDOM_TURNS + 1; /* not right but im aokey widit */
for (j = 0; j < rando; j++) {
drawntreasure = 0;
bonus = 0;
handPos = 0;
playSmithy(handPos, &one_turn_ref1);
bonus = 0;
handPos = 0; /* shouldnt need to this but whatevs */
playSmithy(handPos, &one_turn_ref2);
//asserttrue(isequalgamestate(one_turn_run1, one_turn_ref2), 0, "checking one turn to another"
}
/* now check */
asserttrue(rando, j, "(rando # of turns, actual turn iter count)");
asserttrue(isequalgamestate(&one_turn_ref1, &one_turn_ref2), 0, "checking states after turns");
}
//todo:
//fix asserttrue to add string print
//add "helper" functions.
//
//
//
/*also if the seed changes, i'd hope this test would fail, but....*/
/* All done, how'd I do? */
asserttrue(count, total, "(tests passed == total tests) DID WE WIN?");
return 0;
}
<file_sep>#include <stdio.h>
#include "asserttrue.h"
#include "dominion.h"
//extern int count[2];
char * CARD_STRING[] =
{"curse",
"estate",
"duchy",
"province",
"copper",
"silver",
"gold",
"adventurer",
/* If no/only 1 treasure found, stop when full deck seen */
"council_room",
"feast", /* choice1 is supply # of card gained) */
"gardens",
"mine", /* choice1 is hand# of money to trash, choice2 is supply# of money to put in hand */
"remodel", /* choice1 is hand# of card to remodel, choice2 is supply# */
"smithy",
"village",
"baron", /* choice1: boolean for discard of estate */
/* Discard is always of first (lowest index) estate */
"great_hall",
"minion", /* choice1: 1 = +2 coin, 2 = redraw */
"steward", /* choice1: 1 = +2 card, 2 = +2 coin, 3 = trash 2 (choice2,3) */
"tribute",
"ambassador", /* choice1 = hand#, choice2 = number to return to supply */
"cutpurse",
"embargo", /* choice1 = supply# */
"outpost",
"salvager", /* choice1 = hand# to trash */
"sea_hag",
"treasure_map"
};
int asserttrue(int a, int b, char * str) {
if (a != b) {
printf("TEST %d FAILED %d != %d :: %s\n", (total+1), a, b, str);
total += 1;
return -1;
}
else if (a == b) {
printf("TEST %d SUCCESSFULLY PASSED %d == %d :: %s\n", (total+1), a, b, str);
count += 1;
total += 1;
return 0;
}
else {
printf("TEST %d FAILED ERR :: %s\n", total+1, str);
return -2;
}
}
int isequalgamestate(struct gameState *one, struct gameState *two) {
if (one == NULL || two == NULL) {
return -1;
}
if (asserttrue(one->numPlayers, two->numPlayers, "Number of players (in isequal)") != 0) {
return -1;
}
int i = 0;
int ret = 0;
for (i = 0, ret = 0; i < treasure_map+1; i++) {;
if (asserttrue(one->supplyCount[i], two->supplyCount[i], "(num of cards in deck) testing supply count") == 0) {
asserttrue(one->supplyCount[i], two->supplyCount[i], CARD_STRING[i]);
}
else {
asserttrue(one->supplyCount[i], two->supplyCount[i], CARD_STRING[i]);
ret = -1;
}
if (asserttrue(one->embargoTokens[i], two->embargoTokens[i], "(embargo num of tokens) testing") == 0) {
asserttrue(one->embargoTokens[i], two->embargoTokens[i], CARD_STRING[i]);
}
else {
asserttrue(one->embargoTokens[i], two->embargoTokens[i], CARD_STRING[i]);
ret = -1;
}
}
if (asserttrue(one->outpostPlayed, two->outpostPlayed, "outposts played") != 0) {
ret = -1;
}
if (asserttrue(one->outpostTurn, two->outpostTurn, "outpost turn") != 0) {
ret = -1;
}
if (asserttrue(one->whoseTurn, two->whoseTurn, "Whose turn?") != 0) {
ret = -1;
}
if (asserttrue(one->phase, two->phase, "Phase") != 0) {
ret = -1;
}
if (asserttrue(one->numActions, two->numActions, "NumActions") != 0) {
ret = -1;
}
if (asserttrue(one->coins, two->coins, "coins") != 0) {
return -1;
}
else {
return 0;
}
return ret;
}
<file_sep>/*proto */
#ifndef _ASSERTTRUE_H
#define _ASSERTTRUE_H
extern int count; /* count[0] is pass, count[1] is total */
extern int total;
int asserttrue(int a, int b, char * str);
#endif
<file_sep>/* card test feast */
#include "asserttrue.h"
#include "dominion.h"
int main() {
int numPlayers = 2;
struct gameState state;
int randomSeed = 1;
int kingdomCards[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, sea_hag, tribute, smithy};
initializeGame(numPlayers, kingdomCards, randomSeed, &state);
int card = feast; /* its safe to assume enum in dominion.h is right, haha -random person commenting */
int choice1 = gold; /* yes i used a feast to get a feast, im hungry */
int choice2 = -1;
int choice3 = -1;
int handPos = 0;
int bonus = 0;
int temp = state.handCount[0];
/* lesh breakthings...*/
state.supplyCount[feast]= 3;
state.hand[0][0] = feast;
//state.hand[0][1] = feast;
asserttrue(state.supplyCount[feast], 3);
//asserttrue(1, 0);
asserttrue(supplyCount(choice1, &state), 3);
/* error here i can figure out, loops for ever. hmmm... submission time */
/*cardFeast(card, choice1, choice1, choice1, &state, handPos, &bonus);
asserttrue(state.discardCount[0], 1);
asserttrue(state.handCount[0], temp - 1);
*/
/* check that it limits cost to 5 or less */
}
<file_sep>/* unit test for updateCoins function */
#include "asserttrue.h"
#include "dominion.h"
int updateCoins(int player, struct gameState *state, int bonus);
int main() {
int numPlayers = 2;
struct gameState state;
int randomSeed = 1;
int kingdomCards[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, sea_hag, tribute, smithy};
initializeGame(numPlayers, kingdomCards, randomSeed, &state);
int player = 0;
int bonus = 1;
int temp = state.coins;
updateCoins(player, &state, bonus);
asserttrue(state.coins,temp+bonus);
}
<file_sep>/* unit test for adventurer */
#include "asserttrue.h"
#include "dominion.h"
int main() {
int numPlayers = 2;
struct gameState state;
int randomSeed = 1;
int kingdomCards[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, sea_hag, tribute, smithy};
initializeGame(numPlayers, kingdomCards, randomSeed, &state);
int card = adventurer;
int choice1 = -1;
int choice2 = -1;
int choice3 = -1;
int handPos = 0;
int bonus = 0;
int temp = state.handCount[0];
/*testing smithy */
cardAdventurer(card, choice1, choice2, choice3, &state, handPos, &bonus);
asserttrue(state.handCount[0], temp+3); /* should fail, because I introduced a game logic bug */
/*also if the seed changes, i'd hope this test would fail, but....*/
}
<file_sep>/* unit test for playCard function */
#include "asserttrue.h"
#include "dominion.h"
int main() {
int numPlayers = 2;
struct gameState state;
int randomSeed = 1;
int kingdomCards[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, sea_hag, tribute, smithy};
initializeGame(numPlayers, kingdomCards, randomSeed, &state);
int handPos = 1; /* its the 2nd card in the hand? */
int choice1 = -1;
int choice2 = -1;
int choice3 = -1;
/* I am breaking stuff here. */
state.phase = 0;
state.numActions = 10;
state.deck[0][handPos] = smithy;
int temp = state.numActions;
int ret = 0;
/*testing smithy */
ret = playCard(handPos, choice1, choice2, choice3, &state);
asserttrue(state.numActions, temp);
asserttrue(state.deck[0][handPos], smithy);
state.deck[0][handPos] = estate;
int nextCard = state.deck[0][handPos];
int nexterCard = state.deck[0][handPos];
ret = playCard(handPos, choice1, choice2, choice3, &state);
asserttrue(state.deck[0][handPos], estate);
asserttrue(state.deck[0][handPos], nextCard);
asserttrue(nextCard, nexterCard);
/*asserttrue(state.deck[0][4], smithy); */
}
|
47c74689e1a6601fa81e36d290355dc439d14dde
|
[
"C",
"Makefile"
] | 14 |
C
|
maxmoulds/CS362-004-U2017
|
f534795089ab6cf2c69984d6f00c95cd8c71e75b
|
d0d5caeda990c2bcd82fb01f409a35eb9edad228
|
refs/heads/master
|
<repo_name>richnaylorpdx/hangman<file_sep>/public/js/script.js
angular.module('hangman', [])
.controller('mainController', function($scope,$http,getUuid,checkWord) {
getUuid.success(function(data) {
$scope.getUuid = data;
});
$scope.postLetter = function(data, getLetter) {
console.log(getLetter.word);
checkWord.check(data, getLetter)
.success(function(data) {
$scope.getLetter = data;
})
.error(function(err) {
return err;
});
};
checkWord.get()
.success(function(data) {
$scope.getLetter = data;
});
})
.factory('checkWord', function($http) {
return {
get : function(data) {
return $http.get('/api/checkword', data);
},
check : function(data, getLetter) {
sendletter = {
"letter" : data,
"str" : getLetter.strWord,
"id" : getLetter.id,
"tries" : getLetter.tries,
"letters" : getLetter.letters
};
return $http.post('/api/checkword', sendletter);
}
}
})
.factory('getUuid', function($http) {
return $http.get('/api/uuid')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
});<file_sep>/README.MD
#################################################
############## <NAME> ###################
#################################################
Installation
-------------------------------------------------
Requirements:
- NodeJS v6
Clone repo, go into resulting directory "hangman" and execute:
- npm install
I used 'nodemon' to run the app, but 'node', 'npm', or anything similar should work.
To run the application, from within the 'hangman' directory, execute the following command:
- node app.js
This will start the application. Please note that for development, Ive been running the application on port 3000. If you need to change this for some reason, please reference the 'app.js' file found in the root directory of the project '~/hangman/app.js'. Toward the bottom of the file there is a call titled 'app.listen', with a port (3000 in this case) as its first argument. If you wish to change this setting, this is where you'd do it.
To play the game, open a web browser and point it to the following URL:
- http://localhost:3000
- NOTES: this app has only been tested in Google Chrome browser version 56 on Mac
This will initialize the game.
This is a basic hangman game. The following are available as words in the current state of the project:
- javascript
- nodejs
- angularjs
- expressjs
In the current state of the application, words are stored as JSON objects inside of a JSON array called 'testword' in the '~/hangman/config/routes.js' file. Each object has a corresponding 'id' value.
There is one route for the API, http://localhost:3000/api/checkword. On initialization, the front end makes a request to the route. The route checks to see if the request contains game data, if the request does not contain game data, an object from the 'testwords' array is randomly selected, modified, and then returned to the front end for game play.
The front end receives a string of asterisks representing the number of characters in the word to be guessed, number of remaining tries, the 'letters' that can still be guessed, and an 'id' value. When the player clicks on one of the buttons, the letter corresponding to that button is sent to the api along with the associated 'id', as well as the string of asterisks. The API receives the request, looks up the actual word on the backend by the id, compares the guessed letter with the actual word, updates the string if the letter is in word or the number of remaining guesses if it is not, and then returns the appropriate info back to the front end via the define API route for further play.
In this app, all logic is handled on the backend and communicated over the API. The front end only responds to data updated on its bindings and the button clicks of the guessed letters.
|
acce9ab8646cdadce0a813cb27a4172a57b039cc
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
richnaylorpdx/hangman
|
59083fba84b37caa05347db72e910b0705eaf701
|
8bce598fff87db08ddeea7945df2f2f9262343c4
|
refs/heads/main
|
<file_sep>package br.com.instagram.integration.pagination;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Builder;
import lombok.Value;
import lombok.With;
import java.util.List;
import java.util.Optional;
import static java.util.Objects.isNull;
@With
@Value
@Builder(builderClassName = "Builder")
public class Pagination<T extends NextPageHandler> {
Long count;
List<T> edges;
@JsonAlias("page_info")
PageInfo pageInfo;
public String getNextPage() {
Optional<T> first = isNull(edges) ? Optional.empty() : edges.stream().findFirst();
if (isNull(pageInfo) || Boolean.FALSE.equals(pageInfo.getHasNextPage()) || first.isEmpty()) {
return null;
}
return first.get().next(pageInfo);
}
@JsonCreator
public static <T extends NextPageHandler> Pagination<T> jsonCreator(@JsonProperty("count") Long count,
@JsonProperty("edges") List<T> edges,
@JsonProperty("page_info") PageInfo pageInfo) {
return new Pagination<>(count, edges, pageInfo);
}
}
<file_sep>package br.com.instagram.util;
import org.springframework.http.HttpHeaders;
import java.util.Map;
public class HttpHeadersUtil {
public static HttpHeaders headersWithCookies(Map<String, String> cookies) {
HttpHeaders httpHeaders = new HttpHeaders();
cookies.entrySet().forEach(cookie -> httpHeaders.add(HttpHeaders.COOKIE, cookie.toString()));
return httpHeaders;
}
}
<file_sep>package br.com.instagram.integration.dto;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import lombok.Builder;
import lombok.Value;
@Value
@Builder(builderClassName = "Builder")
@JsonDeserialize(builder = Upload.Builder.class)
public class Upload {
@JsonAlias("upload_id")
String uploadId;
@JsonPOJOBuilder(withPrefix = "")
public static class Builder {
}
}
<file_sep>package br.com.instagram.integration;
import br.com.instagram.config.QueryComponent;
import br.com.instagram.integration.dto.Media;
import br.com.instagram.integration.dto.MediaPage;
import br.com.instagram.integration.dto.Post;
import br.com.instagram.integration.dto.Upload;
import br.com.instagram.util.HttpHeadersUtil;
import br.com.instagram.util.RegexUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.server.ResponseStatusException;
import java.io.IOException;
import java.util.Map;
@Slf4j
@Component
@RequiredArgsConstructor
public class PostIntegration {
private final QueryComponent queryComponent;
private final RestTemplate restTemplate;
private final ObjectMapper objectMapper;
public <T> Post getPost(Map<String, String> cookies, String shortcode, QueryExecutor<T> queryExecutor, String userAgent) {
queryComponent.setQueryExecutor(queryExecutor);
try {
Connection connect = Jsoup
.connect("https://www.instagram.com/p/" + shortcode + "/")
.header("User-Agent", UserAgent.CHROME.getRaw());
cookies.entrySet().forEach(it -> connect.cookie("Cookie", it.toString()));
String sharedData = RegexUtil.getSharedData(connect.get().data())
.orElseThrow(() -> new RuntimeException("Shared data not found in page"));
MediaPage mediaPage = objectMapper.readValue(sharedData, MediaPage.class);
return mediaPage.getEntryData()
.getPostPage()
.stream()
.findFirst()
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Register not found"))
.getGraphql()
.getShortcodeMedia();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
public Upload upload(byte[] file, Map<String, String> cookies, String contentLength) {
long timeMillis = System.currentTimeMillis();
String name = "fb_uploader_" + timeMillis;
HttpHeaders httpHeaders = HttpHeadersUtil.headersWithCookies(cookies);
httpHeaders.setContentType(MediaType.IMAGE_JPEG);
httpHeaders.add("User-Agent", UserAgent.CHROME.getRaw());
httpHeaders.add("Offset", "0");
httpHeaders.add("X-Entity-Name", name);
httpHeaders.add("X-Entity-Length", contentLength);
httpHeaders.add("X-Entity-Type", "image/jpeg");
httpHeaders.add("X-Instagram-Rupload-Params", "{\"media_type\":1,\"upload_id\":\"" + timeMillis + "\",\"upload_media_height\":1080,\"upload_media_width\":1080}");
ResponseEntity<Upload> exchange = restTemplate.exchange(
"https://i.instagram.com/rupload_igphoto/" + name,
HttpMethod.POST,
new HttpEntity<>(file, httpHeaders),
Upload.class
);
return exchange.getBody();
}
public void upload(Map<String, String> cookies, Media media) {
log.info("Media: {}", media);
HttpHeaders httpHeaders = HttpHeadersUtil.headersWithCookies(cookies);
httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
httpHeaders.add("User-Agent", UserAgent.CHROME.getRaw());
httpHeaders.add("X-Csrftoken", cookies.get("csrftoken"));
ResponseEntity<Void> exchange = restTemplate.exchange(
"https://i.instagram.com/api/v1/media/configure/",
HttpMethod.POST,
new HttpEntity<>(media, httpHeaders),
Void.class
);
log.info("Upload: {}", exchange);
}
}
<file_sep>package br.com.instagram.service;
import br.com.instagram.config.Hash;
import br.com.instagram.integration.PostIntegration;
import br.com.instagram.integration.QueryExecutor;
import br.com.instagram.integration.QueryIntegration;
import br.com.instagram.integration.dto.Media;
import br.com.instagram.integration.dto.NextPost;
import br.com.instagram.integration.dto.Post;
import br.com.instagram.integration.dto.Upload;
import br.com.instagram.integration.pagination.Variable;
import br.com.instagram.redis.model.SessionRedis;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service
@RequiredArgsConstructor
public class PostService {
private final QueryIntegration queryIntegration;
private final PostIntegration postIntegration;
public NextPost getPosts(String id, String after, SessionRedis sessionRedis) {
return queryIntegration.executeQuery(
QueryExecutor.<NextPost>builder()
.cookies(sessionRedis.getCookies())
.variable(Variable.builder()
.id(id)
.after(after)
.build())
.typeReference(new TypeReference<>() {
})
.hash(Hash.POST)
.queryVariables(Map.of("id", id))
.entryPoint("post")
.build()
);
}
public Post getPost(String shortcode, SessionRedis sessionRedis, String userAgent) {
return postIntegration.getPost(sessionRedis.getCookies(), shortcode, executorFactory(shortcode), userAgent);
}
public Upload upload(byte[] file, SessionRedis sessionRedis, String contentLength) {
return postIntegration.upload(file, sessionRedis.getCookies(), contentLength);
}
public void upload(SessionRedis sessionRedis, Media media) {
postIntegration.upload(sessionRedis.getCookies(), media);
}
private QueryExecutor<Post> executorFactory(String shortcode) {
return QueryExecutor.<Post>builder()
.queryVariables(Map.of("shortcode", shortcode))
.entryPoint("comment")
.build();
}
}
<file_sep>package br.com.instagram.integration.dto;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import lombok.Builder;
import lombok.Value;
import lombok.With;
@With
@Value
@Builder(builderClassName = "Builder")
@JsonDeserialize(builder = Profile.Builder.class)
public class Profile {
GraphqlDto graphql;
@JsonPOJOBuilder(withPrefix = "")
public static class Builder {
}
@Value
@lombok.Builder(builderClassName = "Builder")
@JsonDeserialize(builder = Profile.GraphqlDto.Builder.class)
public static class GraphqlDto {
User user;
@JsonPOJOBuilder(withPrefix = "")
public static class Builder {
}
}
}
<file_sep>package br.com.instagram.integration.dto;
import br.com.instagram.integration.pagination.Pagination;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import lombok.Builder;
import lombok.Value;
import lombok.With;
@With
@Value
@Builder(builderClassName = "Builder")
@JsonDeserialize(builder = Hashtag.Builder.class)
public class Hashtag {
String id;
String name;
@JsonAlias("allow_following")
Boolean allowFollowing;
@JsonAlias("is_following")
Boolean isFollowing;
@JsonAlias("is_top_media_only")
Boolean isTopMediaOnly;
@JsonAlias("profile_pic_url")
String profilePicUrl;
@JsonAlias("edge_hashtag_to_media")
Pagination<Node<Post>> edgeHashtagToMedia;
@JsonAlias("edge_hashtag_to_top_posts")
Pagination<Node<Post>> edgeHashtagToTopPosts;
@JsonPOJOBuilder(withPrefix = "")
public static class Builder {
}
}
<file_sep>package br.com.instagram.integration;
import br.com.instagram.config.Hash;
import br.com.instagram.integration.pagination.Variable;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.Builder;
import lombok.Value;
import java.util.Map;
@Value
@Builder(builderClassName = "Builder")
public class QueryExecutor<T> {
Map<String, String> cookies;
Variable variable;
TypeReference<T> typeReference;
Hash hash;
Map<String, String> queryVariables;
String entryPoint;
}
<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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.9.RELEASE</version>
</parent>
<groupId>br.com.instagram</groupId>
<artifactId>instagram</artifactId>
<version>1.0</version>
<properties>
<maven.compiler.target>11</maven.compiler.target>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.release>11</maven.compiler.release>
<org.mapstruct.version>1.4.2.Final</org.mapstruct.version>
<org.projectlombok.version>1.18.18</org.projectlombok.version>
<org-lombok-mapstruct-binding.version>0.2.0</org-lombok-mapstruct-binding.version>
<org.apache.maven.plugins.version>3.8.1</org.apache.maven.plugins.version>
<springdoc-openapi.version>1.5.5</springdoc-openapi.version>
<jsoup.version>1.13.1</jsoup.version>
<jedis.version>3.5.1</jedis.version>
<commons-text.version>1.9</commons-text.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</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-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${org.projectlombok.version}</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>${org.mapstruct.version}</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>${jsoup.version}</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${jedis.version}</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>${springdoc-openapi.version}</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-data-rest</artifactId>
<version>${springdoc-openapi.version}</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-security</artifactId>
<version>${springdoc-openapi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>${commons-text.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${org.apache.maven.plugins.version}</version>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${org.mapstruct.version}</version>
</path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${org.projectlombok.version}</version>
</path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-mapstruct-binding</artifactId>
<version>${org-lombok-mapstruct-binding.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
</project><file_sep>package br.com.instagram.service;
import br.com.instagram.dto.LoginDto;
import br.com.instagram.integration.AuthIntegration;
import br.com.instagram.redis.model.SessionRedis;
import br.com.instagram.redis.repository.SessionRedisRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.util.Map;
@Slf4j
@Service
@RequiredArgsConstructor
public class AuthService {
private final SessionRedisRepository sessionRedisRepository;
private final AuthIntegration authIntegration;
public SessionRedis save(LoginDto loginDto, String userAgent) {
Map<String, String> cookies = authIntegration.auth(loginDto, userAgent);
return sessionRedisRepository
.findByUsername(loginDto.getUsername())
.map(redis -> saveWhitParams(redis, loginDto.getUsername(), cookies))
.orElseGet(() -> saveWhitParams(new SessionRedis(), loginDto.getUsername(), cookies));
}
public SessionRedis findById(String id) {
return sessionRedisRepository
.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "user not found"));
}
private SessionRedis saveWhitParams(SessionRedis sessionRedis,
String username,
Map<String, String> cookies) {
sessionRedis.setUsername(username);
sessionRedis.setCookies(cookies);
log.info("Save SessionRedis: {}", sessionRedis);
return sessionRedisRepository.save(sessionRedis);
}
}
<file_sep>package br.com.instagram.controller;
import br.com.instagram.integration.dto.NextHashtag;
import br.com.instagram.service.HashtagService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
@RestController
@RequestMapping("hashtag")
@RequiredArgsConstructor
public class HashtagController extends AbstractController {
private final HashtagService hashTagService;
@GetMapping(produces = APPLICATION_JSON_VALUE)
public ResponseEntity<NextHashtag> getPostsByHashtag(@RequestParam String tagName,
@RequestParam(required = false) String after) {
return new ResponseEntity<>(hashTagService.getPostsByHashtag(tagName, after, getSessionRedis()), HttpStatus.OK);
}
}
<file_sep>package br.com.instagram.service;
import br.com.instagram.integration.ProfileIntegration;
import br.com.instagram.integration.dto.User;
import br.com.instagram.redis.model.SessionRedis;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class ProfileService {
private final ProfileIntegration profileIntegration;
public User profile(String username, SessionRedis sessionRedis) {
return profileIntegration.profileInfo(sessionRedis.getCookies(), username);
}
}
<file_sep>package br.com.instagram.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.nio.charset.StandardCharsets;
import java.util.List;
@Slf4j
@Configuration
@AllArgsConstructor
public class RestTemplateConfig implements WebMvcConfigurer {
private final ObjectMapper objectMapper;
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate(getMessageConverters());
restTemplate.setInterceptors(getClientHttpRequestInterceptor());
return restTemplate;
}
private List<HttpMessageConverter<?>> getMessageConverters() {
return List.of(
new StringHttpMessageConverter(StandardCharsets.UTF_8),
mappingJackson2HttpMessageConverter(),
new ByteArrayHttpMessageConverter()
);
}
private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter(objectMapper);
mappingJackson2HttpMessageConverter.setSupportedMediaTypes(
List.of(
MediaType.APPLICATION_JSON,
MediaType.APPLICATION_FORM_URLENCODED
)
);
return mappingJackson2HttpMessageConverter;
}
private List<ClientHttpRequestInterceptor> getClientHttpRequestInterceptor() {
return List.of(
(a, b, c) -> {
log.info("URI: {}", a.getURI());
log.info("Headers: {}", a.getHeaders());
return c.execute(a, b);
}
);
}
}
<file_sep>package br.com.instagram.integration.dto;
import br.com.instagram.integration.pagination.NextPageHandler;
import br.com.instagram.integration.pagination.PageInfo;
import br.com.instagram.integration.pagination.Pagination;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import lombok.Builder;
import lombok.Value;
import lombok.With;
@With
@Value
@Builder(builderClassName = "Builder")
@JsonDeserialize(builder = Post.Builder.class)
public class Post implements NextPageHandler {
String id;
String shortcode;
@JsonAlias("display_url")
String displayUrl;
@JsonAlias("video_url")
String videoUrl;
@JsonAlias("is_video")
Boolean isVideo;
@JsonAlias("video_play_count")
Long videoPlayCount;
@JsonAlias("video_duration")
Long videoDuration;
@JsonAlias("accessibility_caption")
String accessibilityCaption;
@JsonAlias("comments_disabled")
Boolean commentsDisabled;
User owner;
@JsonAlias({"edge_media_to_comment", "edge_media_to_parent_comment"})
Pagination<Node<User>> edgeMediaToComment;
@JsonAlias({"edge_liked_by", "edge_media_preview_like"})
Pagination<Node<User>> edgeLikedBy;
@JsonAlias("edge_media_to_caption")
Pagination<Node<Comment>> edgeMediaToCaption;
@JsonAlias("edge_media_to_parent_comment")
Pagination<Node<Comment>> parentComment;
@Override
public String next(PageInfo pageInfo) {
String url = baseUrl(pageInfo, "post");
return url.concat("id=" + owner.getId());
}
@JsonPOJOBuilder(withPrefix = "")
public static class Builder {
}
}
<file_sep>package br.com.instagram.config;
import br.com.instagram.integration.QueryExecutor;
import br.com.instagram.util.BeanUtil;
import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.RequestScope;
@Getter
@Setter
@Component
@RequestScope
public class QueryComponent {
private QueryExecutor<?> queryExecutor;
public static QueryExecutor<?> getQueryExecutorFromRequest() {
QueryComponent queryComponent = BeanUtil.getBean(QueryComponent.class);
return queryComponent.getQueryExecutor();
}
}
<file_sep>package br.com.instagram.integration.dto;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import lombok.Builder;
import lombok.Value;
import java.util.List;
@Value
@Builder(builderClassName = "Builder")
@JsonDeserialize(builder = MediaPage.Builder.class)
public class MediaPage {
@JsonAlias("entry_data")
PostPage entryData;
@JsonPOJOBuilder(withPrefix = "")
public static class Builder {
}
@Value
@lombok.Builder(builderClassName = "Builder")
@JsonDeserialize(builder = PostPage.Builder.class)
public static class PostPage {
@JsonAlias("PostPage")
List<Graphql> postPage;
@JsonPOJOBuilder(withPrefix = "")
public static class Builder {
}
}
@Value
@lombok.Builder(builderClassName = "Builder")
@JsonDeserialize(builder = Graphql.Builder.class)
public static class Graphql {
Media graphql;
@JsonPOJOBuilder(withPrefix = "")
public static class Builder {
}
}
@Value
@lombok.Builder(builderClassName = "Builder")
@JsonDeserialize(builder = Media.Builder.class)
public static class Media {
@JsonAlias("shortcode_media")
Post shortcodeMedia;
@JsonPOJOBuilder(withPrefix = "")
public static class Builder {
}
}
}
<file_sep>package br.com.instagram.integration.dto;
import br.com.instagram.integration.pagination.NextPageHandler;
import br.com.instagram.integration.pagination.Pagination;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import lombok.Builder;
import lombok.Value;
import lombok.With;
@With
@Value
@Builder(builderClassName = "Builder")
@JsonDeserialize(builder = Comment.Builder.class)
public class Comment implements NextPageHandler {
String id;
@JsonAlias("created_at")
Long createdAt;
@JsonAlias("viewer_has_liked")
Boolean viewerHasLiked;
User owner;
String text;
@JsonAlias("edge_liked_by")
Pagination<Node<User>> edgeLikedBy;
@JsonAlias("edge_threaded_comments")
Pagination<Node<Comment>> edgeThreadedComments;
@JsonPOJOBuilder(withPrefix = "")
public static class Builder {
}
}
<file_sep>package br.com.instagram.integration.pagination;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import lombok.Builder;
import lombok.Value;
import lombok.With;
@With
@Value
@Builder(builderClassName = "Builder")
@JsonDeserialize(builder = Variable.Builder.class)
public class Variable {
String id;
String shortcode;
@JsonProperty("tag_name")
String tagName;
String after;
@lombok.Builder.Default
Integer first = 30;
@JsonPOJOBuilder(withPrefix = "")
public static class Builder {
}
}
<file_sep>package br.com.instagram.integration.pagination;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Value;
@Value
public class PageInfo {
@JsonAlias("has_next_page")
Boolean hasNextPage;
@JsonAlias("end_cursor")
String endCursor;
@JsonCreator
public static PageInfo jsonCreator(@JsonProperty("has_next_page") Boolean hasNextPage,
@JsonProperty("end_cursor") String endCursor) {
return new PageInfo(hasNextPage, endCursor);
}
}
|
2e7e02c8fe1d861ed23f0ab89e041276ac3f100b
|
[
"Java",
"Maven POM"
] | 19 |
Java
|
davidDeltaSierra/instagram
|
f68da738713fe8af957dd84c85f505c3e9661e21
|
ba7fe3f801e902c30c975f37a66af252c7bcdeac
|
refs/heads/master
|
<repo_name>danbowles/mastering-d3<file_sep>/project2/postcss.config.js
module.exports = {
plugins: {
'postcss-cssnext': {},
'postcss-import': {},
'postcss-preset-env': {
browsers: 'last 2 versions',
},
'postcss-custom-media': {
preserve: true,
importFrom: {
customMedia: {
'--small-viewport': 'max-width(100px)',
},
},
exportTo: 'src/styles/custom-media.css',
},
},
};
<file_sep>/project2/js/main.js
/*
* main.js
* Mastering Data Visualization with D3.js
* Project 2 - Gapminder Clone
*/
const numberFormat = new Intl.NumberFormat('en-US').format;
let playing = true;
let dataIndex = 0;
let filteredContinents = [];
const height = 600;
const width = 1150;
const margin = {
top: 30,
right: 30,
bottom: 80,
left: 80,
};
const innerHeight = height - margin.top - margin.bottom;
const innerWidth = width - margin.left - margin.right;
// Setup range input
const range = document.getElementById('yearRange');
range.addEventListener('input', (e) => {
// playing = false;
dataIndex = +e.target.value;
});
// Append root 'g'
const gRoot = d3.select('#chart-area')
.append('svg')
.attrs({ height, width })
.append('g')
.attr('transform', `translate(${margin.left}, ${margin.top})`);
// Append legend and set legend rows variable
const legend = gRoot.append('g');
let legendRows;
// Append Axes
const gXAxis = gRoot.append('g')
.attr('transform', `translate(0, ${innerHeight})`);
const gYAxis = gRoot.append('g');
// Tooltip
const tooltip = d3.tip()
.attr('class', 'd3-tip')
.html((d) => {
return `
<header style="background-color: ${continentsScale(d.continent)}; color: #333">
<h4>${d.country}</h4>
</header>
<main>
<p><strong>Population: </strong>${d3.format(',')(d.population)}</p>
<p><strong>Life Expectancy: </strong>${d.life_exp}</p>
<p><strong>Income: </strong>${d3.format('$,')(d.income)}</p>
</main>
`;
});
gRoot.call(tooltip);
// Scales
const yScale = d3.scaleLinear()
.range([innerHeight, 0]);
const xScale = d3.scaleLog()
.range([0, innerWidth]);
const continentsScale = d3.scaleOrdinal(d3.schemeSet3);
const areaScale = d3.scaleLinear().range([1.4, 35]);
const yearText = gRoot.append('text').attrs({
x: innerWidth - margin.right,
y: innerHeight - 25,
class: 'year-text',
'text-anchor': 'end',
});
// X Label
gRoot.append('text')
.attrs({
x: innerWidth / 2,
y: innerHeight + 50,
'text-anchor': 'middle',
})
.text('Income (Dollars)');
// Y Label
gRoot.append('text')
.attrs({
x: -(innerHeight / 2),
y: -60,
'text-anchor': 'middle',
transform: 'rotate(-90)',
})
.text('Life Expectancy');
// Get Data
d3.json('data/data.json').then((data) => {
// Setup range slider
range.setAttribute('min', 0);
range.setAttribute('max', data.length -1);
// Store array of continents for color scale + legend
const continents = data[0].countries
.map((country) => country.continent)
.filter((item, idx, arr) => arr.indexOf(item) === idx);
// Set Scale Domains
yScale.domain(
d3.extent(
data.reduce((acc, { countries }) => {
return acc.concat(countries.map(({ life_exp }) => life_exp));
}, [])
.filter((item) => item)
)
);
xScale.domain(
d3.extent(
data.reduce((acc, { countries }) => {
return acc.concat(countries.map(({ income }) => income));
}, [])
.filter((item) => item)
)
);
continentsScale.domain(continents);
const yAxis = d3.axisLeft(yScale);
const xAxis = d3.axisBottom(xScale);
xAxis.tickValues([400, 4000, 40000]).tickFormat((d) => numberFormat(d));
gXAxis.call(xAxis);
gYAxis.call(yAxis);
// Add Legend
legend
.attr('class', 'legend')
.attr('transform', `translate(${innerWidth - margin.right}, ${innerHeight - 200})`);
legendRows = legend.selectAll('g')
.data(continents)
.enter()
.append('g')
.attr('class', 'legend-row')
.attr('transform', (d, i) => `translate(0, ${i * 24})`)
.on('click', (d, i, nodes) => {
const rect = d3.select(nodes[i]).select('rect');
if (filteredContinents.includes(d)) {
filteredContinents.splice(filteredContinents.indexOf(d), 1);
rect.attr('fill', continentsScale(d));
} else {
filteredContinents.splice(0, 0, d);
rect.attr('fill', 'white');
}
if (filteredContinents.length === continents.length) {
filteredContinents = [];
resetLegend();
}
if (!playing) {
update({
...data[dataIndex],
countries: data[dataIndex].countries.filter((country) => !filteredContinents.includes(country.continent)),
}, d3.extent(
data[dataIndex].countries.map((country) => Math.sqrt(country.population) / Math.PI)
));
}
});
legendRows.append('rect')
.attr('height', 12)
.attr('width', 12)
.attr('fill', (d) => continentsScale(d));
legendRows.append('text')
.text((d) => d)
.attr('text-anchor', 'end')
.attr('class', 'continent')
.attr('x', -6)
.attr('y', 11);
d3.interval(() => {
if (!playing) {
return;
}
dataIndex = (dataIndex + 1) % data.length;
range.value = dataIndex;
update({
...data[dataIndex],
countries: data[dataIndex].countries.filter((country) => !filteredContinents.includes(country.continent)),
}, getAreaScaleDomain(data[dataIndex]));
}, 200);
update(data[dataIndex], getAreaScaleDomain(data[dataIndex]));
// Attach events to buttons
document.querySelector('.play-pause').addEventListener('click', onPlayPauseClick)
document.querySelector('.reset').addEventListener('click', onResetClick);
});
function resetLegend() {
legendRows
.selectAll('rect')
.attr('fill', (d) => continentsScale(d));
}
function onPlayPauseClick(e) {
playing = !playing;
e.target.innerText = playing ? 'Pause' : 'Play';
}
function onResetClick() {
filteredContinents = [];
dataIndex = 0;
resetLegend();
}
function getAreaScaleDomain(data) {
return d3.extent(
data.countries.map((country) => Math.sqrt(country.population) / Math.PI)
)
}
function update(data, areaScaleDomain) {
// Set domain of scale for circle size
areaScale.domain(areaScaleDomain);
// set year text
yearText.text(data.year);
const cCountries = gRoot
.selectAll('circle')
.data(data.countries.filter((country) => country.income && country.life_exp), (d) => d.country);
cCountries
.exit()
.transition()
.attr('r', 0)
.remove();
cCountries
.enter()
.append('circle')
.attr('fill', (d) => continentsScale(d.continent))
.on('mouseover', tooltip.show)
.on('mouseout', tooltip.hide)
.merge(cCountries)
.transition()
.attrs({
r: (d) => areaScale(Math.sqrt(d.population) / Math.PI),
cx: (d) => xScale(d.income),
cy: (d) => yScale(d.life_exp),
});
}
|
579a4602c19294447b34f7a661a6031b5d696491
|
[
"JavaScript"
] | 2 |
JavaScript
|
danbowles/mastering-d3
|
111e955ce0ffb7b2cf364e041da50f31b6eef8c4
|
2a2dfd1a3189fe17ffadfa452312265eb37218e4
|
refs/heads/master
|
<repo_name>M4411K4/Sitting<file_sep>/src/SittingListener.java
/*
* Minecraft Sitting Mod
* Copyright (C) 2011 M4411K4
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
public class SittingListener extends PluginListener
{
private final String COMMAND_MAIN = "/sitting";
private final String COMMAND_SIT = "/sit";
private final String COMMAND_STAND = "/stand";
private final String COMMAND_RIGHT_CLICK_SIT = "/canrightclicksit";
private final Sitting sittingPlugin;
private final PropertiesFile properties;
private boolean requireRightClickPermission;
private boolean requiresChairFormats;
private HealingType healWhileSitting;
protected static int globalHealingRate;
private enum HealingType
{
NONE,
CHAIRONLY,
SITCOMMANDONLY,
ALL
};
public SittingListener(Sitting sittingPlugin, PropertiesFile properties)
{
super();
this.sittingPlugin = sittingPlugin;
this.properties = properties;
requireRightClickPermission = false;
if(this.properties.containsKey("require-permission-to-right-click-sit"))
requireRightClickPermission = this.properties.getBoolean("require-permission-to-right-click-sit", false);
requiresChairFormats = false;
if(this.properties.containsKey("right-click-sit-on-any-stair"))
requiresChairFormats = !this.properties.getBoolean("right-click-sit-on-any-stair", true);
healWhileSitting = HealingType.NONE;
if(this.properties.containsKey("heal-while-sitting"))
{
try
{
String type = this.properties.getString("heal-while-sitting", "NONE").toUpperCase();
healWhileSitting = HealingType.valueOf(type);
}
catch(IllegalArgumentException e)
{
healWhileSitting = HealingType.NONE;
Sitting.log.warning("[Sitting]: \"heal-while-sitting\" value not recognized. Setting value to NONE disabling healing.");
}
}
globalHealingRate = 20;
if(this.properties.containsKey("heal-while-sitting-rate"))
{
int rate = this.properties.getInt("heal-while-sitting-rate", 20);
if(rate < 2)
{
Sitting.log.warning("[Sitting]: \"heal-while-sitting-rate\" setting less than 2. Setting value to 2.");
globalHealingRate = 2;
}
else if(rate > 100)
{
Sitting.log.warning("[Sitting]: \"heal-while-sitting-rate\" setting greater than 100. Setting value to 100.");
globalHealingRate = 100;
}
else
{
globalHealingRate = rate;
}
}
}
@Override
public boolean onCommand(Player player, String[] split)
{
if(split[0].equalsIgnoreCase(COMMAND_SIT) && player.canUseCommand(COMMAND_SIT))
{
OEntity ridingEntity = UtilEntity.ridingEntity(player.getEntity());
if(ridingEntity != null)
{
stand(player, 0, UtilEntity.getMountedYOffset(ridingEntity), 0);
}
else
{
SitType[] types = new SitType[1];
switch(healWhileSitting)
{
case ALL:
case SITCOMMANDONLY:
types[0] = SittingType.SIT_HEAL.getType();
break;
default:
types[0] = null;
}
sit(player, types, player.getWorld(), player.getX(), player.getY(), player.getZ(), player.getRotation(), -0.05D);
}
return true;
}
if(split[0].equalsIgnoreCase(COMMAND_STAND))
{
OEntity ridingEntity = UtilEntity.ridingEntity(player.getEntity());
if(ridingEntity == null)
return true;
stand(player, 0, UtilEntity.getMountedYOffset(ridingEntity), 0);
return true;
}
if(split[0].equalsIgnoreCase(COMMAND_MAIN))
{
player.sendMessage(Colors.Gold+sittingPlugin.NAME+" mod version: "+Colors.White+sittingPlugin.VERSION);
player.sendMessage(Colors.Rose+"available commands: ");
if(player.canUseCommand(COMMAND_SIT))
player.sendMessage(" "+Colors.LightBlue+COMMAND_SIT+Colors.White+" - toggles sitting and standing");
player.sendMessage(" "+Colors.LightBlue+COMMAND_STAND+Colors.White+" - makes you stand if you are sitting");
if(!requireRightClickPermission || player.canUseCommand(COMMAND_RIGHT_CLICK_SIT))
player.sendMessage(Colors.Rose+"right-click to sit: "+Colors.White+"allowed");
else
player.sendMessage(Colors.Rose+"right-click to sit: "+Colors.White+"not allowed");
return true;
}
return false;
}
@Override
public void onBlockRightClicked(Player player, Block blockClicked, Item itemInHand)
{
if( (itemInHand == null || itemInHand.getItemId() == 0)
&& (!requireRightClickPermission || player.canUseCommand(COMMAND_RIGHT_CLICK_SIT))
&& EntitySitting.isChairBlock(blockClicked.getType()) )
{
Sign[] signs = isChair(blockClicked);
if(signs == null)
{
if(requiresChairFormats)
return;
signs = new Sign[0];
}
World world = player.getWorld();
int data = world.getBlockData(blockClicked.getX(), blockClicked.getY(), blockClicked.getZ());
if(UtilEntity.ridingEntity(player.getEntity()) != null)
{
switch(data)
{
case 0x0: //south
stand(player, -0.8D, 0, 0);
break;
case 0x1: //north
stand(player, 0.8D, 0, 0);
break;
case 0x2: //west
stand(player, 0, 0, -0.8D);
break;
case 0x3: //east
stand(player, 0, 0, 0.8D);
break;
default:
stand(player, 0, 0, 0);
}
}
else
{
float rotation;
double x = blockClicked.getX() + 0.5D;
double y = blockClicked.getY();
double z = blockClicked.getZ() + 0.5D;
switch(data)
{
case 0x0: //south
rotation = 90F;
x -= 0.2D;
break;
case 0x1: //north
rotation = 270F;
x += 0.2D;
break;
case 0x2: //west
rotation = 180F;
z -= 0.2D;
break;
case 0x3: //east
rotation = 0F;
z += 0.2D;
break;
default:
rotation = 0F;
}
SitType[] types = new SitType[signs.length + 1];
boolean hasHealing = false;
for(int i = 0; i < signs.length; i++)
{
SittingType sittype = getSittingTypeFromSign(signs[i]);
if(sittype == null)
continue;
types[i] = sittype.getType(signs[i]);
if(sittype == SittingType.SIT_HEAL)
hasHealing = true;
}
if(!hasHealing)
{
switch(healWhileSitting)
{
case ALL:
case CHAIRONLY:
types[types.length-1] = SittingType.SIT_HEAL.getType();
break;
default:
types[types.length-1] = null;
}
}
sit(player, types, player.getWorld(), x, y, z, rotation, 0.5D);
}
}
}
@Override
public boolean onSignChange(Player player, Sign sign)
{
if(sign.getBlock().getType() != 68 || !signHasSittingType(sign))
return false;
sign.setText(1, sign.getText(1).toUpperCase());
World world = player.getWorld();
SittingType sittype = getSittingTypeFromSign(sign);
if(sittype == null || !player.canUseCommand(sittype.PERMISSION))
{
world.setBlockAt(0, sign.getX(), sign.getY(), sign.getZ());
world.dropItem(sign.getX(), sign.getY(), sign.getZ(), 323);
player.sendMessage(Colors.Rose+"You do not have permission to build that.");
return true;
}
String valid = sittype.validate(sign);
if(valid != null)
{
world.setBlockAt(0, sign.getX(), sign.getY(), sign.getZ());
world.dropItem(sign.getX(), sign.getY(), sign.getZ(), 323);
player.sendMessage(Colors.Rose+valid);
return true;
}
sign.update();
return false;
}
private static void sit(Player player, SitType[] types, World world, double x, double y, double z, float rotation, double offsety)
{
player.setX(x);
player.setY(y);
player.setZ(z);
OEntityPlayerMP eplayer = (OEntityPlayerMP) player.getEntity();
eplayer.bs = rotation;
OWorldServer oworld = world.getWorld();
EntitySitting esitting = new EntitySitting(types, oworld, player.getX(), player.getY(), player.getZ(), offsety);
UtilEntity.spawnEntityInWorld(oworld, esitting);
UtilEntity.mountEntity(eplayer, esitting);
}
private static void stand(Player player, double offsetx, double offsety, double offsetz)
{
OEntityPlayerMP eplayer = (OEntityPlayerMP) player.getEntity();
if(!(UtilEntity.ridingEntity(eplayer) instanceof EntitySitting))
return;
UtilEntity.mountEntity(eplayer, (OEntity)null);
eplayer.a.a(player.getX()+offsetx, player.getY()+offsety, player.getZ()+offsetz, player.getRotation(), player.getPitch());
}
/*
* @return Returns null if not a chair. If it is a chair, it will return a list of Sign which can have
* a size of 0, meaning no signs found, but it is a chair.
*/
private static Sign[] isChair(Block block)
{
int data = block.getWorld().getBlockData(block.getX(), block.getY(), block.getZ());
Block[] sides = ChairFormatUtil.getStairSideBlocks(block, data);
if(sides == null)
return null;
return ChairFormatUtil.isChair(block, data, sides[0], sides[1]);
}
private static boolean signHasSittingType(Sign sign)
{
String line2 = sign.getText(1).toUpperCase();
if(line2.isEmpty() || line2.charAt(0) != '[' || line2.charAt(line2.length()-1) != ']')
return false;
try
{
SittingType.valueOf(line2.substring(1, line2.length()-1).replace(' ', '_'));
}
catch(IllegalArgumentException e)
{
return false;
}
return true;
}
private static SittingType getSittingTypeFromSign(Sign sign)
{
String line2 = sign.getText(1);
if(line2.isEmpty() || line2.charAt(0) != '[' || line2.charAt(line2.length()-1) != ']')
return null;
SittingType sittype = null;
try
{
sittype = SittingType.valueOf(line2.substring(1, line2.length()-1).replace(' ', '_'));
}
catch(IllegalArgumentException e)
{
return null;
}
return sittype;
}
}
|
ca1c5b2d68bf1884d7c30186910239199929f0cc
|
[
"Java"
] | 1 |
Java
|
M4411K4/Sitting
|
89338f207c832f08b71fd63ea2737d7d5307c8b9
|
8ce3ae612134cd0fb132a5d183d9b453392756fe
|
refs/heads/master
|
<repo_name>samitkumarpatel/jhipster-empmgmt<file_sep>/src/main/java/com/tutorial/web/filter/package-info.java
/**
* Servlet filters.
*/
package com.tutorial.web.filter;
<file_sep>/README.md
README for empMgmt
==========================
<file_sep>/src/main/java/com/tutorial/config/locale/package-info.java
/**
* Locale specific code.
*/
package com.tutorial.config.locale;
|
45edcea49e4d2214a148ee97e09748a889ff2a78
|
[
"Markdown",
"Java"
] | 3 |
Java
|
samitkumarpatel/jhipster-empmgmt
|
08b27f5d465955d685f6bb4446505e5bfa2dd16f
|
7254553ce0ede5b408a327acf6007020606b77c7
|
refs/heads/master
|
<file_sep># Weather/Events/History API reflector for a demo app
This is mostly an API reflector for my demo app within my portfolio site.
This was created with the Express starter so it contains some default stuff.
Also, I set this up for a demo to only point to Seattle. Could have accepted a zip code or lat/long, but its just a demo.
# I want to try this thing
First, make sure that you make your own `.env` file.
Copy the `env.example` file to `.env` and fill it out correctly with API keys from these two places:
- For weather: https://openweathermap.org/api
- For events: https://predicthq.com/
The historical data does come from [here](https://history.muffinlabs.com/), but all we're doing with this Express route is bypassing the CORS rule for the web app.
If you want to try it, here are the routes:
- Weather: http://localhost:3000/weather
- History: http://localhost:3000/history/3/11
- Events: http://localhost:3000/events/2020-03-30
<file_sep>require('dotenv').config()//Gotta load some api keys
const express = require('express');
const router = express.Router();
const fetch = require('node-fetch')
const Sentiment = require('sentiment');
const phq = require('predicthq');
const pClient = new phq.Client({access_token: process.env.PREDICT_KEY, fetch: fetch });
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/**
* Day in history part of the weather app
*/
router.get('/history/:month/:date', function(req, res, next) {
let month = req.params.month
let date = req.params.date
let apiCall = `https://history.muffinlabs.com/date/${month}/${date}`
fetch(apiCall)
.then(res => res.json())
.then(body => {
//If the data exists, pass it off to the sentiment injector.
let result = body.data.Events ? injectSentiment(body) : []
res.json(result)
})
})
/**
* Injects sentiment so we can figure out if the event has positive or negative connotations based on language used.
* This isn't perfect, but its sort of fun!
*/
const injectSentiment = (body)=> {
let events = body.data.Events.reverse() //year,text
let event_sentiment = []
let sentiment = new Sentiment();
events.forEach(event => {
let wSentiment = {
year: event.year,
text: event.text,
sentiment: sentiment.analyze(event.text)
}
event_sentiment.push(wSentiment)
})
return event_sentiment
}
/**
* Pulls weather from the openweathermap.org data sets.
*
*/
router.get('/weather', function(req,res,next) {
let apiCall = "http://api.openweathermap.org/data/2.5/forecast?q=Seattle,US&units=metric&appid="+process.env.WEATHER_KEY
fetch(apiCall)
.then(res => res.json())
.then(body => {
res.json(body)
})
})
/**
* Pulls event data from predictHQ
*/
router.get('/events/:today',function(req,res,next) {
const withinParam = '[email protected],-122.3320717';//Downtown Seattle
pClient.events.search({
'start.gte': req.params.today,
'start.lte': req.params.today,
within: withinParam
}).then((results) => {
res.json(results)
}).catch(error => {
res.json(error)
})
})
module.exports = router;
|
cb2f7bbdbc88d43b34da4d84db56be83ede512a7
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
ryuheiyokokawa/portfolio-api
|
304291fdb52dd6b033399893df8c6da5556c49ee
|
37677926795b9e1cd6a142e6b695f5efadb2ca41
|
refs/heads/master
|
<repo_name>Jibbedi/threet-functions<file_sep>/functions/src/games/pre-match-info.ts
const EloRating = require('elo-rating');
export function preMatchInfo(data) {
const expectedWinFirstPlayer = Math.round(EloRating.expected(data.firstPlayerEloRank, data.secondPlayerEloRank) * 100);
const firstPlayerWin = EloRating.calculate(data.firstPlayerEloRank, data.secondPlayerEloRank, true);
const secondPlayerWin = EloRating.calculate(data.firstPlayerEloRank, data.secondPlayerEloRank, false);
return {
firstPlayer: {
eloIfWin: firstPlayerWin.playerRating,
eloIfLoss: secondPlayerWin.playerRating,
winProbability: expectedWinFirstPlayer
},
secondPlayer: {
eloIfWin: secondPlayerWin.opponentRating,
eloIfLoss: firstPlayerWin.opponentRating,
winProbability: 100 - expectedWinFirstPlayer
}
}
}<file_sep>/functions/src/helper/database.ts
import * as admin from 'firebase-admin';
import {Player} from '../types/Player';
import {Game} from '../types/Game';
import {GAME_COLLECTION, PLAYER_COLLECTION, TOURNAMENT_COLLECTION} from '../constants/collections';
import {Tournament} from '../types/Tournament';
export function getPlayerSnapshotById(id: string, stage: string) {
return admin
.firestore()
.collection(stage + PLAYER_COLLECTION)
.doc(id)
.get()
}
export function getPlayerSnapshotsForIds(ids: string[], stage) {
return Promise.all(ids.map(id => getPlayerSnapshotById(id, stage)));
}
export function getPlayerById(id: string, stage: string): Promise<Player> {
return admin
.firestore()
.collection(stage + PLAYER_COLLECTION)
.doc(id)
.get()
.then(snapshot => snapshot.data() as Player);
}
export function getPlayersForIds(ids: string[], stage): Promise<Player[]> {
return Promise.all(ids.map(id => getPlayerById(id, stage)));
}
export function getNewTournamentDocument(stage: string) {
return admin
.firestore()
.collection(stage + TOURNAMENT_COLLECTION)
.doc()
}
export function getTournamentSnapshotForId(id: string, stage: string) {
return admin
.firestore()
.collection(stage + TOURNAMENT_COLLECTION)
.doc(id)
.get();
}
export function updateGameSnapshot(snapshot, updateData: Partial<Game>) {
return snapshot
.ref
.update(updateData)
}
export function getGameSnapshotById(id: string, stage: string) {
return admin
.firestore()
.collection(stage + GAME_COLLECTION)
.doc(id)
.get()
}
export function getGameById(id: string, stage: string): Promise<Game> {
return admin
.firestore()
.collection(stage + GAME_COLLECTION)
.doc(id)
.get()
.then(snapshot => snapshot.data() as Game);
}
export function getGamesForIds(ids: string[], stage): Promise<Game[]> {
return Promise.all(ids.map(id => getGameById(id, stage)));
}
export function updatePlayerSnapshot(snapshot, updateData: Partial<Player>) {
return snapshot
.ref
.update(updateData)
}
export function updateTournamentSnapshot(snapshot, updateData: Partial<Tournament>) {
return snapshot
.ref
.update(updateData)
}
export function writeTournamentToDatabase(tournamentRef, tournamentData: Tournament): Promise<string> {
return tournamentRef
.set(tournamentData)
.then(_ => tournamentRef.id);
}
export function writeGameToDatabase(game: Game, stage: string): Promise<string> {
const gameDocument = admin
.firestore()
.collection(stage + GAME_COLLECTION)
.doc();
game.gameId = gameDocument.id;
return gameDocument.set(game)
.then(_ => game.gameId);
}<file_sep>/functions/src/helper/game.ts
import {Game} from '../types/Game';
import {Player} from '../types/Player';
import {Tournament} from '../types/Tournament';
export function getFirstPlayerWon(game: Game) {
return game.firstPlayerScore > game.secondPlayerScore;
}
export function getWinnerScore(game: Game): number {
return getFirstPlayerWon(game) ? game.firstPlayerScore : game.secondPlayerScore;
}
export function getLoserScore(game: Game): number {
return getFirstPlayerWon(game) ? game.secondPlayerScore : game.firstPlayerScore;
}
export function getWinnerName(game: Game): string | null {
if (!game.done) {
return null;
}
return getFirstPlayerWon(game) ? game.firstPlayerName : game.secondPlayerName;
}
export function getLoserName(game: Game): string | null {
if (!game.done) {
return null;
}
return getFirstPlayerWon(game) ? game.secondPlayerName : game.firstPlayerName;
}
export function getWinnerId(game: Game): string | null {
if (!game.done) {
return null;
}
return getFirstPlayerWon(game) ? game.firstPlayerId : game.secondPlayerId;
}
export function getLoserId(game: Game): string | null {
if (!game.done) {
return null;
}
return getFirstPlayerWon(game) ? game.secondPlayerId : game.firstPlayerId;
}
export function createGameDataForPlayers(firstPlayer: Player | null, secondPlayer: Player | null, tournament: Tournament): Game {
return {
firstPlayerName: firstPlayer ? firstPlayer.name : null,
firstPlayerId: firstPlayer ? firstPlayer.id : null,
secondPlayerName: secondPlayer ? secondPlayer.name : null,
secondPlayerId: secondPlayer ? secondPlayer.id : null,
firstPlayerScore: 0,
secondPlayerScore: 0,
done: false,
shouldEffectElo: tournament.shouldEffectElo,
shouldEffectRank: tournament.shouldEffectRank,
mode: tournament.mode,
tournamentId: tournament.id,
};
}
<file_sep>/functions/src/tests/calculate-steak.test.ts
import {calculateStreak} from '../helper/calculate-streak';
describe('streak calculation', () => {
test('it should add +1 to current streak if game is won and streak was positive', () => {
expect(calculateStreak(1, true)).toBe(2);
});
test('it should return 1 if game is won and streak was negative', () => {
expect(calculateStreak(-1, true)).toBe(1);
});
test('it should return 1 if game is won and streak was 0', () => {
expect(calculateStreak(0, true)).toBe(1);
});
test('it should return -1 if game is lost and streak was 0', () => {
expect(calculateStreak(0, false)).toBe(-1);
});
test('it should return -1 if game is lost and streak was positive', () => {
expect(calculateStreak(1, false)).toBe(-1);
});
test('it should add -1 if game is lost and streak was negative', () => {
expect(calculateStreak(-1, false)).toBe(-2);
});
});
<file_sep>/functions/src/constants/collections.ts
export const TOURNAMENT_COLLECTION = 'tournaments';
export const PLAYER_COLLECTION = 'players';
export const GAME_COLLECTION = 'games';
export const ALL_COLLECTIONS = [TOURNAMENT_COLLECTION, PLAYER_COLLECTION, GAME_COLLECTION];<file_sep>/functions/src/tournament/league-match-update.ts
import {Game} from '../types/Game';
import {
getGamesForIds,
getPlayerSnapshotsForIds,
getTournamentSnapshotForId,
updatePlayerSnapshot,
updateTournamentSnapshot
} from '../helper/database';
import {Tournament} from '../types/Tournament';
import {getRanking} from '../helper/ranking';
import {Player} from '../types/Player';
import {RankingItem} from '../types/RankingItem';
export async function handleLeagueMatchUpdate(game: Game, stage: string) {
const tournamentSnapshot = await getTournamentSnapshotForId(game.tournamentId, stage);
const tournamentData: Tournament = tournamentSnapshot.data() as Tournament;
const matches = await getGamesForIds(tournamentData.games, stage);
if (!areAllGamesDone(matches)) {
console.log('tournament not done');
return true;
}
console.log('tounament done');
const ranking = getRanking(matches);
const playerSnapshots = await getPlayerSnapshotsForIds(tournamentData.participantsIds, stage);
// Update Players Elo + Stats
const playerUpdates = playerSnapshots.map(snapshot => {
const player = snapshot.data() as Player;
return updatePlayerSnapshot(snapshot, {
eloRank: calculateNewEloForPlayer(player, ranking, tournamentData),
leagueWins: calculateNewLeagueWinsForPlayer(player, ranking)
})
});
// Update Tournament Data
const tournamentUpdate = updateTournamentSnapshot(tournamentSnapshot, {
done: true,
winnerId: ranking[0].id,
winnerName: ranking[0].name
});
return await Promise.all([...playerUpdates, tournamentUpdate]);
}
export function areAllGamesDone(games: Game[]) {
return !games.some(match => !match.done);
}
export function getWonEloPerPlace(tournament: Tournament): number[] {
const totalPot = tournament.participantsIds.length * tournament.stakePerPlayer;
return tournament.splitPercentages.map(percentage => Math.round(percentage / 100 * totalPot));
}
export function getWonEloForPlace(tournament: Tournament, place: number) {
return getWonEloPerPlace(tournament)[place] || 0;
}
export function getPlaceForPlayer(player: Player, ranking: RankingItem[]) {
return ranking.findIndex(r => r.id === player.id);
}
export function calculateNewEloForPlayer(player: Player, ranking: RankingItem[], tournament: Tournament) {
const wonElo = getWonEloForPlace(tournament, getPlaceForPlayer(player, ranking));
return player.eloRank + wonElo - tournament.stakePerPlayer;
}
export function calculateNewLeagueWinsForPlayer(player: Player, ranking: RankingItem[]) {
return playerIsTournamentWinner(player, ranking) ? (player.leagueWins || 0) + 1 : (player.leagueWins || 0);
}
export function playerIsTournamentWinner(player: Player, ranking: RankingItem[]) {
return getPlaceForPlayer(player, ranking) === 0;
}<file_sep>/functions/src/tests/create-league.test.ts
import {createLeagueTournament, mapPlayerIndicesToGames} from '../tournament/create-league';
import * as database from '../helper/database';
import {Tournament} from '../types/Tournament';
import {Game} from '../types/Game';
const MOCK_TOURNAMENT_ID = 1;
const MOCK_TOURNAMENT_REF = {id: MOCK_TOURNAMENT_ID};
database.getPlayersForIds = jest.fn().mockImplementation((ids) =>
Promise.all(ids.map(id => {
return Promise.resolve({
name: 'Mock Player ' + id,
id: id
});
})));
database.writeGameToDatabase = jest.fn().mockImplementation((game: Game) => Promise.resolve(
game.firstPlayerName + ' vs ' + game.secondPlayerName
));
database.writeTournamentToDatabase = jest.fn().mockImplementation((tournament: Tournament) => Promise.resolve(
MOCK_TOURNAMENT_ID
));
database.getNewTournamentDocument = jest.fn().mockImplementation((tournament: Tournament) => {
return MOCK_TOURNAMENT_REF;
}
);
describe('create tournament', () => {
test('it should call create games 6 times for four players and create tournament', async () => {
const tournament = {
participantsIds: [1, 2, 3, 4]
} as any as Tournament;
const tournamentId = await createLeagueTournament(tournament, 'dev_');
expect(database.writeGameToDatabase).toHaveBeenCalledTimes(6);
expect(database.getNewTournamentDocument).toHaveBeenCalledWith('dev_');
expect(database.writeTournamentToDatabase).toHaveBeenCalledWith(MOCK_TOURNAMENT_REF, tournament);
expect(tournament.id).toBe(tournamentId);
expect(tournament.games).toBeTruthy();
});
});
describe('create gameplan', () => {
test('it should map indices to games', () => {
const tournament = {
tournamentId: 1
} as any;
const players = [
{
name: 'First Player',
id: 1
},
{
name: 'Second Player',
id: 2
},
{
name: 'Third Player',
id: 3
},
{
name: '<NAME>',
id: 4
}] as any;
const matchIndices = [[1, 2], [3, 4]];
const games = mapPlayerIndicesToGames(matchIndices, players, tournament);
expect(games[0].firstPlayerName).toEqual(players[0].name);
expect(games[0].secondPlayerName).toEqual(players[1].name);
expect(games[1].firstPlayerName).toEqual(players[2].name);
expect(games[1].secondPlayerName).toEqual(players[3].name);
})
});<file_sep>/functions/src/types/Game.ts
export interface Game {
gameId?: string;
firstPlayerName?: string;
secondPlayerName?: string;
firstPlayerId?: string;
secondPlayerId?: string;
firstPlayerScore?: number;
secondPlayerScore?: number;
done: boolean;
shouldEffectElo?: boolean;
shouldEffectRank?: boolean;
mode?: 'knockout' | 'league';
tournamentId?: string;
}<file_sep>/functions/src/tests/create-knockout.test.ts
import * as database from '../helper/database';
import {Tournament} from '../types/Tournament';
import {Game} from '../types/Game';
import {createKnockoutTournament} from '../tournament/create-knockout';
const MOCK_TOURNAMENT_ID = 1;
const MOCK_TOURNAMENT_REF = {id: MOCK_TOURNAMENT_ID};
database.getPlayersForIds = jest.fn().mockImplementation((ids) =>
Promise.all(ids.map(id => {
return Promise.resolve({
name: 'Mock Player ' + id,
id: id
});
})));
database.writeGameToDatabase = jest.fn().mockImplementation((game: Game) => Promise.resolve(
game.firstPlayerName + ' vs ' + game.secondPlayerName
));
database.writeTournamentToDatabase = jest.fn().mockImplementation((tournament: Tournament) => Promise.resolve(
MOCK_TOURNAMENT_ID
));
database.getNewTournamentDocument = jest.fn().mockImplementation((tournament: Tournament) => {
return MOCK_TOURNAMENT_REF;
}
);
describe('create tournament', () => {
test('it should call create games 2 times for four players and create tournament', async () => {
const tournament = {
participantsIds: [1, 2, 3, 4]
} as any as Tournament;
const tournamentId = await createKnockoutTournament(tournament, 'dev_');
expect(database.writeGameToDatabase).toHaveBeenCalledTimes(2);
expect(database.getNewTournamentDocument).toHaveBeenCalledWith('dev_');
expect(database.writeTournamentToDatabase).toHaveBeenLastCalledWith(MOCK_TOURNAMENT_REF, tournament);
expect(tournament.id).toBe(tournamentId);
expect(tournament.stages).toBeTruthy();
});
});<file_sep>/functions/src/helper/calculate-streak.ts
export function calculateStreak(currentStreak = 0, win: boolean) {
const impact = win ? +1 : -1;
if (currentStreak >= 0 && !win) {
return impact;
} else if (currentStreak < 0 && win) {
return impact;
} else {
return currentStreak + impact;
}
}<file_sep>/functions/src/tests/game-helpers.test.ts
import {Game} from '../types/Game';
import {
createGameDataForPlayers,
getLoserId,
getLoserName,
getLoserScore,
getWinnerId,
getWinnerName,
getWinnerScore
} from '../helper/game';
import {Player} from '../types/Player';
import {Tournament} from '../types/Tournament';
const firstPlayerWonGame: Game = {
firstPlayerName: '<NAME>',
firstPlayerId: '1',
firstPlayerScore: 11,
secondPlayerName: '<NAME>',
secondPlayerScore: 0,
secondPlayerId: '2',
done: true,
};
const secondPlayerWonGame: Game = {
firstPlayerName: '<NAME>',
firstPlayerId: '1',
firstPlayerScore: 0,
secondPlayerName: '<NAME>',
secondPlayerScore: 11,
secondPlayerId: '2',
done: true
};
const notDoneGame: Game = {
firstPlayerName: '<NAME>',
firstPlayerId: '1',
firstPlayerScore: 0,
secondPlayerName: '<NAME>',
secondPlayerScore: 0,
secondPlayerId: '2',
done: false
};
describe('names', () => {
test('winner name should be first player, loser name should be second player if first player won', () => {
expect(getWinnerName(firstPlayerWonGame)).toEqual('First Player');
expect(getLoserName(firstPlayerWonGame)).toEqual('Second Player');
});
test('winner name should be second player, loser name should be first player if second player won', () => {
expect(getWinnerName(secondPlayerWonGame)).toEqual('Second Player');
expect(getLoserName(secondPlayerWonGame)).toEqual('First Player');
});
test('it should return null if game is not done', () => {
expect(getWinnerName(notDoneGame)).toBe(null);
expect(getLoserName(notDoneGame)).toBe(null);
});
});
describe('winner id', () => {
test('winner id should be first player id, loser id should be second player id if first player won', () => {
expect(getWinnerId(firstPlayerWonGame)).toEqual('1');
expect(getLoserId(firstPlayerWonGame)).toEqual('2');
});
test('winner id should be second player id, loser id should be first player id if second player won', () => {
expect(getWinnerId(secondPlayerWonGame)).toEqual('2');
expect(getLoserId(secondPlayerWonGame)).toEqual('1');
});
test('it should return null if game is not done', () => {
expect(getWinnerId(notDoneGame)).toBe(null);
expect(getLoserId(notDoneGame)).toBe(null);
});
});
describe('winner score', () => {
test('winner score should be first player score, loser score should be second player score if first player won', () => {
expect(getWinnerScore(firstPlayerWonGame)).toEqual(11);
expect(getLoserScore(firstPlayerWonGame)).toEqual(0);
});
test('winner score should be second player score, loser score should be first player score if second player won', () => {
expect(getWinnerScore(secondPlayerWonGame)).toEqual(11);
expect(getLoserScore(secondPlayerWonGame)).toEqual(0);
});
});
<file_sep>/functions/src/helper/rewrite-history.ts
export function rewriteHistory(history = [], win: boolean) {
history.push(win);
if (history.length > 5) {
history.shift();
}
return history;
}<file_sep>/functions/src/helper/move-to.ts
import * as admin from 'firebase-admin';
export function moveTo(stage : string) {
const collections = ['games', 'players', 'tournaments'];
return Promise.all(
collections.map(collectionName => admin
.firestore()
.collection(collectionName)
.get()
)
).then((collectionSnapshots) => {
const writes = [];
collectionSnapshots.forEach((collectionSnapshot, index) => {
collectionSnapshot.forEach(doc => {
writes.push(admin.firestore().collection(stage + '_' + collections[index]).doc(doc.id).set(doc.data()));
});
});
return Promise.all(writes);
})
.then(writes => {
return {status: 200};
});
}<file_sep>/functions/src/games/on-game-update.ts
import {Game} from '../types/Game';
import * as handleMatchUpdate from './handle-match-update';
import * as handleKnockoutMatchUpdate from '../tournament/knockout-match-update';
import * as leagueMatchUpdate from '../tournament/league-match-update';
export async function onGameUpdate(game: Game, stage = '') {
if (!game.done) {
return true;
}
await handleMatchUpdate.handleMatchUpdate(game, stage);
if (game.mode === 'knockout') {
await handleKnockoutMatchUpdate.handleKnockoutMatchUpdate(game, stage);
} else if (game.mode === 'league') {
await leagueMatchUpdate.handleLeagueMatchUpdate(game, stage);
}
return true;
};<file_sep>/functions/src/index.ts
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import {Tournament} from './types/Tournament';
import {createKnockoutTournament} from './tournament/create-knockout';
import {createLeagueTournament} from './tournament/create-league';
import {Game} from './types/Game';
import {onGameUpdate} from './games/on-game-update';
import {preMatchInfo} from './games/pre-match-info';
import {moveTo} from './helper/move-to';
import {createUser} from './helper/auth';
admin.initializeApp(functions.config().firebase);
exports.onGameUpdate = functions.firestore
.document('games/{gamesId}')
.onUpdate(event => {
const game = event.after.data() as Game;
return onGameUpdate(game);
});
exports.onGameUpdateDev = functions.firestore
.document('dev_games/{gamesId}')
.onUpdate(event => {
const game = event.after.data() as Game;
return onGameUpdate(game, 'dev_');
});
exports.createKnockoutTournamentFunction = functions.https.onCall((data: { tournament: Tournament, stage: string }) => {
return createKnockoutTournament(data.tournament, data.stage);
});
exports.createLeagueTournamentFunction = functions.https.onCall((data: { tournament: Tournament, stage: string }) => {
return createLeagueTournament(data.tournament, data.stage);
});
exports.preMatchInfo = functions.https.onCall((data, context) => {
return preMatchInfo(data);
});
exports.moveTo = functions.https.onCall((data, context) => {
return moveTo(data);
});
exports.createUser = functions.https.onCall((data, context) => {
return createUser(data.name, data.email, data.password, data.teamId, data.stage);
});<file_sep>/functions/src/tournament/create-knockout.ts
import {
getNewTournamentDocument,
getPlayersForIds,
writeGameToDatabase,
writeTournamentToDatabase
} from '../helper/database';
import {Tournament} from '../types/Tournament';
import {shuffle} from '../helper/array';
import {createGameDataForPlayers} from '../helper/game';
export async function createKnockoutTournament(tournament: Tournament, stage = '') {
const players = shuffle(await getPlayersForIds(tournament.participantsIds, stage));
const tournamentRef = getNewTournamentDocument(stage);
tournament.id = tournamentRef.id;
const gameWrites: Promise<string>[] = [];
for (let i = 0; i < players.length; i += 2) {
gameWrites.push(
writeGameToDatabase(
createGameDataForPlayers(players[i], players[i + 1], tournament), stage)
);
}
tournament.stages = {0: await Promise.all(gameWrites)};
return writeTournamentToDatabase(tournamentRef, tournament);
}
<file_sep>/functions/src/helper/ranking.ts
import {Game} from '../types/Game';
import {getFirstPlayerWon} from './game';
import {RankingItem} from '../types/RankingItem';
export function getRanking(games: Game[]): RankingItem[] {
const ranking = games.reduce((table, game) => {
const {firstPlayerName, secondPlayerName, firstPlayerId, secondPlayerId} = game;
if (!table[firstPlayerName]) {
table[firstPlayerName] = initializePlayer(firstPlayerName, firstPlayerId);
}
if (!table[secondPlayerName]) {
table[secondPlayerName] = initializePlayer(secondPlayerName, secondPlayerId);
}
if (game.done) {
table[firstPlayerName] = updatePlayerStats(table[firstPlayerName], getFirstPlayerWon(game), game.firstPlayerScore, game.secondPlayerScore);
table[secondPlayerName] = updatePlayerStats(table[secondPlayerName], !getFirstPlayerWon(game), game.secondPlayerScore, game.firstPlayerScore);
}
return table;
}, {});
return Object.keys(ranking)
.map(playerKey => ranking[playerKey])
.sort((a: any, b: any) => b.points !== a.points ? b.points - a.points : (b.scoreFor - b.scoreAgainst) - (a.scoreFor - a.scoreAgainst));
}
function initializePlayer(playerName: string, id): RankingItem {
return {name: playerName, id, wins: 0, loses: 0, scoreFor: 0, scoreAgainst: 0, points: 0};
}
function updatePlayerStats(rankingItem: RankingItem, won, scoreFor, scoreAgainst): RankingItem {
rankingItem.wins += won ? 1 : 0;
rankingItem.loses += !won ? 1 : 0;
rankingItem.scoreFor += (scoreFor || 0);
rankingItem.scoreAgainst += (scoreAgainst || 0);
rankingItem.points = rankingItem.wins * 2;
return rankingItem;
}<file_sep>/functions/src/tests/rewrite-history.test.ts
import {rewriteHistory} from '../helper/rewrite-history';
describe('history calculation', () => {
test('it should add true to history if game was won', () => {
expect(rewriteHistory([], true)).toEqual([true]);
});
test('it should add false to history if game was won', () => {
expect(rewriteHistory([], false)).toEqual([false]);
});
test('it should append history data to the array', () => {
expect(rewriteHistory([true], false)).toEqual([true, false]);
});
test('it should remove first entry, when history length is larger than 5', () => {
expect(rewriteHistory([false, true, true, true, true], false))
.toEqual([true, true, true, true, false]);
});
});
<file_sep>/functions/src/tournament/create-league.ts
import {
getNewTournamentDocument,
getPlayersForIds,
writeGameToDatabase,
writeTournamentToDatabase
} from '../helper/database';
import {Tournament} from '../types/Tournament';
import {shuffle} from '../helper/array';
import {Player} from '../types/Player';
import {Game} from '../types/Game';
import {createGameDataForPlayers} from '../helper/game';
const robin = require('roundrobin');
export async function createLeagueTournament(tournament: Tournament, stage = '') {
const players = shuffle(await getPlayersForIds(tournament.participantsIds, stage));
const tournamentRef = getNewTournamentDocument(stage);
tournament.id = tournamentRef.id;
const schedule: Game[] = robin(players.length)
.reduce((matches: Game[], participantIndices: number[][]) => {
return [...matches, ...mapPlayerIndicesToGames(participantIndices, players, tournament)];
}, []);
tournament.games = await Promise.all(schedule.map(game => writeGameToDatabase(game, stage)));
return writeTournamentToDatabase(tournamentRef, tournament);
}
export function mapPlayerIndicesToGames(participantIndices: number[][], players: Player[], tournament: Tournament): Game[] {
return participantIndices.map(pairing => {
const firstPlayer = players[pairing[0] - 1];
const secondPlayer = players[pairing[1] - 1];
return createGameDataForPlayers(firstPlayer, secondPlayer, tournament);
})
}<file_sep>/functions/src/tournament/knockout-match-update.ts
import {Game} from '../types/Game';
import {
getGameSnapshotById,
getPlayerSnapshotsForIds,
getTournamentSnapshotForId,
updateGameSnapshot,
updatePlayerSnapshot,
updateTournamentSnapshot,
writeGameToDatabase
} from '../helper/database';
import {Tournament} from '../types/Tournament';
import {createGameDataForPlayers, getWinnerId, getWinnerName} from '../helper/game';
import {Player} from '../types/Player';
export async function handleKnockoutMatchUpdate(game: Game, stage = '') {
const tournamentSnapshot = await getTournamentSnapshotForId(game.tournamentId, stage);
const tournamentData = tournamentSnapshot.data() as Tournament;
// Game winner
const winnerId = getWinnerId(game);
const winnerName = getWinnerName(game);
// if game was final, tournament is finished
if (isTournamentFinished(tournamentData, game)) {
const playerSnapshots = await getPlayerSnapshotsForIds(tournamentData.participantsIds, stage);
// Update Players Elo + Stats
const playerUpdates = playerSnapshots.map(snapshot => {
const player = snapshot.data() as Player;
return updatePlayerSnapshot(snapshot, {
eloRank: calculateNewEloForPlayer(player, game, tournamentData),
tournamentWins: calculateNewTournamentWins(player, game)
})
});
// Update Tournament Data
const tournamentUpdate = updateTournamentSnapshot(tournamentSnapshot, {
done: true,
winnerId: getWinnerId(game),
winnerName: getWinnerName(game)
});
return Promise.all([playerUpdates, tournamentUpdate]);
}
// tournament not finished
const nextRound = getNextRound(tournamentData, game);
const nextRoundGameData = getNextRoundGameIndex(tournamentData, game);
const nextRoundGameId = nextRound[nextRoundGameData.gameIndex] || null;
console.log(nextRound);
console.log(nextRoundGameData);
console.log(nextRoundGameId);
const winningPlayerCurrentMatch = {id: winnerId, name: winnerName} as Player;
// check if winning player is first or second player in next round
const nextMatchFirstPlayer = nextRoundGameData.winningPlayerIsFirstPlayerInNextMatch ? winningPlayerCurrentMatch : null;
const nextMatchSecondPlayer = !nextRoundGameData.winningPlayerIsFirstPlayerInNextMatch ? winningPlayerCurrentMatch : null;
// create game if game is not already present for next round
if (nextRoundGameId === null) {
const newGameId = await writeGameToDatabase(
createGameDataForPlayers(nextMatchFirstPlayer, nextMatchSecondPlayer, tournamentData), stage
);
console.log('newGameId', newGameId);
nextRound[nextRoundGameData.gameIndex] = newGameId;
console.log('nextRound', nextRound);
console.log(tournamentData.stages);
return updateTournamentSnapshot(tournamentSnapshot, {
stages: tournamentData.stages
})
}
// update game with winning player, if game is already present
const nextGameSnapshot = await getGameSnapshotById(nextRoundGameId, stage);
let updateData: Partial<Game>;
// check if winning player is first player in next round
if (nextMatchFirstPlayer) {
updateData = {
firstPlayerName: nextMatchFirstPlayer.name,
firstPlayerId: nextMatchFirstPlayer.id
}
} else {
updateData = {
secondPlayerName: nextMatchSecondPlayer.name,
secondPlayerId: nextMatchSecondPlayer.id
}
}
return updateGameSnapshot(nextGameSnapshot, updateData);
}
export function getNextRoundGameIndex(tournament: Tournament, game: Game): { gameIndex: number, winningPlayerIsFirstPlayerInNextMatch: boolean } {
const currentRound = getRoundForGame(tournament, game);
const currentGameIndex = currentRound.indexOf(game.gameId);
return {
gameIndex: Math.floor(currentGameIndex / 2),
winningPlayerIsFirstPlayerInNextMatch: currentGameIndex % 2 === 0
};
}
export function getNextRound(tournament: Tournament, game: Game) {
const roundIndexForGame = getRoundIndexForGame(tournament, game);
// Create next round, if not present
if (!tournament.stages[roundIndexForGame + 1]) {
tournament.stages[roundIndexForGame + 1] = [];
}
return tournament.stages[roundIndexForGame + 1];
}
export function getSortedStages(tournament: Tournament) {
return Object.keys(tournament.stages)
.map(key => parseInt(key, 10))
.sort((a, b) => a - b)
.map(key => tournament.stages[key]);
}
export function getRoundForGame(tournament: Tournament, game: Game) {
return getSortedStages(tournament)
.find(sortedStage => sortedStage.indexOf(game.gameId) >= 0);
}
export function getRoundIndexForGame(tournament: Tournament, game: Game) {
return getSortedStages(tournament).indexOf(getRoundForGame(tournament, game));
}
export function isTournamentFinished(tournament: Tournament, game: Game) {
const totalRoundsInTournament = Math.log2(tournament.participantsIds.length);
return totalRoundsInTournament === (getRoundIndexForGame(tournament, game) + 1) && game.done;
}
export function calculateNewEloForPlayer(player: Player, game: Game, tournament: Tournament) {
return getWinnerId(game) === player.id ?
player.eloRank + (tournament.stakePerPlayer * (tournament.participantsIds.length - 1)) :
player.eloRank - tournament.stakePerPlayer;
}
export function calculateNewTournamentWins(player: Player, game: Game) {
return getWinnerId(game) === player.id ?
(player.tournamentWins || 0) + 1 :
(player.tournamentWins || 0)
}<file_sep>/functions/src/tests/ranking.test.ts
import {Game} from '../types/Game';
import {getRanking} from '../helper/ranking';
export const firstPlayer = {name: '<NAME>', id: '1'};
export const secondPlayer = {name: '<NAME>', id: '2'};
export const thirdPlayer = {name: '<NAME>', id: '3'};
const firstVsSecondPlayer: Game = {
firstPlayerScore: 11,
secondPlayerScore: 9,
firstPlayerName: firstPlayer.name,
secondPlayerName: secondPlayer.name,
firstPlayerId: firstPlayer.id,
secondPlayerId: secondPlayer.id,
done: true
};
const firstVsThirdPlayer: Game = {
firstPlayerScore: 11,
secondPlayerScore: 0,
firstPlayerName: firstPlayer.name,
secondPlayerName: thirdPlayer.name,
firstPlayerId: firstPlayer.id,
secondPlayerId: thirdPlayer.id,
done: true
};
const secondVsThirdPlayerUnplayed: Game = {
firstPlayerScore: 0,
secondPlayerScore: 0,
firstPlayerName: secondPlayer.name,
secondPlayerName: thirdPlayer.name,
firstPlayerId: secondPlayer.id,
secondPlayerId: thirdPlayer.id,
done: false
};
const secondVsThirdPlayerPlayed: Game = {
firstPlayerScore: 8,
secondPlayerScore: 11,
firstPlayerName: secondPlayer.name,
secondPlayerName: thirdPlayer.name,
firstPlayerId: secondPlayer.id,
secondPlayerId: thirdPlayer.id,
done: true
};
describe('ranking calculation', () => {
test('it should add two points per win ', () => {
const ranking = getRanking([firstVsSecondPlayer, firstVsThirdPlayer]);
// First vs Second Player: 11 : 9
// First vs Third Player: 11 : 0
expect(ranking[0].points).toBe(4);
});
test('it should add zero points per lose ', () => {
const ranking = getRanking([firstVsSecondPlayer, firstVsThirdPlayer]);
// First vs Second Player: 11 : 9
// First vs Third Player: 11 : 0
expect(ranking[1].points).toBe(0);
});
test('it should calculate table by sorting points first', () => {
const ranking = getRanking([firstVsSecondPlayer, firstVsThirdPlayer, secondVsThirdPlayerPlayed]);
// First vs Second Player: 11 : 9
// First vs Third Player: 11 : 0
// Second vs Third Player 8 : 11
// 1. First Player | Diff + 13 | Points 4
// 2. Third Player | Diff -8 | Points 2
// 3. Second Player | Diff -5 | Points 0
//1st
expect(ranking[0].name).toBe(firstPlayer.name);
expect(ranking[0].id).toBe(firstPlayer.id);
expect(ranking[0].wins).toBe(2);
expect(ranking[0].loses).toBe(0);
expect(ranking[0].scoreFor).toBe(22);
expect(ranking[0].scoreAgainst).toBe(9);
expect(ranking[0].points).toBe(4);
//2nd
expect(ranking[1].name).toBe(thirdPlayer.name);
expect(ranking[1].id).toBe(thirdPlayer.id);
expect(ranking[1].wins).toBe(1);
expect(ranking[1].loses).toBe(1);
expect(ranking[1].scoreFor).toBe(11);
expect(ranking[1].scoreAgainst).toBe(19);
expect(ranking[1].points).toBe(2);
//3rd
expect(ranking[2].name).toBe(secondPlayer.name);
expect(ranking[2].id).toBe(secondPlayer.id);
expect(ranking[2].wins).toBe(0);
expect(ranking[2].scoreFor).toBe(17);
expect(ranking[2].scoreAgainst).toBe(22);
expect(ranking[2].points).toBe(0);
});
test('it should calculate table by score diff if points are equal', () => {
const ranking = getRanking([firstVsSecondPlayer, firstVsThirdPlayer, secondVsThirdPlayerUnplayed]);
// First vs Second Player: 11 : 9
// First vs Third Player: 11 : 0
// Second vs Third Player not done
// 1. First Player | Diff + 13 | Points 4
// 2. Second Player | Diff -2 | Points 0
// 3. Third Player | Diff -11 | Points 0
//1st
expect(ranking[0].name).toBe(firstPlayer.name);
expect(ranking[0].id).toBe(firstPlayer.id);
expect(ranking[0].wins).toBe(2);
expect(ranking[0].loses).toBe(0);
expect(ranking[0].scoreFor).toBe(22);
expect(ranking[0].scoreAgainst).toBe(9);
expect(ranking[0].points).toBe(4);
//2nd
expect(ranking[1].name).toBe(secondPlayer.name);
expect(ranking[1].id).toBe(secondPlayer.id);
expect(ranking[1].wins).toBe(0);
expect(ranking[1].loses).toBe(1);
expect(ranking[1].scoreFor).toBe(9);
expect(ranking[1].scoreAgainst).toBe(11);
expect(ranking[1].points).toBe(0);
//3rd
expect(ranking[2].name).toBe(thirdPlayer.name);
expect(ranking[2].id).toBe(thirdPlayer.id);
expect(ranking[2].wins).toBe(0);
expect(ranking[2].scoreFor).toBe(0);
expect(ranking[2].scoreAgainst).toBe(11);
expect(ranking[2].points).toBe(0);
});
});
<file_sep>/functions/src/types/RankingItem.ts
export interface RankingItem {
name : string;
id : string;
wins : number;
loses: number;
scoreFor : number;
scoreAgainst: number;
points: number;
}<file_sep>/functions/src/tests/league-match-update.test.ts
import {
areAllGamesDone,
calculateNewEloForPlayer,
calculateNewLeagueWinsForPlayer
} from '../tournament/league-match-update';
import {Game} from '../types/Game';
describe('all games done', () => {
test('it should return true if all games are done', async () => {
const games = [{done: true}, {done: true}] as Game[];
expect(areAllGamesDone(games)).toBe(true);
});
test('it should return false if at least one game is not done', async () => {
const games = [{done: true}, {done: false}] as Game[];
expect(areAllGamesDone(games)).toBe(false);
});
});
describe('new elo points', () => {
test('it should return correct new elo points', () => {
const tournament = {
participantsIds: [1, 2, 3, 4],
stakePerPlayer: 10, //total of 40
splitPercentages: [50, 30, 20] // 20 - 12 - 8
};
const ranking = [{id: 1}, {id: 3}, {id: 2}, {id: 4}];
const players = [{id: 1, eloRank: 1000}, {id: 2, eloRank: 900}, {id: 3, eloRank: 1200}, {id: 4, eloRank: 1000}];
// 1000 + 20 won elo - 10 stake = 1010
expect(calculateNewEloForPlayer(players[0], ranking, tournament)).toBe(1010);
// 900 + 8 won elo - 10 stake = 898
expect(calculateNewEloForPlayer(players[1], ranking, tournament)).toBe(898);
// 1200 + 12 won elo - 10 stake = 1202
expect(calculateNewEloForPlayer(players[2], ranking, tournament)).toBe(1202);
// 1000 + 0 won elo - 10 stake = 990
expect(calculateNewEloForPlayer(players[3], ranking, tournament)).toBe(990);
});
test('it should return correct new elo points if winner gets 90 % and loser gets consolation prize ', () => {
const tournament = {
participantsIds: [1, 2, 3, 4],
stakePerPlayer: 20, //total of 80
splitPercentages: [90, 0, 0, 10] // 72 - 0 - 0 - 8
};
const ranking = [{id: 1}, {id: 3}, {id: 2}, {id: 4}];
const players = [{id: 1, eloRank: 1000}, {id: 2, eloRank: 900}, {id: 3, eloRank: 1200}, {id: 4, eloRank: 1000}];
// 1000 + 72 won elo - 20 stake = 1052
expect(calculateNewEloForPlayer(players[0], ranking, tournament)).toBe(1052);
// 900 + 0 won elo - 20 stake = 880
expect(calculateNewEloForPlayer(players[1], ranking, tournament)).toBe(880);
// 1200 + 0 won elo - 20 stake = 1180
expect(calculateNewEloForPlayer(players[2], ranking, tournament)).toBe(1180);
// 1000 + 8 won elo - 20 stake = 988
expect(calculateNewEloForPlayer(players[3], ranking, tournament)).toBe(988);
});
test('it should return correct new elo points if winner gets all and rest is not assigned', () => {
const tournament = {
participantsIds: [1, 2, 3, 4],
stakePerPlayer: 20, //total of 80
splitPercentages: [100] // 80
};
const ranking = [{id: 1}, {id: 3}, {id: 2}, {id: 4}];
const players = [{id: 1, eloRank: 1000}, {id: 2, eloRank: 900}, {id: 3, eloRank: 1200}, {id: 4, eloRank: 1000}];
// 1000 + 72 won elo - 20 stake = 1060
expect(calculateNewEloForPlayer(players[0], ranking, tournament)).toBe(1060);
// 900 + 0 won elo - 20 stake = 880
expect(calculateNewEloForPlayer(players[1], ranking, tournament)).toBe(880);
// 1200 + 0 won elo - 20 stake = 1180
expect(calculateNewEloForPlayer(players[2], ranking, tournament)).toBe(1180);
// 1000 + 0 won elo - 20 stake = 980
expect(calculateNewEloForPlayer(players[3], ranking, tournament)).toBe(980);
})
});
describe('calculate league wins', () => {
test('it should add one to league wins if league wins are present and league is won', async () => {
const tournament = {
participantsIds: [1, 2, 3, 4],
stakePerPlayer: 20, //total of 80
splitPercentages: [100] // 80
};
const ranking = [{id: 1}, {id: 3}, {id: 2}, {id: 4}];
const players = [{id: 1, eloRank: 1000, leagueWins: 1}, {id: 2, eloRank: 900}, {id: 3, eloRank: 1200}, {
id: 4,
eloRank: 1000
}];
expect(calculateNewLeagueWinsForPlayer(players[0], ranking)).toBe(2);
});
test('it should return 1 for league wins if league wins are undefined and league is won', async () => {
const tournament = {
participantsIds: [1, 2, 3, 4],
stakePerPlayer: 20, //total of 80
splitPercentages: [100] // 80
};
const ranking = [{id: 1}, {id: 3}, {id: 2}, {id: 4}];
const players = [{id: 1, eloRank: 1000}, {id: 2, eloRank: 900}, {id: 3, eloRank: 1200}, {
id: 4,
eloRank: 1000
}];
expect(calculateNewLeagueWinsForPlayer(players[0], ranking)).toBe(1);
});
test('it should return 0 for league wins if league wins are undefined and league is not won', async () => {
const tournament = {
participantsIds: [1, 2, 3, 4],
stakePerPlayer: 20, //total of 80
splitPercentages: [100] // 80
};
const ranking = [{id: 1}, {id: 3}, {id: 2}, {id: 4}];
const players = [{id: 1, eloRank: 1000}, {id: 2, eloRank: 900}, {id: 3, eloRank: 1200}, {
id: 4,
eloRank: 1000
}];
expect(calculateNewLeagueWinsForPlayer(players[1], ranking)).toBe(0);
});
test('it should return old league wins if league wins are present and league is not won', async () => {
const tournament = {
participantsIds: [1, 2, 3, 4],
stakePerPlayer: 20, //total of 80
splitPercentages: [100] // 80
};
const ranking = [{id: 1}, {id: 3}, {id: 2}, {id: 4}];
const players = [{id: 1, eloRank: 1000}, {id: 2, eloRank: 900, leagueWins: 2}, {id: 3, eloRank: 1200}, {
id: 4,
eloRank: 1000
}];
expect(calculateNewLeagueWinsForPlayer(players[1], ranking)).toBe(2);
});
});<file_sep>/functions/src/helper/auth.ts
import * as admin from 'firebase-admin';
import {getPlayerSnapshotById} from './database';
export async function createUser(name: string, email: string, password: string, teamId: string, stage = '') {
const userRecord = await admin
.auth()
.createUser({
email,
password
});
const userSnapshot = await getPlayerSnapshotById(userRecord.uid, stage);
return userSnapshot.ref.set({
name,
email,
teamId,
id : userRecord.uid
});
}<file_sep>/functions/src/games/handle-match-update.ts
import {Game} from '../types/Game';
import {getPlayerSnapshotById, updatePlayerSnapshot} from '../helper/database';
import {Player} from '../types/Player';
import {calculateStreak} from '../helper/calculate-streak';
import {getLoserScore, getWinnerId, getWinnerScore} from '../helper/game';
import {rewriteHistory} from '../helper/rewrite-history';
const EloRating = require('elo-rating');
export async function handleMatchUpdate(game: Game, stage = '') {
if (game.shouldEffectRank === false) {
console.log('should not effect rank');
return true;
}
const [firstPlayerSnapshot, secondPlayerSnapshot] = await Promise.all([getPlayerSnapshotById(game.firstPlayerId, stage),
getPlayerSnapshotById(game.secondPlayerId, stage)]);
const firstPlayer = firstPlayerSnapshot.data() as Player;
const secondPlayer = secondPlayerSnapshot.data() as Player;
const firstPlayerUpdate = updatePlayerSnapshot(firstPlayerSnapshot, getPlayerUpdateForGame(firstPlayer, secondPlayer, game));
const secondPlayerUpdate = updatePlayerSnapshot(secondPlayerSnapshot, getPlayerUpdateForGame(secondPlayer, firstPlayer, game));
return await Promise.all([firstPlayerUpdate, secondPlayerUpdate]);
}
export function getPlayerUpdateForGame(player: Player, opponent: Player, game: Game): Partial<Player> {
const playerWonGame = getWinnerId(game) === player.id;
const playerScoreFor = playerWonGame ? getWinnerScore(game) : getLoserScore(game);
const playerScoreAgainst = playerWonGame ? getLoserScore(game) : getWinnerScore(game);
// calculate streak
const streak = calculateStreak(player.streak, playerWonGame);
const longestNegativeStreak = Math.min(streak, player.longestNegativeStreak || 0);
const longestPositiveStreak = Math.max(streak, player.longestPositiveStreak || 0);
// calculate history
const history = rewriteHistory(player.history, playerWonGame);
// new elo
const playerElo = player.eloRank || 1000;
const opponentElo = opponent.eloRank || 1000;
const eloRank = game.shouldEffectElo !== false ? EloRating.calculate(playerElo, opponentElo, playerWonGame).playerRating : player.eloRank;
// wins and loses
const totalWins = playerWonGame ? (player.totalWins || 0) + 1 : (player.totalWins || 0);
const totalLoses = !playerWonGame ? (player.totalLoses || 0) + 1 : (player.totalLoses || 0);
const winPercentage = totalWins / (totalWins + totalLoses);
// score
const totalScoreFor = (player.totalScoreFor || 0) + playerScoreFor;
const totalScoreAgainst = (player.totalScoreAgainst || 0) + playerScoreAgainst;
const totalScoreDiff = totalScoreFor - totalScoreAgainst;
return {
streak,
longestNegativeStreak,
longestPositiveStreak,
history,
eloRank,
totalWins,
totalLoses,
winPercentage,
totalScoreFor,
totalScoreAgainst,
totalScoreDiff
}
}
|
054b03b574846ab1927cac95546238efb04a118b
|
[
"TypeScript"
] | 25 |
TypeScript
|
Jibbedi/threet-functions
|
4e55fa4b1ba0eb5ad5e8b84cc9b900240c038884
|
9133a5bf2b860ffc80ff3f957588c772f82552c2
|
refs/heads/master
|
<repo_name>JoeDravarol/connect_four<file_sep>/lib/board.rb
class Board
attr_accessor :square, :current_drop_position
def initialize
@square = []
@current_drop_position = nil
# Create multi-dimensional array for columns and rows
# Outer array is columns and sub array is rows
7.times { square << Array.new(6) { " " }}
end
def display
line = ""
7.times { line << "----" }
puts line
row = 0
while row < 6
row_square = "|"
7.times { |col| row_square << " #{square[col][row]} |" }
puts row_square
puts line
row += 1
end
puts " 0 1 2 3 4 5 6"
end
def drop_mark(col, mark)
return "Invalid drop" if !col.between?(0,6) || square[col][0] != " "
row = square[col].length - 1
until row < 0
if square[col][row] == " "
square[col][row] = mark
# Save drop position
@current_drop_position = [col,row]
break
end
row -= 1
end
display
end
end
<file_sep>/lib/win_condition.rb
class WinCondition
def draw?(board)
flatten_board = board.square.flatten
flatten_board.all? { |square| square != " " }
end
def win?(position, mark, board)
won = false
4.times do |i|
case i
when 0
won = check_horizontal(position, mark, board)
break if won
when 1
won = check_vertical(position, mark, board)
break if won
when 2
won = check_diagonal_left(position, mark, board)
break if won
when 3
won = check_diagonal_right(position, mark, board)
break if won
end
end
won
end
def check_horizontal(position, mark, board)
counter = 1
col,row = position
# Right
1.upto(3) do |i|
break if !(col+i).between?(0,6) || board.square[col+i][row] != mark
counter += 1
end
# Left
1.upto(3) do |i|
break if !(col-i).between?(0,6) || board.square[col-i][row] != mark
counter += 1
end
counter == 4
end
def check_vertical(position, mark, board)
counter = 1
col,row = position
# Down
1.upto(3) do |i|
break if !(row+i).between?(0,5) || board.square[col][row+i] != mark
counter += 1
end
counter == 4
end
def check_diagonal_left(position, mark, board)
counter = 1
col,row = position
# Up Left
1.upto(3) do |i|
break if !(col-i).between?(0,6) || !(row-i).between?(0,5) || board.square[col-i][row-i] != mark
counter += 1
end
# Down Right
1.upto(3) do |i|
break if !(col+i).between?(0,6) || !(row+i).between?(0,5) || board.square[col+i][row+i] != mark
counter += 1
end
counter == 4
end
def check_diagonal_right(position, mark, board)
counter = 1
col,row = position
# Up Right
1.upto(3) do |i|
break if !(col+i).between?(0,6) || !(row-i).between?(0,5) || board.square[col+i][row-i] != mark
counter += 1
end
# Down Left
1.upto(3) do |i|
break if !(col-i).between?(0,6) || !(row+i).between?(0,5) || board.square[col-i][row+i] != mark
counter += 1
end
counter == 4
end
end
<file_sep>/spec/win_condition_spec.rb
require 'win_condition'
require 'board'
RSpec.describe WinCondition do
let(:board) { @board = Board.new }
let(:player) { @player = Player.new("John", "X") }
let(:win_condition) { @win_condition = WinCondition.new }
describe '#draw?' do
it "returns true when the board is full" do
# Fill board
board.square = []
7.times { board.square << Array.new(6) { "X" }}
expect(win_condition.draw?(board)).to eql(true)
end
it "returns false when the board is empty" do
expect(win_condition.draw?(board)).to eql(false)
end
it "returns false when the board is partially filled" do
# Fill 3 columns
board.square.each_with_index do |col, i|
col.each { |square| square = "X" } if i % 2 == 0
end
expect(win_condition.draw?(board)).to eql(false)
end
end
describe '#win?' do
context "horizontal line" do
it "returns true for right line" do
6.downto(3) { |i| board.drop_mark(i, player.mark) }
expect(win_condition.win?(board.current_drop_position, player.mark, board)).to eql(true)
end
it "returns true for left line" do
4.times { |i| board.drop_mark(i, player.mark) }
expect(win_condition.win?(board.current_drop_position, player.mark, board)).to eql(true)
end
end
it "returns true for vertical line" do
4.times { board.drop_mark(0, player.mark) }
expect(win_condition.win?(board.current_drop_position, player.mark, board)).to eql(true)
end
context "diagonal line" do
it "returns true for up left line" do
board.square[3][2] = "X"
board.square[4][3] = "X"
board.square[5][4] = "X"
board.display
board.drop_mark(6, player.mark)
expect(win_condition.win?(board.current_drop_position, player.mark, board)).to eql(true)
end
it "returns true for up right line" do
board.square[3][2] = "X"
board.square[2][3] = "X"
board.square[1][4] = "X"
board.drop_mark(0, player.mark)
expect(win_condition.win?(board.current_drop_position, player.mark, board)).to eql(true)
end
it "returns true for down left line" do
board.square[0][5] = "X"
board.square[1][4] = "X"
board.square[2][3] = "X"
4.times do |i|
if i == 3
board.drop_mark(3, player.mark)
else
board.drop_mark(3, "O")
end
end
expect(win_condition.win?(board.current_drop_position, player.mark, board)).to eql(true)
end
it "returns true for down right line" do
board.square[6][5] = "X"
board.square[5][4] = "X"
board.square[4][3] = "X"
4.times do |i|
if i == 3
board.drop_mark(3, player.mark)
else
board.drop_mark(3, "O")
end
end
expect(win_condition.win?(board.current_drop_position, player.mark, board)).to eql(true)
end
end
end
end<file_sep>/lib/player.rb
class Player
attr_reader :name, :mark
def initialize(name, mark)
@name = name
@mark = mark
end
def drop_mark(col, board)
board.drop_mark(col, mark)
end
end<file_sep>/README.md
# Connect Four (Command line Version)
Connect Four is a two-player connection game in which the player first choose a color and then take turns dropping one colored disc/circle from the top into a seven-column, six-row vertically suspended grid. The pieces fall straight down occupying the lowest available space within the column. The objective of the game is to be the first to form a horizonta, vertical, or diagonal line of four of one's own discs. From [Wikipedia](https://en.wikipedia.org/wiki/Connect_Four)
## Connect Four Gameplay Example

## Assignment Requirement
The goal of this project is to built a command-line Connect four game using Test-Driven Development (TDD). RSpec will be the framework use for testing.
## To Play This Game
Click [here](https://repl.it/@JoeDravarol/Connect-Four-Game) to view the project.
Created as part of The Odin Project's [curriculum](https://www.theodinproject.com/courses/ruby-programming/lessons/testing-your-ruby-code)
<file_sep>/spec/player_spec.rb
require 'player'
require 'board'
RSpec.describe Player do
describe '#initialize' do
it "requires arguments" do
expect { Player.new }.to raise_error(ArgumentError)
end
it "initialize with valid arguments" do
expect { Player.new("John", "X") }.to_not raise_error
end
it "expects 2 arguments" do
expect { Player.new("John") }.to raise_error(ArgumentError)
end
end
let(:player) do
@player = Player.new("John", "X")
end
describe "#name" do
it "returns the name" do
expect(player.name).to eql("John")
end
end
describe "#mark" do
it "returns the mark" do
expect(player.mark).to eql("X")
end
it "works with unicode" do
player1 = Player.new("Sleepy", "\u25EF")
expect(player1.mark).to eql("◯")
end
end
let(:board) do
@board = Board.new
end
describe "#drop_mark" do
it "drops mark on the bottom of empty column" do
player.drop_mark(0, board)
expect(board.square[0][5]).to eql("X")
end
it "drops mark on top of another mark" do
player.drop_mark(1, board)
player.drop_mark(1, board)
expect(board.square[1][4]).to eql("X")
end
context "returns error message" do
it "when drop mark on a column that is full" do
# Fill all the columns
6.times { player.drop_mark(2, board) }
expect(player.drop_mark(2, board)).to eql "Invalid drop"
end
it "when drop mark on non-existing column" do
expect(player.drop_mark(7, board)).to eql "Invalid drop"
end
end
end
end<file_sep>/spec/connect_four_spec.rb
require 'main'
RSpec.describe Game do
let(:game) { @game = Game.new }
describe "#initialize" do
context "Create a board" do
it "creates a 7 column square" do
expect(game.board.square.length).to eql(7)
end
it "creates a 6 row squares" do
game.board.square.each do |row|
expect(row.length).to eql(6)
end
end
end
it "get player 1 name" do
expect(game.player_1.name).to eql game.name_1
end
it "get player 2 name" do
expect(game.player_2.name).to eql game.name_2
end
end
describe "#col_valid?" do
it "returns true when column entered is between 0 to 6" do
6.times do |col|
expect(game.col_valid?("#{col}")).to eql(true)
end
end
context "returns false" do
it "when given emtpy input" do
expect(game.col_valid?("")).to eql(false)
end
it "when input is a space" do
expect(game.col_valid?(" ")).to eql(false)
end
it "when a character is entered" do
expect(game.col_valid?("X")).to eql(false)
end
it "when a string is entered" do
expect(game.col_valid?("space")).to eql(false)
end
it "when the column entered in not between 0 to 6" do
expect(game.col_valid?("20")).to eql(false)
end
end
end
describe "#switch_player" do
it "switch from player 1 to player 2" do
game.current_player = game.player_1
game.switch_player
expect(game.current_player).to eql(game.player_2)
end
it "switch from player 2 to player 1" do
game.current_player = game.player_2
game.switch_player
expect(game.current_player).to eql(game.player_1)
end
end
end<file_sep>/spec/board_spec.rb
require 'board'
RSpec.describe Board do
let(:board) do
@board = Board.new
end
describe "#initialize" do
it "creates a 7 column square" do
expect(board.square.length).to eql(7)
end
it "creates a 6 row squares" do
board.square.each do |row|
expect(row.length).to eql(6)
end
end
end
describe "#drop_mark" do
it "drops mark on the bottom of empty column" do
board.drop_mark(0, "X")
expect(board.square[0][5]).to eql("X")
end
it "drops mark on top of another mark" do
board.drop_mark(0, "X")
board.drop_mark(0, "O")
expect(board.square[0][4]).to eql("O")
end
context "returns error message" do
it "when drop mark on a column that is full" do
# Fill all the columns
6.times { board.drop_mark(2, "X") }
expect(board.drop_mark(2, "O")).to eql "Invalid drop"
end
it "when drop mark on non-existing column" do
expect(board.drop_mark(7, "X")).to eql "Invalid drop"
end
end
context "save dropped mark position" do
it "when drop mark on the bottom" do
board.drop_mark(2, "X")
expect(board.current_drop_position).to eql([2, 5])
end
it "when drop a new mark" do
board.drop_mark(0, "X")
board.drop_mark(0, "X")
expect(board.current_drop_position).to eql([0, 4])
end
end
end
end<file_sep>/lib/main.rb
require './lib/board'
require './lib/player'
require './lib/win_condition'
class Game
attr_accessor :board, :player_1, :player_2, :current_player, :win_condition
# Only use for testing
attr_reader :name_1, :name_2
def initialize
@board = Board.new
@win_condition = WinCondition.new
@name_1 = get_name("player 1")
@player_1 = Player.new(name_1, "\u2600")
@name_2 = get_name("player 2")
@player_2 = Player.new(name_2, "\u263C")
@current_player = player_1
play_game
end
def get_name(player)
puts "Hi #{player}, what is your name?"
name = gets.chomp.capitalize
puts "Nice to meet you #{name}"
name
end
def display_instructions
puts "***************************************"
puts "** Welcome To The Connect Four Game! **"
puts "***************************************"
puts "======================================="
puts "***************************************"
puts "************ Instructions *************"
puts "***************************************"
puts "======================================="
puts "1. The goal of this game is to get four"
puts "of your mark in line up horizontally, vertically, or diagonally."
puts "2. The players takes turn to drop their mark"
puts "in a column by entering the column number (shown below the board)."
puts "3. If the board is filled, with no victors, it will be a draw."
puts "#{player_1.name}, your mark is #{player_1.mark}"
puts "#{player_2.name}, your mark is #{player_2.mark}"
puts "Good luck and have fun!"
end
def get_mark(player)
puts "It's your turn #{player.name}"
puts "Select a column to drop your mark"
col = gets.chomp
until col_valid?(col)
"Please enter a valid input"
col = gets.chomp
end
col.to_i
end
def col_valid?(col)
# Because the regex returns nil when it's not match, the ternary operator makes it so that it returns false
!col.empty? && col.length == 1 && col =~ (/\d+/) && col.to_i.between?(0,6) ? true : false
end
def drop_mark(player)
loop do
col = get_mark(player)
break unless player.drop_mark(col, board) == "Invalid drop"
puts "Invalid drop"
end
end
def switch_player
@current_player = current_player == player_1 ? player_2 : player_1
end
def play_game
display_instructions
board.display
loop do
col = drop_mark(current_player)
break if game_ended?(current_player, board)
switch_player
end
end
def game_ended?(player, board)
if won?(player, board)
puts "Game Over! #{player.name} has won!"
return true
elsif draw?(board)
puts "Game Over! It's a draw"
return true
end
false
end
def won?(player, board)
win_condition.win?(board.current_drop_position, player.mark, board)
end
def draw?(board)
win_condition.draw?(board)
end
end
game = Game.new
|
8e9ed7d9db5fd229e31a328fd8a0555397b5118e
|
[
"Markdown",
"Ruby"
] | 9 |
Ruby
|
JoeDravarol/connect_four
|
3ca2bd62f257d3a0d266bf1c0ff4d789ce7e2c8d
|
6f84e97b4449f613695b81890c1260ddc4d4e54a
|
refs/heads/master
|
<repo_name>fr2023/4bash-shell-scripting<file_sep>/47_pass-arguments-to-a-bash-script.sh
#! /bin/bash
# $* Returns a single string (``$1, $2 ... $n'')
# comprising all of the positional parameters
# separated by the internal field separator character
#(defined by the IFS environment variable).
# $0 Refers to the name of the script itself
echo $0 $1 $2 $3 ' > echo $1 $2 $3'
# $@ Returns a sequence of strings
# (``$1'', ``$2'', ... ``$n'')
# wherein each positional parameter
# remains separate from the others.
args=("$@")
echo ${args[0]} ${args[1]} ${args[2]}
echo $@
# $# Refers to the number of arguments
# specified on a command line
echo $#
# output
# test@test$ ./hello.sh <NAME>
# ./hello.sh <NAME> > echo $1 $2 $3
# <NAME>
# <NAME>
# 3<file_sep>/README.md
# udemy-bash-shell-scripting
Este repositório contém todas as atividades realizadas durante o [Udemy] Bash Shell Scripting Tutorial for Beginners.
Descrição:
Bash Shell Scripting Tutorial for Beginners
https://www.udemy.com/bash-shell-scripting-tutorial-for-beginners/learn/v4/overview
Instrutores: <NAME> (Software Developer and Programming Enthusiast)<file_sep>/51_file-test-operators.sh
#! /bin/bash
# flag -e juntamente com \c mantém o cursor na mesma linha que a linha de comando do echo
echo -e "Enter the name of the file: \c"
read file_name
# flag -e para verificar se um arquivo existe ou não
#if [ -e $file_name ]
#then
# echo "$file_name found"
#else
# echo "$file_name not found"
#fi
# flag -f para verificar se um arquivo existe e se é um arquivo normal (regular file) ou não
#if [ -f $file_name ]
#then
# echo "$file_name found"
#else
# echo "$file_name not found"
#fi
# flag -d para verificar se um diretório existe ou não
#if [ -d $file_name ]
#then
# echo "$file_name found"
#else
# echo "$file_name not found"
#fi
# flag -s para verificar se um arquivo não está vazio ou está
if [ -s $file_name ]
then
echo "$file_name not empty"
else
echo "$file_name empty"
fi <file_sep>/87_debug-bash-script.sh
#! /bin/bash
set -x
file=/home/wjuniori/git/bash-shell/87_file.txt
set +x
trap "rm -f $file && echo file deleted; exit" 0 2 15 # SIGTERM kill -15 <PID>
echo "pid is $$" # imprimir o PID do próprio script (símbolo $$)
while (( COUNT < 10 ))
do
sleep 10
(( COUNT ++ ))
echo $COUNT
done
exit 0<file_sep>/84_function-example.sh
#! /bin/bash
usage() {
echo "You need to provide an argument"
echo "usage : $0 file_name"
}
is_file_exist() {
local file="$1"
[[ -f "$file" ]] && return 0 || return 1
#if [ -f "$file" ]
#then
# return 0 #0 is true
#else
# return 1 #1 is false
#fi
}
[[ $# -eq 0 ]] && usage
if ( is_file_exist "$1" )
then
echo "File found"
else
echo "File not found"
fi <file_sep>/43_using-variables-and-comments.sh
#! /bin/bash
# this is a comment
echo "Hello World" # this is also a comment
echo Our shell name is $BASH
echo Our shell version name is $BASH_VERSION
echo Our home directory is $HOME
echo Our current working directory is $PWD
echo Our current languagem is $LANG
echo Our current user is $USER
name=Mark
VALUE=10
echo The name is $name
echo value $VALUE<file_sep>/74_until-loop.sh
#! /bin/bash
# until loops
n=1
# first way
echo "----until loops------first way-------------------"
until [ $n -gt 10 ]
do
echo "$n"
(( n++ ))
done
# second way
n=1
echo "----until loops------second way-------------------"
until (( $n > 10 ))
do
echo "$n"
(( ++n ))
done
# third way
n=1
echo "----until loops------third way-------------------"
until [ $n -gt 10 ]
do
echo "$n"
n=$(( n+1 ))
done
#output
#test@test:~/Desktop$ ./hello.sh
#----until loops------first way-------------------
#1
#2
#3
#4
#5
#6
#7
#8
#9
#10
#----until loops------second way-------------------
#1
#2
#3
#4
#5
#6
#7
#8
#9
#10
#----until loops------third way-------------------
#1
#2
#3
#4
#5
#6
#7
#8
#9
#10
#test@test:~/Desktop$<file_sep>/85_readonly-command.sh
#! /bin/bash
# Readonly Variables
echo "---Readonly Variables---"
var=31
readonly var
var=50 # warning - readonly variable
echo "var => $var" # var => 31
# Readonly Functions
echo
echo "---Readonly Functions---"
hello() {
echo "Hello World"
}
readonly -f hello
hello() {
echo "Hello Word Again"
}
hello # Hello World
# Readonly
echo
echo "---readonly---"
readonly
echo
echo "---readonly -p---"
readonly -p
echo
echo "---readonly -f---"
readonly -f<file_sep>/55_logical-and-operator.sh
#! /bin/bash
age=60
# for using And operator use &&
#if [ "$age" -gt 18 ] && [ "$age" -lt 30 ]
#then
# echo "valid age"
#else
# echo "age not valid"
#fi
# The -a option provide
# an alternative compound condition test.
#if [ "$age" -gt 18 -a "$age" -lt 30 ]
#then
# echo "valid age"
#else
# echo "age not valid"
#fi
# if [[ $condition1 && $condition2 ]] # Also works.
if [[ "$age" -gt 18 && "$age" -lt 30 ]]
then
echo "valid age"
else
echo "age not valid"
fi <file_sep>/82_functions.sh
#! /bin/bash
function Hello(){
echo "Hello"
}
function print(){
echo $1 $2 $3
}
quit () {
exit
}
#Hello
print Hello World Again
echo "foo"
quit<file_sep>/59_arithmetic-operations.sh
#! /bin/bash
num1=20
num2=5
#echo $(( num1 + num2 )) #adição
#echo $(( num1 - num2 )) #subtração
#echo $(( num1 * num2 )) #multiplicação
#echo $(( num1 / num2 )) #divisão
#echo $(( num1 % num2 )) #resto
echo $(expr $num1 + $num2 ) #adição
echo $(expr $num1 - $num2 ) #subtração
echo $(expr $num1 \* $num2 ) #multiplicação
echo $(expr $num1 / $num2 ) #divisão
echo $(expr $num1 % $num2 ) #resto<file_sep>/45_read-user-input.sh
#! /bin/bash
#echo "Enter name: "
#read name
#echo "Enterd name: $name"
# Multiple inputs
#echo "Enter names: "
#read name1 name2 name3
#echo "Names: $name1, $name2, $name3"
# Two commonly used options however are
# -p which allows you to specify a prompt
# -s which makes the input silent.
#read -p 'username: ' user_var
#echo "username: $user_var"
#read -p 'username: ' user_var
#read -sp 'password: ' pass_var
#echo
#echo "username: $user_var"
#echo "password: $<PASSWORD>"
# -a makes read command to read into an array
#echo "Enter names: "
#read -a names
#echo "Names: ${names[0]}, ${names[1]}"
# read command will now store the reply into the default build-in variable $REPLY
echo "Enter name: "
read
echo "Name: $REPLY"<file_sep>/61_floating-point-math-operations.sh
#! /bin/bash
num1=20.5
num2=5
# operações aritméticas com números decimais
echo "20.5+5" | bc
echo "20.5-5" | bc
#echo "$num1+$num2" | bc
#echo "$num1-$num2" | bc
echo "20.5*5" | bc
echo "20.5/5" | bc
echo "scale=20;20.5/5" | bc
echo "20.5%5" | bc
num=4
# raiz quadrada
echo "scale=2;sqrt($num)" | bc -l
# potência
echo "scale=2;3^3" | bc -l<file_sep>/67_array-variables.sh
#! /bin/bash
os=('ubuntu' 'windows' 'kali')
#adicionar elementos ao array
#os[3]='mac'
#os[0]='mac'
os[6]='mac'
#remover elementos do array - os índices não são alterados/reordenados
unset os[2]
#imprimir todos os elementos do array
echo "${os[@]}"
#imprimir um elemento específico do array
echo "${os[0]}"
#imprimir os índices do array
echo "${!os[@]}"
#imprimir o comprimento/tamanho do array
echo "${#os[@]}"
#qualquer variável é tratada ou comporta-se como um array, mas o valor da variável/array será sempre atribuída ao índice 0
string=dasfdsafsadfasdf
echo "${string[@]}"
echo "${string[0]}" #o elemento sempre ficará no índice 0
echo "${string[1]}" #não há nenhum elemento
echo "${#string[@]}" #imprimir o comprimento/tamanho do array<file_sep>/57_logical-or-operator.sh
#! /bin/bash
age=25
# for using OR operator use ||
#if [ "$age" -eq 18 ] || [ "$age" -eq 30 ]
#then
# echo "valid age"
#else
# echo "age not valid"
#fi
# The -o option provide
# an alternative compound condition test.
#if [ "$age" -eq 18 -o "$age" -eq 30 ]
#then
# echo "valid age"
#else
# echo "age not valid"
#fi
# if [[ $condition1 || $condition2 ]] # Also works.
if [[ "$age" -eq 18 || "$age" -eq 30 ]]
then
echo "valid age"
else
echo "age not valid"
fi <file_sep>/65_the-case-statement-example.sh
#! /bin/bash
echo -e "Enter some character : \c"
read value
case $value in
[a-z] )
echo "User entered $value a to z" ;;
[A-Z] )
#Caso não identifique letras maiúsculas, deve-se alterar a variável de ambiente 'LANG', a qual indica a linguagem/localidade e a codificação, onde "C" é a configuração de idioma
# echo $LANG
# LANG=C
#Restaurar o padrão (pt_BR.UTF-8) posteriormente
echo "User entered $value A to Z" ;;
[0-9] )
echo "User entered $value 0 to 9" ;;
? )
# ? é um padrão para um apenas um caractere (neste caso, só poderá ser um caractere especial)
echo "User entered $value special character" ;;
* )
echo "Unknown input" ;;
esac
#Output:
#test@test$ ./hello.sh
#Enter some character : f
#User entered f a to z
#test@test$ ./hello.sh
#Enter some character : K
#User entered K a to z
#test@test$ LANG=C
#test@test$ ./hello.sh
#Enter some character : K
#User entered K A to Z
#test@test$ ./hello.sh
#Enter some character : 9
#User entered 9 0 to 9
#test@test$ ./hello.sh
#Enter some character : 5
#User entered 5 0 to 9
#test@test$ ./hello.sh
#Enter some character : &
#User entered & special character
#test@test$ ./hello.sh
#Enter some character : sdsdsdsd
#Unknown input
#test@test$ <file_sep>/49_if-statement.sh
#! /bin/bash
### Number Comparisons (integer comparison)
#count=10
#if [ $count -eq 10 ]
#then
# echo "condition is true"
#fi
#if (( $count >= 9 )) # OR [ $count >= 9 ]
#then
# echo "condition is true"
#fi
### String Comparison
#word=abc
#if [ $word != "abcccc" ]
#then
# echo "condition is true"
#fi
word=a
#if [[ $word < "b" ]]
#then
# echo "condition is true"
#fi
#if [[ $word == "b" ]]
#then
# echo "condition is true"
#else
# echo "condition is false"
#fi
if [[ $word == "b" ]]
then
echo "condition b is true"
elif [[ $word == "a" ]]
then
echo "condition a is true"
else
echo "condition is false"
fi<file_sep>/53_append-output-text-file.sh
#! /bin/bash
# flag -e juntamente com \c mantém o cursor na mesma linha que a linha de comando do echo
echo -e "Enter the name of the file: \c"
read file_name
# flag -f para verificar se um arquivo existe e se é um arquivo normal (regular file) ou não
if [ -f $file_name ]
then
# flag -w para verificar se um arquivo tem a permissão de escrita
if [ -w $file_name ]
then
echo "Type some text data. To quit press ctrl+d."
# um único > de redirecionamento sobrescreverá seu arquivo. Se você duplicar >>, o arquivo será anexado.
cat >> $file_name
else
echo "The file do not have write permissions"
fi
else
echo "$file_name not exists"
fi <file_sep>/71_while-loops.sh
#! /bin/bash
# while loops
n=1
while [ $n -le 3 ]
do
echo "$n"
(( n++ ))
#sleep 1
gnome-terminal &
#xterm &
done <file_sep>/81_break-continue.sh
#! /bin/bash
echo "Break Statement"
for (( i=1 ; i<=10 ; i++ ))
do
if [ $i -gt 5 ]
then
break
fi
echo "$i"
done
echo
echo "Continue Statement"
for (( i=1 ; i<=10 ; i++ ))
do
if [ $i -eq 3 -o $i -eq 6 ]
then
continue
fi
echo "$i"
done <file_sep>/86_signals-traps.sh
#! /bin/bash
echo "---Signals---"
trap "echo Exit signal is detected" SIGINT # (SIGINT OR 2) Ctrl + C
trap "echo Exit signal is detected" SIGKILL SIGSTOP # (SIGKILL OR 9) kill -9 <PID>
file=/home/wjuniori/git/bash-shell/86_file.txt
trap "rm -f $file && echo file deleted; exit" 0 2 15 # SIGTERM kill -15 <PID>
echo "pid is $$" # imprimir o PID do próprio script (símbolo $$)
while (( COUNT < 10 ))
do
sleep 10
(( COUNT ++ ))
echo $COUNT
done
exit 0
echo
echo "---Trap signal 0---"
trap "echo Exit command is detected" 0
echo "Hello world"
exit 0<file_sep>/78_for-loop-execute-commands.sh
#! /bin/bash
# for loops
# comando asterisco carregará todos os itens que estão no diretório corrente, que pode ser arquivo ou diretório
echo "all the files in directory--------"
for item in *
do
if [ -f $item ] # flag -f, se for um arquivo, imprimiremos o nome
then
echo $item
fi
done
echo
echo "all the directory in directory--------"
for item in *
do
if [ -d $item ] # flag -d, se for um diretório, imprimiremos o nome
then
echo $item
fi
done
#Pode haver um warning/erro quando no diretório houver algum arquivo ou diretório denominado, por exemplo, 'qrt function is the', ou seja, com keywords separadas por espaço. O script fica confuso quanto a esses nomes (se são keywords ou o nome de um arquivo)
echo
echo "execute list of commands--------"
for command in ls pwd date
do
echo "command name -> $command"
$command #isso vai realmente executar esse comando
done <file_sep>/73_read-file-content.sh
#! /bin/bash
# while loops
#while read p
#do
# echo $p
#done < 73_read-file-content.sh
#cat 73_read-file-content.sh | while read p
#do
# echo $p
#done
while IFS=' ' read -r line # while IFS= read -r line
do
echo $line
done < /etc/host.conf
<file_sep>/76_for-loop.sh
#! /bin/bash
# for loops
#echo ${BASH_VERSION}
#Example 1 ------------------------
for i in 1 2 3 4 5
do
echo $i
done
#Example 2 ------------------------
for i in {0..10}
do
echo $i
done
#Example 3 ------------------------
for i in {0..10..2}
do
echo $i
done
#Example 4 ------------------------
for (( i=0; i<5; i++ ))
do
echo $i
done
|
d8f0729d331ba181de75fe739eee88812792d22e
|
[
"Markdown",
"Shell"
] | 24 |
Shell
|
fr2023/4bash-shell-scripting
|
8a14ffc6645c403119cd0de3896a6531ac43331b
|
6a4967d76aeaad9eccff834de81cc919320f3fcc
|
refs/heads/master
|
<repo_name>aiurmaple/RecruitAnalyze<file_sep>/datadisplay/src/main/java/indi/aiurmaple/recruitanalyze/datadisplay/model/ExceptionModel.java
package indi.aiurmaple.recruitanalyze.datadisplay.model;
import lombok.Data;
@Data
public class ExceptionModel {
private String path;
private String errorMsg;
public ExceptionModel(String path, String errorMsg) {
this.path = path;
this.errorMsg = errorMsg;
}
}
<file_sep>/datadisplay/src/main/java/indi/aiurmaple/recruitanalyze/datadisplay/controller/WorkingExpController.java
package indi.aiurmaple.recruitanalyze.datadisplay.controller;
import indi.aiurmaple.recruitanalyze.datadisplay.entity.WorkingExpEntity;
import indi.aiurmaple.recruitanalyze.datadisplay.model.ResponseModel;
import indi.aiurmaple.recruitanalyze.datadisplay.service.WorkingExpService;
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;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@RestController
@RequestMapping("/experience")
public class WorkingExpController {
@Autowired
private WorkingExpService workingExpService;
@RequestMapping(method = RequestMethod.GET)
public ResponseModel<List<WorkingExpEntity>> getAll() {
List<WorkingExpEntity> experience = workingExpService.getAll();
return new ResponseModel<>(HttpServletResponse.SC_OK, true, "Success!", experience);
}
}
<file_sep>/datadisplay/src/main/java/indi/aiurmaple/recruitanalyze/datadisplay/dao/JobNameDao.java
package indi.aiurmaple.recruitanalyze.datadisplay.dao;
import indi.aiurmaple.recruitanalyze.datadisplay.entity.JobNameEntity;
import java.util.List;
public interface JobNameDao {
List<JobNameEntity> getAll();
}
<file_sep>/datadisplay/src/main/java/indi/aiurmaple/recruitanalyze/datadisplay/service/RecommendService.java
package indi.aiurmaple.recruitanalyze.datadisplay.service;
import java.util.List;
public interface RecommendService {
List<Integer> getSalaryRanking();
List<Integer> getEduLevelRanking();
List<Integer> getJobRanking();
List<Integer> getJobRankingByCity();
List<Integer> getJobRankingByWorkingExp();
}
<file_sep>/datadisplay/src/main/js/README.md
# 运行步骤
1. 修改config文件夹内的dev.env.js文件配置BASE_API项为后端接口ip
2. 如需外网访问,需修改package.json文件内dev启动参数增加--host=0.0.0.0
3. 执行npm install --registry=https://registry.npm.taobao.org安装依赖包
4. npm run dev
5. 运行成功后可用服务器ip+9528端口访问
<file_sep>/datatransform/src/main/java/indi/aiurmaple/recruitanalyze/datatransform/dao/SequenceRepository.java
package indi.aiurmaple.recruitanalyze.datatransform.dao;
import indi.aiurmaple.recruitanalyze.datatransform.entity.SequenceEntity;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Created by 13925 on 2019/3/5.
*/
public interface SequenceRepository extends JpaRepository<SequenceEntity, Integer> {
SequenceEntity findByTableName(String tableName);
}
<file_sep>/datadisplay/README.md
# 使用说明
该程序为web应用程序,分为前端和后端,后端用于处理数据,前端用于可视化展示数据
# 后端使用步骤
mvn clean
mvn package
nohup java -server -jar target/datadisplay-0.0.1-SNAPSHOT.jar \
--spring.datasource.url="jdbc:mysql://localhost:3306/recruit_analyze?useUnicode=true&characterEncoding=UTF-8&useSSL=true" \
--spring.datasource.username=root \
--spring.datasource.password=<PASSWORD> \
--spring.redis.host=localhost \
--spring.redis.password=<PASSWORD> > datadisplay.log 2>&1 &
# 前端使用步骤
进入src/main/js目录查看README文档运行
<file_sep>/reptile/recruit/config/ZLConfig.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'tzj'
KEYWORDS = ['Java开发', 'Python', 'Android', 'Web前端', 'PHP', '算法工程师', '人工智能', '大数据']
ADDRESS = ['北京', '上海', '广州', '深圳',
'天津', '武汉', '西安', '成都', '大连',
'长春', '沈阳', '南京', '济南', '青岛',
'杭州', '苏州', '无锡', '宁波', '重庆',
'郑州', '长沙', '福州', '厦门', '哈尔滨',
'石家庄', '合肥', '惠州', '太原', '昆明',
'烟台', '佛山', '南昌', '贵阳', '南宁']
<file_sep>/datadisplay/src/main/java/indi/aiurmaple/recruitanalyze/datadisplay/dao/RecommendDao.java
package indi.aiurmaple.recruitanalyze.datadisplay.dao;
import indi.aiurmaple.recruitanalyze.datadisplay.model.CityRankingModel;
import indi.aiurmaple.recruitanalyze.datadisplay.model.JobRankingModel;
import java.util.List;
public interface RecommendDao {
List<String> getSalaryByJobName(Integer jobNameId);
List<JobRankingModel> getRankingByEduLevel(Integer eduLevelId);
List<JobRankingModel> getJobRanking();
List<CityRankingModel> getCityRankingByJobNum();
List<JobRankingModel> getRankingByCity(Integer cityId);
List<JobRankingModel> getRankingByWorkingExp(Integer workingExpId);
}
<file_sep>/datadisplay/src/main/java/indi/aiurmaple/recruitanalyze/datadisplay/model/WelfareReponseModel.java
package indi.aiurmaple.recruitanalyze.datadisplay.model;
import lombok.Data;
@Data
public class WelfareReponseModel {
private Integer count;
private String welfareLabel;
}
<file_sep>/datadisplay/src/main/java/indi/aiurmaple/recruitanalyze/datadisplay/service/WorkingExpService.java
package indi.aiurmaple.recruitanalyze.datadisplay.service;
import indi.aiurmaple.recruitanalyze.datadisplay.entity.WorkingExpEntity;
import java.util.List;
public interface WorkingExpService {
List<WorkingExpEntity> getAll();
}
<file_sep>/datadisplay/src/main/js/src/store/modules/edu.js
import { getEduLevels } from '@/api/edu'
const edu = {
actions: {
getEduLevels({ commit }) {
return new Promise((resolve, reject) => {
getEduLevels().then(response => {
resolve(response)
}).catch(error => {
reject(error)
})
})
}
}
}
export default edu
<file_sep>/datatransform/src/main/java/indi/aiurmaple/recruitanalyze/datatransform/entity/WorkingExpEntity.java
package indi.aiurmaple.recruitanalyze.datatransform.entity;
import javax.persistence.*;
import java.util.Objects;
@Entity
@Table(name = "working_exp", schema = "recruit_analyze")
public class WorkingExpEntity {
private Integer id;
private String workingLabel;
public WorkingExpEntity() {
}
public WorkingExpEntity(String workingLabel) {
this.workingLabel = workingLabel;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Basic
@Column(name = "working_label")
public String getWorkingLabel() {
return workingLabel;
}
public void setWorkingLabel(String workingLabel) {
this.workingLabel = workingLabel;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WorkingExpEntity that = (WorkingExpEntity) o;
return id.equals(that.id) &&
Objects.equals(workingLabel, that.workingLabel);
}
@Override
public int hashCode() {
return Objects.hash(id, workingLabel);
}
}
<file_sep>/reptile/recruit/ZLCrawler.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'tzj'
import json
import os
import time
from datetime import datetime
from itertools import product, count
from multiprocessing import Pool, Value
from urllib.parse import urlencode
import requests
from config.ZLConfig import *
from util.ZLUtil import logger, create_dir
jobNumber = None
def get_data_path():
abs_path = os.path.abspath(".")
file_path = abs_path + os.sep + "data" + os.sep + datetime.now().strftime('%Y%m%d') + os.sep
return file_path
def init(args):
global jobNumber
jobNumber = args
# 下载页面
def download(url):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0'}
response = requests.get(url, headers=headers)
code = response.status_code
if code != 200:
logger.error("Failed to crawle the page:" + url)
raise RuntimeError('crawleError')
return response.json()
# 获取数据
def get_content(results, keyword, address):
dir_path = get_data_path()
filename = dir_path + keyword + "_" + address + ".json"
with open(str(filename), 'a', encoding='utf-8') as rData:
rData.write("[")
for i, result in enumerate(results):
global jobNumber
rData.write(json.dumps(result, ensure_ascii=False))
if i != len(results) - 1:
rData.write(",")
with jobNumber.get_lock():
jobNumber.value += 1
rData.write("]\n")
# 休息一秒,防止反爬虫
time.sleep(1)
# 第一次抓取
def search(args):
base_url = 'https://fe-api.zhaopin.com/c/i/sou?'
number_list = count(0, 60)
pre_first_num = ""
for page_start in number_list:
paras = {
'start': page_start,
'pageSize': 60,
'cityId': args[0],
'kw': args[1],
'workExperience': -1,
'education': -1,
'companyType': -1,
'employmentType': -1,
'jobWelfareTag': -1,
'kt': 3,
'_v': 0.79909260,
'x-zp-page-request-id': 'fe117335f2e048ee82cded2bbd8abb1d-1542281153274-13557'
}
url = base_url + urlencode(paras)
logger.debug(url)
json = download(url)
results = json["data"]["results"]
# 判断是否重复,重复停止线程
if len(results) == 0:
logger.debug("抓取数据为0,停止线程")
return
first_result = results[0]
cur_first_num = first_result["number"]
if pre_first_num == cur_first_num:
logger.debug("抓取数据页重复,停止线程")
return
pre_first_num = cur_first_num
get_content(results, args[1], args[0])
# 主程序入口
if __name__ == '__main__':
# 创建文件夹
create_dir(get_data_path())
# 第一次抓取
logger.info("开始第一次抓取")
jobNumber = Value('i', 0)
start = time.time()
args = product(ADDRESS, KEYWORDS)
pool = Pool(initializer=init, initargs=(jobNumber,))
i = pool.map_async(search, args)
i.wait()
end = time.time()
logger.info("共计用时:" + str(end - start) + "s")
logger.info("本次抓取统计的职位数为:" + str(jobNumber.value))
logger.info("本次抓取时间为:" + datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
<file_sep>/datatransform/src/main/java/indi/aiurmaple/recruitanalyze/datatransform/entity/CityEntity.java
package indi.aiurmaple.recruitanalyze.datatransform.entity;
import javax.persistence.*;
import java.util.Objects;
@Entity
@Table(name = "city", schema = "recruit_analyze")
public class CityEntity {
private Integer id;
private String cityLabel;
public CityEntity() {
}
public CityEntity(String cityLabel) {
this.cityLabel = cityLabel;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Basic
@Column(name = "city_label")
public String getCityLabel() {
return cityLabel;
}
public void setCityLabel(String cityLabel) {
this.cityLabel = cityLabel;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CityEntity that = (CityEntity) o;
return id.equals(that.id) &&
Objects.equals(cityLabel, that.cityLabel);
}
@Override
public int hashCode() {
return Objects.hash(id, cityLabel);
}
}
<file_sep>/datadisplay/src/main/java/indi/aiurmaple/recruitanalyze/datadisplay/dao/WorkingExpDao.java
package indi.aiurmaple.recruitanalyze.datadisplay.dao;
import indi.aiurmaple.recruitanalyze.datadisplay.entity.WorkingExpEntity;
import java.util.List;
public interface WorkingExpDao {
List<WorkingExpEntity> getAll();
}
<file_sep>/datadisplay/src/main/js/src/store/modules/workExp.js
import { getWorkingExp } from '@/api/workExp'
const workExp = {
actions: {
getWorkingExp({ commit }) {
return new Promise((resolve, reject) => {
getWorkingExp().then(response => {
resolve(response)
}).catch(error => {
reject(error)
})
})
}
}
}
export default workExp
<file_sep>/datadisplay/src/main/java/indi/aiurmaple/recruitanalyze/datadisplay/security/RedisTokenService.java
package indi.aiurmaple.recruitanalyze.datadisplay.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
public class RedisTokenService {
private static final long EXPIRETIME = 1L;
@Autowired
private StringRedisTemplate stringRedisTemplate;
public void saveToken(String userName, String token) {
stringRedisTemplate.opsForValue().set(userName, token);
stringRedisTemplate.expire(userName, EXPIRETIME, TimeUnit.DAYS);
}
public String getToken(String userName) {
return stringRedisTemplate.opsForValue().get(userName);
}
public Boolean hasToken(String userName) {
return stringRedisTemplate.hasKey(userName);
}
public Boolean removeToken(String userName) {
return stringRedisTemplate.delete(userName);
}
}
<file_sep>/datadisplay/src/main/js/src/store/modules/city.js
import { getCitys } from '@/api/city'
const city = {
actions: {
getCitys({ commit }) {
return new Promise((resolve, reject) => {
getCitys().then(response => {
resolve(response)
}).catch(error => {
reject(error)
})
})
}
}
}
export default city
<file_sep>/datatransform/src/main/java/indi/aiurmaple/recruitanalyze/datatransform/dao/CompanyRepository.java
package indi.aiurmaple.recruitanalyze.datatransform.dao;
import indi.aiurmaple.recruitanalyze.datatransform.entity.CompanyEntity;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Created by 13925 on 2019/3/6.
*/
public interface CompanyRepository extends JpaRepository<CompanyEntity, Long> {
CompanyEntity findByCompanyNumber(String companyNumber);
}
<file_sep>/datadisplay/src/main/java/indi/aiurmaple/recruitanalyze/datadisplay/controller/CityController.java
package indi.aiurmaple.recruitanalyze.datadisplay.controller;
import indi.aiurmaple.recruitanalyze.datadisplay.entity.CityEntity;
import indi.aiurmaple.recruitanalyze.datadisplay.model.ResponseModel;
import indi.aiurmaple.recruitanalyze.datadisplay.service.CityService;
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;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@RestController
@RequestMapping("/citys")
public class CityController {
@Autowired
private CityService cityService;
@RequestMapping(method = RequestMethod.GET)
public ResponseModel<List<CityEntity>> getAll() {
List<CityEntity> citys = cityService.getAll();
return new ResponseModel<>(HttpServletResponse.SC_OK, true, "Success!", citys);
}
}
<file_sep>/datadisplay/src/main/java/indi/aiurmaple/recruitanalyze/datadisplay/service/CityService.java
package indi.aiurmaple.recruitanalyze.datadisplay.service;
import indi.aiurmaple.recruitanalyze.datadisplay.entity.CityEntity;
import java.util.List;
public interface CityService {
List<CityEntity> getAll();
}
<file_sep>/datadisplay/src/main/java/indi/aiurmaple/recruitanalyze/datadisplay/service/impl/UserServiceImpl.java
package indi.aiurmaple.recruitanalyze.datadisplay.service.impl;
import indi.aiurmaple.recruitanalyze.datadisplay.dao.UserDao;
import indi.aiurmaple.recruitanalyze.datadisplay.entity.UserEntity;
import indi.aiurmaple.recruitanalyze.datadisplay.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public Boolean register(UserEntity user) {
String encryptPassword = BCrypt.hashpw(user.getUserPassword(), BCrypt.gensalt());
user.setUserPassword(encryptPassword);
Integer id = userDao.register(user);
return id > 0;
}
@Override
public UserEntity getUserInfoByName(String userName) {
return userDao.getUserInfoByName(userName);
}
@Override
public Boolean login(UserEntity user) {
if (user == null) {
return false;
}
String password = userDao.login(user);
return !StringUtils.isEmpty(password) && BCrypt.checkpw(user.getUserPassword(), password);
}
}
<file_sep>/datadisplay/src/main/java/indi/aiurmaple/recruitanalyze/datadisplay/service/JobService.java
package indi.aiurmaple.recruitanalyze.datadisplay.service;
import indi.aiurmaple.recruitanalyze.datadisplay.util.Quarter;
import java.util.List;
import java.util.Map;
public interface JobService {
Integer getJobsNum(Boolean time);
List<Integer> getJobsNumByCity(Integer[] cityIds);
Map<String, List<Integer>> getJobsSalaryByCity(Integer jobNameId, Integer[] cityIds, Quarter[] quarter);
List<Integer> getJobsSalaryByExp(Integer jobNameId, Integer[] workingExpIds);
List<Integer> getJobsNumByEdu(Integer jobNameId, Integer[] eduLevelIds);
List<Integer> getJobsNumByQuarter(Integer jobNameId);
List<Integer> getJobsNumByCity(Integer cityId);
}
<file_sep>/datadisplay/src/main/java/indi/aiurmaple/recruitanalyze/datadisplay/entity/JobNameEntity.java
package indi.aiurmaple.recruitanalyze.datadisplay.entity;
import lombok.Data;
@Data
public class JobNameEntity {
private Integer id;
private String jobLabel;
}
<file_sep>/reptile/recruit/util/ZLUtil.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'tzj'
import os
import logging
import logging.config
from datetime import datetime, timedelta
# 设置日志格式
def set_log_conf():
abs_path = os.path.abspath(".")
file_path = abs_path[0:abs_path.rfind("recruit")] + "recruit" + os.sep + "logging.conf"
logging.config.fileConfig(file_path)
return logging.getLogger('cycleRent')
logger = set_log_conf()
# 创建目录
def create_dir(dir_str):
if not os.path.exists(dir_str):
logger.debug("创建了目录" + dir_str)
os.makedirs(dir_str)
# 获得从当前时间到明日的具体秒数
def get_sleep_seconds():
dateNow = datetime.now()
# 获得明日日期
dataN = dateNow + timedelta(days=1)
dataNStr = dataN.strftime('%Y%m%d')
dataNTime = datetime.strptime(dataNStr + '000000', '%Y%m%d%H%M%S')
# 计算差异时间
dataC = dataNTime - dateNow
return dataC.seconds
# 执行命令
def exe_cmd(cmd):
result_str = os.popen(cmd).read()
return result_str
# 判断传入时间是否大于前一天
def is_new_time(createTime):
nowDay = datetime.now()
oneDay = timedelta(days=1)
yestoday = nowDay - oneDay
createTimeData = datetime.strptime(createTime, '%Y-%m-%d %H:%M:%S')
dataC = createTimeData - yestoday
if dataC.days >= 0:
return True
else:
return False
<file_sep>/README.md
# 简介
本项目是一个数据爬取和分析项目,主要对智联招聘网站的招聘数据进行数据爬取并分析。
# 流程
1. 用python脚本爬取智联招聘网站的数据
2. 定时统计招聘数据,并写入mysql
3. 对mysql数据进行分析,并在web上进行可视化展示
# 环境
- JDK 1.8
- maven 3.6.0
- mysql 5.7
- redis 5.0.3
- 360 Atlas 2.2.1
- Python 3.6.7
- Centos 7
- nodeJs 11.6.0
# 功能介绍
主要统计IT类岗位Java, Python, Android, Web前端, PHP, 算法工程师, 人工智能, 大数据职位的招聘数据。
1. 中国地图展示各城市职位数,统计实时职位数和每日职位增数
2. 比较各招聘季度各城市各职位类型平均薪资差距
3. 比较各职位类型工作经验的平均薪资差距
4. 比较各职位类型学历需求
5. 词云展示各职位的福利标签
# 使用步骤
1. 进入reptile/recruit目录用python3执行抓取脚本ZLCrawler.py,会生成一个data文件夹,抓取数据放置在这里
2. 用linux的crontab定时程序每日定时执行脚本ZLCrawlerAdd.py,会生成一个dataAdd文件夹,该文件夹存放每日增量数据
3. 部署mysql,360 Atlas,导入sql文件夹的recruit_analyze.sql到mysql中,Atlas的分表配置可参照conf文件夹内的Atlas.cnf
3. 抓取一定量数据后,进入datatransform目录执行数据传输插件,具体使用看该文件夹下的README
4. 进入datadisplay目录编译并启动可视化web程序,具体使用请看该文件夹下的README
5. web程序启动完成后,输入localhost:9528即可访问
<file_sep>/datadisplay/src/main/java/indi/aiurmaple/recruitanalyze/datadisplay/model/JobSalaryModel.java
package indi.aiurmaple.recruitanalyze.datadisplay.model;
import lombok.Data;
@Data
public class JobSalaryModel {
private Integer salary;
private Integer jobNameId;
public JobSalaryModel() {
}
public JobSalaryModel(Integer salary, Integer jobNameId) {
this.salary = salary;
this.jobNameId = jobNameId;
}
}
<file_sep>/datatransform/README.md
# 使用说明
本插件用于将数据爬取脚本数据传输到mysql中
mvn clean
mvn package
nohup java -jar target/datatransform-0.0.1-SNAPSHOT.jar \
--spring.datasource.url="jdbc:mysql://localhost:3306/recruit_analyze?useUnicode=true&characterEncoding=UTF-8&useSSL=true" \
--spring.datasource.username="root" \
--spring.datasource.password="<PASSWORD>" \
--path=/home > datatransform.log &
# 参数说明
spring.datasource.url:mysql地址
spring.datasource.username:mysql用户名
spring.datasource.password:<PASSWORD>
path:数据爬取脚本生成数据文件夹
<file_sep>/datadisplay/src/main/java/indi/aiurmaple/recruitanalyze/datadisplay/util/Quarter.java
package indi.aiurmaple.recruitanalyze.datadisplay.util;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public enum Quarter {
SPRING("01", "03"), AUTUMN("04", "05"), ALL("01", "12");
private List<String> quarterTime;
Quarter(String startDate, String endDate) {
Calendar calendar = Calendar.getInstance();
String year = String.valueOf(calendar.get(Calendar.YEAR));
quarterTime = new ArrayList<>();
quarterTime.add(year + "-" + startDate + "-01");
quarterTime.add(year + "-" + endDate + "-31");
}
public List<String> getQuarterTime() {
return quarterTime;
}
}
<file_sep>/datadisplay/src/main/java/indi/aiurmaple/recruitanalyze/datadisplay/model/ResponseModel.java
package indi.aiurmaple.recruitanalyze.datadisplay.model;
import lombok.Data;
@Data
public class ResponseModel<T> {
private Integer code;
private String message;
private Boolean status;
private T data;
public ResponseModel(Integer code, Boolean status, String message, T data) {
this.code = code;
this.message = message;
this.status = status;
this.data = data;
}
}
<file_sep>/datadisplay/src/main/js/src/arithmetic/expect.js
export function getExpect(list, year, modulus) {
if (modulus <= 0 || modulus >= 1) {
return null;
}
var length = list.length;
var modulusLeft = 1- modulus;
var lastIndex = list[0];
var lastSeclndex = list[0];
for (var i = 0; i < length; i++) {
lastIndex = modulus * list[i] + modulusLeft * lastIndex;
lastSeclndex = modulus * lastIndex + modulusLeft * lastSeclndex;
}
var a = 2 * lastIndex - lastSeclndex;
var b = (modulus / modulusLeft) * (lastIndex - lastSeclndex);
return a + b * year;
}
<file_sep>/sql/recruit_analyze.sql
/*
Navicat Premium Data Transfer
Source Server : 192.168.3.11
Source Server Type : MySQL
Source Server Version : 50724
Source Host : 192.168.3.11:3306
Source Schema : recruit_analyze
Target Server Type : MySQL
Target Server Version : 50724
File Encoding : 65001
Date: 20/04/2019 16:21:58
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for city
-- ----------------------------
DROP TABLE IF EXISTS `city`;
CREATE TABLE `city` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`city_label` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 35 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for company
-- ----------------------------
DROP TABLE IF EXISTS `company`;
CREATE TABLE `company` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`company_number` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`company_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`company_size_id` int(11) NOT NULL,
`company_type_id` int(11) NOT NULL,
PRIMARY KEY (`id`) USING BTREE,
INDEX `size_index`(`company_size_id`) USING BTREE,
INDEX `type_index`(`company_type_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 50200 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for company_size
-- ----------------------------
DROP TABLE IF EXISTS `company_size`;
CREATE TABLE `company_size` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`size_label` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 9 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for company_type
-- ----------------------------
DROP TABLE IF EXISTS `company_type`;
CREATE TABLE `company_type` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`type_label` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 18 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for edu_level
-- ----------------------------
DROP TABLE IF EXISTS `edu_level`;
CREATE TABLE `edu_level` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`edu_label` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 10 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for job
-- ----------------------------
DROP TABLE IF EXISTS `job`;
CREATE TABLE `job` (
`id` bigint(20) NOT NULL,
`job_number` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '职位号码',
`job_name_id` int(11) NOT NULL COMMENT '职位名',
`salary` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '职位薪资',
`empl_type` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '职位类型(如:全职或实习)',
`recruit_count` int(11) NULL DEFAULT NULL COMMENT '职位数',
`working_exp_id` int(11) NOT NULL COMMENT '工作经验',
`edu_level_id` int(11) NOT NULL COMMENT '学历需求',
`company_id` bigint(20) NOT NULL COMMENT '公司',
`city_id` int(11) NOT NULL COMMENT '所在城市',
`create_date` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
`end_date` datetime(0) NULL DEFAULT NULL COMMENT '过期时间',
PRIMARY KEY (`id`) USING BTREE,
INDEX `create_date`(`create_date`) USING BTREE,
INDEX `end_date`(`end_date`) USING BTREE,
INDEX `city_id`(`city_id`, `end_date`) USING BTREE,
INDEX `job_name_id`(`job_name_id`, `create_date`, `city_id`) USING BTREE,
INDEX `job_name_id_2`(`job_name_id`, `end_date`, `working_exp_id`) USING BTREE,
INDEX `job_name_id_3`(`job_name_id`, `end_date`, `edu_level_id`) USING BTREE
) ENGINE = MyISAM CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for job_0
-- ----------------------------
DROP TABLE IF EXISTS `job_0`;
CREATE TABLE `job_0` (
`id` bigint(20) NOT NULL,
`job_number` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '职位号码',
`job_name_id` int(11) NOT NULL COMMENT '职位名',
`salary` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '职位薪资',
`empl_type` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '职位类型(如:全职或实习)',
`recruit_count` int(11) NULL DEFAULT NULL COMMENT '职位数',
`working_exp_id` int(11) NOT NULL COMMENT '工作经验',
`edu_level_id` int(11) NOT NULL COMMENT '学历需求',
`company_id` bigint(20) NOT NULL COMMENT '公司',
`city_id` int(11) NOT NULL COMMENT '所在城市',
`create_date` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
`end_date` datetime(0) NULL DEFAULT NULL COMMENT '过期时间',
PRIMARY KEY (`id`) USING BTREE,
INDEX `city_id`(`end_date`, `city_id`) USING BTREE,
INDEX `job_name_id`(`job_name_id`, `city_id`, `create_date`) USING BTREE,
INDEX `job_name_id_2`(`job_name_id`, `working_exp_id`, `end_date`) USING BTREE,
INDEX `job_name_id_3`(`job_name_id`, `edu_level_id`, `end_date`) USING BTREE,
INDEX `job_name_id_4`(`job_name_id`, `end_date`) USING BTREE
) ENGINE = MyISAM CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for job_1
-- ----------------------------
DROP TABLE IF EXISTS `job_1`;
CREATE TABLE `job_1` (
`id` bigint(20) NOT NULL,
`job_number` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '职位号码',
`job_name_id` int(11) NOT NULL COMMENT '职位名',
`salary` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '职位薪资',
`empl_type` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '职位类型(如:全职或实习)',
`recruit_count` int(11) NULL DEFAULT NULL COMMENT '职位数',
`working_exp_id` int(11) NOT NULL COMMENT '工作经验',
`edu_level_id` int(11) NOT NULL COMMENT '学历需求',
`company_id` bigint(20) NOT NULL COMMENT '公司',
`city_id` int(11) NOT NULL COMMENT '所在城市',
`create_date` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
`end_date` datetime(0) NULL DEFAULT NULL COMMENT '过期时间',
PRIMARY KEY (`id`) USING BTREE,
INDEX `city_id`(`end_date`, `city_id`) USING BTREE,
INDEX `job_name_id`(`job_name_id`, `city_id`, `create_date`) USING BTREE,
INDEX `job_name_id_2`(`job_name_id`, `working_exp_id`, `end_date`) USING BTREE,
INDEX `job_name_id_3`(`job_name_id`, `edu_level_id`, `end_date`) USING BTREE,
INDEX `job_name_id_4`(`job_name_id`, `end_date`) USING BTREE
) ENGINE = MyISAM CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for job_2
-- ----------------------------
DROP TABLE IF EXISTS `job_2`;
CREATE TABLE `job_2` (
`id` bigint(20) NOT NULL,
`job_number` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '职位号码',
`job_name_id` int(11) NOT NULL COMMENT '职位名',
`salary` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '职位薪资',
`empl_type` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '职位类型(如:全职或实习)',
`recruit_count` int(11) NULL DEFAULT NULL COMMENT '职位数',
`working_exp_id` int(11) NOT NULL COMMENT '工作经验',
`edu_level_id` int(11) NOT NULL COMMENT '学历需求',
`company_id` bigint(20) NOT NULL COMMENT '公司',
`city_id` int(11) NOT NULL COMMENT '所在城市',
`create_date` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
`end_date` datetime(0) NULL DEFAULT NULL COMMENT '过期时间',
PRIMARY KEY (`id`) USING BTREE,
INDEX `city_id`(`end_date`, `city_id`) USING BTREE,
INDEX `job_name_id`(`job_name_id`, `city_id`, `create_date`) USING BTREE,
INDEX `job_name_id_2`(`job_name_id`, `working_exp_id`, `end_date`) USING BTREE,
INDEX `job_name_id_3`(`job_name_id`, `edu_level_id`, `end_date`) USING BTREE,
INDEX `job_name_id_4`(`job_name_id`, `end_date`) USING BTREE
) ENGINE = MyISAM CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for job_merge
-- ----------------------------
DROP TABLE IF EXISTS `job_merge`;
CREATE TABLE `job_merge` (
`id` bigint(20) NOT NULL,
`job_number` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '职位号码',
`job_name_id` int(11) NOT NULL COMMENT '职位名',
`salary` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '职位薪资',
`empl_type` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '职位类型(如:全职或实习)',
`recruit_count` int(11) NULL DEFAULT NULL COMMENT '职位数',
`working_exp_id` int(11) NOT NULL COMMENT '工作经验',
`edu_level_id` int(11) NOT NULL COMMENT '学历需求',
`company_id` bigint(20) NOT NULL COMMENT '公司',
`city_id` int(11) NOT NULL COMMENT '所在城市',
`create_date` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
`end_date` datetime(0) NULL DEFAULT NULL COMMENT '过期时间',
PRIMARY KEY (`id`) USING BTREE,
INDEX `city_id`(`end_date`, `city_id`) USING BTREE,
INDEX `job_name_id`(`job_name_id`, `city_id`, `create_date`) USING BTREE,
INDEX `job_name_id_2`(`job_name_id`, `working_exp_id`, `end_date`) USING BTREE,
INDEX `job_name_id_3`(`job_name_id`, `edu_level_id`, `end_date`) USING BTREE,
INDEX `job_name_id_4`(`job_name_id`, `end_date`) USING BTREE
) ENGINE = MRG_MYISAM CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic UNION = (`job_0`,`job_1`,`job_2`);
-- ----------------------------
-- Table structure for job_name
-- ----------------------------
DROP TABLE IF EXISTS `job_name`;
CREATE TABLE `job_name` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`job_label` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 9 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for job_welfare
-- ----------------------------
DROP TABLE IF EXISTS `job_welfare`;
CREATE TABLE `job_welfare` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`job_id` bigint(20) NOT NULL,
`welfare_id` int(11) NOT NULL,
PRIMARY KEY (`id`) USING BTREE,
INDEX `job_index`(`job_id`) USING BTREE,
INDEX `welfare_index`(`welfare_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4383178 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`role_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for sequence
-- ----------------------------
DROP TABLE IF EXISTS `sequence`;
CREATE TABLE `sequence` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`table_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`next_id` bigint(20) NOT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`user_password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `user_name`(`user_name`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for user_role
-- ----------------------------
DROP TABLE IF EXISTS `user_role`;
CREATE TABLE `user_role` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) NULL DEFAULT NULL,
`role_id` int(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for welfare
-- ----------------------------
DROP TABLE IF EXISTS `welfare`;
CREATE TABLE `welfare` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`welfare_label` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 986 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for working_exp
-- ----------------------------
DROP TABLE IF EXISTS `working_exp`;
CREATE TABLE `working_exp` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`working_label` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
<file_sep>/datadisplay/src/main/js/src/api/recommend.js
import request from '@/utils/request'
export function getSalaryRanking() {
return request({
url: '/recommend/salary',
method: 'get',
})
}
export function getEduLevelRanking() {
return request({
url: '/recommend/edu',
method: 'get',
})
}
export function getJobRanking() {
return request({
url: '/recommend/job',
method: 'get',
})
}
export function getJobRankingByCity() {
return request({
url: '/recommend/city',
method: 'get',
})
}
export function getJobRankingByWorkingExp() {
return request({
url: '/recommend/working',
method: 'get',
})
}
<file_sep>/datadisplay/src/main/js/src/store/modules/recommend.js
import { getSalaryRanking, getEduLevelRanking, getJobRanking, getJobRankingByCity, getJobRankingByWorkingExp } from '@/api/recommend'
const recommend = {
actions: {
getSalaryRanking({ commit }) {
return new Promise((resolve, reject) => {
getSalaryRanking().then(response => {
resolve(response)
}).catch(error => {
reject(error)
})
})
},
getEduLevelRanking({ commit }) {
return new Promise((resolve, reject) => {
getEduLevelRanking().then(response => {
resolve(response)
}).catch(error => {
reject(error)
})
})
},
getJobRanking({ commit }) {
return new Promise((resolve, reject) => {
getJobRanking().then(response => {
resolve(response)
}).catch(error => {
reject(error)
})
})
},
getJobRankingByCity({ commit }) {
return new Promise((resolve, reject) => {
getJobRankingByCity().then(response => {
resolve(response)
}).catch(error => {
reject(error)
})
})
},
getJobRankingByWorkingExp({ commit }) {
return new Promise((resolve, reject) => {
getJobRankingByWorkingExp().then(response => {
resolve(response)
}).catch(error => {
reject(error)
})
})
}
}
}
export default recommend
<file_sep>/datadisplay/src/main/java/indi/aiurmaple/recruitanalyze/datadisplay/entity/JobEntity.java
package indi.aiurmaple.recruitanalyze.datadisplay.entity;
import lombok.Data;
import java.sql.Timestamp;
@Data
public class JobEntity {
private Long id;
private String jobNumber;
private Integer jobNameId;
private String salary;
private String emplType;
private Integer recruitCount;
private Integer workingExpId;
private Integer eduLevelId;
private Long companyId;
private Integer cityId;
private Timestamp createDate;
private Timestamp endDate;
}
<file_sep>/datadisplay/src/main/java/indi/aiurmaple/recruitanalyze/datadisplay/security/JWTLoginFilter.java
package indi.aiurmaple.recruitanalyze.datadisplay.security;
import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import indi.aiurmaple.recruitanalyze.datadisplay.model.ExceptionModel;
import indi.aiurmaple.recruitanalyze.datadisplay.model.ResponseModel;
import indi.aiurmaple.recruitanalyze.datadisplay.security.model.AccountCredentials;
import indi.aiurmaple.recruitanalyze.datadisplay.util.CorsUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {
private static final Gson GSON = new Gson();
private TokenAuthenticationService tokenAuthenticationService;
public JWTLoginFilter(String url, String method, AuthenticationManager authManager, TokenAuthenticationService tokenAuthenticationService) {
super(new AntPathRequestMatcher(url, method));
setAuthenticationManager(authManager);
this.tokenAuthenticationService = tokenAuthenticationService;
}
@Override
public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws AuthenticationException, IOException, ServletException {
CorsUtil.setCors(httpServletResponse);
// JSON反序列化成 AccountCredentials
BufferedReader reader = new BufferedReader(new InputStreamReader(httpServletRequest.getInputStream()));
AccountCredentials creds = GSON.fromJson(IOUtils.toString(reader), AccountCredentials.class);
if (creds == null) {
throw new AuthenticationCredentialsNotFoundException("The account entered is empty, Please check your input");
}
// 返回一个验证令牌
return getAuthenticationManager().authenticate(
new UsernamePasswordAuthenticationToken(
creds.getUsername(),
creds.getPassword()
)
);
}
@Override
protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain,
Authentication auth) throws IOException, ServletException {
tokenAuthenticationService.addAuthentication(res, auth.getName(), auth.getAuthorities());
}
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed)
throws IOException, ServletException {
ResponseModel<ExceptionModel> responseModel = new ResponseModel<>(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, false,
"Authentication failed", new ExceptionModel(request.getRequestURI(), failed.getMessage()));
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
out.println(JSON.toJSONString(responseModel));
}
}
<file_sep>/datadisplay/src/main/java/indi/aiurmaple/recruitanalyze/datadisplay/controller/WelfareController.java
package indi.aiurmaple.recruitanalyze.datadisplay.controller;
import indi.aiurmaple.recruitanalyze.datadisplay.model.ResponseModel;
import indi.aiurmaple.recruitanalyze.datadisplay.model.WelfareReponseModel;
import indi.aiurmaple.recruitanalyze.datadisplay.service.WelfareService;
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;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@RestController
@RequestMapping("/welfare")
public class WelfareController {
@Autowired
private WelfareService welfareService;
@RequestMapping(value = "/num", method = RequestMethod.GET)
public ResponseModel<List<WelfareReponseModel>> getWelfareNumByJob(Integer jobNameId) {
if(jobNameId == null) {
return new ResponseModel<>(HttpServletResponse.SC_BAD_REQUEST, false,
"Input parameter error, Please check your parameter!", null);
}
List<WelfareReponseModel> welfareReponseModels = welfareService.getWelfareNumByJob(jobNameId);
return new ResponseModel<>(HttpServletResponse.SC_OK, true, "Success!", welfareReponseModels);
}
}
<file_sep>/datatransform/src/main/java/indi/aiurmaple/recruitanalyze/datatransform/utils/DataUtils.java
package indi.aiurmaple.recruitanalyze.datatransform.utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class DataUtils {
public static String handleJobName(String fileName) {
String[] arr = fileName.split("_");
return arr[0];
}
public static String handleCity(String fileName) {
String[] arr1 = fileName.split("_");
String str = arr1[1];
Integer num = str.indexOf(".json");
return str.substring(0, num);
}
public static String handleWorkingExp(JSONObject root) {
JSONObject workingExp = root.getJSONObject("workingExp");
return workingExp.getString("name");
}
public static String handleEduLevel(JSONObject root) {
JSONObject eduLevel = root.getJSONObject("eduLevel");
return eduLevel.getString("name");
}
public static String handleCompanySize(JSONObject root) {
JSONObject companySize = root.getJSONObject("size");
return companySize.getString("name");
}
public static String handleCompanyType(JSONObject root) {
JSONObject companyType = root.getJSONObject("type");
return companyType.getString("name");
}
public static List<String> handleWelfares(JSONObject root) {
JSONArray welfareArr = root.getJSONArray("welfare");
List<String> welfares = new ArrayList<>();
welfareArr.forEach((welfare) -> {
welfares.add((String)welfare);
});
return welfares;
}
}
<file_sep>/datatransform/src/main/java/indi/aiurmaple/recruitanalyze/datatransform/dao/JobRepository.java
package indi.aiurmaple.recruitanalyze.datatransform.dao;
import indi.aiurmaple.recruitanalyze.datatransform.entity.JobEntity;
import org.springframework.data.jpa.repository.JpaRepository;
public interface JobRepository extends JpaRepository<JobEntity, Long> {
}
<file_sep>/datadisplay/src/main/js/src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import app from './modules/app'
import user from './modules/user'
import job from './modules/job'
import city from './modules/city'
import edu from './modules/edu'
import workExp from './modules/workExp'
import welfare from './modules/welfare'
import recommend from './modules/recommend'
import getters from './getters'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
app,
user,
job,
city,
edu,
workExp,
welfare,
recommend
},
getters
})
export default store
<file_sep>/datatransform/src/main/java/indi/aiurmaple/recruitanalyze/datatransform/entity/EduLevelEntity.java
package indi.aiurmaple.recruitanalyze.datatransform.entity;
import javax.persistence.*;
import java.util.Objects;
@Entity
@Table(name = "edu_level", schema = "recruit_analyze")
public class EduLevelEntity {
private Integer id;
private String eduLabel;
public EduLevelEntity() {
}
public EduLevelEntity(String eduLabel) {
this.eduLabel = eduLabel;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Basic
@Column(name = "edu_label")
public String getEduLabel() {
return eduLabel;
}
public void setEduLabel(String eduLabel) {
this.eduLabel = eduLabel;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EduLevelEntity that = (EduLevelEntity) o;
return id.equals(that.id) &&
Objects.equals(eduLabel, that.eduLabel);
}
@Override
public int hashCode() {
return Objects.hash(id, eduLabel);
}
}
|
ed487d8f01d0bb82517cd41e65deb76a88f63b2f
|
[
"SQL",
"Markdown",
"JavaScript",
"Java",
"Python"
] | 42 |
Java
|
aiurmaple/RecruitAnalyze
|
762a95bd83eb7d4e429f73f9a24f19f8ffe3ad0a
|
5510e04e15c0cdfe07dd27ccfc1af43c2993b8f6
|
refs/heads/master
|
<file_sep>from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.Chrome()
driver.get('https://orteil.dashnet.org/cookieclicker/')
driver.implicitly_wait(5)
cookie = driver.find_element_by_id('bigCookie')
cookie_count = driver.find_element_by_id('cookies')
items = [driver.find_element_by_id("productPrice" + str(i)) for i in range(1,-1,-1)]
actions = ActionChains(driver)
actions.click(cookie)
for i in range(5000):
actions.perform()
count = int(cookie_count.text.split(" ")[0])
cps = float(cookie_count.text.split(" ")[4])
best = 1
cnt = 1
ok = False
for item in items:
#print(item.text)
if item.text != '':
aux = item.text.split(',')
if len(aux) > 1:
num = str(aux[0]) + str(aux[1])
else:
num = str(aux[0])
if num != '':
value = int(num)
#print(value)
if cps < 0.5 and cnt == 2:
#print(str(best) + "a")
bestItem = item
price = value
elif cnt == 1 and cps >= 0.5:
bestItem = item
price = value
cnt += 1
if count >= price:
upgrade_actions = ActionChains(driver)
upgrade_actions.move_to_element(bestItem)
upgrade_actions.click()
upgrade_actions.perform()
|
670d61985c12b364b20c7a8c5c5bd82380246af6
|
[
"Python"
] | 1 |
Python
|
mihaihe1/cookie
|
1a9fe836230577764a2552c486e18519a295f6ad
|
abfd716287e355e8794cadd03afd446d4db7754b
|
refs/heads/master
|
<file_sep>class Manager:
def __init__(self, man_id: int, man_name: str, man_user: str, man_pass: str):
self.man_id = man_id
self.man_name = man_name
self.man_user = man_user
self.man_pass = man_pass
def as_json_dict(self):
return{
"managerId": self.man_id,
"managerName": self.man_name,
"userName": self.man_user,
"password": <PASSWORD>
}
<file_sep># Project Description
A certain Bug-catching club just finished designing their first website. They're so confident in their coding that they'll pay anyone who can find bugs on their site!
# Features
* Members can create requests and view the approval status of their past reimbursements.
* Managers can view all pending requests and choose to approve or deny them with an optional comment. They also have access to a visual display of statistics related to members' requests.
# Technologies Used
Python
Javascript with Async Awaits
HTML 5
PyTest
Selenium with Cucumber
PostgreSQL hosted on AWS RDS
# See Also
https://github.com/mrussell481/reimProjectFront
<file_sep>from typing import List
from daos.member_dao import MemberDao
from entities.member import Member
from entities.reimbursement import Reimbursement
from utils.connection_util import connection
class MemberDaoImpl(MemberDao):
def login(self, user_name: str, password: str) -> Member:
cursor = connection.cursor()
sql = """select * from site_member where mem_user = '{}' and mem_pass = '{}';""".format(user_name, password)
cursor.execute(sql)
record = cursor.fetchone()
user = Member(*record)
return user
def view_member_requests(self, member_id: int) -> List[Reimbursement]:
cursor = connection.cursor()
sql = """select * from reimbursement where mem_id = '{}' order by rb_id desc;""".format(member_id)
cursor.execute(sql)
records = cursor.fetchall()
request_list = []
for x in records:
request_list.append(Reimbursement(*x))
return request_list
#def view_request(self, member_id: int, request_id: int) -> Reimbursement:
# pass
def create_request(self, reim: Reimbursement) -> str:
cursor = connection.cursor()
sql = """insert into reimbursement (rb_name, sender, reason, amount, rb_date, mem_id)
values ('{}', '{}', '{}', {}, {}, {});""".format(reim.rb_name, reim.sender, reim.reason,
reim.amount, reim.date, reim.fk_mem_id)
cursor.execute(sql)
connection.commit()
return "Successfully added your reimbursement."
<file_sep>from abc import ABC, abstractmethod
from typing import List
from entities.member import Member
from entities.reimbursement import Reimbursement
class MemberService(ABC):
@abstractmethod
def login(self, user_name: str, password: str) -> Member:
pass
@abstractmethod
def view_member_requests(self, member_id: int) -> List[Reimbursement]:
pass
#@abstractmethod
#def view_request(self, member_id: int, request_id: int) -> Reimbursement:
# pass
@abstractmethod
def create_request(self, reim: Reimbursement) -> str:
pass
<file_sep>from typing import List
from daos.manager_dao import ManagerDao
from entities.manager import Manager
from entities.reimbursement import Reimbursement
from utils.connection_util import connection
class ManagerDaoImpl(ManagerDao):
def login(self, user_name: str, password: str) -> Manager:
cursor = connection.cursor()
sql = """select * from manager where man_user = '{}' and man_pass = '{}';""".format(user_name, password)
cursor.execute(sql)
record = cursor.fetchone()
user = Manager(*record)
return user
def view_all_requests(self) -> List[Reimbursement]:
cursor = connection.cursor()
sql = """select * from reimbursement order by rb_id desc;"""
cursor.execute(sql)
records = cursor.fetchall()
request_list = []
for x in records:
request_list.append(Reimbursement(*x))
return request_list
def judge_request(self, member_id: int, request_id: int, verdict: bool, comment: str) -> str:
cursor = connection.cursor()
sql = """update reimbursement set approved = {} where mem_id = {} and rb_id = {};""".format(verdict,
member_id,
request_id)
cursor.execute(sql)
if len(comment) > 0:
sql = """update reimbursement set man_comment = '{}' where mem_id = {} and rb_id = {}""".format(comment,
member_id,
request_id)
cursor.execute(sql)
connection.commit()
return "Successfully updated approval status."
def statistics(self) -> list:
# The values in stats_list are as follows:
# 1. Member who made the most off of reimbursements
# 2. How much that member made
# 3. Member who made the most requests
# 4. Number of requests they made
# 5. Total number of requests
# 6. Total amount of money made by members
# 7. Approval Rate
# 8. Average number of Requests per member
# 9. Number of approved requests (used for the pie chart)
stats_list = []
# Step 1 and 2
cursor = connection.cursor()
sql = """select sender, sum(amount) from reimbursement group by sender;"""
cursor.execute(sql)
records = cursor.fetchall()
richest_member_list = []
for record in records:
richest_member_list.append(record)
richest_member_name = ""
richest_member_amount = 0
for record in richest_member_list:
if record[1] > richest_member_amount:
richest_member_amount = record[1]
richest_member_name = record[0]
stats_list.append(richest_member_name)
stats_list.append(richest_member_amount)
# Step 3 and 4
sql = """SELECT sender, count(*)
FROM reimbursement
GROUP BY sender
order by count desc;"""
cursor.execute(sql)
requesting_member_record = cursor.fetchone()
requesting_member = []
for record in requesting_member_record:
requesting_member.append(record)
stats_list.append(requesting_member[0])
stats_list.append(requesting_member[1])
# Step 5
sql = """select count(*) from reimbursement;"""
cursor.execute(sql)
request_count = cursor.fetchone()
request_total = request_count[0]
stats_list.append(request_count[0])
# Step 6
sql = """select sum(amount) from reimbursement;"""
cursor.execute(sql)
reim_amount = cursor.fetchone()
stats_list.append(reim_amount[0])
# Step 7
sql = """select count(approved) from reimbursement where approved = true;"""
cursor.execute(sql)
accept_rate = cursor.fetchone()
stats_list.append(round((accept_rate[0] / request_total)*100, 3))
# Step 8
sql = """select count(*) from site_member;"""
cursor.execute(sql)
member_count = cursor.fetchone()
stats_list.append(round((request_total / member_count[0]), 3))
# Step 9
stats_list.append(accept_rate[0])
return stats_list
<file_sep>from typing import List
from daos.manager_dao import ManagerDao
from entities.manager import Manager
from entities.reimbursement import Reimbursement
from services.manager_service import ManagerService
class ManagerServiceImpl(ManagerService):
def __init__(self, manager_dao: ManagerDao):
self.manager_dao = manager_dao
def login(self, user_name: str, password: str) -> Manager:
return self.manager_dao.login(user_name, password)
def view_all_requests(self) -> List[Reimbursement]:
return self.manager_dao.view_all_requests()
def judge_request(self, member_id: int, request_id: int, verdict: bool, comment: str) -> str:
return self.manager_dao.judge_request(member_id, request_id, verdict, comment)
def statistics(self) -> list:
return self.manager_dao.statistics()
<file_sep>from daos.member_dao import MemberDao
from daos.member_dao_impl import MemberDaoImpl
from entities.member import Member
from entities.reimbursement import Reimbursement
member_dao: MemberDao = MemberDaoImpl()
def test_member_login():
member: Member = member_dao.login("realrocky46", "jkcbn43857qo")
assert member.mem_name == "<NAME>"
def test_view_member_requests():
assert len(member_dao.view_member_requests(1)) > 6
def test_new_request():
new_request = Reimbursement(0,
"Pytest Bug",
"Mizutani",
"Pytest can submit its own bugs!",
0,
893,
None,
None,
2)
assert member_dao.create_request(new_request) == "Successfully added your reimbursement."
<file_sep>from typing import List
from daos.member_dao import MemberDao
from entities.member import Member
from entities.reimbursement import Reimbursement
from services.member_service import MemberService
class MemberServiceImpl(MemberService):
def __init__(self, member_dao: MemberDao):
self.member_dao = member_dao
def login(self, user_name: str, password: str) -> Member:
return self.member_dao.login(user_name, password)
def view_member_requests(self, member_id: int) -> List[Reimbursement]:
return self.member_dao.view_member_requests(member_id)
#def view_request(self, member_id: int, request_id: int) -> Reimbursement:
# pass
def create_request(self, reim: Reimbursement) -> str:
return self.member_dao.create_request(reim)
<file_sep>from flask import Flask, request, jsonify, render_template
from flask_cors import CORS
import logging
from services.manager_service_impl import ManagerServiceImpl
from services.member_service_impl import MemberServiceImpl
from daos.manager_dao_impl import ManagerDaoImpl
from daos.member_dao_impl import MemberDaoImpl
from entities.member import Member
from entities.manager import Manager
from entities.reimbursement import Reimbursement
from exceptions.user_not_found import UserNotFound
app: Flask = Flask(__name__)
CORS(app)
logging.basicConfig(filename="records.log", level=logging.DEBUG, format=f'%(asctime)s %(levelname)s %(message)s')
member_dao = MemberDaoImpl()
manager_dao = ManagerDaoImpl()
manager_service = ManagerServiceImpl(manager_dao)
member_service = MemberServiceImpl(member_dao)
# The landing page is just here to help build context leading up to the other functions of this site.
# Returns an HTML with no other logic.
@app.route("/", methods=["GET"])
def home_page():
return render_template("main.html")
# A single page serves as a login, reimbursement viewer and manager, as well as a stats page.
# With no information being carried between webpages, there is no need to use session storage or cookies for this site.
# All data (including the login) is cleared when the page is refreshed, allowing you to quickly switch users to
# demo both members and managers.
# The initial routing to this 'God page' only returns an HTML.
@app.route("/bugCatch", methods=["GET"])
def main_page():
return render_template("main.html")
# Log-in request that looks for a user in both the member and manager tables,
# and then returns a list of requests depending on whether the user is an member or manager.
# The front-end will use the info to verify the login and determine which page to show.
# Should return a list with the user object and whether they're a member or manager.
@app.route("/bugCatch/login", methods=["POST"])
def login():
body = request.json
user_name = body["userName"]
password = <PASSWORD>["<PASSWORD>"]
try:
manager = manager_service.login(user_name, password)
return jsonify(manager.as_json_dict()), 200
except Exception:
try:
member = member_service.login(user_name, password)
return jsonify(member.as_json_dict()), 200
except Exception:
return "Incorrect username or password", 404
# A second call made by the login button if the user is a manager. Returns all requests.
@app.route("/bugCatch/requests", methods=["GET"])
def requests():
request_list = manager_service.view_all_requests()
json_list = [l.as_json_dict() for l in request_list]
return jsonify(json_list), 200
# A second call if the user is a member. Returns only requests belonging to them.
@app.route("/bugCatch/requests/<mem_id>", methods=["GET"])
def requests_by_user(mem_id: int):
request_list = member_service.view_member_requests(mem_id)
json_list = [l.as_json_dict() for l in request_list]
if json_list:
return jsonify(json_list), 200
else:
return "Member could not be found.", 404
# Returns a specific reimbursement.
# Managers should also see buttons to approve/deny new requests, but that is handled on the front end.
#@app.route("/bugCatch/member/<mem_id>/reim/<reim_id>", methods=["GET"])
#def retrieve_request(mem_id: int, reim_id: int):
# reimbursement = member_service.view_request(mem_id, reim_id)
# return jsonify(reimbursement.as_json_dict()), 200
# Takes in information from a reimbursement request,
# returns either a success or failure message.
# Front end logic should check each element to ensure everything is filled out.
# Optional: refresh the list of requests to include the new one.
@app.route("/bugCatch/member/<mem_id>/create", methods=["POST"])
def create_request(mem_id: int):
try:
body = request.json
new_request = Reimbursement(body["reimbursementID"],
body["reimbursementName"],
body["sender"],
body["reason"],
body["amount"],
body["date"],
body["approved"],
body["comment"],
body["memberId"])
new_request.fk_mem_id = mem_id
member_service.create_request(new_request)
return "Request created successfully.", 201
except:
return "Unable to create request.", 422
# Updates a request's status to "approved" or "denied", and may also have a comment.
# Returns a success or failure message.
@app.route("/bugCatch/member/<mem_id>/reim/<reim_id>/judge", methods=["PATCH"])
def judge_request(mem_id: int, reim_id: int):
body = request.json
verdict = body["verdict"]
comment = body["comment"]
try:
manager_service.judge_request(mem_id, reim_id, verdict, comment)
return "Success.", 200
except:
return "Failure.", 422
# Returns a list of numbers that represent various statistics about the requests
# made in the database.
@app.route("/bugCatch/stats", methods=["GET"])
def stats():
#stats_list = []
stats_list = manager_service.statistics()
return jsonify(stats_list), 200
if __name__ == '__main__':
app.run()
<file_sep>from daos.manager_dao import ManagerDao
from daos.manager_dao_impl import ManagerDaoImpl
from entities.manager import Manager
manager_dao: ManagerDao = ManagerDaoImpl()
def test_statistics():
stats_list = manager_dao.statistics()
counter = 0
for x in stats_list:
counter += 1
assert counter == 9
def test_judge_request():
response = manager_dao.judge_request(2, 1, True, "Thank you for your help!")
assert response == "Successfully updated approval status."
def test_view_all_requests():
assert len(manager_dao.view_all_requests()) > 10
def test_manager_login():
manager: Manager = manager_dao.login("toughguy12", "0921q83n54v18746")
assert manager.man_name == "<NAME>"
<file_sep>class Member:
def __init__(self, mem_id: int, mem_name: str, mem_user: str, mem_pass: str):
self.mem_id = mem_id
self.mem_name = mem_name
self.mem_user = mem_user
self.mem_pass = mem_pass
def as_json_dict(self):
return{
"memberId": self.mem_id,
"memberName": self.mem_name,
"userName": self.mem_user,
"password": <PASSWORD>
}
<file_sep>class Reimbursement:
def __init__(self, rb_id: int, rb_name: str, sender: str, reason: str, amount: float, date: int, approved: str,
comment: str, fk_mem_id: int):
self.rb_id = rb_id
self.rb_name = rb_name
self.sender = sender
self.reason = reason
self.amount = amount
self.date = date
self.approved = approved
self.comment = comment
self.fk_mem_id = fk_mem_id
def as_json_dict(self):
return{
"reimbursementId": self.rb_id,
"reimbursementName": self.rb_name,
"sender": self.sender,
"reason": self.reason,
"amount": self.amount,
"date": self.date,
"approved": self.approved,
"comment": self.comment,
"memberId": self.fk_mem_id
}
<file_sep>from abc import ABC, abstractmethod
from typing import List
from entities.manager import Manager
from entities.reimbursement import Reimbursement
class ManagerDao(ABC):
@abstractmethod
def login(self, user_name: str, password: str) -> Manager:
pass
@abstractmethod
def view_all_requests(self) -> List[Reimbursement]:
pass
@abstractmethod
def judge_request(self, member_id: int, request_id: int, verdict: bool, comment: str) -> str:
pass
@abstractmethod
def statistics(self) -> list:
pass
|
b7ae3b698c5ea7a6e7238b788925872952082faa
|
[
"Markdown",
"Python"
] | 13 |
Python
|
mrussell481/reimProject
|
eefc4b1dd7829f1fde8cc252eab4b0b702baede0
|
db1e9775f7fd01be101cb41662bb1e728dadb128
|
refs/heads/master
|
<repo_name>simphony/simphony-espresso-dft<file_sep>/examples/charge_density_xyz.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cmath>
#include <cstdlib>
#include <cstdarg>
#include <sstream>
#include <cctype>
using namespace std;
// ---------------------------- //
// Functions
// ---------------------------- //
// FUNCTION TO SAVE THE FILE INTO AN ARRAY
void read_from_the_file(vector<string>& vector_file,string file_name);
// EXTRACT THE VARIABLES Nx, Ny, Nz, number_atoms AND CREATE A 1ROW-VECTOR WITH ALL THE CHARGE DENSITY
void extract_variables(vector<string>& vector_file,vector<float>& charge_density, int& nx, int& ny, int& nz, int& number_atoms);
// CREATE COLOR FOR CHARGE DENSITY
string create_color(float charge);
// CREATE AN OUPTUT XYZ FILE
void create_output_file(vector<float> charge_density,string file_name,int nx, int ny, int nz);
// ---------------------------- //
// Main
// ---------------------------- //
int main(int argc, char* argv[])
{
string file_name;
string part_nb;
int number_points; // number of lines - 2
vector<string> vector_file;
vector<float> charge_density;
int nx(0),ny(0),nz(0); // number of points in each direction of the grid
int number_atoms(0);
cout << "Name of the file to read (with extension) : " << endl;
cin >> file_name;
read_from_the_file(vector_file,file_name);
number_points = vector_file.size()-2;
cout << "Number of points : " << number_points << endl;
extract_variables(vector_file,charge_density,nx,ny,nz,number_atoms);
create_output_file(charge_density,file_name,nx,ny,nz);
}
// ---------------------------- //
// Definition of functions
// ---------------------------- //
void read_from_the_file(vector<string>& vector_file,string file_name)
{
std::ifstream file(file_name.c_str());
if(file.is_open())
{
string new_line;
while (getline(file,new_line))
{
vector_file.push_back(new_line);
}
}
else cout << "Unable to open file";
file.close();
}
void extract_variables(vector<string>& vector_file,vector<float>& charge_density, int& nx, int& ny, int& nz, int& number_atoms)
{
std::string str("");
std::string str0("");
const char *cstr("") ;
float d1(0.0),d2(0.0),d3(0.0),d4(0.0),d5(0.0);
// read the second line and attribute the values to nx,ny,nz and number_atoms
str = vector_file[1];
cstr = str.c_str();
sscanf(cstr,"%d %d %d %d %d %d %d",&nx,&ny,&nz,&nx,&ny,&nz,&number_atoms);
int start(0);
start = 5+number_atoms;
int incr(0);
// create the vector of densities
for (unsigned int i(start); i<vector_file.size(); i++)
{
str = vector_file[i];
cstr = str.c_str();
sscanf(cstr, "%E %E %E %E %E",&d1,&d2,&d3,&d4,&d5);
charge_density.push_back(d1);
incr = incr+1;
charge_density.push_back(d2);
incr = incr+1;
charge_density.push_back(d3);
incr = incr+1;
charge_density.push_back(d4);
incr = incr+1;
charge_density.push_back(d5);
incr = incr+1;
}
}
string create_color(float charge)
{
if (charge <= 0.0005)
{
return "a";
}
else if((charge > 0.0005) && (charge <= 0.001))
{
return "b";
}
else if((charge > 0.001) && (charge <=0.01))
{
return "c";
}
else if((charge > 0.01) && (charge <= 0.05))
{
return "d";
}
else if((charge > 0.05) && (charge <= 0.1))
{
return "e";
}
else if((charge > 0.1) && (charge <= 0.5))
{
return "f";
}
else if((charge > 0.5))
{
return "g";
}
else
return 0;
}
void create_output_file(vector<float> charge_density,string file_name,int nx, int ny, int nz)
{
string output_name;
output_name = file_name + "_.xyz";
std::ofstream file_out;
file_out.open(output_name.c_str());
file_out << charge_density.size() << endl;
file_out << "colored " << endl;
int incr(0);
for (unsigned int k(1); k<=nz; k++)
{
for (unsigned int j(1); j<=ny; j++)
{
for (unsigned int i(1); i<=nx; i++)
{
file_out << create_color(charge_density[incr]) << " " << i << ". " << j << ". " << k << ". " << charge_density[incr] << endl;
incr = i + (j-1) * nx + (k-1)*nx*ny;
}
}
}
file_out.close();
}
<file_sep>/README.md
# simphony-espresso-dft
<file_sep>/simespresso/io/espresso_data_file_handler.py
import string
from enum import Enum
from simphony.cuds.abstractlattice import ABCLattice
from simphony.core.data_container import DataContainer
from simphony.io.data_container_description import Record
#from simphony.core.data_container import DataContainer
import simphony.core.data_container
from simphony.core.cuba import CUBA
def ReadEspressoInputFile(file_name):
""" This class parses Espresso data files, either input or output
(produced by the espresso command write_data) and calls a handler
which processes the parsed information.
A handler class is given the parsed information. This handler class can
then determine what to do with it. For, example it could just store
the data in memory (see LammpsSimpleDataHandler) or write it some other
data file (e.g. a CUDS-file).
cheatsheet for quantum espresso
0. create/obtain input file such as pp.in from cuds data
1. run (using mpi for instance )
for file describing simulation
mpirun -np 48 /usr/local/espresso/bin/pw.x < input_pw.in > pw.out &
once simulation is done, run on file describing desired output
mpirun -np 48 /usr/local/espresso/bin/pp.x < input_pp.in > pp.out &
2. convert output (which is a charge density file) into simphony format (see charge_density_xyz.cpp)
Parameters
----------
handler :
handler will handle the parsed information provided by this class """
dc = simphony.core.data_container.DataContainer
dc(ACCELERATION=220)
state = _ReadState.UNKNOWN
with open(file_name, 'r') as f:
line_number = 0
file_iter = iter(f)
line = file_iter.next()
try:
while line is not None:
#file_iter.hasnext():
# #line = f[line_number]
line_number += 1
#DEBUG
print('read line:'+str(line))
# skip blank lines
# if not line.strip():
# continue
state = _ReadState.get_state(state,line)
if state is _ReadState.CONTROL:
print('reading control section')
line = process_control(file_iter)
continue
elif state is _ReadState.SYSTEM:
print('reading system')
line = process_system(file_iter)
continue
elif state is _ReadState.ELECTRONS:
print('reading electrons')
line = process_electrons(file_iter)
continue
elif state is _ReadState.ATOMIC_SPECIES:
print('reading atomic species')
line = process_atomic_species(file_iter)
continue
elif state is _ReadState.K_POINTS:
print('reading k points')
values = line.split()
line = process_k_points(file_iter,mode=values[1])
continue
elif state is _ReadState.ATOMIC_POSITIONS:
print('reading atomic positions')
values = line.split()
line = process_atomic_positions(file_iter,units=values[1])
if line == 'EOF':
return
else:
continue
line = file_iter.next()
except StopIteration:
print('eof reached')
return
except Exception:
print("problem with line number=", line_number, line)
raise
def process_control(f):
print('processing control section')
line = f.next()
while _ReadState.get_state(_ReadState.CONTROL,line) == _ReadState.CONTROL:
values = [x.strip() for x in line.split('=')]
print('line in control section:'+str(line))
if "calculation" in line:
values = line.split('=')
calculation = values[1]
elif "restart_mode" in line:
restart_mode = values[1]
elif "pseudo_dir" in line:
pseudo_dir = values[1]
elif "prefix" in line:
prefix = values[1]
elif "tprnfor" in line:
tprnfor = values[1]
elif "max_seconds" in line:
max_seconds = float(values[1])
elif "outdir" in line:
outdir = values[1]
line = f.next()
return line
def process_system(f):
print('processing system section')
line = f.next()
celldm=[0,0,0]
while _ReadState.get_state(_ReadState.SYSTEM,line) == _ReadState.SYSTEM:
values = [x.strip() for x in line.split('=')]
print('line in control section:'+str(line))
if "ibrav" in line:
ibrav = int(values[1])
elif "celldm(1)" in line:
celldm[0] = float(values[1])
elif "celldm(2)" in line:
celldm[1] = float(values[1])
elif "celldm(3)" in line:
celldm[2] = float(values[1])
elif "nat" in line:
n_atoms = int(values[1])
elif "ntyp" in line:
n_atom_types = int(values[1])
elif "ecutwfc" in line:
ecutwfc = float(values[1])
elif "ecutrho" in line:
ecutrho = float(values[1]) #maybe int
elif "input_dft" in line:
input_dft = values[1]
line = f.next()
return line
def process_electrons(f):
print('processing eletrons section')
line = f.next()
while _ReadState.get_state(_ReadState.ELECTRONS,line) == _ReadState.ELECTRONS:
values = [x.strip() for x in line.split('=')]
print('line in electrons section:'+str(line))
if "mixing_mode" in line:
mixing_mode = values[1]
elif "mixing_beta" in line:
mixing_beta = float(values[1])
elif "conv_thr" in line:
conv_thr = values[1] #numbers like 1.0d-7 might have to be converted to float
line = f.next()
return line
def process_atomic_species(f):
print('processing atomic species section')
line = f.next()
while _ReadState.get_state(_ReadState.ATOMIC_SPECIES,line) == _ReadState.ATOMIC_SPECIES:
values = line.split()
print('line in atomic species section:'+str(line))
# print('atomtypes:'+str(self.atomtypes))
if len(values)>0:
if values[0] in atomtypes:
print("atom type:"+values[0])
#self.dc(CHEMICAL_SPECIE = values[0])
DataContainer(CHEMICAL_SPECIE=values[0])
mass = float(values[1])
potential_file = values[2]
line = f.next()
return line
def process_k_points(f,mode='automatic'):
#skip line
print('processing k_points section')
line = f.next()
while _ReadState.get_state(_ReadState.ATOMIC_SPECIES,line) == _ReadState.ATOMIC_SPECIES:
values = [x.strip() for x in line.split('=')]
print('line in k points section:'+str(line))
K_points = values
line = f.next()
return line
# for each particle in the file, we do the following
## coords = # determine coordinates
# specie = # determine chemical specie
# partcle = Particle(coordinates = coords
# particle.data[CUBA.CHEMICAL_SPECIE] = specie
# particles.add_particle(particle)
# return particles
def process_atomic_positions(f,units='(angstrom)'):
print('processing atomic_positions section')
atom_positions = []
try:
line = f.next()
except StopIteration:
return('EOF')
while _ReadState.get_state(_ReadState.ATOMIC_SPECIES,line) == _ReadState.ATOMIC_SPECIES:
print('line in atomic positions section:'+str(line))
values = [x.strip() for x in line.split('=')]
if values[0] in atomtypes:
atomtype = values[0]
atom_pos[0] = values[1]
atom_pos[1] = values[2]
atom_pos[2] = values[3]
atom_positions.append(atom_pos)
try:
line = f.next()
except StopIteration:
return('EOF')
return line
class _ReadState(Enum):
UNKNOWN, UNSUPPORTED, \
CONTROL,\
SYSTEM, \
ELECTRONS, \
IONS, \
CELL, \
ATOMIC_SPECIES, \
K_POINTS, \
ATOMIC_POSITIONS = range(10)
@staticmethod
def get_state(current_state, line):
""" Reads line and returns state
"""
new_state = current_state
# TODO how the state is determined and how
# we transition to other states needs to be
# rewritten.
# print('entering getstate')
if "&CONTROL" in line:
new_state = _ReadState.CONTROL
elif "&SYSTEM" in line:
new_state = _ReadState.SYSTEM
elif "&ELECTRONS" in line:
new_state = _ReadState.ELECTRONS
elif "&IONS" in line:
new_state = _ReadState.UNSUPPORTED
elif "&CELL" in line:
new_state = _ReadState.UNSUPPORTED
elif "ATOMIC_SPECIES" in line:
new_state = _ReadState.ATOMIC_SPECIES
elif "K_POINTS" in line:
new_state = _ReadState.K_POINTS
elif "ATOMIC_POSITIONS" in line:
new_state = _ReadState.ATOMIC_POSITIONS
print('current state:'+str(new_state))
return new_state
atomtypes = ["C","H","He","N","O","Na","Mg"]
if __name__ == "__main__":
filename = 'pw.in'
print('started parsing file '+str(filename))
ReadEspressoInputFile(filename)
|
778bcc07105a0a0fb6737c11e67119ad9534c01c
|
[
"Markdown",
"Python",
"C++"
] | 3 |
C++
|
simphony/simphony-espresso-dft
|
c82eaa4c0f31b02e2f074a9fbc4ed2db582e41e1
|
190b7bb7d9447f5bf4b702584862570c416b2292
|
refs/heads/master
|
<file_sep>from tkinter import Tk
from tkinter.filedialog import askopenfilename
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
print(filename)
def alb_collab_to_pdf(filename):
os.system('apt-get install texlive texlive-xetex texlive-latex-extra pandoc')
os.system('pip install pypandoc')
os.system('jupyter nbconvert --to PDF'+filename)
|
d8ffa0065c3c57b299d4eacfd7feb857463f36b1
|
[
"Python"
] | 1 |
Python
|
albertoisorna/UDE
|
c69cf6ad488cfc33f9f18330cdf542a996167b22
|
5fb96f8183bd695584edcb2bee80da49b40e3941
|
refs/heads/master
|
<file_sep>'use strict'
var chai = require('chai')
chai.use(require('chai-shallow-deep-equal'))
chai.use(require('chai-as-promised'));
chai.use(require('chai-json-equal'));
chai.config.includeStack = true
global.expect = chai.expect
global.AssertionError = chai.AssertionError
global.Assertion = chai.Assertion
global.assert = chai.assert
<file_sep> 'use strict'
require('dotenv-safe').load();
var express = require('express')
var app = express()
require('./helper')
var service = require('./bus.service')
var requestService = require('./bus.request.service')
var parseService = require('./bus.parse.service')
var bodyParser = require('body-parser')
var errorHandler = require('express-errorhandler')
var cors = require('cors')
app.use(bodyParser.json())
app.use(errorHandler())
app.use(cors())
app.post('/lines', function(req, res) {
log.debug('REQ: ', req.body)
// if (req.body.length > 0) {
var hashcodes = req.body
service
.checkHashCodes(hashcodes)
.then(function(docs) {
res.json(docs)
})
.catch(function(err) {
res
.status(500)
.json(err)
})
// } else {
// db.lines.find({}, function(e, docs) {
// if (e) {
// res
// .status(500)
// .json(e)
// } else {
//
// res.json(docs);
// }
// })
// }
})
app.get('/line/:line/station/:station/direction/:direction', function(req, res){
var parameters = {
line: req.params.line,
station: req.params.station,
direction: req.params.direction
}
if(requestService.checkParameters(parameters)){
var urlToCall = requestService.buildRequest(parameters)
parseService.sendRequest(urlToCall, function(err, previsions){
if(err){
res.status(500)
.json(err)
}else{
res.json(previsions)
}
})
}
})
var server = app.listen(3000, function() {
var port = server.address().port
log.debug('Example app listening at port %s', port)
})
module.exports = server
<file_sep>DB_USER_NAME=
DB_PASSWORD=
DB_URL=
DB_NAME=
LOG_LEVEL=
URL_DAY_BUS=
<file_sep> 'use strict'
var bunyan = require('bunyan')
var log = bunyan.createLogger({
src: true,
name: 'bus-stop-service',
level: process.env.LOG_LEVEL
})
require('./helpers/chai')
var sinon = require('sinon')
var rewire = require('rewire')
var service = rewire('../lib/bus.request.service')
describe('Service - Request building process', function() {
var mock, find
beforeEach(function() {})
afterEach(function() {})
describe('Check received parameters', function() {
it('Parameters can not be empty', function() {
expect(service.checkParameters()).to.be.false
expect(service.checkParameters({})).to.be.false
})
it('Parameters must be a well formed object', function() {
expect(service.checkParameters({
station: '1'
})).to.be.false
expect(service.checkParameters({
line: '',
station: null,
direction: null
})).to.be.false
expect(service.checkParameters({
line: '',
station: '',
direction: ''
})).to.be.false
expect(service.checkParameters({
line: 'a',
station: 'b',
direction: 'c'
})).to.be.true
})
})
describe('Build request', function() {
it('Generate correct url', function() {
expect(service.buildRequest({
line: 'B120',
station: '120_134_135',
direction: 'R'
})).to.equal(`${process.env.URL_DAY_BUS}B120/120_134_135/R`)
})
})
})
<file_sep> 'use strict'
require('dotenv-safe').load();
require('./helper')
var dbURL = process.env.DB_URL
// var mongojs = require('mongojs')
// var db = mongojs(dbURL, ['lines'])
var Q = require('q')
var db, lines
const MongoClient = require('mongodb').MongoClient
MongoClient.connect(dbURL, (err, database) => {
if (err) return console.log(err)
db = database
lines = db.collection('lines')
})
exports.checkHashCodes = function(hashcodes) {
if (!hashcodes) {
hashcodes = {}
}
return Q.Promise(function(resolve, reject, notify) {
log.warn('hashcodes', hashcodes)
var linesToReturn = []
try {
lines.find({}).toArray(function(e, docs) {
if (e) {
log.error('err', e)
reject(e)
} else {
log.debug(docs)
docs.forEach(function(doc) {
var receivedCode = hashcodes[doc._id]
log.info('received code', receivedCode)
log.info('doc code', doc.code)
if (receivedCode) {
if (receivedCode !== doc.code) {
linesToReturn.push(doc)
}
} else {
linesToReturn.push(doc)
}
})
resolve(linesToReturn)
}
})
} catch (err) {
log.error(err)
reject(err)
}
})
}
<file_sep># bus-stop-service
[](https://semaphoreci.com/landry/bus-stop-service)
Service powering bus-stop mobile app.
## Contributing
1. Fork it ( https://github.com/[my-github-username]/bus-stop-service/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request
## Instructions
By piping to bunyan, you will obtain nice formatted logs.
<file_sep>'use strict'
var bunyan = require('bunyan')
global.log = bunyan.createLogger({
src: true,
name: 'bus-stop-service',
level: process.env.LOG_LEVEL
})
<file_sep> 'use strict'
require('dotenv-safe').load();
var cheerio = require('cheerio')
var request = require('request')
exports.sendRequest = function(req, callback) {
request.get(req, function(error, response, body) {
//TODO: return name of direction
if (error) {
callback(error)
} else {
var $ = cheerio.load(body)
var next1Name = $('#prochains_passages > fieldset > table > tbody > tr:nth-child(1) > td:nth-child(1)')
var next1Time = $('#prochains_passages > fieldset > table > tbody > tr:nth-child(1) > td:nth-child(2)')
var next2Name = $('#prochains_passages > fieldset > table > tbody > tr.even > td:nth-child(1)')
var next2Time = $('#prochains_passages > fieldset > table > tbody > tr.even > td:nth-child(2)')
var direction = $('#prochains_passages > fieldset > span')
var previsions = {
direction: direction.text(),
previsions: [{
station: next1Name.text(),
time: next1Time.text()
}, {
station: next2Name.text(),
time: next2Time.text()
}]
}
callback(null, previsions)
}
})
}
<file_sep> 'use strict'
var bunyan = require('bunyan')
var log = bunyan.createLogger({
src: true,
name: 'bus-stop-service',
level: process.env.LOG_LEVEL
})
require('./helpers/chai')
var sinon = require('sinon')
var rewire = require('rewire')
var service = rewire('../lib/bus.service')
describe('Service - Update process', function() {
var mock, find
beforeEach(function() {
mock = {
lines: {
find: function() {
return ([])
}
}
}
find = sinon.stub(mock.lines, 'find')
find.yields(null, [{
'_id': 'b1',
code: '1234'
}, {
'_id': 'b2',
code: '5678'
}])
service.__set__('db', mock)
})
afterEach(function() {
find.restore()
})
describe('Check hashcode', function() {
it('When hashcode differs, server returns the relevant lines', function() {
return expect(service.checkHashCodes({
'b1': '1234',
'b2': '2222'
})).to.eventually.shallowDeepEqual([{
'_id': 'b2',
code: '5678'
}])
})
it('When nothing differs, server returns empty array', function() {
return expect(service.checkHashCodes({
'b1': '1234',
'b2': '5678'
})).to.eventually.shallowDeepEqual([])
})
it('When parameter is en empty object, server returns all lines', function() {
return expect(service.checkHashCodes({})).to.eventually.shallowDeepEqual([{
'_id': 'b1',
code: '1234'
}, {
'_id': 'b2',
code: '5678'
}])
})
it('When parameter is null, server returns all lines', function() {
return expect(service.checkHashCodes(null)).to.eventually.shallowDeepEqual([{
'_id': 'b1',
code: '1234'
}, {
'_id': 'b2',
code: '5678'
}])
})
})
})
<file_sep> 'use strict'
require('dotenv-safe').load();
require('./helper')
var _ = require('lodash')
exports.checkParameters = function(parameters) {
if (!parameters || _.isEmpty(parameters)) {
return false
}
if (parameters.line && parameters.station && parameters.direction) {
return true
}
return false
}
exports.buildRequest = function(parameters) {
return `${process.env.URL_DAY_BUS}${parameters.line}/${parameters.station}/${parameters.direction}`
}
|
05e1ac00feb4917ec2a60cb27ca5ab2e79d665fd
|
[
"JavaScript",
"Markdown",
"Shell"
] | 10 |
JavaScript
|
landrysoules/bus-stop-service
|
0ef6c08cad78ed34ba4eb34da4278916b723a2fa
|
08ac37972539ef99316f2b989b048efcae0a0be3
|
refs/heads/master
|
<repo_name>yzhang1-chwy/test_git<file_sep>/hello_git_test.py
print("hello world")
for i in range(10):
print(i)
i = 0
j = 1
print(i,j)
|
692f7e6c58b078db52e5beb8e9a01417a6f9d8bd
|
[
"Python"
] | 1 |
Python
|
yzhang1-chwy/test_git
|
cf77947765ede3b3c1d59a4da8bb4731ff5002f7
|
a1b1e06ff9b0f7d355ebcdbafcf5620fb0855894
|
refs/heads/master
|
<file_sep>#include <iostream>
#include <stdio.h>
class weather_msg
{
public:
int message_code;
enum query_type{
GET_BY_CITY_ID=1,
GET_BY_LON_LAT,
GET_BY_CITY_NAME,
GET_BY_ZIP_CODE
};
int city_id;
float lon;
float lat;
std::string city_name;
char zip_code[10];
int getCurrentTemp(int city_id, std::string *output_buf);
int getCurrentTemp(float lon, float lat, std::string *output_buf);
int getCurrentTemp(std::string city_name, std::string *output_buf);
int getCurrentTemp(char zip_code[], std::string *output_buf);
}weather_msg_t;
<file_sep>#include <iostream>
#include <cstring>
#include <unistd.h>
#include <curl/curl.h>
#include <json/value.h>
#include <fstream>
#include <json/reader.h>
#define URL_STATIC "api.openweathermap.org/data/2.5/weather?"
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
std::string curl_function(std::string query)
{
CURL *curl;
CURLcode res;
std::string readBuffer;
std::string appid;
std::string url = URL_STATIC;
appid.assign(query.c_str());
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_ANY);
curl_easy_setopt(curl, CURLOPT_AUTOREFERER , 1);
url.append(appid);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_USERAGENT, "TEST");
//curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
std::cout << url.c_str() << "\n\n\n" << readBuffer << std::endl;
}
return readBuffer;
}
char * json_curl_main(std::string query)
{
std::string readBuffer, temp_buf;
Json::Reader reader;
Json::Value val_field;
float temp;
std::string cityname;
int rc = 0;
readBuffer = curl_function(query);
rc = reader.parse(readBuffer, val_field);
temp = val_field["main"]["temp"].asFloat();
cityname = val_field["name"].asString();
char *output_buf = new char[50];
memset((void *)output_buf, '\0', 50);
if (temp == 0.0) {
sprintf(output_buf,
"Error: Data for requested input - NOT FOUND\n");
} else {
sprintf(output_buf, "%s - %f", cityname.c_str(), temp);
}
std::cout <<"Server: Send output**\n" << output_buf << std::endl;
return output_buf;
}
<file_sep>#include <iostream>
#include <string>
#include <fstream>
#include <common.hpp>
#include <unistd.h>
using namespace std;
#define FILENAME "appid.txt"
char *json_curl_main(std::string query);
class server_class {
std::string appid;
public:
void getAppId(std::string *appid){
std::ifstream fd;
fd.open(FILENAME, std::fstream::in);
if (!fd) {
std::cout << "Error reading appid file\n";
appid->assign(" ");
return;
}
fd.seekg(0, fd.end);
int len = fd.tellg();
fd.seekg(0, fd.beg);
char *app = new char[len];
memset(app, '\0', len);
fd.read(app, len-1);
fd.close();
appid->assign(app);
delete[] app;
//appid->assign("9ed0909d64301bdbfd30f7a8d1b7df88");
return;
}
}server_class_t;
int weather_msg::getCurrentTemp(int city_id, std::string *output_buf)
{
std::cout<< "Server: get by city ID\n";
server_class server_app;
std::string appid, query_url;
char buf[100];
memset(buf, '\0', 100);
char *temp_out;
server_app.getAppId(&appid);
sprintf(buf, "id=%d&&appid=%s", \
city_id,appid.c_str());
query_url.assign(buf);
temp_out = json_curl_main(query_url);
output_buf->assign(temp_out);
delete[] temp_out;
}
int weather_msg::getCurrentTemp(float lon, float lat,
std::string *output_buf)
{
std::cout<< "Server: get by LON LAT\n";
server_class server_app;
std::string appid, query_url;
char buf[100];
memset(buf, '\0', 100);
char *temp_out;
server_app.getAppId(&appid);
sprintf(buf, "lon=%f&lat=%f&&appid=%s", \
lon, lat, appid.c_str());
query_url.assign(buf);
temp_out = json_curl_main(query_url);
output_buf->assign(temp_out);
delete[] temp_out;
}
int weather_msg::getCurrentTemp(std::string city_name,
std::string *output_buf)
{
std::cout<< "Server: get by city name\n";
server_class server_app;
std::string appid, query_url;
char buf[100];
memset(buf, '\0', 100);
char *temp_out;
server_app.getAppId(&appid);
sprintf(buf, "q=%s&&appid=%s", \
city_name.c_str(),appid.c_str());
query_url.assign(buf);
temp_out = json_curl_main(query_url);
output_buf->assign(temp_out);
delete[] temp_out;
}
int weather_msg::getCurrentTemp(char zip_code[],
std::string *output_buf)
{
std::cout<< "Server: get by ZIP CODE\n";
server_class server_app;
std::string appid, query_url;
char buf[100];
memset(buf, '\0', 100);
char *temp_out;
server_app.getAppId(&appid);
sprintf(buf, "zip=%s&&appid=%s", \
zip_code,appid.c_str());
query_url.assign(buf);
std::cout<< "\nServer " <<query_url.c_str() << std::endl;
temp_out = json_curl_main(query_url);
output_buf->assign(temp_out);
delete[] temp_out;
}
<file_sep>#include <zmq.hpp>
#include <string.h>
#include <unistd.h>
#include "iostream"
#include "pthread.h"
#include "server_hdr.hpp"
using namespace std;
#define NUM_THREADS 5
void *server_fn (void *socket);
int main () {
int i =0, rc;
pthread_t thread[NUM_THREADS];
char port[25];
void *context = zmq_init(1);
for (i=0; i< NUM_THREADS; i++)
{
// Prepare our context and socket
void *socket = (void *)zmq_socket (context, ZMQ_REP);
assert(socket);
sprintf(port, "tcp://*:555%d", i);
cout << "Server: main..Creating thread " << i \
<< " port " << port << std::endl;
rc = zmq_bind (socket, port);
assert(rc==0);
rc = pthread_create(&thread[i], NULL, server_fn, (void *)socket);
if (rc)
{
cout << "Error creating thread\n";
exit (-1);
}
sleep(5); // Added for timing
}
for (i=0; i< NUM_THREADS; i++)
{
pthread_join(thread[i],NULL);
}
}
void *server_fn (void *threadid)
{
int len = sizeof(weather_msg_t);
while (1) {
void *socket = (void *)threadid;
zmq_msg_t request;
weather_msg wmsg;
char cname[50], zcode[10];
char w_msg[100]; //TODO
memset(w_msg, '\0', 100);
std::string output_buf;
char *output;
wmsg.message_code = 0;
// Wait for next request from client
int rc = zmq_recv (socket, &w_msg, len, 0);
if (rc > 0) {
sscanf((char *)w_msg, "%d %d %f %f %s %s\n",
&wmsg.message_code,
&wmsg.city_id, &wmsg.lon, &wmsg.lat,
cname, zcode);
// Either cname or zcode is empty
std::cout << "server recieved Message code " << wmsg.message_code
<< std::endl;
switch(wmsg.message_code) {
case wmsg.GET_BY_CITY_ID:
wmsg.getCurrentTemp(wmsg.city_id, &output_buf);
break;
case wmsg.GET_BY_LON_LAT:
wmsg.getCurrentTemp(wmsg.lon, wmsg.lat, &output_buf);
break;
case wmsg.GET_BY_CITY_NAME:
wmsg.city_name.assign(cname);
wmsg.getCurrentTemp(wmsg.city_name, &output_buf);
break;
case wmsg.GET_BY_ZIP_CODE:
wmsg.getCurrentTemp(cname, &output_buf);
break;
}
}
sleep(1);
char send_buf[100];
memset(send_buf, '\0', 100);
strcpy(send_buf, output_buf.c_str());
zmq_send (socket, send_buf, strlen(send_buf), 0);
std::cout << "server: output: " << send_buf << std::endl;
}
std::cout << "server: RETURN;\n";
return 0;
}
<file_sep>#include <zmq.hpp>
#include <string>
#include <iostream>
#include <cstdlib>
#include "common.hpp"
#define INITIAL_SETTING wmsg.city_id = 0; \
wmsg.lon = 0.0; wmsg.lat = 0.0; \
wmsg.city_name.assign(" "); \
memset(&wmsg.zip_code, '\0', 5)
#define CHECK_ARGC(X) if (argc != X) \
{ std::cout << "Usage<>\n" \
"./client 1 <cityid>\n" \
" 2 <long> <lat>\n" \
" 3 <city name>\n" \
" 4 <zip code>\n"; return -1;}
/*
* Returns the City name, temperature and timestamp as output
* argv[1] - enum message
* ./client.out 1 <cityid>
* 2 <long> <lat>
* 3 <city name>
* 4 <zip code>
*
*/
int main (int argc, char *argv[])
{
// Prepare our context and socket
void *context = zmq_init(1);
int rc = 0, port_num;
char port[25];
std::cout << "Client: main.. " ;
void *socket = (void *)zmq_socket (context, ZMQ_REQ);
assert(socket);
weather_msg wmsg;
int request_size = sizeof(weather_msg_t);
//zmq::message_t request(request_size);
char w_msg[100]; //TODO
memset(&wmsg, '\0', 100);
port_num = 5550 + ((rand() % 5 ));
sprintf(port, "tcp://localhost:%d", port_num);
std::cout << "Connecting to server…" << port_num << std::endl;
rc = zmq_connect (socket, port);
assert(rc==0);
wmsg.message_code = (argc >= 2) ? atoi(argv[1]): 1;
INITIAL_SETTING;
switch(wmsg.message_code) {
case wmsg.GET_BY_CITY_ID:
CHECK_ARGC(3);
wmsg.city_id = atoi(argv[2]);
break;
case wmsg.GET_BY_LON_LAT:
CHECK_ARGC(4);
wmsg.lon = atof(argv[2]);
wmsg.lat = atof(argv[3]);
break;
case wmsg.GET_BY_CITY_NAME:
CHECK_ARGC(3);
wmsg.city_name.assign(argv[2]);
break;
case wmsg.GET_BY_ZIP_CODE:
CHECK_ARGC(3);
memcpy(wmsg.zip_code, argv[2], 6);
break;
}
snprintf(w_msg, request_size, "%d %d %f %f %s %s\n",
wmsg.message_code,
wmsg.city_id, wmsg.lon, wmsg.lat, wmsg.city_name.c_str(),
wmsg.zip_code);
std::cout << "Client: Sending Message " << \
wmsg.message_code << "\n" << \
wmsg.city_name.c_str() << "\n" << \
wmsg.zip_code << "…" << std::endl;
rc = zmq_send (socket, &w_msg, request_size, 0);
char reply[100]; //TODO - based on weather_msg_t
memset(reply, '\0', 100);
rc = zmq_recv (socket, reply, 100, 0);
std::cout << "Client: Received Temp details:\n\n " \
<< reply << std::endl;
return 0;
}
<file_sep>CC = g++
CFLAGS = -I/usr/include -I. -I/usr/include/jsoncpp -I/root/curl/include
LDFLAGS1 = -lzmq
LDFLAGS2 = -lpthread -lcurl -ljsoncpp
all: server client
client: client_zmq.o
$(CC) -o $@ $^ $(LDFLAGS1)
client_zmq.o: client_zmq.cpp
$(CC) -c $(CFLAGS) $<
server: curl_detail.o server_zmq.o
$(CC) -o $@ $^ $(LDFLAGS1) $(LDFLAGS2)
server_zmq.o: server_zmq.cpp
$(CC) -c $(CFLAGS) $<
curl_detail.o: curl_detail.cpp
$(CC) -c $(CFLAGS) $<
.PHONY: clean
clean:
rm *.o
rm server
rm client
|
93c764fb0c664e7aca953d12ff88c8ea23401f6b
|
[
"Makefile",
"C++"
] | 6 |
C++
|
ambikaican/curl_zmq_exercise
|
7f958f13ec1a058a34735d34d32c4b2b65029ac2
|
ca3c829a5e85e4bac289934fd90ec7789c156384
|
refs/heads/master
|
<repo_name>DaveSpeak/Week-7-Rock-Paper-Scissors<file_sep>/assets/javascript/hw.js
var config = {
apiKey: "<KEY>",
authDomain: "daves-first-firebase.firebaseapp.com",
databaseURL: "https://daves-first-firebase.firebaseio.com",
storageBucket: "daves-first-firebase.appspot.com",
};
firebase.initializeApp(config);
// Create a variable to reference the database.
var database = firebase.database();
var playersRef = database.ref("/players");
var turnRef = database.ref('/turn');
var messageRef = database.ref('/message');
var converseRef = database.ref('/smack');
var playersConnected = database.ref(".info/connected");
var someone="";
var thisInstance=1;
var clicked=false;
var players = [
{
choice:"",
losses:0,
name:"",
wins:0
},
{
choice:"",
losses:0,
name:"",
wins:0
}
];
var gameState="choosePlayer";
var turn=1;
var outcome="";
// When the client's connection state changes...
playersConnected.on('value', function(snap){
turnRef.set(turn);
players[0].choice="";
players[1].choice="";
clicked=false;
var location=(thisInstance).toString();
playersRef.child(location).onDisconnect().remove();
// playersConnected.onDisconnect().remove();
return false;
})
playersRef.on('value',function(snapshot){
var temp=snapshot.val();
for (var i=0;i<players.length;i++){
// console.log(snapshot.child(i.toString()));
if (snapshot.child(i.toString()).exists()){
players[i].choice=temp[i].choice;
players[i].losses=temp[i].losses;
players[i].name=temp[i].name;
players[i].wins=temp[i].wins;
}else {
clearPlayers(i);
}
}
playersRef.set(players);
playerDisp();
if (players[1].name!="" && players[0].name!=""){
gameState='play'
gamePlay();
}
// var anotherloc=(thisInstance).toString();
// console.log(thisInstance);
// playersRef.child(anotherloc).onDisconnect().remove();
return false;
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
messageRef.on('value', function(snapshot){
outcome=snapshot.val();
if (outcome!=null){
$('#message').html(outcome);
}
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
turnRef.on('value',function(snap){
turn=snap.val();
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
$('#reset').on('click', function(){
database.ref().remove();
location.reload();
});
$('#addPlayer').on('click',function(){
clicked=true;
if (players[0].name ===""){
players[0].name=$('#name').val().trim();
}else {
players[1].name=$('#name').val().trim();
thisInstance=2;
playerDisp();
gameState="play";
}
playersRef.set(players);
return false;
});
$('#converse').on('click', function(){
var input=$('#smack').val().trim();
var inputStuff=$('<p>').html($('#smack').val().trim()).append('<br>');
converseRef.push(input);
$('#smackbox').append(inputStuff);
});
converseRef.on('value', function(snap){
var input=snap.val();
console.log(inputStuff);
var inputStuff=$('<p>').html($('#smack').val().trim()).append('<br>');
$('#smackbox').append(inputStuff);
});
function playerDisp(){
for (var i=0;i<players.length;i++){
if (players[i].name !=""){
$('#player'+(i+1)).empty();
var playerInfo=$('<h3>').html(players[i].name).append('<br>','<h4>'+'Wins: '+players[i].wins+
' Losses: '+players[i].losses);
$('#player'+(i+1)).append(playerInfo);
if (players[i].choice!="" && turn!=thisInstance){
$('#player'+(i+1)).append('<h1>'+players[i].choice);
}
if (clicked && i==(thisInstance-1)){
$('#nameInput').empty();
var playerHead=$('<h4>').html('Hi '+players[i].name+'! You are Player '+(i+1));
if (players[1].name=="" && thisInstance==1){
playerHead.append('<br>','<h4>'+'Waiting for another player to join.');
}
$('#nameInput').append(playerHead);
}
}else {
$('#player'+(i+1)).empty();
$('#player'+(i+1)).append($('<h3>').html('Waiting for Player '+(i+1)));
}
}
return false;
}
function gamePlay(){
turnRef.set(turn);
var oppturn=0;
$('#player'+turn).css('border-color','yellow');
if (turn==1){oppturn=2}else{oppturn=1};
$('#player'+oppturn).css('border-color','black');
if (thisInstance==turn){
setChoices();
}else {
}
$('.choiceButton').on('click',function(){
var playerChoice=$(this).attr('value');
var result="";
messageRef.set("");
if (players[0].choice==""){
players[0].choice=playerChoice;
setPlayer(2);
playersRef.set(players);
}else if(players[1].choice==""){
players[1].choice=playerChoice;
gameState="compare";
if (players[0].choice =='Rock'){
if (players[1].choice =='Paper'){
result=players[1].name+' Wins!!';
players[1].wins++;
players[0].losses++;
}else if(players[1].choice == 'Scissors'){
result=players[0].name+' Wins!!';
players[0].wins++;
players[1].losses++;
}else {result='Tie!!'}
}else if (players[0].choice=='Paper'){
if (players[1].choice =='Scissors'){
result=players[1].name+' Wins!!';
players[1].wins++;
players[0].losses++;
}else if(players[1].choice=='Rock'){
result=players[0].name+' Wins!!';
players[0].wins++;
players[1].losses++;
}else {
result='Tie!!';
}
}else {
if (players[1].choice=='Rock'){
result=players[1].name+' Wins!!';
players[1].wins++;
players[0].losses++;
}else if(players[1].choice=='Paper'){
result=players[0].name+' Wins!!';
players[0].wins++;
players[1].losses++;
}else {
result='Tie!!';
}
}
outcome='<h1>'+result+'</h1';
messageRef.set(outcome);
playersRef.set(players);
setPlayer(1);
playerDisp();
setTimeout(reset,1500);
}
});
return false;
}
function setPlayer(playersturn){
turn=playersturn;
turnRef.set(turn);
// gamePlay();
return false;
}
function setChoices(){
console.log(thisInstance);
var insertRPS=$('<div>').attr('id','rps');
insertRPS.append($('<button>').attr({'class':'choiceButton','value':'Rock'}).append('<h3>'+'Rock'));
insertRPS.append($('<button>').attr({'class':'choiceButton','value':'Paper'}).append('<h3>'+'Paper'));
insertRPS.append($('<button>').attr({'class':'choiceButton','value':'Scissors'}).append('<h3>'+'Scissors'));
$('#player'+turn).append(insertRPS);
$('#nameInput').empty();
var playerHead=$('<h4>').html('Hi '+players[thisInstance-1].name+'! You are Player '+(thisInstance));
playerHead.append($('<h4>').html('It\'s your turn.'));
$('#nameInput').append(playerHead);
return false;
}
function reset(){
players[0].choice="";
players[1].choice="";
setPlayer(1);
playersRef.set(players);
gameState='play';
gamePlay();
return false;
}
function clearPlayers(i){
players[i].choice="";
players[i].losses=0;
players[i].name="";
players[i].wins=0;
return false;
}
|
a3297dffce20cec82ae2123d1c218d29e613feb0
|
[
"JavaScript"
] | 1 |
JavaScript
|
DaveSpeak/Week-7-Rock-Paper-Scissors
|
eb1fad12d4a41942c516da5ba1d7a466d7eeb045
|
bbc1649f2e0234cfde555a26c08eac67fce97368
|
refs/heads/master
|
<repo_name>filipdomachowski/maxterm<file_sep>/controllers/api/power-consumption.js
var RoomPowerConsumption = require('../../models/controlPanel/room-power-consumption')
var router = require('express').Router() //obiekt router używany jako warstwa pośrednicząca aplikacji
// var panel = express()
// panel.use(bodyParser.json())
router.get('/', function(req, res, next){
RoomPowerConsumption.find(function(err, roomPowerConsumption){
if(err) {return next(err)}
res.status(201).json(roomPowerConsumption)
})
})
router.post('/', function(req, res, next){
var body = req.body
var roomPowerConsumption = new RoomPowerConsumption({
roomId: body.roomId,
consumptionList: body.consumptionList
})
roomPowerConsumption.save(function (err, roomPowerConsumption){
if(err) {return next(err)}
res.status(201).json(roomPowerConsumption)
})
})
router.patch('/', function(req, res){
RoomPowerConsumption.bulkWrite(req.body.map(function(roomPowerConsumption){
return {
updateOne:{
filter:{
_id : roomPowerConsumption._id
},
update:{
$set:{
consumptionList: roomPowerConsumption.consumptionList
}
},
upsert: true
}
}})
).then(function(response){
res.send(response)
})
})
router.delete('/:id', function(req, res){
RoomPowerConsumption.findByIdAndRemove({_id: req.params.id}).then(function(roomPowerConsumption){
res.send(roomPowerConsumption)
})
})
module.exports = router<file_sep>/models/fitterPanel/sensors.js
var database = require('../../db')
var sensorObj = database.Schema({
hardwareIdLow : Number,
hardwareIdHigh : Number,
visibleId: String
})
module.exports = database.model('Sensor', sensorObj)
<file_sep>/controllers/api/drivers.js
var Driver = require('../../models/fitterPanel/drivers')
var router = require('express').Router() //obiekt router używany jako warstwa pośrednicząca aplikacji
// var panel = express()
// panel.use(bodyParser.json())
router.get('/', function(req, res, next){
Driver.find(function(err, drivers){
if(err) {return next(err)}
res.status(201).json(drivers)
})
})
//DO WYWALENIA CHYBA
router.post('/', function(req, res, next){
var body = req.body
var driver = new Driver({
matts: body.matts,
address: body.address,
busId: body.busId,
sensorsList: body.sensorsList
})
driver.save(function (err, driver){
if(err) {return next(err)}
res.status(201).json(driver)
})
})
router.patch('/', function(req, res){
Driver.bulkWrite(req.body.map(function(driver){
return {
updateOne:{
filter:{
_id : driver._id
},
update:{
$set:{
matts: driver.matts,
busId: driver.busId,
address: driver.address
}
},
upsert: true
}
}})
).then(function(response){
res.send(response)
})
})
module.exports = router<file_sep>/controllers/layouts/modals/login-modal.js
var loginModal = function(){
return {
templateUrl: '/login-modal.html',
backdrop: 'static',
windowClass: 'responsive-size',
controller:['$scope', '$uibModalInstance', function ($scope, $uibModalInstance) {
$scope.message = null
$scope.yes = function(){
if($scope.message === "admin"){
$uibModalInstance.close(true);
}
}
}]
}
}<file_sep>/controllers/api/_week-plans.js
// var Plan = require('../../models/fitterPanel/week-plans')
// var router = require('express').Router() //obiekt router używany jako warstwa pośrednicząca aplikacji
// // var panel = express()
// // panel.use(bodyParser.json())
// router.get('/', function(req, res, next){
// Plan.find(function(err, plans){
// if(err) {return next(err)}
// res.status(201).json(plans)
// })
// })
// router.post('/', function(req, res, next){
// var body = req.body
// var plan = new Plan({
// _id: body._id,
// planName: body.planName,
// days: body.days
// })
// plan.save(function (err, plan){
// if(err) {return next(err)}
// res.status(201).json(plan)
// })
// })
// router.patch('/', function(req, res){
// var body = req.body
// console.log(body)
// Plan.findOneAndUpdate({_id: body._id},
// {
// $set:{
// planName: body.planName,
// days: body.days
// }
// }, {new: true}
// ).then(function(plan){
// res.send(plan)
// })
// })
// module.exports = router<file_sep>/models/controlPanel/room-power-consumption.js
var database = require('../../db')
var powerConsumptionUnitObj = require('../controlPanel/power-consumption-unit')
var roomPowerConsumptionObj = database.Schema({
roomId: String,
consumptionList: [powerConsumptionUnitObj.schema]
})
module.exports = database.model('roomPowerConsumption', roomPowerConsumptionObj)<file_sep>/controllers/layouts/modals/statistics-modal.js
var statisticsModal = function(roomObj, roomConsumptionObj){
return {
templateUrl: '/statistics-modal.html',
backdrop: 'static',
windowClass: 'max-size',
controller:['$scope', '$uibModalInstance', '$http', function ($scope, $uibModalInstance, $http) {
console.log(roomObj, roomConsumptionObj)
$scope.roomConsumptionObj = roomConsumptionObj
$scope.roomObj = roomObj
$scope.period = "currentDay"
$scope.sum = 0
$scope.labels = [];
$scope.series = [];
$scope.data = [];
$scope.datasetOverride = {
backgroundColor: "#87b728",
borderColor: "#d2f299",
};
$scope.options = {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'kWh'
}
}],
xAxes: [{
ticks: {
autoSkip: false,
maxRotation: 75,
minRotation: 45
}
}]
}
}
//ZAKRESY
var now = function(){
return moment().startOf('hour')
}
var currentDay = function(){
return {
from: moment().startOf('day'),
to: now()
}
}
var previousDay = function(){
return {
from: moment().startOf('day').subtract(1, 'day'),
to: moment().startOf('day')
}
}
var currentWeek = function(){
return {
from: now().startOf('isoweek'),
to: now()
}
}
var previousWeek = function(){
return {
from: moment().startOf('isoweek').subtract(7,'day'),
to: moment().startOf('isoweek')
}
}
var currentMonth = function(){
return{
from: now().startOf('month'),
to: now()
}
}
var wholeMonth = function(){
return{
from: now().startOf('month'),
to: moment().endOf('month')
}
}
//=============
$scope.convertToTimestamp = function(date){
return Number(moment(date))
}
$scope.getCurrentDayConsumption = function(){
var consumptionList = []
$scope.data = []
$scope.labels = []
$scope.sum = 0;
$scope.roomConsumptionObj.consumptionList.forEach(function(consumptionObj, index){
if( moment(consumptionObj.date) >= currentDay().from &&
moment(consumptionObj.date) < currentDay().to ){
consumptionList.push(consumptionObj)
}
})
$scope.labels = [ '00:00-01:00', '01:00-02:00', '02:00-03:00', '03:00-04:00', '04:00-05:00', '05:00-06:00', '06:00-07:00', '07:00-08:00',
'08:00-09:00', '09:00-10:00', '10:00-11:00', '11:00-12:00', '12:00-13:00', '13:00-14:00', '14:00-15:00', '15:00-16:00',
'16:00-17:00', '17:00-18:00', '18:00-19:00', '19:00-20:00', '20:00-21:00', '21:00-22:00', '22:00-23:00', '23:00-00:00']
consumptionList.reduce(function(prev, consumptionObj, index){
if(prev.date !== undefined && moment(prev.date).startOf('hour').format() === moment(consumptionObj.date).startOf('hour').format()){
$scope.data[$scope.data.length - 1] += Math.round(consumptionObj.consumption*10)/10
prev = consumptionObj
}else{
$scope.data.push(consumptionObj.consumption)
prev = consumptionObj
}
return prev
}, []);
$scope.data.forEach(function(val){
$scope.sum += val
})
$scope.sum = Math.round($scope.sum * 10) / 10
}
$scope.getPreviousDayConsumption = function(){
var consumptionList = []
$scope.data = []
$scope.labels = []
$scope.sum =0
$scope.roomConsumptionObj.consumptionList.forEach(function(consumptionObj){
if( moment(consumptionObj.date) >= previousDay().from &&
moment(consumptionObj.date) < previousDay().to ){
consumptionList.push(consumptionObj)
}
})
$scope.labels = [ '00:00-01:00', '01:00-02:00', '02:00-03:00', '03:00-04:00', '04:00-05:00', '05:00-06:00', '06:00-07:00', '07:00-08:00',
'08:00-09:00', '09:00-10:00', '10:00-11:00', '11:00-12:00', '12:00-13:00', '13:00-14:00', '14:00-15:00', '15:00-16:00',
'16:00-17:00', '17:00-18:00', '18:00-19:00', '19:00-20:00', '20:00-21:00', '21:00-22:00', '22:00-23:00', '23:00-24:00']
consumptionList.reduce(function(prev, consumptionObj, index){
if(prev.date !== undefined && moment(prev.date).startOf('hour').format() === moment(consumptionObj.date).startOf('hour').format()){
$scope.data[$scope.data.length - 1] += Math.round(consumptionObj.consumption*10)/10
prev = consumptionObj
}else{
$scope.data.push(consumptionObj.consumption)
prev = consumptionObj
}
return prev
}, []);
$scope.data.forEach(function(val){
$scope.sum += val
})
$scope.sum = Math.round($scope.sum * 10) / 10
}
$scope.getCurrentWeekConsumption = function(){
var consumptionList = {
M: 0,
T: 0,
W: 0,
Th: 0,
F: 0,
Sat:0,
S: 0
}
$scope.data = []
$scope.labels = []
$scope.sum =0
$scope.roomConsumptionObj.consumptionList.forEach(function(consumptionObj){
if( moment(consumptionObj.date) >= currentWeek().from &&
moment(consumptionObj.date) < currentWeek().to ){
if(moment(consumptionObj.date).day() === 1) consumptionList.M += consumptionObj.consumption
if(moment(consumptionObj.date).day() === 2) consumptionList.T += consumptionObj.consumption
if(moment(consumptionObj.date).day() === 3) consumptionList.W += consumptionObj.consumption
if(moment(consumptionObj.date).day() === 4) consumptionList.Th += consumptionObj.consumption
if(moment(consumptionObj.date).day() === 5) consumptionList.F += consumptionObj.consumption
if(moment(consumptionObj.date).day() === 6) consumptionList.Sat += consumptionObj.consumption
if(moment(consumptionObj.date).day() === 0) consumptionList.S += consumptionObj.consumption
}
})
consumptionList.M = Math.round((consumptionList.M)*10)/10
consumptionList.T = Math.round((consumptionList.T)*10)/10
consumptionList.W = Math.round((consumptionList.W)*10)/10
consumptionList.Th = Math.round((consumptionList.Th)*10)/10
consumptionList.F = Math.round((consumptionList.F)*10)/10
consumptionList.Sat = Math.round((consumptionList.Sat)*10)/10
consumptionList.S = Math.round((consumptionList.S)*10)/10
console.log(consumptionList)
$scope.labels = ['Montag ', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag']
$scope.data = [ consumptionList.M,
consumptionList.T,
consumptionList.W,
consumptionList.Th,
consumptionList.F,
consumptionList.Sat,
consumptionList.S ]
$scope.data.forEach(function(data){
$scope.sum += data
})
$scope.sum = Math.round($scope.sum * 10) / 10
}
$scope.getPreviousWeekConsumption = function(){
var consumptionList = {
M: 0,
T: 0,
W: 0,
Th: 0,
F: 0,
Sat:0,
S: 0
}
$scope.data = []
$scope.labels = []
$scope.sum = 0;
$scope.roomConsumptionObj.consumptionList.forEach(function(consumptionObj){
if( moment(consumptionObj.date) >= previousWeek().from &&
moment(consumptionObj.date) < previousWeek().to ){
if(moment(consumptionObj.date).day() === 1) consumptionList.M += consumptionObj.consumption
if(moment(consumptionObj.date).day() === 2) consumptionList.T += consumptionObj.consumption
if(moment(consumptionObj.date).day() === 3) consumptionList.W += consumptionObj.consumption
if(moment(consumptionObj.date).day() === 4) consumptionList.Th += consumptionObj.consumption
if(moment(consumptionObj.date).day() === 5) consumptionList.F += consumptionObj.consumption
if(moment(consumptionObj.date).day() === 6) consumptionList.Sat += consumptionObj.consumption
if(moment(consumptionObj.date).day() === 0) consumptionList.S += consumptionObj.consumption
}
})
consumptionList.M = Math.round((consumptionList.M)*10)/10
consumptionList.T = Math.round((consumptionList.T)*10)/10
consumptionList.W = Math.round((consumptionList.W)*10)/10
consumptionList.Th = Math.round((consumptionList.Th)*10)/10
consumptionList.F = Math.round((consumptionList.F)*10)/10
consumptionList.Sat = Math.round((consumptionList.Sat)*10)/10
consumptionList.S = Math.round((consumptionList.S)*10)/10
console.log(consumptionList)
$scope.labels = ['Montag ', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag']
$scope.data = [ consumptionList.M,
consumptionList.T,
consumptionList.W,
consumptionList.Th,
consumptionList.F,
consumptionList.Sat,
consumptionList.S ]
$scope.data.forEach(function(data){
$scope.sum += data
})
$scope.sum = Math.round($scope.sum * 10) / 10
}
$scope.getCurrentMonthConsumption = function(){
$scope.wholeList = [];
var consumptionList = []
$scope.data = []
$scope.labels = []
$scope.obj = []
$scope.sum = 0;
$scope.roomConsumptionObj.consumptionList.forEach(function(consumptionObj){
if( moment(consumptionObj.date) >= wholeMonth().from &&
moment(consumptionObj.date) <= wholeMonth().to ){
$scope.wholeList.push(consumptionObj)
var day = moment(consumptionObj.date).locale('de').format('ddd') + ' ' + moment(consumptionObj.date).locale('de').format('MM/DD')
if($scope.labels.length === 0){
$scope.labels.push(day)
$scope.data.push(consumptionObj.consumption)
}else{
if(day !== $scope.labels[$scope.labels.length-1]){
$scope.labels.push(day)
$scope.data.push(consumptionObj.consumption)
}
else{
$scope.data[$scope.data.length-1] += consumptionObj.consumption
$scope.data[$scope.data.length-1] = Math.round($scope.data[$scope.data.length-1] * 10) / 10
}
}
}
})
$scope.data.forEach(function(data){
$scope.sum += data
})
$scope.sum = Math.round($scope.sum * 10) / 10
console.log(consumptionList)
console.log($scope.labels)
console.log($scope.data)
}
$scope.getCurrentDayConsumption()
$scope.generateChart = function(period){
console.log(period)
if(period === 'currentDay') $scope.getCurrentDayConsumption()
if(period === 'previousDay') $scope.getPreviousDayConsumption()
if(period === 'currentWeek') $scope.getCurrentWeekConsumption()
if(period === 'previousWeek') $scope.getPreviousWeekConsumption()
if(period === 'currentMonth') $scope.getCurrentMonthConsumption()
}
$scope.yes = function(){
$uibModalInstance.close(true);
}
}]
}
}<file_sep>/controllers/layouts/pages/fitter-page-controller.js
panelMainController.controller('fitter-panel-page-controller', ['$scope', '$uibModal', '$http', function ($scope, $uibModal, $http) {
$uibModal.open(loginModal()).result.then(
function(){
$http({
method: 'GET',
url: '/api/fitter/rooms'
}).then(function success(response){
console.log(response)
$scope.rooms = response.data
$scope.roomObj = null
$scope.addNewRoom = function(){
$scope.rooms.push($scope.roomObj)
}
$scope.deleteRoom = function(room, roomIndex, $event){
$event.stopPropagation()
$scope.address = location.hostname
// $scope.configDataWS = new WebSocket("ws://"+$scope.address+":8765/config_updated")
$uibModal.open(confirmationModal('Diese Aktion löscht das ausgewählte Raumobjekt. Bist du sicher, dass du diese Aktion ausführst?')).result.then(
function success(result){
if(result){
if(room !== null){
// $scope.configDataWS.send("{'roomsUpdated' : [" + room._id.toString() + "]")
$http({ method: 'DELETE', url: '/api/fitter/rooms/' + room._id })
.then(function success(response){
console.log(response)
$scope.rooms.splice(roomIndex, 1)
$scope.driversList = room.drivers
$scope.driversList.forEach(function(driver){
driver.matts = [];
})
return $http({ method: 'PATCH', url: '/api/fitter/drivers', data: $scope.driversList })
})
.then(function success(response){
return $http({ method: 'GET', url: '/api/controlPanel/consumption'})
})
.then(function success(response){
var roomConsumptionObj = response.data.find(function(roomConsumptionObj){
return roomConsumptionObj.roomId === room._id
})
return $http({ method: 'DELETE', url: '/api/controlPanel/consumption/' + roomConsumptionObj._id})
})
}else{
$scope.rooms.splice(roomIndex, 1)
}
}
})
}
$scope.openRoomSettings = function(room){
$uibModal.open(driverConfigureModal(room, $scope.rooms)).result.then(
function success(result){
console.log(result)
$http({
method: 'GET',
url: '/api/fitter/rooms'
}).then(function success(response){
console.log(response)
$scope.rooms = response.data
})
}, function error(result){
console.log(result)
})
}
})
})
}]);
<file_sep>/controllers/layouts/modals/calc-modal.js
var calcModal = function(powerConsumption){
return {
templateUrl: '/calc-modal.html',
backdrop: 'static',
windowClass: 'responsive-size',
controller:['$scope', '$uibModalInstance', function ($scope, $uibModalInstance) {
$scope.powerConsumption = powerConsumption !== null && powerConsumption !== undefined ? Math.round(powerConsumption * 10) /10 : 0
$scope.powerPrice = 0;
$scope.result = 0;
$scope.calculate = function(){
$scope.result = $scope.powerConsumption * $scope.powerPrice
$scope.result = Math.round($scope.result * 100) / 100
}
$scope.yes = function(){
$uibModalInstance.close(true);
}
}]
}
}<file_sep>/controllers/layouts/pages/charts-page-controller.js
panelMainController.controller('charts-page-controller', function () {
});<file_sep>/README.md
# maxterm
Web application for diploma at the early stage of development.
Used Technolgies
1) Frontend:
AngularJS
Bootstrap 4
CSS3
HTML5
2) Backend:
NodeJS
Express
MongoDB
Mongoose
3) Other:
Gulp
Stylus
In plans:
- Simpler more up to date layout design with using flexboxes
- I would like to rewrite everything using ES6
- JWT and BCRYPT technologies for user authentication
<file_sep>/controllers/api/rooms.js
var Room = require('../../models/fitterPanel/rooms')
var router = require('express').Router() //obiekt router używany jako warstwa pośrednicząca aplikacji
// var panel = express()
// panel.use(bodyParser.json())
router.get('/', function(req, res, next){
Room.find(function(err, rooms){
if(err) {return next(err)}
res.status(201).json(rooms)
})
})
router.post('/', function(req, res, next){
var body = req.body
var room = new Room({
name: body.name,
drivers: body.drivers,
tempPlan: body.tempPlan,
powerConsumption: body.powerConsumption,
roomSensor: body.roomSensor,
targetTemp: body.targetTemp,
mode: body.mode
})
room.save(function (err, room){
if(err) {return next(err)}
res.status(201).json(room)
})
})
router.patch('/', function(req, res){
var body = req.body
console.log(body._id)
Room.findByIdAndUpdate({_id: body._id},
{
$set:{
name: body.name,
drivers: body.drivers,
tempPlan: body.tempPlan,
powerConsumption: body.powerConsumption,
roomSensor: body.roomSensor,
targetTemp: body.targetTemp,
mode: body.mode
}
}, {new: true}
).then(function(room){
res.send(room)
})
// function(err, room){
// if(err) return handleError(err)
// console.log("ROOM: ", room)
// res.send(room)
// })
})
router.delete('/:id', function(req, res){
Room.findByIdAndRemove({_id: req.params.id}).then(function(room){
res.send(room)
})
})
module.exports = router<file_sep>/controllers/layouts/modals/week-temperature-plan-modal-controller.js
var weekTempModal = function(plan){
return {
templateUrl: '/week-temperature-plan-modal.html',
backdrop: 'static',
windowClass: 'responsive-size',
controller:['$scope', '$uibModalInstance', '$http', function ($scope, $uibModalInstance, $http) {
$scope.plan = plan;
$scope.hovering = false;
$scope.no = function(){
$uibModalInstance.dismiss('anulowano');
};
$scope.yes = function(){
// $http({
// method: 'PATCH',
// url: '/api/fitter/weekPlans',
// data: $scope.plan
// }).then(function success(response){
// console.log(response)
$uibModalInstance.close($scope.plan)
// })
}
}]
}
}<file_sep>/controllers/layouts/routing/routes.js
angular.module('panel-main-controller')
.config(["$routeProvider", function ($routeProvider) {
$routeProvider
.when('/fitterPanel' ,{ templateUrl:'fitter-page.html'})
.when('/controlPanel' ,{ templateUrl:'control-panel-page.html'})
.when('/charts' ,{ templateUrl:'charts-page.html'})
.when('/login' ,{ templateUrl:'login-page.html'})
.otherwise({ redirectTo:'/controlPanel'})
}]);<file_sep>/jsony.js
var driverObj = database.Schema({
matts: [mattObj.schema],
address: String,
busId: String,
sensorsList: [sensorObj.schema]
})
var mattObj = database.Schema({
sensor: [sensorObj.schema],
driverId: String,
})
var roomObj = database.Schema({
name: String,
drivers: [driverObj.schema],
setRoomTemp:Number,
tempPlan: String,
targetTemp: Number,
//roboczo roomSensor: {objekt z idDrivera do ktorego nalezy ten czujnik, temperatura}
mode: Boolean
})
var sensorObj = database.Schema({
temp: Number,
sensorId: Number
})<file_sep>/server.js
var express = require('express')
var bodyParser = require('body-parser')
// var Sensor = require('./models/fitterPanel/post')
var panel = express()
panel.use(bodyParser.json())
panel.use('/api/fitter/sensors', require('./controllers/api/sensors'))
panel.use('/api/fitter/matts', require('./controllers/api/matts'))
panel.use('/api/fitter/drivers', require('./controllers/api/drivers'))
panel.use('/api/fitter/rooms', require('./controllers/api/rooms'))
panel.use('/api/fitter/rooms/:id', require('./controllers/api/rooms'))
panel.use('/api/controlPanel/consumption', require('./controllers/api/power-consumption'))
panel.use('/api/controlPanel/consumption/:id', require('./controllers/api/power-consumption'))
// panel.use('/api/fitter/weekPlans', require('./controllers/api/week-plans'))
panel.use('/', require('./controllers/static'))
panel.listen(80, function(){
console.log('server.js: Server is listening on port 80, maxterm')
})
<file_sep>/controllers/api/sensors.js
var Sensor = require('../../models/fitterPanel/sensors')
var router = require('express').Router() //obiekt router używany jako warstwa pośrednicząca aplikacji
// var panel = express()
// panel.use(bodyParser.json())
router.get('/', function(req, res, next){
Sensor.find(function(err, sensors){
if(err) {return next(err)}
res.status(201).json(sensors)
})
})
router.post('/', function(req, res, next){
var body = req.body
var sensor = new Sensor({
hardwareIdLow : body.hardwareIdLow,
hardwareIdHigh : body.hardwareIdHigh,
visibleId: body.visibleId
})
sensor.save(function (err, sensor){
if(err) {return next(err)}
res.status(201).json(sensor)
})
})
module.exports = router
<file_sep>/controllers/layouts/modals/current-temperature-modal-controller.js
var currentTempModal = function(currentRoom){
return {
templateUrl: '/current-temperature-modal.html',
backdrop: 'static',
controller:['$scope', '$uibModalInstance', '$http', function ($scope, $uibModalInstance, $http) {
$scope.currentRoom = currentRoom
$scope.targetTemp = currentRoom.targetTemp
console.log(currentRoom)
$scope.addTemp = function(){
$scope.targetTemp = $scope.targetTemp < 35 ? $scope.targetTemp + 0.5 : $scope.targetTemp
}
$scope.subTemp = function(){
$scope.targetTemp = $scope.targetTemp > 15 ? $scope.targetTemp - 0.5 : $scope.targetTemp
}
$scope.yes = function () {
$scope.currentRoom.targetTemp = $scope.targetTemp
$http({
method: 'PATCH',
url: '/api/fitter/rooms',
data: $scope.currentRoom
}).then(function success(response){
console.log(response)
$uibModalInstance.close(response)
})
}
$scope.no = function(){
$uibModalInstance.dismiss('anulowano');
};
}]
}
}<file_sep>/models/fitterPanel/matts.js
var database = require('../../db')
var sensorObj = require('../fitterPanel/sensors')
var mattObj = database.Schema({
sensor: sensorObj.schema,
driverId: String,
})
module.exports = database.model('Matt', mattObj)
|
5050dc7d537e92df383b1f3b6aa163b30505ad72
|
[
"JavaScript",
"Markdown"
] | 19 |
JavaScript
|
filipdomachowski/maxterm
|
b2006cd80ba38d65a27eaba08a622bff21bb14d5
|
644d8f911797d3c99f9a429453c9ba91c984e4c2
|
refs/heads/master
|
<repo_name>mhujer/zfclasses<file_sep>/Mhujer/View/Helper/Email.php
<?php
/**
* Martin Hujer's Components
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to <EMAIL> so I can send you a copy immediately.
*
* @category Mhujer
* @package Mhujer_View_Helper
* @author <NAME> <EMAIL>
*/
/**
* View Helper
*
* @category Mhujer
* @package Mhujer_View_Helper
* @author <NAME> <EMAIL>
*/
/**
* Obfuscates an e-mail address
*
*/
class Mhujer_View_Helper_Email
{
/**
* Obfuscates an e-mail address
*
* @param string $address E-mail address to obfuscate
* @param boolean $mailto Generate mailto link?
* @return string
*/
public function email($address, $mailto = false)
{
//thanks dgx for this tip
$obfuscated = str_replace('@', '@<!---->', $address);
if (!$mailto) {
return $obfuscated;
} else {
$mailtoAdress = str_replace('@', '@', $address);
$mailto = '<a href="mailto:' . $mailtoAdress . '">' . $obfuscated . '</a>';
return $mailto;
}
}
}<file_sep>/Tests/Mhujer/Filter/TransliterationTest.php
<?php
/**
* Martin Hujer's Components
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to <EMAIL> so I can send you a copy immediately.
*
* @category Mhujer
* @package Mhujer_View_Helper
* @author <NAME> <EMAIL>
*/
set_include_path(get_include_path() . PATH_SEPARATOR . 'library');
/**
* @see Mhujer_Filter_Transliteration
*/
require_once 'Mhujer/Filter/Transliteration.php';
/**
* @category Mhujer
* @package Mhujer_Filter
* @subpackage UnitTests
* @author <NAME> <EMAIL>
*/
class Zend_Filter_TransliterationTest extends PHPUnit_Framework_TestCase
{
/**
* Zend_Filter_Transliteration object
*
* @var Zend_Filter_Transliteration
*/
protected $_filter;
/**
* Creates a new Zend_Filter_Transliteration object for each test method
*
* @return void
*/
public function setUp ()
{
$this->_filter = new Mhujer_Filter_Transliteration();
}
public function testTransCzech ()
{
$this->assertEquals("escrzyaieuu", $this->_filter->filter("ěščřžýáíéůú"));
}
public function testTransHacekCarka ()
{
$this->assertEquals("", $this->_filter->filter("ˇ´"));
}
public function testTransCzechSentence ()
{
//Czech sentence used for font-testing
$czech = "Příliž žluťoučký kůň úpěl ďábelské ody!";
$converted = "Priliz zlutoucky kun upel dabelske ody!";
$this->assertEquals($converted, $this->_filter->filter($czech));
}
public function testTransGerman ()
{
$this->assertEquals('e-i-oe-ue', $this->_filter->filter("ë-ï-ö-ü"));
$this->assertEquals('E-I-Oe-Ue', $this->_filter->filter("Ë-Ï-Ö-Ü"));
$this->assertEquals('ss', $this->_filter->filter("ß"));
}
public function testTransFrench ()
{
$this->assertEquals('aeiou', $this->_filter->filter("âêîôû"));
$this->assertEquals('AEIOU', $this->_filter->filter("ÂÊÎÔÛ"));
$this->assertEquals('oe', $this->_filter->filter("œ"));
$this->assertEquals('ae', $this->_filter->filter("æ"));
$this->assertEquals('Y', $this->_filter->filter("Ÿ"));
$this->assertEquals('Cc', $this->_filter->filter("Çç"));
}
public function testTransHungarian ()
{
$this->assertEquals('aeioouu', $this->_filter->filter("áéíóőúű"));
}
public function testTransRussian ()
{
$this->assertEquals('korzina', $this->_filter->filter("kорзина"));
$this->assertEquals('studjenchjeskije rjukzaki', $this->_filter->filter("студенческие рюкзаки"));
}
public function testNotTranslitere ()
{
$this->assertEquals("'", $this->_filter->filter("'"));
$this->assertEquals("\"", $this->_filter->filter("\""));
$this->assertEquals("^", $this->_filter->filter("^"));
}
public function testTransPolish ()
{
$this->assertEquals('aoclesnzz', $this->_filter->filter('ąóćłęśńżź'));
$this->assertEquals('aeoclnszzOCLSZZ', $this->_filter->filter('ąęóćłńśżźÓĆŁŚŻŹ'));
}
public function testTransPolishSentence ()
{
$polish = 'Pchnąć w tę łódź jeża lub ośm skrzyń fig.';
$converted = 'Pchnac w te lodz jeza lub osm skrzyn fig.';
$this->assertEquals($converted, $this->_filter->filter($polish));
}
public function testTransDanish ()
{
$this->assertEquals('ae oe aa Ae Oe Aa', $this->_filter->filter('æ ø å Æ Ø Å'));
}
public function testTransDanishSentence ()
{
$danish = 'På Falster, i nærheden af Nykøbing.';
$converted = 'Paa Falster, i naerheden af Nykoebing.';
$this->assertEquals($converted, $this->_filter->filter($danish));
}
public function testTransCroatian ()
{
$this->assertEquals("cczsdCCZSD", $this->_filter->filter("čćžšđČĆŽŠĐ"));
}
public function testTransSlovak ()
{
$this->assertEquals("aAaAcCdDeE", $this->_filter->filter("áÁäÄčČďĎéÉ"));
$this->assertEquals("iIlLlLnNoOoO", $this->_filter->filter("íÍĺĹľĽňŇóÓôÔ"));
$this->assertEquals("rRsStTuUYyzZ", $this->_filter->filter("ŕŔšŠťŤúÚÝýžŽ"));
}
}
<file_sep>/README.md
# Mhujer_View_Helper_Email
Helps you to obfuscate an e-mail address
More details on https://github.com/mhujer/zfclasses/wiki/Mhujer_View_Helper_Email
# Mhujer_Filter_Sanitize & Mhujer_Filter_Transliteration
Help you to convert string to url friendly string
- See http://framework.zend.com/wiki/display/ZFPROP/Zend_Filter_Sanitize+-+Martin+Hujer
- See http://framework.zend.com/wiki/display/ZFPROP/Zend_Filter_Transliteration+-+Martin+Hujer
# Mhujer_View_Helper_FileSize(Simple)
Helper to display filesize in a friendly format
- See http://framework.zend.com/wiki/display/ZFPROP/Zend_View_Helper_FileSize+-+Martin+Hujer<file_sep>/Tests/Mhujer/View/Helper/FileSizeSimpleTest.php
<?php
/**
* Martin Hujer's Components
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to <EMAIL> so I can send you a copy immediately.
*
* @category Mhujer
* @package Mhujer_Tests
* @author <NAME> <EMAIL>
*/
/**
*
* @category Mhujer
* @package Mhujer_Tests
* @author <NAME> <EMAIL>
*/
set_include_path(get_include_path() . PATH_SEPARATOR . 'library');
require_once 'Mhujer/View/Helper/FileSizeSimple.php';
/**
* Mhujer_View_Helper_FileSizeSimple test case.
*/
class Mhujer_View_Helper_FileSizeSimpleTest extends PHPUnit_Framework_TestCase
{
/**
* @var Mhujer_View_Helper_FileSizeSimple
*/
private $_fs;
/**
* Prepares the environment before running a test.
*/
protected function setUp ()
{
parent::setUp();
$this->_fs = new Mhujer_View_Helper_FileSizeSimple();
}
/**
* Cleans up the environment after running a test.
*/
protected function tearDown ()
{
$this->_fs = null;
parent::tearDown();
}
/**
* Tests Mhujer_View_Helper_FileSize->fileSize()
*/
public function testFileSize ()
{
$equals = array(
"0 B" => 0,
"1 B" => 1,
"1 KB" => 1024,
"1 MB" => 1024*1024,
"1 GB" => 1024*1024*1024,
"1 TB" => 1024*1024*1024*1024,
"1024 TB" => 1024*1024*1024*1024*1024
);
foreach ($equals as $result => $size) {
$this->assertEquals($result, $this->_fs->fileSize($size));
}
}
/**
* Test filesize convert with specified precision
*/
public function testFileSizePrecision()
{
$this->assertEquals("976.563 KB", $this->_fs->fileSize(1000000, 3));
$this->assertEquals("976.5625 KB", $this->_fs->fileSize(1000000, 4));
$this->assertEquals("976.5625 KB", $this->_fs->fileSize(1000000, 10));
}
}
<file_sep>/Mhujer/View/Helper/FileSizeSimple.php
<?php
/**
* Martin Hujer's Components
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to <EMAIL> so I can send you a copy immediately.
*
* @category Mhujer
* @package Mhujer_View_Helper
* @author <NAME> <EMAIL>
*/
/**
* View Helper
*
* @category Mhujer
* @package Mhujer_View_Helper
* @author <NAME> <EMAIL>
*
*/
class Mhujer_View_Helper_FileSizeSimple
{
/**
* Size of one Kilobyte
*/
const SIZE_KILOBYTES = 1024;
/**
* Size of one Megabyte
*/
const SIZE_MEGABYTES = 1048576;
/**
* Size of one Gigabyte
*/
const SIZE_GIGABYTES = 1073741824;
/**
* Size of one Terabyte
*/
const SIZE_TERABYTES = 1099511627776;
/**
* Formats filesize with specified precision
*
* @param integer $fileSize Filesize in bytes
* @param integer $precision Precision
*/
public function fileSize($fileSize, $precision = 3)
{
if ($fileSize >= self::SIZE_TERABYTES) {
$newFilesize = $fileSize / self::SIZE_TERABYTES;
$sizeName = 'TB';
} else if ($fileSize >= self::SIZE_GIGABYTES) {
$newFilesize = $fileSize / self::SIZE_GIGABYTES;
$sizeName = 'GB';
} else if ($fileSize >= self::SIZE_MEGABYTES) {
$newFilesize = $fileSize / self::SIZE_MEGABYTES;
$sizeName = 'MB';
} else if ($fileSize >= self::SIZE_KILOBYTES) {
$newFilesize = $fileSize / self::SIZE_KILOBYTES;
$sizeName = 'KB';
} else {
$newFilesize = $fileSize;
$sizeName = 'B';
}
$newFilesize = round($newFilesize, $precision);
return $newFilesize . ' ' . $sizeName;
}
}
<file_sep>/Tests/Mhujer/Filter/SanitizeTest.php
<?php
/**
* Martin Hujer's Components
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to <EMAIL> so I can send you a copy immediately.
*
* @category Mhujer
* @package Mhujer_View_Helper
* @author <NAME> <EMAIL>
*/
set_include_path(get_include_path() . PATH_SEPARATOR . 'library');
/**
* @see Mhujer_Filter_Sanitize
*/
require_once 'Mhujer/Filter/Sanitize.php';
/**
* @category Mhujer
* @package Mhujer_Filter
* @subpackage UnitTests
* @author <NAME> <EMAIL>
*/
class Mhujer_Filter_SanitizeTest extends PHPUnit_Framework_TestCase
{
/**
* Mhujer_Filter_Sanitize object
*
* @var Mhujer_Filter_Sanitize
*/
protected $_f;
protected function setUp ()
{
$this->_f = new Mhujer_Filter_Sanitize();
}
public function testConstructor ()
{
$this->_f = new Mhujer_Filter_Sanitize('_', '!');
$this->assertEquals('test_word_test', $this->_f->filter('test!word!test'));
}
public function testConstructorArray ()
{
$this->_f = new Mhujer_Filter_Sanitize('_', array('!', ':'));
$this->assertEquals('test_word_test', $this->_f->filter('test!word:test'));
}
public function testSetDelimiterReplacement ()
{
$this->_f->setDelimiterReplacement('_');
$this->assertEquals('_', $this->_f->getDelimiterReplacement());
}
public function testAddWordDelimiter ()
{
$delimiters = $this->_f->getWordDelimiters();
$delimiters[] = '=';
$this->_f->addWordDelimiter('=');
$this->assertEquals($delimiters, $this->_f->getWordDelimiters());
}
public function testAddWordDelimiterArray ()
{
$delimiters = $this->_f->getWordDelimiters();
$delimiters[] = '=';
$delimiters[] = '!';
$this->_f->addWordDelimiter(array('=', '!'));
$this->assertEquals($delimiters, $this->_f->getWordDelimiters());
}
public function testAddWordDelimiterAlreadyAddedException ()
{
try {
$this->_f->addWordDelimiter('=');
$this->_f->addWordDelimiter('=');
} catch (Zend_Filter_Exception $e) {
return;
}
$this->fail('An expected exception has not been raised.');
}
public function testAddWordDelimiterEmptyException ()
{
try {
$this->_f->addWordDelimiter('');
} catch (Zend_Filter_Exception $e) {
return;
}
$this->fail('An expected exception has not been raised.');
}
public function testRemoveWordDelimiter ()
{
$this->_f->addWordDelimiter('=');
$this->assertEquals('foo-url', $this->_f->filter("foo=url"));
$this->_f->removeWordDelimiter('=');
$this->assertNotEquals('foo-url', $this->_f->filter("foo=url"));
}
public function testRemoveWordDelimiterArray ()
{
$this->_f->addWordDelimiter('=');
$this->_f->addWordDelimiter('!');
$this->assertEquals('foo-bar-baz', $this->_f->filter('foo=bar!baz'));
$this->_f->removeWordDelimiter(array('=', '!'));
$this->assertEquals('foobarbaz', $this->_f->filter('foo=bar!baz'));
}
public function testRemoveWordDelimiterEmptyException ()
{
try {
$this->_f->removeWordDelimiter('');
} catch (Zend_Filter_Exception $e) {
return;
}
$this->fail('An expected exception has not been raised.');
}
public function testTrimSpaces ()
{
$this->assertEquals('foo-url', $this->_f->filter("\t\n foo-url "));
}
public function testReplaceSpaces ()
{
$this->assertEquals('foo-url', $this->_f->filter('foo url'));
$this->_f->setDelimiterReplacement('_');
$this->assertEquals('foo_url', $this->_f->filter('foo url'));
}
public function testReplaceDoubleDelimiterWithSingleReplacement ()
{
$this->assertEquals('foo-url', $this->_f->filter('foo--url'));
$this->_f->setDelimiterReplacement('_');
$this->assertEquals('foo_url', $this->_f->filter('foo__url'));
}
public function testToLower ()
{
$this->assertEquals('escrzyaieuu', $this->_f->filter("ESCRZYAIEUU"));
}
public function testDotsReplacement ()
{
$this->assertEquals('foo-url', $this->_f->filter("foo.url"));
}
public function testSlashesReplacement ()
{
$this->assertEquals('foo-url', $this->_f->filter("foo/url"));
$this->assertEquals('foo-url', $this->_f->filter("foo\url"));
}
public function testTrimStartAndEndSpaceReplacement ()
{
$this->assertEquals('foo-url', $this->_f->filter("--foo-url--"));
$this->_f->setDelimiterReplacement('_');
$this->assertEquals('foo_url', $this->_f->filter("__foo-url__"));
}
public function testTrimSpecialChars ()
{
$this->assertEquals('foo-url', $this->_f->filter("foo-url'?&@{}\\[]\""));
}
public function testNormalizeFilename ()
{
//TODO add tests like delimiter adding/removing
$this->_f->addNotReplacedChars('.');
$this->assertEquals('mozilla-firefox-1.0.0.12.exe', $this->_f->filter("MoZIlla FiREfOx 1.0.0.12.EXE"));
$this->_f->removeNotReplacedChar('.');
$this->assertEquals('mozilla-firefox-1-0-0-12-exe', $this->_f->filter("MoZIlla FiREfOx 1.0.0.12.EXE"));
}
/**
* complete test
*/
public function testConvertStringToUrl ()
{
$this->assertEquals('foo-url', $this->_f->filter("-- F*OÓ !-úřl'?&@{ }\\[]\""));
}
public function testConvertStringToUrl2 ()
{
$this->assertEquals('arvizturo-tuekoerfurogep', $this->_f->filter("Árvíztűrő tükörfúrógép"));
}
}<file_sep>/Tests/Mhujer/View/Helper/FileSizeTest.php
<?php
/**
* @see PHPUnit_Framework_TestCase
*/
require_once 'PHPUnit/Framework/TestCase.php';
/**
* @see Mhujer_View_Helper_FileSize
*/
set_include_path(get_include_path() . PATH_SEPARATOR . 'library');
require_once 'Mhujer/View/Helper/FileSize.php';
/**
* @author <NAME> <EMAIL>
*/
class Mhujer_View_Helper_FileSizeTest extends PHPUnit_Framework_TestCase
{
/**
* @var Mhujer_View_Helper_FileSize
*/
private $_fs;
/**
* Prepares the environment before running a test.
*/
protected function setUp()
{
$this->_fs = new Mhujer_View_Helper_FileSize();
}
/**
* Cleans up the environment after running a test.
*/
protected function tearDown()
{
$this->_fs = null;
Zend_Registry::set('Zend_Locale', null);
}
protected function _setDefaultLocale()
{
$locale = new Zend_Locale('en_US');
require_once 'Zend/Registry.php';
Zend_Registry::set('Zend_Locale', $locale);
}
/**
* Tests Mhujer_View_Helper_FileSize->fileSize()
*/
public function testFileSize ()
{
$this->_setDefaultLocale();
$equals = array(
"0 B" => 0,
"1 B" => 1,
"1 kB" => 1024,
"1 MB" => 1024 * 1024,
"1 GB" => 1024 * 1024 * 1024,
"1 TB" => 1024 * 1024 * 1024 * 1024,
"1,024 TB" => 1024 * 1024 * 1024 * 1024 * 1024,
);
foreach ($equals as $result => $size) {
$this->assertEquals($result, $this->_fs->fileSize($size));
}
}
/**
* Test filesize convert with specified precision
*/
public function testFileSizePrecision()
{
$this->_setDefaultLocale();
$this->assertEquals("976.563 kB", $this->_fs->fileSize(1000000, 3));
$this->assertEquals("976.5625 kB", $this->_fs->fileSize(1000000, 4));
$this->assertEquals("1.1 MB", $this->_fs->fileSize('1153433.6', 1));
}
/**
* Test defined export type
*/
public function testDefinedType()
{
$this->_setDefaultLocale();
$this->assertEquals('1,048,576 kB', $this->_fs->fileSize(1024 * 1024 * 1024, null, null, 'KILOBYTE'));
$this->assertEquals('1,024 MB', $this->_fs->fileSize(1024 * 1024 * 1024, null, null, 'MEGABYTE'));
$this->assertEquals('1 GB', $this->_fs->fileSize(1024 * 1024 * 1024, null, null, 'GIGABYTE'));
}
/**
* Test defined export type
*/
public function testNormSi()
{
$this->_setDefaultLocale();
/** @see ZF-11488 */
$this->assertEquals('1 B', $this->_fs->fileSize(1, 5, 'si')); //
$this->assertEquals('1.00000 kB.', $this->_fs->fileSize(1000, 5, 'si'));
$this->assertEquals('1.00000 MB.', $this->_fs->fileSize(1000 * 1000, 5, 'si'));
$this->assertEquals('1.00000 GB.', $this->_fs->fileSize(1000 * 1000 * 1000, 5, 'si'));
}
/**
* Test iec convert
*/
public function testNormIec()
{
$this->_setDefaultLocale();
$this->assertEquals('1 B', $this->_fs->fileSize(1, null, 'iec'));
$this->assertEquals('1 KiB', $this->_fs->fileSize(1024, null, 'iec'));
$this->assertEquals('1 MiB', $this->_fs->fileSize(1024 * 1024, null, 'iec'));
$this->assertEquals('1 GiB', $this->_fs->fileSize(1024 * 1024 * 1024, null, 'iec'));
}
/**
* Test localised input string
*/
public function testLocalised()
{
$this->markTestSkipped('This feature will be added in next ZF release.');
$locale = new Zend_Locale('cs_CZ');
require_once 'Zend/Registry.php';
Zend_Registry::set('Zend_Locale', $locale);
$this->assertEquals('1,1 MB', $this->_fs->fileSize('1153433,6', 1));
}
/**
* Test when no locale is set
*/
public function testNoLocaleSet()
{
Zend_Registry::getInstance()->_unsetInstance();
$this->assertEquals("976.563 kB", $this->_fs->fileSize(1000000, 3));
$this->assertEquals("976.5625 kB", $this->_fs->fileSize(1000000, 4));
$this->assertEquals("1.1 MB", $this->_fs->fileSize('1153433.6', 1));
$this->assertEquals("1.1 MB", $this->_fs->fileSize('1153433,6', 1)); //Czech decimal separator
}
}<file_sep>/Tests/Mhujer/View/Helper/EmailTest.php
<?php
/**
* Martin Hujer's Components
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to <EMAIL> so I can send you a copy immediately.
*
* @category Mhujer
* @package Mhujer_Tests
* @author <NAME> <EMAIL>
*/
/**
*
* @category Mhujer
* @package Mhujer_Tests
* @author <NAME> <EMAIL>
*/
set_include_path(get_include_path() . PATH_SEPARATOR . 'library');
require_once 'Mhujer/View/Helper/Email.php';
/**
* Mhujer_View_Helper_Email test case.
*/
class Mhujer_View_Helper_EmailTest extends PHPUnit_Framework_TestCase
{
/**
* @var Mhujer_View_Helper_Email
*/
private $_fs;
/**
* Prepares the environment before running a test.
*/
protected function setUp ()
{
parent::setUp();
$this->_fs = new Mhujer_View_Helper_Email();
}
/**
* Cleans up the environment after running a test.
*/
protected function tearDown ()
{
$this->_fs = null;
parent::tearDown();
}
public function testEmailAdress()
{
$data = array(
'<EMAIL>' => 'test@<!---->example.com',
);
foreach ($data as $input => $expected) {
$this->assertEquals($expected, $this->_fs->email($input));
}
}
public function testEmailAdressMailto()
{
$data = array(
'<EMAIL>' => '<a href="mailto:test@example.com">test@<!---->example.com</a>',
);
foreach ($data as $input => $expected) {
$this->assertEquals($expected, $this->_fs->email($input, true));
}
}
}
|
fc5f4f9e1af60af61cc2cb3eea647828b01140b0
|
[
"Markdown",
"PHP"
] | 8 |
PHP
|
mhujer/zfclasses
|
dd2887e11e6b3de554ab0c4754113495f0bb2e4f
|
5985edbc5b6283cc78eeff918cba848472e6f859
|
refs/heads/main
|
<repo_name>RAKESH1012A/CNN_CAT_DOG_APP<file_sep>/requirements.txt
Flask==1.1.2
gunicorn==20.0.4
h5py==2.8.0
Jinja2==2.11.3
Keras==2.2.2
Keras-Applications==1.0.4
Keras-Preprocessing==1.0.2
matplotlib==2.2.3
numpy==1.15.1
python-dateutil==2.8.1
scikit-learn==0.19.1
scipy==1.1.0
tensorboard==1.10.0
tensorflow==1.10.0
Werkzeug==1.0.1
<file_sep>/main.py
from flask import Flask, render_template, request
from werkzeug.utils import secure_filename
from keras.models import load_model
import numpy as np
from keras.preprocessing import image
import os
from keras import backend as K
app = Flask(__name__)
def pred(dog_img):
K.clear_session()
new_model = load_model('cat_dog_100epochs.h5')
return new_model.predict_classes(dog_img)
@app.route("/")
def home():
return render_template("home.html")
@app.route("/predict", methods=["GET","POST"])
def predict():
if request.method == 'POST':
file = request.files['file']
filename = secure_filename(file.filename)
file.save(os.path.join('static/images/', filename))
sfname = 'static/images/'+str(secure_filename(file.filename))
dog_img = image.load_img(sfname, target_size=(150, 150))
dog_img = image.img_to_array(dog_img)
dog_img = np.expand_dims(dog_img, axis=0)
dog_img = dog_img/255
#return render_template("result.html",pred = dog_img)
prediction_prob = pred(dog_img)
#return render_template("result.html",pred = prediction_prob)
a=prediction_prob.ravel()
if a==1:
return render_template("result.html",pred = 'Dog',pic=sfname)
else:
return render_template("result.html",pred = 'Cat',pic=sfname)
return render_template("predict.html")
if __name__ == "__main__":
app.run(debug=True)
|
2ecdb91a125204f4842ec9747f832851a577a32c
|
[
"Python",
"Text"
] | 2 |
Text
|
RAKESH1012A/CNN_CAT_DOG_APP
|
ccd662e6c0a8f91d3d9f54775e5ab9b8fe5c5edb
|
c86e6b9407bf2cf16d40373b6ab4b36820c69bde
|
refs/heads/master
|
<file_sep>from flask import Flask, redirect, make_response, request, Response, abort, render_template
import random
import requests
import datetime
import logging
app = Flask(__name__)
logging.basicConfig(level=logging.INFO)
CHUNK_SIZE = 1024
LOG = logging.getLogger("main.py")
base_url = "http://10.80.1.69:81/"
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def index(path):
try:
zone_cookie = request.cookies.get('zone', 0)
url_fetch = request.url.replace(request.url_root, base_url)
if zone_cookie != 0:
#response = Response() #make_response(requests.get(url_fetch, stream=True).text)
#response.headers["Cookie"] = request.headers.get("Cookie", "")
#response.headers["HTTP_X_FORWARDED_HOST"] = 'http://radnews.net'
returnstuff = proxy(url_fetch)
return returnstuff
else:
redirect_to_index = redirect('/')
response = make_response(redirect_to_index)
response.set_cookie('zone', value=str(random.randint(1, 2)))
response.headers['Last-Modified'] = datetime.datetime.now()
response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, ' \
'post-check=0, pre-check=0, max-age=0'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '-1'
return response
except Exception as e:
return str(e)
@app.route('/killcookie/')
def kill_cookie():
response = make_response()
response.set_cookie('zone', '', expires=0)
return response
def proxy(url):
"""Fetches the specified URL and streams it out to the client.
If the request was referred by the proxy itself (e.g. this is an image fetch for
a previously proxied HTML page), then the original Referer is passed."""
r = get_source_rsp(url)
LOG.info("Got %s response from %s",r.status_code, url)
headers = dict(r.headers)
return Response(r.raw.read(), headers=headers)
def get_source_rsp(url):
LOG.info("Fetching %s", url)
# Ensure the URL is approved, else abort
# Pass original Referer for subsequent resource requests
proxy_ref = proxy_ref_info(request)
headers = { "Referer" : "http://%s/%s" % (proxy_ref[0], proxy_ref[1])} if proxy_ref else {}
# Fetch the URL, and stream it back
LOG.info("Fetching with headers: %s, %s", url, headers)
return requests.get(url, stream=True , params = request.args, headers=headers)
def split_url(url):
"""Splits the given URL into a tuple of (protocol, host, uri)"""
proto, rest = url.split(':', 1)
rest = rest[2:].split('/', 1)
host, uri = (rest[0], rest[1]) if len(rest) == 2 else (rest[0], "")
return (proto, host, uri)
def proxy_ref_info(request):
"""Parses out Referer info indicating the request is from a previously proxied page.
For example, if:
Referer: http://localhost:8080/p/google.com/search?q=foo
then the result is:
("google.com", "search?q=foo")
"""
ref = request.headers.get('referer')
if ref:
_, _, uri = split_url(ref)
if uri.find("/") < 0:
return None
first, rest = uri.split("/", 1)
if first in "pd":
parts = rest.split("/", 1)
r = (parts[0], parts[1]) if len(parts) == 2 else (parts[0], "")
LOG.info("Referred by proxy host, uri: %s, %s", r[0], r[1])
return r
return None
if __name__ == '__main__':
app.run('0.0.0.0', debug=True)
<file_sep><h1>Docker-Flask</h1>
Docker-Flask is a Docker setup for a very simple Flask application. It runs on Python 3.x via Nginx and UWSGI. To build this Docker file and get going follow the installation instructions below -- *installation instructions are written for Mac OS X users*
<h2>Step 1: Install Docker</h2>
Download Docker's [boot2docker](https://github.com/boot2docker/osx-installer/releases) to get started.
<h2>Step 2: Start boot2docker</h2>
Start *boot2docker* with the following command in your terminal:
```bash
$ boot2docker up
```
The command will return something that looks like the following statement. Copy and paste what *boot2docker* returned and execute it in your terminal:
```bash
$ export DOCKER_HOST=tcp://192.168.59.103:2375
```
<h2>Step 3: Download docker-flask</h2>
```bash
$ git clone https://github.com/ryanmcdermott/docker-flask.git
$ cd docker-flask
```
<h2>Step 4: Build docker-flask</h2>
```bash
$ docker build --rm --tag=flask .
```
<h2>Step 5: Run docker-flask</h2>
```bash
$ docker run -it -p 80:80 flask
```
You should see Docker running a supervisord session with Nginx and UWSGI. Now all that's left to do is open up your browser and type the IP address that boot2docker returned. In this example it was 192.168.59.103.
You should see the text *Flask is running!* in your browser. That's all there is to it!
|
ee2744112fb059e55950284a857d753e55bc7bbf
|
[
"Markdown",
"Python"
] | 2 |
Python
|
GiantRobots/docker-flask
|
d019c78a476629383430b1720361bab09d140131
|
5a07eb097c734ad4aee675a7f7327bb1dbe6fed0
|
refs/heads/master
|
<file_sep>[tox]
envlist = py27, py35, py36, py37, qa
[testenv]
extras = testing
deps =
# for testing the typing module
py27: typing
# numpydoc for typing scipy stack
numpydoc
# sphinx, a dependency of numpydoc, dropped Python 2 support in version 2.0
sphinx < 2.0
cov: coverage
# Overwrite the parso version (only used sometimes).
git+https://github.com/davidhalter/parso.git
passenv = JEDI_TEST_ENVIRONMENT
setenv =
# https://github.com/tomchristie/django-rest-framework/issues/1957
# tox corrupts __pycache__, solution from here:
PYTHONDONTWRITEBYTECODE=1
# Enable all warnings.
PYTHONWARNINGS=always
# To test Jedi in different versions than the same Python version, set a
# different test environment.
env27: JEDI_TEST_ENVIRONMENT=27
env35: JEDI_TEST_ENVIRONMENT=35
env36: JEDI_TEST_ENVIRONMENT=36
env37: JEDI_TEST_ENVIRONMENT=37
interpreter: JEDI_TEST_ENVIRONMENT=interpreter
commands =
pytest {posargs}
[testenv:cov-py37]
commands =
coverage run --source jedi -m pytest {posargs}
coverage report
[testenv:sith]
commands =
{envpython} -c "import os; a='{envtmpdir}'; os.path.exists(a) or os.makedirs(a)"
{envpython} sith.py --record {envtmpdir}/record.json random {posargs:jedi}
[testenv:qa]
# Ignore F401, which are unused imports. flake8 is a primitive tool and is sometimes wrong.
commands = flake8 --extend-ignore F401 {posargs:jedi}
deps =
extras = qa
<file_sep># -------------------------------------------------- no-name-error
#? 0 error
1
# ++++++++++++++++++++++++++++++++++++++++++++++++++
There is no name under the cursor
# -------------------------------------------------- multi-equal-error
def test():
#? 4 error
a = b = 3
return test(100, a)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
Cannot inline a statement with multiple definitions
# -------------------------------------------------- no-definition-error
#? 5 error
test(a)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
No definition found to inline
# -------------------------------------------------- multi-names-error
#? 0 error
a, b[1] = 3
test(a)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
Cannot inline a statement with multiple definitions
# -------------------------------------------------- addition-error
#? 0 error
a = 2
a += 3
test(a)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
Cannot inline a name with multiple definitions
# -------------------------------------------------- only-addition-error
#? 0 error
a += 3
test(a)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
Cannot inline a statement with "+="
# -------------------------------------------------- with-annotation
foobarb: int = 1
#? 5
test(foobarb)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
--- inline.py
+++ inline.py
@@ -1,4 +1,3 @@
-foobarb: int = 1
#? 5
-test(foobarb)
+test(1)
# -------------------------------------------------- only-annotation-error
a: int
#? 5 error
test(a)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
Cannot inline a statement that is defined by an annotation
# -------------------------------------------------- builtin
import math
#? 7 error
math.cos
# ++++++++++++++++++++++++++++++++++++++++++++++++++
Cannot inline builtins/extensions
# -------------------------------------------------- module-error
from import_tree import inline_mod
#? 11 error
test(inline_mod)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
Cannot inline imports or modules
# -------------------------------------------------- module-works
from import_tree import inline_mod
#? 22
test(x, inline_mod. inline_var.conjugate)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
--- import_tree/inline_mod.py
+++ import_tree/inline_mod.py
@@ -1,2 +1 @@
-inline_var = 5 + 3
--- inline.py
+++ inline.py
@@ -1,4 +1,4 @@
from import_tree import inline_mod
#? 22
-test(x, inline_mod. inline_var.conjugate)
+test(x, (5 + 3).conjugate)
# -------------------------------------------------- class
class A: pass
#? 5 error
test(A)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
Cannot inline a class
# -------------------------------------------------- function
def foo(a):
return a + 1
#? 5 error
test(foo(1))
# ++++++++++++++++++++++++++++++++++++++++++++++++++
Cannot inline a function
# -------------------------------------------------- for-stmt
for x in []:
#? 9 error
test(x)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
Cannot inline a for_stmt
# -------------------------------------------------- simple
def test():
#? 4
a = (30 + b, c) + 1
return test(100, a)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
--- inline.py
+++ inline.py
@@ -1,5 +1,4 @@
def test():
#? 4
- a = (30 + b, c) + 1
- return test(100, a)
+ return test(100, (30 + b, c) + 1)
# -------------------------------------------------- tuple
if 1:
#? 4
a = 1, 2
return test(100, a)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
--- inline.py
+++ inline.py
@@ -1,5 +1,4 @@
if 1:
#? 4
- a = 1, 2
- return test(100, a)
+ return test(100, (1, 2))
# -------------------------------------------------- multiplication-add-parens1
a = 1+2
#? 11
test(100 * a)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
--- inline.py
+++ inline.py
@@ -1,4 +1,3 @@
-a = 1+2
#? 11
-test(100 * a)
+test(100 * (1+2))
# -------------------------------------------------- multiplication-add-parens2
a = 1+2
#? 11
(x, 100 * a)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
--- inline.py
+++ inline.py
@@ -1,4 +1,3 @@
-a = 1+2
#? 11
-(x, 100 * a)
+(x, 100 * (1+2))
# -------------------------------------------------- multiplication-add-parens3
x
a = 1+2
#? 9
(100 ** a)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
--- inline.py
+++ inline.py
@@ -1,5 +1,4 @@
x
-a = 1+2
#? 9
-(100 ** a)
+(100 ** (1+2))
# -------------------------------------------------- no-add-parens1
x
a = 1+2
#? 5
test(a)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
--- inline.py
+++ inline.py
@@ -1,5 +1,4 @@
x
-a = 1+2
#? 5
-test(a)
+test(1+2)
# -------------------------------------------------- no-add-parens2
a = 1+2
#? 9
test(3, a)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
--- inline.py
+++ inline.py
@@ -1,4 +1,3 @@
-a = 1+2
#? 9
-test(3, a)
+test(3, 1+2)
# -------------------------------------------------- no-add-parens3
a = 1|2
#? 5
(3, a)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
--- inline.py
+++ inline.py
@@ -1,4 +1,3 @@
-a = 1|2
#? 5
-(3, a)
+(3, 1|2)
# -------------------------------------------------- comment
a = 1 and 2 # foo
#? 9
(3, 3 * a)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
--- inline.py
+++ inline.py
@@ -1,4 +1,4 @@
-a = 1 and 2 # foo
+ # foo
#? 9
-(3, 3 * a)
+(3, 3 * (1 and 2))
# -------------------------------------------------- semicolon
a = 1, 2 ; b = 3
#? 9
(3, 3 == a)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
--- inline.py
+++ inline.py
@@ -1,4 +1,4 @@
-a = 1, 2 ; b = 3
+ b = 3
#? 9
-(3, 3 == a)
+(3, 3 == (1, 2))
# -------------------------------------------------- no-tree-name
a = 1 + 2
#? 0
a.conjugate
# ++++++++++++++++++++++++++++++++++++++++++++++++++
--- inline.py
+++ inline.py
@@ -1,4 +1,3 @@
-a = 1 + 2
#? 0
-a.conjugate
+(1 + 2).conjugate
<file_sep># -------------------------------------------------- in-module-1
glob = 3
#? 11 text {'new_name': 'a'}
test(100, (glob.a + b, c) + 1)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
glob = 3
#? 11 text {'new_name': 'a'}
def a(b):
return glob.a + b
test(100, (a(b), c) + 1)
# -------------------------------------------------- in-module-2
#? 0 text {'new_name': 'ab'}
100 + 1 * 2
# ++++++++++++++++++++++++++++++++++++++++++++++++++
#? 0 text {'new_name': 'ab'}
def ab():
return 100 + 1 * 2
ab()
# -------------------------------------------------- in-function-1
def f(x):
#? 11 text {'new_name': 'ab'}
return x + 1 * 2
# ++++++++++++++++++++++++++++++++++++++++++++++++++
def ab(x):
return x + 1 * 2
def f(x):
#? 11 text {'new_name': 'ab'}
return ab(x)
# -------------------------------------------------- in-function-with-dec
@classmethod
def f(x):
#? 11 text {'new_name': 'ab'}
return x + 1 * 2
# ++++++++++++++++++++++++++++++++++++++++++++++++++
def ab(x):
return x + 1 * 2
@classmethod
def f(x):
#? 11 text {'new_name': 'ab'}
return ab(x)
# -------------------------------------------------- in-method-1
class X:
def z(self): pass
def f(x, b):
#? 11 text {'new_name': 'ab'}
return x + b * 2
# ++++++++++++++++++++++++++++++++++++++++++++++++++
class X:
def z(self): pass
def ab(x, b):
return x + b * 2
def f(x, b):
#? 11 text {'new_name': 'ab'}
return x.ab(b)
# -------------------------------------------------- in-method-2
glob1 = 1
class X:
def g(self): pass
def f(self, b, c):
#? 11 text {'new_name': 'ab'}
return self.g() or self.f(b) ^ glob1 & b
# ++++++++++++++++++++++++++++++++++++++++++++++++++
glob1 = 1
class X:
def g(self): pass
def ab(self, b):
return self.g() or self.f(b) ^ glob1 & b
def f(self, b, c):
#? 11 text {'new_name': 'ab'}
return self.ab(b)
# -------------------------------------------------- in-method-order
class X:
def f(self, b, c):
#? 18 text {'new_name': 'b'}
return b | self.a
# ++++++++++++++++++++++++++++++++++++++++++++++++++
class X:
def b(self, b):
return b | self.a
def f(self, b, c):
#? 18 text {'new_name': 'b'}
return self.b(b)
# -------------------------------------------------- in-classmethod-1
class X:
@classmethod
def f(x):
#? 16 text {'new_name': 'ab'}
return 25
# ++++++++++++++++++++++++++++++++++++++++++++++++++
class X:
@classmethod
def ab(x):
return 25
@classmethod
def f(x):
#? 16 text {'new_name': 'ab'}
return x.ab()
# -------------------------------------------------- in-staticmethod-1
class X(int):
@staticmethod
def f(x):
#? 16 text {'new_name': 'ab'}
return 25 | 3
# ++++++++++++++++++++++++++++++++++++++++++++++++++
def ab():
return 25 | 3
class X(int):
@staticmethod
def f(x):
#? 16 text {'new_name': 'ab'}
return ab()
# -------------------------------------------------- in-class-1
class Ya():
a = 3
#? 11 text {'new_name': 'f'}
c = a + 2
# ++++++++++++++++++++++++++++++++++++++++++++++++++
def f(a):
return a + 2
class Ya():
a = 3
#? 11 text {'new_name': 'f'}
c = f(a)
# -------------------------------------------------- in-closure
def x(z):
def y(x):
#? 15 text {'new_name': 'f'}
return -x * z
# ++++++++++++++++++++++++++++++++++++++++++++++++++
def f(x, z):
return -x * z
def x(z):
def y(x):
#? 15 text {'new_name': 'f'}
return f(x, z)
# -------------------------------------------------- with-range-1
#? 0 text {'new_name': 'a', 'until_line': 4}
v1 = 3
v2 = 2
x = test(v1 + v2 * v3)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
#? 0 text {'new_name': 'a', 'until_line': 4}
def a(test, v3):
v1 = 3
v2 = 2
x = test(v1 + v2 * v3)
return x
x = a(test, v3)
# -------------------------------------------------- with-range-2
#? 2 text {'new_name': 'a', 'until_line': 6, 'until_column': 4}
#foo
v1 = 3
v2 = 2
x, y = test(v1 + v2 * v3)
#raaaa
y
# ++++++++++++++++++++++++++++++++++++++++++++++++++
#? 2 text {'new_name': 'a', 'until_line': 6, 'until_column': 4}
def a(test, v3):
#foo
v1 = 3
v2 = 2
x, y = test(v1 + v2 * v3)
#raaaa
return y
y = a(test, v3)
y
# -------------------------------------------------- with-range-3
#foo
#? 2 text {'new_name': 'a', 'until_line': 5, 'until_column': 4}
v1 = 3
v2 = 2
x, y = test(v1 + v2 * v3)
#raaaa
y
# ++++++++++++++++++++++++++++++++++++++++++++++++++
#foo
#? 2 text {'new_name': 'a', 'until_line': 5, 'until_column': 4}
def a(test, v3):
v1 = 3
v2 = 2
x, y = test(v1 + v2 * v3)
return y
y = a(test, v3)
#raaaa
y
# -------------------------------------------------- with-range-func-1
import os
# comment1
@dec
# comment2
def x(v1):
#foo
#? 2 text {'new_name': 'a', 'until_line': 9, 'until_column': 5}
v2 = 2
if 1:
x, y = os.listdir(v1 + v2 * v3)
#bar
return x, y
# ++++++++++++++++++++++++++++++++++++++++++++++++++
import os
# comment1
def a(v1, v3):
v2 = 2
if 1:
x, y = os.listdir(v1 + v2 * v3)
return x, y
@dec
# comment2
def x(v1):
#foo
#? 2 text {'new_name': 'a', 'until_line': 9, 'until_column': 5}
x, y = a(v1, v3)
#bar
return x, y
# -------------------------------------------------- with-range-func-2
import os
# comment1
# comment2
def x(v1):
#? 2 text {'new_name': 'a', 'until_line': 10, 'until_column': 0}
#foo
v2 = 2
if 1:
x, y = os.listdir(v1 + v2 * v3)
#bar
return y
x
# ++++++++++++++++++++++++++++++++++++++++++++++++++
import os
# comment1
# comment2
def a(v1, v3):
#foo
v2 = 2
if 1:
x, y = os.listdir(v1 + v2 * v3)
#bar
return y
def x(v1):
#? 2 text {'new_name': 'a', 'until_line': 10, 'until_column': 0}
y = a(v1, v3)
return y
x
# -------------------------------------------------- with-range-func-3
def x(v1):
#? 2 text {'new_name': 'func', 'until_line': 6, 'until_column': 4}
#foo
v2 = 2
x = v1 * 2
y = 3
#bar
return x
x
# ++++++++++++++++++++++++++++++++++++++++++++++++++
def func(v1):
#foo
v2 = 2
x = v1 * 2
return x
def x(v1):
#? 2 text {'new_name': 'func', 'until_line': 6, 'until_column': 4}
x = func(v1)
y = 3
#bar
return x
x
# -------------------------------------------------- in-class-range-1
class X1:
#? 9 text {'new_name': 'f', 'until_line': 4}
a = 3
c = a + 2
# ++++++++++++++++++++++++++++++++++++++++++++++++++
def f():
a = 3
c = a + 2
return c
class X1:
#? 9 text {'new_name': 'f', 'until_line': 4}
c = f()
# -------------------------------------------------- in-method-range-1
glob1 = 1
class X:
# ha
def g(self): pass
# haha
def f(self, b, c):
#? 11 text {'new_name': 'ab', 'until_line': 12, 'until_column': 28}
#foo
local1 = 3
local2 = 4
x= self.g() or self.f(b) ^ glob1 & b is local1
# bar
# ++++++++++++++++++++++++++++++++++++++++++++++++++
glob1 = 1
class X:
# ha
def g(self): pass
# haha
def ab(self, b):
#foo
local1 = 3
local2 = 4
x= self.g() or self.f(b) ^ glob1 & b is local1
return x
def f(self, b, c):
#? 11 text {'new_name': 'ab', 'until_line': 12, 'until_column': 28}
x = self.ab(b)
# bar
# -------------------------------------------------- in-method-range-2
glob1 = 1
class X:
# comment
def f(self, b, c):
#? 11 text {'new_name': 'ab', 'until_line': 11, 'until_column': 10}
#foo
local1 = 3
local2 = 4
return local1 * glob1 * b
# bar
# ++++++++++++++++++++++++++++++++++++++++++++++++++
glob1 = 1
class X:
# comment
def ab(self, b):
#foo
local1 = 3
local2 = 4
return local1 * glob1 * b
# bar
def f(self, b, c):
#? 11 text {'new_name': 'ab', 'until_line': 11, 'until_column': 10}
return self.ab(b)
# -------------------------------------------------- in-method-range-3
glob1 = 1
class X:
def f(self, b, c):
local1, local2 = 3, 4
#foo
#? 11 text {'new_name': 'ab', 'until_line': 7, 'until_column': 29}
return local1 & glob1 & b
# bar
local2
# ++++++++++++++++++++++++++++++++++++++++++++++++++
glob1 = 1
class X:
def ab(self, local1, b):
return local1 & glob1 & b
def f(self, b, c):
local1, local2 = 3, 4
#foo
#? 11 text {'new_name': 'ab', 'until_line': 7, 'until_column': 29}
return self.ab(local1, b)
# bar
local2
# -------------------------------------------------- in-method-no-param
glob1 = 1
class X:
def f():
#? 11 text {'new_name': 'ab', 'until_line': 5, 'until_column': 22}
return glob1 + 2
# ++++++++++++++++++++++++++++++++++++++++++++++++++
glob1 = 1
class X:
def ab():
return glob1 + 2
def f():
#? 11 text {'new_name': 'ab', 'until_line': 5, 'until_column': 22}
return ab()
# -------------------------------------------------- random-return-1
def x():
#? 0 error {'new_name': 'ab', 'until_line': 5, 'until_column': 10}
if x:
return 1
return 1
# ++++++++++++++++++++++++++++++++++++++++++++++++++
Can only extract return statements if they are at the end.
# -------------------------------------------------- random-return-2
def x():
#? 0 error {'new_name': 'ab', 'until_line': 5, 'until_column': 10}
#
return
pass
# ++++++++++++++++++++++++++++++++++++++++++++++++++
Can only extract return statements if they are at the end.
# -------------------------------------------------- random-yield-1
def x():
#? 0 error {'new_name': 'ab', 'until_line': 5, 'until_column': 10}
#
if (yield 1):
return
pass
# ++++++++++++++++++++++++++++++++++++++++++++++++++
Cannot extract yield statements.
# -------------------------------------------------- random-yield-2
def x():
#? 0 error {'new_name': 'ab', 'until_line': 4, 'until_column': 10}
#
try:
yield
finally:
pass
# ++++++++++++++++++++++++++++++++++++++++++++++++++
Cannot extract yield statements.
<file_sep># -------------------------------------------------- simple-1
def test():
#? 35 text {'new_name': 'a'}
return test(100, (30 + b, c) + 1)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
def test():
#? 35 text {'new_name': 'a'}
a = (30 + b, c) + 1
return test(100, a)
# -------------------------------------------------- simple-2
def test():
#? 25 text {'new_name': 'a'}
return test(100, (30 + b, c) + 1)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
def test():
#? 25 text {'new_name': 'a'}
a = 30 + b
return test(100, (a, c) + 1)
# -------------------------------------------------- simple-3
#? 13 text {'new_name': 'zzx.x'}
test(100, {1 |1: 2 + 3})
# ++++++++++++++++++++++++++++++++++++++++++++++++++
#? 13 text {'new_name': 'zzx.x'}
zzx.x = 1 |1
test(100, {zzx.x: 2 + 3})
# -------------------------------------------------- multiline-1
def test():
#? 30 text {'new_name': 'x'}
return test(1, (30 + b, c)
+ 1)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
def test():
#? 30 text {'new_name': 'x'}
x = (30 + b, c)
+ 1
return test(1, x)
# -------------------------------------------------- multiline-2
def test():
#? 25 text {'new_name': 'x'}
return test(1, (30 + b, c)
+ 1)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
def test():
#? 25 text {'new_name': 'x'}
x = 30 + b
return test(1, (x, c)
+ 1)
# -------------------------------------------------- for-param-error-1
#? 10 error {'new_name': 'x'}
def test(p1):
return
# ++++++++++++++++++++++++++++++++++++++++++++++++++
Cannot extract a name that defines something
# -------------------------------------------------- for-param-error-2
#? 12 error {'new_name': 'x'}
def test(p1= 3):
return
# ++++++++++++++++++++++++++++++++++++++++++++++++++
Cannot extract a "param"
# -------------------------------------------------- for-param-1
#? 12 text {'new_name': 'x'}
def test(p1=20):
return
# ++++++++++++++++++++++++++++++++++++++++++++++++++
#? 12 text {'new_name': 'x'}
x = 20
def test(p1=x):
return
# -------------------------------------------------- for-something
#? 12 text {'new_name': 'x'}
def test(p1=20):
return
# ++++++++++++++++++++++++++++++++++++++++++++++++++
#? 12 text {'new_name': 'x'}
x = 20
def test(p1=x):
return
# -------------------------------------------------- class-inheritance-1
#? 12 text {'new_name': 'x'}
class Foo(foo.Bar):
pass
# ++++++++++++++++++++++++++++++++++++++++++++++++++
#? 12 text {'new_name': 'x'}
x = foo.Bar
class Foo(x):
pass
# -------------------------------------------------- class-inheritance-2
#? 16 text {'new_name': 'x'}
class Foo(foo.Bar):
pass
# ++++++++++++++++++++++++++++++++++++++++++++++++++
#? 16 text {'new_name': 'x'}
x = foo.Bar
class Foo(x):
pass
# -------------------------------------------------- keyword-pass
#? 12 error {'new_name': 'x'}
def x(): pass
# ++++++++++++++++++++++++++++++++++++++++++++++++++
Cannot extract a "simple_stmt"
# -------------------------------------------------- keyword-continue
#? 5 error {'new_name': 'x'}
continue
# ++++++++++++++++++++++++++++++++++++++++++++++++++
Cannot extract a "simple_stmt"
# -------------------------------------------------- keyword-None
if 1:
#? 4 text {'new_name': 'x'}
None
# ++++++++++++++++++++++++++++++++++++++++++++++++++
if 1:
#? 4 text {'new_name': 'x'}
x = None
x
# -------------------------------------------------- with-tuple
#? 4 text {'new_name': 'x'}
x + 1, 3
# ++++++++++++++++++++++++++++++++++++++++++++++++++
#? 4 text {'new_name': 'x'}
x = x + 1
x, 3
# -------------------------------------------------- range-1
#? 4 text {'new_name': 'x', 'until_column': 9}
y + 1, 3
# ++++++++++++++++++++++++++++++++++++++++++++++++++
#? 4 text {'new_name': 'x', 'until_column': 9}
x = y + 1, 3
x
# -------------------------------------------------- range-2
#? 1 text {'new_name': 'x', 'until_column': 3}
y + 1, 3
# ++++++++++++++++++++++++++++++++++++++++++++++++++
#? 1 text {'new_name': 'x', 'until_column': 3}
x = y + 1
x, 3
# -------------------------------------------------- range-3
#? 1 text {'new_name': 'x', 'until_column': 6}
y + 1, 3
# ++++++++++++++++++++++++++++++++++++++++++++++++++
#? 1 text {'new_name': 'x', 'until_column': 6}
x = y + 1
x, 3
# -------------------------------------------------- range-4
#? 1 text {'new_name': 'x', 'until_column': 1}
y + 1, 3
# ++++++++++++++++++++++++++++++++++++++++++++++++++
#? 1 text {'new_name': 'x', 'until_column': 1}
x = y
x + 1, 3
# -------------------------------------------------- addition-1
#? 4 text {'new_name': 'x', 'until_column': 9}
z = y + 1 + 2+ 3, 3
# ++++++++++++++++++++++++++++++++++++++++++++++++++
#? 4 text {'new_name': 'x', 'until_column': 9}
x = y + 1
z = x + 2+ 3, 3
# -------------------------------------------------- addition-2
#? 8 text {'new_name': 'x', 'until_column': 12}
z = y +1 + 2+ 3, 3
# ++++++++++++++++++++++++++++++++++++++++++++++++++
#? 8 text {'new_name': 'x', 'until_column': 12}
x = 1 + 2
z = y +x+ 3, 3
# -------------------------------------------------- addition-3
#? 10 text {'new_name': 'x', 'until_column': 14}
z = y + 1 + 2+ 3, 3
# ++++++++++++++++++++++++++++++++++++++++++++++++++
#? 10 text {'new_name': 'x', 'until_column': 14}
x = 1 + 2+ 3
z = y + x, 3
# -------------------------------------------------- addition-4
#? 13 text {'new_name': 'x', 'until_column': 17}
z = y + (1 + 2)+ 3, 3
# ++++++++++++++++++++++++++++++++++++++++++++++++++
#? 13 text {'new_name': 'x', 'until_column': 17}
x = (1 + 2)+ 3
z = y + x, 3
# -------------------------------------------------- mult-add-1
#? 8 text {'new_name': 'x', 'until_column': 11}
z = foo(y+1*2+3, 3)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
#? 8 text {'new_name': 'x', 'until_column': 11}
x = y+1
z = foo(x*2+3, 3)
# -------------------------------------------------- mult-add-2
#? 12 text {'new_name': 'x', 'until_column': 15}
z = foo(y+1*2+3)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
#? 12 text {'new_name': 'x', 'until_column': 15}
x = 2+3
z = foo(y+1*x)
# -------------------------------------------------- mult-add-3
#? 9 text {'new_name': 'x', 'until_column': 13}
z = (y+1*2+3)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
#? 9 text {'new_name': 'x', 'until_column': 13}
x = (y+1*2+3)
z = x
# -------------------------------------------------- extract-weird-1
#? 0 error {'new_name': 'x', 'until_column': 7}
foo = 3
# ++++++++++++++++++++++++++++++++++++++++++++++++++
Cannot extract a "expr_stmt"
# -------------------------------------------------- extract-weird-2
#? 0 error {'new_name': 'x', 'until_column': 5}
def x():
foo = 3
# ++++++++++++++++++++++++++++++++++++++++++++++++++
Cannot extract a "funcdef"
# -------------------------------------------------- extract-weird-3
def x():
#? 4 error {'new_name': 'x', 'until_column': 8}
if 1:
pass
# ++++++++++++++++++++++++++++++++++++++++++++++++++
Cannot extract a "if_stmt"
# -------------------------------------------------- extract-weird-4
#? 4 error {'new_name': 'x', 'until_column': 7}
x = foo = 4
# ++++++++++++++++++++++++++++++++++++++++++++++++++
Cannot extract a name that defines something
# -------------------------------------------------- keyword-None
#? 4 text {'new_name': 'x', 'until_column': 7}
yy = not foo or bar
# ++++++++++++++++++++++++++++++++++++++++++++++++++
#? 4 text {'new_name': 'x', 'until_column': 7}
x = not foo
yy = x or bar
# -------------------------------------------------- augassign
yy = ()
#? 6 text {'new_name': 'x', 'until_column': 10}
yy += 3, 4
# ++++++++++++++++++++++++++++++++++++++++++++++++++
yy = ()
#? 6 text {'new_name': 'x', 'until_column': 10}
x = 3, 4
yy += x
# -------------------------------------------------- if-else
#? 9 text {'new_name': 'x', 'until_column': 22}
yy = foo(a if y else b)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
#? 9 text {'new_name': 'x', 'until_column': 22}
x = a if y else b
yy = foo(x)
# -------------------------------------------------- lambda
#? 8 text {'new_name': 'x', 'until_column': 17}
y = foo(lambda x: 3, 5)
# ++++++++++++++++++++++++++++++++++++++++++++++++++
#? 8 text {'new_name': 'x', 'until_column': 17}
x = lambda x: 3
y = foo(x, 5)
<file_sep># python >= 3.4
from typing import Any, Iterable, List, Sequence, Tuple, TypeVar, Union
T = TypeVar('T')
U = TypeVar('U')
TList = TypeVar('TList', bound=List[Any])
untyped_list_str = ['abc', 'def']
typed_list_str = ['abc', 'def'] # type: List[str]
untyped_tuple_str = ('abc',)
typed_tuple_str = ('abc',) # type: Tuple[str]
untyped_tuple_str_int = ('abc', 4)
typed_tuple_str_int = ('abc', 4) # type: Tuple[str, int]
variadic_tuple_str = ('abc',) # type: Tuple[str, ...]
variadic_tuple_str_int = ('abc', 4) # type: Tuple[Union[str, int], ...]
def untyped_passthrough(x):
return x
def typed_list_generic_passthrough(x: List[T]) -> List[T]:
return x
def typed_tuple_generic_passthrough(x: Tuple[T]) -> Tuple[T]:
return x
def typed_multi_typed_tuple_generic_passthrough(x: Tuple[T, U]) -> Tuple[U, T]:
return x[1], x[0]
def typed_variadic_tuple_generic_passthrough(x: Tuple[T, ...]) -> Sequence[T]:
return x
def typed_iterable_generic_passthrough(x: Iterable[T]) -> Iterable[T]:
return x
def typed_fully_generic_passthrough(x: T) -> T:
return x
def typed_bound_generic_passthrough(x: TList) -> TList:
return x
for a in untyped_passthrough(untyped_list_str):
#? str()
a
for b in untyped_passthrough(typed_list_str):
#? str()
b
for c in typed_list_generic_passthrough(untyped_list_str):
#? str()
c
for d in typed_list_generic_passthrough(typed_list_str):
#? str()
d
for e in typed_iterable_generic_passthrough(untyped_list_str):
#? str()
e
for f in typed_iterable_generic_passthrough(typed_list_str):
#? str()
f
for g in typed_tuple_generic_passthrough(untyped_tuple_str):
#? str()
g
for h in typed_tuple_generic_passthrough(typed_tuple_str):
#? str()
h
out_untyped = typed_multi_typed_tuple_generic_passthrough(untyped_tuple_str_int)
#? int()
out_untyped[0]
#? str()
out_untyped[1]
out_typed = typed_multi_typed_tuple_generic_passthrough(typed_tuple_str_int)
#? int()
out_typed[0]
#? str()
out_typed[1]
for j in typed_variadic_tuple_generic_passthrough(untyped_tuple_str_int):
#? str() int()
j
for k in typed_variadic_tuple_generic_passthrough(typed_tuple_str_int):
#? str() int()
k
for l in typed_variadic_tuple_generic_passthrough(variadic_tuple_str):
#? str()
l
for m in typed_variadic_tuple_generic_passthrough(variadic_tuple_str_int):
#? str() int()
m
for n in typed_fully_generic_passthrough(untyped_list_str):
#? str()
n
for o in typed_fully_generic_passthrough(typed_list_str):
#? str()
o
for p in typed_bound_generic_passthrough(untyped_list_str):
#? str()
p
for q in typed_bound_generic_passthrough(typed_list_str):
#? str()
q
<file_sep>import os
import pytest
from parso.utils import PythonVersionInfo
from jedi.inference.gradual import typeshed
from jedi.inference.value import TreeInstance, BoundMethod, FunctionValue, \
MethodValue, ClassValue
from jedi.inference.names import StubName
TYPESHED_PYTHON3 = os.path.join(typeshed.TYPESHED_PATH, 'stdlib', '3')
def test_get_typeshed_directories():
def get_dirs(version_info):
return {
d.replace(typeshed.TYPESHED_PATH, '').lstrip(os.path.sep)
for d in typeshed._get_typeshed_directories(version_info)
}
def transform(set_):
return {x.replace('/', os.path.sep) for x in set_}
dirs = get_dirs(PythonVersionInfo(2, 7))
assert dirs == transform({'stdlib/2and3', 'stdlib/2', 'third_party/2and3', 'third_party/2'})
dirs = get_dirs(PythonVersionInfo(3, 5))
assert dirs == transform({'stdlib/2and3', 'stdlib/3',
'third_party/2and3', 'third_party/3'})
dirs = get_dirs(PythonVersionInfo(3, 6))
assert dirs == transform({'stdlib/2and3', 'stdlib/3',
'stdlib/3.6', 'third_party/2and3',
'third_party/3', 'third_party/3.6'})
def test_get_stub_files():
def get_map(version_info):
return typeshed._create_stub_map(version_info)
map_ = typeshed._create_stub_map(TYPESHED_PYTHON3)
assert map_['functools'] == os.path.join(TYPESHED_PYTHON3, 'functools.pyi')
def test_function(Script, environment):
code = 'import threading; threading.current_thread'
def_, = Script(code).infer()
value = def_._name._value
assert isinstance(value, FunctionValue), value
def_, = Script(code + '()').infer()
value = def_._name._value
assert isinstance(value, TreeInstance)
def_, = Script('import threading; threading.Thread').infer()
assert isinstance(def_._name._value, ClassValue), def_
def test_keywords_variable(Script):
code = 'import keyword; keyword.kwlist'
for seq in Script(code).infer():
assert seq.name == 'Sequence'
# This points towards the typeshed implementation
stub_seq, = seq.goto(only_stubs=True)
assert typeshed.TYPESHED_PATH in stub_seq.module_path
def test_class(Script):
def_, = Script('import threading; threading.Thread').infer()
value = def_._name._value
assert isinstance(value, ClassValue), value
def test_instance(Script):
def_, = Script('import threading; threading.Thread()').infer()
value = def_._name._value
assert isinstance(value, TreeInstance)
def test_class_function(Script):
def_, = Script('import threading; threading.Thread.getName').infer()
value = def_._name._value
assert isinstance(value, MethodValue), value
def test_method(Script):
code = 'import threading; threading.Thread().getName'
def_, = Script(code).infer()
value = def_._name._value
assert isinstance(value, BoundMethod), value
assert isinstance(value._wrapped_value, MethodValue), value
def_, = Script(code + '()').infer()
value = def_._name._value
assert isinstance(value, TreeInstance)
assert value.class_value.py__name__() == 'str'
def test_sys_exc_info(Script):
code = 'import sys; sys.exc_info()'
none, def_ = Script(code + '[1]').infer()
# It's an optional.
assert def_.name == 'BaseException'
assert def_.type == 'instance'
assert none.name == 'NoneType'
none, def_ = Script(code + '[0]').infer()
assert def_.name == 'BaseException'
assert def_.type == 'class'
def test_sys_getwindowsversion(Script, environment):
# This should only exist on Windows, but type inference should happen
# everywhere.
definitions = Script('import sys; sys.getwindowsversion().major').infer()
if environment.version_info.major == 2:
assert not definitions
else:
def_, = definitions
assert def_.name == 'int'
def test_sys_hexversion(Script):
script = Script('import sys; sys.hexversion')
def_, = script.complete()
assert isinstance(def_._name, StubName), def_._name
assert typeshed.TYPESHED_PATH in def_.module_path
def_, = script.infer()
assert def_.name == 'int'
def test_math(Script):
def_, = Script('import math; math.acos()').infer()
assert def_.name == 'float'
value = def_._name._value
assert value
def test_type_var(Script, skip_python2):
def_, = Script('import typing; T = typing.TypeVar("T1")').infer()
assert def_.name == 'TypeVar'
assert def_.description == 'class TypeVar'
@pytest.mark.parametrize(
'code, full_name', (
('import math', 'math'),
('from math import cos', 'math.cos')
)
)
def test_math_is_stub(Script, code, full_name):
s = Script(code)
cos, = s.infer()
wanted = os.path.join('typeshed', 'stdlib', '2and3', 'math.pyi')
assert cos.module_path.endswith(wanted)
assert cos.is_stub() is True
assert cos.goto(only_stubs=True) == [cos]
assert cos.full_name == full_name
cos, = s.goto()
assert cos.module_path.endswith(wanted)
assert cos.goto(only_stubs=True) == [cos]
assert cos.is_stub() is True
assert cos.full_name == full_name
def test_goto_stubs(Script):
s = Script('import os; os')
os_module, = s.infer()
assert os_module.full_name == 'os'
assert os_module.is_stub() is False
stub, = os_module.goto(only_stubs=True)
assert stub.is_stub() is True
os_module, = s.goto()
def _assert_is_same(d1, d2):
assert d1.name == d2.name
assert d1.module_path == d2.module_path
assert d1.line == d2.line
assert d1.column == d2.column
@pytest.mark.parametrize('type_', ['goto', 'infer'])
@pytest.mark.parametrize(
'code', [
'import os; os.walk',
'from collections import Counter; Counter',
'from collections import Counter; Counter()',
'from collections import Counter; Counter.most_common',
'from collections import Counter; Counter().most_common',
])
def test_goto_stubs_on_itself(Script, code, type_):
"""
If goto_stubs is used on an identifier in e.g. the stdlib, we should goto
the stub of it.
"""
s = Script(code)
if type_ == 'infer':
def_, = s.infer()
else:
def_, = s.goto(follow_imports=True)
stub, = def_.goto(only_stubs=True)
script_on_source = Script(path=def_.module_path)
if type_ == 'infer':
definition, = script_on_source.infer(def_.line, def_.column)
else:
definition, = script_on_source.goto(def_.line, def_.column)
same_stub, = definition.goto(only_stubs=True)
_assert_is_same(same_stub, stub)
_assert_is_same(definition, def_)
assert same_stub.module_path != def_.module_path
# And the reverse.
script_on_stub = Script(
path=same_stub.module_path,
)
if type_ == 'infer':
same_definition, = script_on_stub.infer(same_stub.line, same_stub.column)
same_definition2, = same_stub.infer()
else:
same_definition, = script_on_stub.goto(same_stub.line, same_stub.column)
same_definition2, = same_stub.goto()
_assert_is_same(same_definition, definition)
_assert_is_same(same_definition, same_definition2)
<file_sep>parso>=0.7.0
|
ea1737bb9885db1809563a68f0616228f74e5ad4
|
[
"Python",
"Text",
"INI"
] | 7 |
INI
|
haoqixu/jedi
|
ea93dbc08eac0a1b8c39e15c554c0b0c4ce65591
|
5f00ac03ffa480c02538072dbefae0027c547000
|
refs/heads/main
|
<file_sep>package ru.levkopo.qrreader
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.util.DisplayMetrics
import android.view.ContextThemeWrapper
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.LinearLayout
import androidx.annotation.AttrRes
import androidx.annotation.ColorRes
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.MutableLiveData
import com.google.android.material.color.MaterialColors
const val WRAP_CONTENT = ViewGroup.LayoutParams.WRAP_CONTENT
const val MATCH_PARENT = ViewGroup.LayoutParams.MATCH_PARENT
var View.padding get() = paddingLeft
set(padding) = setPadding(padding, padding, padding, padding)
var View.paddingLR
get() = paddingLeft
set(value) = setPadding(value, paddingTop, value, paddingBottom)
var View.paddingTB
get() = paddingTop
set(value) = setPadding(paddingLeft, value, paddingRight, value)
var View.backgroundColor
get() = background.let {
if(it is ColorDrawable)
it.color
else 0
}
set(value) {
background = ColorDrawable(value)
}
inline fun <reified V: View> ViewGroup.view(
width: Int = WRAP_CONTENT,
height: Int = WRAP_CONTENT,
block: V.() -> Unit = {}) = addView(context.view(block), width, height)
inline fun <reified V: View> Context.view(
block: V.() -> Unit = {}): V = V::class.java.getConstructor(Context::class.java).newInstance(this).apply {
block()
}
inline fun <reified V: View> View.view(
block: V.() -> Unit = {}): V = context.view(block)
fun <V: View> V.onClick(block: V.() -> Unit = {}) {
setOnClickListener { this.block() }
}
fun Context.dp(dp: Int) = dp * (resources.displayMetrics.densityDpi.toFloat() /
DisplayMetrics.DENSITY_DEFAULT).toInt()
fun View.attr(@AttrRes attr: Int) = MaterialColors.getColor(this, attr)
fun Context.color(@ColorRes color: Int) = ContextCompat.getColor(this, color)
fun Context.string(@StringRes string: Int) = getString(string)
fun ViewGroup.box(
orientation: Int = LinearLayout.VERTICAL,
width: Int = WRAP_CONTENT,
height: Int = WRAP_CONTENT,
block: LinearLayout.() -> Unit = {}) = addView(context.box(orientation, block), width, height)
fun Context.box(
orientation: Int = LinearLayout.VERTICAL,
block: LinearLayout.() -> Unit = {}) = view<LinearLayout> {
this.orientation = orientation
padding = context.dp(10)
block()
}
inline fun <T> ViewGroup.state(
defaultValue: T? = null,
crossinline body: StateLayout<T?>.(T?, (T?) -> Unit) -> Unit
) = context.getAppCompatActivity()?.state(defaultValue, body)?.let {
addView(it, MATCH_PARENT, MATCH_PARENT)
} ?: Unit
inline fun <T> AppCompatActivity.state(
defaultValue: T? = null,
crossinline body: StateLayout<T?>.(T?, (T?) -> Unit) -> Unit
): StateLayout<T?> {
return view {
liveData.observe(this@state, { value ->
removeAllViews()
body(value) { liveData.postValue(it) }
})
liveData.postValue(defaultValue)
}
}
class StateLayout<T>(context: Context): FrameLayout(context) {
val liveData = MutableLiveData<T>()
}
fun Context.getAppCompatActivity(): AppCompatActivity? {
return when (this) {
is AppCompatActivity -> this
is ContextThemeWrapper -> baseContext.getAppCompatActivity()
else -> null
}
}<file_sep>package ru.levkopo.qrreader
import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Size
import android.widget.ScrollView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatTextView
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.core.content.ContextCompat
import androidx.lifecycle.LifecycleOwner
import com.google.common.util.concurrent.ListenableFuture
import com.google.mlkit.vision.barcode.Barcode
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
class MainActivity: AppCompatActivity() {
private lateinit var cameraProviderFuture: ListenableFuture<ProcessCameraProvider>
private lateinit var cameraExecutor: ExecutorService
private val analyzer = BarcodeImageAnalyzer()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
cameraExecutor = Executors.newSingleThreadExecutor()
cameraProviderFuture = ProcessCameraProvider.getInstance(this)
setContentView(box {
view<PreviewView> {
cameraProviderFuture.addListener({
val cameraProvider = cameraProviderFuture.get()
bindPreview(this, cameraProvider)
}, ContextCompat.getMainExecutor(this@MainActivity))
}
state<Barcode> { barcode, setBarcode ->
analyzer.onBarcode = {
setBarcode(it)
}
view<ScrollView> {
box {
barcode?.let {
when(it.valueType){
Barcode.TYPE_URL -> startActivity(Intent(Intent.ACTION_VIEW,
Uri.parse(barcode.url?.url)))
Barcode.TYPE_TEXT -> view<AppCompatTextView> {
text = barcode.rawValue
}
Barcode.TYPE_EMAIL -> startActivity(Intent(Intent.ACTION_VIEW,
Uri.parse("mailto:"
+ it.email?.address
+ "?subject=" + it.email?.subject + "&body=" + it.email?.body)))
Barcode.TYPE_GEO -> startActivity(Intent(Intent.ACTION_VIEW,
Uri.parse("geo:${barcode.geoPoint?.lat}," +
"${barcode.geoPoint?.lng}")))
}
}
}
}
}
})
}
@SuppressLint("UnsafeExperimentalUsageError")
private fun bindPreview(previewView: PreviewView, cameraProvider: ProcessCameraProvider) {
val preview = Preview.Builder()
.build()
val cameraSelector = CameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_BACK)
.build()
preview.setSurfaceProvider(previewView.surfaceProvider)
cameraProvider.bindToLifecycle(
this as LifecycleOwner,
cameraSelector,
preview
)
val imageAnalysis = ImageAnalysis.Builder()
.setTargetResolution(Size(1280, 720))
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.build()
imageAnalysis.setAnalyzer(cameraExecutor, analyzer)
cameraProvider.bindToLifecycle(
this as LifecycleOwner,
cameraSelector,
imageAnalysis,
preview
)
}
override fun onPause() {
super.onPause()
analyzer.lastValue = null
}
}<file_sep>package ru.levkopo.qrreader
import android.annotation.SuppressLint
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import com.google.mlkit.vision.barcode.Barcode
import com.google.mlkit.vision.barcode.BarcodeScanning
import com.google.mlkit.vision.common.InputImage
class BarcodeImageAnalyzer : ImageAnalysis.Analyzer {
lateinit var onBarcode: (Barcode) -> Unit
var lastValue: String? = null
override fun analyze(imageProxy: ImageProxy) {
scanBarcode(imageProxy)
}
@SuppressLint("UnsafeExperimentalUsageError", "UnsafeOptInUsageError")
private fun scanBarcode(imageProxy: ImageProxy) {
imageProxy.image?.let { image ->
val inputImage = InputImage.fromMediaImage(image, imageProxy.imageInfo.rotationDegrees)
val scanner = BarcodeScanning.getClient()
scanner.process(inputImage)
.addOnCompleteListener {
imageProxy.close()
if (it.isSuccessful) {
readBarcodeData(it.result as List<Barcode>)
}
}
}
}
private fun readBarcodeData(barcodes: List<Barcode>) {
if(barcodes.isNotEmpty()) {
val barcode = barcodes.last()
if(lastValue!=barcode.rawValue) {
onBarcode(barcode)
lastValue = barcode.rawValue
}
}
}
}
|
08aca7fe9518d37eb1493efdaebfeafd98582958
|
[
"Kotlin"
] | 3 |
Kotlin
|
levkopo/QRReader
|
59adb80bc10ab006aec9dd9bdd836badeae03844
|
7beece23ed96c42fb5bad76a6b9bc8060671502b
|
refs/heads/master
|
<file_sep>package com.cesgroup.imp.wotalk.factory;
import com.cesgroup.common.listener.SystemInitListener;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.tomcat.jdbc.pool.DataSource;
public abstract class QueryRunnerFactory {
private static QueryRunner qr ;
public static QueryRunner createQueryRunner(){
DataSource dataSource = (DataSource) SystemInitListener.getBean("dataSource-wotalk");
if(qr == null){
qr = new QueryRunner(dataSource);
}
return qr;
}
}
<file_sep>package com.cesgroup.imp.wotalk.entity;
public class OldUser {
private Integer userId;
private String loginName;
private String userName;
private Integer showOrder;
private String type;
private String phoneNum;
private String password;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getShowOrder() {
return showOrder;
}
public void setShowOrder(Integer showOrder) {
this.showOrder = showOrder;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
<file_sep>package com.cesgroup.imp.wotalk.entity;
public class OldOrgUser {
private Integer userId;
private Integer organizeId;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getOrganizeId() {
return organizeId;
}
public void setOrganizeId(Integer organizeId) {
this.organizeId = organizeId;
}
}
<file_sep>package com.cesgroup.imp.wotalk.web;
import com.cesgroup.common.web.NonEntityController;
import com.cesgroup.core.annotation.CesLog;
import com.cesgroup.imp.wotalk.service.ImportAuthService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
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;
@Controller
@RequestMapping(value = "/auth/imp")
public class AuthImportController extends NonEntityController<ImportAuthService>{
@Override
@Autowired
public void setService(ImportAuthService service) {
super.service = service;
}
@Override
public String getModelName() {
return "同步wotalk数据";
}
@RequestMapping(value = "/importWotalkData")
@ResponseBody
@RequiresPermissions(value = "/auth/imp/importWotalkData")
public boolean importWotalkData(){
getService().oneKeyImportAuthData();
return true;
}
}
<file_sep># auth_frame
springmvc+spring+hibernate+jpa的一套RBAC系统
<file_sep>package com.cesgroup.imp.wotalk.entity;
public class OldOrg {
private Integer organizeId;
private Integer parentId;
private String organizeName;
private String organizeTypeName;
private Integer showOrder;
public Integer getOrganizeId() {
return organizeId;
}
public void setOrganizeId(Integer organizeId) {
this.organizeId = organizeId;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public String getOrganizeName() {
return organizeName;
}
public void setOrganizeName(String organizeName) {
this.organizeName = organizeName;
}
public String getOrganizeTypeName() {
return organizeTypeName;
}
public void setOrganizeTypeName(String organizeTypeName) {
this.organizeTypeName = organizeTypeName;
}
public Integer getShowOrder() {
return showOrder;
}
public void setShowOrder(Integer showOrder) {
this.showOrder = showOrder;
}
}
<file_sep>package com.cesgroup.auth.reception;
import com.cesgroup.auth.user.entity.User;
import com.cesgroup.auth.user.service.UserService;
import com.cesgroup.core.web.NonEntityServiceController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
/**
* User: 管俊 <EMAIL>
* Date: 2016-9-4
* Time: 17:19
*/
@Controller
@RequestMapping(value = "/reception/auth")
public class AuthReceptionController extends NonEntityServiceController{
@Override
public String getModelName() {
return "auth匿名访问模块";
}
@RequestMapping(value = "/unlock")
@ResponseBody
public Map<String,Object> unlock(@RequestParam String loginName){
Map<String,Object> result = new HashMap<String, Object>();
User user = getService(UserService.class).getUserByLoginName(loginName);
if(user != null){
getService(UserService.class).unlockUser(user.getId());
result.put("message","解锁["+loginName+"]成功");
}else{
result.put("message","未能解锁["+loginName+"]用户");
}
return result;
}
}
<file_sep>package com.cesgroup.common.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import com.cesgroup.auth.user.entity.User;
import com.cesgroup.core.utils.CSRFTokenManager;
/**
* 未登录,登陆失效等过滤器
*
* @author 国栋
*
*/
public class SecurityFilter implements Filter
{
@Override
public void init(FilterConfig filterConfig) throws ServletException
{
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse rep = (HttpServletResponse) response;
HttpSession session = req.getSession();
String uri = req.getRequestURI();
if (uri.contains("/druid"))
{
chain.doFilter(request, response);
return;
}
User user = (User) session.getAttribute("CURRENTUSER");
String requestToken = CSRFTokenManager.getTokenFromRequest(req);
if (user != null)
{
boolean isAjaxRequest = isAjaxRequest(req);
String solidToken = CSRFTokenManager.getTokenForSession(session);
boolean isEqual = StringUtils.equals(solidToken, requestToken);
if (isAjaxRequest)// 如果是ajax请求,需要特殊处理。
{
if (!isEqual)
{
// // 踢回登陆
rep.setStatus(300469);
return;
}
}
}
else if (StringUtils.isNotBlank(requestToken))
{
rep.setStatus(300468);
return;
}
else if (user == null && "".equals(requestToken))
{
rep.setStatus(300467);
return;
}
chain.doFilter(request, response);
}
public static boolean isAjaxRequest(HttpServletRequest request)
{
String requestedWith = request.getHeader("X-Requested-With");
return requestedWith != null ? "XMLHttpRequest".equals(requestedWith) : false;
}
@Override
public void destroy()
{
}
}
<file_sep>package com.cesgroup.auth.test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;
/**
* spring test 测试的基类
*
* @author niklaus
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/spring-mvc.xml", "file:src/main/resources/applicationContext-project.xml","file:src/main/resources/applicationContext.xml"})
@ActiveProfiles(value = "development")
@TransactionConfiguration(transactionManager = "transactionManager")
@Transactional
public class AbstractContextControllerTest
{
}
<file_sep>package com.cesgroup.imp.wotalk.dao;
import com.cesgroup.imp.wotalk.entity.OldOrg;
import com.cesgroup.imp.wotalk.entity.OldOrgUser;
import com.cesgroup.imp.wotalk.entity.OldUser;
import java.sql.SQLException;
import java.util.List;
public interface OldAuthDao {
List<OldOrg> getOrgList() throws SQLException;
List<OldOrgUser> getOrgUserList() throws SQLException;
List<OldUser> getUserList() throws SQLException;
}
<file_sep>package com.cesgroup.imp.wotalk.service;
import com.cesgroup.core.service.NonEntityService;
/**
* Created by Administrator on 2016-8-24.
*/
public interface ImportAuthService extends NonEntityService{
void oneKeyImportAuthData();
}
|
7c0eeb8d256681054824d3411d73b0a1c02cd25e
|
[
"Markdown",
"Java"
] | 11 |
Java
|
KannShunn/auth_frame
|
8dee844ef0087524fba66ff926d2d8971c89a04d
|
6806f81ea11a8accb239b2c9ace7e54e1898482b
|
refs/heads/main
|
<file_sep>#!/usr/bin/env python
# coding: utf-8
# In[106]:
import numpy as np
import pandas as pd
from math import sqrt
from sklearn.metrics import mean_squared_error
from sklearn.metrics import pairwise_distances
from sklearn.neighbors import NearestNeighbors
# In[107]:
transaction = pd.read_csv("Transactions.csv")
outlet = pd.read_csv("Outlet.csv")
product = pd.read_csv("Product.csv")
# In[108]:
transaction.head()
# In[119]:
Rating = transaction.groupby("OutletKey")["NetValue"].sum().reset_index()
Rating = Rating.rename(columns = {"NetValue": "Sum","OutletKey":"Key"})
df = transaction.set_index('OutletKey').join(Rating.set_index('Key'),on = "OutletKey",how="left")
#df.sort_values(by='OutletKey', ascending=False)
df = df.reset_index()
df["Rating"] = (df["NetValue"]/df["Sum"]) * 10
# In[127]:
transaction = df[["OutletKey", "ProductKey","Rating"]]
# In[128]:
transaction.head()
# In[134]:
product_new = product[["ProductKey","SKU","SKUShortName"]]
product_new = product_new[product_new["ProductKey"] != -1]
# In[135]:
df = pd.merge(transaction,product_new,on = 'ProductKey')
# In[137]:
df.head()
# In[150]:
missing_pivot = df.pivot_table(values = 'Rating',index = 'OutletKey', columns = 'SKUShortName')
missing_pivot.head()
# In[151]:
rate = {}
rows_indexes = {}
for i,row in missing_pivot.iterrows():
rows = [x for x in range(0,len(missing_pivot.columns))]
combine = list(zip(row.index, row.values, rows))
rated = [(x,z) for x,y,z in combine if str(y) != 'nan']
index = [i[1] for i in rated]
row_names = [i[0] for i in rated]
rows_indexes[i] = index
rate[i] = row_names
# In[ ]:
rate
# In[153]:
pivot_table = df.pivot_table(values = 'Rating',index = 'OutletKey', columns = 'SKUShortName').fillna(0)
pivot_table = pivot_table.apply(np.sign)
# In[154]:
notrate = {}
notrate_indexes = {}
for i,row in pivot_table.iterrows():
rows = [x for x in range(0,len(missing_pivot.columns))]
combine = list(zip(row.index, row.values, rows))
idx_row = [(idx,col) for idx,val,col in combine if not val > 0]
indices = [i[1] for i in idx_row]
row_names = [i[0] for i in idx_row]
notrate_indexes[i] = indices
notrate[i] = row_names
# In[ ]:
# In[172]:
n = 10
cosine_nn = NearestNeighbors(n_neighbors=n, algorithm= 'brute', metric = 'cosine')
item_cosine_nn_fit = cosine_nn.fit(pivot_table.T.values)
item_distances, item_indices = item_cosine_nn_fit.kneighbors(pivot_table.T.values)
# In[173]:
items_dic = {}
for i in range(len(pivot_table.T.index)):
item_idx = item_indices[i]
col_names = pivot_table.T.index[item_idx].tolist()
items_dic[pivot_table.T.index[i]] = col_names
# In[174]:
items_dic
# In[175]:
item_rec = pd.DataFrame.from_dict(items_dic)
# In[178]:
item_rec = item_rec.T
item_rec.head()
# In[179]:
item_rec
# # Accuracy
# In[158]:
item_distances = 1 - item_distances
# In[160]:
predictions = item_distances.T.dot(pivot_table.T.values)/ np.array([np.abs(item_distances.T).sum(axis=1)]).T
# In[162]:
ground_truth = pivot_table.T.values[item_distances.argsort()[0]]
# In[164]:
def rmse(prediction,ground_truth):
prediction = prediction[ground_truth.nonzero()].flatten()
ground_truth = ground_truth[ground_truth.nonzero()].flatten()
return sqrt(mean_squared_error(prediction,ground_truth))
# In[165]:
error_rate = rmse(predictions,ground_truth)
print("Accuracy: {:.3f}".format(100 - error_rate))
print("RMSE: {:.5f}".format(error_rate))
# In[ ]:
|
06b4c3b0e9fe942dad5fb4f6f9e1e8f717ca6a40
|
[
"Python"
] | 1 |
Python
|
ShamenParis/Python
|
f0f5919f2bc54145724db3fc8cc7261bc6233cce
|
8ee461dba6390c53b7d09f9cff4bb930df566b41
|
refs/heads/master
|
<repo_name>lonelydatum/game-dental<file_sep>/app/Create.js
import Cup from './cup/Cup.js'
export default function () {
new Cup()
}<file_sep>/app/cup/ShuffleButton.js
//custom object that dispatch a `started` signal
class ShuffleButton extends Phaser.Group {
constructor() {
super(game, game.world, 'ShuffleButton')
this.holler = {
clicked : new signals.Signal()
};
this.image = game.add.image(0, 0, 'shuffle');
this.image.inputEnabled = true;
this.image.events.onInputDown.add(this.onClicked, this);
this.image.anchor.set(.5)
this.image.input.useHandCursor = true;
this.add(this.image)
this.text = game.add.text(0,0,'SHUFFLE', {fill:'#d24c9b', font:'20px Archivo Black'})
this.text.anchor.set(.5)
this.add(this.text)
this.x = game.world.centerX
this.y = 250
this.scale.set(0)
}
onClicked() {
this.hide()
}
hide() {
TweenMax.to(this.scale, .2, {x:0, y:0, alpha:0, ease:Power2.easeOut, onComplete:this.holler.clicked.dispatch})
}
show(delay=2) {
this.visible = true
TweenMax.to(this.scale, .5, {x:1, y:1, alpha:1, ease:Back.easeOut, delay, onComplete:this.spin.bind(this)})
}
spin() {
TweenMax.to(this.image, 1.5, {rotation: `+=${Math.PI}`, yoyo:true, repeat:2, repeatDelay:.5, ease:Back.easeOut, delay:.5})
}
}
export default ShuffleButton<file_sep>/app/cup/ButtonSelect.js
// import { observable, autorun } from 'mobx';
// import cupStore from './CupState.js'
// class ButtonSelect extends Phaser.Group{
// constructor() {
// super(game, game.world, 'button')
// this.holler = {
// clicked : new signals.Signal()
// };
// // this.callBack = callBack
// this.arrow = game.add.image(0, 0, 'pick');
// this.arrow.inputEnabled = true;
// this.arrow.events.onInputDown.add(this.onClicked, this);
// // var text = game.add.text(0, 0, 'Select', {font:'11px Arial', color: '#000000'});
// this.add(this.arrow)
// // this.add(text)
// this.name = 'buttt'
// // text.alignTo(buttonBG, Phaser.TOP_CENTER, 0, -23)
// // text.y = 3
// }
// onClicked() {
// this.holler.clicked.dispatch()
// }
// hide() {
// // this.visible = false
// }
// show() {
// // this.visible = true
// }
// }
// export default ButtonSelect<file_sep>/app/cup/Cat.js
import { observable, autorun } from 'mobx';
import cupStore from './CupState.js'
import _ from 'lodash'
class Cat extends Phaser.Sprite {
constructor() {
super(game, 0 , 0, 'cat')
game.stage.addChild(this)
this.tw = {
yoyo:true,
repeat:1,
ease:Back.easeOut,
repeatDelay:.5
}
this.speed = .3
this.anchor.set(.5, 0)
this.visible = false;
}
random() {
this.visible = true;
this.tl = new TimelineMax()
const list = [this.top, this.right, this.left]
const index = _.random(0, 2)
list[index].call(this)
}
show() {
this.right()
this.left()
}
top() {
this.tl.set(this, {rotation:Math.PI, x:game.world.centerX, y:0})
this.tl.to(this, this.speed, {...this.tw, y:this.height})
}
left() {
this.tl.set(this, {rotation:Math.PI / 2, x:0, y:game.world.centerY * .5})
this.tl.to(this, this.speed,{...this.tw, x:this.height}, "+=1")
}
right() {
this.tl.set(this, {rotation:-Math.PI / 2, x:game.width, y:game.world.centerY * .5})
this.tl.to(this, this.speed,{...this.tw, x:game.width-this.height}, "+=1")
}
}
export default Cat<file_sep>/app/cup/Cup.js
import { observable, autorun } from 'mobx';
import cupStore from './CupState.js'
import PlayAgain from './PlayAgain.js'
import CupItem from './CupItem.js'
import CupScore from './CupScore.js'
import Cat from './Cat.js'
import ShuffleButton from './ShuffleButton.js'
import _ from 'lodash'
class Cup {
constructor() {
this.cupList = []
const table = game.add.sprite(0, 0, 'table')
table.scale.set(1)
table.anchor.set(.5)
table.x = game.world.centerX
table.y = 1100
const playAgain = new PlayAgain()
playAgain.reset.add(this.reset.bind(this))
const shuffleButton = new ShuffleButton()
shuffleButton.holler.clicked.add( this.selected.bind(this) )
this.createScore()
this.createCups()
window.game.stage.backgroundColor = "#FFFFFF";
autorun( () => {
console.log(cupStore.status);
if(cupStore.status === cupStore.STATUS_SHUFFLE) {
shuffleButton.show()
}
if(cupStore.tartarList.length>=10) {
ga('send', {'hitType': 'event', 'eventCategory': 'game-dental', 'eventAction': 'finished', 'eventLabel': 'gar' });
playAgain.show()
shuffleButton.visible = false
}
} )
this.cat = new Cat()
}
reset() {
this.score.reset()
cupStore.playAgain()
}
selected() {
cupStore.statusUpdate(cupStore.STATUS_SHUFFLING)
const tl = new TimelineMax({onComplete: this.onCompleteShuffle})
this.cupList.forEach((cupItem) => {
tl.add(cupItem.showHide(), (cupItem.id*.2)+.5)
})
tl.add(this.shuffle())
if(cupStore.getDifficulty().speed <= .6) {
TweenMax.delayedCall(_.random(1.8,3), this.cat.random.bind(this.cat))
}
}
createScore() {
this.score = new CupScore()
}
shuffle() {
const tl = new TimelineMax( {repeat:cupStore.getDifficulty().repeat} )
tl.add( () => {
cupStore.randomIdList()
}, `+=${(cupStore.getDifficulty().speed)+.1}` )
return tl
}
onCompleteShuffle() {
TweenMax.delayedCall(1, ()=>{
cupStore.statusUpdate(cupStore.STATUS_SELECT)
})
}
createCups() {
this.cupGroup = game.add.group();
this.cupList = cupStore.idList.map((dataItem, index) => {
const cupItem = new CupItem(index)
this.cupGroup.add(cupItem)
return cupItem
})
}
}
export default Cup
<file_sep>/app/Preload.js
import _ from 'lodash'
function loadUser(user) {
return {
cup: `images/users/${user}/cup.png`,
apple: `images/users/${user}/apple.png`,
cupcake: `images/users/${user}/cupcake.png`,
donut: `images/users/${user}/donut.png`
}
}
// window.WebFontConfig = {
// // 'active' means all requested fonts have finished loading
// // We set a 1 second delay before calling 'createText'.
// // For some reason if we don't the browser cannot render the text the first time it's created.
// active: function() { game.time.events.add(Phaser.Timer.SECOND, createText, this); },
// // The Google Fonts we want to load (specify as many as you like in the array)
// google: {
// families: ['Archivo']
// }
// };
export default function () {
const profiles = ['gar', 'eliot']
const user = loadUser(profiles[_.random(0,1)])
game.load.image('shuffle', 'images/buttons/shuffle.png');
game.load.image('pick', 'images/buttons/pick.png');
game.load.image('table', 'images/table.jpg');
game.load.image('cup', user.cup);
game.load.image('apple', user.apple);
game.load.image('cupcake', user.cupcake);
game.load.image('donut', user.donut);
game.load.image('tooth-default', 'images/teeth/tooth-default.png');
game.load.image('tooth-good', 'images/teeth/tooth-good.png');
game.load.image('tooth-bad', 'images/teeth/tooth-bad.png');
game.load.image('cat', 'images/cat.png');
// game.load.script('webfont', '//fonts.googleapis.com/css?family=Archivo+Black');
}
|
88ac8f50d40e7f53d709640bcd7bbd02157f74d7
|
[
"JavaScript"
] | 6 |
JavaScript
|
lonelydatum/game-dental
|
6b8014fdc32f250d55c64eff9da214d913da1cc7
|
1b7526e1418b97825aa2c4eb3ded4c50b1a093e5
|
refs/heads/master
|
<file_sep>import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
import java.util.List;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
public class Server {
private int tcpPort;
private int udpPort;
private Inventory inv;
private OrderHistory orders;
private final Logger log = Logger.getLogger(Server.class.getCanonicalName());
public Server(int tcpPort, int udpPort, String fileName) {
super();
this.tcpPort = tcpPort;
this.udpPort = udpPort;
inv = new Inventory(fileName);
orders = new OrderHistory();
try {
FileHandler fh = new FileHandler("server_log_" + System.currentTimeMillis() + ".log");
fh.setFormatter(new SimpleFormatter());
log.addHandler(fh);
logInfo("Server initializing...");
logInfo("Server TCP Port: " + tcpPort);
logInfo("Server UDP Port: " + udpPort);
logInfo("Server Inventory File: " + fileName);
logInfo("Server init complete");
logInfo("--------------------------------");
} catch (SecurityException | IOException e) {
e.printStackTrace();
}
}
public synchronized void logInfo(String mesg) {
log.log(Level.INFO, mesg);
}
public synchronized void logWarn(String mesg) {
log.log(Level.WARNING, mesg);
}
/**
* Run the server. Creates an new thread running the UDP listener, and new
* threads for each incoming TCP connection.
*/
public void run() {
// start async udp responder here
logInfo("Starting UDP thread");
Thread udp_thread = new Thread(new UdpServerTask(this, udpPort));
udp_thread.start();
// listen for incoming TCP requests
logInfo("Starting TCP listen loop");
try (ServerSocket serverSocket = new ServerSocket(tcpPort);) {
while (true) {
Socket clientSocket = serverSocket.accept();
logInfo("Accepted TCP connection from " + clientSocket.getInetAddress() + " on port "
+ clientSocket.getLocalPort());
Thread t = new Thread(new TcpServerTask(this, clientSocket));
t.start();
}
} catch (IOException e) {
e.printStackTrace();
logWarn("ERROR in TCP loop: " + e.getMessage());
}
}
/**
* Parse a received object and dispatch to correct method.
*
* @param receivedObject
* object received from client
* @return response string
*/
public String processObject(Object receivedObject) {
String response = "Unknown or bad command received";
if (receivedObject.getClass() == ClientOrder.class)
response = processRequest((ClientOrder) receivedObject);
else if (receivedObject.getClass() == ClientCancel.class)
response = processRequest((ClientCancel) receivedObject);
else if (receivedObject.getClass() == ClientSearch.class)
response = processRequest((ClientSearch) receivedObject);
else if (receivedObject.getClass() == ClientProductList.class)
response = processRequest((ClientProductList) receivedObject);
return response;
}
/**
* Process an order request.
*
* @param order
* a ClientOrder object with purchase details
* @return response string
*/
public String processRequest(ClientOrder order) {
StringBuilder response = new StringBuilder();
int stock = inv.getItemCount(order.productName);
int quantity = order.quantity;
if (stock == -1)
response.append("Not Available - We do not sell this product");
else if (stock < quantity)
response.append("Not Available - Not enough items");
else {
orders.addOrder(order);
inv.removeItem(order.productName, quantity);
response.append("Your order has been placed, ");
response.append(order.orderID);
response.append(" ");
response.append(order.userName);
response.append(" ");
response.append(order.productName);
response.append(" ");
response.append(order.quantity);
}
logInfo("Processed purchase request: " + order);
return response.toString();
}
/**
* Process a cancel request: cancel an active order.
*
* @param cancel
* a ClientCancel object with orderID
* @return response string
*/
public String processRequest(ClientCancel cancel) {
ClientOrder order = orders.cancelOrderByID(cancel.orderID);
logInfo("Processed cancel request: " + order);
if (order != null) {
inv.addItem(order.productName, order.quantity);
return "Order " + cancel.orderID + " is cancelled";
}
return (cancel.orderID + " not found, no such order");
}
/**
* Process a search request: search for orders by username.
*
* @param search
* a ClientSearch object with username
* @return response string
*/
public String processRequest(ClientSearch search) {
List<ClientOrder> orderList = orders.searchOrdersByUser(search.username);
StringBuilder response = new StringBuilder();
if (orderList.size() == 0) {
response.append("No order found for ");
response.append(search.username);
} else
for (ClientOrder order : orderList) {
response.append(order.orderID);
response.append(", ");
response.append(order.productName);
response.append(", ");
response.append(order.quantity);
response.append((order.isActive) ? "" : " (cancelled)");
response.append(":");
}
logInfo("Processed search request: user=" + search.username);
return response.toString();
}
/**
* Process an list request: list the inventory.
*
* @param list
* a ClientList object
* @return response string
*/
public String processRequest(ClientProductList list) {
StringBuilder response = new StringBuilder();
String[] names = inv.getItemNames().toArray(new String[] {});
Arrays.sort(names);
for (String item : names) {
response.append(item);
response.append(", ");
response.append(inv.getItemCount(item));
response.append(":");
}
logInfo("Processed list request");
return response.toString();
}
/**
* Run the main program
*
* @param args
* command line input. Expects [tcpPort] [udpPort] [inventory
* file]
*/
public static void main(String[] args) {
int tcpPort;
int udpPort;
if (args.length != 3) {
System.out.println("ERROR: Provide 3 arguments");
System.out.println("\t(1) <tcpPort>: the port number for TCP connection");
System.out.println("\t(2) <udpPort>: the port number for UDP connection");
System.out.println("\t(3) <file>: the file of inventory");
System.exit(-1);
}
tcpPort = Integer.parseInt(args[0]);
udpPort = Integer.parseInt(args[1]);
String fileName = args[2];
Server server = new Server(tcpPort, udpPort, fileName);
server.run();
}
}<file_sep># Distributed Agreement
Weighted PAXOS
<file_sep>import java.io.Serializable;
public class ClientCancel implements Serializable {
private static final long serialVersionUID = 1L;
public int orderID;
public ClientCancel(int id) {
orderID = id;
}
public ClientCancel(String id) {
this(Integer.parseInt(id));
}
}
<file_sep>import java.io.Serializable;
public class ClientSearch implements Serializable {
private static final long serialVersionUID = 1L;
public String username;
public ClientSearch(String username) {
super();
this.username = username;
}
}
<file_sep># Weighted Paxos
This is an implementation of weighted Paxos, done as a final project for Distributed Systems at UT Austin, Fall 2017.
## Building
This project has an `ant` build file. With `ant` installed, simply running the command `ant` should build the project and create the jar file.
## Running
There are several scripts for convenience. The list of commands below show how to perform some of the basic tasks. In addition, there are several directories under `./demo/` that have simple `run.sh` scripts which will launch a Paxos system automatically.
## Common useful commands
Kill all and remove pids files
```
python sbin/killPaxosNodes.py `cat pids_*` ; rm -rf pids_*
```
Run ten nodes
```
python sbin/launchNPaxos.py inputs/tenNodes.txt
```
Kill all, remove pids files, build, run ten nodes
```
python sbin/killPaxosNodes.py `cat pids_*` ; rm -rf pids_* ; ant ; python sbin/launchNPaxos.py inputs/tenNodes_unreliable_diffweights.txt
```
Kill first node in pids_0
```
cat pids_0.txt | cut -d' ' -f1 | xargs python sbin/killPaxosNodes.py
```
Restart node 0
```
python sbin/restartPaxos.py inputs/tenNodes.txt states/node_0.state
```
show INFO logs for proc 0
```
cat logs/log_0.log | grep INFO
```
manual kill ALL PretendApp procs using
```
jps | grep PretendApp | cut -f1 -d' ' | xargs kill
```
look for pretendapp messages on log0
```
cat logs/log_0.log | grep -i pretendapp
```
look for crash messages on all logs
```
cat logs/log_*.log | grep -i crash
```
scrape paxos round times
```
cat logs/log_0.log | grep -i pretendapp | grep time | rev | cut -d' ' -f3 | rev > times.dat
```
<file_sep>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.util.Scanner;
public class Client {
private String hostAddress;
private int tcpPort;
private int udpPort;
private boolean modeIsTCP = false; // TCP is default mode, other mode is UDP
private Socket tcpSocket = null;
private ObjectOutputStream out = null;
private BufferedReader in = null;
private DatagramSocket udpSocket;
public Client(String hostAddress, int tcpPort, int udpPort) {
super();
this.hostAddress = hostAddress;
this.tcpPort = tcpPort;
this.udpPort = udpPort;
try {
udpSocket = new DatagramSocket();
} catch (SocketException e) {
e.printStackTrace();
}
}
/**
* Send an object to the server, method depending on whether mode is TCP or
* UDP
*
* @param o
* the object to send
*/
public void sendObject(Object o) {
try {
if (modeIsTCP)
out.writeObject(o);
else
UdpObjectIO.sendObject(o, InetAddress.getByName(hostAddress), udpPort, udpSocket);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* receive a String from the server, method depending on whether mode is TCP
* or UDP
*
* @param o
* the object to send
*/
public String receiveString() {
try {
if (modeIsTCP) {
return in.readLine();
} else {
return (String) UdpObjectIO.receiveObject(udpSocket, 1024).object;
}
} catch (IOException e) {
e.printStackTrace();
}
return "could not receive string";
}
/**
* Connect to the server via TCP
*/
public void connectTCP() {
if (modeIsTCP)
return;
modeIsTCP = true;
try {
tcpSocket = new Socket(hostAddress, tcpPort);
out = new ObjectOutputStream(tcpSocket.getOutputStream());
in = new BufferedReader(new InputStreamReader(tcpSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Set the network protocol to TCP or UDP
*
* @param tokens
* string input from command line
* @return server response
*/
public String setMode(String[] tokens) {
// expecting setmode T | U
if (tokens.length < 2) {
return "ERROR: Not enough tokens in setmode string" + "\nERROR: Expected format: setmode T | U";
} else {
String mode = tokens[1].toUpperCase();
if (mode.equals("T")) {
udpSocket.close();
connectTCP();
return "mode: TCP";
} else if (mode.equals("U")) {
modeIsTCP = false;
try {
tcpSocket.close();
udpSocket.connect(InetAddress.getByName(hostAddress), udpPort);
} catch (IOException e) {
e.printStackTrace();
}
return "mode: UDP";
} else {
// unrecognized mode, setting to TCP (since that is the default
// mode)
udpSocket.close();
connectTCP();
return ("ERROR: unrecognized mode: " + mode + "\nmode:TCP");
}
}
}
/**
* Create and send a purchase order to the server
*
* @param tokens
* string input from command line
* @return server response
*/
public String purchase(String[] tokens) {
if (tokens.length < 4) {
return ("ERROR: Not enough tokens in purchase string"
+ "\nERROR: Expected format: purchase <user-name> <product-name> <quantity>");
} else {
String userName = tokens[1];
String productName = tokens[2];
int quantity = Integer.parseInt(tokens[3]);
ClientOrder order = new ClientOrder(userName, productName, quantity);
sendObject(order);
return receiveString();
}
}
/**
* Create and send an order cancel request to the server
*
* @param tokens
* string input from command line
* @return server response
*/
public String cancel(String[] tokens) {
if (tokens.length < 2) {
return ("ERROR: Not enough tokens in cancel string" + "\nERROR: Expected format: cancel <order-id>");
} else {
String orderID = tokens[1];
sendObject(new ClientCancel(orderID));
String cancelConf = receiveString().replace(":", "\n");
return cancelConf;
}
}
/**
* Create and send a user search request to the server
*
* @param tokens
* string input from command line
* @return server response
*/
public String search(String[] tokens) {
if (tokens.length < 2) {
return ("ERROR: Not enough tokens in search string" + "\nERROR: Expected format: search <user-name>");
} else {
String userName = tokens[1];
sendObject(new ClientSearch(userName));
String orders = receiveString().replace(":", "\n");
return orders;
}
}
/**
* Create and send an inventory list request to the server
*
* @return server response
*/
public String list() {
sendObject(new ClientProductList());
String list = receiveString().replace(":", "\n");
return list;
}
/**
* Run the client command-line interface
*/
public void run() {
try (Scanner sc = new Scanner(System.in);) {
System.out.print(">>>");
// connect TCP by default
connectTCP();
// main command loop
while (sc.hasNextLine()) {
String[] tokens = sc.nextLine().split(" ");
String response = "";
if (tokens[0].equals("setmode"))
response = setMode(tokens);
else if (tokens[0].equals("purchase"))
response = purchase(tokens);
else if (tokens[0].equals("cancel"))
response = cancel(tokens);
else if (tokens[0].equals("search"))
response = search(tokens);
else if (tokens[0].equals("list"))
response = list();
else
response = "ERROR: No such command\n";
System.out.print(response + "\n>>>");
}
}
}
/**
* Main function.
*/
public static void main(String[] args) {
if (args.length != 3) {
System.out.println("ERROR: Provide 3 arguments");
System.out.println("\t(1) <hostAddress>: the address of the server");
System.out.println("\t(2) <tcpPort>: the port number for TCP connection");
System.out.println("\t(3) <udpPort>: the port number for UDP connection");
System.exit(-1);
}
String hostAddress = args[0];
int tcpPort = Integer.parseInt(args[1]);
int udpPort = Integer.parseInt(args[2]);
Client client = new Client(hostAddress, tcpPort, udpPort);
client.run();
}
}
<file_sep>import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Set;
public class Inventory {
private HashMap<String, Integer> inventory;
public Inventory(String inputFile) {
inventory = new HashMap<>(10);
parseFile(inputFile);
}
public Set<String> getItemNames() {
return inventory.keySet();
}
public int getItemCount(String item) {
if (inventory.containsKey(item))
return inventory.get(item);
return -1;
}
public synchronized void removeItem(String item, int amount) {
if (inventory.containsKey(item) && inventory.get(item) > 0)
inventory.put(item, inventory.get(item) - amount);
}
public synchronized void addItem(String item, int amount) {
if (inventory.containsKey(item))
inventory.put(item, inventory.get(item) + amount);
else
inventory.put(item, amount);
}
private void parseFile(String inputFile) {
try (BufferedReader br = new BufferedReader(new FileReader(inputFile))) {
String line;
while ((line = br.readLine()) != null) {
String[] tokens = line.split(" ");
inventory.put(tokens[0], Integer.parseInt(tokens[1]));
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Inventory inv = new Inventory("input/input.txt");
System.out.println(inv.getItemNames());
System.out.println(inv.getItemCount("ps4"));
}
}
<file_sep>#! /bin/bash
id=$1
file=$2
restart=$3
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/.."
dist_classpath=${DIR}/dist/lib
lib_classpath=${DIR}/libs
java -classpath $dist_classpath/Paxos.jar:$lib_classpath/gson-2.6.2.jar:. paxos.application.PretendApp $id $file $restart
<file_sep>import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.net.Socket;
public class TcpServerTask implements Runnable {
Socket clientSocket;
Server server;
public TcpServerTask(Server server, Socket clientSocket) {
super();
this.server = server;
this.clientSocket = clientSocket;
}
@Override
public void run() {
try (PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());) {
Object receivedObject;
while ((receivedObject = in.readObject()) != null) {
String response = server.processObject(receivedObject);
out.println(response);
}
} catch (EOFException e) {
server.logWarn("Connection to " + clientSocket.getInetAddress() + " ended unexpectedly.");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
|
a859c6941759096cdc702b14d7e528125426a822
|
[
"Markdown",
"Java",
"Shell"
] | 9 |
Java
|
ericaddison/Distributed_Systems
|
d5c08a7e9225c22159e3a0a4e7e69f7bf9bc9ae2
|
df992bbbb6e5a04f3dbe1777e31c640d8eb6cab6
|
refs/heads/master
|
<file_sep>package com.postnov.pivot.controller;
import com.postnov.pivot.entity.SourceDataSQLException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import java.sql.SQLException;
@ControllerAdvice
public class ExceptionHandlerSourceData extends ResponseEntityExceptionHandler {
@ExceptionHandler(SQLException.class)
protected ResponseEntity<Object> sqlException(SQLException ex) {
SourceDataSQLException sourceDataSQLException = new SourceDataSQLException("SQLException", ex.getMessage());
return new ResponseEntity<>(sourceDataSQLException, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
<file_sep>package com.postnov.pivot.service;
import com.postnov.pivot.entity.SourceData;
import org.springframework.http.ResponseEntity;
import java.sql.SQLException;
import java.util.List;
public interface SourceDataService {
ResponseEntity<List<SourceData>> getPivotDataFromDb(String row, String col) throws SQLException;
}
<file_sep>package com.postnov.pivot.entity;
public class SourceData {
private String row;
private String col;
private String value;
public SourceData() {
}
public String getRow() {
return row;
}
public void setRow(String row) {
this.row = row;
}
public String getCol() {
return col;
}
public void setCol(String col) {
this.col = col;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
<file_sep>## Решение задачи - сводная таблица (Pivot table) для датасета "Налоги РФ"
### Цели
1. Работа с кодом Java SE, Spring Boot
2. Работа с БД, понимание SQL
3. Понимание принципов плоского и многомерного представления данных.
4. Проектирование и реализация API.
5. Работа с HTTP API, JSON.
6. Инструменты для CI/CD
7. Документирование
8. Файл БД dataset/data.sqlite содержит единственную таблицу source_data (датасет) с 10К записей по налогам РФ за 2010-2015 годы. Нужно реализовать API для отображения датасета в виде двухмерной сводной таблицы на стеке JavaSE/Spring Boot
### Описание колонок таблицы source_data
```
a - группа налога
b - подгруппа налога
c - округ РФ
d - регион РФ
y - год
v - значение
```
### Серверная часть
Принимает запросы клиента по HTTP API, выполняет запросы в БД и отдает результат в виде JSON.
Вызов API GET принимает два параметра
```
row - название столбца БД для группировки таблицы по горизонтали.
col - название столбца БД для группировки таблицы по вертикали.
Каждый параметр может принимать значения a,b,c,d,y.
```
http://localhost:8080/?row=b&col=d
В результате запроса в БД sqlite возвращается массив JSON, где каждый элемент - результат агрегации по указанным столбцам таблицы
### пример возвращаемого значения:
```
[
{"row" : "Транспортный налог", "col" : "Краснодарский край", "value" : 1},
{"row" : "Транспортный налог", "col" : "Ростовская область", "value" : 2},
{"row" : "Земельный налог", "col" : "Краснодарский край", "value" : 3},
{"row" : "Земельный налог", "col" : "Ростовская область", "value" : 4}
]
```
### Реализация:
1. Использовались Java SE 11 и Spring Boot.
2. Так как в таблице source_data нет primary_key, то было принято решение выполнить реализацию задачи с использованием jdbc.
3. При разработке использовалась база данных sqlite.
4. Проект скачивается к себе на локальную машину и запускается с использованием Intellij Idea.
- подключаем базу данных sqlite, указываем в ней URL (путь к файлу data.sqlite, который находится в главной директории проекта.)
- переходим в Project Structure, выбираем там 11 java.
- переходим в File->Settings->Gradle, устанавливаем там java 11.
<file_sep>spring.jpa.database-platform=com.postnov.pivot.configuration.SQLiteDialect
spring.jpa.hibernate.ddl-auto=create-drop
name.table=source_data
data.source.url=jdbc:sqlite:data.sqlite
driver.class.name=org.sqlite.JDBC
<file_sep>package com.postnov.pivot.entity;
public class SourceDataSQLException {
private String typeException;
private String exceptionMessage;
public String getTypeException() {
return typeException;
}
public void setTypeException(String typeException) {
this.typeException = typeException;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = exceptionMessage;
}
public SourceDataSQLException(String typeException, String exceptionMessage) {
this.typeException = typeException;
this.exceptionMessage = exceptionMessage;
}
}
<file_sep>package com.postnov.pivot.service.impl;
import com.postnov.pivot.entity.SourceData;
import com.postnov.pivot.repository.SourceDataRepository;
import com.postnov.pivot.service.SourceDataService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import java.sql.SQLException;
import java.util.List;
@Service
public class SourceDataServiceImpl implements SourceDataService {
private final SourceDataRepository sourceDataRepository;
@Value("${name.table}")
private String nameTable;
public SourceDataServiceImpl(SourceDataRepository sourceDataRepository) {
this.sourceDataRepository = sourceDataRepository;
}
@Override
public ResponseEntity<List<SourceData>> getPivotDataFromDb(String row, String col) throws SQLException {
List<SourceData> sourceDataList = sourceDataRepository.getPivotDataFromDb(row, col, nameTable);
return new ResponseEntity<List<SourceData>>(sourceDataList, HttpStatus.OK);
}
}
|
ca2635a11b6ab8312def7add2ad4732f0f859fba
|
[
"Markdown",
"Java",
"INI"
] | 7 |
Java
|
AnatoliyPostnov/PivotTable
|
e68e19c0e1671aeb80bf0b96340e274e03de4d85
|
0a45ae1044d11b3f232e2b1030b8937128786f14
|
refs/heads/master
|
<repo_name>DTMichael/ActiveMQ<file_sep>/src/main/java/com/atguigu/CunsumeTest.java
package com.atguigu;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.junit.jupiter.api.Test;
import javax.jms.*;
import javax.management.Query;
import javax.xml.soap.Text;
import java.io.IOException;
public class CunsumeTest {
public static final String ACTIVEMQ_URL="tcp://192.168.125.140:61616";
public static final String QUERY_NAME="query02";
//同步阻塞方式(recive())
//订阅者或接受者调用MessageConsume的recive方法来接受消息时,recive能够在接收到消息之前一直阻塞
//每个消息只能由一个消费者消费
public void Consume() throws JMSException {
System.out.println("消费者1已经成功接收到消息");
ActiveMQConnectionFactory activeMQConnectionFactory=new ActiveMQConnectionFactory(ACTIVEMQ_URL);
Connection connection=activeMQConnectionFactory.createConnection();
connection.start();
Session session=connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue query=session.createQueue(QUERY_NAME);
MessageConsumer messageConsumer=session.createConsumer(query);
while(true)
{
//同步阻塞方式(recive)
TextMessage textMessage = (TextMessage) messageConsumer.receive(8000);
if(null!=textMessage)
{
System.out.println("*******消费者接收到消息*****"+textMessage.getText());
}
else{
break;
}
}
messageConsumer.close();
session.close();
connection.close();
}
//通过监听的方法来获得消息
public static void main(String[] args) throws JMSException, IOException {
System.out.println("1号消费者就位");
ActiveMQConnectionFactory activeMQConnectionFactory=new ActiveMQConnectionFactory(ACTIVEMQ_URL);
Connection connection=activeMQConnectionFactory.createConnection();
connection.start();
Session session=connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue query=session.createQueue(QUERY_NAME);
MessageConsumer messageConsumer=session.createConsumer(query);
//异步非阻塞方式(通过setMessageListener注册一个消息监听器,当消息到达,系统自动调用监听器MessageListener的onmessage方法)
messageConsumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
if(message!=null&&message instanceof TextMessage)
{
TextMessage textMessage=(TextMessage)message;
try {
System.out.println("消费者接收到消息"+textMessage.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
}
});
System.in.read();
messageConsumer.close();
session.close();
connection.close();
}
}
<file_sep>/src/main/java/com/atguigu/jmsproduce_topic/consume_topic.java
package com.atguigu.jmsproduce_topic;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
import java.io.IOException;
public class consume_topic {
public static final String ACTIVEMQ_URL="tcp://192.168.125.140:61616";
public static final String TOPIC_NAME="atguigu_topic";
//同步阻塞方式(recive())
//订阅者或接受者调用MessageConsume的recive方法来接受消息时,recive能够在接收到消息之前一直阻塞
//每个消息只能由一个消费者消费
public void Consume() throws JMSException {
System.out.println("消费者1已经成功接收到消息");
ActiveMQConnectionFactory activeMQConnectionFactory=new ActiveMQConnectionFactory(ACTIVEMQ_URL);
Connection connection=activeMQConnectionFactory.createConnection();
connection.start();
Session session=connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue query=session.createQueue(TOPIC_NAME);
MessageConsumer messageConsumer=session.createConsumer(query);
while(true)
{
//同步阻塞方式(recive)
TextMessage textMessage = (TextMessage) messageConsumer.receive(8000);
if(null!=textMessage)
{
System.out.println("*******消费者接收到消息*****"+textMessage.getText());
}
else{
break;
}
}
messageConsumer.close();
session.close();
connection.close();
}
//通过监听的方法来获得消息
public static void main(String[] args) throws JMSException, IOException {
System.out.println("2号消费者就位");
ActiveMQConnectionFactory activeMQConnectionFactory=new ActiveMQConnectionFactory(ACTIVEMQ_URL);
Connection connection=activeMQConnectionFactory.createConnection();
connection.start();
Session session=connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic=session.createTopic(TOPIC_NAME);
MessageConsumer messageConsumer=session.createConsumer(topic);
// 异步非阻塞方式(通过setMessageListener注册一个消息监听器,当消息到达,系统自动调用监听器MessageListener的onmessage方法)
/*messageConsumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
if(message!=null&&message instanceof TextMessage)
{
TextMessage textMessage=(TextMessage)message;
try {
System.out.println("消费者接收到消息"+textMessage.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
}
});*/
//代替原有的匿名内部类,采用lambda表达式
messageConsumer.setMessageListener((message)->{
if(message!=null&&message instanceof TextMessage)
{
TextMessage textMessage=(TextMessage)message;
try {
System.out.println("消费者接收到TOPIC消息"+textMessage.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
});
System.in.read();
messageConsumer.close();
session.close();
connection.close();
}
}
|
ae25e24344b166d8771d241f2920d675e99c90e4
|
[
"Java"
] | 2 |
Java
|
DTMichael/ActiveMQ
|
2c3692a4a41c445e236ed4a14213b7c16a2d4144
|
20ffebd62034c5131e1008a612620b270d8aa31b
|
refs/heads/master
|
<repo_name>sirjaden92/d912pxy<file_sep>/d912pxy/d912pxy_vfs.cpp
/*
MIT License
Copyright(c) 2018-2019 megai2
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 "stdafx.h"
d912pxy_vfs_file_header s_headerTable[PXY_VFS_MAX_FILES_PER_BID];
d912pxy_vfs::d912pxy_vfs()
{
}
d912pxy_vfs::~d912pxy_vfs()
{
for (int i = 0; i != PXY_VFS_MAX_BID; ++i)
{
d912pxy_vfs_entry* item = &items[i];
if (item->m_vfsBlocks != NULL)
{
fflush(item->m_vfsBlocks);
fclose(item->m_vfsBlocks);
delete item->m_vfsFileOffsets;
if (item->m_vfsCache)
PXY_FREE(item->m_vfsCache);
}
}
if (writeAllowed)
{
CloseHandle(lockFile);
}
}
void d912pxy_vfs::Init(const char * lockPath)
{
lockFile = CreateFileA(lockPath, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_FLAG_DELETE_ON_CLOSE, NULL);
if (lockFile == INVALID_HANDLE_VALUE)
{
writeAllowed = 0;
}
else {
DWORD pid = GetProcessId(GetCurrentProcess());
DWORD ret = 0;
WriteFile(lockFile, &pid, 4, &ret, NULL);
writeAllowed = 1;
}
ZeroMemory(items, sizeof(d912pxy_vfs_entry)*PXY_VFS_MAX_BID);
for (int i = 0; i != PXY_VFS_MAX_BID; ++i)
{
items[i].lock.Init();
}
}
void d912pxy_vfs::SetRoot(wchar_t * rootPath)
{
sprintf(m_rootPath, "%s/%ws", d912pxy_helper::GetFilePath(FP_VFS_PREFIX)->s, rootPath);
}
void* d912pxy_vfs::LoadVFS(d912pxy_vfs_id_name* id, UINT memCache)
{
char fn[4096];
sprintf(fn, "%s/%s.pck", m_rootPath, id->name);
d912pxy_vfs_entry* item = &items[id->num];
item->m_vfsBlocks = fopen(fn, "rb+");
if (item->m_vfsBlocks == NULL)
item->m_vfsBlocks = fopen(fn, "wb+");
if (item->m_vfsBlocks == NULL)
{
return NULL;
}
fseek(item->m_vfsBlocks, 0, SEEK_END);
UINT sz = ftell(item->m_vfsBlocks);
fseek(item->m_vfsBlocks, 0, SEEK_SET);
item->m_vfsFileOffsets = new d912pxy_memtree2(8, 256, 2);
item->m_vfsLastFileOffset = PXY_VFS_BID_TABLE_SIZE + PXY_VFS_BID_TABLE_START;
item->m_vfsFileCount = 0;
ZeroMemory(s_headerTable, PXY_VFS_BID_TABLE_SIZE);
UINT64 signature[2] = { PXY_VFS_SIGNATURE, PXY_VFS_VER };
if (sz < PXY_VFS_BID_TABLE_SIZE + PXY_VFS_BID_TABLE_START)
{
if (fwrite(signature, 8, 2, item->m_vfsBlocks) != 2)
return NULL;
fwrite(s_headerTable, PXY_VFS_FILE_HEADER_SIZE, PXY_VFS_MAX_FILES_PER_BID, item->m_vfsBlocks);
fwrite(&sz, 1, 4, item->m_vfsBlocks);
fflush(item->m_vfsBlocks);
}
else {
UINT64 readedSignature[2] = { 0,0 };
if (fread(readedSignature, 8, 2, item->m_vfsBlocks) != 2)
return NULL;
if (memcmp(signature, readedSignature, 16))
{
return NULL;
}
fseek(item->m_vfsBlocks, 0, SEEK_SET);
if (fwrite(signature, 8, 2, item->m_vfsBlocks) != 2)
return NULL;
fseek(item->m_vfsBlocks, 16, SEEK_SET);
fread(s_headerTable, PXY_VFS_FILE_HEADER_SIZE, PXY_VFS_MAX_FILES_PER_BID, item->m_vfsBlocks);
for (int i = 0; i != PXY_VFS_MAX_FILES_PER_BID; ++i)
{
if (s_headerTable[i].offset > item->m_vfsLastFileOffset)
item->m_vfsLastFileOffset = s_headerTable[i].offset;
if (s_headerTable[i].hash != 0)
{
item->m_vfsFileOffsets->PointAtMem(&s_headerTable[i].hash, 8);
item->m_vfsFileOffsets->SetValue(s_headerTable[i].offset);
++item->m_vfsFileCount;
}
}
if (item->m_vfsLastFileOffset > 0)
{
fseek(item->m_vfsBlocks, (UINT32)item->m_vfsLastFileOffset, SEEK_SET);
UINT32 lastFileSize;
fread(&lastFileSize, 4, 1, item->m_vfsBlocks);
item->m_vfsLastFileOffset += lastFileSize + 4;
}
else
item->m_vfsLastFileOffset = PXY_VFS_BID_TABLE_SIZE + PXY_VFS_BID_TABLE_START;
if (item->m_vfsLastFileOffset == sz)
{
fseek(item->m_vfsBlocks, 0, SEEK_END);
fwrite(&sz, 1, 4, item->m_vfsBlocks);
fflush(item->m_vfsBlocks);
}
item->m_vfsCacheSize = (UINT32)item->m_vfsLastFileOffset - PXY_VFS_BID_TABLE_SIZE - PXY_VFS_BID_TABLE_START;
if (item->m_vfsCacheSize && memCache)
{
PXY_MALLOC(item->m_vfsCache, item->m_vfsCacheSize, void*);
fseek(item->m_vfsBlocks, PXY_VFS_BID_TABLE_SIZE+PXY_VFS_BID_TABLE_START, SEEK_SET);
fread(item->m_vfsCache, 1, item->m_vfsCacheSize, item->m_vfsBlocks);
}
else {
item->m_vfsCache = 0;
item->m_vfsCacheSize = 0;
}
}
return item->m_vfsBlocks;
}
UINT64 d912pxy_vfs::IsPresentN(const char * fnpath, UINT32 vfsId)
{
return IsPresentH(HashFromName(fnpath), vfsId);
}
UINT64 d912pxy_vfs::IsPresentH(UINT64 fnHash, UINT32 vfsId)
{
d912pxy_vfs_entry* item = &items[vfsId];
{
if (item->m_vfsBlocks != NULL)
{
item->m_vfsFileOffsets->PointAtMem(&fnHash, 8);
UINT64 offset = item->m_vfsFileOffsets->CurrentCID();
if (offset)
{
return offset;
}
}
}
return 0;
}
void * d912pxy_vfs::LoadFileN(const char * fnpath, UINT * sz, UINT id)
{
return LoadFileH(HashFromName(fnpath), sz, id);
}
void d912pxy_vfs::WriteFileN(const char * fnpath, void * data, UINT sz, UINT id)
{
WriteFileH(HashFromName(fnpath), data, sz, id);
}
void d912pxy_vfs::ReWriteFileN(const char * fnpath, void * data, UINT sz, UINT id)
{
ReWriteFileH(HashFromName(fnpath), data, sz, id);
}
void * d912pxy_vfs::LoadFileH(UINT64 namehash, UINT * sz, UINT id)
{
d912pxy_vfs_entry* item = &items[id];
item->lock.Hold();
UINT64 offset = IsPresentH(namehash, id);
if (!offset)
{
item->lock.Release();
return nullptr;
}
if (item->m_vfsCache && ((offset - PXY_VFS_BID_TABLE_SIZE - PXY_VFS_BID_TABLE_START) < item->m_vfsCacheSize))
{
offset -= PXY_VFS_BID_TABLE_SIZE + PXY_VFS_BID_TABLE_START;
item->lock.Release();
*sz = *((UINT32*)((intptr_t)item->m_vfsCache + offset));
void* ret = NULL;
PXY_MALLOC(ret, *sz, void*);
memcpy(ret, ((void*)((intptr_t)item->m_vfsCache + offset + 4)), *sz);
return ret;
}
fseek(item->m_vfsBlocks, (UINT32)offset, SEEK_SET);
fread(sz, 4, 1, item->m_vfsBlocks);
void* ret = NULL;
PXY_MALLOC(ret, *sz, void*);
fread(ret, 1, *sz, item->m_vfsBlocks);
item->lock.Release();
return ret;
}
void d912pxy_vfs::WriteFileH(UINT64 namehash, void * data, UINT sz, UINT id)
{
if (!writeAllowed)
return;
d912pxy_vfs_entry* item = &items[id];
item->lock.Hold();
fseek(item->m_vfsBlocks, PXY_VFS_FILE_HEADER_SIZE*item->m_vfsFileCount + PXY_VFS_BID_TABLE_START, SEEK_SET);
fwrite(&namehash, 8, 1, item->m_vfsBlocks);
fwrite(&item->m_vfsLastFileOffset, 8, 1, item->m_vfsBlocks);
++item->m_vfsFileCount;
fseek(item->m_vfsBlocks, (UINT32)item->m_vfsLastFileOffset, SEEK_SET);
fwrite(&sz, 1, 4, item->m_vfsBlocks);
fwrite(data, 1, sz, item->m_vfsBlocks);
fwrite(&sz, 1, 4, item->m_vfsBlocks);
fflush(item->m_vfsBlocks);
item->m_vfsFileOffsets->PointAtMem(&namehash, 8);
item->m_vfsFileOffsets->SetValue(item->m_vfsLastFileOffset);
item->m_vfsLastFileOffset += sz + 4;
item->lock.Release();
}
void d912pxy_vfs::ReWriteFileH(UINT64 namehash, void * data, UINT sz, UINT id)
{
if (!writeAllowed)
return;
d912pxy_vfs_entry* item = &items[id];
item->lock.Hold();
UINT64 offset = IsPresentH(namehash, id);
if (offset)
{
fseek(item->m_vfsBlocks, (UINT32)offset + 4, SEEK_SET);
fwrite(data, 1, sz, item->m_vfsBlocks);
fflush(item->m_vfsBlocks);
if (item->m_vfsCache && (item->m_vfsCacheSize > (offset - PXY_VFS_BID_TABLE_SIZE - PXY_VFS_BID_TABLE_START)))
memcpy((void*)((intptr_t)item->m_vfsCache + (offset - PXY_VFS_BID_TABLE_SIZE - PXY_VFS_BID_TABLE_START) + 4), data, sz);
}
else
WriteFileH(namehash, data, sz, id);
item->lock.Release();
}
UINT64 d912pxy_vfs::HashFromName(const char * fnpath)
{
return d912pxy_memtree2::memHash64s((void*)fnpath, (UINT32)strlen(fnpath));
}
d912pxy_memtree2 * d912pxy_vfs::GetHeadTree(UINT id)
{
d912pxy_vfs_entry* item = &items[id];
return item->m_vfsFileOffsets;
}
void * d912pxy_vfs::GetCachePointer(UINT32 offset, UINT id)
{
d912pxy_vfs_entry* item = &items[id];
offset -= PXY_VFS_BID_TABLE_SIZE + PXY_VFS_BID_TABLE_START;
return ((void*)((intptr_t)item->m_vfsCache + offset + 4));
}
<file_sep>/d912pxy/d912pxy_vfs_packer.cpp
/*
MIT License
Copyright(c) 2019 megai2
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 "stdafx.h"
#include "../thirdparty/fastlz/fastlz.h"
d912pxy_vfs_packer::d912pxy_vfs_packer(wchar_t * rootPath, d912pxy_vfs_id_name * id)
{
sprintf(m_rootPath, "%s/%ws", d912pxy_helper::GetFilePath(FP_VFS_PREFIX)->s, rootPath);
items = id;
}
d912pxy_vfs_packer::~d912pxy_vfs_packer()
{
}
bool d912pxy_vfs_packer::IsUnpackNeeded()
{
int i = 0;
while (items[i].name != 0)
{
char fn[4096];
sprintf(fn, "%s/%s.pck", m_rootPath, items[i].name);
if (d912pxy_helper::IsFileExist(fn))
return false;
++i;
}
return true;
}
void d912pxy_vfs_packer::UnpackArchive(const char * name)
{
char fn[4096];
sprintf(fn, "%s/%s.zpck", m_rootPath, name);
FILE* f = fopen(fn, "rb");
UINT32 header[3] = { 0 };
fread(header, 1, 4 * 3, f);
void* zipData = NULL;
void* rawData = NULL;
PXY_MALLOC(zipData, header[0], void*);
PXY_MALLOC(rawData, header[1], void*);
fread(zipData, 1, header[0], f);
if (fastlz_decompress(zipData, header[0], rawData, header[1]) != header[1])
return;
PXY_FREE(zipData);
intptr_t listingPtr = (intptr_t)rawData;
intptr_t dataPtrBase = (intptr_t)rawData + header[2];
intptr_t dataPtr = dataPtrBase;
while (listingPtr < dataPtrBase)
{
UINT32* listingInfo = (UINT32*)listingPtr;
listingPtr += 8;
char fn_vfs[4096];
sprintf(fn_vfs, "%s/%s.pck", m_rootPath, items[listingInfo[0]].name);
FILE* vfs_f = fopen(fn_vfs, "wb+");
UINT64 signature[2] = { PXY_VFS_SIGNATURE, PXY_VFS_VER };
d912pxy_vfs_file_header* headerTable = NULL;
PXY_MALLOC(headerTable, PXY_VFS_BID_TABLE_SIZE, d912pxy_vfs_file_header*);
ZeroMemory(headerTable, PXY_VFS_BID_TABLE_SIZE);
fseek(vfs_f, 0, SEEK_SET);
fwrite(signature, 1, 16, vfs_f);
fwrite(headerTable, PXY_VFS_FILE_HEADER_SIZE, PXY_VFS_MAX_FILES_PER_BID, vfs_f);
int fileNum = 0;
int offset = PXY_VFS_BID_TABLE_SIZE + PXY_VFS_BID_TABLE_START;
while (listingInfo[1] != 0)
{
headerTable[fileNum].hash = *(UINT64*)(listingPtr);
listingPtr += 8;
headerTable[fileNum].offset = offset;
UINT fileSize = *(UINT32*)(listingPtr);
fwrite((void*)listingPtr, 1, 4, vfs_f);
fwrite((void*)dataPtr, 1, fileSize, vfs_f);
dataPtr += fileSize;
listingPtr += 4;
offset += fileSize + 4;
++fileNum;
--listingInfo[1];
}
fseek(vfs_f, 0, SEEK_SET);
fwrite(signature, 1, 16, vfs_f);
fwrite(headerTable, PXY_VFS_FILE_HEADER_SIZE, PXY_VFS_MAX_FILES_PER_BID, vfs_f);
fclose(vfs_f);
PXY_FREE(headerTable);
}
PXY_FREE(rawData);
}
void d912pxy_vfs_packer::PackArchive(const char * name)
{
char fn[4096];
sprintf(fn, "%s/%s.zpck", m_rootPath, name);
FILE* of = fopen(fn, "wb");
StreamInit(VFS_PCK_STREAM_LISTING, 1 << 20);
StreamInit(VFS_PCK_STREAM_DATA, 1 << 20);
int i = 0;
while (items[i].name != 0)
{
ReadVFS(&items[i]);
++i;
}
UINT sz, oSz;
void* retMem = PackStreams(&sz, &oSz);
fwrite(&sz, 1, 4, of);
fwrite(&oSz, 1, 4, of);
fwrite(&streams[VFS_PCK_STREAM_LISTING].offset, 1, 4, of);
fwrite(retMem, 1, sz, of);
fclose(of);
PXY_FREE(retMem);
}
void d912pxy_vfs_packer::StreamInit(d912pxy_vfs_packer_stream_id id, UINT warmupSz)
{
d912pxy_vfs_packer_stream* stream = &streams[id];
PXY_MALLOC(stream->buf, warmupSz, intptr_t);
stream->offset = 0;
stream->sz = warmupSz;
}
void d912pxy_vfs_packer::StreamWrite(d912pxy_vfs_packer_stream_id id, void * mem, UINT sz)
{
d912pxy_vfs_packer_stream* stream = &streams[id];
UINT newOffset = sz + stream->offset;
StreamReAlloc(stream, newOffset);
memcpy((void*)(stream->buf + stream->offset), mem, sz);
stream->offset = newOffset;
}
void d912pxy_vfs_packer::StreamWriteFrom(d912pxy_vfs_packer_stream_id id, FILE * f, UINT sz)
{
d912pxy_vfs_packer_stream* stream = &streams[id];
UINT newOffset = sz + stream->offset;
StreamReAlloc(stream, newOffset);
fread((void*)(stream->buf + stream->offset), 1, sz, f);
stream->offset = newOffset;
}
void d912pxy_vfs_packer::StreamReAlloc(d912pxy_vfs_packer_stream * stream, UINT newOffset)
{
if (newOffset >= stream->sz)
{
UINT32 nsz = (newOffset + (1 << 20) * 10);
PXY_REALLOC(stream->buf, nsz, intptr_t);
stream->sz = nsz;
}
}
void* d912pxy_vfs_packer::PackStreams(UINT * sz, UINT* oSz)
{
UINT totalSz = 0;
for (int i = 0; i != VFS_PCK_STREAM_CNT; ++i)
{
totalSz += streams[i].offset;
}
void* rawData = NULL;
void* zipData = NULL;
*sz = (UINT32)(((UINT64)totalSz * 120ULL) / 100ULL);
PXY_MALLOC(rawData, totalSz, void*);
PXY_MALLOC(zipData, *sz, void*);
UINT wPtr = 0;
for (int i = 0; i != VFS_PCK_STREAM_CNT; ++i)
{
memcpy((void*)((intptr_t)rawData + wPtr), (void*)streams[i].buf, streams[i].offset);
wPtr += streams[i].offset;
PXY_FREE(streams[i].buf);
}
*oSz = totalSz;
*sz = fastlz_compress(rawData, totalSz, zipData);
PXY_FREE(rawData);
return zipData;
}
void d912pxy_vfs_packer::ReadVFS(d912pxy_vfs_id_name * id)
{
char fn[4096];
sprintf(fn, "%s/%s.pck", m_rootPath, id->name);
FILE* f = fopen(fn, "rb+");
if (f == NULL)
return;
fseek(f, 0, SEEK_END);
UINT sz = ftell(f);
fseek(f, 0, SEEK_SET);
UINT64 signature[2] = { PXY_VFS_SIGNATURE, PXY_VFS_VER };
if (sz < PXY_VFS_BID_TABLE_SIZE + PXY_VFS_BID_TABLE_START)
{
fclose(f);
return;
}
else {
UINT64 readedSignature[2] = { 0,0 };
if (fread(readedSignature, 8, 2, f) != 2)
{
fclose(f);
return;
}
if (memcmp(signature, readedSignature, 16))
{
fclose(f);
return;
}
fseek(f, 16, SEEK_SET);
d912pxy_vfs_file_header* headerTable = NULL;
PXY_MALLOC(headerTable, PXY_VFS_BID_TABLE_SIZE, d912pxy_vfs_file_header*);
fread(headerTable, PXY_VFS_FILE_HEADER_SIZE, PXY_VFS_MAX_FILES_PER_BID, f);
d912pxy_memtree2* files = new d912pxy_memtree2(8, 256, 2);
UINT32 haveFiles = 0;
for (int i = 0; i != PXY_VFS_MAX_FILES_PER_BID; ++i)
{
if (headerTable[i].hash != 0)
{
files->PointAtMem(&headerTable[i].hash, 8);
files->SetValue(i+1);
++haveFiles;
}
}
if (haveFiles)
{
StreamWrite(VFS_PCK_STREAM_LISTING, &id->num, 4);
//megai2: count unique files
UINT uniqueFiles = haveFiles;
files->Begin();
while (!files->IterEnd())
{
if (files->CurrentCID() != 0)
--haveFiles;
files->Next();
}
uniqueFiles -= haveFiles;
StreamWrite(VFS_PCK_STREAM_LISTING, &uniqueFiles, 4);
files->Begin();
void* vfsFileData = NULL;
PXY_MALLOC(vfsFileData, (sz - PXY_VFS_DATA_OFFSET), void*);
fread(vfsFileData, 1, sz - PXY_VFS_DATA_OFFSET, f);
while (!files->IterEnd())
{
if (files->CurrentCID() == 0)
{
files->Next();
continue;
}
d912pxy_vfs_file_header fDsc = headerTable[files->CurrentCID()-1];
StreamWrite(VFS_PCK_STREAM_LISTING, &fDsc.hash, 8);
StreamWrite(VFS_PCK_STREAM_LISTING, (void*)((intptr_t)vfsFileData + fDsc.offset - PXY_VFS_DATA_OFFSET) , 4);
StreamWrite(VFS_PCK_STREAM_DATA, (void*)((intptr_t)vfsFileData + fDsc.offset - PXY_VFS_DATA_OFFSET + 4), *(UINT32*)((intptr_t)vfsFileData + fDsc.offset - PXY_VFS_DATA_OFFSET));
files->Next();
}
PXY_FREE(vfsFileData);
}
PXY_FREE(headerTable);
delete files;
fclose(f);
}
}
|
91899d7f995d9fe334d48c61fbc367ec4d2a247b
|
[
"C++"
] | 2 |
C++
|
sirjaden92/d912pxy
|
fa7aa506f57acf1c09a63b23d6ae9c211df6da92
|
fa0e0a5fd7a40c3077af2303d468d1e9473bd047
|
refs/heads/main
|
<file_sep>#include <SoftwareSerial.h>
#include "SIM800L.h"
#include "HX711.h"
#define LOADCELL_DOUT_PIN 3
#define LOADCELL_SCK_PIN 2
#define calibration_factor -7050.0 //This value is obtained using the SparkFun_HX711_Calibration sketch
#define SIM800_RX_PIN 10
#define SIM800_TX_PIN 11
#define SIM800_RST_PIN 6
const char APN[] = "safaricom,saf,data";
const char URL[] = "http://c0eafc8d79c0.ngrok.io/v1/sensors/";
const char CONTENT_TYPE[] = "application/json";
SIM800L* sim800l;
HX711 scale;
void setup() {
// Initialize Serial Monitor for debugging
Serial.begin(115200);
while(!Serial);
// Initialize a SoftwareSerial
SoftwareSerial* serial = new SoftwareSerial(SIM800_RX_PIN, SIM800_TX_PIN);
Serial.println("Initializing Serial Monitor...");
serial->begin(9600);
delay(1000);
// Initialize SIM800L driver with an internal buffer of 200 bytes and a reception buffer of 512 bytes, debug disabled
sim800l = new SIM800L((Stream *)serial, SIM800_RST_PIN, 200, 512);
scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
Serial.println("Calibrating scale...");
scale.set_scale(calibration_factor); //This value is obtained by using the SparkFun_HX711_Calibration sketch
scale.tare(); //Assuming there is no weight on the scale at start up, reset the scale to 0
// Setup module for GPRS communication
setupModule();
}
void loop() {
// Establish GPRS connectivity (5 trials)
bool connected = false;
for(uint8_t i = 0; i < 5 && !connected; i++) {
delay(1000);
connected = sim800l->connectGPRS();
}
check_connection(connected);
Serial.println(F("Start HTTP POST..."));
float i = scale.get_units();
Serial.print("Load_cell output val: ");
Serial.println(i);
char PAYLOAD[200];
char temp_weight[6];
dtostrf(i, 5, 2, temp_weight);
sprintf(PAYLOAD, "{\"weight\": \"%s\", \"owner\": \"Esir\"}", temp_weight);
Serial.println(PAYLOAD);
// Do HTTP POST communication with 10s for the timeout (read and write)
uint16_t rc = sim800l->doPost(URL, CONTENT_TYPE, PAYLOAD, 10000, 10000);
if(rc == 200) {
// Success, output the data received on the serial
Serial.print(F("HTTP POST successful ("));
Serial.print(sim800l->getDataSizeReceived());
Serial.println(F(" bytes)"));
Serial.print(F("Received : "));
Serial.println(sim800l->getDataReceived());
} else {
// Failed...
Serial.print(F("HTTP POST error "));
Serial.println(rc);
}
// Close GPRS connectivity (5 trials)
bool disconnected = sim800l->disconnectGPRS();
for(uint8_t i = 0; i < 5 && !connected; i++) {
delay(1000);
disconnected = sim800l->disconnectGPRS();
}
if(disconnected) {
Serial.println(F("GPRS disconnected !"));
} else {
Serial.println(F("GPRS still connected !"));
}
// Go into low power mode
bool lowPowerMode = sim800l->setPowerMode(MINIMUM);
if(lowPowerMode) {
Serial.println(F("Module in low power mode"));
} else {
Serial.println(F("Failed to switch module to low power mode"));
}
// Sleep for 1 minute
delay(60000);
}
void setupModule() {
Serial.println(F("Setting up GPRS..."));
// Establish GPRS connectivity (5 trials)
bool connected = false;
for(uint8_t i = 0; i < 5 && !connected; i++) {
delay(1000);
connected = sim800l->connectGPRS();
}
check_connection(connected);
// Wait until the module is ready to accept AT commands
while(!sim800l->isReady()) {
Serial.println(F("Problem to initialize AT command, retry in 1 sec"));
delay(1000);
}
Serial.println(F("GPRS Setup Complete!"));
// Wait for the GSM signal
uint8_t signal = sim800l->getSignal();
while(signal <= 0) {
delay(1000);
signal = sim800l->getSignal();
}
Serial.print(F("Signal OK (strenght: "));
Serial.println(F(")"));
delay(1000);
// Wait for operator network registration (national or roaming network)
NetworkRegistration network = sim800l->getRegistrationStatus();
while(network != REGISTERED_HOME && network != REGISTERED_ROAMING) {
Serial.print(network);
delay(1000);
network = sim800l->getRegistrationStatus();
}
Serial.println(F("Network registration OK"));
delay(1000);
// Setup APN for GPRS configuration
bool success = sim800l->setupGPRS(APN);
while(!success) {
success = sim800l->setupGPRS(APN);
delay(5000);
}
Serial.println(F("GPRS config OK"));
}
void check_connection(bool connected) {
// Check if connected, if not reset the module and setup the config again
if(connected) {
Serial.println(F("GPRS connected !"));
} else {
Serial.println(F("GPRS not connected !"));
Serial.println(F("Reset the module."));
sim800l->reset();
setupModule();
}
}
<file_sep>/*
Connect ESP32 to gums servers
* Description: connects to gums API using an ESP32 Wifi module.
*/
#include <WiFi.h>
#include <HTTPClient.h>
#include "HX711.h"
#define calibration_factor -7050.0 //This value is obtained using the SparkFun_HX711_Calibration sketch
#define OWNER "0708468333"
#define DOUT 2
#define CLK 15
// <KEY>
HX711 scale;
HTTPClient http;
const char* ssid = "Jibambex";//Wifi SSID
const char* password = "<PASSWORD>";//Wifi Password
// GUMS API host config
const char* host = "192.168.100.80"; // API host name
const int httpPort = 8000; // port
// Use WiFiClient class to create TCP connections
WiFiClient client;
long t;
void setup() {
Serial.begin(57600);
delay(10);
Serial.println();
Serial.println("Starting...");
Serial.println("Wait for WiFi... ");
// connecting to the WiFi network
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// connected
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
scale.begin(DOUT, CLK);
scale.set_scale(calibration_factor); //This value is obtained by using the SparkFun_HX711_Calibration sketch
scale.tare(); //Assuming there is no weight on the scale at start up, reset the scale to 0
}
void loop() {
static boolean newDataReady = 0;
const int serialPrintInterval = 10000; //increase value to slow down serial print activity
if (millis() > t + serialPrintInterval) {
String url = "http://192.168.100.80:8000/v1/sensors/";
Serial.print("********** Sending data to the following URL: ");
Serial.println(url);
float i = scale.get_units();
Serial.print("Load_cell output val: ");
Serial.println(i);
http.begin(url);
// Specify content-type header
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
String httpRequestData = "owner=" OWNER "&value1=";
int httpResponseCode = http.POST(httpRequestData+=i);
Serial.println(httpResponseCode);
String payload = http.getString();
Serial.println(httpResponseCode);
Serial.println(payload);
newDataReady = 0;
t = millis();
}
}
<file_sep>/*
Connect ESP32 to gums servers
* Description: connects to gums API using an ESP32 Wifi module.
*/
#include <WiFi.h>
#include <HTTPClient.h>
HTTPClient ask;
const char* ssid = "Jibambex";//Wifi SSID
const char* password = "<PASSWORD>";//Wifi Password
// GUMS API host config
const char* host = "192.168.100.80"; // API host name
const int httpPort = 8080; // port
// Use WiFiClient class to create TCP connections
WiFiClient client;
void setup(){
// open serial
Serial.begin(115200);
Serial.println("*****************************************************");
Serial.println("********** Program Start : Connect GUMS to GUMS server");
Serial.println("Wait for WiFi... ");
// connecting to the WiFi network
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// connected
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop(){
if (!client.connect(host, httpPort)){
Serial.println("connection to");
Serial.println(host);
Serial.println("failed.");
delay(10000);
return;
}
String url = "http://192.168.100.80:8080/";
Serial.print("********** requesting URL: ");
Serial.println(url);
ask.begin(url);
int httpResponseCode = ask.GET();
String payload = ask.getString();
Serial.println(httpResponseCode);
Serial.println(payload);
ask.end();
client.stop();
delay(10000);
}
|
15cfa7fa8466f1a66200965364ce1a26e884e1e5
|
[
"C++"
] | 3 |
C++
|
esirK/gums
|
a12db2190895f4a2850869dcb60cd6277eda594a
|
8915d4c0e4f581702d618c126ff7120096e38f09
|
refs/heads/master
|
<file_sep>package amazons;
import org.junit.Test;
import static amazons.Piece.*;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Iterator;
import static amazons.Board.*;
/** Tests of the Board class.
* @author <NAME>.
*/
public class BoardTest {
private Board b;
@Test
public void testIsUnblockedMove() {
b = new Board();
makeBoard(b);
assertTrue(b.isUnblockedMove(Square.sq(32), Square.sq(22), null));
assertFalse(b.isUnblockedMove(Square.sq(32), Square.sq(37), null));
}
@Test
public void testMakeMoveAndUndo() {
b = new Board();
makeBoard(b);
b.makeMove(Move.mv(Square.sq(32), Square.sq(33), Square.sq(0)));
assertEquals(SMILE1, b.toString());
b.undo();
assertEquals(SMILE, b.toString());
assertEquals(0, b.numMoves());
}
@Test
public void testReachableFrom() {
b = new Board();
makeBoard(b);
Iterator<Square> a = b.reachableFrom(Square.sq(88), null);
assertEquals(Square.sq(98), a.next());
assertEquals(Square.sq(99), a.next());
assertEquals(Square.sq(89), a.next());
assertEquals(Square.sq(79), a.next());
assertEquals(Square.sq(77), a.next());
assertEquals(Square.sq(97), a.next());
b = new Board();
a = b.reachableFrom(Square.sq(3), null);
ArrayList<Square> result = new ArrayList<>();
Square c = a.next();
while (c != null) {
result.add(c);
c = a.next();
}
assertEquals(20, result.size());
b = new Board();
makeBoard(b);
a = b.reachableFrom(Square.sq(77), null);
assertEquals(null, a.next());
}
@Test
public void testLegalMoves() {
b = new Board();
Iterator<Move> a = b.legalMoves(WHITE);
ArrayList<Move> result = new ArrayList<>();
Move c = a.next();
while (c != null) {
result.add(c);
c = a.next();
}
assertEquals(2176, result.size());
b = new Board();
for (int i = 0; i < 97; i += 1) {
b.put(SPEAR, Square.sq(i));
}
b.put(WHITE, Square.sq(99));
a = b.legalMoves(WHITE);
result = new ArrayList<>();
c = a.next();
while (c != null) {
result.add(c);
c = a.next();
}
assertEquals(4, result.size());
b = new Board();
makeboard1(b);
a = b.legalMoves(WHITE);
result = new ArrayList<>();
c = a.next();
while (c != null) {
result.add(c);
c = a.next();
}
assertEquals(4, result.size());
b = new Board();
makeBoard(b);
b.put(BLACK, Square.sq(77));
a = b.legalMoves(BLACK);
assertEquals(null, a.next());
}
@Test
public void testSquare() {
assertEquals("j2", Square.sq(19).toString());
}
private void makeboard1(Board board) {
for (int i = 0; i < 100; i += 1) {
board.put(BLACK, Square.sq(i));
}
board.put(EMPTY, Square.sq(99));
board.put(EMPTY, Square.sq(89));
board.put(WHITE, Square.sq(79));
}
private void makeBoard(Board board) {
board.put(EMPTY, Square.sq(0, 3));
board.put(EMPTY, Square.sq(0, 6));
board.put(EMPTY, Square.sq(9, 3));
board.put(EMPTY, Square.sq(9, 6));
board.put(EMPTY, Square.sq(3, 0));
board.put(EMPTY, Square.sq(3, 9));
board.put(EMPTY, Square.sq(6, 0));
board.put(EMPTY, Square.sq(6, 9));
for (int col = 1; col < 4; col += 1) {
for (int row = 6; row < 9; row += 1) {
b.put(SPEAR, Square.sq(col, row));
}
}
board.put(EMPTY, Square.sq(2, 7));
for (int col = 6; col < 9; col += 1) {
for (int row = 6; row < 9; row += 1) {
board.put(SPEAR, Square.sq(col, row));
}
}
board.put(EMPTY, Square.sq(7, 7));
for (int lip = 3; lip < 7; lip += 1) {
board.put(WHITE, Square.sq(lip, 2));
}
board.put(WHITE, Square.sq(2, 3));
board.put(WHITE, Square.sq(7, 3));
}
static final String SMILE =
" - - - - - - - - - -\n"
+ " - S S S - - S S S -\n"
+ " - S - S - - S - S -\n"
+ " - S S S - - S S S -\n"
+ " - - - - - - - - - -\n"
+ " - - - - - - - - - -\n"
+ " - - W - - - - W - -\n"
+ " - - - W W W W - - -\n"
+ " - - - - - - - - - -\n"
+ " - - - - - - - - - -\n";
static final String SMILE1 =
" - - - - - - - - - -\n"
+ " - S S S - - S S S -\n"
+ " - S - S - - S - S -\n"
+ " - S S S - - S S S -\n"
+ " - - - - - - - - - -\n"
+ " - - - - - - - - - -\n"
+ " - - - W - - - W - -\n"
+ " - - - W W W W - - -\n"
+ " - - - - - - - - - -\n"
+ " S - - - - - - - - -\n";
}
|
3cc20f955e48e8254cae73c6f0e7ba504e07d82d
|
[
"Java"
] | 1 |
Java
|
zxie1/Amazons
|
70984251effa4c63eaf6a0bff4c286eba9939ede
|
b6927ecf1b428bd23fbf0c141a692bba683e1a02
|
refs/heads/master
|
<repo_name>vidyamani/dotfiles<file_sep>/.profile
alias pgstart='pg_ctl -D /usr/local/var/postgres -l /tmp/pg.log start'
alias pgstop='pg_ctl -D /usr/local/var/postgres -l /tmp/pg.log stop'
alias grep='grep --color'
alias ip='ifconfig | grep "inet 10" | cut -f 2 -d " "'
# Mingle
alias mingle='cd ~/projects/tw/mingle'
alias jss='./script/jruby_mingle_server'
alias ss='./script/server'
|
b838f220de51374b570c37c345cce14043e97f95
|
[
"Shell"
] | 1 |
Shell
|
vidyamani/dotfiles
|
8fac7def5737dedeb2ac9dd2df0a76c65c7f44ad
|
a3f58706f4f966f1254205fe3967bbb6c8e658c2
|
refs/heads/master
|
<file_sep>buildscript {
ext {
springBootVersion = '1.4.3.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
processResources.destinationDir = compileJava.destinationDir
compileJava.dependsOn processResources
idea.module.inheritOutputDirs = true
jar {
baseName = 'spring-boot-doma-template'
version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile 'org.seasar.doma:doma:2.14.0'
compile('org.flywaydb:flyway-core')
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.seasar.doma.boot:doma-spring-boot-starter:1.1.0')
runtime('com.h2database:h2')
compileOnly('org.projectlombok:lombok')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
task wrapper(type: Wrapper) {
gradleVersion = '3.3'
distributionUrl = 'http://services.gradle.org/distributions/gradle-3.3-all.zip'
}
<file_sep>package org.seasar.doma.boot;
import java.util.List;
import lombok.AllArgsConstructor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
@AllArgsConstructor
public class DomaBootTemplateApplication {
MessageDao messageDao;
@RequestMapping("/")
List<Message> list(@PageableDefault Pageable pageable) {
return messageDao.selectAll(Pageables.toSelectOptions(pageable));
}
@RequestMapping(value = "/", params = "text")
Message add(@RequestParam String text) {
Message message = new Message();
message.text = text;
messageDao.insert(message);
return message;
}
public static void main(String[] args) {
SpringApplication.run(DomaBootTemplateApplication.class, args);
}
}
<file_sep># Spring Boot and Doma project template
## Dependencies
- Spring Boot
- Doma
- Flyway
## Notes
- IntelliJ settings
- IntelliJ IDEA > Preferences > Annotation Processes > Enable annotation processing
|
b972299d474f04470c5824f5e185f7f9e3be5b01
|
[
"Markdown",
"Java",
"Gradle"
] | 3 |
Gradle
|
disc99/spring-boot-doma-template
|
30cb118b837c512b1fd707d36b076966dc026a62
|
2b87f8d2be84d09fbe8ccf39d3496f75d101678a
|
refs/heads/master
|
<file_sep># All the aliases a sysadmin could want.
# Ever accidently remove something very important with rm? Let's fix that. Also, no -rf required for folders!
rm () { mv $1 /tmp/Trash; }
alias emptytrash="/bin/rm -rf /tmp/Trash/*"
# Apt stuff
alias install="apt-get -y install "
alias update="apt-get -y -q update"
alias upgrade="apt-get -y -q update && apt-get -y -q upgrade"
alias remove="apt-get -y remove"
alias uninstall="apt-get -y remove"
alias purge="sudo apt-get -y remove --purge"
# Handy git aliases
alias ga="git add -A --ignore-errors"
alias gc="git commit -a"
alias gs="git status"
alias gb="git branch"
alias gp="git push origin"
#Git feature branch
gfb () { git checkout -b $1 develop; }
#Merge feature branch
gmfb () { git checkout develop; git merge --no-ff $1; git branch -d $1; git push origin develop; }
<file_sep>#!/bin/bash
# Args:
# $1 domain name (example.com)
# $2 mysql root password
if [ "$(id -u)" != "0" ]; then
echo ""
echo "Script must be run as root."
echo ""
exit 1
fi
if [ $# != 2 ]; then
echo ""
echo "Incorrect number of arguments, 2 required."
echo "1: domain name to install Wordpress to. (e.g. example.com)"
echo "2: MySQL root password (to create databases)"
echo ""
exit 2
fi
randpass() {
CHAR="[:alnum:]"
RET=`cat /dev/urandom | tr -cd "$CHAR" | head -c ${1:-16}`
}
#Sanitize domain name to take out periods
DOMAIN_NAME=$(echo $1 | sed "s/\./__/")
#Generate all required random passwords/salt/hashes
randpass
DB_PASS=$RET
randpass
USER_PASS=$RET
#Make user and group
useradd -m -d /home/$DOMAIN_NAME -U $DOMAIN_NAME
echo $USER_PASS > tmp
echo $USER_PASS >> tmp
passwd $DOMAIN_NAME < tmp
rm tmp
INSTALL_DIR="/home/$DOMAIN_NAME/wordpress"
cd $INSTALL_DIR
#Get latest version, delete old version
rm latest.*
wget http://wordpress.org/latest.tar.gz
#Extract to web directory
tar xf latest*
mv wordpress/* /home/$DOMAIN_NAME/wordpress/
rm -rf wordpress/
#change permissions (not necessary so far)
#Create Database and Database user
echo "CREATE USER '$DOMAIN_NAME'@'localhost' IDENTIFIED BY '$DB_PASS'
CREATE DATABASE $DOMAIN_NAME;
GRANT ALL PRIVILEGES ON $DOMAIN_NAME.* TO '$DOMAIN_NAME'@'localhost' IDENTIFIED BY '$DB_PASS';
FLUSH PRIVILEGES;
EXIT;" > input
mysql --user=root --password=$2 < input
rm input
#Make config.php file
echo "<?php
/**
* The base configurations of the WordPress.
*
* This file has the following configurations: MySQL settings, Table Prefix,
* Secret Keys, WordPress Language, and ABSPATH. You can find more information
* by visiting {@link http://codex.wordpress.org/Editing_wp-config.php Editing
* wp-config.php} Codex page. You can get the MySQL settings from your web host.
*
* This file is used by the wp-config.php creation script during the
* installation. You don't have to use the web site, you can just copy this file
* to "wp-config.php" and fill in the values.
*
* @package WordPress
*/
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', '$DOMAIN_NAME');
/** MySQL database username */
define('DB_USER', '$DOMAIN_NAME');
/** MySQL database password */
define('DB_PASSWORD', <PASSWORD>');
/** MySQL hostname */
define('DB_HOST', 'localhost');
/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');
/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');
/** The FTP settings. These settings are assumed, and if using
the ServerCobra set of scripts, it will work automagically */
/* WordPress FTP Information (For removing the constant password request on plugin install and removal) */
define("FTP_HOST", "$1");
define("FTP_USER", "$DOMAIN_NAME");
define("FTP_PASS", <PASSWORD>");
/**#@+
* Authentication Unique Keys and Salts.
*
* Change these to different unique phrases!
* You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
* You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
*
* @since 2.6.0
*/" > wp-config.php
wget https://api.wordpress.org/secret-key/1.1/salt/
cat index.html >> wp-config.php
echo "/**#@-*/
/**
* WordPress Database Table prefix.
*
* You can have multiple installations in one database if you give each a unique
* prefix. Only numbers, letters, and underscores please!
*/
\$table_prefix = 'wp_';
/**
* WordPress Localized Language, defaults to English.
*
* Change this to localize WordPress. A corresponding MO file for the chosen
* language must be installed to wp-content/languages. For example, install
* de.mo to wp-content/languages and set WPLANG to 'de' to enable German
* language support.
*/
define ('WPLANG', '');
/**
* For developers: WordPress debugging mode.
*
* Change this to true to enable the display of notices during development.
* It is strongly recommended that plugin and theme developers use WP_DEBUG
* in their development environments.
*/
define('WP_DEBUG', false);
/* That's all, stop editing! Happy blogging. */
/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');" >> wp-config.php
#Cleanup, or the index.html file will be displayed right away, along with all
# the security keys.
rm index.html
#Make sure no one can read this file, since it has all the passwords and such
chmod 770 $DOMAIN_NAME wp-config.php
#Installation is now complete..
echo "////////////////////////////////////////////////////////////////////////////////"
echo "Install completed successfully!"
echo "Please visit http://$1/wp-admin/install.php to finalize your installation."
echo ""
echo "Your new wordpress username is: $DOMAIN_NAME"
echo "with password: <PASSWORD>"
echo "and your MySQL username is: $DOMAIN_NAME"
echo "with password: <PASSWORD>"
echo ""
echo "You can also find these in wp-config.php"
<file_sep>#/usr/bin/env python
# This script sits on an Nginx server, and is run by remote Apache/Nginx
# or app servers to register themselves in a cluster with Nginx. We are using
# this on EC2, to let web/php servers register with the Nginx load balancer.
# Assumes nginx.conf has an upstream default in the config like so:
# upstream default { include /etc/nginx/default.upstream; }
# This file is simply a list of hostnames.
# You may include other upstream files, in the form:
# upstream cluster_name { include /etc/nginx/cluster_name.upstream; }
# Usage: python register-nginx.py [-d/--deregister] client_hostname [cluster_name]
# By the way, I know this is UGLY. But it was quick and dirty. Some day, I might
# fix it.
import sys
import os
DEBUG = True
if DEBUG:
file_template = "%s.upstream"
else:
file_template = "/etc/nginx/%s.upstream"
def register(hostname, cluster="default"):
# Blank file, add in required lines
if os.path.getsize(file_template % cluster) == 0:
with open(file_template % cluster, 'a') as cluster_file:
cluster_file.write("upstream %s {\n}" % cluster)
# See if the hostname exists already
with open(file_template % cluster, 'r') as cluster_file:
new_file = []
lines = cluster_file.readlines()
for line in lines:
if "{" in line:
new_file.append(line)
elif "}" in line:
line = "server " + hostname + ';\n'
new_file.append(line)
new_file.append('}')
elif "server " + hostname + ';\n' == line:
print "Host %s already registered with cluster %s" % (hostname, cluster)
sys.exit(1)
else:
new_file.append(line)
# Append the new hostname to the file
with open(file_template % cluster, 'w') as cluster_file:
for line in new_file:
cluster_file.write(line)
def deregister(hostname, cluster="default"):
new_file = []
# Read through the file, add all lines that aren't the hostname to a new array
with open(file_template % cluster, 'r') as cluster_file:
lines = cluster_file.readlines()
old_file_len = len(lines)
for line in lines:
if "{" in line or "}" in line:
new_file.append(line)
elif "server " + hostname + ';\n' != line:
#print hostname, line
new_file.append(line)
if len(new_file) == old_file_len:
print "Host %s not registered with cluster %s" % (hostname, cluster)
sys.exit(2)
# Write the array, minus the deregistered hostname, to the file
with open(file_template % cluster, 'w') as cluster_file:
for line in new_file:
cluster_file.write(line)
if __name__ == "__main__":
# arv[0] == appname, argv[1] == first arg, etc If len == 2: default register, 3: deregister OR other cluster. 4: deregister other cluster
if len(sys.argv) == 2:
register(sys.argv[1])
elif len(sys.argv) == 3:
if sys.argv[1] == '-d' or sys.argv[1] == '--deregister':
deregister(sys.argv[2])
else:
register(sys.argv[1], sys.argv[2])
elif len(sys.argv) == 4:
deregister(sys.argv[2], sys.argv[3])
else:
print "usage:"
print "python register-nginx.py [-d/--deregister] hostname [cluster_name]"
<file_sep>#!/bin/bash
USER_DIR='/Users/ruscon'
DOMAIN=''
USER_TRUNC=''
DOMAIN_TRUNC=''
DB_PASS=''
RET=''
function sanity_check {
if [ "$(id -u)" != "0" ]; then
echo "Script must be run as root."
exit 1
fi
# egrep "^$USERNAME:" /etc/passwd >/dev/null
# if [ $? -eq 0 ]; then
# echo "$USERNAME exists!"
# exit 3
# fi
# if [ ! -e /root/mysql ]; then
# echo "Root MySQL password file missing. Please run create the file /root/mysql,"
# echo "And put your root password as the first and only line."
# exit 4
# fi
}
#
#function password {
# RET=$(cat /dev/urandom | tr -cd [:alnum:] | head -c ${1:-16})
#}
#
#function setup_user {
# useradd -m -d $USER_DIR/$USERNAME -U $USERNAME
#
# password
# PASSWORD=$RET
# echo "$USERNAME:$PASSWORD" | chpasswd
#
# mkdir -p $USER_DIR/$USERNAME/$DOMAIN/htdocs
# mkdir $USER_DIR/$USERNAME/$DOMAIN/logs
# touch $USER_DIR/$USERNAME/$DOMAIN/logs/access.log
# touch $USER_DIR/$USERNAME/$DOMAIN/logs/error.log
# chown -R $USERNAME $USER_DIR/$USERNAME
# chgrp -R $USERNAME $USER_DIR/$USERNAME
#
# echo "Create user: $USERNAME with password: $<PASSWORD>"
#}
function php_pool {
# if [ ! -f /etc/php5/fpm/port ]; then
# echo "Cannot access /etc/php5/fpm/port"
# exit 2
# fi
#
# # Grab the port from file, and increment.
# PORT=$(cat /etc/php5/fpm/port)
# echo $(($PORT + 1)) > /etc/php5/fpm/port
cp pool.template /usr/local/etc/php/5.4/fpm.d/$PROJECT.conf
sed -i.tmp "s|example.com|$DOMAIN|g" /usr/local/etc/php/5.4/fpm.d/$PROJECT.conf
rm /usr/local/etc/php/5.4/fpm.d/$PROJECT.conf.tmp
# sed -i "s|PORT|$PORT|" /usr/local/etc/php/5.4/fpm.d/$DOMAIN
# sed -i "s|user = example|user = $USERNAME|" /usr/local/etc/php/5.4/fpm.d/$DOMAIN
# sed -i "s|group = example|group = $USERNAME|" /usr/local/etc/php/5.4/fpm.d/$DOMAIN
echo "Added $DOMAIN to the PHP pool"
}
function nginx_vhost {
cp vhost.template /usr/local/etc/nginx/sites-available/$DOMAIN
sed -i.tmp "s|example.com|$DOMAIN|g" /usr/local/etc/nginx/sites-available/$DOMAIN
rm /usr/local/etc/nginx/sites-available/$DOMAIN.tmp
# sed -i "s|username|$USERNAME|g" /usr/local/etc/nginx/sites-available/$DOMAIN
# sed -i "s|PORT|$PORT|g" /usr/local/etc/nginx/sites-available/$DOMAIN
# Should probably sed through and replace /ebs/www with $USER_DIR
# Enable the site
ln -s /usr/local/etc/nginx/sites-available/$DOMAIN /usr/local/etc/nginx/sites-enabled/$DOMAIN
mkdir "$USER_DIR/projects/$PROJECT"
chown ruscon:staff "$USER_DIR/projects/$PROJECT"
ln -s $USER_DIR/projects/$PROJECT /usr/local/var/www/$DOMAIN
echo "Enabled $DOMAIN in the web server"
}
function ect_host {
echo "127.0.0.1 $DOMAIN" >> /etc/hosts
}
#function server_reload {
# /etc/init.d/php5-fpm reload
# /etc/init.d/nginx reload
# echo "Servers reloaded"
#}
#function prepare_mysql {
# # Generate dbuser password
# password
# DB_PASS=$RET
#
# # Truncate username (15 chars max) and dbname (63 chars max)
# USER_TRUNC=$(echo $USERNAME | cut -c1-15)
#
# # This should be a separate user with only create perms.
# echo "CREATE DATABASE $USER_TRUNC;
#GRANT ALL PRIVILEGES ON $USER_TRUNC.* to '$USER_TRUNC'@'localhost' IDENTIFIED BY '$DB_PASS';" > $USERNAME.sql
# mysql -u root -p$(cat /root/mysql) < $USERNAME.sql
# rm $USERNAME.sql
# echo "Created MySQL user: $USER_TRUNC password: $DB_PASS database: $DOMAIN_TRUNC"
#}
#function add_to_ftp {
# usermod -g proftpd $USERNAME
#}
#function install_wordpress {
# wget http://wordpress.org/latest.tar.gz
# tar xf latest.tar.gz
# mv wordpress/* $USER_DIR/$USERNAME/$DOMAIN/htdocs/
# cp $USER_DIR/$USERNAME/$DOMAIN/htdocs/wp-config-sample.php $USER_DIR/$USERNAME/$DOMAIN/htdocs/wp-config.php
# sed -i "s|database_name_here|$USER_TRUNC|g" $USER_DIR/$USERNAME/$DOMAIN/htdocs/wp-config.php
# sed -i "s|username_here|$USERNAME|g" $USER_DIR/$USERNAME/$DOMAIN/htdocs/wp-config.php
# sed -i "s|password_here|$DB_PASS|g" $USER_DIR/$USERNAME/$DOMAIN/htdocs/wp-config.php
#
# echo " define(\"FTP_HOST\", \"$DOMAIN\");
# define(\"FTP_USER\", \"$USERNAME\");
# define(\"FTP_PASS\", \"$USERPASS\");" >> $USER_DIR/$USERNAME/$DOMAIN/htdocs/wp-config.php
#
# # Add in salts from the wordpress salt generator
# wget https://api.wordpress.org/secret-key/1.1/salt/
# sed -i "s/|/a/g" index.html
## cat index.html | while read line; do
## sed -i "s|define('.*',.*'put your unique phrase here');|$line|" $USER_DIR/$USERNAME/$DOMAIN/htdocs/wp-config.php
## sed 1d $USER_DIR/$USERNAME/$DOMAIN/htdocs/wp-config.php
## done
# sed -i '/#@-/r index.html' $USER_DIR/$USERNAME/$DOMAIN/htdocs/wp-config.php
# sed -i "/#@+/,/#@-/d" $USER_DIR/$USERNAME/$DOMAIN/htdocs/wp-config.php
# rm index.html
# rm latest.tar.gz
#
# # Add in FTP stuff, even though that's not defined yet..
#
# # Own these new files
# chown -R $USERNAME $USER_DIR/$USERNAME/$DOMAIN/htdocs/*
# chgrp -R $USERNAME $USER_DIR/$USERNAME/$DOMAIN/htdocs/*
# # Make sure no one else can read this file
# chmod 700 $USER_DIR/$USERNAME/$DOMAIN/htdocs/wp-config.php
#
# #echo "Wordpress for $DOMAIN installed."
# #echo "Visit http://$DOMAIN/wp-admin/install.php to complete installation"
#}
##############################################################################
# Start of program
#USERNAME=$1
PROJECT=$1
DOMAIN="$1.dev"
sanity_check $#
#setup_user
php_pool
nginx_vhost
ect_host
#server_reload
#prepare_mysql
#add_to_ftp
#install_wordpress
exit 0
<file_sep>#!/bin/bash
USER='josh'
# Ensure script is run as root
if [ "$(id -u)" != "0" ]; then
echo "Script must be run as root."
exit 1
fi
# Ensure Ubuntu One has already been signed into and synced.
if [ ! -d "/home/$USER/Ubuntu\ One" ]; then
echo "Please login to Ubuntu One and start syncing first"
echo "Then rerun this script."
exit 1
fi
apt-get -y update && apt-get -y upgrade
apt-get -y install kate subversion eclipse powertop git-core gitosis flashplugin-nonfree
ln -s /home/$USER/Ubuntu\ One/programming/ /home/$USER/programming
#Install Chrome
echo "deb http://dl.google.com/linux/deb/ unstable non-free main" | sudo tee -a /etc/apt/sources.list > /dev/null
wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
sudo apt-get update && sudo apt-get install google-chrome-unstable
#Install Skype
echo "deb http://download.skype.com/linux/repos/debian/ stable non-free #Skype" | sudo tee -a /etc/apt/sources.list > /dev/null
gpg --keyserver pgp.mit.edu --recv-keys 0xd66b746e && gpg --export --armor 0xd66b746e | sudo apt-key add -
sudo apt-get update && sudo apt-get install skype
<file_sep>#Installs all the necessary tools to use the ec2-start-test and ec2-kill-test scripts.
#Doesn't install the actual tools. Should probably add that as an option.
#Oh, and this wouldn't even work for anyone but me. Should probably fix that too..
#Modify path names?
sudo add-apt-repository "deb http://archive.canonical.com/ lucid partner"
sudo apt-get -y update
sudo apt-get -y install unzip sun-java6-jre
#Export variables to ~/.bashrc
#Need to check for each variable in ~/.bashrc. Grep?
RES=$(grep "EC2_HOME" ~/.bashrc)
if [ $? -ne 0 ]; then
echo export EC2_HOME=$HOME/Dropbox/config/ec2/ec2-api-tools-1.4.2.4/ >> ~/.bashrc
else
echo "EC2_HOME exists"
fi
RES=$(grep "EC2_CERT" ~/.bashrc)
if [ $? -ne 0 ]; then
echo export EC2_CERT=$HOME/Dropbox/config/ec2/cert-3VJG2ORMUEMUWE2IZNQNZNH2IWS5HYEM.pem >> ~/.bashrc
else
echo "EC2_CERT exists"
fi
RES=$(grep "EC2_PRIVATE_KEY" ~/.bashrc)
if [ $? -ne 0 ]; then
echo export EC2_PRIVATE_KEY=$HOME/Dropbox/config/ec2/pk-3VJG2ORMUEMUWE2IZNQNZNH2IWS5HYEM.pem >> ~/.bashrc
else
echo "EC2_PRIVATE_KEY exists"
fi
RES=$(grep "PATH" ~/.bashrc)
if [ $? -ne 0 ]; then
echo export PATH=$PATH:$EC2_HOME/bin >> ~/.bashrc
else
echo "PATH exists"
fi
RES=$(grep "JAVA_HOME" ~/.bashrc)
if [ $? -ne 0 ]; then
echo export JAVA_HOME=/usr/lib/jvm/java-6-sun/jre >> ~/.bashrc
else
echo "JAVA_HOME exists"
fi
RES=$(grep "EC2_DEFAULT_KEY" ~/.bashrc)
if [ $? -ne 0 ]; then
echo export EC2_DEFAULT_KEY=$HOME/Dropbox/config/ec2/Default.pem >> ~/.bashrc
else
echo "EC2_DEFAULT_KEY exists"
fi
echo "Installed environmental variables into ~/.bashrc. Please restart the terminal"
<file_sep>#Exit statuses:
# 1: Incorrect arguements
# 2: Vhost already exists
#Follows the Gachnang Username Standard (haha)
# 1. Usernames for websites will be the web address.
# 1a. All periods will be replaced by double underscores.
# 1b. Username cannot exceed 16 characters, so they can be used in MySQL.
# 1c. Web address will be in the form example.com or sub.example.com
#Makes the script exit if anything is evaluated as false or a variable
#isn't set properly. Robust!!
#set -uo
#The directory in which the vhost files will be stored. Default is
# '/etc/apache2/sites-available/' in Debian/Ubuntu. Make sure it ends in a "/"
APACHE_DIR='/etc/apache2/sites-available/'
#Random Password Generator Script originally from jbreland
#http://legroom.net/2010/05/06/bash-random-password-generator
# Generate a random password
PASS=`cat /dev/urandom | tr -cd [:alnum:] | head -c ${1:-16}`
#Check for subdomain. Only works for singlur subdomain.
if [[ $1 == *.*.* ]]; then
#Domain is a subdomain
SUBDOMAIN=1
DOMAIN=${1#*.}
else
#Not subdomain
SUBDOMAIN=0
fi
#Removes the periods in the domain name and replaces them with double
#underscores (for usernames and database names)
if [ ${#name} -gt 16 ]; then
USERT=$(echo $1 | sed "s/\./__/" | cut -c1-16)
else
USERT=$(echo $1 | sed "s/\./__/")
fi
if [ USER==1 ]; then
USERT=$(echo $1 | sed "s/\./__/" | cut -c1-16)
fi
#Print usage if no args.
if [ $# != "2" ]; then
echo ""
echo "Generates a VirtualHost file for the given hostname, to be used with"
echo 'MindTouch multi-tenant installations. Must have "Include script-dir/*"'
echo "in an enabled Apache site for this to work. Apache will then use every"
echo "VHost file in that directory."
echo ""
echo " Usage:"
echo " vhost-gen.sh hostname admin_email"
echo ""
exit 1
fi
#Check if VHost directory exists. If not, make it.
if [ ! -d $APACHE_DIR ]; then
mkdir $APACHE_DIR
fi
if [ -f $APACHE_DIR$1 ]; then
echo "VHost already exists"
exit 2
fi
if [ ! -d /home/$USER ]; then
#User doesn't exist, doesn't consider users without home directories
USERDIR="/home/$USERTRUNC"
#Create user and user directory
useradd -m -d $USERDIR -U $USERT
#Set password
echo $PASS | passwd $USERT --stdin
else
echo "User already exists"
fi
mkdir /home/$USERT/$1/
mkdir /home/$USERT/$1/htdocs
mkdir /home/$USERT/$1/logs
touch /home/$USERT/$1/logs/access.log
touch /home/$USERT/$1/logs/error.log
#Write the vhost file to the Apache vhost directory
echo "<VirtualHost *:80>
ServerAdmin $2
ServerName $1
ServerAlias www.$1
DocumentRoot /home/$USERT/$1/htdocs/
<Directory /home/$USERT/$1/htdocs/>
Options Indexes FollowSymLinks ExecCGI
AllowOverride All
Order allow,deny
Allow from all
</Directory>
# Logfiles
ErrorLog /home/$USERT/$1/logs/error.log
CustomLog /home/$USERT/$1/logs/access.log combined
SuexecUserGroup $USERT $USERT
ScriptAlias /php-fastcgi/ /home/$USERT/$1/php-fastcgi/
FCGIWrapper /home/$USERT/$1/php-fastcgi/wrapper .php
AddHandler fcgid-script .php
Options ExecCGI Indexes
</VirtualHost>
" > $APACHE_DIR$1
#Enable the new vhost
a2ensite $APACHE_DIR$1
#Make Apache aware of the new VHost file.
/etc/init.d/apache2 reload
<file_sep>import os, subprocess, sys
def main(argv):
run(argv)
def run(arg):
"""
Runs the given arg at the command line using the default shell. Outputs
when commands are run successfully.
Based on http://developer.spikesource.com/wiki/index.php/How_to_invoke_subprocesses_from_Python
@param Tuple args
A tuple of args, with the first being the command to be run, and
the remaining ones flags and arguments for the command. STDOUT and
STDERR are piped to tuple, waiting until the output is finished,
then writing both to the log file, if not empty.
Ex. ['apt-get', '-y', 'install', 'dnsmasq'], which installs
dnsmasq using apt-get, and assumes yes to questions.
"""
# Open output and write some info about the command to be written, including
# name of command and arguments.
# This could be modified to adjust how much is printed via a DEBUG variable.
with open(os.path.join(os.curdir, "output.log"), 'a') as outFile:
outFile.write("Command: ")
for a in arg:
outFile.write(a,)
outFile.write(" ")
outFile.write("\n")
# Open output and error log file and append to them the output of the commands
with open(os.path.join(os.curdir, "output.log"), 'a') as outFile:
with open(os.path.join(os.curdir, "error.log"), 'a') as errorFile:
# Call the subprocess using convenience method
retval = subprocess.call(arg, -1, None, None, outFile, errorFile)
# Check the process exit code, print error information if it exists
if not retval == 0:
errData = errorFile.read()
raise Exception("Error executing command: " + repr(errData))
if __name__=="__main__":
main(sys.argv[1:])<file_sep>#!/usr/bin/python
# Copyright <NAME> 2010
# Release under the New BSD License
# ServerCobra.com
# Based off http://www.straw-dogs.co.uk/12/10/python-virtual-host-creator/
import getopt
import os
import subprocess
import sys
from random import randint, choice
def main(argv):
try:
opts, args = getopt.getopt(argv, "hd:a:", ["help", "domain="])
except getopt.GetoptError:
usage()
sys.exit(2)
if len(opts) == 0:
usage()
sys.exit(2)
for o, a in opts:
if o in ("-h", "--help"):
usage()
sys.exit()
if o in ("-d", "--domain"):
domain = a
normalize_domain = domain.replace(".", "__")
else:
assert False, "unhandled option"
#if not os.path.isdir("/var/www/%s" % directory):
# os.mkdir("/var/www/%s" % directory)
#if not os.path.isdir("/var/www/%s/htdocs" % directory):
# os.mkdir("/var/www/%s/htdocs" % directory)
default_vhost_template = """
<VirtualHost *:80>
ServerName __DOMAIN__
ServerAlias www.__DOMAIN__
#Log files
CustomLog /home/__NORM_DOM__/__NORM_DOM__/logs/access.log combined
ErrorLog /home/__NORM_DOM__/__NORM_DOM__/logs/error.log
ErrorDocument 404 /404.html
ErrorDocument 401 /401.html
ErrorDocument 500 /500.html
DocumentRoot /home/__NORM_DOM__/__NORM_DOM__/htdocs
<Directory /home/__NORM_DOM__/__NORM_DOM__/htdocs >
Options +Indexes +FollowSymlinks +ExecCGI +Includes -MultiViews
AllowOverride All
Order Allow,Deny
Allow from all
</directory>
</virtualhost>
"""
django_vhost_template = """
<VirtualHost *:80>
ServerName __DOMAIN__
ServerAlias www.__DOMAIN__
#Log files
CustomLog /home/__NORM_DOM__/__NORM_DOM__/logs/access.log combined
ErrorLog /home/__NORM_DOM__/__NORM_DOM__/logs/error.log
ErrorDocument 404 /404.html
ErrorDocument 401 /401.html
ErrorDocument 500 /500.html
DocumentRoot /home/__NORM_DOM__/__NORM_DOM__/htdocs
<Directory /home/__NORM_DOM__/__NORM_DOM__/htdocs >
Options +Indexes +FollowSymlinks +ExecCGI +Includes -MultiViews
AllowOverride All
Order Allow,Deny
Allow from all
</directory>
Alias /static /home/__NORM_DOM__/__NORM_DOM__/__APP__/static/
<Location "/static">
Order allow,deny
Allow from all
</Location>
Alias /media/ /usr/lib/python-django/django/contrib/admin/media/
<Location "/media/">
SetHandler None
Order allow,deny
Allow from all
</Location>
#Start mod_wsgi
WSGIScriptAlias / /home/__NORM_DOM__/__NORM_DOM__/__APP__/apache/wsgi_handler.py
<Directory "/home/__NORM_DOM__/__NORM_DOM__/__APP__/apache">
Order allow,deny
Allow from all
</Directory>
WSGIDaemonProcess __NORM_DOM__ user=__NORM_DOM__ group=__NORM_DOM__ processes=2 threads=10
WSGIProcessGroup __NORM_DOM__
</virtualhost>
"""
vhost = vhost_template.replace('__DOMAIN__', domain).replace('__NORM_DOM__', normalize_domain)
open('/etc/apache2/sites-available/%s.conf' % directory, 'w').write(vhost)
os.system('a2ensite %s.conf' % directory)
os.system('/etc/init.d/apache2 reload')
# Characters to be used while generating password
chars = string.ascii_letters + string.digits + "!#$&"
def random_password(length):
return "".join(choice(chars) for x in range(randint(length, length)))
def usage():
print 'usage: newv.py [-d domain.com]'
print ' Please exclude the "www" at the front of the domain'
def run(arg):
"""
Runs the given arg at the command line using the default shell. Outputs
when commands are run successfully.
Based on http://developer.spikesource.com/wiki/index.php/How_to_invoke_subprocesses_from_Python
@param Tuple args
A tuple of args, with the first being the command to be run, and
the remaining ones flags and arguments for the command. STDOUT and
STDERR are piped to tuple, waiting until the output is finished,
then writing both to the log files, if not empty.
Ex. ['apt-get', '-y', 'install', 'dnsmasq'], which installs
dnsmasq using apt-get, and assumes yes to questions.
"""
# Open output and write some info about the command to be written, including
# name of command and arguments.
# This could be modified to adjust how much is printed via a DEBUG variable.
with open(os.path.join(os.curdir, "output.log"), 'a') as outFile:
outFile.write("Command: ")
for a in arg:
outFile.write(a,)
outFile.write(" ")
outFile.write("\n")
# Open output and error log file and append to them the output of the commands
with open(os.path.join(os.curdir, "output.log"), 'a') as outFile:
with open(os.path.join(os.curdir, "error.log"), 'a') as errorFile:
# Call the subprocess using convenience method
retval = subprocess.call(arg, -1, None, None, outFile, errorFile)
# Check the process exit code, print error information if it exists
if not retval == 0:
errData = errorFile.read()
raise Exception("Error executing command: " + repr(errData))
if __name__=="__main__":
main(sys.argv[1:])<file_sep>#!/bin/bash
HOSTS="nang.kicks-ass.net"
COUNT=4
echo "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" >> /var/log/rsyncFreeNAS
echo "Starting rsync attempt at `date`" >> /var/log/rsyncFreeNAS
for myHost in $HOSTS
do
count=$(ping -c $COUNT $myHost | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }')
if [ $count -eq 0 ]; then
# 100% failed
echo "Host : $myHost is down (ping failed) at $(date)" >> /var/log/rsyncFreeNAS
else
echo "Host : $myHost is up at $(date)" >> /var/log/rsyncFreeNAS
#rsync -aP /home/josh/programming/* josh@$HOSTS:home >> /var/log/rsyncFreeNAS
rsync -aHvz -e ssh /home/josh/programming/* [email protected]:/mnt/storage/Config/home >> /var/log/rsyncFreeNAS
fi
done
echo "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" >> /var/log/rsyncFreeNAS
<file_sep>#Exit statuses:
# 1: Incorrect arguements
# 2: Vhost already exists
#Makes the script exit if anything is evaluated as false or a variable
#isn't set properly. Robust!!
#set -uo
#The directory in which the vhost files will be stored. Default is
# '/etc/apache2/sites-available/' in Debian/Ubuntu. Make sure it ends in a "/"
APACHE_DIR='/etc/apache2/sites-available/'
#MySQL hostname. Change to "localhost" if Apache and MySQL are on the same
#server.
MYSQL_HOST="localhost"
#Removes the periods in the domain name and replaces them with double
#underscores (for usernames and database names)
WIKI=$(echo $1 | sed "s/\./__/")
#Random Password Generator Script originally from jbreland
#http://legroom.net/2010/05/06/bash-random-password-generator
# Generate a random password
PASS=`cat /dev/urandom | tr -cd [:alnum:] | head -c ${1:-16}`
WEB_PASS=`cat /dev/urandom | tr -cd [:alnum:] | head -c ${1:-16}`
#Print usage if no args.
if [ $# != "2" ]; then
echo ""
echo "Generates a VirtualHost file for the given hostname, to be used with"
echo 'MindTouch multi-tenant installations. Must have "Include script-dir/*"'
echo "in an enabled Apache site for this to work. Apache will then use every"
echo "VHost file in that directory."
echo ""
echo " Usage:"
echo " vhost-gen.sh hostname admin_email"
echo ""
exit 1
fi
#Check if VHost directory exists. If not, make it.
if [ ! -d $APACHE_DIR ]; then
mkdir $APACHE_DIR
fi
if [ -f $APACHE_DIR$1 ]; then
echo "VHost already exists"
exit 2
fi
#Write the vhost file to the Apache vhost directory
#echo "<VirtualHost *:80>" >> $APACHE_DIR$1
#echo " ServerName $1" >> $APACHE_DIR$1
#echo " ServerAlias $1" >> $APACHE_DIR$1
#echo " DocumentRoot /var/www/dekiwiki/" >> $APACHE_DIR$1
#echo "</VirtualHost>" >> $APACHE_DIR$1
#Enable the new vhost
#a2ensite $APACHE_DIR$1
/var/www/dekiwiki/maintenance/createdb.sh --dbName $1 --dbAdminUser root --dbAdminPassword <PASSWORD> \
--dbServer localhost --dbWikiUser $WIKI --wikiAdmin Admin \
--wikiAdminPassword $<PASSWORD> --wikiAdminEmail $2 \
--storageDir /var/www/dekiwiki/attachments/$1 \
--s3PublicKey <KEY> \
--s3PrivateKey <KEY> \
--s3Bucket servercobra-mindtouch --s3Prefix $1 --s3Timeout 60\
--storageDir /var/www/dekiwiki/$1 >> /tmp/createdb
#Adds to the mindtouch config file, using sed to go in the middle of the file.
# -i is to do in place editing, while creating a backup file (file.bak)
#Searches for string "/globalconfig" (note escaped /)
#Then appends the rest at the next line (a\ )
#Final line specifies config file location. Note double quotes to allow
#variables in sed strings.
sed -i.bak "
/\/globalconfig/ a\
\ <config id=\"$1\">\
\n\ <host>$1</host>\
\n\ <db-server>localhost</db-server>\
\n\ <db-port>3306</db-port>\
\n\ <db-catalog>$WIKI</db-catalog>\
\n\ <db-user>$WIKI</db-user>\
\n\ <db-password>$PASS</db-user>\
\n\ <db-options>>pooling=true; Connection Timeout=5; Protocol=socket; Min Pool Size=2; Max Pool Size=50; Connection Reset=false;character set=utf8;$
\n\ </config>
" /etc/dekiwiki/mindtouch.deki.startup.xml
#Does the same as above, but modifies the LocalSettings.php file in
#the dekiwiki web directory. Not sure why there are two places for
#the same information though.
sed -i.bak "
/$wgWikis = array(/ a\
\ '$1' => array(
\n\ 'db-server' => 'localhost',
\n\ 'db-port' => '3306',
\n\ 'db-catalog' => '$WIKI',
\n\ 'db-user' => '$WIKI',
\n\ 'db-password' => <PASSWORD>',
\n\ ),
" /var/www/dekiwiki/LocalSettings.php
#Make Apache aware of the new VHost file.
/etc/init.d/apache2 reload
#Restart Mindtouch for changes to take effect. This needs to be fixed
#eventually, because everyone's site goes down at the same time.
#MindTouch has an artice on how they fixed it, which may be of use.
#
#http://developer.mindtouch.com/Wik.is/EC2_Infrastructure
/etc/init.d/dekiwiki restart
|
1086549cbaa4accb768b78cae880faaa03658acc
|
[
"Python",
"Shell"
] | 11 |
Shell
|
ruscon/Sysadmin-scripts
|
8c6b47590b49bf1918d2422c62c1eac95581b94a
|
0bb971bd7a12e9dcf8deebc822317223918f54a8
|
refs/heads/master
|
<repo_name>zzleomar/sigedocsoldBeta<file_sep>/app/RutasP.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class RutasP extends Model
{
protected $table = 'rutasp';
protected $primaryKey='id_ruta_p';
protected $fillable=['id_estado','id_preparaduria','id_dependencia','id_user','fecha'];
}
<file_sep>/public/js/MarksRecord.js
$(document).ready(function(){
var CSRF_TOKEN = $('input[name="_token"]').val();
var tipo = $('#tipo').val();
var url_base=$('#url_base').val();
var count=0;
$("#imgRecord").uploadFile({
url:url_base+"/file/upload",
fileName:"myfile",
allowedTypes:tipo,
acceptFiles:"image/*",
maxFileCount:1,
dragDrop:false,
multiple:false,
dragDropStr: "<span><b>Arrastre su archivo hasta Aqui</b></span>",
uploadStr:'Subir Imagen',
extErrorStr:'Solo archivos tipo imagen ',
cancelStr:"Cancelar",
doneStr:"Listo!!",
uploadErrorStr:"No se permite Subir",
formData: {"tipo":"imagen","_token":CSRF_TOKEN},
returnType: "json",
showDelete: true,
showPreview:true,
previewHeight: "150px",
previewWidth: "130px",
deleteCallback: function (data, pd) {
for (var i = 0; i < data.length; i++) {
$.post(url_base+"/file/delete", {op: "delete",name: data[i],"_token":CSRF_TOKEN},
function (resp,textStatus, jqXHR) {
//Show Message
$('#file-imgRecord').val('');
alert("Archivo Eliminado");
});
}
pd.statusbar.hide();
},
onSuccess:function(files,data,xhr,pd){
$("#file-imgRecord").val(data[0]);
},
customProgressBar: function (obj, s){
this.statusbar = $("<div class='ajax-file-upload-statusbar'></div>");
this.preview = $("<img class='ajax-file-upload-preview' />").width(s.previewWidth).height(s.previewHeight).appendTo(this.statusbar).hide();
this.filename = $("<div class='ajax-file-upload-filename'></div>").appendTo(this.statusbar);
this.progressDiv = $("<div class='progress progress-lg'>").appendTo(this.statusbar).hide();
this.progressbar = $("<div class='progress-bar progress-bar-info'></div>").appendTo(this.progressDiv);
this.abort = $("<div>" + s.abortStr + "</div>").appendTo(this.statusbar).hide();
this.cancel = $("<div>" + s.cancelStr + "</div>").appendTo(this.statusbar).hide();
this.done = $("<div>" + s.doneStr + "</div>").appendTo(this.statusbar).hide();
this.download = $("<div>" + s.downloadStr + "</div>").appendTo(this.statusbar).hide();
this.del = $("<div>" + s.deletelStr + "</div>").appendTo(this.statusbar).hide();
this.abort.addClass("ajax-file-upload-red");
this.done.addClass("btn btn-success");
this.download.addClass("btn btn-success");
this.cancel.addClass("btn btn-danger");
this.del.addClass("btn btn-danger");
if (count++ % 2 == 0)
this.statusbar.addClass("even");
else
this.statusbar.addClass("odd");
return this;
}
});
});<file_sep>/database/seeds/CircularesTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\Circular;
class CircularesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$Circular=[[
'id_circular'=>'1',
'id_documento'=>'1',
'id_itemsubcategoria'=>'1',
'nota_circular'=>'La consideracion debe ser debidamente justificada.',
'para_circular'=>'PROFESORES DEL PROGRAMA DE LA LICENCIATURA EN INFORMATICA',
'de_circular'=>'PROFA. DIANELINA AGUIAR (COORDINADORA)',
'cuerpo_circular'=>'Estimados colegas si usted necesita que se tome en cuenta alguna consideración en la asignación de sus horas academicas para el venidero Semestre I-2013, favor enviarlo por correo a mas tardar el dia 01/02/2013.'
. ''
. 'Sin Otra particular y seguro de contar con su colaboracion, se despide. Gato motas',
'numero'=>'8',
'anio_circular'=>'2018',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
]];
foreach($Circular as $circulares){
if(!Circular::find($circulares['id_circular'])){
DB::table('circular')->insert($circulares);
}
}
}
}
<file_sep>/app/Asignaturas.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Asignaturas extends Model
{
//
protected $table='asignatura';
protected $primaryKey='id_asignatura';
protected $fillable=['codigo','nombre','semestre'];
}
<file_sep>/database/migrations/2018_04_24_171048_create_preparaduria_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePreparaduriaTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('preparaduria', function (Blueprint $table) {
$table->increments('id_preparaduria');
$table->integer('id_estados')->unsigned();
$table->foreign('id_estados')->references('id_estados')->on('estados')->onDelete('cascade');
$table->integer('id_concurso')->unsigned();
$table->foreign('id_concurso')->references('id_concurso')->on('concurso')->onDelete('cascade');
$table->integer('id_estudiante')->unsigned();
$table->foreign('id_estudiante')->references('id_estudiante')->on('estudiante')->onDelete('cascade');
$table->integer('id_asignatura')->unsigned();
$table->foreign('id_asignatura')->references('id_asignatura')->on('asignatura')->onDelete('cascade');
$table->integer('id_periodo')->unsigned();
$table->foreign('id_periodo')->references('id_periodo')->on('periodo')->onDelete('cascade');
$table->integer('numero');
$table->text('anio');
$table->text('semestre');
$table->text('creditos_aprobados');
$table->text('promedio_general');
$table->text('record');
$table->text('nota');
$table->text('observacion');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('preparaduria');
}
}
<file_sep>/database/migrations/2018_04_27_161216_create_rutasp_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRutaspTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('rutasp', function (Blueprint $table) {
$table->increments('id_ruta_p');
$table->integer('id_estado')->unsigned();
$table->foreign('id_estado')->references('id_estados')->on('estados')->onDelete('cascade');
$table->integer('id_preparaduria')->unsigned();
$table->foreign('id_preparaduria')->references('id_preparaduria')->on('preparaduria')->onDelete('cascade');
$table->integer('id_dependencia')->unsigned();
$table->foreign('id_dependencia')->references('id_dependencia')->on('dependencia')->onDelete('cascade');
$table->integer('id_user')->unsigned();
$table->foreign('id_user')->references('id')->on('users')->onDelete('cascade');
$table->date('fecha');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('rutasP');
}
}
<file_sep>/app/RutaOficio.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class RutaOficio extends Model
{
protected $table = 'ruta_oficio';
protected $primaryKey='id_ruta_oficio';
protected $fillable=['id_estado','id_oficio','id_dependencia','id_user','fecha'];
}
<file_sep>/app/JefeDepartamento.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class JefeDepartamento extends Model
{
protected $table = 'jefedepartamento';
protected $primaryKey='id_jefedepartamento';
protected $fillable=['id_profesor','id_dependencia'];
}<file_sep>/app/Http/Controllers/UbicacionOficioControllers.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Oficio;
use App\Dependencia;
class UbicacionOficioControllers extends Controller
{
public function show($id){
$Oficio=Oficio::where('id_documento',$id)->get();
$Dependencia= Dependencia::where('id_dependencia',$Oficio[0]['attributes']['id_dependencia'])->get();
$Escuela=$Dependencia[0]['attributes']['id_escuela'];
$data=DB::table('ruta_oficio')->
select('escuela.nombre as escuela','users.nombres','perfil.nombre_perfil','users.apellidos','users.id_perfil','documento.codigo_plantilla','documento.descripcion_documento','oficio.acronimo','ruta_oficio.fecha','dependencia.nombre_dependencia','estados.id_estados','estados.nombre')
->join('oficio','ruta_oficio.id_oficio','=','oficio.id_oficio')
->join('documento','oficio.id_documento','=','documento.id_documento')
->join('dependencia','oficio.id_dependencia','=','dependencia.id_dependencia')
->join('escuela','dependencia.id_escuela','=','dependencia.id_escuela')
->join('estados','ruta_oficio.id_estado','=','estados.id_estados')
->join('users','ruta_oficio.id_user','=','users.id')
->join('perfil','users.id_perfil','=','perfil.id_perfil')
->where('ruta_oficio.id_oficio',$Oficio[0]['attributes']['id_oficio'])
->where ('escuela.id_escuela',$Escuela)
->orderBy('ruta_oficio.fecha', 'asc')->get();
return view('ubicacionoficio/show')->with(['data'=>$data]);
}
}
<file_sep>/database/seeds/CiudadTableSeeders.php
<?php
use Illuminate\Database\Seeder;
Use App\Ciudades;
class CiudadTableSeeders extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$Ciudad=[[
'id_ciudad'=>'1',
'id_pais'=>'1',
'id_state'=>'1' ,
'id_municipio'=>'1',
'nombre'=>'Cumana',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_ciudad'=>'2',
'id_pais'=>'1',
'id_state'=>'1' ,
'id_municipio'=>'2',
'nombre'=>'Guiria',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',],[
'id_ciudad'=>'3',
'id_pais'=>'1',
'id_state'=>'1' ,
'id_municipio'=>'3',
'nombre'=>'Cumanacoa',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_ciudad'=>'4',
'id_pais'=>'1',
'id_state'=>'4' ,
'id_municipio'=>'4',
'nombre'=>'<NAME>',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_ciudad'=>'5',
'id_pais'=>'2',
'id_state'=>'3' ,
'id_municipio'=>'5',
'nombre'=>'Madrid',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_ciudad'=>'6',
'id_pais'=>'2',
'id_state'=>'2' ,
'id_municipio'=>'6',
'nombre'=>'Barcelona',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_ciudad'=>'7',
'id_pais'=>'2',
'id_state'=>'2' ,
'id_municipio'=>'6',
'nombre'=>'Girona/Gerona',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
]];
foreach($Ciudad as $Ciudades){
if(!Ciudades::find($Ciudades['id_ciudad'])){
DB::table('ciudad')->insert($Ciudades);
}
}
}
}
<file_sep>/database/seeds/StatusTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\Status;
class StatusTableSeeder extends Seeder
{
public function run()
{
$status=[
['id_status'=>'1','name'=>'Aprobado'],
['id_status'=>'2','name'=>'Pendiente'],
['id_status'=>'3','name'=>'Suspendido'],
['id_status'=>'4','name'=>'Bloqueado']
];
foreach($status as $statu){
if(!Status::find($statu['id_status'])){
DB::table('status')->insert($statu);
}
}
}
}
<file_sep>/app/Convocatoria.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Convocatoria extends Model
{
protected $table = 'convocatoria';
protected $primaryKey='id_convocatoria';
protected $fillable=['id_itemsubcategoria','codigo_convocatoria','nota_convocatoria','para_convocatoria','de_convocatoria','cuerpo_convocatoria','html_convocatoria'];
}<file_sep>/app/Preparadurias.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Preparadurias extends Model
{
protected $table='preparaduria';
protected $primaryKey='id_preparaduria';
protected $fillable=['id_estados','id_estudiante','id_asignatura','semestre','creditos_aprobados','promedio_general','f2','f3','f4','f5','f6','f7','condicion'];
}
<file_sep>/app/Sellos.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Sellos extends Model
{
protected $table='sello';
protected $primaryKey='id_sello';
protected $fillable=['id_dependencia','sello'];
}
<file_sep>/database/seeds/DocumentosTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\Documento;
class DocumentosTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$Documento=[[
'id_documento'=>'1',
'id_dependencia_c'=>'2',
'id_usuario'=>'4',
'id_categoria'=>'1',
'id_subcategoria'=>'1',
'id_itemsubcategoria'=>'1',
'id_estados'=>'7',
'codigo_plantilla'=>'1523450668',
'descripcion_documento'=>'Circular',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
]];
foreach($Documento as $Documentos){
if(!Documento::find($Documentos['id_documento'])){
DB::table('documento')->insert($Documentos);
}
}
}
}
<file_sep>/app/User.php
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Database\Eloquent\Relations;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use DB;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['id_dependencia','id_perfil','id_pais','id_state','id_municipio','id_ciudad','name', 'email','avatar','cedula','nombres','apellidos','telefono','sexo','ocupacion'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
public function perfil()
{
return $this->belongsToMany('App\Perfil');
}
public static function usuario($id,$id_perfil)
{
return User::select(DB::table('users')
->raw("CONCAT(users.nombres,' ',users.apellidos) AS fullname"),'id')
->where('id_perfil',$id_perfil)
->where('id_dependencia', $id)
->get();
}
}<file_sep>/database/migrations/2018_04_18_162636_create_documento_table.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateDocumentoTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('documento', function (Blueprint $table) {
$table->increments('id_documento');
$table->integer('id_dependencia_c')->unsigned();
$table->foreign('id_dependencia_c')->references('id_dependencia')->on('dependencia')->onDelete('cascade');
$table->integer('id_usuario')->unsigned();
$table->foreign('id_usuario')->references('id')->on('users')->onDelete('cascade');
$table->integer('id_categoria')->unsigned();
$table->foreign('id_categoria')->references('id_categoria')->on('categoria_documento')->onDelete('cascade');
$table->integer('id_subcategoria')->unsigned();
$table->foreign('id_subcategoria')->references('id_subcategoria')->on('subcategoria_documento')->onDelete('cascade');
$table->integer('id_itemsubcategoria')->unsigned();
$table->foreign('id_itemsubcategoria')->references('id_itemsubcategoria')->on('itemsubcategoria')->onDelete('cascade');
$table->integer('id_estados')->unsigned();
$table->foreign('id_estados')->references('id_estados')->on('estados')->onDelete('cascade');
$table->integer('codigo_plantilla')->unique();
$table->text('descripcion_documento');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('documento');
}
}
<file_sep>/app/AsignarAulas.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class AsignarAulas extends Model
{
protected $table='asignar_aula';
protected $primaryKey='id_asignar_aula';
protected $fillable=['id_horario','id_aula','dia','entrada','salida'];
}
<file_sep>/public/js/correcion.js
$(document).ready(function(){
$('#id_categoria').val($('#id_categoria_h').val()).change();
});<file_sep>/database/seeds/MunicipiosTableSeeders.php
<?php
use Illuminate\Database\Seeder;
Use App\Municipios;
class MunicipiosTableSeeders extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$Municipio=[[
'id_municipio'=>'1',
'id_state'=>'1' ,
'id_pais'=>'1',
'nombre'=>'Sucre',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_municipio'=>'2',
'id_state'=>'1' ,
'id_pais'=>'1',
'nombre'=>'Valdez',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05'],
[
'id_municipio'=>'3',
'id_state'=>'1' ,
'id_pais'=>'1',
'nombre'=>'Montes',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_municipio'=>'4',
'id_state'=>'4' ,
'id_pais'=>'1',
'nombre'=>'Sotillo',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_municipio'=>'5',
'id_state'=>'3' ,
'id_pais'=>'2',
'nombre'=>'Comunidad De Madrid',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_municipio'=>'6',
'id_state'=>'2' ,
'id_pais'=>'2',
'nombre'=>'Cataluña',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
]];
foreach($Municipio as $Municipios){
if(!Municipios::find($Municipios['id_municipio'])){
DB::table('municipio')->insert($Municipios);
}
}
}
}
<file_sep>/app/Http/Controllers/ComprasController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Compras;
use App\Material;
use App\SolicitudCompras;
use App\DependenciaUDO;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use DB;
use Auth;
class ComprasController extends Controller
{
public function index()
{
$Material= Material::pluck('descripcion','id_material');
return view('compras/index')->with(['Material'=>$Material]);
}
public function GuargarSolicitudCompra(Request $request)
{
$rules =
[
'observacion' =>'required',
'material_id' =>'required',
'cantidad' =>'required|numeric',
];
$mensajes=array(
'observacion.required'=>'La Observacion es Obligatoria',
'material_id.required'=>'El Material a Solicitar es Obligatoria',
'cantidad.required'=>'La Cantidad es Obligatoria',
'cantidad.numeric'=>'La Cantidad debe ser numerica',
);
$validator = Validator::make(Input::all(), $rules,$mensajes);
if ($validator->fails())
{
return \Response::json([
'created' => false,
'errors' => $validator->errors()->all()
],500);
}
else
{
DB::beginTransaction();
$Dependencia=DependenciaUDO::where('id_dependencia','59')->first();
$P=Compras::where('estatus_id','1')->count();
$D=Compras::where('estatus_id','1')->first();
$C=Compras::select('nrosol')->where('anio',date('Y'))->count();
$Material=Material::where('id_material',$request->material_id)->first();
if($C>0)
{
$nrooficio=$C+1;
}
else
{
$nrooficio=1;
}
if( $P>0)
{
$F=SolicitudCompras::where('compra_id',$D->id_compra)->where('material_id',$request->material_id)->count();
if($F>0){
return \Response::json([
'created' => false,
'errores' => 'El Material '. $Material->descripcion. ' ya se encuentra registrado en la Solicitud de Compra N°: '.$D->nro_solicitud
],500);
}
else
{
$Sol_Compra=new SolicitudCompras();
$Sol_Compra->compra_id=$D->id_compra;
$Sol_Compra->material_id=$request->material_id;
$Sol_Compra->cantidad=$request->cantidad;
$Sol_Compra->save();
}
}
else
{
$NroSolicitud=$Dependencia->siglas.'-N°'.$nrooficio.'/'.date('Y');
$Compra=new Compras();
$Compra->dependencia_id=Auth::user()->id_dependencia;
$Compra->estatus_id='1';
$Compra->nrosol=$nrooficio;
$Compra->nro_solicitud=$NroSolicitud;
$Compra->fecha=date('Y-m-d');
$Compra->anio=date('Y');
$Compra->observacion=$request->observacion;
$Compra->solicitado_por=$Dependencia->responsable_ejec;
$Compra->conformado_por='Licdo. Homer <NAME>';
$Compra->autorizado_por='R-VRA-VRAD-S-D';
$Compra->save();
$Sol_Compra=new SolicitudCompras();
$Sol_Compra->compra_id=$Compra->id_compra;
$Sol_Compra->material_id=$request->material_id;
$Sol_Compra->cantidad=$request->cantidad;
$Sol_Compra->save();
}
$Dx=Compras::where('estatus_id','1')->first();
DB::commit();
return \Response::json([
'created' => true,
'mensaje' => "Se registro con exito el Material: ".$Material->descripcion.' En la Solicitud de Compra N° '.$Dx->nro_solicitud,
'id_compra'=> $Sol_Compra->compra_id
],200);
}
}
public function AgregarSolicitudCompra(Request $request)
{
$rules =
[
'material_id' =>'required',
'cantidad' =>'required|numeric',
];
$mensajes=array(
'material_id.required'=>'El Material a Solicitar es Obligatoria',
'cantidad.required'=>'La Cantidad es Obligatoria',
'cantidad.numeric'=>'La Cantidad debe ser numerica',
);
$validator = Validator::make(Input::all(), $rules,$mensajes);
if ($validator->fails())
{
return \Response::json([
'created' => false,
'errors' => $validator->errors()->all()
],500);
}
else
{
DB::beginTransaction();
$Dependencia=DependenciaUDO::where('id_dependencia','59')->first();
$P=Compras::where('estatus_id','17')->count();
$D=Compras::where('estatus_id','17')->first();
$C=Compras::select('nrosol')->where('anio',date('Y'))->count();
$Material=Material::where('id_material',$request->material_id)->first();
if($C>0)
{
$nrooficio=$C+1;
}
else
{
$nrooficio=1;
}
if( $P>0)
{
$F=SolicitudCompras::where('compra_id',$D->id_compra)->where('material_id',$request->material_id)->count();
if($F>0){
return \Response::json([
'created' => false,
'errores' => 'El Material '. $Material->descripcion. ' ya se encuentra registrado en la Solicitud de Compra N°: '.$D->nro_solicitud
],500);
}
else
{
$Sol_Compra=new SolicitudCompras();
$Sol_Compra->compra_id=$D->id_compra;
$Sol_Compra->material_id=$request->material_id;
$Sol_Compra->cantidad=$request->cantidad;
$Sol_Compra->save();
}
}
$Dx=Compras::where('estatus_id','17')->first();
DB::commit();
return \Response::json([
'created' => true,
'mensaje' => "Se registro con exito el Material: ".$Material->descripcion.' En la Solicitud de Compra N° '.$Dx->nro_solicitud,
'id_compra'=> $Sol_Compra->compra_id
],200);
}
}
public function MostrarCompras()
{
$Compras= array();
$Compras= Compras::select('compra.*','dependencia_udo.descripcion','estados.nombre')->join('dependencia_udo','compra.dependencia_id','=','dependencia_udo.id_dependencia')->join('estados','compra.estatus_id','=','estados.id_estados')->orderby('compra.estatus_id','asc')->orderby('compra.id_compra','asc')->paginate(10);
return
[
'pagination'=>
[
'total'=>$Compras->total(),
'current_page'=>$Compras->currentPage(),
'per_page'=>$Compras->perPage(),
'last_page'=>$Compras->lastPage(),
'from'=>$Compras->firstItem(),
'to'=>$Compras->lastItem(),
],
'compras'=>$Compras
];
}
public function editshow($id){
$Compras= array();
$Compras= Compras::select('compra.*','material.descripcion as material','material.unidad_medida','material.codigo','dependencia_udo.descripcion','estados.nombre','solicitud_compra.cantidad','solicitud_compra.id_solicitud_compra')
->join('dependencia_udo','compra.dependencia_id','=','dependencia_udo.id_dependencia')
->join('solicitud_compra','compra.id_compra','=','solicitud_compra.compra_id')
->join('material','solicitud_compra.material_id','=','material.id_material')
->join('estados','compra.estatus_id','=','estados.id_estados')
->where('compra.id_compra',$id)
->orderby('compra.id_compra','asc')
->paginate(4);
return
[
'pagination_edit_materiales'=>
[
'totals_edit'=>$Compras->total(),
'current_pages_edit'=>$Compras->currentPage(),
'per_pages_edit'=>$Compras->perPage(),
'last_pages_edit'=>$Compras->lastPage(),
'froms_edit'=>$Compras->firstItem(),
'tos_edit'=>$Compras->lastItem(),
],
'compras'=>$Compras
];
}
public function show($id)
{
$Compras= array();
$Compras= Compras::select('compra.*','material.descripcion as material','material.unidad_medida','material.codigo','dependencia_udo.descripcion','estados.nombre','solicitud_compra.cantidad','solicitud_compra.id_solicitud_compra')
->join('dependencia_udo','compra.dependencia_id','=','dependencia_udo.id_dependencia')
->join('solicitud_compra','compra.id_compra','=','solicitud_compra.compra_id')
->join('material','solicitud_compra.material_id','=','material.id_material')
->join('estados','compra.estatus_id','=','estados.id_estados')
->where('compra.id_compra',$id)
->orderby('compra.id_compra','asc')
->paginate(4);
return
[
'pagination_edit_materiales'=>
[
'totals_edit'=>$Compras->total(),
'current_pages_edit'=>$Compras->currentPage(),
'per_pages_edit'=>$Compras->perPage(),
'last_pages_edit'=>$Compras->lastPage(),
'froms_edit'=>$Compras->firstItem(),
'tos_edit'=>$Compras->lastItem(),
],
'compras'=>$Compras
];
}
public function showMateriales($id)
{
$Compras= array();
$Compras= Compras::select('compra.*','material.descripcion as material','material.unidad_medida','material.codigo','dependencia_udo.descripcion','estados.nombre','solicitud_compra.cantidad','solicitud_compra.id_solicitud_compra')
->join('dependencia_udo','compra.dependencia_id','=','dependencia_udo.id_dependencia')
->join('solicitud_compra','compra.id_compra','=','solicitud_compra.compra_id')
->join('material','solicitud_compra.material_id','=','material.id_material')
->join('estados','compra.estatus_id','=','estados.id_estados')
->where('compra.id_compra',$id)
->orderby('compra.id_compra','asc')
->paginate(4);
return
[
'pagination_edit_materiales'=>
[
'totals_edit'=>$Compras->total(),
'current_pages_edit'=>$Compras->currentPage(),
'per_pages_edit'=>$Compras->perPage(),
'last_pages_edit'=>$Compras->lastPage(),
'froms_edit'=>$Compras->firstItem(),
'tos_edit'=>$Compras->lastItem(),
],
'compras'=>$Compras
];
}
public function Materiales($id)
{
$Compras= array();
$Compras= Compras::select('compra.id_compra','material.descripcion as material','material.unidad_medida','material.codigo','solicitud_compra.cantidad','solicitud_compra.id_solicitud_compra')
->join('solicitud_compra','compra.id_compra','=','solicitud_compra.compra_id')
->join('material','solicitud_compra.material_id','=','material.id_material')
->where('compra.id_compra',$id)
->paginate(4);
return
[
'pagination_materiales'=>
[
'totals'=>$Compras->total(),
'current_pages'=>$Compras->currentPage(),
'per_pages'=>$Compras->perPage(),
'last_pages'=>$Compras->lastPage(),
'froms'=>$Compras->firstItem(),
'tos'=>$Compras->lastItem(),
],
'compras'=>$Compras
];
}
public function MaterialesNew($id)
{
$Compras= array();
$Compras= Compras::select('compra.id_compra','material.descripcion as material','material.unidad_medida','material.codigo','solicitud_compra.cantidad','solicitud_compra.id_solicitud_compra')
->join('solicitud_compra','compra.id_compra','=','solicitud_compra.compra_id')
->join('material','solicitud_compra.material_id','=','material.id_material')
->where('compra.id_compra',$id)
->paginate(4);
return
[
'pagination_materiales_new'=>
[
'total_new'=>$Compras->total(),
'current_page_new'=>$Compras->currentPage(),
'per_page_new'=>$Compras->perPage(),
'last_page_new'=>$Compras->lastPage(),
'from_new'=>$Compras->firstItem(),
'to_new'=>$Compras->lastItem(),
],
'compras'=>$Compras
];
}
public function Borrador($id_compra){
Compras::where('id_compra',$id_compra)->update(['estatus_id' =>'17']);
}
public function PorAutorizar($id_compra){
Compras::where('id_compra',$id_compra)->update(['estatus_id' =>'18']);
}
public function ModificarCompras(){
}
}<file_sep>/app/Dependencia.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Dependencia extends Model
{
//
protected $table='dependencia';
protected $primaryKey='id_dependencia';
protected $fillable=['id_user','id_institucion','nombre_dependencia','descripcion_dependencia','relacion_dependencia','cedula_jefe'];
}<file_sep>/public/js/dropdown.js
/**
* Created by Administrador on 24/10/2016.
*/
var url_base=$('#url_base').val();
$("#id_pais").prop('selectedIndex',0);
$("#id_pais").change(function (event) {
$.get(url_base+"/usuarios/" + event.target.value + "", function (response, id_pais) {
$("#id_state").empty();
$("#id_state").append("<option value=''>Seleccione Un Estado</option>");
for (i = 0; i < response.length; i++) {
$("#id_state").append("<option value='" + response[i].id_state + "'>" + response[i].nombre + "</option>");
}
if($('#id_state_h').val()){
$('#id_state').val($('#id_state_h').val()).change();
}
});
});
$("#id_state").prop('selectedIndex',0);
$("#id_state").change(function (event) {
$.get(url_base+"/usuarios/municipio/" + event.target.value + "", function (response, id_state) {
$("#id_municipio").empty();
$("#id_municipio").append("<option value=''>Seleccione Un Municipio</option>");
for (i = 0; i < response.length; i++) {
$("#id_municipio").append("<option value='" + response[i].id_municipio + "'>" + response[i].nombre + "</option>");
}
if($('#id_municipio_h').val()){
$('#id_municipio').val($('#id_municipio_h').val()).change();
}
});
});
$("#id_municipio").change(function (event) {
$.get(url_base+"/usuarios/ciudad/" + event.target.value + "", function (response, id_municipio) {
$("#id_ciudad").empty();
$("#id_ciudad").append("<option value=''>Seleccione Una Ciudad</option>");
for (i = 0; i < response.length; i++) {
$("#id_ciudad").append("<option value='" + response[i].id_ciudad + "'>" + response[i].nombre + "</option>");
}
if($('#id_ciudad_h').val()){
$('#id_ciudad').val($('#id_ciudad_h').val()).change();
}
});
});
$("#id_categoria").change(function (event) {
$.get(url_base+"/documentos/" + event.target.value + "", function (response, id_categoria) {
$("#id_subcategoria").empty();
$("#id_subcategoria").append("<option value=''>Seleccione Un Documento</option>");
for (i = 0; i < response.length; i++) {
$("#id_subcategoria").append("<option value='" + response[i].id_subcategoria + "'>" + response[i].nombre_subcategoria + "</option>");
}
if($('#id_subcategoria_h').val()){
$('#id_subcategoria').val($('#id_subcategoria_h').val()).change();
}
});
});
$("#id_subcategoria").change(function (event) {
$.get(url_base+"/documentos/ItemSubcategoria/" + event.target.value + "", function (response, id_subcategoria) {
$("#id_itemsubcategoria").empty();
$("#id_itemsubcategoria").append("<option value=''>Seleccione Una Plantilla</option>");
for (i = 0; i < response.length; i++) {
$("#id_itemsubcategoria").append("<option value='" + response[i].id_itemsubcategoria + "'>" + response[i].nombre_itemsubcategoria + "</option>");
}
if($('#id_itemsubcategoria_h').val()){
$('#id_itemsubcategoria').val($('#id_itemsubcategoria_h').val()).change();
}
});
});
$("#id_itemsubcategoria").change(function (event)
{
$('#pleaseWaitDialog').modal('show');
var subcategoria= $('select[name=id_itemsubcategoria]').val();
alert(subcategoria)
if(subcategoria<5)
{
$('#circular').show();
$('#pleaseWaitDialog').modal('hide');
$('#oficio').hide();
$('#estructurado').hide();
}
if(subcategoria==9)//oficio
{
$('#libre').show();
$('#pleaseWaitDialog').modal('hide');
$('#circular').hide();
$('#estructurado').hide();
}
if(subcategoria==11)//convocatorias
{
$('#convocatoria').show();
$('#estructurado').hide();
$('#pleaseWaitDialog').modal('hide');
$('#libre').hide();
$('#circular').hide();
}
if(subcategoria==10)//oficio
{
$('#libre').hide();
$('#pleaseWaitDialog').modal('hide');
$('#circular').hide();
$('#estructurado').show();
$('#convocatoria').hide();
}
});
$("#id_dependencia").prop('selectedIndex',0);
$("#id_dependencia").change(function (event) {
var id_perfil=$('select[name=id_perfil]').val();
$.get(url_base+"/oficios/" + event.target.value + "/"+id_perfil+ "", function (response, id_dependencia) {
$("#id").empty();
$("#id").append("<option value=''>Seleccione Una Persona</option>");
for (i = 0; i < response.length; i++) {
$("#id").append("<option value='" + response[i].id + "'>" + response[i].fullname + "</option>");
}
if($('#id_h').val()){
$('#id').val($('#id_h').val()).change();
}
});
});
$("#id_tipo_oficio").change(function (event)
{
$('#pleaseWaitDialog').modal('show');
var tipooficio= $('select[name=id_tipo_oficio]').val();
if(tipooficio==1)
{
$('#contratacion').show();
$('#pleaseWaitDialog').modal('hide');
}
});<file_sep>/database/migrations/2018_04_18_162633_create_subcategoria_documento_table.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSubcategoriaDocumentoTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('subcategoria_documento', function (Blueprint $table) {
$table->increments('id_subcategoria');
$table->integer('id_categoria')->unsigned();
$table->foreign('id_categoria')->references('id_categoria')->on('categoria_documento')->onDelete('cascade');
$table->string('nombre_subcategoria');
$table->text('descripcion_subcategoria');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('subcategoria_documento');
}
}
<file_sep>/database/seeds/UsersTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\User;
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$User=[[
'id'=>'1',
'status_id'=>'1',
'id_nom_nucleo'=>'1',
'id_dependencia'=>'58',
'id_perfil'=>'1',
'personal_id'=>'267',
'name'=>'ebetancourt',
'email'=>'<EMAIL>',
'avatar'=>'udologo.png',
'password'=>bcrypt('<PASSWORD>'),
'created_at'=>'2018-06-20 17:00:00',
'updated_at'=>'2018-06-20 17:00:00'
],[
'id'=>'2',
'status_id'=>'1',
'id_nom_nucleo'=>'1',
'id_dependencia'=>'58',
'id_perfil'=>'7',
'personal_id'=>'1662',
'name'=>'mpagliarulo',
'email'=>'<EMAIL>',
'avatar'=>'udologo.png',
'password'=>bcrypt('<PASSWORD>'),
'created_at'=>'2018-06-20 17:00:00',
'updated_at'=>'2018-06-20 17:00:00'
]];
foreach($User as $Usuarios){
if(!User::find($Usuarios['id'])){
DB::table('users')->insert($Usuarios);
}
}
}}
<file_sep>/database/seeds/RutasTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\Ruta;
class RutasTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$Ruta=[[
'id_ruta'=>'1',
'id_estado'=>'1',
'id_documento'=>'1',
'id_dependencia'=>'2',
'id_user'=>'4',
'fecha'=>'2017-04-01',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_ruta'=>'2',
'id_estado'=>'2',
'id_documento'=>'1',
'id_dependencia'=>'2',
'id_user'=>'3',
'fecha'=>'2017-04-02',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_ruta'=>'3',
'id_estado'=>'3',
'id_documento'=>'1',
'id_dependencia'=>'2',
'id_user'=>'3',
'fecha'=>'2017-04-03',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_ruta'=>'4',
'id_estado'=>'4',
'id_documento'=>'1',
'id_dependencia'=>'2',
'id_user'=>'4',
'fecha'=>'2017-04-04',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_ruta'=>'5',
'id_estado'=>'5',
'id_documento'=>'1',
'id_dependencia'=>'2',
'id_user'=>'4',
'fecha'=>'2017-04-05',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_ruta'=>'6',
'id_estado'=>'6',
'id_documento'=>'1',
'id_dependencia'=>'2',
'id_user'=>'3',
'fecha'=>'2017-04-07',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_ruta'=>'7',
'id_estado'=>'7',
'id_documento'=>'1',
'id_dependencia'=>'2',
'id_user'=>'3',
'fecha'=>'2017-04-08',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
]];
foreach($Ruta as $rutas){
if(!Ruta::find($rutas['id_ruta'])){
DB::table('ruta')->insert($rutas);
}
}
}
}<file_sep>/database/seeds/InstitucionesTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\Institucion;
class InstitucionesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$Institucion=[[
'id_institucion'=>'1',
'nombre_institucion'=>'Universidad De Oriente',
'siglas_institucion'=>'UDO',
'descripcion_institucion'=>'UNIVERSIDAD DE ORIENTE Nucleo de Sucre',
'nucleo_institucion'=>'Nucleo de Sucre',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
]];
foreach($Institucion as $Instituciones){
if(!Institucion::find($Instituciones['id_institucion'])){
DB::table('institucion')->insert($Instituciones);
}
}
}
}<file_sep>/app/Http/Controllers/BusquedaPersonalController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Personal;
use Yajra\Datatables\Datatables;
class BusquedaPersonalController extends Controller
{
public function store(Request $request)
{
$Personal=Personal::select(['personal.id_personal','personal.nacionalidad','personal.nombre','personal.apellido','personal.telefono_oficina','personal.telefono_habitacion','personal.unidad_ejecutora','personal.unidad_asignado','dependencia_udo.descripcion','dependencia_udo.id_dependencia'])
->join('dependencia_udo','personal.unidad_asignado','=','dependencia_udo.dependencia')
->where('personal.cedula',$request->cedula);
return Datatables::of($Personal)->make(true);
}
/*public function busqueda(Request $request){
$Personal=Personal::select(['personal.id_personal','personal.nacionalidad','personal.nombre','personal.apellido','personal.telefono_oficina','personal.telefono_habitacion','personal.unidad_ejecutora','personal.unidad_asignado','dependencia_udo.descripcion','dependencia_udo.id_dependencia'])
->join('dependencia_udo','personal.unidad_asignado','=','dependencia_udo.dependencia')
->where('personal.cedula',$request->cedula);
return Datatables::of($Personal)->make(true);
}*/
}
<file_sep>/database/migrations/2018_05_01_194232_create_contratacion_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateContratacionTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('contratacion', function (Blueprint $table) {
$table->increments('id_contratacion');
$table->integer('id_user')->unsigned();
$table->foreign('id_user')->references('id')->on('users')->onDelete('cascade');
$table->integer('id_oficio')->unsigned();
$table->foreign('id_oficio')->references('id_oficio')->on('oficio')->onDelete('cascade');
$table->integer('id_asignatura')->unsigned();
$table->foreign('id_asignatura')->references('id_asignatura')->on('asignatura')->onDelete('cascade');
$table->text('periodo');
$table->text('seccion');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('contratacion');
}
}
<file_sep>/public/js/Usuario.js
$("#CrearUsuario").click(function ()
{
$('#pleaseWaitDialog').modal('show');
$.ajax
({
type: 'post',
url: $('#url_base').val()+'/usuarios/agregarUsuario',
data: {
'_token': $('input[name=_token]').val(),
'cedula': $('input[name=cedula]').val(),
'nombre': $('input[name=nombre]').val(),
'apellido': $('input[name=apellido]').val(),
'telefono': $('input[name=telefono]').val(),
'sexo': $('select[name=sexo]').val(),
'email': $('input[name=email]').val(),
'ocupacion': $('input[name=ocupacion]').val(),
'id_pais': $('select[name=id_pais]').val(),
'id_state': $('select[name=id_state]').val(),
'id_municipio': $('select[name=id_municipio]').val(),
'id_ciudad': $('select[name=id_ciudad]').val(),
'id_dependencia': $('select[name=id_dependencia]').val(),
'id_perfil': $('select[name=id_perfil]').val(),
'imgUser': $('input[name=imgUser]').val(),
'direccion':$('#direccion').val()
},
success: function (data)
{
if ((data.success==true))
{
$('#pleaseWaitDialog').modal('hide');
$('#modalerrorbody').empty().append(data.mensaje);
$('#modalError [class= "modal-dialog modal-sm"]').addClass('modal-success');
$('#modalError [class= "modal-title"]').empty().append('Informacion');
$('#modalError').modal('show');
location.href=$('#url_base').val()+'/usuarios';
}
else
{
var mensaje='';
for(var i=0;i<data.errors.length;i++)
{
mensaje+=data.errors[i]+'<br>';
}
$('#pleaseWaitDialog').modal('hide');
$('#modalerrorbody').empty().append(mensaje);
$('#modalError [class= "modal-dialog modal-sm"]').addClass('modal-danger');
$('#modalError [class= "modal-title"]').empty().append('Ha ocurrido un error');
$('#modalError').modal('show');
}
}
});
});
$("#ModificarUsuario").click(function ()
{
var id=$('input[name=id_usuario]').val();
$('#pleaseWaitDialog').modal('show');
$.ajax
({
type: 'put',
url: $('#url_base').val()+'/usuarios/modificarUsuario/'+id,
data: {
'_token': $('input[name=_token]').val(),
'cedula': $('input[name=cedula]').val(),
'nombre': $('input[name=nombre]').val(),
'apellido': $('input[name=apellido]').val(),
'telefono': $('input[name=telefono]').val(),
'sexo': $('select[name=sexo]').val(),
'ocupacion': $('input[name=ocupacion]').val(),
'id_pais': $('select[name=id_pais]').val(),
'id_state': $('select[name=id_state]').val(),
'id_municipio': $('select[name=id_municipio]').val(),
'id_ciudad': $('select[name=id_ciudad]').val(),
'id_dependencia': $('select[name=id_dependencia]').val(),
'id_perfil': $('select[name=id_perfil]').val(),
'id':id,
'direccion':$('#direccion').val()
},
success: function (data)
{
if ((data.success==true))
{
$('#pleaseWaitDialog').modal('hide');
$('#modalerrorbody').empty().append(data.mensaje);
$('#modalError [class= "modal-dialog modal-sm"]').addClass('modal-success');
$('#modalError [class= "modal-title"]').empty().append('Informacion');
$('#modalError').modal('show');
location.href=$('#url_base').val()+'/usuarios';
}
else
{
var mensaje='';
for(var i=0;i<data.errors.length;i++)
{
mensaje+=data.errors[i]+'<br>';
}
$('#pleaseWaitDialog').modal('hide');
$('#modalerrorbody').empty().append(mensaje);
$('#modalError [class= "modal-dialog modal-sm"]').addClass('modal-danger');
$('#modalError [class= "modal-title"]').empty().append('Ha ocurrido un error');
$('#modalError').modal('show');
}
}
});
});
$("#id_buscar_usuario").click(function ()
{
//levantar modal myModal_Buscar
//alert(this.id);
$('#myModal_Buscar').modal('show');
});
<file_sep>/database/migrations/2018_08_13_123313_create_solicitud_compra_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSolicitudCompraTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('solicitud_compra', function (Blueprint $table) {
$table->increments('id_solicitud_compra');
$table->integer('compra_id')->unsigned();
$table->foreign('compra_id')->references('id_compra')->on('compra')->onDelete('cascade');
$table->integer('material_id')->unsigned();
$table->foreign('material_id')->references('id_material')->on('material')->onDelete('cascade');
$table->integer('cantidad');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('solicitud_compra');
}
}
<file_sep>/database/seeds/EscuelaTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\Escuela;
class EscuelaTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$Escuela=[[
'id_escuela'=>'1',
'nombre'=>'Escuela De Ciencias',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_escuela'=>'2',
'nombre'=>'Escuela De Ciencias Sociales',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_escuela'=>'3',
'nombre'=>'Escuela De Administracion',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_escuela'=>'4',
'nombre'=>'Decanato',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
]];
foreach($Escuela as $dep){
if(!Escuela::find($dep['id_escuela'])){
DB::table('escuela')->insert($dep);
}
}
}
}
<file_sep>/public/js/Material.js
new Vue({
el:'#material',
created:function(){
this.getMateriales();
},
data:
{
materiales:[],
pagination:
{
'total':0,
'current_page':0,
'per_page':0,
'last_page':0,
'from':0,
'to':0
},
DetalleMaterial:[],
errors:[],
codigo:'',
descripcion:'',
unidad_medida:'',
fillMateriales:
{
'id_material':'',
'codigo':'',
'descripcion':'',
'unidad_medida':''
}
},
computed:{
isActived:function(){
return this.pagination.current_page;
},
pagesNumber:function(){
if(!this.pagination.to){
return[];
}
this.offset=2;
var from = this.pagination.current_page - this.offset;//todo offset
if(from<1){
from=1;
}
var to=from +(this.offset*2);//todo
if(to>=this.pagination.last_page){
to=this.pagination.last_page;
}
var pagesArray=[];
while(from<=to){
pagesArray.push(from);
from++;
}
return pagesArray;
}
},
methods:
{
getMateriales:function(page)
{
var urlMaterial='material?page='+page;
$('#pleaseWaitDialog').modal('show');
axios.get(urlMaterial).then(response=>{
this.materiales = response.data.material.data;
this.pagination=response.data.pagination;
});
$('#pleaseWaitDialog').modal('hide');
},
limpiarFormularioMaterial:function(){
this.codigo='';
this.descripcion='';
this.unidad_medida='';
this.errors=[];
},
CreateMaterial:function()
{
var urlPost='material/GuardarMaterial';
$('#pleaseWaitDialog').modal('show');
axios.post(urlPost,
{
codigo:this.codigo,
descripcion:this.descripcion,
unidad_medida:this.unidad_medida
}).then(response=>{
$('#pleaseWaitDialog').modal('hide');
$('#modalExitoBody').empty().append('El Material '+ this.descripcion +' Fue Creado con exito');
$('#modalExito [class= "modal-header"]').addClass('bg-success');
$('#modalExito [class= "modal-title"]').empty().append('Informacion');
$('#modalExito').modal('show');
this.limpiarFormularioMaterial();
}).catch(error=>{
$('#pleaseWaitDialog').modal('hide');
if (Array.isArray(error.response.data.errors)) {
for (var i = 0; i < error.response.data.errors.length; i++) {
this.errors += error.response.data.errors[i] + '<br>';
}
}
$('#modalerrorbody').empty().append(this.errors);
$('#modalError [class= "modal-dialog "]').addClass('modal-danger');
$('#modalError [class= "modal-title"]').empty().append('Se ha producido un error');
$('#modalError').modal('show');
this.errors=[];
});
},
changePage:function(page){
this.pagination.current_page=page;
this.getMateriales(page);
}
}
});<file_sep>/app/Estudiante.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Estudiante extends Model
{
protected $table='estudiante';
protected $primaryKey='id_estudiante';
protected $fillable=['id_user','id_tipo','id_dependencia','cargo_estudiante'];
}
<file_sep>/database/seeds/StatesTableSeeders.php
<?php
use Illuminate\Database\Seeder;
Use App\States;
class StatesTableSeeders extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$State=[[
'id_state'=>'1' ,
'id_pais'=>'1',
'nombre'=>'Sucre',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_state'=>'2' ,
'id_pais'=>'2',
'nombre'=>'Barcelona',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_state'=>'3' ,
'id_pais'=>'2',
'nombre'=>'Madrid',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_state'=>'4' ,
'id_pais'=>'1',
'nombre'=>'Anzoategui',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
]];
foreach($State as $states){
if(!States::find($states['id_state'])){
DB::table('states')->insert($states);
}
}
}
}
<file_sep>/app/Institucion.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Institucion extends Model
{
protected $table='institucion';
protected $primaryKey='id_institucion';
protected $fillable=['nombre_institucion','siglas_institucion','descripcion_institucion','nucleo_institucion'];
}
<file_sep>/public/file/foto/1684413453.sql
SELECT p.cod_emp
,id_personal
,nombres
,apellido_paterno
,apellido_materno
,genero
,DATE_FORMAT(fecha_nacimiento, '%d/%m/%Y') fecha_nacimiento
,p.vigencia
,p.interno
,id_filial
,id_organizacion
,p.cod_cargo
,c.descripcion cargo
,workflow
,email
,relator
,reviso
,elaboro
,aprobo
,extranjero
,DATE_FORMAT(fecha_ingreso, '%d/%m/%Y') fecha_ingreso
,DATE_FORMAT(fecha_egreso, '%d/%m/%Y') fecha_egreso
,responsable_area
,id_organizacion_resp
,promover_cargo
,analisis_causa
,verifica_eficacia
,valida_acc_co
, impresion_cc
, org.title organizacion
FROM mos_personal p
LEFT JOIN mos_cargo c ON c.cod_cargo = p.cod_cargo
left join(select cod_emp,
GROUP_CONCAT(id_organizacion) id_organizacion_resp
from mos_responsable_area
group by cod_emp) resp on p.cod_emp = resp.cod_emp
inner join
mos_organizacion org on p.id_organizacion = org.id
WHERE p.cod_emp = $id
SELECT cod_emp
,id_personal
,initcap(nombres) nombres
,initcap(apellido_paterno) apellido_paterno
,initcap(apellido_materno) apellido_materno
,id_organizacion
,(select
GROUP_CONCAT(o.title) id
from mos_organizacion o
where o.parent_id =id_organizacion
group by o.parent_id)
,DATE_FORMAT(fecha_nacimiento, '%d/%m/%Y') fecha_nacimiento
,CASE genero WHEN 1 THEN 'Masculino' ELSE 'Femenino' END genero
,c.descripcion cod_cargo
,CASE workflow when 'S' then 'Si' Else 'No' END workflow
,p.vigencia
,CASE p.interno when 1 then 'Si' Else 'No' END interno
,id_filial
,email
,CASE relator when 'S' then 'Si' Else 'No' END relator
,CASE elaboro when 'S' then 'Si' Else 'No' END elaboro
,CASE reviso when 'S' then 'Si' Else 'No' END reviso
,CASE aprobo when 'S' then 'Si' Else 'No' END aprobo
,CASE responsable_area when 'S' then 'Si' Else 'No' END responsable_area
-- ,extranjero
,DATE_FORMAT(fecha_ingreso, '%d/%m/%Y') fecha_ingreso
,DATE_FORMAT(fecha_egreso, '%d/%m/%Y') fecha_egreso
,p1.nom_detalle p1 ,p2.nom_detalle p2 ,p3.nom_detalle p3
FROM mos_personal p
LEFT JOIN mos_cargo c ON c.cod_cargo = p.cod_cargo LEFT JOIN(select t1.id_registro, t2.descripcion as nom_detalle from mos_parametro_modulos t1
inner join mos_parametro_det t2 on t1.cod_categoria=t2.cod_categoria and t1.cod_parametro=t2.cod_parametro and t1.cod_parametro_det=t2.cod_parametro_det
where t1.cod_categoria='3' and t1.cod_parametro='17' ) AS p1 ON p1.id_registro = p.cod_emp LEFT JOIN(select t1.id_registro, t2.descripcion as nom_detalle from mos_parametro_modulos t1
inner join mos_parametro_det t2 on t1.cod_categoria=t2.cod_categoria and t1.cod_parametro=t2.cod_parametro and t1.cod_parametro_det=t2.cod_parametro_det
where t1.cod_categoria='3' and t1.cod_parametro='18' ) AS p2 ON p2.id_registro = p.cod_emp LEFT JOIN(select t1.id_registro, t2.descripcion as nom_detalle from mos_parametro_modulos t1
inner join mos_parametro_det t2 on t1.cod_categoria=t2.cod_categoria and t1.cod_parametro=t2.cod_parametro and t1.cod_parametro_det=t2.cod_parametro_det
where t1.cod_categoria='3' and t1.cod_parametro='36' ) AS p3 ON p3.id_registro = p.cod_emp
WHERE 1 = 1 AND upper(p.interno) like '%1%' AND id_organizacion IN (21,44,55,160) order by apellido_paterno asc
select
id, GROUP_CONCAT(title) id
from mos_organizacion
group by parent_id<file_sep>/app/Pais.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Pais extends Model
{
protected $table = 'pais';
protected $primaryKey='id_pais';
protected $fillable=['nombre'];
public function users()
{
return $this->hasMany('App\User', 'pais', 'id');
}
}<file_sep>/app/Oficio.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Oficio extends Model
{
protected $table = 'oficio';
protected $primaryKey='id_oficio';
protected $fillable=['id_documento','id_categoria','id_subcategoria','id_itemsubcategoria','id_estados','id_dependencia','id_user','numero','anio','acronimo','nota','para','de','cuerpo','fecha'];
}
<file_sep>/app/Http/Controllers/AdminFileController.php
<?php
/*
*
*
* */
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class AdminFileController extends Controller
{
private $dir_tmp;
public function __construct()
{
//inicializar las variables de configuracion
$this->dir_tmp=env('TMP_DIR');
//verificar si el directorio tmp existes
if(!is_dir($this->dir_tmp))
{
//crear el directorio
mkdir($this->dir_tmp,0777);
chmod($this->dir_tmp,0777);
}
}
public function uploadFile(Request $request)
{
if ($request->myfile)
{
$ret = array();
if ($request->myfile->getClientOriginalName())
{ //single file
$fileName = strtotime(date('d-m-y h:i:s')).'.'.$request->myfile->getClientOriginalExtension();
if ($request->myfile->isValid())
{
$request->myfile->move($this->dir_tmp, $fileName);
}
$ret[] = $fileName;
}
return json_encode($ret);
}
}
public function deleteFile(Request $request)
{
$fileName = $request->name;
$filePath = $this->dir_tmp .'/'. $fileName;
if (file_exists($filePath))
{
unlink($filePath);
}
return json_encode(array('success'=>true,'msg'=>"Deleted File " . $fileName . "<br>"));
}
}<file_sep>/database/migrations/2018_05_13_210421_create_factores_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFactoresTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('factores', function (Blueprint $table) {
$table->increments('id_factores');
$table->integer('id_user')->unsigned();
$table->foreign('id_user')->references('id')->on('users')->onDelete('cascade');
$table->integer('id_preparaduria')->unsigned();
$table->foreign('id_preparaduria')->references('id_preparaduria')->on('preparaduria')->onDelete('cascade');
$table->integer('id_periodo')->unsigned();
$table->foreign('id_periodo')->references('id_periodo')->on('periodo')->onDelete('cascade');
$table->float('f1');
$table->float('f2');
$table->float('f3');
$table->float('f4');
$table->float('f5');
$table->float('f6');
$table->float('f7');
$table->float('f8');
$table->float('f9');
$table->float('f10');
$table->integer('lugar');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('factores');
}
}
<file_sep>/app/Horario.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Horario extends Model
{
protected $table='horario';
protected $primaryKey='id_horario';
protected $fillable=['id_preparaduria','id_asignatura'];
}
<file_sep>/app/factores.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class factores extends Model
{
protected $table = 'factores';
protected $primaryKey='id_factores';
protected $fillable=['id_user','id_preparaduria','id_periodo','f1','f2','f3','f4','f5','f6','f7','f8','f9','f10','lugar'];
}
<file_sep>/database/migrations/2018_04_24_171656_create_preparaduria_asignaturas_cursando_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePreparaduriaAsignaturasCursandoTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('preparaduria_asignaturas_cursando', function (Blueprint $table) {
$table->increments('id_preparaduria_asignaturas_cursando');
$table->integer('id_preparaduria')->unsigned();
$table->foreign('id_preparaduria')->references('id_preparaduria')->on('preparaduria')->onDelete('cascade');
$table->integer('id_asignatura')->unsigned();
$table->foreign('id_asignatura')->references('id_asignatura')->on('asignatura')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('preparaduria_asignaturas_cursando');
}
}
<file_sep>/app/Status.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Status extends Model
{
protected $table = 'status';
protected $primaryKey = 'id_status';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
public function status()
{
return $this->belongsTo('App\User','rol_id');
}
}
<file_sep>/app/Tipo.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tipo extends Model
{
protected $table='tipo';
protected $primaryKey='id_tipo';
protected $fillable=['nombre_tipo','descripcion_tipo'];
}
<file_sep>/database/migrations/2018_05_11_170013_create_oficio_contratacion_preparador_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateOficioContratacionPreparadorTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('oficio_contratacion_preparador', function (Blueprint $table) {
$table->increments('id_oficio_contratacion_preparador');
$table->integer('id_oficio')->unsigned();
$table->foreign('id_oficio')->references('id_oficio')->on('oficio')->onDelete('cascade');
$table->integer('id_concurso')->unsigned();
$table->foreign('id_concurso')->references('id_concurso')->on('concurso')->onDelete('cascade');
$table->integer('id_periodo')->unsigned();
$table->foreign('id_periodo')->references('id_periodo')->on('periodo')->onDelete('cascade');
$table->text('descripcion');
$table->text('nro_consejo');
$table->text('fecha_consejo');;
$table->text('fecha_contratacion');
$table->text('observacion');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('oficio_contratacion_preparador');
}
}
<file_sep>/app/Circular.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Circular extends Model
{
protected $table = 'circular';
protected $primaryKey='id_circular';
protected $fillable=['id_itemsubcategoria','codigo_circular','nota_circular','para_circular','de_circular','cuerpo_circular','html_circular'];
}<file_sep>/app/Http/Controllers/ProfileController.php
<?php
namespace App\Http\Controllers;
use App\Dedicacion;
use App\DedicacionEstudiante;
use Illuminate\Http\Request;
use App\User;
use App\Profesor;
use App\Estudiante;
use App\Sellos;
use App\SellosEscuelas;
use Illuminate\Support\Facades\Response;
use App\Http\Controllers\FuncionesController;
use DB;
use Auth;
class ProfileController extends Controller
{
private $dir_tmp;
private $dir_mark;
private $tipo_validos;
public function __construct()
{
//inicializar las variables de configuracion
$this->dir_tmp=env('TMP_DIR');
$this->dir_mark=env('URL_MARKS');
$this->tipo_validos=env('FORMAT_IMG');
//verificar si el directorio existes
if(!is_dir($this->dir_mark))
{
//crear el directorio
mkdir($this->dir_mark,0777);
chmod($this->dir_mark,0777);
}
}
//
public function index() {
$Dedicacion=Dedicacion::pluck('nombre_dedicacion','id_dedicacion');
$DedicacionEstudiante=DedicacionEstudiante::pluck('nombre','id_dedicacion_estudiante');
return view('profile/edit')->with([ 'Dedicacion'=>$Dedicacion,'DedicacionEstudiante'=>$DedicacionEstudiante ]);
}
public function store(Request $request) {
if( Auth::user()->id_perfil==6 || Auth::user()->id_perfil==2)
{
$rules = [
'nombres' => 'required',
'apellidos' => 'required',
'id_dedicacion' => 'required',
'password' => '<PASSWORD>',
'imgUser' =>'required_with:'.$this->tipo_validos,
'imgSello' =>'required|required_with:'.$this->tipo_validos,
'imgFirma' =>'required|required_with:'.$this->tipo_validos,
];
$mensajes=[
'nombres.required'=>'El Nombre es Obligatorio',
'apellidos.required'=>'El Apellido es Obligatorio',
'id_dedicacion.required'=>'La Dedicacion Es Obligatoria',
'password.required'=>'La Contraseña es O<PASSWORD>',
'imgUser.required'=>'La Imagen es Obligatoria',
'imgSello.required'=>'El Sello es Obligatoria',
'imgFirma.required'=>'La Firma es Obligatoria',
'imgUser.required_with'=>'La imagen debe ser de los tipo '.$this->tipo_validos,
'imgSello.required_with'=>'La imagen debe ser de los tipo '.$this->tipo_validos,
'imgFirma.required_with'=>'La imagen debe ser de los tipo '.$this->tipo_validos,
];
$validator = \Validator::make($request->all(), $rules,$mensajes);
if ($validator->fails()) {
return Response::json([
'success' => false,
'errors' => $validator->errors()->all()
],500);
}
}
if( Auth::user()->id_perfil==4)
{
$rules = [
'nombres' => 'required',
'apellidos' => 'required',
'id_dedicacion' => 'required',
'password' => '<PASSWORD>',
'imgUser' =>'required_with:'.$this->tipo_validos,
'imgFirma' =>'required|required_with:'.$this->tipo_validos,
];
$mensajes=[
'nombres.required'=>'El Nombre es Obligatorio',
'apellidos.required'=>'El Apellido es Obligatorio',
'id_dedicacion.required'=>'La Dedicacion Es Obligatoria',
'password.required'=>'La Contraseña es O<PASSWORD>',
'imgUser.required'=>'La Imagen es Obligatoria',
'imgFirma.required'=>'La Firma es Obligatoria',
'imgUser.required_with'=>'La imagen debe ser de los tipo '.$this->tipo_validos,
'imgFirma.required_with'=>'La imagen debe ser de los tipo '.$this->tipo_validos,
];
$validator = \Validator::make($request->all(), $rules,$mensajes);
if ($validator->fails()) {
return Response::json([
'success' => false,
'errors' => $validator->errors()->all()
],500);
}
}
if(Auth::user()->id_perfil==5)
{
$rules = [
'nombres' => 'required',
'apellidos' => 'required',
'id_dedicacion_estudiante' => 'required',
'password' => '<PASSWORD>',
'imgUser' =>'required_with:'.$this->tipo_validos,
'imgFirma' =>'required|required_with:'.$this->tipo_validos,
];
$mensajes=[
'nombres.required'=>'El Nombre es Obligatorio',
'apellidos.required'=>'El Apellido es Obligatorio',
'id_dedicacion_estudiante.required'=>'La Dedicacion Es Obligatoria',
'password.<PASSWORD>'=>'<PASSWORD> <PASSWORD>',
'imgUser.required'=>'La Imagen es Obligatoria',
'imgFirma.required'=>'La Firma es Obligatoria',
'imgUser.required_with'=>'La imagen debe ser de los tipo '.$this->tipo_validos,
'imgFirma.required_with'=>'La imagen debe ser de los tipo '.$this->tipo_validos,
];
$validator = \Validator::make($request->all(), $rules,$mensajes);
if ($validator->fails()) {
return Response::json([
'success' => false,
'errors' => $validator->errors()->all()
],500);
}
}
if(Auth::user()->id_perfil==1 || Auth::user()->id_perfil==3)
{
$rules = [
'nombres' => 'required',
'apellidos' => 'required',
'password' => '<PASSWORD>',
'imgUser' =>'required_with:'.$this->tipo_validos,
];
$mensajes=[
'nombres.required'=>'El Nombre es Obligatorio',
'apellidos.required'=>'El Apellido es Obligatorio',
'password.required'=>'La Contraseña es <PASSWORD>',
'imgUser.required'=>'La Imagen es Obligatoria',
'imgUser.required_with'=>'La imagen debe ser de los tipo '.$this->tipo_validos,
];
$validator = \Validator::make($request->all(), $rules,$mensajes);
if ($validator->fails()) {
return Response::json([
'success' => false,
'errors' => $validator->errors()->all()
],500);
}
}
$datos=array(
'name' => $request->name,
);
DB::beginTransaction();
if($request->password!==$request->passwordold)
{
$datos['password']= bcrypt ($request->password);
}
$datos['name']= $request->nombres;
$datos['nombres']= $request->nombres;
$datos['apellidos']=$request->apellidos;
if($request->imgUser!==$request->img_old)
{
$datos['avatar']= $request->imgUser;
}
User::where('id',$request->id)->update($datos);
if(Auth::user()->id_perfil==2)
{
$Profesor= new Profesor();
$Profesor->id_user=Auth::user()->id;
$Profesor->id_tipo='1';
$Profesor->id_dependencia=Auth::user()->id_dependencia;
$Profesor->id_dedicacion=$request->id_dedicacion;
$Profesor->firma=$request->imgFirma;
$Profesor->save();
$Sello=new Sellos();
$Sello->id_dependencia=Auth::user()->id_dependencia;
$Sello->id_users=Auth::user()->id;
$Sello->sello=$request->imgSello;
$Sello->save();
rename($this->dir_tmp . '/' . $request->imgFirma, ($this->dir_mark . '/' . $request->imgFirma));
rename($this->dir_tmp . '/' . $request->imgSello, ($this->dir_mark . '/' . $request->imgSello));
}
if(Auth::user()->id_perfil==5 )
{
$Estudiante= new Estudiante();
$Estudiante->id_user=Auth::user()->id;
$Estudiante->id_tipo='2';
$Estudiante->id_dependencia=Auth::user()->id_dependencia;
$Estudiante->id_dedicacion_estudiante=$request->id_dedicacion_estudiante;
$Estudiante->firma=$request->imgFirma;
$Estudiante->save();
rename($this->dir_tmp . '/' . $request->imgFirma, ($this->dir_mark . '/' . $request->imgFirma));
}
if(Auth::user()->id_perfil==6)
{
$Profesor= new Profesor();
$Profesor->id_user=Auth::user()->id;
$Profesor->id_tipo='1';
$Profesor->id_dependencia=Auth::user()->id_dependencia;
$Profesor->id_dedicacion=$request->id_dedicacion;
$Profesor->firma=$request->imgFirma;
$Profesor->save();
$Sello=new SellosEscuelas();
$Sello->id_dependencia=Auth::user()->id_dependencia;
$Sello->id_users=Auth::user()->id;
$Sello->sello=$request->imgSello;
$Sello->save();
rename($this->dir_tmp . '/' . $request->imgFirma, ($this->dir_mark . '/' . $request->imgFirma));
rename($this->dir_tmp . '/' . $request->imgSello, ($this->dir_mark . '/' . $request->imgSello));
}
if(Auth::user()->id_perfil==4)
{
$Profesor= new Profesor();
$Profesor->id_user=Auth::user()->id;
$Profesor->id_tipo='1';
$Profesor->id_dependencia=Auth::user()->id_dependencia;
$Profesor->id_dedicacion=$request->id_dedicacion;
$Profesor->firma=$request->imgFirma;
$Profesor->save();
}
DB::commit();
if($request->imgUser!==$request->img_old)
{
unlink($this->dir_mark . '/' . $request->img_old);
rename($this->dir_tmp . '/' . $request->imgUser, ($this->dir_mark . '/' . $request->imgUser));
}
if($request->password!==$request->passwordold)
{
$address=env('MAIL_USERNAME');
$email=$request->email;
$name=$request->email;
$Name=$request->nombres.' '.$request->apellidos;
$password=$request->password;
$Funciones= new FuncionesController();
$Funciones->EnviarCambioClave($name,$email,$password,$Name,$address);
return response()->json(['success'=>true,'msj'=>'Tu Cuenta fue actualizada con éxito revise su correo!!!']);
}
else{
return response()->json(['success'=>true,'msj'=>'Tu Cuenta fue actualizada con éxito !!!']);
}
}
}
<file_sep>/database/seeds/SubcategoriaDocumentoTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\Subcategoria;
class SubcategoriaDocumentoTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$SubCategoria=[[
'id_subcategoria'=>'1',
'id_categoria'=>'1',
'nombre_subcategoria'=>'Circular',
'descripcion_subcategoria'=>'Administrativos',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_subcategoria'=>'2',
'id_categoria'=>'1',
'nombre_subcategoria'=>'Invitacion',
'descripcion_subcategoria'=>'Administrativos',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_subcategoria'=>'3',
'id_categoria'=>'1',
'nombre_subcategoria'=>'Oficio',
'descripcion_subcategoria'=>'Administrativos',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_subcategoria'=>'4',
'id_categoria'=>'1',
'nombre_subcategoria'=>'Solicitud',
'descripcion_subcategoria'=>'Administrativos',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_subcategoria'=>'5',
'id_categoria'=>'2',
'nombre_subcategoria'=>'Concurso',
'descripcion_subcategoria'=>'Administrativos',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_subcategoria'=>'6',
'id_categoria'=>'2',
'nombre_subcategoria'=>'Estudiante',
'descripcion_subcategoria'=>'Administrativos',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_subcategoria'=>'7',
'id_categoria'=>'2',
'nombre_subcategoria'=>'Profesor',
'descripcion_subcategoria'=>'Administrativos',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_subcategoria'=>'8',
'id_categoria'=>'2',
'nombre_subcategoria'=>'Planificacion Academica',
'descripcion_subcategoria'=>'Administrativos',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
]];
foreach($SubCategoria as $subcategorias){
if(!Subcategoria::find($subcategorias['id_subcategoria'])){
DB::table('subcategoria_documento')->insert($subcategorias);
}
}
}
}
<file_sep>/database/seeds/CategoriaDocumentoTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\Categoria;
class CategoriaDocumentoTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$Categoria=[[
'id_categoria'=>'1',
'nombre_categoria'=>'Administrativos',
'descripcion_categoria'=>'Administrativos',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_categoria'=>'2',
'nombre_categoria'=>'Academicos',
'descripcion_categoria'=>'Academicos',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
]];
foreach($Categoria as $categorias){
if(!Categoria::find($categorias['id_categoria'])){
DB::table('categoria_documento')->insert($categorias);
}
}
}
}
<file_sep>/database/seeds/PaisTableSeeders.php
<?php
use Illuminate\Database\Seeder;
Use App\Pais;
class PaisTableSeeders extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$Pais=[[
'id_pais'=>'1',
'nombre'=>'Venezuela',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_pais'=>'2',
'nombre'=>'España',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
]];
foreach($Pais as $paises){
if(!Pais::find($paises['id_pais'])){
DB::table('pais')->insert($paises);
}
}
}
}
<file_sep>/app/Dependencias.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Dependencias extends Model
{
protected $table='dependencias';
protected $primaryKey='id_dependencias';
protected $fillable=['id_departamento','nombre'];
}
<file_sep>/app/OficioContratacionPreparador.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class OficioContratacionPreparador extends Model
{
protected $table = 'oficio_contratacion_preparador';
protected $primaryKey='id_oficio_contratacion_preparador';
protected $fillable=['id_oficio','id_concurso','id_periodo','descripcion','nro_consejo','fecha_contratacion','observacion','fecha_consejo'];
}
<file_sep>/app/Ruta.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Ruta extends Model
{
protected $table = 'ruta';
protected $primaryKey='id_ruta';
protected $fillable=['id_estado','id_documento','id_dependencia','id_user','fecha'];
}
<file_sep>/app/PreparaduriaAsignaturasCursando.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PreparaduriaAsignaturasCursando extends Model
{
protected $table='preparaduria_asignaturas_cursando';
protected $primaryKey='id_preparaduria_asignaturas_cursando';
protected $fillable=['id_preparaduria','id_asignatura'];
}
<file_sep>/database/migrations/2014_06_19_155456_create_dependencia_udo_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateDependenciaUdoTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('dependencia_udo', function (Blueprint $table) {
$table->increments('id_dependencia');
$table->char('dependencia',13);
$table->text('unidad_solicitante');
$table->text('unidad_ejecutora');
$table->integer('nucleo');
$table->char('siglas',10);
$table->text('descripcion');
$table->text('responsable_soli');
$table->text('responsable_ejec');
$table->char('ano',4);
$table->text('descripcion_unidad_eje');
$table->text('codigo_jerarquico');
$table->text('cod_compuesto');
$table->integer('nivel');
$table->text('descripcion_unidad_sol');
$table->text('cargo_solicitante');
$table->text('cargo_ejecutor');
$table->text('rowid');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('dependencia');
}
}
<file_sep>/database/seeds/EstadosTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\Estado;
class EstadosTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$Estados=[[
'nombre'=>'Creado',
'id_estados'=>'1',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_estados'=>'2',
'nombre'=>'Enviado',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_estados'=>'3',
'nombre'=>'Visto',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_estados'=>'4',
'nombre'=>'Por Correcion',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_estados'=>'5',
'nombre'=>'Corregido',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_estados'=>'6',
'nombre'=>'Por Firmar',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_estados'=>'7',
'nombre'=>'Firmado',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_estados'=>'8',
'nombre'=>'Verificado',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_estados'=>'9',
'nombre'=>'Entregado',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_estados'=>'10',
'nombre'=>'Aprobado',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_estados'=>'11',
'nombre'=>'Rechazado',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_estados'=>'12',
'nombre'=>'Remitido',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_estados'=>'13',
'nombre'=>'aperturado',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_estados'=>'14',
'nombre'=>'cerrado',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_estados'=>'15',
'nombre'=>'asignado',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
]];
foreach($Estados as $status){
if(!Estado::find($status['id_estados'])){
DB::table('estados')->insert($status);
}
}
}}
<file_sep>/app/Itemsubcategoria.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Itemsubcategoria extends Model
{
protected $table = 'itemsubcategoria';
protected $primaryKey='id_itemsubcategoria';
protected $fillable=['id_subcategoria','nombre_itemsubcategoria','descripcion_itemsubcategoria'];
public static function itemsubcategorias($id)
{
return Itemsubcategoria::where('id_subcategoria', $id)->get();
}
}<file_sep>/app/Plazas.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Plazas extends Model
{
protected $table='plazas';
protected $primaryKey='id_plazas';
protected $fillable=['id_concurso','id_asignatura'];
}
<file_sep>/database/migrations/2014_04_22_010216_create_ciudad_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCiudadTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('ciudad', function (Blueprint $table) {
$table->increments('id_ciudad');
$table->integer('id_pais')->unsigned();
$table->foreign('id_pais')->references('id_pais')->on('pais')->onDelete('cascade');
$table->integer('id_state')->unsigned();
$table->foreign('id_state')->references('id_state')->on('states')->onDelete('cascade');
$table->integer('id_municipio')->unsigned();
$table->foreign('id_municipio')->references('id_municipio')->on('municipio')->onDelete('cascade');
$table->text('nombre');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('ciudad');
}
}
<file_sep>/database/migrations/2018_07_18_142554_add_unidad_ejecutora_personal.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddUnidadEjecutoraPersonal extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('personal', function (Blueprint $table) {
$table->text('unidad_ejecutora')->after('id_personal');
$table->text('unidad_asignado')->after('unidad_ejecutora');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
<file_sep>/database/migrations/2018_03_11_163821_create_concurso_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateConcursoTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('concurso', function (Blueprint $table) {
$table->increments('id_concurso');
$table->integer('id_estados')->unsigned();
$table->foreign('id_estados')->references('id_estados')->on('estados')->onDelete('cascade');
$table->integer('id_periodo')->unsigned();
$table->foreign('id_periodo')->references('id_periodo')->on('periodo')->onDelete('cascade');
$table->date('fecha_apertura');
$table->date('fecha_cierre');
$table->integer('cupo_asignado');
$table->integer('limite');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('concurso');
}
}
<file_sep>/database/migrations/2018_05_01_021030_create_oficio_copia_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateOficioCopiaTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('oficio_copia', function (Blueprint $table) {
$table->increments('id_oficio_copia');
$table->integer('id_oficio')->unsigned();
$table->foreign('id_oficio')->references('id_oficio')->on('oficio')->onDelete('cascade');
$table->integer('id_dependencia')->unsigned();
$table->foreign('id_dependencia')->references('id_dependencias')->on('dependencias')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('oficio_copia');
}
}
<file_sep>/app/Escuela.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Escuela extends Model
{
protected $table='escuela';
protected $primaryKey='id_escuela';
protected $fillable=['nombre'];
}
<file_sep>/database/seeds/DependenciaTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\Dependencias;
class DependenciaTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$Dependencias=[[
'id_dependencias'=>'1',
'id_departamento'=>'21',
'nombre'=>'Decano(a)',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencias'=>'2',
'id_departamento'=>'14',
'nombre'=>'Delegación de Personal',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencias'=>'3',
'id_departamento'=>'15',
'nombre'=>'Coordinacion Academica',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencias'=>'4',
'id_departamento'=>'16',
'nombre'=>'Coordinacion Administrativa',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencias'=>'5',
'id_departamento'=>'17',
'nombre'=>'Delegación de Finanzas',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencias'=>'6',
'id_departamento'=>'18',
'nombre'=>'Contraloria Delegada',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencias'=>'7',
'id_departamento'=>'19',
'nombre'=>'Delegación de Presupuesto',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencias'=>'8',
'id_departamento'=>'22',
'nombre'=>'Sección de Nomina',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencias'=>'9',
'id_departamento'=>'2',
'nombre'=>'COMISION DE PREPARADURIAS',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencias'=>'9',
'id_departamento'=>'2',
'nombre'=>'ARCHIVO',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
]];
foreach($Dependencias as $Dependencia){
if(!Dependencias::find($Dependencia['id_dependencias'])){
DB::table('dependencias')->insert($Dependencia);
}
}
}
}
<file_sep>/database/migrations/2018_04_18_163303_create_profesor_table.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProfesorTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('profesor', function (Blueprint $table) {
$table->increments('id_profesor');
$table->integer('id_user')->unsigned();
$table->foreign('id_user')->references('id')->on('users')->onDelete('cascade');
$table->integer('id_tipo')->unsigned();
$table->foreign('id_tipo')->references('id_tipo')->on('tipo')->onDelete('cascade');
$table->integer('id_dependencia')->unsigned();
$table->foreign('id_dependencia')->references('id_dependencia')->on('dependencia')->onDelete('cascade');
$table->integer('id_dedicacion')->unsigned();
$table->foreign('id_dedicacion')->references('id_dedicacion')->on('dedicacion')->onDelete('cascade');
$table->text('firma')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('profesor');
}
}
<file_sep>/app/Http/Controllers/MaterialController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Material;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use DB;
class MaterialController extends Controller
{
public function index()
{
$Material= array();
$Material= Material::orderby('id_material','asc')->paginate(4);
return
[
'pagination'=>
[
'total'=>$Material->total(),
'current_page'=>$Material->currentPage(),
'per_page'=>$Material->perPage(),
'last_page'=>$Material->lastPage(),
'from'=>$Material->firstItem(),
'to'=>$Material->lastItem(),
],
'material'=>$Material
];
}
public function GuargarMaterial(Request $request)
{
$rules =
[
'codigo' => 'required|min:2|max:20',
'descripcion' => 'required|unique:material',
'unidad_medida' =>'required',
];
$mensajes=array(
'codigo.required'=>'El Codigo es Obligatorio',
'codigo.min'=>'El Codigo debe ser minimo de 6 Caracteres',
'codigo.max'=>'El Codigo debe ser Maximo de 20 Caracteres',
'unidad_medida.required'=>'La Unidad de Medida es Obligatoria',
'descripcion.required'=>'La Descripcion del Material es Obligatoria',
'descripcion.unique'=>'Ya se encuentra registrado un Material Llamado: '. $request->descripcion,
);
$validator = Validator::make(Input::all(), $rules,$mensajes);
if ($validator->fails())
{
return \Response::json([
'created' => false,
'errors' => $validator->errors()->all()
],500);
}
else
{
DB::beginTransaction();
$Material= new Material();
$Material->codigo=$request->codigo;
$Material->descripcion=$request->descripcion;
$Material->unidad_medida=$request->unidad_medida;
$Material->save();
DB::commit();
return \Response::json([
'created' => true,
'mensaje' => "Se registro con exito el Material"
],200);
}
}
}
<file_sep>/database/seeds/DependenciasTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\Dependencia;
class DependenciasTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$Dependencia=[[
'id_dependencia'=>'1',
'id_institucion'=>'1',
'id_escuela'=>'1',
'nombre_dependencia'=>'DEPARTAMENTO DE FISICA',
'descripcion_dependencia'=>'',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencia'=>'2',
'id_institucion'=>'1',
'id_escuela'=>'1',
'nombre_dependencia'=>'DESPARATMENTO DE INFORMATICA',
'descripcion_dependencia'=>'Departamento Informatica Nucleo de Sucre',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencia'=>'3',
'id_institucion'=>'1',
'id_escuela'=>'1',
'nombre_dependencia'=>'DEPARTAMENTO DE MATEMATICAS',
'descripcion_dependencia'=>'Departamento Matematica Nucleo de Sucre',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencia'=>'4',
'id_institucion'=>'1',
'id_escuela'=>'1',
'nombre_dependencia'=>'DEPARTAMENTO DE QUIMICA',
'descripcion_dependencia'=>'Departamento Matematica Nucleo de Sucre',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencia'=>'5',
'id_institucion'=>'1',
'id_escuela'=>'1',
'nombre_dependencia'=>'DEPARTAMENTO DE BIOLOGIA',
'descripcion_dependencia'=>'Departamento Matematica Nucleo de Sucre',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencia'=>'6',
'id_institucion'=>'1',
'id_escuela'=>'1',
'nombre_dependencia'=>'DEPARTAMENTO DE BIOANALISIS',
'descripcion_dependencia'=>'Departamento Matematica Nucleo de Sucre',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencia'=>'7',
'id_institucion'=>'1',
'id_escuela'=>'2',
'nombre_dependencia'=>'DEPARTAMENTO DE CASTELLANO Y LITERATURA',
'descripcion_dependencia'=>'Departamento Matematica Nucleo de Sucre',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencia'=>'8',
'id_institucion'=>'1',
'id_escuela'=>'2',
'nombre_dependencia'=>'DEPARTAMENTO DE SOCIOLOGIA',
'descripcion_dependencia'=>'Departamento Matematica Nucleo de Sucre',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencia'=>'9',
'id_institucion'=>'1',
'id_escuela'=>'2',
'nombre_dependencia'=>'DEPARTAMENTO DE IDIOMAS MODERNOS',
'descripcion_dependencia'=>'Departamento Matematica Nucleo de Sucre',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencia'=>'10',
'id_institucion'=>'1',
'id_escuela'=>'3',
'nombre_dependencia'=>'DEPARTAMENTO DE ADMINISTRACION',
'descripcion_dependencia'=>'Departamento Matematica Nucleo de Sucre',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencia'=>'11',
'id_institucion'=>'1',
'id_escuela'=>'3',
'nombre_dependencia'=>'DEPARTAMENTO DE CONTADURIA PUBLICA',
'descripcion_dependencia'=>'Departamento Matematica Nucleo de Sucre',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencia'=>'12',
'id_institucion'=>'1',
'id_escuela'=>'3',
'nombre_dependencia'=>'DEPARTAMENTO DE RECURSOS HUMANOS',
'descripcion_dependencia'=>'Departamento Matematica Nucleo de Sucre',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencia'=>'13',
'id_institucion'=>'1',
'id_escuela'=>'1',
'nombre_dependencia'=>'DEPARTAMENTO DE ENFERMERIA',
'descripcion_dependencia'=>'Departamento Matematica Nucleo de Sucre',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencia'=>'14',
'id_institucion'=>'1',
'id_escuela'=>'4',
'nombre_dependencia'=>'Delegación de Personal',
'descripcion_dependencia'=>'Departamento Matematica Nucleo de Sucre',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencia'=>'15',
'id_institucion'=>'1',
'id_escuela'=>'4',
'nombre_dependencia'=>'Coordinacion Academica',
'descripcion_dependencia'=>'Departamento Matematica Nucleo de Sucre',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencia'=>'16',
'id_institucion'=>'1',
'id_escuela'=>'4',
'nombre_dependencia'=>'Coordinacion Administrativa',
'descripcion_dependencia'=>'Departamento Matematica Nucleo de Sucre',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencia'=>'17',
'id_institucion'=>'1',
'id_escuela'=>'4',
'nombre_dependencia'=>'Delegación de Finanzas',
'descripcion_dependencia'=>'Departamento Matematica Nucleo de Sucre',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencia'=>'18',
'id_institucion'=>'1',
'id_escuela'=>'4',
'nombre_dependencia'=>'Contraloria Delegada',
'descripcion_dependencia'=>'Departamento Matematica Nucleo de Sucre',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencia'=>'19',
'id_institucion'=>'1',
'id_escuela'=>'4',
'nombre_dependencia'=>'Delegación de Presupuesto',
'descripcion_dependencia'=>'Departamento Matematica Nucleo de Sucre',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencia'=>'22',
'id_institucion'=>'1',
'id_escuela'=>'4',
'nombre_dependencia'=>'Sección de Nomina',
'descripcion_dependencia'=>'Departamento Matematica Nucleo de Sucre',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencia'=>'20',
'id_institucion'=>'1',
'id_escuela'=>'1',
'nombre_dependencia'=>'ESCUELA DE CIENCIAS',
'descripcion_dependencia'=>'',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dependencia'=>'21',
'id_institucion'=>'1',
'id_escuela'=>'4',
'nombre_dependencia'=>'DECANO(A)',
'descripcion_dependencia'=>'',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
]];
foreach($Dependencia as $Dependencias){
if(!Dependencia::find($Dependencias['id_dependencia'])){
DB::table('dependencia')->insert($Dependencias);
}
}
}
}
<file_sep>/app/OficioCopia.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class OficioCopia extends Model
{
protected $table = 'oficio_copia';
protected $primaryKey='id_oficio_copia';
protected $fillable=['id_oficio','id_dependencia'];
}
<file_sep>/app/Profesor.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profesor extends Model
{
protected $table = 'profesor';
protected $primaryKey='id_profesor';
protected $fillable=['id_user','id_tipo','id_dependencia','id_dedicacion','cargo_profesor'];
}
<file_sep>/database/seeds/DedicacionEstudianteTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\DedicacionEstudiante;
class DedicacionEstudianteTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$DedicacionEstudiantes=[[
'id_dedicacion_estudiante'=>'1',
'nombre'=>'Preparador',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dedicacion_estudiante'=>'2',
'nombre'=>'<NAME>',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dedicacion_estudiante'=>'3',
'nombre'=>'Tesista',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dedicacion_estudiante'=>'4',
'nombre'=>'Estudiante',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dedicacion_estudiante'=>'5',
'nombre'=>'<NAME>',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
]];
foreach($DedicacionEstudiantes as $DedicacionEstudiante){
if(!DedicacionEstudiante::find($DedicacionEstudiante['id_dedicacion_estudiante'])){
DB::table('dedicacion_estudiante')->insert($DedicacionEstudiante);
}
}
}
}
<file_sep>/app/Http/Controllers/AdminUserController.php
<?php
namespace App\Http\Controllers;
use App\Perfil;
use App\Nom_Nucleo;
use App\Status;
use View;
class AdminUserController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$rol=Perfil::pluck('nombre_perfil','id_perfil');
$Nucleo= Nom_Nucleo::pluck('descripcion','id_nom_nucleo');
$Status=Status::pluck('name','id_status');
return View::make('usuarios/index')->with(['Status'=>$Status,'rol'=>$rol,'Nucleo'=>$Nucleo]);
}
}
<file_sep>/app/Http/Controllers/UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Perfil;
use App\Pais;
use App\States;
use App\Municipios;
use App\Ciudades;
use App\Dependencia;
use App\Ruta;
use App\Status;
use App\Nom_Nucleo;
use Response;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use View;
use App\Http\Controllers\FuncionesController;
use DB;
use Mail;
use Illuminate\Support\Facades\Session;
class UserController extends Controller
{
private $dir_tmp;
private $dir_mark;
private $tipo_validos;
public function __construct()
{ $this->middleware('auth');
//inicializar las variables de configuracion
$this->dir_tmp=env('TMP_DIR');
$this->dir_mark=env('URL_MARKS');
$this->tipo_validos=env('FORMAT_IMG');
//verificar si el directorio existes
if(!is_dir($this->dir_mark))
{
//crear el directorio
mkdir($this->dir_mark,0777);
chmod($this->dir_mark,0777);
}
}
public function index()
{
$rol=Perfil::pluck('nombre_perfil','id_perfil');
$Nucleo= Nom_Nucleo::pluck('descripcion','id_nom_nucleo');
$User= array();
$User= User::select('users.*','perfil.nombre_perfil','dependencia.nombre_dependencia')->join('perfil','users.id_perfil','=','perfil.id_perfil')->leftjoin('dependencia','users.id_dependencia','=','dependencia.id_dependencia')
->orderby('users.id','asc')
->paginate(10);
return
[
'pagination'=>
[
'total'=>$User->total(),
'current_page'=>$User->currentPage(),
'per_page'=>$User->perPage(),
'last_page'=>$User->lastPage(),
'from'=>$User->firstItem(),
'to'=>$User->lastItem(),
],
'user'=>$User ,
'rol'=>$rol,
'Nucleo'=>$Nucleo
];
}
public function AgregarUsuario(Request $request)
{
$rules = [
'name' => 'required|min:6|max:20',
'email' => 'required|email|unique:users',
'dependencia_id' =>'required',
'id_nom_nucleo' =>'required',
'status_id' =>'required',
'rol_id' =>'required'
];
$mensajes=array(
'name.required'=>'El Nombre es Obligatorio',
'name.min'=>'El Nombre debe ser minimo de 6 Caracteres',
'name.max'=>'El Nombre debe ser Maximo de 20 Caracteres',
'dependencia_id.required'=>'La Dependencia es Obligatoria',
'rol_id.required'=>'El Rol es Obligatorio',
'id_nom_nucleo.required'=>'El Nucleo es Obligatorio',
'status_id.required'=>'El Status es Obligatorio',
'email.required'=>'El correo es Obligatorio',
'email'=>'debe introducir un email valido',
'email.unique'=>'Ya existe un email con ese Nombre',
);
$validator = Validator::make(Input::all(), $rules,$mensajes);
if ($validator->fails())
{
return \Response::json([
'created' => false,
'errors' => $validator->errors()->all()
],500);
} else
{
DB::beginTransaction();
$Funciones= new FuncionesController();
$password=$Funciones->GenerarPassword();
$request->password= <PASSWORD>($password);
$User = new User();
$User->id_dependencia=$request->dependencia_id;
$User->personal_id=$request->personal_id;
$User->id_perfil=$request->rol_id;
$User->id_nom_nucleo=$request->id_nom_nucleo;
$User->status_id=$request->status_id;
$User->name=$request->name;
$User->email=$request->email;
$User->avatar='udologo.png';
$User->password=$request->password;
$User->remember_token=$request->_token;
$User->save();
DB::commit();
$email=env('MAIL_USERNAME');
$admin=$request->email;
$name=$request->email;
$fullname=$request->nombre;
$Funciones->EnviarCorreo($name,$fullname,$email,$password,$admin);
return \Response::json([
'created' =>true
],200);
}
}
public function EditarUsuario(Request $request, $id)
{
$rules = [
'name' => 'required|min:6|max:20',
'id_nom_nucleo' =>'required',
'status_id' =>'required',
'rol_id' =>'required'
];
$mensajes=array(
'name.required'=>'El Nombre es Obligatorio',
'name.min'=>'El Nombre debe ser minimo de 6 Caracteres',
'name.max'=>'El Nombre debe ser Maximo de 20 Caracteres',
'rol_id.required'=>'El Rol es Obligatorio',
'id_nom_nucleo.required'=>'El Nucleo es Obligatorio',
'status_id.required'=>'El Status es Obligatorio',
);
$validator = Validator::make(Input::all(), $rules,$mensajes);
if ($validator->fails())
{
return \Response::json([
'created' => false,
'errors' => $validator->errors()->all()
],500);
}
else
{
DB::beginTransaction();
DB::table('users')->where('id', $id)
->update(['name' => $request->name,
'id_dependencia' => $request->dependencia_id,
'id_perfil' => $request->rol_id,
'status_id'=>$request->status_id,
'id_nom_nucleo'=>$request->id_nom_nucleo]);
DB::commit();
return \Response::json([
'created' =>true
],200);
// $succarray('success'=>true,'mensaje'=>'Usuario Modificado con Exito!!');
// return response()->json($success);ess=
}
}
public function Destroy($id){
User::destroy($id);
return redirect()->back();
}
public function resetPassword(Request $request) {
//verificar si la globals settings email esta configurada
// if(!$this->emailConfig()){
// return \Response::json(['result' => false,'errors'=>'The global settings for sending e-mail password is not configured'], 400);
// }
$rules = ['email' =>'required'];
$validator = \Validator::make($request->all(), $rules);
if ($validator->fails())
{
if(empty($request->type)){//significa que no es por ajax
return [
'created' => false,
'errors' => $validator->errors()->all()
];
}
else{
return response()->json(['created' => false,'errors' => $validator->errors()->all()],500);
}
}
//verificar si el usuario existe
$User=User::where('email',$request->email)->get()->toArray();
if(sizeof($User) !== 0){//el url existe
$cadena = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
$longitudCadena=strlen($cadena);
$pass = "";
$longitudPass=10;
for($i=1 ; $i<=$longitudPass ; $i++)
{
$pos=rand(0,$longitudCadena-1);
$pass .= substr($cadena,$pos,1);
}
// $request->password= <PASSWORD>($pass);
$password= $pass;
$email=$request->email;
$name=$request->email;
//cambiar el valor de la variable config
// config(['mail.username'=>'<EMAIL>']);
// config(['mail.password'=>'*<PASSWORD>#']);
Mail::send('email.reset_password',['name' =>$User[0]['email'] ,'password' => $pass],
function($message) use ($email,$name,$password)
{
// $message->from('<EMAIL>', 'CIMACAST');
$message->to($email, $name)
->subject('Password reset successfully '.$name);
});
User::find($User[0]['id'])->update(['password'=><PASSWORD>($pass)]);
if(empty($request->type)){//significa que no es por ajax
Session::flash('success','success');
Session::flash('mensaje','An email has been sent with your new password');
return redirect('login');
}
else{
return response()->json(['success'=>true,'mensaje'=>'An email has been sent with your new password']);
}
}
else{//el url no existe
if(empty($request->type)){//significa que no es por ajax
Session::flash('success','danger');
Session::flash('mensaje','Unregistered email '.$request->email);
return redirect('login');
}
else{
return response()->json(['success'=>false,'errors'=>['Unregistered email '.$request->email]],500);
}
}
}
public function show($id){
$User=User::
select('users.*','personal.nombre','dependencia_udo.descripcion','personal.apellido','personal.telefono_habitacion','personal.telefono_oficina','perfil.nombre_perfil')->where('id',$id)
->join('perfil','users.id_perfil','=','perfil.id_perfil')
->join('dependencia_udo','users.id_dependencia','=','dependencia_udo.id_dependencia')
->join('personal','users.personal_id','=','personal.id_personal')->first();
if($User=='[]'){
return Response::json([
'created' => false,
'errors' => 'Este equipo no es Propiedad de La Universidad de Oriente'
], 500);
}
return $User;
}
}
<file_sep>/database/migrations/2018_05_05_111728_create_jefes_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateJefesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('jefes', function (Blueprint $table) {
$table->increments('id_jefes');
$table->integer('id_dependencias')->unsigned();
$table->foreign('id_dependencias')->references('id_dependencias')->on('dependencias')->onDelete('cascade');
$table->integer('id_users')->unsigned();
$table->foreign('id_users')->references('id')->on('users')->onDelete('cascade');
$table->date('fecha_inicio');
$table->date('fecha_fin');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('jefes');
}
}
<file_sep>/public/js/Profile.js
/*
* 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.
*/
var url_base=$('#url_base').val();
function save(id){
$('#pleaseWaitDialog').modal('show');
$.ajax
({
type: 'post',
url: url_base+'/profile/save/'+id,
data:{
_token:$('input[name=_token]').val(),
nombres:$('#nombres').val(),
apellidos:$('#apellidos').val(),
email:$('#email').val(),
password:$('#<PASSWORD>').val(),
passwordold:$('#password-old').val(),
imgUser: $('input[name=imgUser]').val(),
img_old: $('input[name=img_old]').val(),
imgSello: $('input[name=imgSello]').val(),
imgFirma: $('input[name=imgFirma]').val(),
id_dedicacion: $('select[name=id_dedicacion]').val(),
id_dedicacion_estudiante: $('select[name=id_dedicacion_estudiante]').val()
},
success:function (data)
{
$('#pleaseWaitDialog').modal('hide');
$('#modalerrorbody').empty().append(data.msj);
$('#modalError [class= "modal-title"]').empty().append('Información');
$('#modalError').modal('show');
location.href=$('#url_base').val()+'/home';
},
error:function(data){
$('#pleaseWaitDialog').modal('hide');
data=jQuery.parseJSON(data.responseText);
var mensaje='';
if(Array.isArray(data.errors)){
for (var i = 0; i < data.errors.length; i++){
mensaje += data.errors[i] + '<br>';
}
}
else{
mensaje=data.errors;
}
$('#modalerrorbody').empty().append(mensaje);
$('#modalError [class= "modal-title"]').empty().append('A Ocurrido Un Error');
$('#modalError').modal('show');
}
});
}<file_sep>/database/seeds/TipoTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\Tipo;
class TipoTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$Tipo=[[
'id_tipo'=>'1',
'nombre_tipo'=>'DOCENTE',
'descripcion_tipo'=>'DOCENTE',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_tipo'=>'2',
'nombre_tipo'=>'ADMINISTRATIVO',
'descripcion_tipo'=>'ADMINISTRATIVO',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_tipo'=>'3',
'nombre_tipo'=>'ESTUDIANTE',
'descripcion_tipo'=>'ESTUDIANTE',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
]];
foreach($Tipo as $tipos){
if(!Tipo::find($tipos['id_tipo'])){
DB::table('tipo')->insert($tipos);
}
}
}
}
<file_sep>/app/TipoOficio.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class TipoOficio extends Model
{
protected $table = 'tipo_oficio';
protected $primaryKey='id_tipo_oficio';
protected $fillable=['nombre'];
}
<file_sep>/app/Personal.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Personal extends Model
{
protected $table = 'personal';
protected $primaryKey = 'id_personal';
protected $fillable = [
'unidad_ejecutora',
'unidad_asignado',
'nacionalidad',
'cedula',
'nombre',
'apellido',
'telefono_habitacion',
'telefono_oficina',
];
}
<file_sep>/app/Municipios.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Municipios extends Model
{
protected $table='municipio';
protected $primaryKey='id_municipio';
protected $fillable=['id_pais','id_state','nombre'];
public static function municipios($id)
{
return Municipios::where('id_state', $id)->get();
}
}
<file_sep>/database/migrations/2018_04_18_163154_create_circular_table.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCircularTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('circular', function (Blueprint $table) {
$table->increments('id_circular');
$table->integer('id_documento')->unsigned();
$table->foreign('id_documento')->references('id_documento')->on('documento')->onDelete('cascade');
$table->integer('id_itemsubcategoria')->unsigned();
$table->foreign('id_itemsubcategoria')->references('id_itemsubcategoria')->on('itemsubcategoria')->onDelete('cascade');
$table->text('nota_circular');
$table->string('para_circular',100);
$table->string('de_circular',100);
$table->text('cuerpo_circular');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('circular');
}
}
<file_sep>/database/seeds/EstudiantesTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\Estudiante;
class EstudiantesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$Estudiante=[[
'id_estudiante'=>'1',
'id_user'=>'1',
'id_tipo'=>'1',
'id_dependencia'=>'2',
'id_dedicacion_estudiante'=>'1',
'firma'=>'firma.png',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
]];
foreach($Estudiante as $estudiantes){
if(!Estudiante::find($estudiantes['id_estudiante'])){
DB::table('estudiante')->insert($estudiantes);
}
}
}
}<file_sep>/database/seeds/AsignaturasTableSeeders.php
<?php
use Illuminate\Database\Seeder;
use App\Asignaturas;
class AsignaturasTableSeeders extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$Asignatura=[[
'id_asignatura'=>'1',
'codigo'=>'006-1513',
'nombre'=>'Compresion y expesion lingüística',
'semestre'=>'1',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'2',
'codigo'=>'230-1214',
'nombre'=>'Algoritmo y Estructura de Dato I',
'semestre'=>'1',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'3',
'codigo'=>'230-1713',
'nombre'=>'Introduccion a la Informatica',
'semestre'=>'1',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'4',
'codigo'=>'230-1613',
'nombre'=>'Metodologia de la investigacion',
'semestre'=>'1',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'5',
'codigo'=>'008-1214',
'nombre'=>'Matematicas I',
'semestre'=>'1',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'6',
'codigo'=>'007-1323',
'nombre'=>'Ingles I',
'semestre'=>'2',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'7',
'codigo'=>'230-1324',
'nombre'=>'Algoritmo y Estructura de Dato II',
'semestre'=>'2',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'8',
'codigo'=>'230-1723',
'nombre'=>'Organización y Sistemas',
'semestre'=>'1',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'9',
'codigo'=>'230-1224',
'nombre'=>'Estructuras Discretas',
'semestre'=>'1',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'10',
'codigo'=>'008-1224',
'nombre'=>'Matematicas II',
'semestre'=>'1',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'11',
'codigo'=>'007-2333',
'nombre'=>'Ingles II',
'semestre'=>'3',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'12',
'codigo'=>'230-2234',
'nombre'=>'Algoritmo y Estructura de Dato III',
'semestre'=>'3',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'13',
'codigo'=>'230-2534',
'nombre'=>'Fundamentos de Electricidad y Electronica',
'semestre'=>'3',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'14',
'codigo'=>'230-2333',
'nombre'=>'Procesamientos de Datos y Archivo',
'semestre'=>'3',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'15',
'codigo'=>'008-2134',
'nombre'=>'Matematicas III',
'semestre'=>'3',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'16',
'codigo'=>'230-2144',
'nombre'=>'Probabilidad y Estadistica',
'semestre'=>'4',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'17',
'codigo'=>'230-2444',
'nombre'=>'Organizacion y Estructura del Computador',
'semestre'=>'4',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'18',
'codigo'=>'230-1723',
'nombre'=>'Sistemas de Informacion I',
'semestre'=>'4',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'19',
'codigo'=>'230-2244',
'nombre'=>'Algebra Lineal',
'semestre'=>'4',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'20',
'codigo'=>'230-3254',
'nombre'=>'Lenguaje de Programacion',
'semestre'=>'5',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'21',
'codigo'=>'230-3454',
'nombre'=>'Comunicacion de Datos',
'semestre'=>'5',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'22',
'codigo'=>'230-3354',
'nombre'=>'Diseño de Base De Datos',
'semestre'=>'5',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'23',
'codigo'=>'230-3154',
'nombre'=>'Calculo Numerico',
'semestre'=>'5',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'24',
'codigo'=>'230-3564',
'nombre'=>'Interaccion Hombre Maquina',
'semestre'=>'6',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'25',
'codigo'=>'230-3464',
'nombre'=>'Sistemas Operativos',
'semestre'=>'6',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'26',
'codigo'=>'230-3364',
'nombre'=>'Sistemas De Informacion II',
'semestre'=>'6',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'27',
'codigo'=>'230-3164',
'nombre'=>'Programacion Lineal',
'semestre'=>'6',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'28',
'codigo'=>'230-4174',
'nombre'=>'Simulacion y Modelos',
'semestre'=>'7',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'29',
'codigo'=>'230-5896',
'nombre'=>'Practicas Pre-Profesionales',
'semestre'=>'9',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'30',
'codigo'=>'230-5804',
'nombre'=>'Trabajo de Grado I',
'semestre'=>'10',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_asignatura'=>'31',
'codigo'=>'230-5805',
'nombre'=>'Trabajo de Grado II',
'semestre'=>'10',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
]];
foreach($Asignatura as $asignaturas){
if(!Asignaturas::find($asignaturas['id_asignatura'])){
DB::table('asignatura')->insert($asignaturas);
}
}
}
}
<file_sep>/app/Http/Controllers/UbicacionController.php
<?php
namespace App\Http\Controllers;
use App\Documento;
use DB;
class UbicacionController extends Controller
{
public function index()
{
$data= Documento::paginate(10);
return view('ubicacion/index')->with(['data'=>$data]);
}
public function show($id){
/* $data=DB::table('ruta')->select('documento.codigo_plantilla','documento.descripcion_documento','ruta.*','dependencia.nombre_dependencia','estados.id_estados','estados.nombre','users.nombres','users.apellidos')
->join('documento','ruta.id_documento','=','documento.id_documento')
->join('dependencia','documento.id_dependencia_c','=','dependencia.id_dependencia')
->join('estados','ruta.id_estado','=','estados.id_estados')
->join('users','ruta.id_user','=','users.id')
->where('ruta.id_documento',$id)
->orderBy('ruta.fecha', 'asc')->get();*/
$data=DB::table('ruta')->select('documento.codigo_plantilla','documento.descripcion_documento','ruta.*','dependencia.nombre_dependencia','estados.id_estados','estados.nombre','users.nombres','users.apellidos')
->join('documento','ruta.id_documento','=','documento.id_documento')
//->join('dependencia','documento.id_dependencia_c','=','dependencia.id_dependencia')
//
->join('estados','ruta.id_estado','=','estados.id_estados')
->join('dependencia','ruta.id_dependencia','=','dependencia.id_dependencia')
->join('users','ruta.id_user','=','users.id')
->where('ruta.id_documento',$id)
->orderBy('ruta.fecha', 'asc')->get();
return view('ubicacion/show')->with(['data'=>$data]);
}
}
<file_sep>/app/Subcategoria.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Subcategoria extends Model
{
protected $table = 'subcategoria_documento';
protected $primaryKey='id_subcategoria';
protected $fillable=['id_categoria','nombre_subcategoria','descripcion_subcategoria'];
public static function subcategorias($id)
{
return Subcategoria::where('id_categoria', $id)->get();
}
}<file_sep>/app/Concursos.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Concursos extends Model
{
protected $table='concurso';
protected $primaryKey='id_concurso';
protected $fillable=['id_periodo','fecha_apertura','fecha_cierre','cupo_asignado','limite'];
}
<file_sep>/app/Http/Controllers/HorarioController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\ConcursoPreparador;
use App\Horario;
use App\Aulas;
use App\Asignaturas;
use App\Plazas;
use App\Concursos;
use App\AsignarAulas;
use App\RutasP;
use App\Preparadurias;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Response;
use DB;
use Auth;
use PDF;
use Illuminate\Support\Facades\Input;
class HorarioController extends Controller
{
public function index()
{
$data=ConcursoPreparador::select('preparaduria.id_preparaduria','users.nombres','users.apellidos','concurso_preparador.puntaje','concurso_preparador.condicion')
->join('preparaduria','concurso_preparador.id_preparaduria','preparaduria.id_preparaduria')
->join('estudiante','preparaduria.id_estudiante','estudiante.id_estudiante')
->join('users','estudiante.id_user','users.id')
->where('concurso_preparador.id_periodo','1')
->where('concurso_preparador.plaza','1')
->orderby('concurso_preparador.puntaje','desc')
->get();
return view('horario/index')->with(['data'=>$data]);
}
public function create($id)
{
$Concurso=Concursos::where('id_periodo','1')->paginate(10);
$Aula=Aulas::orderby('nombre','asc')->pluck('nombre','id_aula');
$Asignatura= Asignaturas::join('plazas','asignatura.id_asignatura','=','plazas.id_asignatura')->where('plazas.id_concurso',$Concurso[0]['attributes']['id_concurso'])->where('plazas.asignado','0')->orderby('nombre','asc')->pluck('nombre','asignatura.id_asignatura');
return view('horario/create')->with(['Asignatura'=>$Asignatura,'Aula'=>$Aula,'id'=>$id]);
}
public function CargarHorario(Request $request)
{
if( $request->id_aula_4!=""){
$rules = array(
'id_asignatura'=> 'required',
'id_aula_1'=> 'required',
'dia_1'=> 'required',
'hora_entrada_1'=> 'required',
'hora_salida_1'=> 'required',
'id_aula_2'=> 'required',
'dia_2'=> 'required',
'hora_entrada_2'=> 'required',
'hora_salida_2'=> 'required',
'id_aula_3'=> 'required',
'dia_3'=> 'required',
'hora_entrada_3'=> 'required',
'hora_salida_3'=> 'required',
'id_aula_4'=> 'required',
'dia_4'=> 'required',
'hora_entrada_4'=> 'required',
'hora_salida_4'=> 'required',
);
$mensajes=array(
'id_asignatura.required'=>'La Asignatura a Dar Es Obligatoria',
'id_aula_1.required' => 'El Aula Para el Dia N°1 Es Obligatoria',
'dia_1.required'=>'El Dia N°1 Es Obligatorio',
'hora_entrada_1.required'=>'La Hora de Entrada Es Obligatoria',
'hora_salidad_1.required'=>'La Hora de Salida Es Obligatoria',
'id_aula_2.required' => 'El Aula Para el Dia N°2 Es Obligatoria',
'dia_2.required'=>'El Dia N°2 Es Obligatorio',
'hora_entrada_2.required'=>'La Hora de Entrada Es Obligatoria',
'hora_salidad_2.required'=>'La Hora de Salida Es Obligatoria',
'id_aula_3.required' => 'El Aula Para el Dia N°3 Es Obligatoria',
'dia_3.required'=>'El Dia N°3 Es Obligatorio',
'hora_entrada_3.required'=>'La Hora de Entrada Es Obligatoria',
'hora_salidad_3.required'=>'La Hora de Salida Es Obligatoria',
'id_aula_4.required' => 'El Aula Para el Dia N°4 Es Obligatoria',
'dia_4.required'=>'El Dia N°4 Es Obligatorio',
'hora_entrada_4.required'=>'La Hora de Entrada Es Obligatoria',
'hora_salidad_4.required'=>'La Hora de Salida Es Obligatoria',
);
}
else{
$rules = array(
'id_asignatura'=> 'required',
'id_aula_1'=> 'required',
'dia_1'=> 'required',
'hora_entrada_1'=> 'required',
'hora_salida_1'=> 'required',
'id_aula_2'=> 'required',
'dia_2'=> 'required',
'hora_entrada_2'=> 'required',
'hora_salida_2'=> 'required',
'id_aula_3'=> 'required',
'dia_3'=> 'required',
'hora_entrada_3'=> 'required',
'hora_salida_3'=> 'required',
);
$mensajes=array(
'id_asignatura.required'=>'La Asignatura a Dar Es Obligatoria',
'id_aula_1.required' => 'El Aula Para el Dia N°1 Es Obligatoria',
'dia_1.required'=>'El Dia N°1 Es Obligatorio',
'hora_entrada_1.required'=>'La Hora de Entrada Es Obligatoria',
'hora_salidad_1.required'=>'La Hora de Salida Es Obligatoria',
'id_aula_2.required' => 'El Aula Para el Dia N°2 Es Obligatoria',
'dia_2.required'=>'El Dia N°2 Es Obligatorio',
'hora_entrada_2.required'=>'La Hora de Entrada Es Obligatoria',
'hora_salidad_2.required'=>'La Hora de Salida Es Obligatoria',
'id_aula_3.required' => 'El Aula Para el Dia N°3 Es Obligatoria',
'dia_3.required'=>'El Dia N°3 Es Obligatorio',
'hora_entrada_3.required'=>'La Hora de Entrada Es Obligatoria',
'hora_salidad_3.required'=>'La Hora de Salida Es Obligatoria',
);
}
$validator = Validator::make(Input::all(), $rules,$mensajes);
if ($validator->fails())
return Response::json(array('success'=>false,'errors' => $validator->errors()->all()));
else
{
DB::beginTransaction();
$Horario=new Horario();
$Horario->id_preparaduria=$request->id_preparaduria;
$Horario->id_asignatura=$request->id_asignatura;
$Horario->save();
$AsingarAulas=new AsignarAulas();
$AsingarAulas->id_horario=$Horario->id_horario;
$AsingarAulas->id_aula=$request->id_aula_1;
$AsingarAulas->dia=$request->dia_1;
$AsingarAulas->entrada=substr($request->hora_entrada_1,0,5);
$AsingarAulas->salida=substr($request->hora_salida_1,0,5);
$AsingarAulas->save();
$AsingarAu=new AsignarAulas();
$AsingarAu->id_horario=$Horario->id_horario;
$AsingarAu->id_aula=$request->id_aula_2;
$AsingarAu->dia=$request->dia_2;
$AsingarAu->entrada=substr($request->hora_entrada_2,0,5);
$AsingarAu->salida=substr($request->hora_salida_2,0,5);
$AsingarAu->save();
$AsingarAul=new AsignarAulas();
$AsingarAul->id_horario=$Horario->id_horario;
$AsingarAul->id_aula=$request->id_aula_3;
$AsingarAul->dia=$request->dia_3;
$AsingarAul->entrada=substr($request->hora_entrada_3,0,5);
$AsingarAul->salida=substr($request->hora_salida_3,0,5);
$AsingarAul->save();
if( $request->id_aula_4!="")
{
$AsingarAula=new AsignarAulas();
$AsingarAula->id_horario=$Horario->id_horario;
$AsingarAula->id_aula=$request->id_aula_4;
$AsingarAula->dia=$request->dia_4;
$AsingarAula->entrada=substr($request->hora_entrada_4,0,5);
$AsingarAula->salida=substr($request->hora_salida_4,0,5);
$AsingarAula->save();
}
$RutasP=new RutasP;
$RutasP->id_estado='15';
$RutasP->id_preparaduria=$request->id_preparaduria;
$RutasP->id_dependencia=Auth::User()->id_dependencia;
$RutasP->id_user=Auth::user()->id;
$RutasP->fecha=date('Y-m-d');
$RutasP->save();
Plazas::where('id_asignatura',$request->id_asignatura)->update(['asignado' => '1']);
Preparadurias::where('id_preparaduria',$request->id_preparaduria)->update(['id_estados' => '15']);
ConcursoPreparador::where('id_preparaduria',$request->id_preparaduria)->update(['plaza' =>'2']);
DB::commit();
$success=array('success'=>true,'mensaje'=>'Horario Asignado Con Exito!!');
return response()->json($success);
}
}
public function HorarioClases(Request $request)
{
$Periodo= \App\Periodos::where('id_periodo','1')->get();
$Horario = Horario::select('users.nombres','users.apellidos','asignatura.nombre','periodo.nombre as periodo')->join('asignatura','horario.id_asignatura','=','asignatura.id_asignatura')
->join('preparaduria','horario.id_preparaduria','=','preparaduria.id_preparaduria')
->join('periodo','preparaduria.id_periodo','=','periodo.id_periodo')
->join('estudiante','preparaduria.id_estudiante','=','estudiante.id_estudiante')
->join('users','estudiante.id_user','=','users.id')
->get();
$Asignado=AsignarAulas::select('aula.nombre','asignar_aula.*')->join('aula','asignar_aula.id_aula','=','aula.id_aula')->get();
view()->share(['Horario'=>$Horario,'Asignado'=>$Asignado,'Periodo'=>$Periodo]);//VARIABLE GLOBAL PRODUCTOS
if($request->has('descargar'))
{
$pdf = PDF::loadView('vista-html-pdf-horario');//CARGO LA VISTA
$pdf->output();
$filename = 'horarioclases.pdf';
return $pdf->stream($filename, array('Attachment' => false));
}
}
}
<file_sep>/app/DependenciaUDO.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class DependenciaUDO extends Model
{
protected $table='dependencia_udo';
protected $primaryKey='id_dependencia';
protected $fillable=['descripcion','siglas','responsable_ejec'];
}
<file_sep>/app/Documento.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Documento extends Model
{
//
protected $table = 'documento';
protected $primaryKey='id_documento';
protected $fillable=['id_dependencia_c','id_usuario','id_categoria','id_subcategoria','id_itemsubcategoria','id_estados','codigo_plantilla','descripcion_documento','descripcion_documento','html_documento'];
}<file_sep>/database/migrations/2018_04_18_163242_create_estudiante_table.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateEstudianteTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('estudiante', function (Blueprint $table) {
$table->increments('id_estudiante');
$table->integer('id_user')->unsigned();
$table->foreign('id_user')->references('id')->on('users')->onDelete('cascade');
$table->integer('id_tipo')->unsigned();
$table->foreign('id_tipo')->references('id_tipo')->on('tipo')->onDelete('cascade');
$table->integer('id_dependencia')->unsigned();
$table->foreign('id_dependencia')->references('id_dependencia')->on('dependencia')->onDelete('cascade');
$table->integer('id_dedicacion_estudiante')->unsigned();
$table->foreign('id_dedicacion_estudiante')->references('id_dedicacion_estudiante')->on('dedicacion_estudiante')->onDelete('cascade');
$table->text('firma')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('estudiante');
}
}
<file_sep>/database/seeds/DedicacionTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\Dedicacion;
class DedicacionTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$Dedicacion=[[
'id_dedicacion'=>'1',
'nombre_dedicacion'=>'Exclusiva',
'descripcion_dedicacion'=>'Exclusiva',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dedicacion'=>'2',
'nombre_dedicacion'=>'Tiempo Completo',
'descripcion_dedicacion'=>'Tiempo Completo',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_dedicacion'=>'3',
'nombre_dedicacion'=>'Medio Tiempo',
'descripcion_dedicacion'=>'Medio Tiempo',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
]];
foreach($Dedicacion as $Dedicaciones){
if(!Dedicacion::find($Dedicaciones['id_dedicacion'])){
DB::table('dedicacion')->insert($Dedicaciones);
}
}
}}
<file_sep>/app/Ciudades.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Ciudades extends Model
{
protected $table='ciudad';
protected $primaryKey='id_ciudad';
protected $fillable=['id_pais','id_state','id_municipio','nombre'];
public static function ciudades($id)
{
return Ciudades::where('id_municipio', $id)->get();
}
}
<file_sep>/app/contrataciones.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class contrataciones extends Model
{
protected $table = 'contratacion';
protected $primaryKey='id_contratacion';
protected $fillable=['id_oficio','id_user','id_asignatura','periodo'];
}
<file_sep>/public/js/Compra.js
new Vue({
el:'#compra',
created:function(){
this.getCompras();
this.getMaterial();
this.getMaterialNew();
this.getMaterial_edit();
},
data:
{
compras:[],
solicitudcompras:[],
solicitud:[],
solicitud_new:[],
pagination_materiales_new:
{
'total_new':0,
'current_page_new':0,
'per_page_new':0,
'last_page_new':0,
'from_new':0,
'to_new':0
},
pagination:
{
'total':0,
'current_page':0,
'per_page':0,
'last_page':0,
'from':0,
'to':0
},
pagination_materiales:
{
'totals':0,
'current_pages':0,
'per_pages':0,
'last_pages':0,
'froms':0,
'tos':0
},
pagination_edit_materiales:
{
'totals_edit':0,
'current_pages_edit':0,
'per_pages_edit':0,
'last_pages_edit':0,
'froms_edit':0,
'tos_edit':0
},
DetalleCompra:[],
errors:[],
errores:[],
nro_solicitud:'',
dependencia:'',
solicitado_por:'',
status:'',
id_compra:'',
depedencia_id:'',
estatus_id:'',
fecha:'',
anio:'',
observacion:'',
conformado_por:'',
autorizado_por:'',
material_id:'',
cantidad:'',
material:'',
unidad_medida:'',
codigo:'',
i:'1',
fillCompras:
{
'id_compra':'',
'depedencia_id':'',
'estatus_id':'',
'fecha':'',
'nro_solicitud':'',
'anio':'',
'observacion':'',
'solicitado_por':'',
'conformado_por':'',
'autorizado_por':'',
'material_id':'',
'material':'',
'unidad_medida':'',
'codigo':'',
'cantidad':''
}
},
computed:{
isActived:function(){
return this.pagination.current_page;
},
pagesNumber:function(){
if(!this.pagination.to){
return[];
}
this.offset=2;
var from = this.pagination.current_page - this.offset;//todo offset
if(from<1){
from=1;
}
var to=from +(this.offset*2);//todo
if(to>=this.pagination.last_page){
to=this.pagination.last_page;
}
var pagesArray=[];
while(from<=to){
pagesArray.push(from);
from++;
}
return pagesArray;
},
isActiveds:function(){
return this.pagination_materiales.current_pages;
},
pagesNumbers:function(){
if(!this.pagination_materiales.tos){
return[];
}
this.offsets=2;
var froms = this.pagination_materiales.current_pages - this.offsets;//todo offset
if(froms<1){
froms=1;
}
var tos=froms +(this.offsets*2);//todo
if(tos>=this.pagination_materiales.last_pages){
tos=this.pagination_materiales.last_pages;
}
var pagesArrays=[];
while(froms<=tos){
pagesArrays.push(froms);
froms++;
}
return pagesArrays;
},
isActiveds_edit:function(){
return this.pagination_edit_materiales.current_pages_edit;
},
pagesNumbers_edit:function(){
if(!this.pagination_edit_materiales.tos_edit){
return[];
}
this.offsets_edit=2;
var froms_edit = this.pagination_edit_materiales.current_pages_edit - this.offsets_edit;//todo offset
if(froms_edit<1){
froms_edit=1;
}
var tos_edit=froms_edit +(this.offsets_edit*2);//todo
if(tos_edit>=this.pagination_edit_materiales.last_pages_edit){
tos_edit=this.pagination_edit_materiales.last_pages_edit;
}
var pagesArrays_edit=[];
while(froms_edit<=tos_edit){
pagesArrays_edit.push(froms_edit);
froms_edit++;
}
return pagesArrays_edit;
},
isActived_new:function(){
return this.pagination_materiales_new.current_page_new;
},
pagesNumbers_new:function()
{
if(!this.pagination_materiales_new.to_new){
return[];
}
this.offset_new=2;
var from_new = this.pagination_materiales_new.current_page_new - this.offset_new;//todo offset
if(from_new<1){
from_new=1;
}
var to_new=from_new +(this.offset_new*2);//todo
if(to_new>=this.pagination_materiales_new.last_page_new){
to_new=this.pagination_materiales_new.last_page_new;
}
var pagesArrays_New=[];
while(from_new<=to_new){
pagesArrays_New.push(from_new);
from_new++;
}
return pagesArrays_New;
}
},
methods:
{
getCompras:function(page)
{
var urlCompras='compras/mostrar?page='+page;
$('#pleaseWaitDialog').modal('show');
axios.get(urlCompras).then(response=>{
this.compras = response.data.compras.data;
this.pagination=response.data.pagination;
});
$('#pleaseWaitDialog').modal('hide');
},
limpiarFormularioCompras:function()
{
this.material_id='',
this.cantidad='',
this.observacion='',
this.errors=[];
},
limpiarFormularioAgregarMaterial:function()
{
this.material_id='',
this.cantidad='',
this.errors=[];
},
CreateSolCompra:function()
{
var urlPost='compras/store';
$('#pleaseWaitDialog').modal('show');
axios.post(urlPost,
{
material_id:this.material_id,
cantidad:this.cantidad,
observacion:this.observacion
}).then(response=>{
$('#pleaseWaitDialog').modal('hide');
this.id_compra=response.data.id_compra;
this.nro_solicitud=response.data.nro_solicitud;
this.getMaterialNew();
$('#modalExitoBody').empty().append(response.data.mensaje);
$('#modalExito [class= "modal-header"]').addClass('bg-success');
$('#modalExito [class= "modal-title"]').empty().append('Informacion');
$('#modalExito').modal('show');
this.limpiarFormularioAgregarMaterial();
}).catch(error=>{
$('#pleaseWaitDialog').modal('hide');
if (Array.isArray(error.response.data.errors)) {
for (var i = 0; i < error.response.data.errors.length; i++) {
this.errors += error.response.data.errors[i] + '<br>';
}
}
this.errores=error.response.data.errores;
if(this.errors!="")
{
$('#modalerrorbody').empty().append(this.errors);
$('#modalError [class= "modal-dialog "]').addClass('modal-danger');
$('#modalError [class= "modal-title"]').empty().append('Se ha producido un error');
$('#modalError').modal('show');
}
else{
$('#modalerrorbody').empty().append(this.errores);
$('#modalError [class= "modal-dialog "]').addClass('modal-danger');
$('#modalError [class= "modal-title"]').empty().append('Se ha producido un error');
$('#modalError').modal('show');
}
this.errors=[];
this.errores=[];
});
},
AgregaSolCompra:function()
{
var urlPost='compras/agrega';
$('#pleaseWaitDialog').modal('show');
axios.post(urlPost,
{
material_id:this.material_id,
cantidad:this.cantidad,
observacion:this.observacion
}).then(response=>{
$('#pleaseWaitDialog').modal('hide');
this.id_compra=response.data.id_compra;
this.nro_solicitud=response.data.nro_solicitud;
this.getMaterial();
$('#modalExitoBody').empty().append(response.data.mensaje);
$('#modalExito [class= "modal-header"]').addClass('bg-success');
$('#modalExito [class= "modal-title"]').empty().append('Informacion');
$('#modalExito').modal('show');
this.limpiarFormularioAgregarMaterial();
}).catch(error=>{
$('#pleaseWaitDialog').modal('hide');
if (Array.isArray(error.response.data.errors)) {
for (var i = 0; i < error.response.data.errors.length; i++) {
this.errors += error.response.data.errors[i] + '<br>';
}
}
this.errores=error.response.data.errores;
if(this.errors!="")
{
$('#modalerrorbody').empty().append(this.errors);
$('#modalError [class= "modal-dialog "]').addClass('modal-danger');
$('#modalError [class= "modal-title"]').empty().append('Se ha producido un error');
$('#modalError').modal('show');
}
else{
$('#modalerrorbody').empty().append(this.errores);
$('#modalError [class= "modal-dialog "]').addClass('modal-danger');
$('#modalError [class= "modal-title"]').empty().append('Se ha producido un error');
$('#modalError').modal('show');
}
this.errors=[];
this.errores=[];
});
},
ShowCompras:function(compra)
{
$('#DetalleCompra').modal('show');
var urlComprasShow='compras/show/'+compra.id_compra;
axios.get(urlComprasShow,this.fillCompras).then(response=>
{
this.id_compra= compra.id_compra;
this.nro_solicitud=response.data.compras.data[0].nro_solicitud;
this.dependencia=response.data.compras.data[0].descripcion;
this.fecha=response.data.compras.data[0].fecha;
this.solicitado_por=response.data.compras.data[0].solicitado_por;
this.conformado_por=response.data.compras.data[0].conformado_por;
this.autorizado_por=response.data.compras.data[0].autorizado_por;
this.getMaterial();
});
},
getMaterialNew:function(pages)
{
var urlCompras='compras/materialnew/'+this.id_compra+'?page='+pages;
axios.get(urlCompras).then(response=>{
this.solicitud_new = response.data.compras.data;
this.pagination_materiales_new=response.data.pagination_materiales_new;
});
},
getMaterial:function(pages)
{
var urlCompras='compras/material/'+this.id_compra+'?page='+pages;
axios.get(urlCompras).then(response=>{
this.solicitud = response.data.compras.data;
this.pagination_materiales=response.data.pagination_materiales;
});
},
getMaterial_edit:function(pages_edit)
{
var urlCompras='compras/editshow/'+this.id_compra+'?page='+pages_edit;
axios.get(urlCompras).then(response=>{
this.DetalleCompra = response.data.compras.data;
this.pagination_edit_materiales=response.data.pagination_edit_materiales;
});
},
Borrador:function()
{
var urlCompras='compras/borrador/'+this.id_compra;
axios.get(urlCompras).then(response=>{
$('#modalExitoBody').empty().append("SE GUARDO CON EXITO LA SOLICITUD DE COMPRA");
$('#modalExito [class= "modal-header"]').addClass('bg-success');
$('#modalExito [class= "modal-title"]').empty().append('Informacion');
$('#modalExito').modal('show');
this.limpiarFormularioCompras();
this.getCompras();
this.solicitud_new=[];
});
},
EditCompras:function(compra)
{
$('#EditCompra').modal('show');
var urlComprasShow='compras/editshow/'+compra.id_compra;
axios.get(urlComprasShow,this.fillCompras).then(response=>
{
this.fillCompras.observacion=compra.observacion;
this.id_compra=compra.id_compra;
this.getMaterial_edit();
});
},
MoficiarCompras:function(compra)
{
var urlCompras='compras/modificarcompra/'+compra.id_compra;
axios.put(urlCompras).then(response=>{
$('#modalExitoBody').empty().append(response.data.mensaje);
$('#modalExito [class= "modal-header"]').addClass('bg-success');
$('#modalExito [class= "modal-title"]').empty().append('Informacion');
$('#modalExito').modal('show');
this.getMaterial_edit();
});
},
UbicacionCompras:function(compra){
alert("Ubicacion de La Ruta de la solicitud de compras En construccion");
},
PdfCompras:function(compra){
alert("PDF de la solicitud de compras En construccion");
},
PorAutorizarCompras:function(compra)
{
var urlCompras='compras/porautorizar/'+compra.id_compra;
axios.get(urlCompras).then(response=>{
$('#modalExitoBody').empty().append("LA SOLICITUD DE COMPRA FUE COLOCADA POR AUTORIZAR");
$('#modalExito [class= "modal-header"]').addClass('bg-success');
$('#modalExito [class= "modal-title"]').empty().append('Informacion');
$('#modalExito').modal('show');
this.getCompras();
});
},
changePage:function(page)
{
this.pagination.current_page=page;
this.getCompras(page);
},
changePages:function(pages)
{
this.pagination_materiales.current_pages=pages;
this.getMaterial(pages);
},
changePages_edit:function(pages_edit)
{
this.pagination_edit_materiales.current_pages_edit=pages_edit;
this.getMaterial_edit(pages_edit);
},
changePage_new:function(page_new)
{
this.pagination_materiales_new.current_page_new=page_new;
this.getMaterialNew(page_new);
},
EliminarMaterialEdit:function(compra){
var urlDelete='solicitudcompras/eliminar/'+compra.id_solicitud_compra;
this.valor=false;
this.valor=this.aviso(compra);
if(this.valor==true)
{
axios.get(urlDelete).then(response=>{
$('#modalerrorbody').empty().append('Se Elimino el Material: '+ compra.material +' de la solicitud de compras satisfactoriamente');
$('#modalError [class= "modal-dialog modal-sm"]').addClass('modal-success');
$('#modalError [class= "modal-title"]').empty().append('Informacion');
$('#modalError').modal('show');
this.getMaterial_edit();
});
}
},
EliminarMaterial:function(compra){
var urlDelete='solicitudcompras/eliminar/'+compra.id_solicitud_compra;
this.valor=false;
this.valor=this.aviso(compra);
if(this.valor==true)
{
axios.get(urlDelete).then(response=>{
$('#modalerrorbody').empty().append('Se Elimino el Material: '+ compra.material +' de la solicitud de compras satisfactoriamente');
$('#modalError [class= "modal-dialog modal-sm"]').addClass('modal-success');
$('#modalError [class= "modal-title"]').empty().append('Informacion');
$('#modalError').modal('show');
this.getMaterial();
});
}
},
aviso:function(compra)
{
if (!confirm("ALERTA!! va a proceder a eliminar el material: " +compra.material+" de la solicitud de compra si desea eliminarlo de click en ACEPTAR\n de lo contrario de click en CANCELAR.")) {
return false;
}
else {
return true;
}
}
}
});<file_sep>/database/seeds/ProfesoresTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\Profesor;
class ProfesoresTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$Profesor=[[
'id_profesor'=>'1',
'id_user'=>'3',
'id_tipo'=>'1',
'id_dependencia'=>'2',
'id_dedicacion'=>'1',
'firma'=>'firma1.jpg',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_profesor'=>'2',
'id_user'=>'6',
'id_tipo'=>'1',
'id_dependencia'=>'1',
'id_dedicacion'=>'1',
'firma'=>'firma2.png',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
]];
foreach($Profesor as $profesores){
if(!Profesor::find($profesores['id_profesor'])){
DB::table('profesor')->insert($profesores);
}
}
}
}<file_sep>/app/Dedicacion.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Dedicacion extends Model
{
protected $table='dedicacion';
protected $primaryKey='id_dedicacion';
protected $fillable=['nombre_dedicacion','descripcion_dedicacion'];
}
<file_sep>/app/Categoria.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Categoria extends Model
{
//
protected $table='categoria_documento';
protected $primaryKey='id_categoria';
protected $fillable=['nombre_categoria','descripcion_categoria'];
}<file_sep>/database/migrations/2018_08_13_123300_create_compra_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCompraTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('compra', function (Blueprint $table) {
$table->increments('id_compra');
$table->integer('dependencia_id')->unsigned();
$table->foreign('dependencia_id')->references('id_dependencia')->on('dependencia_udo')->onDelete('cascade');
$table->integer('estatus_id')->unsigned();
$table->foreign('estatus_id')->references('id_estados')->on('estados')->onDelete('cascade');
$table->date('fecha');
$table->text('nro_solicitud');
$table->text('anio');
$table->text('observacion');
$table->text('solicitado_por');
$table->text('conformado_por');
$table->text('autorizado_por');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('compra');
}
}
<file_sep>/database/seeds/ItemSubcategoriaDocumentoTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\Itemsubcategoria;
class ItemSubcategoriaDocumentoTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$ItemSubCategoria=[[
'id_itemsubcategoria'=>'1',
'id_subcategoria'=>'1',
'nombre_itemsubcategoria'=>'Evento',
'descripcion_itemsubcategoria'=>'',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_itemsubcategoria'=>'2',
'id_subcategoria'=>'1',
'nombre_itemsubcategoria'=>'Charla',
'descripcion_itemsubcategoria'=>'',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_itemsubcategoria'=>'3',
'id_subcategoria'=>'1',
'nombre_itemsubcategoria'=>'Reunion',
'descripcion_itemsubcategoria'=>'',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_itemsubcategoria'=>'4',
'id_subcategoria'=>'1',
'nombre_itemsubcategoria'=>'Otro',
'descripcion_itemsubcategoria'=>'',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_itemsubcategoria'=>'5',
'id_subcategoria'=>'8',
'nombre_itemsubcategoria'=>'Actas/Veredictos',
'descripcion_itemsubcategoria'=>'Actas/Veredictos',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_itemsubcategoria'=>'6',
'id_subcategoria'=>'8',
'nombre_itemsubcategoria'=>'Constancias de Preparaduria',
'descripcion_itemsubcategoria'=>'Constancias de Preparaduria',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_itemsubcategoria'=>'7',
'id_subcategoria'=>'8',
'nombre_itemsubcategoria'=>'Solicitud de menor y mayor carga academica',
'descripcion_itemsubcategoria'=>'',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_itemsubcategoria'=>'8',
'id_subcategoria'=>'8',
'nombre_itemsubcategoria'=>'Solicitud de menor carga y mayor carga acádemica',
'descripcion_itemsubcategoria'=>'',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
]];
foreach($ItemSubCategoria as $items){
if(!Itemsubcategoria::find($items['id_itemsubcategoria'])){
DB::table('itemsubcategoria')->insert($items);
}
}
}
}
<file_sep>/database/seeds/PerfilesTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\Perfil;
class PerfilesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$Perfil=[[
'id_perfil'=>'1',
'nombre_perfil'=>'ADMINISTRADOR',
'descripcion_perfil'=>'ADMINISTRADOR',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_perfil'=>'2',
'nombre_perfil'=>'JEFE DE DEPARTAMENTO',
'descripcion_perfil'=>'JEFE DE DEPARTAMENTO',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_perfil'=>'3',
'nombre_perfil'=>'SECRETARIA',
'descripcion_perfil'=>'SECRETARIA',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_perfil'=>'4',
'nombre_perfil'=>'PROFESOR',
'descripcion_perfil'=>'PROFESOR',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_perfil'=>'5',
'nombre_perfil'=>'ESTUDIANTE',
'descripcion_perfil'=>'ESTUDIANTE',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_perfil'=>'6',
'nombre_perfil'=>'JEFE DE ESCUELA',
'descripcion_perfil'=>'JEFE DE ESCUELA',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
],[
'id_perfil'=>'7',
'nombre_perfil'=>'<NAME>',
'descripcion_perfil'=>'',
'created_at'=>'2017-05-21 10:48:05',
'updated_at'=>'2017-05-21 10:48:05',
]];
foreach($Perfil as $Perfiles){
if(!Perfil::find($Perfiles['id_perfil'])){
DB::table('perfil')->insert($Perfiles);
}
}
}
}
<file_sep>/app/Http/Controllers/UbicacionPreparaduriaController.php
<?php
namespace App\Http\Controllers;
use App\Preparadurias;
use App\Estudiante;
use App\Dependencia;
use App\Horario;
use App\AsignarAulas;
use DB;
use Auth;
class UbicacionPreparaduriaController extends Controller
{
public function index()
{
if(Auth::User()->id_perfil==5)
{
$data= Preparadurias::select('preparaduria.*','asignatura.nombre','users.nombres','users.apellidos')
->join('asignatura','preparaduria.id_asignatura','=','asignatura.id_asignatura')
->join('estudiante','preparaduria.id_estudiante','=','estudiante.id_estudiante')
->join('users','estudiante.id_user','=','users.id')
->where('users.id',Auth::User()->id)
->paginate(10);
}
else{
$data= Preparadurias::select('preparaduria.*','asignatura.nombre','users.nombres','users.apellidos')
->join('asignatura','preparaduria.id_asignatura','=','asignatura.id_asignatura')
->join('estudiante','preparaduria.id_estudiante','=','estudiante.id_estudiante')
->join('users','estudiante.id_user','=','users.id')
->paginate(10);
}
return view('ubicacionpreparaduria/index')->with(['data'=>$data]);
}
public function show($id)
{
$Preparador=Preparadurias::where('id_preparaduria',$id)->get();
$Estudiante=Estudiante::where('id_estudiante',$Preparador[0]['attributes']['id_estudiante'])->get();
$Dependencia= Dependencia::where('id_dependencia',$Estudiante[0]['attributes']['id_dependencia'])->get();
$Escuela=$Dependencia[0]['attributes']['id_escuela'];
$data=DB::table('rutasp')
->select('preparaduria.numero','escuela.nombre as escuela','preparaduria.observacion','rutasp.*','dependencia.nombre_dependencia','estados.id_estados','estados.nombre','asignatura.nombre as materia','users.nombres','users.apellidos','dependencias.nombre as dependencia')
->join('preparaduria','rutasp.id_preparaduria','=','preparaduria.id_preparaduria')
->join('asignatura','preparaduria.id_asignatura','=','asignatura.id_asignatura')
->join('estudiante','preparaduria.id_estudiante','=','estudiante.id_estudiante')
->join('estados','rutasp.id_estado','=','estados.id_estados')
->join('users','rutasp.id_user','=','users.id')
->join('dependencia','users.id_dependencia','=','dependencia.id_dependencia')
->join('dependencias','dependencia.id_dependencia','=','dependencias.id_departamento')
->join('escuela','dependencia.id_escuela','=','dependencia.id_escuela')
->where ('dependencias.id_dependencias','9')
->where ('escuela.id_escuela',$Escuela)
->where('rutasp.id_preparaduria',$id)
->orderBy('rutasp.fecha', 'asc')->get();
$Horario = Horario::select('asignatura.nombre')->join('asignatura','horario.id_asignatura','=','asignatura.id_asignatura')
->join('preparaduria','horario.id_preparaduria','=','preparaduria.id_preparaduria')
->join('periodo','preparaduria.id_periodo','=','periodo.id_periodo')
->join('estudiante','preparaduria.id_estudiante','=','estudiante.id_estudiante')
->join('users','estudiante.id_user','=','users.id')
->get();
$Asignado=AsignarAulas::select('aula.nombre','asignar_aula.*')->join('aula','asignar_aula.id_aula','=','aula.id_aula')->get();
return view('ubicacionpreparaduria/show')->with(['data'=>$data,'Horario'=>$Horario,'Asignado'=>$Asignado]);
}
}
<file_sep>/database/migrations/2014_04_22_005952_create_municipio_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMunicipioTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('municipio', function (Blueprint $table) {
$table->increments('id_municipio');
$table->integer('id_pais')->unsigned();
$table->foreign('id_pais')->references('id_pais')->on('pais')->onDelete('cascade');
$table->integer('id_state')->unsigned();
$table->foreign('id_state')->references('id_state')->on('states')->onDelete('cascade');
$table->text('nombre');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('municipio');
}
}
<file_sep>/database/migrations/2015_10_12_000000_create_users_table.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->integer('id_dependencia')->unsigned();
$table->foreign('id_dependencia')->references('id_dependencia')->on('dependencia')->onDelete('cascade');
$table->integer('id_perfil')->unsigned();
$table->foreign('id_perfil')->references('id_perfil')->on('perfil')->onDelete('cascade');
$table->integer('id_pais')->unsigned();
$table->foreign('id_pais')->references('id_pais')->on('pais')->onDelete('cascade');
$table->integer('id_state')->unsigned();
$table->foreign('id_state')->references('id_state')->on('states')->onDelete('cascade');
$table->integer('id_municipio')->unsigned();
$table->foreign('id_municipio')->references('id_municipio')->on('municipio')->onDelete('cascade');
$table->integer('id_ciudad')->unsigned();
$table->foreign('id_ciudad')->references('id_ciudad')->on('ciudad')->onDelete('cascade');
$table->string('name');
$table->string('email')->unique();
$table->text('avatar');
$table->text('password');
$table->string('cedula',12);
$table->text('nombres');
$table->text('apellidos');
$table->string('telefono',12);
$table->string('sexo',20);
$table->text('ocupacion');
$table->text('direccion');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
<file_sep>/app/Compras.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Compras extends Model
{
protected $table = 'compra';
protected $primaryKey='id_compra';
protected $fillable=['dependencia_id','estatus_id','fecha','nrosol','nro_solicitud','anio','observacion','solicitado_por','conformado_por','autorizado_por'];
}
<file_sep>/database/migrations/2018_05_01_015511_create_oficio_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateOficioTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('oficio', function (Blueprint $table) {
$table->increments('id_oficio');
$table->integer('id_documento')->unsigned();
$table->foreign('id_documento')->references('id_documento')->on('documento')->onDelete('cascade');
$table->integer('id_categoria')->unsigned();
$table->foreign('id_categoria')->references('id_categoria')->on('categoria_documento')->onDelete('cascade');
$table->integer('id_subcategoria')->unsigned();
$table->foreign('id_subcategoria')->references('id_subcategoria')->on('subcategoria_documento')->onDelete('cascade');
$table->integer('id_itemsubcategoria')->unsigned();
$table->foreign('id_itemsubcategoria')->references('id_itemsubcategoria')->on('itemsubcategoria')->onDelete('cascade');
$table->integer('id_estados')->unsigned();
$table->foreign('id_estados')->references('id_estados')->on('estados')->onDelete('cascade');
$table->integer('id_dependencia')->unsigned();
$table->foreign('id_dependencia')->references('id_dependencia')->on('dependencia')->onDelete('cascade');
$table->integer('id_user')->unsigned();
$table->foreign('id_user')->references('id')->on('users')->onDelete('cascade');
$table->integer('id_para_user')->unsigned();
$table->foreign('id_para_user')->references('id')->on('users')->onDelete('cascade');
$table->integer('numero');
$table->text('anio');
$table->text('acronimo');
$table->text('nota');
$table->string('de',100);
$table->text('cuerpo');
$table->date('fecha');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('oficio');
}
}
<file_sep>/app/Http/Controllers/ImportController.php
<?php
namespace App\Http\Controllers;
use App\User;
use App\Profesionales;
use App\Ciudad;
use App\Comunidad;
use App\Provincia;
use App\Privacity;
use App\Pais;
use DB;
use Illuminate\Http\Request;
use Response;
use Illuminate\Support\Facades\Input;
use Validator;
use App\Http\Controllers\Controller;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Controllers\FuncionesCotroller;
class ImportController extends Controller
{
private $dir_tmp;
private $dir_mark;
private $tipo_validos;
public function __construct()
{
//inicializar las variables de configuracion
$this->dir_tmp=env('TMP_DIR');
$this->dir_mark=env('URL_MARKS');
$this->tipo_validos=env('FORMAT_IMG');
//verificar si el directorio existes
if(!is_dir($this->dir_mark))
{
//crear el directorio
mkdir($this->dir_mark,0777);
chmod($this->dir_mark,0777);
}
}
public function importar()
{
return view('perfil/importar');
}
public function import(Request $request)
{
$rules = array(
'file' =>'required|required_with:'.$this->tipo_validos,
);
$mensajes=array(
'file.required'=>'El Archivo CSV A Importar es Obligatorio',
'file.required_with'=>'El archivo CSV debe ser de los tipos '.$this->tipo_validos,
);
$validator = Validator::make(Input::all(), $rules,$mensajes);
if ($validator->fails())
return Response::json(array('success'=>false,'errors' => $validator->errors()->all()));
else
{
Excel::load('file/tmp/'.$request->file, function($reader)
{
foreach ($reader->get() as $user)
{
$email="";
$Consulta=DB::table('users')->select('email','id')->where('email',$user->email)->get()->toArray();
foreach($Consulta as $x){
$email=$x->email;
$id=$x->id;
}
if($email==$user->email)
{
DB::beginTransaction();
$rol="2";
$Funciones= new FuncionesCotroller();
$Hexadecimal=$Funciones->GenerarPGA($rol);
$curriculum = array(
"easociadoe" => $user->asoc,
"licenciafederativa"=>$user->codigo,
"clubpga" => $Hexadecimal,
);
// $Ciudad=Ciudad::where('nombre',$user->poblacion)->get();
//
// $Id_Ciudad=$Ciudad[0]['attributes']['id_ciudad'];
$Provincia= Provincia::where('nombre',$user->provincia)->get();
$Id_Provincia=$Provincia[0]['attributes']['id_provincia'];
$Comunidad= Comunidad::select('comunidad.id_comunidad')->join('provincia','comunidad.id_comunidad','=','provincia.comunidad_id')->where('provincia.nombre',$user->provincia)->get();
$Id_Comunidad=$Comunidad[0]['attributes']['id_comunidad'];
$Pais=Pais::select('pais.id_pais')->join('comunidad','pais.id_pais','=','comunidad.pais_id')->where('comunidad.id_comunidad',$Id_Comunidad)->get();
$Id_Pais=$Pais[0]['attributes']['id_pais'];
DB::table('profesionales')->where('users_id',$id)->update([
'users_id'=>$id,
'pais_id'=>$Id_Pais,
'ciudad_id'=>'1',
'provincia_id'=>$Id_Provincia,
'comunidad_id'=>$Id_Comunidad,
'clubpga'=>$Hexadecimal,
'nombre'=>$user->nombre,
'curriculum'=>json_encode($curriculum),
'direccion'=>'editar',
'telefono_1'=>$id,
'telefono_2'=>$id,
'extracto'=>'editar'
]);
DB::commit();
}
// else
// {
// DB::beginTransaction();
// $rol="2";
// $Funciones= new FuncionesCotroller();
// $Hexadecimal=$Funciones->GenerarPGA($rol);
// $password=$Funciones->GenerarPassword();
// $clave= bcrypt($password);
// $User=User::create
// ([
// 'rol_id'=>'2',
// 'estatus_id'=>'1',
// 'name'=>$user->nombre,
// 'email'=>$user->email,
// 'password'=> $<PASSWORD>,
// 'foto'=>'admin.png',
// 'hexadecimal'=>$Hexadecimal
// ]);
// $curriculum = array(
// "easociadoe" => $user->asoc,
// "licenciafederativa"=>$user->codigo,
// "clubpga" => $Hexadecimal,
// );
//// $Ciudad=Ciudad::where('nombre',$user->poblacion)->get();
//// $Id_Ciudad=$Ciudad[0]['attributes']['id_ciudad'];
// $Provincia= Provincia::where('nombre',$user->provincia)->get();
// $Id_Provincia=$Provincia[0]['attributes']['id_provincia'];
// $Comunidad= Comunidad::select('comunidad.id_comunidad')->join('provincia','comunidad.id_comunidad','=','provincia.comunidad_id')->where('provincia.nombre',$user->provincia)->get();
// $Id_Comunidad=$Comunidad[0]['attributes']['id_comunidad'];
// $Pais=Pais::select('pais.id_pais')->join('comunidad','pais.id_pais','=','comunidad.pais_id')->where('comunidad.id_comunidad',$Id_Comunidad)->get();
// $Id_Pais=$Pais[0]['attributes']['id_pais'];
// Profesionales::create
// ([
// 'users_id'=>$User->id,
// 'pais_id'=>$Id_Pais,
// 'ciudad_id'=>'1',
// 'provincia_id'=>$Id_Provincia,
// 'comunidad_id'=>$Id_Comunidad,
// 'clubpga'=>$Hexadecimal,
// 'nombre'=>$user->nombre,
// 'curriculum'=>json_encode($curriculum),
// 'direccion'=>'editar',
// 'telefono_1'=>$User->id,
// 'telefono_2'=>$User->id,
// 'extracto'=>'editar'
// ]);
// $Privacity = new Privacity();
// $Privacity->users_id = $User->id;
// $Privacity->correo = '0';
// $Privacity->telefono = '0';
// $Privacity->direccion = '0';
// $Privacity->servicios = '0';
// $Privacity->curriculum = '0';
// $Privacity->mapa= '0';
// $Privacity->save();
// DB::commit();
// $admin=env('MAIL_USERNAME');
// $email=env('MAIL_USERNAME');;
// $name=$user->email;
// $fullname=$user->nombre;
// $x=$Funciones->EnviarCorreo($name,$fullname,$email,$password,$admin,$Hexadecimal);
// }
}
});
$success=array('success'=>true,'mensaje'=>'Se importo con exito el csv: '. $request->file);
return response()->json($success);
}
}
}<file_sep>/app/Http/Controllers/SolicitudComprasController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Response;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use View;
use App\Http\Controllers\FuncionesController;
use Illuminate\Support\Facades\Session;
use App\SolicitudCompras;
class SolicitudComprasController extends Controller
{
public function Destroy($id){
SolicitudCompras::destroy($id);
return \Response::json([
'created' => true
],200);
}
}
<file_sep>/database/migrations/2018_04_18_162635_create_itemsubcategoria_table.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateItemsubcategoriaTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('itemsubcategoria', function (Blueprint $table) {
$table->increments('id_itemsubcategoria');
$table->integer('id_subcategoria')->unsigned();
$table->foreign('id_subcategoria')->references('id_subcategoria')->on('subcategoria_documento')->onDelete('cascade');
$table->string('nombre_itemsubcategoria',100);
$table->text('descripcion_itemsubcategoria',100);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('itemsubcategoria');
}
}
<file_sep>/database/migrations/2018_05_05_113912_create_concursopreparador_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateConcursopreparadorTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('concurso_preparador', function (Blueprint $table) {
$table->increments('id_concurso_preparador');
$table->integer('id_user')->unsigned();
$table->foreign('id_user')->references('id')->on('users')->onDelete('cascade');
$table->integer('id_preparaduria')->unsigned();
$table->foreign('id_preparaduria')->references('id_preparaduria')->on('preparaduria')->onDelete('cascade');
$table->integer('id_periodo')->unsigned();
$table->foreign('id_periodo')->references('id_periodo')->on('periodo')->onDelete('cascade');
$table->float('puntaje');
$table->text('condicion');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('concursoperparador');
}
}
<file_sep>/app/ConcursoPreparador.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ConcursoPreparador extends Model
{
protected $table='concurso_preparador';
protected $primaryKey='id_concurso_preparador';
protected $fillable=['id_user','puntaje','condicion'];
}
<file_sep>/database/migrations/2018_08_11_114243_add_id_nom_nucleo_to_users_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddIdNomNucleoToUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->integer('id_nom_nucleo')->after('id_perfil')->unsigned();
$table->foreign('id_nom_nucleo')->references('id_nom_nucleo')->on('nom_nucleo')->onDelete('cascade');
$table->integer('personal_id')->after('id_perfil')->unsigned();
$table->foreign('personal_id')->references('id_personal')->on('personal')->onDelete('cascade');
$table->integer('status_id')->after('id_perfil')->unsigned();
$table->foreign('status_id')->references('id_status')->on('status')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
//
});
}
}
<file_sep>/app/SellosEscuelas.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class SellosEscuelas extends Model
{
protected $table='selloescuela';
protected $primaryKey='id_sello_sello_escuela';
protected $fillable=['id_dependencia','sello'];
}
<file_sep>/app/DedicacionEstudiante.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class DedicacionEstudiante extends Model
{
protected $table='dedicacion_estudiante';
protected $primaryKey='id_dedicacion_estudiante';
protected $fillable=['nombre'];
}<file_sep>/database/migrations/2018_03_11_163840_create_plazas_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePlazasTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('plazas', function (Blueprint $table) {
$table->increments('id_plazas');
$table->integer('id_concurso')->unsigned();
$table->foreign('id_concurso')->references('id_concurso')->on('concurso')->onDelete('cascade');
$table->integer('id_asignatura')->unsigned();
$table->foreign('id_asignatura')->references('id_asignatura')->on('asignatura')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('plazas');
}
}
<file_sep>/app/States.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class States extends Model
{
protected $table='states';
protected $primaryKey='id_state';
protected $fillable=['id_pais','nombre'];
public static function estados($id)
{
return States::where('id_pais', $id)->get();
}
}
<file_sep>/database/migrations/2018_05_11_174239_create_asignar_aula_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAsignarAulaTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('asignar_aula', function (Blueprint $table) {
$table->increments('id_asignar_aula');
$table->integer('id_horario')->unsigned();
$table->foreign('id_horario')->references('id_horario')->on('horario')->onDelete('cascade');
$table->integer('id_aula')->unsigned();
$table->foreign('id_aula')->references('id_aula')->on('aula')->onDelete('cascade');
$table->text('dia');
$table->time('entrada');
$table->time('salida');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('asignar_aula');
}
}
|
23e2042412369a5067c0a5e03b573692b147d734
|
[
"JavaScript",
"SQL",
"PHP"
] | 116 |
PHP
|
zzleomar/sigedocsoldBeta
|
961c87c45eef7b1952d7bdfca457c568f7f5e4e1
|
119921c122c33f989e752d8ddeb7edaef705da18
|
refs/heads/main
|
<repo_name>kvnloughead/news-explorer-api<file_sep>/routes/auth.js
const router = require('express').Router();
const {
createUser, authorizeUser,
} = require('../controllers/auth');
const {
validateCreateUser, validateAuthorizeUser,
} = require('../middleware/validate');
router.post('/signup', validateCreateUser, createUser);
router.post('/signin', validateAuthorizeUser, authorizeUser);
module.exports = router;
<file_sep>/routes/users.js
const router = require('express').Router();
const {
getUsers, getUserById,
} = require('../controllers/users');
const auth = require('../middleware/auth');
const { validateIdParam } = require('../middleware/validate');
router.get('/', auth, getUsers);
router.get('/:id', auth, validateIdParam, getUserById);
module.exports = router;
<file_sep>/controllers/auth.js
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const dotenv = require('dotenv');
const BadRequestError = require('../errors/BadRequestError');
const UnauthorizedError = require('../errors/UnauthorizedError');
const User = require('../models/user');
const { ERROR_MESSAGES, STATUS_CODES, DEV_KEY } = require('../utils/constants');
dotenv.config();
const { NODE_ENV, JWT_SECRET } = process.env;
module.exports.createUser = (req, res, next) => {
const
{
name, email, password,
} = req.body;
bcrypt.hash(password, 10)
.then((hash) => User.create({
email,
name,
password: <PASSWORD>,
}))
.then((user) => res.status(STATUS_CODES.created).send(user))
.catch((err) => {
if (err.message.includes('duplicate key error')) {
throw new BadRequestError(ERROR_MESSAGES.emailNotUnique);
}
if (err.name === 'ValidationError' || err.name === 'MongoError') {
throw new BadRequestError(ERROR_MESSAGES.userBadRequest);
}
next(err);
})
.catch(next);
};
module.exports.authorizeUser = (req, res, next) => {
const { email, password } = req.body;
User.findOne({ email }).select('+password')
.then((user) => {
if (!user) {
throw new UnauthorizedError(ERROR_MESSAGES.badCredentials);
} else {
req._id = user._id;
return bcrypt.compare(password, user.password);
}
})
.then((matched) => {
if (!matched) {
throw new UnauthorizedError(ERROR_MESSAGES.badCredentials);
}
const token = jwt.sign({ _id: req._id }, NODE_ENV === 'production' ? JWT_SECRET : DEV_KEY, { expiresIn: '7d' });
res.header('authorization', `Bearer ${token}`);
res.cookie('token', token, { httpOnly: true });
res.status(STATUS_CODES.ok).send({ token });
})
.catch(next);
};
<file_sep>/routes/articles.js
const router = require('express').Router();
const {
getArticles, createArticle, deleteArticleById,
} = require('../controllers/articles');
const auth = require('../middleware/auth');
const { validateIdParam, validateCreateArticle } = require('../middleware/validate');
router.get('/', auth, getArticles);
router.post('/', auth, validateCreateArticle, createArticle);
router.delete('/:id', auth, validateIdParam, deleteArticleById);
module.exports = router;
<file_sep>/controllers/articles.js
const BadRequestError = require('../errors/BadRequestError');
const InternalServerError = require('../errors/InternalServerError');
const NotFoundError = require('../errors/NotFoundError');
const UnauthorizedError = require('../errors/UnauthorizedError');
const Article = require('../models/article');
const { ERROR_MESSAGES, STATUS_CODES } = require('../utils/constants');
module.exports.getArticles = (req, res, next) => {
Article.find({})
.then((articles) => {
res.status(STATUS_CODES.ok).send(articles);
})
.catch(() => {
throw new InternalServerError(ERROR_MESSAGES.internalServer);
})
.catch(next);
};
module.exports.createArticle = (req, res, next) => {
const {
keyword, title, text, date, source, link, image,
} = req.body;
Article.create({
keyword,
title,
text,
date,
source,
link,
image,
owner: req.user._id,
})
.then((article) => {
res.status(STATUS_CODES.created).send(article);
})
.catch((err) => {
if (err.name === 'ValidationError') {
throw new BadRequestError(ERROR_MESSAGES.articleBadRequest);
}
})
.catch(next);
};
module.exports.deleteArticleById = (req, res, next) => {
Article.findById(req.params.id)
.then((article) => {
if (article && req.user._id.toString() === article.owner.toString()) {
Article.deleteOne(article).then((deletedArticle) => {
res.status(STATUS_CODES.ok).send(deletedArticle);
});
} else if (!article) {
throw new NotFoundError(ERROR_MESSAGES.articleNotFound);
} else {
throw new UnauthorizedError(ERROR_MESSAGES.ownedArticlesOnly);
}
})
.catch((err) => {
if (err.name === 'CastError') {
throw new NotFoundError(ERROR_MESSAGES.articleNotFound);
}
next(err);
})
.catch(next);
};
<file_sep>/app.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const helmet = require('helmet');
const path = require('path');
const { requestLogger, errorLogger } = require('./middleware/logger');
const { handleErrors } = require('./middleware/errors.js');
const { DB_ADDRESS, ERROR_MESSAGES, STATUS_CODES } = require('./utils/constants');
const { limiter } = require('./middleware/limiter');
const routes = require('./routes/index.js');
const { PORT = 3000 } = process.env;
const app = express();
app.use(bodyParser.json());
app.use(express.json({ extended: true }));
app.use(express.urlencoded({ extended: true }));
app.use(helmet());
app.use(limiter);
app.use(errorLogger);
app.use(requestLogger);
mongoose.connect(DB_ADDRESS, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true,
});
app.use('/', routes);
app.use(express.static(path.join(__dirname, 'public')));
app.use((req, res) => {
res.status(STATUS_CODES.notFound).json({ message: ERROR_MESSAGES.notFound });
});
app.use(handleErrors);
app.listen(PORT, () => {
console.log(`App listening at port ${PORT}`);
});
<file_sep>/utils/constants.js
const { NODE_ENV, SERVER_DB_ADDRESS } = process.env;
module.exports.DB_ADDRESS = NODE_ENV === 'production' ? SERVER_DB_ADDRESS : 'mongodb://127.0.0.1:27017/articlesdb';
module.exports.DEV_KEY = 'dev-secret';
module.exports.ERROR_MESSAGES = {
notFound: 'Requested resource not found.',
unauthorized: 'Authorization Required',
ownedArticlesOnly: 'Authorization required. You can only delete your own articles.',
interalServer: 'An error has occured on the server.',
articleBadRequest: 'Data validation failed: article cannot be created.',
articleNotFound: 'Article not found.',
userNotFound: 'User not found',
emailNotUnique: 'That email is already in use.',
userBadRequest: 'Data validation failed: user cannot be created.',
badCredentials: 'Incorrect password or email.',
};
module.exports.STATUS_CODES = {
ok: 200,
created: 201,
badRequest: 400,
unauthorized: 401,
notFound: 404,
internalServer: 500,
};
<file_sep>/README.md
# News Explorer API
This is the backend for my news explorer / article collection app, which is the capstone project in the Practicum Web Development curriculum.
## Features
- Routes for signup and signin, with JWT user authentication.
- Routes for saving articles, and for getting information about saved users and articles.
- Mongo DB for saving users and articles.
- Centralized error handling
## Stack
- Node, Express, Mongo
## Deployment
- Domain - https://api.k.news.students.nomoreparties.site/
- Public IP - 172.16.31.10
<file_sep>/controllers/users.js
const NotFoundError = require('../errors/NotFoundError');
const User = require('../models/user');
const { ERROR_MESSAGES, STATUS_CODES } = require('../utils/constants');
module.exports.getUsers = (req, res, next) => {
User.find({}).select('+password')
.then((user) => res.status(STATUS_CODES.ok).send(user))
.catch(next);
};
module.exports.getUserById = (req, res, next) => {
User.findById(req.params.id === 'me' ? req.user._id : req.params.id).select('+password')
.then((user) => {
if (user) {
res.status(STATUS_CODES.ok).send(user);
}
})
.catch((err) => {
if (err.name === 'CastError' || err.name === 'TypeError') {
throw new NotFoundError(ERROR_MESSAGES.userNotFound);
}
next(err);
})
.catch(next);
};
|
2bc24b739ec6e2c7986aea12eb9a183d1e392d96
|
[
"JavaScript",
"Markdown"
] | 9 |
JavaScript
|
kvnloughead/news-explorer-api
|
1bb4f54898119b75952f195f1b3d604ac5cb9d87
|
3374970f6b3e7545e0b079fec3a5507fb28cdda0
|
refs/heads/master
|
<file_sep>package org.kkamnyang.persistence;
import java.util.List;
import org.kkamnyang.domain.EventVO;
import org.springframework.stereotype.Repository;
@Repository
public class EventMapperImpl extends AbstractCRUDMapper<EventVO,Integer> implements EventMapper {
@Override
public List<EventVO> elist(Integer routeno) {
// TODO Auto-generated method stub
return session.selectList(namespace+".elist",routeno);
}
}
<file_sep>package org.kkamnyang.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.kkamnyang.domain.RouteVO;
import org.kkamnyang.service.RouteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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;
@Controller
@RequestMapping(value="/route/*")
public class RouteController{
@Autowired
RouteService service;
@RequestMapping(value="/list", method=RequestMethod.GET)
public @ResponseBody List<RouteVO> list(HttpServletRequest request) throws Exception{
System.out.println("★모든 루트 리스트의 출력.");
List<RouteVO> result = service.list();
return result;
}
@RequestMapping(value="/create", method=RequestMethod.POST)
public void createRoute(@RequestBody RouteVO vo,HttpServletResponse response) throws Exception{
System.out.println("["+vo.getRoutename()+"] 루트 생성 호출됨.=====");
service.regist(vo);
Integer nowSequnece = vo.getRouteno();
response.getWriter().print(nowSequnece);
}
@RequestMapping(value="/view", method = RequestMethod.GET)
public void view(@RequestParam("routeno") Integer routeno,Model model) throws Exception{
RouteVO vo = service.view(routeno);
model.addAttribute("ROUTE", vo);
}
@RequestMapping(value="/modify", method = RequestMethod.POST)
public void modifyRoute(RouteVO vo) throws Exception{
service.modify(vo);
}
@RequestMapping(value="/remove", method = RequestMethod.POST)
public void removeRoute(@RequestParam("routeno") Integer routeno, Model model) throws Exception{
service.remove(routeno);
}
}
<file_sep>package org.kkamnyang.persistence;
import java.util.Map;
import org.kkamnyang.domain.RouteVO;
import org.springframework.stereotype.Repository;
@Repository
public class RouteMapperImpl extends AbstractCRUDMapper<RouteVO,Integer> implements RouteMapper {
}
<file_sep>package org.kkamnyang.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.kkamnyang.domain.EventVO;
import org.kkamnyang.service.EventService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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;
@Controller
@RequestMapping(value="/event/*")
public class EventController {
@Autowired
EventService service;
@RequestMapping(value="/list", method=RequestMethod.GET)
public @ResponseBody List<EventVO> list(HttpServletRequest request) throws Exception{
System.out.println("이벤트 리스트GET 호출됨.");
List<EventVO> result = service.list();
System.out.println(service.list());
return result;
}
@RequestMapping(value="/elist", method=RequestMethod.GET)
public @ResponseBody List<EventVO> elist(@RequestParam("routeno")Integer routeno, HttpServletRequest request) throws Exception{
System.out.println("모든 이벤트 리스트 호출됨.=====");
List<EventVO> result = service.elist(routeno);
System.out.println(service.elist(routeno));
return result;
}
@RequestMapping(value="/create", method=RequestMethod.POST)
public ResponseEntity<String> createEvent(@RequestBody EventVO vo) throws Exception{
System.out.println("["+vo.getTitle() + "] 이벤트의 생성 호출됨.=====");
System.out.println(vo);
ResponseEntity<String> entity = null;
try{
service.regist(vo);
entity = new ResponseEntity<String>("result",HttpStatus.OK);
}catch(Exception e){
entity = new ResponseEntity<String>("result",HttpStatus.BAD_REQUEST);
}
return entity;
}
@RequestMapping(value="/view", method = RequestMethod.GET)
public @ResponseBody EventVO view(@RequestParam("eventno") Integer eventno, HttpServletRequest request ) throws Exception{
System.out.println("Event View GET 호출됨.");
EventVO result = service.view(eventno);
System.out.println(result);
return result;
}
@RequestMapping(value="/modify", method = RequestMethod.POST)
public ResponseEntity<String> modifyEvent(@RequestBody EventVO vo) throws Exception{
System.out.println("Event 수정 POST 호출됨.");
ResponseEntity<String> entity = null;
try{
service.modify(vo);
entity = new ResponseEntity<String>("result",HttpStatus.OK);
}catch(Exception e){
entity = new ResponseEntity<String>("result", HttpStatus.BAD_REQUEST);
}
return entity;
}
@RequestMapping(value="/remove", method = RequestMethod.POST)
public ResponseEntity<String> removeEvent(@RequestBody EventVO vo) throws Exception{
System.out.println("Event 삭제 POST 호출됨.");
ResponseEntity<String> entity = null;
try{
service.remove(vo.getEventno());
entity = new ResponseEntity<String>("result",HttpStatus.OK);
}catch(Exception e){
entity = new ResponseEntity<String>("result",HttpStatus.BAD_REQUEST);
}
return entity;
}
}
|
38751c588e2b86961edaded7bf83caa8d851aad8
|
[
"Java"
] | 4 |
Java
|
didhddldlq/myArchistory
|
b3e9c1d3bffcc01581b2912ed61c379edeef63a3
|
2d5ddb467a0203e81079410a76edbfcfb6e287a4
|
refs/heads/master
|
<repo_name>nanjiye123/test-one<file_sep>/README.md
# test-one
test github
<file_sep>/hello_github.c
#include <stdio.h>
int main(void)
{
printf("hello_github\n");
return 0;
}
|
d02810f51ac233fda9a4cfee92284da7f18a31f7
|
[
"Markdown",
"C"
] | 2 |
Markdown
|
nanjiye123/test-one
|
f6a1735468be2f3268d6c3da6ab8542959576d2f
|
49360968514d1d3d0bc56e7fc9e8bdf3c3593989
|
refs/heads/main
|
<file_sep># Generated by Django 3.2.5 on 2021-07-26 20:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('clinic_app', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Patient',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('first_name', models.CharField(max_length=30)),
('last_name', models.CharField(max_length=30)),
('id_number', models.IntegerField(blank=True)),
('birth_certificate_no', models.IntegerField(blank=True)),
('gender', models.CharField(choices=[('Male', 'Male'), ('Female', 'Female')], max_length=15)),
('age', models.IntegerField()),
],
),
]
<file_sep>from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from . import views as app_views
from django.contrib.auth import views as auth_views
urlpatterns = [
path('', app_views.index, name="home"),
path('accounts/login/',app_views.login,name='login'),
path('logout/',auth_views.LogoutView.as_view(template_name = 'registration/logout.html'),name='logout'),
path('search',app_views.search,name='search'),
path('add_patient', app_views.add_patient,name='add_patient'),
path('patients', app_views.patients,name='patients'),
path('update_patient/<int:patient_id>', app_views.update_patient,name='update_patient'),
path('delete_patient/<int:patient_id>', app_views.delete_patient,name='delete_patient'),
path('patient_details/<int:patient_id>',app_views.patient_details,name='patient_details'),
path('export_patients',app_views.export_patients,name='export_patients'),
path('add_appointment', app_views.add_appointment,name='add_appointment'),
path('appointments', app_views.appointments,name='appointments'),
path('update_appointment/<int:appointment_id>', app_views.update_appointment,name='update_appointment'),
path('delete_appointment/<int:appointment_id>', app_views.delete_appointment,name='delete_appointment'),
path('appointment_details/<int:appointment_id>',app_views.appointment_details,name='appointment_details'),
path('export_appointments',app_views.export_appointments,name='export_appointments'),
path('add_prescription', app_views.add_prescription,name='add_prescription'),
path('prescriptions', app_views.prescriptions,name='prescriptions'),
path('update_prescription/<int:prescription_id>', app_views.update_prescription,name='update_prescription'),
path('delete_prescription/<int:prescription_id>', app_views.delete_prescription,name='delete_prescription'),
path('prescription_details/<int:prescription_id>',app_views.prescription_details,name='prescription_details'),
path('export_prescriptions',app_views.export_prescriptions,name='export_prescriptions'),
path('add_drug', app_views.add_drug,name='add_drug'),
path('drugs', app_views.drugs,name='drugs'),
path('update_drug/<int:drug_id>', app_views.update_drug,name='update_drug'),
path('delete_drug/<int:drug_id>', app_views.delete_drug,name='delete_drug'),
path('drug_details/<int:drug_id>',app_views.drug_details,name='drug_details'),
path('export_drugs',app_views.export_drugs,name='export_drugs'),
path('add_health_history', app_views.add_health_history,name='add_health_history'),
path('history', app_views.history,name='history'),
path('update_history/<int:history_id>', app_views.update_history,name='update_history'),
path('delete_history/<int:history_id>', app_views.delete_history,name='delete_history'),
path('history_details/<int:history_id>',app_views.history_details,name='history_details'),
path('export_histories',app_views.export_histories,name='export_histories'),
path('add_feedback', app_views.add_feedback,name='add_feedback'),
path('feedback', app_views.feedback,name='feedback'),
path('update_feedback/<int:feedback_id>', app_views.update_feedback,name='update_feedback'),
path('delete_feedback/<int:feedback_id>', app_views.delete_feedback,name='delete_feedback'),
path('feedback_details/<int:feedback_id>',app_views.feedback_details,name='feedback_details'),
path('export_feedbacks',app_views.export_feedbacks,name='export_feedbacks'),
path('add_visit', app_views.add_visit,name='add_visit'),
path('visits', app_views.visits,name='visits'),
path('update_visit/<int:visit_id>', app_views.update_visit,name='update_visit'),
path('delete_visit/<int:visit_id>', app_views.delete_visit,name='delete_visit'),
path('visit_details/<int:visit_id>',app_views.visit_details,name='visit_details'),
path('export_visits',app_views.export_visits,name='export_visits'),
]<file_sep>from django import forms
from django.db.models import fields
from .models import *
class PatientForm(forms.ModelForm):
class Meta:
model = Patient
fields = ('first_name','last_name','id_number','birth_certificate_no','gender','age','phone')
class AppointmentForm(forms.ModelForm):
class Meta:
model = PatientAppointment
fields = ('first_name','last_name','gender','age','phone','appointment_date','approve')
class PrescriptionForm(forms.ModelForm):
class Meta:
model = Prescription
fields = ('patient','dose','drug','prescriber','note')
class DrugForm(forms.ModelForm):
class Meta:
model = Medicine
fields = ('name','description')
class HealthHistoryForm(forms.ModelForm):
class Meta:
model = PatientHealthHistory
fields = ('patient','health_record')
class FeedbackForm(forms.ModelForm):
class Meta:
model = FeedBack
fields = ('patient','feedback_message')
class VisitForm(forms.ModelForm):
class Meta:
model = Visit
fields = ('patient','note')<file_sep># Generated by Django 3.2.5 on 2021-07-28 15:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('clinic_app', '0013_prescription_dose'),
]
operations = [
migrations.AddField(
model_name='medicine',
name='date',
field=models.DateTimeField(auto_now_add=True, default='2021-07-27 22:58:51.049087+03'),
preserve_default=False,
),
migrations.AddField(
model_name='medicine',
name='description',
field=models.TextField(default='Medicine'),
preserve_default=False,
),
]
<file_sep># Generated by Django 3.2.5 on 2021-07-29 09:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('clinic_app', '0014_auto_20210728_1841'),
]
operations = [
migrations.AddField(
model_name='patientappointment',
name='approve',
field=models.BooleanField(default=False),
),
]
<file_sep># Generated by Django 3.2.5 on 2021-07-26 20:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('clinic_app', '0003_visit'),
]
operations = [
migrations.AddField(
model_name='patient',
name='phone',
field=models.IntegerField(blank=True, max_length=10, null=True),
),
migrations.AlterField(
model_name='patient',
name='birth_certificate_no',
field=models.IntegerField(blank=True, null=True),
),
migrations.AlterField(
model_name='patient',
name='id_number',
field=models.IntegerField(blank=True, null=True),
),
]
<file_sep># Generated by Django 3.2.5 on 2021-07-26 20:55
from django.conf import settings
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('clinic_app', '0004_auto_20210726_2349'),
]
operations = [
migrations.RenameModel(
old_name='Profile',
new_name='ClinicalStaff',
),
migrations.RenameField(
model_name='clinicalstaff',
old_name='user',
new_name='staff',
),
]
<file_sep># Generated by Django 3.2.5 on 2021-07-27 13:55
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('clinic_app', '0008_prescription'),
]
operations = [
migrations.CreateModel(
name='PatientAppointment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('first_name', models.CharField(max_length=30)),
('last_name', models.CharField(max_length=30)),
('gender', models.CharField(choices=[('Male', 'Male'), ('Female', 'Female')], max_length=15)),
('age', models.IntegerField()),
('phone', models.IntegerField(blank=True, null=True)),
('date_made', models.DateTimeField(auto_now_add=True)),
('appointment_date', models.DateTimeField(default=django.utils.timezone.now)),
],
),
]
<file_sep># Generated by Django 3.2.5 on 2021-07-29 10:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('clinic_app', '0015_patientappointment_approve'),
]
operations = [
migrations.AlterField(
model_name='patientappointment',
name='approve',
field=models.BooleanField(choices=[('Approved', 'Approved'), ('Not Approved', 'Not Approved'), ('Pending', 'Pending')], default='Pending', max_length=15),
),
]
<file_sep>from django.db import models
from django.contrib.auth.models import User
from django.db.models.deletion import CASCADE
from cloudinary.models import CloudinaryField
from django.db.models.fields import DateTimeField
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils import timezone
# Create your models here.
class ClinicalStaff(models.Model):
staff = models.OneToOneField(User,on_delete=CASCADE)
first_name = models.CharField(max_length=144)
last_name = models.CharField(max_length=144)
email = models.EmailField()
profile_picture = CloudinaryField('image')
def __str__(self):
return self.staff.username
@receiver(post_save, sender=User)
def update_staff_signal(sender, instance, created, **kwargs):
if created:
ClinicalStaff.objects.create(staff=instance)
instance.clinicalstaff.save()
GENDER_CHOICES = (
("Male", "Male"),("Female","Female")
)
APPOINTMENT_STATUS = (
("Approved", "Approved"),("Not Approved", "Not Approved"),("Pending","Pending")
)
class Patient(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
id_number = models.IntegerField(blank=True,null=True)
birth_certificate_no = models.IntegerField(blank=True,null=True)
gender = models.CharField(max_length=15, choices= GENDER_CHOICES)
age = models.IntegerField()
phone = models.IntegerField(blank=True,null=True)
def save_patient(self):
self.save()
def delete_patient(self):
self.delete()
@classmethod
def search_patients(cls, patients):
return cls.objects.filter(first_name__icontains=patients).all()
def __str__(self):
return self.first_name
class Visit(models.Model):
date_visited = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
patient = models.ForeignKey(Patient,on_delete=CASCADE)
note = models.TextField()
def save_visit(self):
self.save()
def delete_visit(self):
self.delete()
def __str__(self):
return self.patient.first_name
class Medicine(models.Model):
name = models.CharField(max_length=144)
description = models.TextField()
date = models.DateTimeField(auto_now_add=True)
def save_medicine(self):
self.save()
def delete_medicine(self):
self.delete()
def __str__(self):
return self.name
class Prescription(models.Model):
patient = models.ForeignKey(Patient,on_delete=CASCADE)
dose = models.CharField(max_length=30)
drug = models.ForeignKey(Medicine,on_delete=CASCADE)
prescriber = models.ForeignKey(ClinicalStaff,on_delete=CASCADE)
date = models.DateTimeField(auto_now_add=True)
note = models.TextField()
def save_prescription(self):
self.save()
def delete_prescription(self):
self.delete()
def __str__(self):
return self.patient.first_name
class PatientHealthHistory(models.Model):
patient = models.ForeignKey(Patient,on_delete=CASCADE)
date_recorded = models.DateTimeField(auto_now_add=True)
health_record = models.TextField()
def save_patient_health_history(self):
self.save()
def delete_patient_health_history(self):
self.delete()
def __str__(self):
return self.patient.first_name
class PatientAppointment(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
gender = models.CharField(max_length=15, choices= GENDER_CHOICES)
age = models.IntegerField()
phone = models.IntegerField(blank=True,null=True)
date_made = models.DateTimeField(auto_now_add=True)
appointment_date = DateTimeField(default=timezone.now)
approve = models.CharField(default="Pending", max_length=15, choices= APPOINTMENT_STATUS)
def save_patient_appointment(self):
self.save()
def delete_patient_appointment(self):
self.delete()
def __str__(self):
return self.first_name
class FeedBack(models.Model):
patient = models.ForeignKey(Patient,on_delete=CASCADE)
feedback_message = models.TextField()
feedback_date = models.DateTimeField(auto_now_add=True)
def save_feedback(self):
self.save()
def delete_feedback(self):
self.delete()
def __str__(self):
return self.patient.first_name
<file_sep># Generated by Django 3.2.5 on 2021-07-28 08:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('clinic_app', '0011_feedback'),
]
operations = [
migrations.AddField(
model_name='patienthealthhistory',
name='date_recorded',
field=models.DateTimeField(auto_now_add=True, default='2021-07-28 00:10:25.142087+03'),
preserve_default=False,
),
]
<file_sep># Generated by Django 3.2.5 on 2021-07-27 13:41
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('clinic_app', '0007_medicine'),
]
operations = [
migrations.CreateModel(
name='Prescription',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date', models.DateTimeField(auto_now_add=True)),
('note', models.TextField()),
('drug', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='clinic_app.medicine')),
('patient', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='clinic_app.patient')),
('prescriber', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='clinic_app.clinicalstaff')),
],
),
]
<file_sep># Generated by Django 3.2.5 on 2021-07-26 21:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('clinic_app', '0005_auto_20210726_2355'),
]
operations = [
migrations.AlterField(
model_name='patient',
name='phone',
field=models.IntegerField(blank=True, null=True),
),
]
<file_sep>from django.apps import AppConfig
class ClinicAppConfig(AppConfig):
name = 'clinic_app'
<file_sep># Meds
## Author
<NAME>
*****
### Description
This is a Django web application for managing patients information in a clinic.
*****
### Application dashboard
*****

*****
### Patients List
*****

*****
### Prerequisites
* Text editor eg Visual Studio Code
* You need to have git installed. You can install it with the following command in your terminal
`$ sudo apt install git-all`
*****
## Setup Instruction
To access this project on your local files, you can clone it using these steps
1. Open your terminal
1. Use this command to clone `$ git clone git remote add origin https://github.com/ngetichnicholas/Meds.git`
1. This will clone the repositoty into your local folder
*****
## Dependencies
* django-bootstrap
* Pillow
* cloudinary
* psycopg2
* django-registration
* python-decouple
* Python Venv
* whitenoise
* gunicorn
*****
## Technologies Used
* HTML
* Python 3
* JavaScript
* CSS
******
### Youtube DEMO
[WATCH DEMO HERE](https://youtu.be/SCUnc7i7-Yg).
*****
### License
This project is under:
[](/LICENSE)
<file_sep>from django.http import response
from django.http.response import Http404, HttpResponse
from django.shortcuts import render, redirect, get_object_or_404, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.contrib.auth import login as auth_login
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import login, authenticate
from django.core.exceptions import ObjectDoesNotExist
from .forms import *
from .models import *
import datetime
import csv
# Create your views here.
@login_required
def index(request):
current_user = request.user
all_patients = Patient.objects.all()
feedback = FeedBack.objects.all()
approved_appointments = PatientAppointment.objects.filter(approve = 'Approved').all()
pending_appointments = PatientAppointment.objects.filter(approve = 'Pending').all()
return render(request, 'index.html',{'feedback':feedback, 'all_patients':all_patients,'current_user':current_user,'approved_appointments':approved_appointments,'pending_appointments':pending_appointments})
def login(request):
if request.method == 'POST':
form = AuthenticationForm(request=request, data=request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
auth_login(request, user)
messages.info(request, f"You are now logged in as {username}")
return redirect('home')
else:
messages.error(request, "Invalid username or password.")
else:
messages.error(request, "Invalid username or password.")
form = AuthenticationForm()
return render(request = request,template_name = "registration/login.html",context={"form":form})
#Patient views
@login_required
def patients(request):
patients = Patient.objects.all().order_by('-first_name')
return render(request,'patients.html',{'patients':patients})
@login_required
def search(request):
if 'name' in request.GET and request.GET["name"]:
search_term = request.GET.get("name")
searched_patients = Patient.search_patients(search_term)
message = f"{search_term}"
return render(request,'search.html', {"message":message,"patients":searched_patients})
else:
message = "You haven't searched for any term"
return render(request,'search.html',{"message":message})
#Export table data as csv
@login_required
def export_patients(request):
response = HttpResponse(content_type = 'text/csv')
response['Content-Disposition'] = 'attachment; filename = Patients'+ str(datetime.datetime.now())+'.csv'
writer = csv.writer(response)
writer.writerow(['First Name','Last Name','ID Number','Birth certificate No','Gender','Age','Tel No'])
patients = Patient.objects.all()
for patient in patients:
writer.writerow([patient.first_name,patient.last_name,patient.id_number,patient.birth_certificate_no,patient.gender,patient.age,patient.phone])
return response
#Get single patient
@login_required
def patient_details(request,patient_id):
try:
patient =get_object_or_404(Patient, pk = patient_id)
except ObjectDoesNotExist:
raise Http404()
return render(request,'patient_details.html',{'patient':patient})
@login_required
def add_patient(request):
if request.method == 'POST':
add_patient_form = PatientForm(request.POST)
if add_patient_form.is_valid():
patient = add_patient_form.save(commit=False)
patient.save()
return redirect('patients')
else:
add_patient_form = PatientForm()
return render(request, 'add_patient.html',{'add_patient_form':add_patient_form})
@login_required
def update_patient(request, patient_id):
patient = Patient.objects.get(pk=patient_id)
if request.method == 'POST':
update_patient_form = PatientForm(request.POST,request.FILES, instance=patient)
if update_patient_form.is_valid():
update_patient_form.save()
messages.success(request, f'Patient updated!')
return redirect('patients')
else:
update_patient_form = PatientForm(instance=patient)
return render(request, 'update_patient.html', {"update_patient_form":update_patient_form})
@login_required
def delete_patient(request,patient_id):
patient = Patient.objects.get(pk=patient_id)
if patient:
patient.delete_patient()
return redirect('patients')
#Appointment views
@login_required
def appointments(request):
appointments = PatientAppointment.objects.all().order_by('-date_made')
return render(request,'appointments.html',{'appointments':appointments})
#Export table data as csv
@login_required
def export_appointments(request):
response = HttpResponse(content_type = 'text/csv')
response['Content-Disposition'] = 'attachment; filename = appointments'+ str(datetime.datetime.now())+'.csv'
writer = csv.writer(response)
writer.writerow(['First Name','Last Name','Gender','Age','Tel No','Status','Date Recorded','Appointment Date',])
appointments = PatientAppointment.objects.all()
for appointment in appointments:
writer.writerow([appointment.first_name,appointment.last_name,appointment.gender,appointment.age,appointment.phone,appointment.approve,appointment.approve,appointment.date_made,appointment.appointment_date])
return response
#Get single appointment
@login_required
def appointment_details(request,appointment_id):
try:
appointment =get_object_or_404(PatientAppointment, pk = appointment_id)
except ObjectDoesNotExist:
raise Http404()
return render(request,'appointment_details.html',{'appointment':appointment})
@login_required
def add_appointment(request):
if request.method == 'POST':
add_appointment_form = AppointmentForm(request.POST)
if add_appointment_form.is_valid():
appointment = add_appointment_form.save(commit=False)
appointment.save()
return redirect('appointments')
else:
add_appointment_form = AppointmentForm()
return render(request, 'add_appointment.html',{'add_appointment_form':add_appointment_form})
@login_required
def update_appointment(request, appointment_id):
appointment = PatientAppointment.objects.get(pk=appointment_id)
if request.method == 'POST':
update_appointment_form = AppointmentForm(request.POST,request.FILES, instance=appointment)
if update_appointment_form.is_valid():
update_appointment_form.save()
messages.success(request, f'Appointment updated!')
return redirect('appointments')
else:
update_appointment_form = AppointmentForm(instance=appointment)
return render(request, 'update_appointment.html', {"update_appointment_form":update_appointment_form})
@login_required
def delete_appointment(request,appointment_id):
appointment = PatientAppointment.objects.get(pk=appointment_id)
if appointment:
appointment.delete_patient_appointment()
return redirect('appointments')
#Prescription views
@login_required
def prescriptions(request):
prescriptions = Prescription.objects.all().order_by('-date')
return render(request,'prescriptions.html',{'prescriptions':prescriptions})
#Export table data as csv
@login_required
def export_prescriptions(request):
response = HttpResponse(content_type = 'text/csv')
response['Content-Disposition'] = 'attachment; filename = prescriptions'+ str(datetime.datetime.now())+'.csv'
writer = csv.writer(response)
writer.writerow(['First Name','Last Name','Dose','Drug','Prescriber','Date','Note'])
prescriptions = Prescription.objects.all()
for prescription in prescriptions:
writer.writerow([prescription.patient.first_name,prescription.patient.last_name,prescription.dose,prescription.drug,prescription.prescriber,prescription.date,prescription.note])
return response
#Get single prescription
@login_required
def prescription_details(request,prescription_id):
try:
prescription =get_object_or_404(Prescription, pk = prescription_id)
except ObjectDoesNotExist:
raise Http404()
return render(request,'prescription_details.html',{'prescription':prescription})
@login_required
def add_prescription(request):
if request.method == 'POST':
add_prescription_form = PrescriptionForm(request.POST)
if add_prescription_form.is_valid():
prescription = add_prescription_form.save(commit=False)
prescription.save()
return redirect('prescriptions')
else:
add_prescription_form = PrescriptionForm()
return render(request, 'add_prescription.html',{'add_prescription_form':add_prescription_form})
@login_required
def update_prescription(request, prescription_id):
prescription = Prescription.objects.get(pk=prescription_id)
if request.method == 'POST':
update_prescription_form = PrescriptionForm(request.POST,request.FILES, instance=prescription)
if update_prescription_form.is_valid():
update_prescription_form.save()
messages.success(request, f'Prescription updated!')
return redirect('prescriptions')
else:
update_prescription_form = PrescriptionForm(instance=prescription)
return render(request, 'update_prescription.html', {"update_prescription_form":update_prescription_form})
@login_required
def delete_prescription(request,prescription_id):
prescription = Prescription.objects.get(pk=prescription_id)
if prescription:
prescription.delete_prescription()
return redirect('prescriptions')
#Medicine views
@login_required
def drugs(request):
drugs = Medicine.objects.all()
return render(request,'drugs.html',{'drugs':drugs})
#Export table data as csv
@login_required
def export_drugs(request):
response = HttpResponse(content_type = 'text/csv')
response['Content-Disposition'] = 'attachment; filename = drugs'+ str(datetime.datetime.now())+'.csv'
writer = csv.writer(response)
writer.writerow(['Name','Description','Date Recorded'])
drugs = Medicine.objects.all()
for drug in drugs:
writer.writerow([drug.name,drug.description,drug.date])
return response
#Get single drug
@login_required
def drug_details(request,drug_id):
try:
drug =get_object_or_404(Medicine, pk = drug_id)
except ObjectDoesNotExist:
raise Http404()
return render(request,'drug_details.html',{'drug':drug})
@login_required
def add_drug(request):
if request.method == 'POST':
add_drug_form = DrugForm(request.POST)
if add_drug_form.is_valid():
drug = add_drug_form.save(commit=False)
drug.save()
return redirect('drugs')
else:
add_drug_form = DrugForm()
return render(request, 'add_drug.html',{'add_drug_form':add_drug_form})
@login_required
def update_drug(request, drug_id):
drug = Medicine.objects.get(pk=drug_id)
if request.method == 'POST':
update_drug_form = DrugForm(request.POST,request.FILES, instance=drug)
if update_drug_form.is_valid():
update_drug_form.save()
messages.success(request, f'Drug updated!')
return redirect('drugs')
else:
update_drug_form = DrugForm(instance=drug)
return render(request, 'update_drug.html', {"update_drug_form":update_drug_form})
@login_required
def delete_drug(request,drug_id):
drug = Medicine.objects.get(pk=drug_id)
if drug:
drug.delete_medicine()
return redirect('drugs')
#Feedback Views
@login_required
def feedback(request):
feedbacks = FeedBack.objects.all().order_by('-feedback_date')
return render(request,'feedback.html',{'feedbacks':feedbacks})
#Export table data as csv
@login_required
def export_feedbacks(request):
response = HttpResponse(content_type = 'text/csv')
response['Content-Disposition'] = 'attachment; filename = feedbacks'+ str(datetime.datetime.now())+'.csv'
writer = csv.writer(response)
writer.writerow(['First Name','Last Name','Feedback Message','Date'])
feedbacks = FeedBack.objects.all()
for feedback in feedbacks:
writer.writerow([feedback.patient.first_name,feedback.patient.last_name,feedback.feedback_message,feedback.feedback_date])
return response
#Get single feedback
@login_required
def feedback_details(request,feedback_id):
try:
feedback =get_object_or_404(FeedBack, pk = feedback_id)
except ObjectDoesNotExist:
raise Http404()
return render(request,'feedback_details.html',{'feedback':feedback})
@login_required
def add_feedback(request):
if request.method == 'POST':
add_feedback_form = FeedbackForm(request.POST)
if add_feedback_form.is_valid():
feedback = add_feedback_form.save(commit=False)
feedback.save()
return redirect('feedback')
else:
add_feedback_form = FeedbackForm()
return render(request, 'add_feedback.html',{'add_feedback_form':add_feedback_form})
@login_required
def update_feedback(request, feedback_id):
feedback = FeedBack.objects.get(pk=feedback_id)
if request.method == 'POST':
update_feedback_form = FeedbackForm(request.POST,request.FILES, instance=feedback)
if update_feedback_form.is_valid():
update_feedback_form.save()
messages.success(request, f'Feedback updated!')
return redirect('feedback')
else:
update_feedback_form = FeedbackForm(instance=feedback)
return render(request, 'update_feedback.html', {"update_feedback_form":update_feedback_form})
@login_required
def delete_feedback(request,feedback_id):
feedback = FeedBack.objects.get(pk=feedback_id)
if feedback:
feedback.delete_feedback()
return redirect('feedback')
#Health History views
@login_required
def history(request):
histories = PatientHealthHistory.objects.all().order_by('-date_recorded')
return render(request,'history.html',{'histories':histories})
#Export table data as csv
@login_required
def export_histories(request):
response = HttpResponse(content_type = 'text/csv')
response['Content-Disposition'] = 'attachment; filename = histories'+ str(datetime.datetime.now())+'.csv'
writer = csv.writer(response)
writer.writerow(['First Name','Last Name','Date','Description'])
histories = PatientHealthHistory.objects.all()
for historie in histories:
writer.writerow([historie.patient.first_name,historie.patient.last_name,historie.date_recorded,historie.health_record])
return response
#Get single history
@login_required
def history_details(request,history_id):
try:
history =get_object_or_404(PatientHealthHistory, pk = history_id)
except ObjectDoesNotExist:
raise Http404()
return render(request,'history_details.html',{'history':history})
@login_required
def add_health_history(request):
if request.method == 'POST':
add_history_form = HealthHistoryForm(request.POST)
if add_history_form.is_valid():
history = add_history_form.save(commit=False)
history.save()
return redirect('history')
else:
add_history_form = HealthHistoryForm()
return render(request, 'add_health_history.html',{'add_history_form':add_history_form})
@login_required
def update_history(request, history_id):
history = PatientHealthHistory.objects.get(pk=history_id)
if request.method == 'POST':
update_history_form = HealthHistoryForm(request.POST,request.FILES, instance=history)
if update_history_form.is_valid():
update_history_form.save()
messages.success(request, f'Health history updated!')
return redirect('history')
else:
update_history_form = HealthHistoryForm(instance=history)
return render(request, 'update_history.html', {"update_history_form":update_history_form})
@login_required
def delete_history(request,history_id):
history = PatientHealthHistory.objects.get(pk=history_id)
if history:
history.delete_patient_health_history()
return redirect('history')
#Patient Visits views
@login_required
def visits(request):
visits = Visit.objects.all().order_by('-date_visited')
return render(request,'visits.html',{'visits':visits})
#Export table data as csv
@login_required
def export_visits(request):
response = HttpResponse(content_type = 'text/csv')
response['Content-Disposition'] = 'attachment; filename = visits'+ str(datetime.datetime.now())+'.csv'
writer = csv.writer(response)
writer.writerow(['First Name','Last Name','Date','Note'])
visits = Visit.objects.all()
for visit in visits:
writer.writerow([visit.patient.first_name,visit.patient.last_name,visit.date_visited,visit.note])
return response
#Get single visit
@login_required
def visit_details(request,visit_id):
try:
visit =get_object_or_404(Visit, pk = visit_id)
except ObjectDoesNotExist:
raise Http404()
return render(request,'visit_details.html',{'visit':visit})
@login_required
def add_visit(request):
if request.method == 'POST':
add_visit_form = VisitForm(request.POST)
if add_visit_form.is_valid():
visit = add_visit_form.save(commit=False)
visit.save()
return redirect('visits')
else:
add_visit_form = VisitForm()
return render(request, 'add_visit.html',{'add_visit_form':add_visit_form})
@login_required
def update_visit(request, visit_id):
visit = Visit.objects.get(pk=visit_id)
if request.method == 'POST':
update_visit_form = VisitForm(request.POST,request.FILES, instance=visit)
if update_visit_form.is_valid():
update_visit_form.save()
messages.success(request, f'Visit updated!')
return redirect('visits')
else:
update_visit_form = VisitForm(instance=visit)
return render(request, 'update_visit.html', {"update_visit_form":update_visit_form})
@login_required
def delete_visit(request,visit_id):
visit = Visit.objects.get(pk=visit_id)
if visit:
visit.delete_visit()
return redirect('visits')
|
0376d0d6af2b5c31da7a0713909a12401070b3b9
|
[
"Markdown",
"Python"
] | 16 |
Python
|
ngetichnicholas/Meds
|
2dd2b649ea216f76b2d316dac0591a01d2c836bf
|
667cf73cdb8f51e3608e79c421466535f9d99f35
|
refs/heads/master
|
<file_sep><?php
namespace Bokbasen\Auth;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Log\LoggerInterface;
use Http\Client\HttpClient;
use Bokbasen\Auth\Exceptions\BokbasenAuthException;
/**
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Authentication class to use against Bokbasen's web services
*
* @link https://bokbasen.jira.com/wiki/display/api/Authentication+Service API Documentation
* @license https://opensource.org/licenses/MIT
*/
class Login
{
use \Bokbasen\Http\HttpMethodsTrait;
/**
*
* @var string
*/
protected $tgt;
/**
*
* @var \Psr\Cache\CacheItemPoolInterface
*/
protected $tgtCache;
/**
* Number of minutes a TGT should be cached
*
* @var int
*/
protected $tgtExpireMinutes = self::DEFAULT_TGT_EXPIRE_TIME_MINUTES;
/**
*
* @var string
*/
protected $username;
/**
*
* @var string
*/
protected $password;
/**
*
* @var bool
*/
protected $reAuthAttempted;
/**
*
* @var \Psr\Log\LoggerInterface
*/
protected $logger;
const URL_PROD = 'https://login.boknett.no/v1/tickets';
const URL_TEST = 'https://login.boknett.webbe.no/v1/tickets';
const HEADER_TGT = 'Boknett-TGT';
const BEARER_NAME = 'Boknett';
const HTTP_HEADER_DATE_FORMAT = 'D, d M Y H:i:s e';
const DEFAULT_TGT_EXPIRE_TIME_MINUTES = 110;
const CACHE_ITEM_KEY = 'bokbasen.tgt';
/**
*
* @param string $username
* @param string $password
* @param string $url
* @param CacheItemPoolInterface $tgtCache
* @param LoggerInterface $logger
* @param HttpClient $httpClient
*/
public function __construct($username, $password, $url = self::URL_PROD, CacheItemPoolInterface $tgtCache = null, LoggerInterface $logger = null, HttpClient $httpClient = null)
{
$this->username = $username;
$this->password = <PASSWORD>;
$this->url = $url;
$this->tgtCache = $tgtCache;
$this->logger = $logger;
$this->setHttpClient($httpClient);
$this->reAuthAttempted = false;
}
/**
* Check if reauthetication is attempted, used to ensure that only one attempt is made for reauthetication
*
* @return boolean
*/
public function isReAuthAttempted()
{
if (! is_null($this->logger)) {
$this->logger->info('isReAuthAttempted returns ' . $this->reAuthAttempted);
}
return $this->reAuthAttempted;
}
/**
* Rerun authentication (will force new TGT, regardless of cache)
*/
public function reAuthenticate()
{
$this->reAuthAttempted = true;
$this->authenticate();
}
/**
* Get TGT (will attempt to create TGT if it does not exists)
*
* @return string
*/
public function getTgt()
{
if (is_null($this->tgt)) {
$this->setTGT();
}
return $this->tgt;
}
/**
*
* @param int $tgtExpireMinutes
*/
public function setTgtExpireMinutes($tgtExpireMinutes)
{
$this->tgtExpireMinutes = (int) $tgtExpireMinutes;
}
/**
* Invalidates current TGT for future use
*/
public function logout()
{
if (! is_null($this->tgt)) {
$this->getMessageFactory()->createRequest('DELETE', $this->url . '/' . $this->tgt);
if (! is_null($this->logger)) {
$this->logger->info('TGT deleted');
}
unset($this->tgt);
}
}
/**
* Get authorzation headers as array
*
* @return array
*/
public function getAuthHeadersAsArray()
{
if (is_null($this->tgt)) {
$this->setTGT();
}
if (! is_null($this->logger)) {
$this->logger->debug('Authorization header returned: ' . self::BEARER_NAME . ' ' . $this->tgt);
}
return [
'Authorization' => self::BEARER_NAME . ' ' . $this->tgt,
'Date' => gmdate(self::HTTP_HEADER_DATE_FORMAT)
];
}
/**
* Populate $this->tgt either frmo cache or execute call to auth server
*/
protected function setTGT()
{
if (! $this->isCachedTGT()) {
$this->authenticate($this->username, $this->password);
}
}
/**
* Check if TGT is cached and if cache is valid, will set $this->tgt to cached value if true
*
* @return bool
*/
protected function isCachedTGT()
{
if (is_null($this->tgtCache)) {
if (! is_null($this->logger)) {
$this->logger->info('No cache interface available, create new ticket.');
}
return false;
} else {
$cachedItem = $this->tgtCache->getItem(self::CACHE_ITEM_KEY);
if (! $cachedItem->isHit()) {
if (! is_null($this->logger)) {
$this->logger->info('Cache available, but not hit.');
}
return false;
} else {
$this->tgt = $cachedItem->get();
if (! is_null($this->logger)) {
$this->logger->info('Cache hit, returning: ' . $this->tgt);
}
return ! empty($this->tgt);
}
}
}
/**
* Authorize user and store TGT
*
* @throws BokbasenAuthException
* @return void
*/
public function authenticate()
{
$request = $this->getMessageFactory()->createRequest('POST', $this->url, [], http_build_query([
'username' => $this->username,
'password' => $<PASSWORD>
]));
$response = $this->httpClient->sendRequest($request);
if ($response->getStatusCode() != 201) {
$message = 'Ticket not created. HTTP: ' . $response->getStatusCode() . ' Body:' . $response->getBody();
if (! is_null($this->logger)) {
$this->logger->error($message);
}
throw new BokbasenAuthException($message);
}
$this->tgt = $response->getHeaderLine(self::HEADER_TGT);
if (! is_null($this->logger)) {
$this->logger->info('New TGT created: ' . $this->tgt);
}
if (! is_null($this->tgtCache)) {
$tgtCacheItem = $this->tgtCache->getItem(self::CACHE_ITEM_KEY);
$tgtCacheItem->set($this->tgt);
$tgtCacheItem->expiresAfter($this->tgtExpireMinutes * 60);
if ($this->tgtCache->save($tgtCacheItem) === false) {
$message = 'Saving of cache failed.';
if (! is_null($this->logger)) {
$this->logger->error($message);
}
throw new BokbasenAuthException($message);
}
if (! is_null($this->logger)) {
$this->logger->info('New TGT added to cache');
}
}
}
/**
* If no TGT cache is defined, then destruct will perform a HTTP DELETE call to clear the TGT
*/
public function __destruct()
{
if (! empty($this->tgt) && empty($this->tgtCache)) {
$this->logout();
unset($this->tgt);
}
}
}<file_sep><?php
namespace Bokbasen\Auth\Tests\Integration;
use Bokbasen\Auth\Login;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
class LoginTest extends \PHPUnit_Framework_TestCase
{
/**
*
* @var array
*/
protected $config;
/**
*
* @var \Bokbasen\Auth\Login
*/
protected $auth;
public function __construct($name = null, array $data = [], $dataName = '')
{
parent::__construct($name, $data, $dataName);
$this->config = parse_ini_file(__DIR__ . '/config.ini');
}
public function testHttpClientsLogin()
{
// Using default autodetected client
$this->auth = new Login($this->config['username'], $this->config['password'], null, $this->config['url']);
$this->assertNotEmpty($this->auth->getTgt());
$adapter = new \Http\Adapter\Guzzle6\Client();
$this->auth = new Login($this->config['username'], $this->config['password'], null, $this->config['url'], $adapter);
$this->assertNotEmpty($this->auth->getTgt());
}
public function testLogin()
{
$this->auth = new Login($this->config['username'], $this->config['password'], null, $this->config['url']);
$this->assertNotEmpty($this->auth->getTgt());
}
public function testFailedLogin()
{
$this->expectException(\Bokbasen\Auth\Exceptions\BokbasenAuthException::class);
$auth = new Login('dsds', '<PASSWORD>', null, $this->config['url']);
$auth->authenticate();
}
public function testCache()
{
$cache = new FilesystemAdapter(null, 0, $this->config['fileCacheDir']);
$auth = new Login($this->config['username'], $this->config['password'], $cache, $this->config['url']);
$this->assertNotEmpty($auth->getTgt());
// rerun auth with cache to see that we get the same TGT
$auth2 = new Login($this->config['username'], $this->config['password'], $cache, $this->config['url']);
$this->assertEquals($auth->getTgt(), $auth2->getTgt());
}
}<file_sep><?php
namespace Bokbasen\Auth\Tests\Unit;
use Bokbasen\Auth\Login;
use Http\Mock\Client;
class LoginTest extends \PHPUnit_Framework_TestCase
{
public function testLogin()
{
$client = new Client();
$response = $this->getMockBuilder('Psr\Http\Message\ResponseInterface')->getMock();
$tgt = 'TGT-152-leeshOABMDJE41s55z9WBLq7d7kk2ONUQozYHOF2FimxI5a9D9Z-login.boknett.no';
$response->method('getHeaderLine')->willReturn($tgt);
$response->method('getStatusCode')->willReturn('201');
$client->addResponse($response);
$auth = $this->createLoginObject($client);
$this->assertEquals($auth->getTgt(), $tgt);
}
protected function createLoginObject($client){
return new Login('test', 'test', null, null, null,$client);
}
public function testFailedLogin()
{
$this->expectException(\Bokbasen\Auth\Exceptions\BokbasenAuthException::class);
$client = new Client();
$response = $this->getMockBuilder('Psr\Http\Message\ResponseInterface')->getMock();
$tgt = null;
$response->method('getHeaderLine')->willReturn($tgt);
$response->method('getStatusCode')->willReturn('400');
$client->addResponse($response);
$auth = $this->createLoginObject($client);
$auth->authenticate();
}
}<file_sep><?php
namespace Bokbasen\Http\Exceptions;
class BokbasenHttpException extends \Exception
{
}<file_sep># PHP SDK for Bokbasen authentication service
This PHP SDK enables easy usage of Bokbasen's authentication service that is required for accessing any of Bokbasen's API such as digital distribution platform, metadata or orders. Bokbasen's APIs are not public and only available on commercial terms, you must have a username/password from Bokbasen in order to use this package.
The basic package enable creation of a TGT that can be used for further login to API services. The package also provides an interface for caching TGTs so one can get a more efficient flow, only renewing TGT when it is about to expire. For production usage this is highly recommended. The API documentation is available on [this page](https://bokbasen.jira.com/wiki/display/api/Authentication+Service).
## HTTP client
The SDK has a dependency on the virtual package php-http/client-implementation which requires to you install an adapter, but we do not care which one. That is an implementation detail in your application. We also need a PSR-7 implementation and a message factory.
This is based on [PHP-HTTP](http://docs.php-http.org/en/latest/index.html) that provides an implementation-independent plugin system to build pipelines regardless of the HTTP client implementation used. So basically you can plugin whichever HTTP implementation you would like to use.
### I do not care, I just want it to work!
By adding a compatible HTTP adapter to your project the SDK will automatically detect the package and use this adapter. As long as you do not need any specific HTTP settings injected (such as proxy settings etc.) this will work just fine.
```$ composer require php-http/guzzle6-adapter```
## Auto detected client and TGT cache
In production environments you should always use teh caching feature. Not doing this will potentially give you a significant performance impact on the response time from Bokbasen's APIs. You can cache the TGT using any [PSR-6](http://www.php-fig.org/psr/psr-6/) compatible package. Example below is using Symfony's file caching.
```php
<?php
use Bokbasen\Auth\Login;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
try{
$cache = new FilesystemAdapter();
$auth = new Login('my_username', '<PASSWORD>', Login::URL_PROD, $cache);
//If the TGT is cached, the SDK will only call the Bokbasen login server when the token is set to expire
} catch(\Exception $e){
//error handling
}
?>
```
## Use injected HTTP client
```php
<?php
use Bokbasen\Auth\Login;
try{
//just an example, any client implementing \Http\Client\HttpClient\HttpClient will work
$client = new \Http\Adapter\Guzzle6\Client();
$auth = new Login('my_username', '<PASSWORD>', Login::URL_PROD, null, null, $client);
} catch(\Exception $e){
//error handling
}
?>
```
<file_sep>;config template, rename this to config.ini before executing tests
url = https://login.boknett.webbe.no/v1/tickets
username =
password =
fileCacheDir =<file_sep><?php
namespace Bokbasen\Auth\Exceptions;
class BokbasenAuthException extends \Exception{}<file_sep><?php
namespace Bokbasen\Http;
use Http\Discovery\HttpClientDiscovery;
use Http\Discovery\MessageFactoryDiscovery;
use Http\Discovery\StreamFactoryDiscovery;
use Http\Client\HttpClient;
use Psr\Http\Message\ResponseInterface;
use Bokbasen\Auth\Login;
/**
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Collection of http methods shared across Bokbasen PHP libraries ensuring support for HTTP discovery and HTTP client injection
*
* @license https://opensource.org/licenses/MIT
*/
trait HttpMethodsTrait{
/**
*
* @var \Http\Client\HttpClient
*/
protected $httpClient;
/**
*
* @var \Http\Discovery\MessageFactory
*/
protected $messageFactory;
/**
*
* @var \Http\Discovery\MessageFactory
*/
protected $streamFactory;
/**
*
* @var \Bokbasen\Auth\Login
*/
protected $auth;
/**
*
* @var string
*/
protected $url;
/**
* Set HTTP client, if none is given autodetection is attempted
*
* @param HttpClient $httpClient
*/
public function setHttpClient(HttpClient $httpClient = null)
{
if (is_null($httpClient)) {
$this->httpClient = HttpClientDiscovery::find();
} else {
$this->httpClient = $httpClient;
}
}
/**
* Create a message factory
*
* @return \Http\Discovery\MessageFactory
*/
protected function getMessageFactory()
{
if (is_null($this->messageFactory)) {
$this->messageFactory = MessageFactoryDiscovery::find();
}
return $this->messageFactory;
}
/**
* Create a stream factory
*
* @return \Http\Discovery\StreamFactory
*/
protected function getStreamFactory()
{
if (is_null($this->streamFactory)) {
$this->streamFactory = StreamFactoryDiscovery::find();
}
return $this->streamFactory;
}
/**
*
* @param Login $auth
* @param array $customHeaders
*/
protected function makeHeadersArray(Login $auth, array $customHeaders = [])
{
return array_merge($auth->getAuthHeadersAsArray(), $customHeaders);
}
/**
* Check if the auth client should attempt reauthetication based on response.
* Will only run reauth once.
*
* @param ResponseInterface $response
* @return boolean
*/
protected function needReAuthentication(ResponseInterface $response)
{
if ($response->getStatusCode() == 401 && ! $this->auth->isReAuthAttempted()) {
$this->auth->reAuthenticate();
return true;
} else {
return false;
}
}
}
|
09a8f9c7d1691adba5f087bf4dab29f768e26d35
|
[
"Markdown",
"PHP",
"INI"
] | 8 |
PHP
|
Bokbasen/php-sdk-auth
|
bade138e07844e0b1479665bd3537b4fd8289d85
|
d9c940b4850e15e15861bca36988fd4b4728d538
|
refs/heads/master
|
<file_sep># A simple test of importing the lightcurve.
# ...that then became the main class of EVERYTHING
import tkFileDialog
import time as tardis
import numpy as np
import matplotlib.pyplot as plt
import csv
from matplotlib.widgets import Button
from matplotlib.widgets import Cursor
from matplotlib.widgets import RectangleSelector
from pylab import *
from Tkinter import Tk
from tkFileDialog import askopenfilename
time = []
flux = []
frequency = []
selectedDataRange = []
resumeFlag = False
beenTransf = False
Tk().withdraw() # open file open dialog
filename = askopenfilename()
f = open(filename)
for row in csv.reader(f):
#generated lightcurves are stored differently than saved lightcurves,
#so here we check if the file is a saved file or a new file
if row[0] == 'F' or row[0] == 'R' or row[0] == 'P':
resumeFlag = True
if row[0] == 'F':
global beenTransf
beenTransf = True
if row[0] == 'P':
global beenTransf
beenTransf = True
global beenPhased
beenPhased = True
continue
if resumeFlag:
time.append(row[0])
flux.append(row[1])
if not resumeFlag:
time.append(row[0])
flux.append(row[5])
#for use later on
beenSelected = False
currentX = time
currentY = flux
#to find the closest index from what we select since it's *too* precise
def findClosest(num, list):
new_list = [float(i) for i in list]
idx = (np.abs(new_list - num)).argmin() #I have no idea how this works, I just got it from stackoverflow
return idx
#for the rectangle selector
def onselect(eclick, erelease):
'eclick and erelease are matplotlib events at press and release'
#print ' startposition : (%f, %f)' % (eclick.xdata, eclick.ydata)
#print ' endposition : (%f, %f)' % (erelease.xdata, erelease.ydata)
global selectedDataRange
if erelease.xdata < eclick.xdata:
selectedDataRange = [erelease.xdata, eclick.xdata]
elif erelease.xdata > eclick.xdata:
selectedDataRange = [eclick.xdata, erelease.xdata]
global beenSelected #to access global variables
beenSelected = True
#I don't know why there's redundancy but it doesn't work if I take this out
def toggle_selector(event):
if toggle_selector.RS.active:
print ' RectangleSelector deactivated.'
toggle_selector.RS.set_active(False)
if not toggle_selector.RS.active:
print ' RectangleSelector activated.'
toggle_selector.RS.set_active(True)
#still for the selector
class Index:
def toggle(self, event):
if toggle_selector.RS.active:
print ' RectangleSelector deactivated.'
toggle_selector.RS.set_active(False)
elif (not toggle_selector.RS.active):
print ' RectangleSelector activated.'
toggle_selector.RS.set_active(True)
def select(self, event):
#The code that's run when you hit the "Select Data" button
if not beenSelected:
return
global beenTransf
if beenTransf:
phaseData()
else:
fourierSection()
beenTransf = True
def saveFile(self, event):
outputFile = tkFileDialog.asksaveasfile(mode='w', defaultextension=".csv")
writer = csv.writer(outputFile, delimiter=',')
#check if we've done a Fourier transform and flag the file properly
if beenTransf and not beenPhased:
writer.writerow("F")
else:
writer.writerow("R")
writer.writerows(zip(currentX,currentY))
outputFile.close()
#the section that processes doing the Fourier Transform and plotting it to screen
def fourierSection():
global time, flux #this is how we modify global variables
x1 = findClosest(selectedDataRange[0], time) #find variables in flux array
x2 = findClosest(selectedDataRange[1], time)
newArr = flux[x1:x2] #slicing the array
newArr = [float(i) for i in newArr]
mean = np.mean(newArr)
newArr2 = []
newArr2[:] = [x - mean for x in newArr]
newTime = time[x1:x2]
#everything is already a float but we need to cast it anyway
newTime2 = [float(i) for i in newTime]
#creating a variable frequency array
f = createArrOfSize(0.0225, 10, size(newTime2))
newTime2 = np.asarray(newTime2)
newArr2 = np.asarray(newArr2)
f = np.asarray(f)
newFlux = dft(newTime2, newArr2, f)
#and we start re-plotting
l.set_ydata(np.abs(newFlux))
ymax = np.amax(np.abs(newFlux))
l.set_xdata(f)
ax.set_ylim([0,ymax+1000])
ax.set_xlim([0,10])
ax.set_title("Transformed Data", fontsize=20)
ax.set_xlabel('Frequency', fontsize=16)
ax.set_ylabel('Flux', fontsize=16)
selectData.label.set_text("Phase Data")
fig.canvas.draw()
#update the global x and y for use throughout the rest of the program
global currentX, currentY, time, frequency
currentX = newTime2
currentY = np.abs(newFlux)
time = newTime2
flux = newArr
frequency = f
#create a frequency array of the size specified
def createArrOfSize(start, stop, size):
increment = float(stop-start)/float(size)
arr = arange(start, stop, increment)
return arr
#Discrete Fourier Transform, taken directly from Dr. Buzasi's MATLAB function
def dft(t, x, f):
N = t.size
i = 1j
W = np.exp((-2 * math.pi * i)*np.dot(f.reshape(N,1),t.reshape(1,N)))
X = np.dot(W,x.reshape(N,1))
out = X.reshape(f.shape).T
return out
def phaseData():
global currentY, time, frequency, flux
peak = np.argmax(currentY)
print peak
global f_max
f_max = frequency[peak]
phasedTime = time
phasedTime[:] = [x*f_max for x in time]
#modulus operator is % in Python as well as other languages
#normal programmers actually use (meaning languages with C-like syntax)
phasedTime[:] = [x%1 for x in time]
yx = zip(phasedTime, flux)
yx.sort()
flux = [x for y, x in yx]
phasedTime.sort()
l.set_ydata(flux)
ymax = np.amax(flux)
ymin = np.amin(flux)
xmax = np.amax(phasedTime)
l.set_xdata(phasedTime)
ax.set_ylim([ymin-10,ymax+10])
ax.set_xlim([0,xmax])
ax.set_xlabel('Time', fontsize=16)
ax.set_title("Phased Data", fontsize=20)
global beenPhased
beenPhased = True
fig.canvas.draw()
# the rectangle drawer
class Annotate(object):
def __init__(self):
self.ax = plt.gca()
self.rect = Rectangle((0, 0), 1, 1)
self.x0 = None
self.y0 = None
self.x1 = None
self.y1 = None
self.ax.add_patch(self.rect)
self.ax.figure.canvas.mpl_connect('button_press_event', self.on_press)
self.ax.figure.canvas.mpl_connect('button_release_event', self.on_release)
def on_press(self, event):
if not toggle_selector.RS.active:
return
self.x0 = event.xdata
self.y0 = event.ydata
def on_release(self, event):
if not toggle_selector.RS.active:
return
self.x1 = event.xdata
self.y1 = event.ydata
self.rect.set_width(self.x1 - self.x0)
self.rect.set_height(self.y1 - self.y0)
self.rect.set_xy((self.x0, self.y0))
self.rect.set_facecolor('blue')
self.rect.set_alpha(0.5)
self.ax.figure.canvas.draw()
#UI setup
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.2)
l, = plt.plot(time, flux, lw=2)
plt.grid(True)
plt.xlabel('Time', fontsize=16)
plt.ylabel('Flux', fontsize=16)
a = Annotate() #the rectangle
cursor = Cursor(ax, useblit=True, color='black', linewidth=2) #the crosshair
callback = Index() #button handler
togglePlacement = plt.axes([0.65, 0.05, 0.3, 0.055])
rectToggle = Button(togglePlacement, 'Rectangle Select Toggle')
rectToggle.on_clicked(callback.toggle)
selectDataPlacement = plt.axes([0.45, 0.05, 0.15, 0.055])
selectData = Button(selectDataPlacement, 'Select Data')
selectData.on_clicked(callback.select)
savePlacement = plt.axes([0.1, 0.05, 0.1, 0.055])
saveData = Button(savePlacement, 'Save')
saveData.on_clicked(callback.saveFile)
toggle_selector.RS = RectangleSelector(ax, onselect, drawtype='line')
toggle_selector.RS.set_active(False)
plt.grid(True)
plt.show()
|
b384e44fee640fd71169bf88766ca028ad842fc6
|
[
"Python"
] | 1 |
Python
|
Chessler/TransitViewer
|
c74d2557bf2316db49562da94894b3ec123b7e42
|
eef4986043f5dc23fcda2cdc3ebaa4c2956a8ea5
|
refs/heads/master
|
<file_sep>#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node*link;
};
struct node*front;
struct node*rear;
struct node*temp;
void enqueue (int data)
{
struct node*newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=data;
newnode->link=NULL;
if(front==NULL || rear==NULL)
{
front=newnode;
rear=newnode;
}
else
{
rear->link=newnode;
rear=newnode;
}
}
void dequeue()
{
if(front==NULL || rear==NULL)
{
printf("empty queue");
}
else
{
temp=front;
front=temp->link;
free(temp);
}
}
void display()
{
temp=front;
if(temp==NULL || rear==NULL){
printf("empty queue");
}
else
while(temp!=NULL)
{
printf("%d \t ",temp->data);
temp=temp->link;
}
}
int main()
{
printf("\n \t\t MENU \n\t1.PUSH\n\t2.POP\n\t3.DISPLAY\n\t4.EXIT");
int ch,data;
while(1)
{
printf("\nEnter your choice:");
scanf("%d",&ch);
if(ch==4)
break;
switch(ch)
{
case 1:printf("\nEnter the element to be pushed:");
scanf("%d",&data);
enqueue (data);break;
case 2:dequeue();break;
case 3:display();break;
default:printf("\n Invalid Choice");
}
}
}
<file_sep>#include<stdio.h>
#define MAX 100
void heapify(int a[],int i,int n)
{
int largest,lc,rc,temp;
largest=i;
lc=2*i+1;
rc=2*i+2;
if(a[lc]>a[largest]&&lc<n)
largest=lc;
if(a[rc]>a[largest]&&rc<n)
largest=rc;
if(i!=largest)
{
temp=a[i];
a[i]=a[largest];
a[largest]=temp;
heapify(a,largest,n);
}
}
void heapsort(int a[],int n)
{
int i,temp;
for(i=n/2-1;i>=0;i--)
heapify(a,i,n);
for(i=n-1;i>=0;i--)
{
temp=a[0];
a[0]=a[i];
a[i]=temp;
heapify(a,0,i);
}
}
int main(void)
{
int n,a[MAX];
printf("\nEnter the size of the array: ");
scanf("%d",&n);
printf("\nEnter the elements: ");
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
heapsort(a,n);
printf("\nSorted array: ");
for(int i=0;i<n;i++)
printf("\t%d",a[i]);
printf("\n");
}
<file_sep>#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node*link;
};
struct node*top;
struct node*temp;
void push (int data)
{
struct node*newnode=(struct node*)malloc(sizeof(struct node));
if(top==NULL)
{
newnode->data=data;
newnode->link=NULL;
top=newnode;
}
else
{
newnode->data=data;
newnode->link=top;
top=newnode;
}
}
void pop()
{
if(top==NULL)
{
printf("stack is empty");
}
else
{
temp=top;
top=top->link;
free(temp);
}
}
void display()
{
temp=top;
if(temp==NULL)
printf("empty stack");
while(temp!=NULL)
{
printf("%d \t",temp->data);
temp=temp->link;
}
}
int main()
{
printf("\n \t\t MENU \n\t1.PUSH\n\t2.POP\n\t3.DISPLAY\n\t4.EXIT");
int ch,data;
while(1)
{
printf("\nEnter your choice:");
scanf("%d",&ch);
if(ch==4)
break;
switch(ch)
{
case 1:printf("\nEnter the element to be pushed:");
scanf("%d",&data);
push(data);break;
case 2:pop();break;
case 3:display();break;
default:printf("\n Invalid Choice");
}
}
}
<file_sep>#include<stdio.h>
void insertsort(int arr[50],int n)
{
int i,element,pos;
for(i=1;i<n;i++)
{
element=arr[i];
pos=i;
while(pos>0 & arr[pos-1]>element)
{
arr[pos]=arr[pos-1];
pos=pos-1;
}
arr[pos]=element;
}
printf("the sorted array is");
for(i=0;i<n;i++)
{
printf("%d",arr[i]);
}
}
int main()
{
int arr[50],n,i;
printf("enter the limit");
scanf("%d",&n);
printf("enter the array");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
insertsort(arr,n);
return 0;
}
<file_sep>#include<stdio.h>
#define max 20
int a[max];
void merge(int lb,int mid,int ub)
{
int temp[max];
int i,j,k;
i=lb;
j=mid+1;
k=0;
while(i<=mid && j<=ub)
{
if(a[i]<a[j])
{
temp[k]=a[i];
i++;
k++;
}
else
{
temp[k]=a[j];
j++;
k++;
}
}
while(i<=mid)
{
temp[k]=a[i];
i++;
k++;
}
while(j<=ub)
{
temp[k]=a[j];
j++;
k++;
}
for(i=lb,k=0;i<=ub;i++,k++)
{
a[i]=temp[k];
}
}
void mergesort(int lb,int ub)
{
int mid;
if(lb<ub)
{
mid=(lb+ub)/2;
mergesort(lb,mid);
mergesort(mid+1,ub);
merge(lb,mid,ub);
}
}
int main(void)
{
int n;
printf("\nEnter the size of the array:");
scanf("%d",&n);
printf("\nEnter the elements:");
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(0,n-1);
printf("\nSorted array:\n");
for(int i=0;i<n;i++)
printf("\t%d",a[i]);
printf("\n");
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node * left,*right;
};
struct node* root=NULL,*parent,*s;
int i;
void insert()
{
int x;
struct node *ptr;
struct node *parent;
printf("Enter the data :");
scanf("%d",&x);
struct node* new=(struct node *)malloc(sizeof(struct node));
new->data=x;
new->left =NULL;
new->right=NULL;
if(root ==NULL)
{
root =new;
}
else
{
struct node* ptr=root;
int flag=0;
while((ptr!=NULL)&&(flag==0))
{
if(x<ptr->data)
{
parent =ptr;
ptr=ptr->left;
}
else if(x>ptr->data)
{
parent =ptr;
ptr=ptr->right;
}
else
flag=1;
}
if(flag==0)
{
if(x>parent->data)
parent->right=new;
else
parent->left=new;
}
else
printf("The value exist");
}
}
void delete(int x)
{
//int x,k;
//printf("Enter the data to be deleted : ");
//scanf("%d",&x);
struct node *ptr;
if(root==NULL)
printf("Empty Treee ");
else
{
ptr=root;
int flag=0;
while((ptr!=NULL)&&(flag==0))
{
if(x>ptr->data)
{
parent=ptr;
ptr=ptr->right;
}
else if(x<ptr->data)
{
parent=ptr;
ptr=ptr->left;
}
else
{
flag=1;
}
}
if(flag==0)
printf("Value Not found");
else if((ptr->left==NULL)&&(ptr->right==NULL))
{
printf("case 1");
if(parent->left==ptr)
parent->left=NULL;
else
parent->right=NULL;
free(ptr);
}
else if((ptr->left!=NULL)&&(ptr->right!=NULL))
{
s=ptr->right;
printf("case 3");
while(s->left!=NULL)
{
s=s->left;
}
i=s->data;
delete(s->data);
ptr->data=i;
//free(ptr);
}
else
{
printf("case 2");
if(parent->left==ptr)
{
if(ptr->left==NULL)
parent->left=ptr->right;
else
parent->left=ptr->left;
}
else if(parent->right==ptr)
{
if(ptr->left==NULL)
parent->right=ptr->right;
else
parent->right=ptr->left;
}
free(ptr);
}
}
}
void preorder(struct node*p)
{
if(p!=NULL)
{
printf("%d ",p->data);
preorder(p->left);
preorder(p->right);
}
}
void inorder(struct node*p)
{
if(p!=NULL)
{
inorder(p->left);
printf("%d ",p->data);
inorder(p->right);
}
}
void postorder(struct node*p)
{
if(p!=NULL)
{
postorder(p->left);
postorder(p->right);
printf("%d ",p->data);
}
}
void search()
{
int x;
struct node *ptr;
ptr=root;
int flag=0;
printf("Enter the data :");
scanf("%d",&x);
if(ptr==NULL)
printf("Empty Tree ");
else
{
while((ptr!=NULL)&&(flag==0))
{
if(x<ptr->data)
{
ptr=ptr->left;
}
else if(x>ptr->data)
{
ptr=ptr->right;
}
else
flag=1;
}
if(flag==1)
printf("Element Found\n");
else
printf("Element Not Found\n");
}
}
void main()
{
int c,x;
while(1){
printf("\n1. Insert \n2.Delete \n3. Preorder traversal \n4. Inorder traversal \n5. Postorder traversal \n6.Search \n7.Exit \nEnter the choice: ");
scanf("%d",&c);
switch(c)
{
case 1 : insert();
break;
case 2 :
printf("Enter the data to be deleted : ");
scanf("%d",&x);
delete(x);
break;
case 3 : preorder(root);
break;
case 4: inorder(root);
break;
case 5 : postorder(root);
break;
case 6: search();
break;
case 7: exit(0);
default : printf("Invalid choice \n");
}
}
}
<file_sep>#include<stdio.h>
#define max 4
int q[max];
int front=-1;
int rear=-1;
void enqueue(int x)
{
if(front==(rear+1)%max)
{
printf("\nQueue full");
}
else
{
if(front==-1)
front=rear=0;
else
rear=(rear+1)%max;
q[rear]=x;
}
}
void dequeue()
{
if(front==-1)
{
printf("\nQueue empty");return;
}
else if(front==rear)
{
printf("\nElement deleted is: %d",q[front]);
front=-1;
rear=-1;
}
else
{
printf("\nElement deleted is: %d",q[front]);
front=(front+1)%max;
}
}
void display()
{
if(front==-1)
{
printf("\nQueue empty");
}
else if(front<=rear)
{
for(int i=front;i<=rear;i++)
{
printf("\t%d",q[i]);
}
}
else
{
for(int i=front;i<=max-1;i++)
{
printf("\t%d",q[i]);
}
for(int i=0;i<=rear;i++)
{
printf("\t%d",q[i]);
}
}
}
int main(void)
{
int x,ch;
printf("\n\n\tMENU\n1.ENQUEUE\n2.DEQUEUE\n3.DISPLAY\n4.EXIT");
while(1)
{
printf("\nEnter your choice:");
scanf("%d",&ch);
if(ch==4)
break;
switch(ch)
{
case 1:printf("\nEnter the element:");
scanf("%d",&x);
enqueue(x);
break;
case 2:dequeue();
break;
case 3:display();
break;
default:printf("\nInvalid choice:");
}
}
}
<file_sep>#include<stdio.h>
#include<stdlib.h>
#define MAX 30
typedef struct node
{
int data;
struct node *link;
}node;
node *head[MAX]={NULL};;
void insert(int key,int n)
{
int i=key%n;
node *newnode,*temp;
newnode=(node *)malloc(sizeof(node));
newnode->data=key;
newnode->link=NULL;
if(head[i]==NULL)
head[i]=newnode;
else
{
temp=head[i];
while(temp->link!=NULL)
temp=temp->link;
temp->link=newnode;
}
}
void display(int n)
{
node *temp;
int i=0;
while(i<n)
{
printf("\nIndex %d:",i);
if(head[i]!=NULL)
{
temp=head[i];
while(temp!=NULL)
{
printf("\t%d",temp->data);
temp=temp->link;
}
i++;
}
else
i++;
}
}
void search(int key,int n)
{
int pos=key%n,flag=0;
node *temp;
if(head[pos]==NULL)
printf("\nKey not found");
else
temp=head[pos];
while(temp!=NULL)
{
if(temp->data==key)
{
flag=1;
break;
}
temp=temp->link;
}
if(flag==1)
printf("\nKey found");
else
printf("\nKey not found");
}
int main (void)
{
int ch,key,n;
printf("\nEnter the size of the hash table: ");
scanf("%d",&n);
printf("\n\t\tMENU\n1.INSERT\n2.DISPLAY\n3.SEARCH\n4.EXIT");
while(1)
{
printf("\nEnter your choice: ");
scanf("%d",&ch);
if(ch==4)
break;
switch(ch)
{
case 1:printf("\nEnter the element to be inserted: ");
scanf("%d",&key);
insert(key,n);
break;
case 2:display(n);
break;
case 3:printf("\nEnter the element to be searched: ");
scanf("%d",&key);
search(key,n);
break;
default:printf("\nInvalid choice!");
}
}
}
<file_sep>#include<stdio.h>
void bubble(int arr[50],int n)
{
int i,j,temp;
for(i=0;i<=n;i++)
{
for(j=0;j<=n-i;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
for(i=1;i<=n;i++)
{
printf("%d",arr[i]);
}
}
int main()
{
int arr[50],n,i;
printf("enter the limit");
scanf("%d",&n);
printf("enter the array");
for(i=0;i<=n;i++)
{
scanf("%d",&arr[i]);
}
bubble(arr,n);
return 0;
}
<file_sep>#include<stdio.h>
#define MAX 30
int hash[MAX];
int search(int key,int n)
{
int pos=key%n,i,flag=0;
for(i=pos;i<n;i++)
{
if(hash[i]==key)
{
flag=1;
break;
}
}
for(i=0;i<pos;i++)
{
if(hash[i]==key)
{
flag=1;
break;
}
}
if(flag==1)
return 1;
else
return 0;
}
void insert(int key,int n)
{
int flag=0,index,z;
index=key%n;
if(hash[index]==-1)
{
hash[index]=key;
return;
}
else
{
z=search(key,n);
if(z==1)
{
printf("\nElement exists");
}
else
{
int i=index+1,j;
while(i<n)
{
if(hash[i]==-1)
{
flag=1;
hash[i]=key;
break;
}i++;
}
if(flag==0)
{
j=0;
while(j<index)
{
if(hash[j]==-1)
{
flag=1;
hash[j]=key;
break;
}j++;
}
}
}
}
if(flag==0)
printf("\nTable full");
}
void display(int n)
{
int i=0;
while(i<n)
{
printf("\nIndex %d:",i);
if(hash[i]!=-1)
printf("\t%d",hash[i]);
i++;
}
}
int main (void)
{
int ch,key,n,z;
printf("\nEnter the size of the hash table: ");
scanf("%d",&n);
for(int i=0;i<n;i++)
hash[i]=-1;
printf("\n\t\tMENU\n1.INSERT\n2.DISPLAY\n3.SEARCH\n4.EXIT");
while(1)
{
printf("\nEnter your choice: ");
scanf("%d",&ch);
if(ch==4)
break;
switch(ch)
{
case 1:printf("\nEnter the element to be inserted: ");
scanf("%d",&key);
insert(key,n);
break;
case 2:display(n);
break;
case 3:printf("\nEnter the element to be searched: ");
scanf("%d",&key);
z=search(key,n);
if(z==1)
printf("\nElement found");
else
printf("\nElement not found");
break;
default:printf("\nInvalid choice!");
}
}
}
<file_sep>#include<stdio.h>
int linearsearch(int* b,int a,int n)
{
int d;
for(int i=0;i<=n;i++)
{
if(b[i]==a)
{
d=i+1;
return d;
}
}
return 0;
}
int main()
{
int n,a,i,b[50],d;
printf("enter the element to be searched");
scanf("%d",&a);
printf("enter the array limit");
scanf("%d",&n);
printf("enter the array");
for(i=0;i<n;i++)
{
scanf("%d",&b[i]);
}
d=linearsearch(b,a,n);
if(d>0)
{
printf("the element is found at the position %d",d);
}
else
printf("element not found");
}
<file_sep>#include<stdio.h>
#include<stdlib.h>
#define MAX 5
int arr[MAX];
int front=-1,rear=-1;
void enqueue(int data)
{
if(rear==MAX-1)
{
printf("queue overflow");
}
else if(front==-1 && rear==-1)
{
rear=rear+1;
front=front+1;
arr[rear]=data;
}
else
{
rear=rear+1;
arr[rear]=data;
}
}
void dequeue()
{
int data;
if(front==-1 || front>rear)
{
printf("queue is empty");
}
else
{
data=arr[front];
printf("the element dequed is%d",data);
front=front+1;
}
}
void display()
{
int i;
if(front==-1 || front>rear)
{
printf("empty queue");
}
else
{
for(i=front;i<=rear;i++)
{
printf("\t %d",arr[i]);
}
}
}
int main()
{
printf("\n \t\t MENU \n\t1.enqueue\n\t2.dequeue\n\t3.DISPLAY\n\t4.EXIT");
int ch,data;
while(1)
{
printf("\nEnter your choice:");
scanf("%d",&ch);
if(ch==4)
break;
switch(ch)
{
case 1:printf("\nEnter the element to be enqued:");
scanf("%d",&data);
enqueue(data);break;
case 2:dequeue();break;
case 3:display();break;
default:printf("\n Invalid Choice");
}
}
}
<file_sep>#include<stdio.h>
void selectsort(int arr[50],int n)
{
int i,min,pos,j;
for(i=0;i<n-1;i++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(arr[j]<arr[min])
{
min=j;
}
}
if(min!=i)
{
pos=arr[i];
arr[i]=arr[min];
arr[min]=pos;
}
}
printf("the sorted array is");
for(i=0;i<n;i++)
{
printf("%d",arr[i]);
}
}
int main()
{
int arr[50],n,i;
printf("enter the limit");
scanf("%d",&n);
printf("enter the array");
for(i=0;i<=n;i++)
{
scanf("%d",&arr[i]);
}
selectsort(arr,n);
return 0;
}
<file_sep>#include<stdio.h>
struct node
{
int data;
struct node* link;
};
void insertion(struct *head,int pos,int X)
{
struct node*newnode;
newnode=(struct node*)malloc(sizeof(struct node));
if(newnode==NULL)
{
printf("no space");
}
int temp;
temp=head;
count=0;
while(temp->link!=NULL)
{
temp=temp->link;
count=count+1;
}
if(pos>count+1||pos<1)
{
printf("pos is invalid");
}
newnode->data=X;
if(pos==1)
{
newnode->link=head;
head=newnode;
}
|
e1e39cf6b2aa8856633ab2cc7106f4cd155f000e
|
[
"C"
] | 14 |
C
|
scarphase45/CSE-S3-LAB
|
ba7ff9c1449464fe1b1c8a8183f23e762f796366
|
ea17cbb09f4dfa7c60a958eaa48ce283cf75637c
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.