branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep>import glob
import os
from jinja2 import Template
pages = []
#builds pages list by iterating through files in content directory
def page_list():
all_html_files = glob.glob('content/*.html')
for item in all_html_files:
file_path = os.path.basename(item)
name_only, extension = os.path.splitext(file_path)
pages.append({
"filename": item,
"output": 'docs/' + file_path,
"active": name_only,
"title": name_only,
"link": file_path,
})
def new_page():
file_name = input('File name? ')
file_content = '''<h1>New Page</h1>
<p>New content...</p>'''
open('content/' + file_name, 'w+').write(file_content)
# apply_template function will read in base template and
# replace {{content}} {{title}} and {{active_...} string
# with code from each html page
def apply_template(content, page, active):
template_html = open("templates/base.html").read()
template = Template(template_html)
result = template.render({
"title": page['title'],
"content": content,
"pages": pages,
page['active']: "active",
})
return result
# build function will write the completed webpage
# to the docs directory
def build(doc, page):
finished_doc = open(page['output'], 'w+').write(doc)
return finished_doc
# main function will read in content from pages list
# build pages with apply_template and write to docs directory with build
def main():
page_list()
for page in pages:
content = open(page['filename']).read()
active = page['active']
print('Reading:', page['filename'])
doc = apply_template(content, page, active)
print('Compiling template...')
finished_webpage = build(doc, page)
print('Writing to docs:', page['output'])
print('[Website built]')<file_sep># zachary-hw4
Kickstart Coding - HW #4
Improves upon HW #3 assignment:
Uses Jinja for more advanced templating
Uses Python modules and packages for more efficient SSG
<file_sep>import utils
import sys
if len(sys.argv) > 1:
command = sys.argv[1]
if command == "build":
print("[Build was specified]")
if __name__ == "__main__":
utils.main()
elif command == "new":
print("New page was specified")
utils.new_page()
else:
print('Please specify "build" or "new"')
else:
print('''Usage:
Rebuild site: python manage.py build
Create new page: python manage.py new''')
| eaecf193fa5d5142c6939758bada781d899a70e4 | [
"Markdown",
"Python"
] | 3 | Python | zlake23/zachary-hw4 | 6bed01308aabffb959a5771fd55cbb9448eebd59 | 1c897591530d79486b4d570d327f9d5769849138 |
refs/heads/master | <repo_name>louiskareem/DevAirLab<file_sep>/app/Device.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Device extends Model
{
use SoftDeletes;
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
//START STEFAN
protected $dates = ['deleted_at'];
public $organization;
//END STEFAN
/**
* Device relationship with an organization
* @return [type] [description]
*/
public function organization()
{
return $this->belongsTo('App\Organization');
}
/**
* Device relationship with meters
* @return [type] [description]
*/
public function records()
{
return $this->hasMany('App\Record');
}
/**
* Find or create device by using name
* @param [type] $name [description]
* @return [type] [description]
*/
public static function findOrCreateDeviceByName($name)
{
$device = Device::where('name', '=', $name)->first();
if ($device === NULL) {
$device = new Device;
$device->name = $name;
$device->save();
}
return $device;
}
}
<file_sep>/routes/api.php
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::post('login', 'AuthController@login');
Route::post('validate', 'RegisterController@validate');
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::group([
'middleware' => 'api'
], function ($router) {
Route::post('user/register', 'RegisterController@create');
// Route for reset password and email
Route::post('uhoo/password/reset', 'ApiController@changePassword');
// Routes for basic Log in
Route::post('refresh', 'AuthController@refresh');
Route::post('me', 'AuthController@me');
Route::post('logout', 'AuthController@logout');
// Routes for Blueprint
Route::post('blueprint/upload', 'BlueprintController@uploadBP');
Route::post('blueprint/uploadAdmin', 'BlueprintController@uploadBPAdmin');
Route::post('blueprint/update', 'BlueprintController@updateBP');
Route::get('blueprint/get', 'BlueprintController@getBP');
Route::post('blueprint/changeName', 'BlueprintController@changeName');
Route::post('blueprint/coordinations/get', 'BlueprintController@getCoordination');
Route::post('blueprint/delete', 'BlueprintController@blueprintDelete');
Route::get('blueprint/devices/get', 'BlueprintController@getUserDevices');
Route::get('blueprint/db/devices/get', 'BlueprintController@getUserDBDevices');
Route::post('blueprint/device/remove', 'BlueprintController@removeDeviceFromBlueprint');
Route::post('blueprint/records/getForDevice', 'BlueprintController@getRecordsForDevice');
// Routes for Uhoo API
Route::post('uhoo/');
Route::post('uhoo/data/devices', 'ApiController@getUhooDevices');
Route::post('uhoo/data/records', 'ApiController@getUhooData');
// Routes for Uhoo records and devices view
Route::post('uhoo/devices', 'ApiController@deviceView');
Route::post('uhoo/records', 'ApiController@recordView');
Route::post('uhoo/record', 'ApiController@recordDetail');
// Route::post('uhoo/user/device', 'ApiController@userDevice');
Route::post('uhoo/meter/detail/{id}', 'ApiController@meterDetail');
// Routes for organizations and organization's device
Route::post('uhoo/organizations', 'ApiController@getOrganizations');
//Getting all devices no class_parent
Route::post('uhoo/getDevicesOrganization', 'ApiController@getDevicesOrganization');
Route::post('uhoo/getNewDevices', 'ApiController@getNewDevices');
//Add device to organization
Route::post('uhoo/addDeviceOrg', 'ApiController@addDeviceOrg');
//Delete device from organization
Route::post('uhoo/deleteDevicesOrganization', 'ApiController@deleteDevicesOrganization');
//edit device
Route::post('uhoo/editDevice', 'ApiController@editDevice');
// Routes for Dashboard
Route::post('uhoo/getDevicesWithData', 'ApiController@getDevicesWithData');
//routes for records by
Route::post('uhoo/recordsById', 'ApiController@recordsById');
});
<file_sep>/app/Http/Controllers/ApiController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use App\Record;
use App\Device;
use App\Organization;
use App\User;
use Carbon\Carbon;
use App\Http\Controllers\AuthController;
class ApiController extends Controller
{
/**
* [recordsById description]
* @param Request $request [description]
* @return [type] [description]
*/
public function recordsById(Request $request)
{
if ($request->id) {
$records = Record::where('device_id', $request->id)->orderBy('updated_at', 'desc')->get();
}
return $records;
}
/**
* Display all devices
*
* [deviceView description]
* @return [type] [description]
*/
public function getOrganizations()
{
$organizations = Organization::all();
return $organizations;
}
/**
* Display all devices from organization
*
* [deviceView description]
* @return [type] [description]
*/
public function getDevicesOrganization(Request $request)
{
if ($request->id) {
$orgDevices = Device::where('organization_id', $request->id)->get();
}
return $orgDevices;
}
/**
* Display all devices with no organization
*
* [deviceView description]
* @return [type] [description]
*/
public function getNewDevices()
{
$cleanDevices = Device::where('organization_id', NULL)->get();
return $cleanDevices;
}
/**
* Display for adding organization devices
*
* [deviceView description]
* @return [type] [description]
*/
public function addDeviceOrg(Request $request)
{
$status = 0;
foreach ($request->device_id as $id) {
Device::where('id', $id)->update(['organization_id' => $request->organization_id]);
$status = 1;
}
return $status;
}
/**
* Display for deleting organization devices
*
* [deviceView description]
* @return [type] [description]
*/
public function deleteDevicesOrganization(Request $request)
{
$status = 0;
foreach ($request->device_id as $id) {
Device::where('id', $id)->update(['organization_id' => NULL]);
//softdelete concept
//Device::where('id', $id)->delete();
$status = 1;
}
return $status;
}
/**
* [Method for changing/updating password]
* @param Request $request [description]
* @return [type] [description]
*/
public function changePassword(Request $request){
$user = Auth::user();
if (Hash::check($request->get('current_password'), Auth::user()->password)) {
//Change the password
$user->fill([
'password' => Hash::make($request->get('new_password'))
])->save();
// $request->session()->flash('success', 'Your password has been changed.');
}
// if (!(Hash::check($request->get('current_password'), Auth::user()->password))) {
// // The passwords matches
// return redirect()->back()->with("error","Your current password does not matche with the password you provided. Please try again.");
// }
// if(strcmp($request->get('current_password'), $request->get('new_password')) == 0){
// //Current password and new password are same
// return redirect()->back()->with("error","New Password cannot be same as your current password. Please choose a different password.");
// }
// $validatedData = $request->validate([
// 'current_password' => '<PASSWORD>',
// 'new_password' => 'required|string|min:6|confirmed',
// 'confirm_password' => 'required|string|min:6|confirmed'
// ]);
// //Change Password
// $user = Auth::user();
// $user->password = <PASSWORD>($request->get('new_password'));
// $user->save();
return redirect('/');
}
/**
* Display record details
*
* @param [type] $id [description]
* @return [type] [description]
*/
public function recordDetail()
{
$id = request('id');
$device = Device::findOrFail($id);
//->orderBy('id', 'desc')->first()
$record = Record::where('device_id', '=', $device->id)->first();
// return response()->json($record);
return $record;
}
/**
* function to get all devices with values
* Colors:
green = bg-success
orange = bg-warning
red = bg-danger
undefiend = secondary
* @return [type] [description]
*/
public function getDevicesWithData(Request $request){
if ($request->id) {
$device = array();
$orgDevices = Device::where('organization_id', $request->id)->get();
$orgDeviceData = array();
foreach ($orgDevices as $device) {
$deviceData = Record::where('device_id', $device['id'])->orderByRaw('created_at DESC')->first();
if(isset($deviceData)){
$color = "bg-success";
$message = "All values are great!";
//Check warning for temperature
if($deviceData['temperature'] <= 20 || $deviceData['temperature'] >= 27){
$color = "bg-warning";
$message = "The temperature is under the 20 degrees or above the 27 degrees";
}
//Check danger for temprature
if($deviceData['temperature'] <= 10 || $deviceData['temperature'] >= 40){
$color = "bg-danger";
$message = "The temperature is under de 10 degrees or above the 40 degrees";
}
//Check warning for relative humidity
if($deviceData['relative_humidity'] <= 30 || $deviceData['relative_humidity'] >= 50){
$color = "bg-warning";
$message = "The humidity is under the 30% or above 50%";
}
}else{
$color = "bg-secondary";
$message = "There is no data for this device";
}
//set color by device
$orgDeviceData[] = array(
'name' => $device['name'],
'color' => $color,
'message' => $message,
);
}
}
return $orgDeviceData;
}
/**
* [editDevice description]
* @param Request $request [description]
* @return [type] [description]
*/
public function editDevice(Request $request){
$id = $request->id;
$name = $request->name;
if(isset($id) && isset($name)){
DB::table('devices')
->where('id', $id)
->update(['name' => $name]);
}
return 'Succes update! ';
}
/**
* Method to get all devices tha belongs to logged in user
* [userDevice description]
* @return [type] [description]
*/
public function userDevice()
{
$devices = Device::all();
$records = Record::all();
$organizations = Organization::all();
$user = auth()->user();
$content = $user->getContent();
$userInfo = json_decode($content, true);
$userDevice = array();
foreach ($organizations as $organization) {
if ($userInfo['name'] == $organization->name) {
foreach ($devices as $device) {
// $device->records;
if ($device->organization->name == $organization->name) {
$userDevice[] = $device;
}
}
}
}
return $userDevice;
}
/**
* Method for getting a list of all available devices.
*
* [getUhooData description]
* @return [type] [description]
* @return \Illuminate\Http\Response
*/
public function getUhooDevices()
{
$data = array('username' => '<EMAIL>', 'password' => '<PASSWORD>');
// Receive API by doing an 'POST' request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://api.uhooinc.com/v1/getdevicelist");
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_MAXREDIRS, 10);
curl_setopt($curl, CURLOPT_ENCODING, "");
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_exec($curl);
$result = curl_exec($curl);
$response = json_decode($result);
$devices = Device::all();
$organizations = Organization::all();
$user = AuthController::me();
$content = $user->getContent();
$userInfo = json_decode($content, true);
foreach ($response as $res) {
foreach ($devices as $device) {
if ($res->deviceName !== $device->name) {
dd('not iden');
//Save new devices to DB
$device = new Device;
$device->name = $res->deviceName;
$device->mac_address = $res->macAddress;
$device->serial_number = $res->serialNumber;
foreach ($organizations as $organization) {
if ($userInfo['name'] == $organization->name) {
$device->organization_id = $organization->id;
}
}
// $device->save();
}
}
}
// Redirect to devices page
return redirect('api/uhoo/devices');
}
/**
* Method for getting a data per minute.
*
* [getUhooData description]
* @return [type] [description]
* @return \Illuminate\Http\Response
*/
public function getUhooData()
{
$data = array('username' => '<EMAIL>', 'password' => '<PASSWORD>', 'serialNumber' => '52ff6e067565555639500367');
// Receive API by doing an 'POST' request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://api.uhooinc.com/v1/getlatestdata");
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_MAXREDIRS, 10);
curl_setopt($curl, CURLOPT_ENCODING, "");
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_exec($curl);
$result = curl_exec($curl);
$response = json_decode($result);
$devices = Device::all();
// Save new records data to DB
$record = new Record;
foreach ($devices as $device) {
if ($device->serial_number == $data['serialNumber']) {
$record->device_id = $device->id;
}
}
$record->temperature = $response->Temperature;
$record->relative_humidity = $response->{'Relative Humidity'};
$record->pm2_5 = $response->{'PM2.5'};
$record->tvoc = $response->TVOC;
$record->co2 = $response->CO2;
$record->co = $response->CO;
$record->air_pressure = $response->{'Air Pressure'};
$record->ozone = $response->Ozone;
$record->no2 = $response->NO2;
// $record->save();
// Redirect to records page
return redirect('api/uhoo/records');
}
}
<file_sep>/public/js/main.js
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
})
var localStorage = window.localStorage
var base_url = window.location.origin
/**
*
* Knockoutjs
*/
var ViewModel = function (){
var self = this
self.files = ko.observableArray()
self.none = ko.observable('none')
self.dev = ko.observableArray([
{name:"Device Name"},
{name:"Mac Address"},
{name:"Serial Number"}
])
self.record = ko.observableArray([
{name:"Device Name"},
{name:"Temperature"},
{name:"Relative Humidity"},
{name:"PM 2.5"},
{name:"TVOC"},
{name:"CO2"},
{name:"CO"},
{name:"Air Pressure"},
{name:"Ozone"},
{name:"NO2"},
])
self.recordHead = ko.observableArray([
{name:"Temperature"},
{name:"Relative Humidity"},
{name:"PM 2.5"},
{name:"TVOC"},
{name:"CO2"},
{name:"CO"},
{name:"Air Pressure"},
{name:"Ozone"},
{name:"NO2"},
])
self.currentPage = ko.observable()
self.lastCurrentTab = ko.observable()
self.showRow = ko.observable(false);
self.showDev = ko.observable(false);
self.showRec = ko.observable(false);
self.currentPageData = ko.observableArray()
self.currentTabDataProfile = ko.observableArray()
self.currentTabDataDevices = ko.observableArray()
self.currentTabDataRecords = ko.observableArray()
self.prof = ko.observableArray()
self.pages = ko.observableArray()
self.userRole = ko.observable();
self.userDevice = ko.observableArray()
self.deviceMeter = ko.observableArray()
self.lastRecord = ko.observableArray()
self.lastRecordHead = ko.observableArray()
self.currentLastRecord = ko.observableArray()
self.lastCurrentTab = ko.observable()
self.showRow = ko.observable(false);
self.showDev = ko.observable(false);
self.showRec = ko.observable(false);
/*START STEFAN CODE*/
self.getOrganizations = function(){
if(self.userRole() == 'user')
{
return '401';
}
$.post(base_url + '/api/uhoo/organizations', {token: self.token()}).done(function(data){
self.organization(data)
console.log(self.organization());
})
}
/**
* [organizationCheckbox description]
* @return {[type]} [description]
*/
self.organizationRadiobox = function(data,event) {
if(self.userRole() == 'user')
{
return '401';
}
self.showOrgDevices(false)
self.showNewDevices(false)
if (event.target.checked) {
//id organization
self.orgId = event.target.value;
//get all devices with no organization
$.post(base_url + '/api/uhoo/getDevicesOrganization' ,{token: self.token(),id:self.orgId}).done(function(data){
if (data[0]['organization_id'] != null ){
self.devicesOrganization(data)
self.showOrgDevices(!self.showOrgDevices());
}
})
$.post(base_url + '/api/uhoo/getNewDevices' ,{token: self.token()}).done(function(data){
if (data != ''){
self.newDevices(data)
self.showNewDevices(!self.showNewDevices());
}
})
}
return true; // to trigger the browser default bahaviour
}
self.devicesOwner = function(data) {
if(self.userRole() == 'user')
{
return '401';
}
var items=document.getElementsByName('devicesOrganization');
var selectedItems = [];
for(var i=0; i<items.length; i++){
if(items[i].type=='checkbox' && items[i].checked==true)
selectedItems.push(items[i].value+"\n");
}
if (selectedItems != 0) {
$.post(base_url + '/api/uhoo/deleteDevicesOrganization' ,{token: self.token(), device_id:selectedItems}).done(function(data){
if (data == 1) {
$.post(base_url + '/api/uhoo/getNewDevices' ,{token: self.token()}).done(function(data){
if (data[0]['organization_id'] == null ){
self.newDevices(data)
self.showNewDevices();
}
else {
console.log('Geen nieuwe devices');
}
})
$.post(base_url + '/api/uhoo/getDevicesOrganization' ,{token: self.token(),id:self.orgId}).done(function(data){
if (data[0]['organization_id'] != null ){
self.devicesOrganization(data)
self.showOrgDevices(self.showOrgDevices());
}
else {
console.log('Geen nieuwe devices');
}
})
}else {
console.log('Deleten niet gelukt')
}
})
}
}
self.newDevice = function(data) {
if(self.userRole() == 'user')
{
return '401';
}
var items=document.getElementsByName('newDevices');
var selectedItems = [];
for(var i=0; i<items.length; i++){
if(items[i].type=='checkbox' && items[i].checked==true)
selectedItems.push(items[i].value+"\n");
}
if (selectedItems != 0) {
$.post(base_url + '/api/uhoo/addDeviceOrg' ,{token: self.token(), organization_id:self.orgId, device_id:selectedItems}).done(function(data){
if (data == 1) {
$.post(base_url + '/api/uhoo/getNewDevices' ,{token: self.token()}).done(function(data){
if (data[0]['organization_id'] == null ){
self.newDevices(data)
self.showNewDevices();
}
else {
console.log('Geen nieuwe devices');
}
})
$.post(base_url + '/api/uhoo/getDevicesOrganization' ,{token: self.token(),id:self.orgId}).done(function(data){
if (data[0]['organization_id'] != null ){
self.devicesOrganization(data)
self.showOrgDevices(self.showOrgDevices());
}
else {
console.log('Geen devices van organization');
}
})
}else {
console.log('Updaten niet gelukt')
}
})
}
}
/*END STEFAN CODE*/
/* START CODE LARS */
self.colorDevices = function(){
$.post(base_url + '/api/me', {token: self.token()})
.done(function(data){
self.user(data)
//get devices with organization
$.post(base_url + '/api/uhoo/getDevicesWithData' ,{token: self.token(),id:self.user().organization_id})
.done(function(data){
self.allColorDevices(data)
})
})
}
/* END CODE LARS */
/**
* [profile description]
* @return {[type]} [description]
*/
self.toggleVisibilityDevices = function() {
if(self.userRole() == 'user')
{
return '401';
}
self.showDev(!self.showDev())
self.showRow(false)
self.showRec(false)
}
/**
* [getLastRecord description]
* @param {[type]} data [description]
* @return {[type]} [description]
*/
self.getLastRecord = function(data){
self.currentLastRecord(self.lastRecord()[data])
}
/**
* [toggleVisibilityRecords description]
* @return {[type]} [description]
*/
self.toggleVisibilityRecords = function() {
if(self.userRole() == 'user')
{
return '401';
}
$.post(base_url + '/api/uhoo/records', {token: self.token()}).done(function(data){
self.currentTab("Records")
self.currentTabHead(self.record())
data.forEach(function(element) {
self.currentTabDataRecords(data)
// console.log(element);
});
})
self.showRec(!self.showRec());
self.showRow(false);
self.showDev(false);
}
}
<file_sep>/public/js/logout.js
var logoutModel = function (){
var self = this
self.nav = ko.observable(false)
self.token = ko.observable()
if (localStorage.getItem('token'))
{
self.token(localStorage.getItem('token'))
}
self.loadModel = ko.observable(false)
console.log('Ik zit hier')
/**
* [logout description]
* @return {[type]} [description]
*/
self.logout = function(){
$.post(base_url + '/api/logout', {token:self.token()}).done(function(data){
console.log('User has been logged out')
localStorage.removeItem('myCat')
localStorage.removeItem('token')
ko.cleanNode($("#main")[0])
var newModel = new loginModel()
ko.applyBindings(newModel)
})
}
self.logout()
}
<file_sep>/README.md
# Developer AirLab
School project.
Created my own branche to display my code.
<file_sep>/public/js/datatable.js
/**
*
* Data tables
*/
ko.bindingHandlers.dataTablesForEach = {
page: 0,
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var options = ko.unwrap(valueAccessor());
ko.unwrap(options.data);
if(options.dataTableOptions.paging){
valueAccessor().data.subscribe(function (changes) {
var table = $(element).closest('table').DataTable();
ko.bindingHandlers.dataTablesForEach.page = table.page();
table.destroy();
}, null, 'arrayChange');
}
var nodes = Array.prototype.slice.call(element.childNodes, 0);
ko.utils.arrayForEach(nodes, function (node) {
if (node && node.nodeType !== 1) {
node.parentNode.removeChild(node);
}
});
return ko.bindingHandlers.foreach.init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
},
update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var options = ko.unwrap(valueAccessor()),
key = 'DataTablesForEach_Initialized';
ko.unwrap(options.data);
var table;
if(!options.dataTableOptions.paging){
table = $(element).closest('table').DataTable();
table.destroy();
}
ko.bindingHandlers.foreach.update(element, valueAccessor, allBindings, viewModel, bindingContext);
table = $(element).closest('table').DataTable(options.dataTableOptions);
if (options.dataTableOptions.paging) {
if (table.page.info().pages - ko.bindingHandlers.dataTablesForEach.page == 0)
table.page(--ko.bindingHandlers.dataTablesForEach.page).draw(false);
else
table.page(ko.bindingHandlers.dataTablesForEach.page).draw(false);
}
if (!ko.utils.domData.get(element, key) && (options.data || options.length))
ko.utils.domData.set(element, key, true);
return { controlsDescendantBindings: true };
}}; | 69697631565ff2fdb5663dc18944027109f6a75e | [
"JavaScript",
"Markdown",
"PHP"
] | 7 | PHP | louiskareem/DevAirLab | e29ebffcbf809551bc365af16c417c8eb9239575 | 3d6b5040f8865b9e09af626aa09a3c4f6992cdc7 |
refs/heads/master | <repo_name>akira3518/springStudy<file_sep>/README.md
# springStudy
IBDATA team study meterial
<file_sep>/tddMoneyTest/src/test/java/com/test/moneyTest/testHomeController.java
package com.test.moneyTest;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml"})
@WebAppConfiguration
public class testHomeController {
}
<file_sep>/tddWebTest/src/main/java/com/web/test/HomeController.java
package com.web.test;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
/**
* Handles requests for the application home page.
*/
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
@RequestMapping(value = "/", method = RequestMethod.GET, produces ="application/json;charset=utf-8")
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
return "home";
}
//void ๋ฆฌํด ํ์
@RequestMapping("/doA")
public void doA() {
logger.info("/doA called...");
}
//String ๋ฆฌํด ํ์
@RequestMapping("/doC")
public String doC(@ModelAttribute("msg") String msg) {
logger.info("/doC called");
return "result";
}
//String ๋ฆฌํด ํ์
@RequestMapping("/doD")
public String doD(Model model) {
ProductVO product = new ProductVO("desktop", 10000);
logger.info("/doD called");
model.addAttribute(product);
return "product_detail";
}
//doF๋ฅผ ๋ฆฌ๋ค์ด๋ ํธ
@RequestMapping("/doE")
public String doE(RedirectAttributes redirectAttributes) {
logger.info("/doE called and redirect to /doF");
redirectAttributes.addAttribute("msg","this is the message with redirected");
return "redirect:/doF";
}
@RequestMapping("/doF")
public void doF(@ModelAttribute String msg) {
logger.info("/doF called" + msg);
}
//json๋ฐ์ดํฐ๋ฅผ ์์ฑํ๋ ๊ฒฝ์ฐ
@RequestMapping("/doJson")
@ResponseBody
public ProductVO doJson() {
ProductVO productVO = new ProductVO("laptop",300000);
return productVO;
}
}
<file_sep>/tddWebTest/src/test/java/com/web/test/HomeControllerTest.java
package com.web.test;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import javax.inject.Inject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = "file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml")
public class HomeControllerTest {
private static final Logger logger = LoggerFactory.getLogger(HomeControllerTest.class);
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
logger.info("setup!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
/*
@Test
public void test() throws Exception {
this.mockMvc
//GET ๋ฐฉ์์ผ๋ก "/" URL์ ํธ์ถํ๋ค
.perform(get("/"))
//์ฒ๋ฆฌ๋ด์ฉ์ ์ถ๋ ฅํ๋ค
.andDo(print())
//status ๊ฐ์ด ์ ์์ธ ๊ฒฝ์ฐ๋ฅผ ๊ธฐ๋ํ๊ณ ๋ง๋ ์ฒด์ด๋ ๋ฉ์๋ ์ค ์ผ๋ถ์
๋๋ค.
.andExpect(status().isOk())
//model ์์ฑ์์ "serverTime"์ด ์กด์ฌํ๋์ง ๊ฒ์ฆํ๋ค
.andExpect(model().attributeDoesNotExist("serverTime"))
//model ์์ฑ์์ "serverTime"์ ๊ฐ์ด ์ํ๋ ๊ฐ์ผ๋ก ์ธํ
๋์ด ์๋์ง ๊ฒ์ฆํ๋ค.
.andExpect(model().attribute("serverTime", "22"))
//contentType์ ๊ฒ์ฆํฉ๋๋ค.
.andExpect((ResultMatcher) content().contentType("application/json;charset=utf-8"));
}
@Test
public void testDoA() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/doA"))
.andDo(print())
.andExpect(status().isOk());
}
@Test
public void testDoC() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/doC?msg=world"))
.andDo(print())
.andExpect(status().isOk());
}
@Test
public void testDoD() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/doD"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(model().attributeExists("productVO"));
}
@Test
public void testDoE() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/doE"))
.andDo(print())
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("doF?msg=this+is+the+message+with+redirected"));
} */
@Test
public void testDoJson() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/doJson"))
.andDo(print())
.andExpect(status().isOk())
.andExpect((ResultMatcher) content().contentType("application/json;charset=utf-8"));
}
//์์ ์ฐธ๊ณ ์ฌ์ดํธ
//https://doublesprogramming.tistory.com/175
}
| a963b74f3dc7659728780fa499dad34922836bb6 | [
"Markdown",
"Java"
] | 4 | Markdown | akira3518/springStudy | e47e22733287b4b8ee9d0e895226742e13fd7d83 | 76f0e399e6b80df332e1aa017dd9e0822dd92b90 |
refs/heads/master | <repo_name>aphreet/transmission_bot<file_sep>/src/main.rs
extern crate rustc_serialize;
#[macro_use]
extern crate hyper;
extern crate url;
extern crate clap;
#[macro_use]
extern crate log;
extern crate env_logger;
mod telegram;
mod t11n;
mod t11nbot;
use std::env;
use telegram::TgmClient;
use telegram::TgmServerHandler;
fn validate_bot(client:&TgmClient) {
let me = client.get_me();
match me {
Err(msg) => {
panic!("Failed to retrieve bot info: {}", msg);
},
Ok(user) => {
info!("Retrived bot info {:?}", user);
}
}
}
#[derive(Debug)]
struct MainArgs {
token: String,
webhook: Option<String>,
transmission: String,
users: Vec<u64>
}
fn get_env(key: &str) -> Option<String> {
match env::var_os(key) {
Some(val) => {
Some(val.into_string().unwrap())
}
None => None
}
}
fn parse_env() -> Option<MainArgs> {
let webhook = get_env("TGM_HOOK");
let token = get_env("TGM_TOKEN");
let transmission = get_env("TGM_TRANSMISSION_URL");
let users = get_env("TGM_USERS");
if token.is_some() && transmission.is_some() && users.is_some() {
let users_str = users.unwrap();
let mut user_ids = users_str.split(",").map(|val| val.parse::<u64>().unwrap()).collect::<Vec<u64>>();
user_ids.sort();
Some(
MainArgs{
token: token.unwrap(),
webhook: webhook,
transmission: transmission.unwrap(),
users: user_ids
}
)
}else{
None
}
}
fn parse_args() -> Option<MainArgs> {
let matches = clap::App::new("Telegram transmision bot")
.version("1.0")
.author("<NAME>. <<EMAIL>gin.me>")
.about("Allows to work with transmission via telegram")
.arg(clap::Arg::with_name("token")
.short("t")
.long("token")
.value_name("BOTID")
.help("Sets bot id")
.required(true)
.takes_value(true))
.arg(clap::Arg::with_name("webhook")
.short("w")
.long("webhook")
.value_name("URL")
.takes_value(true)
.help("Sets the webhook to use for updated. No webhook means to use long polling"))
.arg(clap::Arg::with_name("users")
.short("u")
.long("users")
.value_name("USERS")
.required(true)
.takes_value(true)
.multiple(true)
.value_delimiter(",")
.require_delimiter(true)
.help("Comma separated list of user ids allowed to use bot"))
.arg(clap::Arg::with_name("transmission")
.long("transmission")
.value_name("URL")
.takes_value(true)
.required(true)
.help("RPC endpoint for transmission"))
.get_matches();
let token = matches.value_of("token").unwrap();
let webhook = matches.value_of("webhook");
let transmission = matches.value_of("transmission").unwrap();
let mut users = matches.values_of_lossy("users").unwrap().iter().map(|val| val.parse::<u64>().unwrap()).collect::<Vec<u64>>();
users.sort();
Some(MainArgs{
token: token.to_owned(),
webhook: webhook.map(|s| s.to_owned()),
transmission: transmission.to_owned(),
users: users
})
}
fn main() {
env_logger::init().unwrap();
let mut args_opt = parse_env();
if args_opt.is_none() {
args_opt = parse_args();
}
info!("Got arguments: {:?}", args_opt);
let args = args_opt.unwrap();
let tgm_client = TgmClient::new(&args.token);
validate_bot(&tgm_client);
let configured_webhook = if args.webhook.is_some(){
let webhook_val = args.webhook.unwrap();
tgm_client.configure_webhook(Some(&webhook_val))
}else{
tgm_client.configure_webhook(None)
};
//http://192.168.88.11:9091/transmission/rpc
let handler = t11nbot::MessageHandler::new(&args.transmission, &tgm_client, args.users);
match configured_webhook {
Some(url) => {
info!("Starting webserver, expecting updates at {}", url);
let server_handler = TgmServerHandler::new(&format!("/{}", args.token), tgm_client, handler);
hyper::server::Server::http("0.0.0.0:8080").unwrap().handle(server_handler).unwrap();
},
None => {
info!("Using long polling to receive updates");
tgm_client.listen_for_updates(handler)
}
}
}
<file_sep>/src/t11nbot.rs
use telegram::TgmClient;
use telegram::TgmMessage;
use telegram::TgmDocument;
use telegram::TgmCommandParser;
use telegram::TgmMessageHandler;
use t11n;
use std::collections::hash_map;
use std::sync::{Arc, RwLock};
use std::string::String;
use std::thread;
use std::time;
#[derive(Debug)]
pub enum MessageCommand {
Add { url: String },
List { all: bool},
Status,
Unknown {value: String}
}
struct MessageCommandParser {
}
impl TgmCommandParser<MessageCommand> for MessageCommandParser {
fn parse(&self, command: String, value: String) -> MessageCommand {
match command.as_ref() {
"add" => MessageCommand::Add{url: value},
"list" => MessageCommand::List{all: value == "all"},
"status" => MessageCommand::Status,
_ => MessageCommand::Unknown{value: command}
}
}
}
#[derive(Clone)]
struct Watcher {
watchers: Arc<RwLock<hash_map::HashMap<u64, Vec<i64>>>>,
}
impl Watcher {
pub fn new() -> Watcher {
Watcher{
watchers: Arc::new(RwLock::new(hash_map::HashMap::new()))
}
}
fn watch(&self, tgm_client: &TgmClient, t11n_client: &t11n::Client) {
let mut to_notify = Vec::new();
{
let read_guard = self.watchers.read().unwrap();
// iterate over everything.
for (from, ids) in read_guard.iter() {
if ids.len() > 0 {
let get_result = t11n_client.get_torrents_by_ids(ids);
match get_result {
Ok(torrents) => {
for torrent in torrents.torrents {
if !(torrent.percentDone.unwrap_or(0.0) < 1.0) {
to_notify.push((*from, torrent.id, torrent.name.unwrap_or("unknown".to_string())));
}
}
}
Err(msg) => {
warn!("Failed to get status {}", msg)
}
}
}
}
}
for tuple in to_notify {
let send_resp = tgm_client.send_message(tuple.0,
&format!("Download {} has just finished", tuple.2));
match send_resp {
Ok(_) => {
debug!("Notification success, removing {} from watcher", tuple.2);
self.remove(tuple.0, tuple.1);
}
Err(msg) => {
warn!("Failed to send notification about torrent {}, err {}", tuple.2, msg)
}
}
}
}
fn add(&self, from: u64, id: i64) {
debug!("Start watching {} for {}", id, from);
let mut write_guard = self.watchers.write().unwrap();
if !write_guard.contains_key(&from) {
write_guard.insert(from, Vec::new());
}
let mut vec = write_guard.get_mut(&from).unwrap();
if let Err(index) = vec.binary_search(&id) {
vec.insert(index, id);
}
}
fn remove(&self, from: u64, id: i64) {
debug!("Stop watching {} for {}", id, from);
let mut write_guard = self.watchers.write().unwrap();
if write_guard.contains_key(&from) {
let mut vec = write_guard.get_mut(&from).unwrap();
if let Ok(index) = vec.binary_search(&id) {
vec.remove(index);
}
}
}
}
pub struct MessageHandler {
transmission_client: t11n::Client,
tgm_client: TgmClient,
watcher: Watcher,
users: Vec<u64>
}
impl MessageHandler {
pub fn new(t11n_uri: &str, tgm_client: &TgmClient, users: Vec<u64>) -> MessageHandler {
let handler = MessageHandler{
transmission_client: t11n::Client::new(t11n_uri.to_string()),
tgm_client: tgm_client.clone(),
watcher: Watcher::new(),
users: users
};
handler.watch_start();
handler
}
fn watch_start(&self) {
let watcher = self.watcher.clone();
let tgm_client = self.tgm_client.clone();
let t11n_client = self.transmission_client.clone();
thread::spawn(move || {
loop {
watcher.watch(&tgm_client, &t11n_client);
thread::sleep(time::Duration::from_secs(10));
}
});
}
fn send_message(&self, text:&str, message: &TgmMessage){
let result = self.tgm_client.send_message(message.from.id, &text.to_string());
match result {
Ok(send_msg) => debug!("Sent message {:?}", send_msg),
Err(err) => warn!("Failed to send message: {}, error: {}", text, err)
}
}
fn process_document(&self, doc:&TgmDocument, message: &TgmMessage) -> String {
let ref mime_type = doc.mime_type;
if mime_type != "application/x-bittorrent" {
warn!("Got invalid file type {}", mime_type);
return format!("Invalid file type: {:?}", mime_type).to_owned();
}
let file_result = self.tgm_client.get_file(&doc.file_id);
match file_result {
Ok(file) => {
let bytes = self.tgm_client.download_file(&file);
match bytes {
Ok(data) => {
self.send_message(&format!("Received file: {:?} of size {}", file, data.len()), &message);
return self.handle_add_torrent(self.transmission_client.add_torrent(data), message.from.id);
},
Err(msg) => {
return format!("Failed to receive file: {}", msg).to_owned();
}
}
}
Err(msg) => {
format!("Failed to retrieve file info: {}", msg).to_owned()
}
}
}
fn handle_add_torrent(&self, add_result:Result<t11n::ResponseArgAdd, String>, from: u64) -> String {
match add_result {
Ok(args) => {
if args.added.is_some() {
self.watcher.add(from, args.added.unwrap().id);
"Torrent added".to_string()
}else if args.duplicate.is_some() {
"Torrent was added previously".to_string()
}else {
"Unknown add result :(".to_string()
}
},
Err(msg) => {
format!("Failed to add link {}", msg).to_owned()
}
}
}
fn handle_status(&self, get_result:Result<t11n::ResponseArgsGet, String>) -> String {
match get_result {
Ok(torrents) => {
let mut complete = 0;
let mut incomplete = 0;
for torrent in torrents.torrents {
trace!("Got torrent {:?}", torrent);
if !(torrent.percentDone.unwrap_or(0.0) < 1.0) {
complete = complete + 1;
}else{
incomplete = incomplete + 1;
}
}
format!("{} files, incomplete {}", complete + incomplete, incomplete).to_owned()
}
Err(msg) => {
format!("Failed to get status {}", msg).to_owned()
}
}
}
fn format_size(&self, size: i64) -> String {
let mut vec = vec!["TB", "GB", "MB", "KB", "B"];
let mut size_mut = size;
loop {
if size_mut < 1024 {
return format!("{}{}", size_mut, vec.pop().unwrap_or(""));
}else {
size_mut = size_mut / 1024;
vec.pop();
}
}
}
fn handle_list(&self, get_result:Result<t11n::ResponseArgsGet, String>, list_all: bool) -> String {
match get_result {
Ok(torrents) => {
let mut count = 0;
let mut result = "files:\n".to_owned();
for torrent in torrents.torrents {
trace!("Got torrent {:?}", torrent);
let percent_done = torrent.percentDone.unwrap_or(0.0);
if percent_done < 1.0 || list_all {
let row = format!("{}, {}, {}%\n",
torrent.name.unwrap_or("".to_string()),
self.format_size(torrent.totalSize.unwrap_or(0)),
(percent_done * 100.0).round() as i64
);
result.push_str(&row);
count = count + 1
}
}
format!("{} {}", count, result).to_owned()
}
Err(msg) => {
format!("Failed to get status {}", msg).to_owned()
}
}
}
fn process_command(&self, command:&MessageCommand, message:&TgmMessage) -> String {
debug!("Got command {:?}", command);
match command {
&MessageCommand::Unknown{ref value} => {
warn!("Got unknown command {}", value);
"Sorry?".to_string()
},
&MessageCommand::Add{ref url} => {
self.handle_add_torrent(self.transmission_client.add_link(url.to_string()), message.from.id)
},
&MessageCommand::List{all} => {
self.handle_list(self.transmission_client.get_torrents(), all)
},
&MessageCommand::Status => {
self.handle_status(self.transmission_client.get_torrents())
}
}
}
}
impl TgmMessageHandler for MessageHandler {
fn process_message(&self, message:&TgmMessage) -> String{
debug!("Got message {:?}", message);
if let Err(_) = self.users.binary_search(&message.from.id) {
return format!("I don't know you, {} ({})", &message.from.first_name, &message.from.id).to_owned();
}
if let Some(ref doc) = message.document {
return self.process_document(&doc, &message);
}
let parser = MessageCommandParser{};
if let Some(ref command) = message.get_command(&parser) {
return self.process_command(&command, &message);
}
"Please, type a command".to_string()
}
}
<file_sep>/src/telegram.rs
extern crate rustc_serialize;
extern crate hyper;
extern crate url;
extern crate log;
extern crate mime;
use hyper::client::Client;
use rustc_serialize::json;
use rustc_serialize::Decoder;
use rustc_serialize::Decodable;
use url::percent_encoding;
use std::io::Read;
use std::time::Duration;
use std::cmp;
use std::marker::{Send, Sync};
use std::string;
use hyper::server;
#[derive(RustcDecodable, Debug)]
struct TgmResponse<T> {
ok: bool,
result: T
}
#[derive(RustcDecodable, Debug)]
pub struct TgmDocument {
pub file_name: String,
pub mime_type: String,
pub file_id: String,
pub file_size: u64
}
#[derive(RustcDecodable, Debug)]
pub struct TgmUpdate {
pub update_id: u64,
pub message: Option<TgmMessage>
}
#[derive(RustcDecodable, Debug)]
pub struct TgmMessage {
pub message_id: i64,
pub from: TgmUser,
pub text: Option<String>,
pub document: Option<TgmDocument>,
pub entities: Option<Vec<TgmMessageEntity>>
}
pub trait TgmCommandParser<T> {
fn parse(&self, command: String, value: String) -> T;
}
impl TgmMessage {
pub fn get_command<T>(&self, parser:&TgmCommandParser<T>) -> Option<T> {
if let Some(ref ents) = self.entities {
for e in ents {
if e.entity_type == "bot_command" {
if let Some(ref text) = self.text {
let command: String = text.chars().skip(1 + e.offset).take(e.length - 1).collect();
let rest: String = text.chars().skip(1 + e.offset + e.length).collect();
return Some(parser.parse(command, rest))
}
}
}
}
None
}
}
#[derive(Debug)]
pub struct TgmMessageEntity {
pub entity_type: String,
pub offset: usize,
pub length: usize
}
impl Decodable for TgmMessageEntity {
fn decode<D: Decoder>(d: &mut D) -> Result<TgmMessageEntity, D::Error> {
d.read_struct("TgmMessageEntity", 3, |d| {
let entity_type = try!(d.read_struct_field("type", 0, |d| { d.read_str() }));
let offset = try!(d.read_struct_field("offset", 1, |d| { d.read_usize() }));
let length = try!(d.read_struct_field("length", 2, |d| { d.read_usize() }));
Ok(TgmMessageEntity{ entity_type: entity_type, offset: offset, length: length })
})
}
}
#[derive(RustcDecodable, Debug)]
pub struct TgmUser {
pub id: u64,
pub first_name: String,
pub last_name: Option<String>,
pub username: Option<String>
}
#[derive(RustcDecodable, Debug)]
pub struct TgmFile {
pub file_id: String,
pub file_size: Option<u64>,
pub file_path: Option<String>
}
#[derive(RustcDecodable, Debug)]
pub struct TgmWebHook {
pub url: String
}
pub trait TgmMessageHandler : Sync + Send {
fn process_message(&self, message:&TgmMessage) -> string::String;
}
#[derive(Clone)]
pub struct TgmClient {
token: String
}
impl TgmClient {
pub fn new(token: &str) -> TgmClient {
TgmClient {
token: token.to_string()
}
}
fn create_client(&self) -> Client {
let mut client = Client::new();
let duration = Some(Duration::new(60, 0));
client.set_read_timeout(duration);
client
}
fn send_request(&self, method: &str, args:&str) -> Result<String, String> {
let response = self.create_client().get(&format!("https://api.telegram.org/{}/{}?{}",
self.token, method, args)).send();
if let Err(msg) = response {
return Err(format!("Failed to send request: {}", msg));
};
let mut res = response.unwrap();
if res.status != hyper::Ok {
return Err(format!("Unexpected response status {}", res.status))
}
let mut res_body = String::new();
match res.read_to_string(&mut res_body) {
Err(msg) => {
Err(format!("Failed to read response body {}", msg))
},
Ok(_) => {
trace!("Got response {}", res_body);
Ok(res_body)
}
}
}
fn execute<T:rustc_serialize::Decodable>(&self, method: &str, args:&str) -> Result<T, String> {
trace!("Executing method:{} with args:{}", method, args);
let result = self.send_request(method, args);
match result {
Ok(json) => {
let response: Result<TgmResponse<T>, String> =
json::decode(&json).map_err(|err| err.to_string());
match response {
Ok(resp) => {
if resp.ok {
Ok(resp.result)
}else{
Err("Result value is not ok".to_string())
}
}
Err(msg) => Err(msg)
}
},
Err(msg) => Err(msg)
}
}
pub fn get_me(&self) -> Result<TgmUser, String> {
self.execute::<TgmUser>("getMe", "")
}
pub fn get_updates(&self, offset: u64) -> Result<Vec<TgmUpdate>, String> {
self.execute::<Vec<TgmUpdate>>("getUpdates", &format!("timeout=30&offset={}", offset))
}
pub fn send_message(&self, chat:u64, text: &String) -> Result<TgmMessage, String> {
self.execute::<TgmMessage>("sendMessage", &format!("chat_id={}&text={}", chat, encode_message_string(text)))
}
pub fn get_file(&self, file_id:&str) -> Result<TgmFile, String> {
self.execute::<TgmFile>("getFile", &format!("file_id={}", file_id))
}
pub fn download_file(&self, file:&TgmFile) -> Result<Vec<u8>, String> {
if let Some(ref path) = file.file_path {
debug!("Downloading file {:?}", file);
let response = self.create_client().get(&format!("https://api.telegram.org/file/{}/{}",
self.token, path)).send();
if let Err(msg) = response {
return Err(format!("Failed to send request: {}", msg));
};
let mut res = response.unwrap();
if res.status != hyper::Ok {
return Err(format!("Unexpected response status {}", res.status))
}
let mut body = Vec::new();
match res.read_to_end(&mut body) {
Err(msg) => {
Err(format!("Failed to read response body {}", msg))
},
Ok(size) => {
debug!("Downloaded {} bytes", size);
Ok(body)
}
}
}else{
return Err("Missing file path".to_string());
}
}
pub fn listen_for_updates<T: TgmMessageHandler>(&self, handler: T) {
let mut update_id:u64 = 0;
loop {
trace!("Getting updates from id {}", update_id);
let updates = self.get_updates(update_id + 1);
match updates{
Ok(update_list) => {
for upd in update_list {
update_id = cmp::max(update_id, upd.update_id);
if let Some(message) = upd.message {
let text_response = handler.process_message(&message);
let result = self.send_message(message.from.id, &text_response);
match result {
Ok(send_msg) => debug!("Sent message {:?}", send_msg),
Err(err) => warn!("Failed to send message: {}, error: {}", text_response, err)
}
}
}
},
Err(msg) => warn!("Failed to get updates {}", msg)
}
}
}
pub fn get_web_hook(&self) -> Result<TgmWebHook, String> {
self.execute::<TgmWebHook>("getWebhookInfo", "")
}
pub fn delete_web_hook(&self) -> Result<String, String> {
self.send_request("deleteWebhook", "")
}
pub fn set_web_hook(&self, url:&str) -> Result<String, String> {
self.send_request("setWebhook", &format!("url={}", url))
}
pub fn configure_webhook(&self, required_hook:Option<&str>) -> Option<string::String>{
let webhook = match self.get_web_hook() {
Err(msg) => {
panic!("Failed to retrieve webhook info: {}", msg)
}
Ok(hook) => hook
};
info!("Got webhook: {:?}", webhook);
match required_hook {
Some(url) => {
if url != webhook.url {
match self.set_web_hook(&format!("{}/{}", url, self.token)).err() {
Some(msg) => panic!("Failed to update webhook, {}", msg),
None => info!("Updated webhook to url {}", url)
}
}
Some(url.to_string())
}
None => {
if webhook.url.len() > 0{
match self.delete_web_hook().err() {
Some(msg) => panic!("Failed to remove webhook {}", msg),
None => info!("Deleted webhook")
}
}
None
}
}
}
}
fn encode_message_string(text: &string::String) -> string::String {
percent_encoding::utf8_percent_encode(text, percent_encoding::QUERY_ENCODE_SET).collect::<String>()
}
pub struct TgmServerHandler<T : TgmMessageHandler> {
pub message_handler: T,
pub client: TgmClient,
pub uri: hyper::uri::RequestUri
}
impl<T : TgmMessageHandler> TgmServerHandler<T> {
pub fn new(uri: &str, tgm_client:TgmClient, handler:T) -> TgmServerHandler<T> {
TgmServerHandler{
message_handler: handler,
client: tgm_client,
uri: hyper::uri::RequestUri::AbsolutePath(uri.to_string())
}
}
}
impl<T : TgmMessageHandler> server::Handler for TgmServerHandler<T> {
fn handle(&self, mut req: server::Request, mut resp: server::Response) {
match req.method {
hyper::Post => {
if req.uri != self.uri {
*resp.status_mut() = hyper::status::StatusCode::NotFound;
return
}
trace!("Got request to {:?}", req.uri);
let mut res_body = String::new();
let size = req.read_to_string(&mut res_body).unwrap();
trace!("Got {:?} bytes {:?}", size, res_body);
let update_result: Result<TgmUpdate, String> =
json::decode(&res_body).map_err(|err| err.to_string());
match update_result {
Ok(upd) => {
if let Some(message) = upd.message {
let text_response = self.message_handler.process_message(&message);
debug!("Got text response {}", text_response);
let query = format!("method=sendMessage&chat_id={}&text={}",
message.from.id,
encode_message_string(&text_response)
).to_owned();
resp.headers_mut().set(hyper::header::ContentType(
mime::Mime(mime::TopLevel::Application,
mime::SubLevel::WwwFormUrlEncoded,
vec![])));
let result = resp.send(query.as_bytes());
debug!("Got resut {:?}", result)
}
}
Err(msg) => {
warn!("Failed to parse request {:?}", msg);
*resp.status_mut() = hyper::status::StatusCode::BadRequest
}
}
},
_ => *resp.status_mut() = hyper::status::StatusCode::MethodNotAllowed
}
}
}
<file_sep>/src/t11n.rs
extern crate rustc_serialize;
extern crate hyper;
extern crate url;
extern crate log;
use rustc_serialize::json;
use rustc_serialize::Decoder;
use rustc_serialize::Decodable;
use rustc_serialize::base64::ToBase64;
use rustc_serialize::base64;
use std::io::Read;
use std::sync::{Arc, RwLock};
use std::string;
use std::ops::Deref;
use hyper::status::StatusCode;
header! { (XTransmissionSessionId, "X-Transmission-Session-Id") => [String] }
#[derive(RustcEncodable)]
struct Request<T> {
method: String,
arguments:T
}
#[derive(RustcDecodable, Debug)]
struct Response<T> {
result: String,
arguments:T
}
#[derive(RustcEncodable)]
struct RequestArgAdd {
filename: String
}
#[derive(RustcEncodable)]
struct RequestArgTorrentAdd {
metainfo: String
}
#[derive(Debug)]
pub struct ResponseArgAdd {
pub added: Option<TorrentInfo>,
pub duplicate: Option<TorrentInfo>
}
impl Decodable for ResponseArgAdd {
fn decode<D: Decoder>(d: &mut D) -> Result<ResponseArgAdd, D::Error> {
d.read_struct("ResponseArgAdd", 2, |d| {
let added = try!(d.read_struct_field("torrent-added", 0, |d| { d.read_option(|d, flag| {
if flag {
TorrentInfo::decode(d).and_then(|value| Ok(Some(value)))
}else{
Ok(None)
}
})}));
let duplicate = try!(d.read_struct_field("torrent-duplicate", 0, |d| { d.read_option(|d, flag| {
if flag {
TorrentInfo::decode(d).and_then(|value| Ok(Some(value)))
}else{
Ok(None)
}
})}));
Ok(ResponseArgAdd{ added: added, duplicate: duplicate })
})
}
}
#[derive(RustcEncodable, Debug)]
struct RequestArgsGet {
fields: Vec<String>
}
#[derive(RustcEncodable, Debug)]
struct RequestArgsGetByIds {
fields: Vec<String>,
ids: Vec<i64>
}
#[derive(RustcDecodable, Debug)]
#[allow(non_snake_case)]
pub struct TorrentInfo {
pub id: i64,
pub name: Option<String>,
pub totalSize: Option<i64>,
pub percentDone: Option<f64>
}
#[derive(RustcDecodable, Debug)]
pub struct ResponseArgsGet {
pub torrents: Vec<TorrentInfo>,
}
#[derive(Clone)]
pub struct Client {
location: String,
session_id: Arc<RwLock<string::String>>,
}
impl Client {
pub fn new(location: String) -> Client {
Client{
location: location,
session_id: Arc::new(RwLock::new("".to_string())),
}
}
fn send_request_internal(&self, body:&String) -> Result<hyper::client::Response, hyper::Error> {
trace!("Sending request with body {}", body);
let session_id = self.session_id.read().unwrap().deref().clone();
let response = hyper::Client::new()
.post(&self.location)
.header(XTransmissionSessionId(session_id))
.body(body).send();
if let Err(msg) = response {
return Err(msg);
};
let res = response.unwrap();
if res.status == StatusCode::Conflict {
debug!("Got 409 conflict from transmission, refreshing session id");
if let Some(session) = res.headers.get::<XTransmissionSessionId>() {
match session {
&XTransmissionSessionId(ref value) => {
let mut session_id = self.session_id.write().unwrap();
debug!("Updating session id to {}", value.clone());
*session_id = value.clone()
}
}
return self.send_request_internal(body)
}
}
return Ok(res);
}
fn send_request(&self, body:&String) -> Result<String, String> {
let response = self.send_request_internal(body);
if let Err(msg) = response {
return Err(format!("Failed to send request: {}", msg));
};
let mut res = response.unwrap();
if res.status != StatusCode::Ok {
return Err(format!("Unexpected response status {}", res.status))
}
let mut res_body = String::new();
match res.read_to_string(&mut res_body) {
Err(msg) => {
Err(format!("Failed to read response body {}", msg))
},
Ok(_) => {
trace!("Got response {}", res_body);
Ok(res_body)
}
}
}
fn execute<Args:rustc_serialize::Encodable, Resp:rustc_serialize::Decodable>(&self, method:String, args:Args) -> Result<Resp, String> {
let request: Request<Args> = Request {
method: method,
arguments: args
};
let response_body = json::encode(&request)
.map_err(|err| err.to_string())
.and_then(|body| self.send_request(&body));
match response_body {
Ok(body) => {
let parsed_response: Result<Response<Resp>, String> =
json::decode(&body).map_err(|err| err.to_string());
match parsed_response {
Ok(response) => {
if response.result == "success" {
Ok(response.arguments)
}else{
Err("response status is not \"success\"".to_string())
}
},
Err(msg) => Err(msg)
}
},
Err(msg) => Err(msg)
}
}
pub fn add_link(&self, link:String) -> Result<ResponseArgAdd, String> {
let req_args = RequestArgAdd{
filename:link
};
let response: Result<ResponseArgAdd, String> =
self.execute(format!("torrent-add"), req_args);
trace!("Got response {:?}", response);
response
}
pub fn add_torrent(&self, torrent:Vec<u8>) -> Result<ResponseArgAdd, String> {
let serialized = torrent.to_base64(base64::STANDARD);
let req_args = RequestArgTorrentAdd {
metainfo: serialized
};
let response: Result<ResponseArgAdd, String> =
self.execute(format!("torrent-add"), req_args);
trace!("Got response {:?}", response);
response
}
pub fn get_torrents(&self) -> Result<ResponseArgsGet, String> {
let fields = vec![
"id".to_owned(),
"name".to_owned(),
"totalSize".to_owned(),
"percentDone".to_owned()
];
let req_args = RequestArgsGet {
fields: fields
};
let response: Result<ResponseArgsGet, String> =
self.execute(format!("torrent-get"), req_args);
trace!("Got response {:?}", response);
response
}
pub fn get_torrents_by_ids(&self, ids: &Vec<i64>) -> Result<ResponseArgsGet, String> {
let fields = vec![
"id".to_owned(),
"name".to_owned(),
"totalSize".to_owned(),
"percentDone".to_owned()
];
let req_args = RequestArgsGetByIds {
fields: fields,
ids: ids.clone()
};
let response: Result<ResponseArgsGet, String> =
self.execute(format!("torrent-get"), req_args);
trace!("Got response {:?}", response);
response
}
}
<file_sep>/Cargo.toml
[package]
name = "transmission_bot"
version = "0.1.0"
authors = ["<NAME> <<EMAIL>>"]
[dependencies]
hyper = "0.9.10"
rustc-serialize = "0.3"
url = "1.2.1"
log = "0.3"
env_logger = "0.3"
clap = "2.20.3"
mime = "0.2.2"
<file_sep>/Dockerfile
from scorpil/rust:1.17
RUN mkdir -p /opt/transmission_bot \
&& apt-get update \
&& apt-get install --no-install-recommends -y libssl-dev \
&& rm -rf rm -rf /var/lib/apt/lists/*
COPY . /opt/transmission_bot
RUN cd /opt/transmission_bot \
&& cargo build --release \
&& cp /opt/transmission_bot/target/release/transmission_bot /opt/bot \
&& rm -rf /opt/transmission_bot
EXPOSE 8080
ENV RUST_LOG=transmission_bot=info
ENTRYPOINT ["/opt/bot"]
CMD [""]
| a875a8ee65b97f1e2897b0972dcc87c8e215d036 | [
"TOML",
"Rust",
"Dockerfile"
] | 6 | Rust | aphreet/transmission_bot | dc4a3043353639846ace027838adc1e055ea4b71 | 251056996734d0ba7b1f35731eaf02c2ecc87cbc |
refs/heads/master | <repo_name>RC-Dynamics/robotics-speech<file_sep>/src/test/grammar_test.py
import nltk
def create_command(tree):
command = {}
command['action'] = tree[0].label()
command['entity'] = {}
if tree[1][0].label() == 'PERSON':
command['entity']['type'] = tree[1][0][0]
else:
for word in t[1][0]:
if word.label() == 'COLOR':
command['entity']['color'] = word[0]
if word.label() == 'OBJECT' or word.label() == 'FURNITURE':
command['entity']['type'] = word[0]
return command
grammar = nltk.data.load('./grammar/athome.cfg')
rd_parser = nltk.RecursiveDescentParser(grammar)
said = []
said.append('pick up the blue cup')
said.append('navigate to John')
said.append('look at the shelf')
for s in said:
tokens = nltk.word_tokenize(s)
trees = rd_parser.parse(tokens)
for t in trees:
print(t)
command = create_command(t)
print (command)<file_sep>/src/main.py
import speech_recognition as sr
import nltk
import pyttsx3
grammar = nltk.data.load('./grammar/athome.cfg')
engine = pyttsx3.init()
def create_command(tree):
command = {}
command['action'] = tree[0].label()
command['entity'] = {}
if tree[1][0].label() == 'PERSON':
command['entity']['type'] = tree[1][0][0]
else:
for word in tree[1][0]:
if word.label() == 'COLOR':
command['entity']['color'] = word[0]
if word.label() == 'OBJECT' or word.label() == 'FURNITURE':
command['entity']['type'] = word[0]
return command
def callback(recognizer, audio):
global grammar
global engine
rd_parser = nltk.RecursiveDescentParser(grammar)
try:
said = recognizer.recognize_google(audio)
print("Google Speech Recognition thinks you said " + said)
tokens = nltk.word_tokenize(said)
try:
trees = rd_parser.parse(tokens)
for t in trees:
print(t)
try:
command = create_command(t)
print (command)
engine.say(command['action']
+ (' ' + command['entity']['color'] if 'color' in command['entity'] else '')
+ ' ' + command['entity']['type'])
engine.runAndWait()
except:
engine.say('Sorry, this is not a valid command')
engine.runAndWait()
print('Malformed phrase.')
except ValueError as e:
print(e)
except sr.UnknownValueError:
engine.say('Sorry, I cannot understand what you said, could you repeat please?')
engine.runAndWait()
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
engine.say('Sorry, I cannot understand what you said, could you repeat please?')
engine.runAndWait()
print("Could not request results from Google Speech Recognition service; {0}".format(e))
def main():
r = sr.Recognizer()
m = sr.Microphone()
print('Ambient noise check.')
with m as source:
r.adjust_for_ambient_noise(source)
print('Done.')
stop_listening = r.listen_in_background(m, callback, phrase_time_limit=5)
input("Press Enter to stop...\n\n")
stop_listening(wait_for_stop=False)
engine.stop()
if __name__ == "__main__":
main()<file_sep>/src/test/recognition_test.py
import os
import json
import speech_recognition as sr
def get_files(audio_path):
audio_files = []
audio_names = []
for file_name in os.listdir(audio_path):
if file_name.endswith('.wav'):
audio_files.append(os.path.join(audio_path, file_name))
audio_names.append(file_name[:-4])
return audio_files, audio_names
def initialize_predictions(models):
predictions = { }
for key in models.keys():
predictions[key] = []
predictions['label'] = []
return predictions
def main():
r = sr.Recognizer()
models = {
'google': r.recognize_google,
'pocket_sphinx': r.recognize_sphinx
}
try:
with open('src/test/test_checkpoint.in', 'r') as checkpoint:
i = int(checkpoint.readline())
except:
i = 0
try:
with open('src/test/predictions.json') as json_file:
predictions = json.load(json_file)
except:
predictions = initialize_predictions(models)
audio_paths, audio_names = get_files('./audio_samples')
files = list(zip(audio_paths, audio_names))
while i < len(files):
audio_path, audio_name = files[i
predictions['label'].append(audio_name)]
for model_name in models.keys():
print('%s - %s' %(audio_name, model_name))
source_file = sr.AudioFile(audio_path)
with source_file as source:
audio = r.record(source)
repeat = True
while repeat:
try:
recognition = models[model_name](audio)
repeat = False
except Exception as e:
print(e)
predictions[model_name].append(recognition)
i += 1
with open('src/test/test_checkpoint.in', 'w') as checkpoint:
checkpoint.write(str(i))
with open('src/test/predictions.json', 'w+') as outfile:
json.dump(predictions, outfile)
if __name__ == "__main__":
main()<file_sep>/src/test/models_accuracy.py
import json
def main():
with open('./src/test/predictions.json', 'r') as f:
data = json.load(f)
total = len(data['label'])
google = 0
sphinx = 0
for i in range(len(data['label'])):
label = data['label'][i]
google_entry = data['google'][i]
sphinx_entry = data['pocket_sphinx'][i]
if google_entry == label:
google += 1
if sphinx_entry == label:
sphinx += 1
print('Google %d out of %d: %.4f' %(google, total, google/total))
print('Pocket Sphinx %d out of %d: %.4f' %(sphinx, total, sphinx/total))
if __name__ == "__main__":
main()<file_sep>/src/test/offline_sample.py
import speech_recognition as sr
r = sr.Recognizer()
harvard = sr.AudioFile('audio_files/harvard.wav')
with harvard as source_h:
audio_harvard = r.record(source_h)
print ('\nHarvard:')
print ('\tGoogle: ' + r.recognize_google(audio_harvard))
print ('\tPocketSphinx: ' + r.recognize_sphinx(audio_harvard))
r = sr.Recognizer()
jackhammer = sr.AudioFile('audio_files/jackhammer.wav')
with jackhammer as source_j_r:
audio_jackhammer = r.record(source_j_r)
print ('\nJack Hammer (raw):')
print ('\tGoogle: ' + r.recognize_google(audio_jackhammer))
print ('\tPocketSphinx: ' + r.recognize_sphinx(audio_jackhammer))
r = sr.Recognizer()
jackhammer = sr.AudioFile('audio_files/jackhammer.wav')
with jackhammer as source_j_f:
r.adjust_for_ambient_noise(source_j_f, duration=0.5)
audio_jackhammer = r.record(source_j_f)
print ('\nJack Hammer (filter):')
print ('\tGoogle: ' + r.recognize_google(audio_jackhammer))
print ('\tPocketSphinx: ' + r.recognize_sphinx(audio_jackhammer))<file_sep>/README.md
# Robotics Speech
## Requirements
* [Anaconda](https://www.anaconda.com/)
* [SpeechRecognition](https://github.com/Uberi/speech_recognition)
## Installation
```bash
sudo apt-get install swig libpulse-dev libasound2-dev portaudio19-dev python-pyaudio python3-pyaudio espeak
conda create -n robotics-speech python=3.7.3
conda activate robotics-speech
pip install -r requirements.txt
```
Open a python terminal and run:
```python
import nltk
nltk.download('punkt')
```
## Running
```bash
conda activate robotics-speech
python src/main.py
```<file_sep>/requirements.txt
pocketsphinx
PyAudio
nltk
SpeechRecognition
numpy
pyttsx3<file_sep>/src/test/speak.py
import pyttsx3
engine = pyttsx3.init() # object creation
engine.say("pick up blue bow")
engine.say("pick up blue bowl")
engine.runAndWait()
engine.stop()<file_sep>/src/record_samples.py
import nltk
import os
import sys
import pyaudio
import wave
import numpy as np
from nltk.parse.generate import generate
np.random.seed(199)
class Recorder(object):
'''A recorder class for recording audio to a WAV file.
Records in mono by default.
'''
def __init__(self, channels=1, rate=44100, frames_per_buffer=1024):
self.channels = channels
self.rate = rate
self.frames_per_buffer = frames_per_buffer
def open(self, fname, mode='wb'):
return RecordingFile(fname, mode, self.channels, self.rate,
self.frames_per_buffer)
class RecordingFile(object):
def __init__(self, fname, mode, channels,
rate, frames_per_buffer):
self.fname = fname
self.mode = mode
self.channels = channels
self.rate = rate
self.frames_per_buffer = frames_per_buffer
self._pa = pyaudio.PyAudio()
self.wavefile = self._prepare_file(self.fname, self.mode)
self._stream = None
def __enter__(self):
return self
def __exit__(self, exception, value, traceback):
self.close()
def record(self, duration):
# Use a stream with no callback function in blocking mode
self._stream = self._pa.open(format=pyaudio.paInt16,
channels=self.channels,
rate=self.rate,
input=True,
frames_per_buffer=self.frames_per_buffer)
for _ in range(int(self.rate / self.frames_per_buffer * duration)):
audio = self._stream.read(self.frames_per_buffer)
self.wavefile.writeframes(audio)
return None
def start_recording(self):
# Use a stream with a callback in non-blocking mode
self._stream = self._pa.open(format=pyaudio.paInt16,
channels=self.channels,
rate=self.rate,
input=True,
frames_per_buffer=self.frames_per_buffer,
stream_callback=self.get_callback())
self._stream.start_stream()
return self
def stop_recording(self):
self._stream.stop_stream()
return self
def get_callback(self):
def callback(in_data, frame_count, time_info, status):
self.wavefile.writeframes(in_data)
return in_data, pyaudio.paContinue
return callback
def close(self):
self._stream.close()
self._pa.terminate()
self.wavefile.close()
def _prepare_file(self, fname, mode='wb'):
wavefile = wave.open(fname, mode)
wavefile.setnchannels(self.channels)
wavefile.setsampwidth(self._pa.get_sample_size(pyaudio.paInt16))
wavefile.setframerate(self.rate)
return wavefile
def generate_phrases(grammar):
phrases = []
for sentence in generate(grammar, depth=10):
phrases.append(' '.join(sentence))
return phrases
if __name__ == '__main__':
grammar = nltk.data.load('./grammar/athome.cfg')
phrases = generate_phrases(grammar)
phrases = list(np.random.permutation(phrases))
rec = Recorder(channels=1)
os.system('clear')
try:
with open('audio_samples/checkpoint.in', 'r') as checkpoint:
i = int(checkpoint.readline())
except:
i = 0
while i < len(phrases):
phrase = phrases[i]
with rec.open('audio_samples/%s.wav' %(phrase), 'wb') as recfile:
os.system('clear')
input('Press enter to start recording and say: %s' %(phrase))
recfile.start_recording()
print('Please say " %s ".' %(phrase))
input('Press enter to stop recording...')
recfile.stop_recording()
os.system('clear')
i += 1
with open('audio_samples/checkpoint.in', 'w') as checkpoint:
checkpoint.write(str(i))
| 5a392db6bc44b2a3c9c1566816eb690aed63c7af | [
"Markdown",
"Python",
"Text"
] | 9 | Python | RC-Dynamics/robotics-speech | 979e696c66e649445c5b03117cb59c671794ee77 | 64aecf512013f824ea85b2af29a10d1a58edd935 |
refs/heads/master | <file_sep>//
// User.swift
// FirebaseUsers
//
// Created by <NAME> on 3/31/18.
// Copyright ยฉ 2018 <NAME>. All rights reserved.
//
import Foundation
struct User
{
var UserId: String?
var FullName: String?
var UserImage: String?
var Email: String?
}
struct Post
{
var UserId: String
var PostDescription: String
var PostImage: String
var Location: String?
var Timestamp: Double
var PostId: String
}
class CurrentUser: NSObject {
struct Static {
static var instance: CurrentUser?
}
class var sharedInstance: CurrentUser {
if Static.instance == nil
{
Static.instance = CurrentUser()
}
return Static.instance!
}
func dispose() {
CurrentUser.Static.instance = nil
print("Disposed Singleton instance")
}
private override init() {}
var userId: String!
var email: String!
var fullname: String?
var password: String?
var UserImage: String?
// var username: String?
// var website: String?
// var bio: String?
var phoneNumber: String?
// var gender: String?
// var posts: [String] = []
var following: [String] = []
// var follwers: [String] = []
}
<file_sep>//
// SignUpVC.swift
// FirebaseUsers
//
// Created by <NAME> on 3/28/18.
// Copyright ยฉ 2018 <NAME>. All rights reserved.
//
import UIKit
import FirebaseAuth
import FirebaseDatabase
import SVProgressHUD
import TWMessageBarManager
import AlamofireImage
import FirebaseStorage
class SignUpVC: UIViewController
{
@IBOutlet weak var user_image: UIImageView!
var refDatabase: DatabaseReference!
var refstorage: StorageReference!
@IBOutlet weak var fullname_tf: kTextFiledPlaceHolder!
@IBOutlet weak var phonenumber_tf: kTextFiledPlaceHolder!
@IBOutlet weak var password_tf: kTextFiledPlaceHolder!
@IBOutlet weak var email_tf: kTextFiledPlaceHolder!
let imagePicker = UIImagePickerController()
override func viewDidLoad()
{
super.viewDidLoad()
refDatabase = Database.database().reference()
refstorage = Storage.storage().reference()
title = "SIGN UP"
user_image.layer.cornerRadius = user_image.frame.height / 2
imagePicker.delegate = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func Signup_btn_Action(_ sender: Any)
{
if (email_tf.text?.isEmpty)! || (password_tf.text?.isEmpty)! || (fullname_tf.text?.isEmpty)!
{
TWMessageBarManager.sharedInstance().showMessage(withTitle: "Required Field", description: "Email, Password and Full name are required field", type: .error)
}
else
{
SVProgressHUD.show()
Auth.auth().createUser(withEmail: email_tf.text!, password: <PASSWORD>!, completion: { (user, error) in
if error == nil
{
if let fuser = user
{
self.CreateUser(uid: fuser.uid)
}
}
else
{
SVProgressHUD.dismiss()
TWMessageBarManager.sharedInstance().showMessage(withTitle: "Email & Password", description: error?.localizedDescription ?? "", type: .error)
}
})
}
}
func CreateUser(uid: String)
{
if let img = user_image.image
{
let size = CGSize(width: 110, height: 110)
let reducedsizeimg = img.af_imageScaled(to: size)
let data = UIImagePNGRepresentation(reducedsizeimg)
let metadata = StorageMetadata()
metadata.contentType = "image/png"
let imagename = "UserImage/\(uid).png"
refstorage = refstorage.child(imagename)
refstorage.putData(data!, metadata: metadata, completion: { (meta, error) in
if error == nil
{
guard let userImage = meta?.downloadURL()?.absoluteString else{
return
}
let userDic = ["UserId": uid ,"FullName": self.fullname_tf.text!, "Email" : self.email_tf.text!, "Password": <PASSWORD>!, "Phonenumber": self.phonenumber_tf.text ?? "","UserImage": userImage] as [String : Any]
self.refDatabase.child("User").child(uid).updateChildValues(userDic)
SVProgressHUD.dismiss()
TWMessageBarManager.sharedInstance().showMessage(withTitle: "Congratulations", description: "You have Successfully Created your new Account", type: .success)
self.GoToTabbarController()
}
else
{
print(error?.localizedDescription as! String)
}
})
}
}
func GoToTabbarController()
{
let obj_TabViewController = self.storyboard?.instantiateViewController(withIdentifier: "TabViewController") as! TabViewController
self.navigationController?.pushViewController(obj_TabViewController, animated: true)
}
@IBAction func PickupProfilePicture(_ sender: Any)
{
imagePicker.allowsEditing = true
if imagePicker.sourceType == .camera
{
imagePicker.sourceType = .camera
}
else
{
imagePicker.sourceType = .photoLibrary
}
present(imagePicker, animated: true, completion: nil)
}
}
extension SignUpVC:UIImagePickerControllerDelegate, UINavigationControllerDelegate
{
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage
{
user_image.image = image
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
}
<file_sep>//
// PhotoVC.swift
// FirebaseUsers
//
// Created by <NAME> on 3/31/18.
// Copyright ยฉ 2018 <NAME>. All rights reserved.
//
import UIKit
import TWMessageBarManager
import GooglePlaces
import FirebaseAuth
import SVProgressHUD
class PhotoVC: UIViewController
{
let imagePicker = UIImagePickerController()
@IBOutlet weak var location_txt: UITextField!
@IBOutlet weak var caption_text: UITextView!
@IBOutlet weak var post_img: UIImageView!
override func viewDidLoad()
{
super.viewDidLoad()
imagePicker.delegate = self
let tap = UITapGestureRecognizer(target: self, action: #selector(PhotoVC.Imagetapped))
post_img.addGestureRecognizer(tap)
post_img.isUserInteractionEnabled = true
CallImagePicker()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
@objc func Imagetapped()
{
CallImagePicker()
}
func CallImagePicker()
{
imagePicker.allowsEditing = true
if imagePicker.sourceType == .camera
{
imagePicker.sourceType = .camera
}
else
{
imagePicker.sourceType = .photoLibrary
}
present(imagePicker, animated: true, completion: nil)
}
@IBAction func Sharepost(_ sender: Any)
{
if post_img.image == nil
{
TWMessageBarManager.sharedInstance().showMessage(withTitle: "Post Image", description: "Please selcte the post image", type: .error)
}
else if caption_text.text == "write a caption...." || caption_text.text == ""
{
TWMessageBarManager.sharedInstance().showMessage(withTitle: "Caption", description: "Please decribe your post with few words", type: .error)
}
else
{
if let userid = Auth.auth().currentUser?.uid
{
SVProgressHUD.show()
GoogleDatahandler.SharedInstance.CreatePost(img: post_img.image!, caption: caption_text.text, userid: userid, Location: location_txt.text ?? "")
let tabBarController = TabViewController()
self.tabBarController?.selectedIndex = 0
}
else
{
print("Error")
}
}
}
@IBAction func Cancel_btn_for_txt(_ sender: Any)
{
location_txt.text = ""
}
}
extension PhotoVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate
{
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage
{
post_img.image = image
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
}
extension PhotoVC: GMSAutocompleteViewControllerDelegate, UITextFieldDelegate
{
func textFieldDidBeginEditing(_ textField: UITextField)
{
let autocompleteController = GMSAutocompleteViewController()
autocompleteController.delegate = self
self.present(autocompleteController, animated: true, completion: nil)
}
func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
dismiss(animated: true, completion: nil)
location_txt.text = place.name
guard let addresscomponents = place.formattedAddress?.components(separatedBy: ",") else
{
location_txt.text = place.name
return
}
if addresscomponents.count > 2
{
let count = addresscomponents.count
location_txt.text = "\(place.name),\(addresscomponents[count-2]),\(addresscomponents[count-1])" as String
}
else if addresscomponents.count > 1
{
let count = addresscomponents.count
location_txt.text = "\(place.name),\(addresscomponents[count-2]),\(addresscomponents[count - 1])" as String
}
else if addresscomponents.count == 0
{
location_txt.text = "\(place.name),\(addresscomponents[0])"
}
else
{
location_txt.text = place.name
}
}
func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
print("ERROR AUTO COMPLETE \(error)")
}
func wasCancelled(_ viewController: GMSAutocompleteViewController) {
self.dismiss(animated: true, completion: nil)
}
}
<file_sep>//
// ViewController.swift
// FirebaseUsers
//
// Created by <NAME> on 3/28/18.
// Copyright ยฉ 2018 <NAME>. All rights reserved.
//
import UIKit
import FirebaseAuth
import FirebaseDatabase
import SVProgressHUD
import TWMessageBarManager
import GoogleSignIn
class SignInViewController: BaseViewController, GIDSignInDelegate, GIDSignInUIDelegate
{
@IBOutlet weak var password_txtfield: kTextFiledPlaceHolder!
@IBOutlet weak var eamil_txtfield: kTextFiledPlaceHolder!
var refDatabase: DatabaseReference!
override func viewDidLoad()
{
super.viewDidLoad()
refDatabase = Database.database().reference()
}
@IBAction func GoogleLogin(_ sender: Any)
{
GIDSignIn.sharedInstance().delegate = self
GIDSignIn.sharedInstance().uiDelegate = self
GIDSignIn.sharedInstance().signIn()
}
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) {
// ...
if error != nil {
return
}
guard let authentication = user.authentication else { return }
let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,accessToken: authentication.accessToken)
Auth.auth().signIn(with: credential) { (user, error) in
if error != nil {
TWMessageBarManager.sharedInstance().showMessage(withTitle: "Sign-In Failure", description: error?.localizedDescription, type: .error)
return
}
else
{
if let userdata = user
{
let userDic = ["UserId": userdata.uid ,"FullName": userdata.displayName ?? "", "Email" : userdata.email!, "Password": "", "Phonenumber": userdata.phoneNumber ?? "","UserImage": userdata.photoURL?.absoluteString ?? ""] as [String : Any]
self.refDatabase.child("User").child(userdata.uid).updateChildValues(userDic, withCompletionBlock: { (error, ref) in
if error != nil
{
print(error?.localizedDescription)
}
else
{
TWMessageBarManager.sharedInstance().showMessage(withTitle: "Success", description: "You have succesfully created account", type: .success)
}
})
}
}
}
}
@IBAction func SignIn_btn(_ sender: Any)
{
if (eamil_txtfield.text?.isEmpty)! || (password_txtfield.text?.isEmpty)!
{
TWMessageBarManager.sharedInstance().showMessage(withTitle: "Required Feild", description: "Please Enter Email and Password", type: .error)
}
else
{
SVProgressHUD.show()
Auth.auth().signIn(withEmail: eamil_txtfield.text!, password: <PASSWORD>!, completion: { (user, error) in
SVProgressHUD.dismiss()
if error == nil
{
self.AfterLoginController()
}
else
{
TWMessageBarManager.sharedInstance().showMessage(withTitle: "Email & Password", description: error?.localizedDescription ?? "Please Enter Correct Email & Password.", type: .error)
}
})
}
}
func AfterLoginController()
{
let obj_TabViewController = self.storyboard?.instantiateViewController(withIdentifier: "TabViewController") as! TabViewController
self.navigationController?.pushViewController(obj_TabViewController, animated: true)
}
@IBAction func SignUp_btn_action(_ sender: Any)
{
let obj_SignUpVC = self.storyboard?.instantiateViewController(withIdentifier: "SignUpVC") as! SignUpVC
self.navigationController?.pushViewController(obj_SignUpVC, animated: true)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
<file_sep>//
// APIClient.swift
// FirebaseUsers
//
// Created by <NAME> on 3/31/18.
// Copyright ยฉ 2018 <NAME>. All rights reserved.
//
typealias completionHandler = ([User]?) -> ()
typealias userprofilecompletionHandler = (User?) -> ()
typealias postscompletionHandler = ([Post]?) -> ()
typealias FetchCurrentUserResultHandler = (CurrentUser, String?) -> ()
import Foundation
import FirebaseAuth
import FirebaseDatabase
import FirebaseStorage
import AlamofireImage
import SVProgressHUD
import TWMessageBarManager
class GoogleDatahandler: NSObject
{
private override init(){}
static let SharedInstance = GoogleDatahandler()
var currentuser = CurrentUser.sharedInstance
var refstorage: StorageReference?
var refDatabase = Database.database().reference()
func getAllUsers(completion: @escaping completionHandler)
{
if let userid = Auth.auth().currentUser?.uid
{
refDatabase.child("User").observeSingleEvent(of: .value, with: { (snapshot) in
guard let value = snapshot.value as? Dictionary<String,Any> else
{
return
}
var arr: Array<User> = []
for item in value
{
if let userdata = item.value as? Dictionary<String,String>
{
if userdata["UserId"] == userid
{
}
else
{
arr.append(User(UserId: userdata["UserId"], FullName: userdata["FullName"], UserImage: userdata["UserImage"], Email: userdata["Email"]))
}
}
}
completion(arr)
})
}
else
{
completion(nil)
}
}
func getUserProfile(completion: @escaping userprofilecompletionHandler )
{
if let userid = Auth.auth().currentUser?.uid
{
refDatabase.child("User/\(userid)").observeSingleEvent(of: .value, with: { (snapshot) in
guard let value = snapshot.value as? Dictionary<String,String> else
{
return
}
var obj_User_profile: User?
print(value)
obj_User_profile = User(UserId: value["UserId"], FullName: value["FullName"], UserImage: value["UserImage"], Email: value["Email"])
completion(obj_User_profile)
})
}
else
{
completion(nil)
}
}
func fetchCurrentUserData(uid: String, completion: FetchCurrentUserResultHandler?) {
var errorMessage: String?
//refDatabase = Database.database().reference()
//guard let id = Auth.auth().currentUser?.uid else { return }
refDatabase.child("User/\(uid)").observeSingleEvent(of: .value) { [weak self] (snapshot) in
guard let strongSelf = self else { return }
if let userObj = snapshot.value as? Dictionary<String,Any?>,
let fullName = userObj["FullName"],
let email = userObj["Email"],
let password = userObj["<PASSWORD>"],
let phoneNumber = userObj["Phonenumber"],
let userimageStr = userObj["UserImage"]
{
strongSelf.currentuser.userId = uid
strongSelf.currentuser.fullname = fullName as? String
strongSelf.currentuser.email = email as! String
strongSelf.currentuser.UserImage = userimageStr as? String
strongSelf.currentuser.password = <PASSWORD> as? String
strongSelf.currentuser.phoneNumber = phoneNumber as? String
self?.refDatabase.child("User/\(uid)").observe(.value, with: { (snapshot) in
if let publicUserDict = snapshot.value as? [String: Any] {
if let followingDict = publicUserDict["following"] as? [String: Bool] {
for val in followingDict{
strongSelf.currentuser.following.append(val.key)
}
}
else {
errorMessage = "No following users"
}
completion?((self?.currentuser)!, errorMessage)
} else {
errorMessage = "Error pasing public user data"
}
})
} else {
errorMessage = "Error pasing user data"
}
}
}
func CreatePost(img: UIImage, caption: String,userid: String, Location: String?)
{
refDatabase = Database.database().reference()
refstorage = Storage.storage().reference()
let reducedsizeimg = img.af_imageScaled(to: CGSize(width: 426, height: 240))
let data = UIImagePNGRepresentation(reducedsizeimg)
let metadata = StorageMetadata()
metadata.contentType = "image/png"
let postkey = refDatabase.child("Post").childByAutoId().key
print(postkey)
let imagename = "PostImage/\(postkey).png"
refstorage = refstorage?.child(imagename)
let timestamp = Date().timeIntervalSince1970
let PostDic = ["UserId": userid ,"PostDescription": caption, "PostImage" : "", "Location": Location ?? "", "Timestamp": timestamp] as [String : Any]
self.refDatabase.child("Post").child(postkey).updateChildValues(PostDic)
self.refstorage?.putData(data!, metadata: metadata, completion: { (meta, error) in
SVProgressHUD.dismiss()
TWMessageBarManager.sharedInstance().showMessage(withTitle: "Congratulations", description: "You have succesfully created a post", type: .success)
if error == nil
{
if let imageData = meta?.downloadURL()?.absoluteString
{
self.refDatabase.child("Post/\(postkey)/PostImage").setValue(imageData)
}
}
})
}
func getAllPost(completion: @escaping postscompletionHandler)
{
//refDatabase = Database.database().reference()
refDatabase.child("Post").observeSingleEvent(of: .value, with: { (snapshot) in
let postid = self.refDatabase.child("Post").key
guard let value = snapshot.value as? Dictionary<String,Any> else
{
return
}
var arr: Array<Post> = []
for item in value
{
if let userdata = item.value as? Dictionary<String,Any>
{
arr.append(Post(UserId: userdata["UserId"]! as! String, PostDescription: userdata["PostDescription"]! as! String, PostImage: userdata["PostImage"]! as! String, Location: userdata["Location"] as? String, Timestamp: userdata["Timestamp"]! as! Double, PostId: postid))
}
}
arr.sort(by: {$0.Timestamp > $1.Timestamp})
completion(arr)
})
}
func followUser(uid: String, followinguid: String)
{
let userdic = [followinguid: true] as [String : Bool]
refDatabase.child("User/\(uid)").child("following").updateChildValues(userdic)
}
func removeuserformfollowing(uid: String, followinguid: String)
{
refDatabase.child("User/\(uid)").child("following").child(followinguid).removeValue()
}
func getUserData(userid: String, completion: @escaping userprofilecompletionHandler)
{
refDatabase.child("User/\(userid)").observeSingleEvent(of: .value, with: { (snapshot) in
guard let value = snapshot.value as? Dictionary<String,String> else
{
return
}
var obj_User_profile: User?
obj_User_profile = User(UserId: value["UserId"], FullName: value["FullName"], UserImage: value["UserImage"], Email: value["Email"])
completion(obj_User_profile)
})
}
}
<file_sep>//
// ProfileVC.swift
// FirebaseUsers
//
// Created by <NAME> on 3/31/18.
// Copyright ยฉ 2018 <NAME>. All rights reserved.
//
import UIKit
class ProfileVC: UIViewController
{
@IBOutlet weak var user_image: UIImageView!
var user_profile: User?
@IBOutlet weak var posts_lbl: UILabel!
@IBOutlet weak var user_name_lbl: UILabel!
override func viewDidLoad()
{
super.viewDidLoad()
user_image.layer.cornerRadius = user_image.frame.size.height / 2
GetUserProfileData()
print(CurrentUser.sharedInstance)
print(CurrentUser.sharedInstance.email)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func Edit_profile_btn(_ sender: Any)
{
}
func GetUserProfileData()
{
GoogleDatahandler.SharedInstance.getUserProfile { (userprofile) in
if let url = URL(string: (userprofile?.UserImage)!)
{
DispatchQueue.global().async
{
if let data = try? Data(contentsOf: url)
{
DispatchQueue.main.async {
self.user_image.image = UIImage(data: data)
}
}
}
self.user_name_lbl.text = userprofile?.FullName
}
}
}
}
<file_sep>//
// PostTableViewCell.swift
// FirebaseUsers
//
// Created by <NAME> on 4/2/18.
// Copyright ยฉ 2018 <NAME>. All rights reserved.
//
import UIKit
class PostTableViewCell: UITableViewCell
{
@IBOutlet weak var user_name: UILabel!
@IBOutlet weak var user_image: UIImageView!
@IBOutlet weak var post_image: UIImageView!
@IBOutlet weak var post_description: UILabel!
override func awakeFromNib()
{
super.awakeFromNib()
user_image.layer.cornerRadius = user_image.frame.size.height / 2
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep>//
// CreatePostVC.swift
// FirebaseUsers
//
// Created by <NAME> on 4/3/18.
// Copyright ยฉ 2018 <NAME>. All rights reserved.
//
import UIKit
class CreatePostVC: UIViewController
{
@IBOutlet weak var location_txt: UITextField!
@IBOutlet weak var caption_text: UITextView!
@IBOutlet weak var post_img: UIImageView!
override func viewDidLoad()
{
super.viewDidLoad()
// navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Share", style: .plain, target: self, action: #selector(sharePostAction))
// Do any additional setup after loading the view.
}
// @objc func sharePostAction()
// {
// if post_img.image == nil
// {
// TWMessageBarManager.sharedInstance().showMessage(withTitle: "Post Image", description: "Please selcte the post image", type: .error)
// }
// else if caption_text.text == "write a caption...." || caption_text.text == ""
// {
// TWMessageBarManager.sharedInstance().showMessage(withTitle: "Caption", description: "Please decribe your post with few words", type: .error)
// }
// else
// {
// if let userid = Auth.auth().currentUser?.uid
// {
// SVProgressHUD.show()
// GoogleDatahandler.SharedInstance.CreatePost(img: post_img.image!, caption: caption_text.text, userid: userid, Location: location_txt.text ?? "")
// let tabBarController = TabViewController()
// self.tabBarController?.selectedIndex = 0
// }
// else
// {
// print("Error")
// }
// }
// }
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// func CallImagePicker()
// {
// imagePicker.allowsEditing = true
// if imagePicker.sourceType == .camera
// {
// imagePicker.sourceType = .camera
// }
// else
// {
// imagePicker.sourceType = .photoLibrary
// }
// present(imagePicker, animated: true, completion: nil)
// }
}
<file_sep>//
// UsersVC.swift
// FirebaseUsers
//
// Created by <NAME> on 3/31/18.
// Copyright ยฉ 2018 <NAME>. All rights reserved.
//
import UIKit
import SDWebImage
class UsersVC: UIViewController {
@IBOutlet weak var Users_tableview: UITableView!
var arrUsers: Array<User>?
override func viewDidLoad()
{
super.viewDidLoad()
title = "Users"
GetTableData()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func GetTableData()
{
GoogleDatahandler.SharedInstance.getAllUsers { (UsersArr) in
self.arrUsers = UsersArr
DispatchQueue.main.async {
self.Users_tableview.reloadData()
}
}
}
}
extension UsersVC: UITableViewDelegate, UITableViewDataSource
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if arrUsers == nil
{
return 0
}
else
{
return (arrUsers?.count)!
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! UsersTableViewCell
let user = arrUsers![indexPath.row]
cell.user_email.text = user.Email
cell.user_name.text = user.FullName
let url = URL(string: user.UserImage!)
cell.user_img.sd_setImage(with: url!, completed: nil)
cell.follow_btn.isSelected = GoogleDatahandler.SharedInstance.currentuser.following.contains(user.UserId!)
cell.follow_btn.tag = indexPath.row
cell.follow_btn.addTarget(self, action: #selector(followbtnAction), for: .touchUpInside)
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
return "Suggestions For You"
}
@objc func followbtnAction(sender: UIButton)
{
sender.isSelected = !sender.isSelected
let userProfile = arrUsers?[sender.tag]
let uid = CurrentUser.sharedInstance.userId
if !sender.isSelected
{
GoogleDatahandler.SharedInstance.removeuserformfollowing(uid: uid!, followinguid: (userProfile?.UserId!)!)
}
else
{
GoogleDatahandler.SharedInstance.followUser(uid: uid!, followinguid: (userProfile?.UserId!)! )
}
}
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.tintColor = UIColor.white
}
}
<file_sep>//
// UsersTableViewCell.swift
// FirebaseUsers
//
// Created by <NAME> on 3/31/18.
// Copyright ยฉ 2018 <NAME>. All rights reserved.
//
import UIKit
class UsersTableViewCell: UITableViewCell
{
@IBOutlet weak var user_email: UILabel!
@IBOutlet weak var user_img: UIImageView!
@IBOutlet weak var user_name: UILabel!
@IBOutlet weak var follow_btn: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
user_img.layer.cornerRadius = user_img.frame.size.width / 2
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep>//
// HomeVC.swift
// FirebaseUsers
//
// Created by <NAME> on 3/31/18.
// Copyright ยฉ 2018 <NAME>. All rights reserved.
//
import UIKit
import SDWebImage
import Firebase
import GooglePlaces
import GoogleSignIn
class HomeVC: UIViewController
{
@IBOutlet weak var post_tableview: UITableView!
var Posrarr: Array<Post>?
override func viewDidLoad()
{
super.viewDidLoad()
GetCurrentUserProfile()
// GetAllPosts()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func GetCurrentUserProfile()
{
if let uid = Auth.auth().currentUser?.uid
{
GoogleDatahandler.SharedInstance.fetchCurrentUserData(uid: uid, completion: { (obj_currentUser, error) in
print(obj_currentUser.email)
print(obj_currentUser.fullname ?? "No Full name")
print(obj_currentUser.following.count)
})
}
else if let uid = GIDSignIn.sharedInstance().currentUser.userID
{
GoogleDatahandler.SharedInstance.fetchCurrentUserData(uid: uid, completion: { (obj_currentUser, error) in
print(obj_currentUser.email)
})
}
}
func GetAllPosts()
{
GoogleDatahandler.SharedInstance.getAllPost { (postarr) in
self.Posrarr = postarr
DispatchQueue.main.async {
self.post_tableview.reloadData()
}
}
}
override func viewWillAppear(_ animated: Bool)
{
post_tableview.reloadData()
}
@IBAction func AddNewPost(_ sender: Any)
{
let obj_CreatePostVC = self.storyboard?.instantiateViewController(withIdentifier: "CreatePostVC") as! CreatePostVC
self.navigationController?.pushViewController(obj_CreatePostVC, animated: true)
}
}
extension HomeVC: UITableViewDelegate,UITableViewDataSource
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
guard let arr = Posrarr else
{
return 0
}
return arr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "postcell") as! PostTableViewCell
cell.post_description.text = Posrarr![indexPath.row].PostDescription
let url = URL(string: Posrarr![indexPath.row].PostImage)
cell.post_image.sd_setImage(with: url!, completed: nil)
let userid = Posrarr![indexPath.row].UserId
GoogleDatahandler.SharedInstance.getUserData(userid: userid) { (User) in
let url = URL(string: (User?.UserImage)!)
cell.user_name.text = (User?.FullName)!
cell.user_image.sd_setImage(with: url!, completed: nil)
}
return cell
}
}
<file_sep>//
// Constants.swift
// FirebaseUsers
//
// Created by <NAME> on 4/1/18.
// Copyright ยฉ 2018 <NAME>. All rights reserved.
//
import Foundation
class Constants
{
let googlePlacesAPI = "<KEY>"
}
<file_sep># Un/Users/viren8694/Desktop/RJT_Program/Assignments/FirebaseUsers/Podfilecomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'FirebaseUsers' do
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!
pod 'Firebase/Core'
pod 'Firebase/Auth'
pod 'Firebase/Database'
pod 'SVProgressHUD'
pod 'TWMessageBarManager'
pod 'AlamofireImage', '~> 3.3'
pod 'Firebase/Storage'
pod 'GooglePlaces'
pod 'SDWebImage','~> 4.0'
pod 'GoogleSignIn'
# Pods for FirebaseUsers
target 'FirebaseUsersTests' do
inherit! :search_paths
# Pods for testing
end
target 'FirebaseUsersUITests' do
inherit! :search_paths
# Pods for testing
end
end
| c3b64eecb07407d8c5f0e9eb248fef2efbd05922 | [
"Swift",
"Ruby"
] | 13 | Swift | viren8694/InstagramRepo | eb35ed5880595d6011f1e9de3e5baa94dff9c278 | ca09ba14cf4976e4188d0253886c3662a9f0ce5a |
refs/heads/master | <repo_name>dongyingCN/easyMVC<file_sep>/mvcDemo/src/mvc/ext/utils/ClassFileScanner.java
package mvc.ext.utils;
import java.io.File;
import java.net.URL;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/**
* ๆซๆๆๆclassๆไปถ๏ผๅนถๅฐ่ทฏๅพ่ฝฌๆขไธบpackgeName + className ็ๅฝขๅผ๏ผไปฅไพฟ็จไบๅๅฐ
* @author ying.dong
*
*/
public class ClassFileScanner {
//windows :C:\Users\Administrator\Desktop\mvcDemo\build\classes
//linux or mac: \Users\Administrator\Desktop\mvcDemo\build\classes\
private static final String APP_CLASS_PATH = new File(Thread.currentThread().getContextClassLoader().getResource("").getPath()).getAbsolutePath();
private static final String CLASS_SUFFIX = ".class";
public static void main(String[] args) {
Set<String> set = scanClassFiles();
for(String fileName: set) {
System.out.println(fileName);
}
}
/**
* ้ๅฝๆซๆๆๆclassๆไปถ
* @param file
* @return
*/
private static Collection<String> getAllClassFile(File file, Collection<String> collection) {
if(file.isFile() && file.getName().endsWith(CLASS_SUFFIX)) {
collection.add(parseClassFileToFullName(file));
} else {
File[] files = file.listFiles();
for(File tempFile: files) {
getAllClassFile(tempFile, collection);
}
}
return collection;
}
/**
* ๅฐclass็่ทฏๅพๅ่ฝฌๆขไธบpackage
* @param file
* @return
*/
private static String parseClassFileToFullName(File file) {
StringBuilder fileNameSb = new StringBuilder(file.getPath());
if (fileNameSb.toString().startsWith(APP_CLASS_PATH)) {
fileNameSb.delete(0, APP_CLASS_PATH.length());
//่ฟๆปคclassๆไปถๅนถ่ฝฌๆขๆไปถๅไธบpackageName + className
if(fileNameSb.toString().endsWith(CLASS_SUFFIX)) {
fileNameSb.delete(fileNameSb.length() - CLASS_SUFFIX.length(), fileNameSb.length());
}
}
String fileName = fileNameSb.toString().replace(File.separator, ".");
if (fileName.startsWith(".")) {
fileName = fileName.substring(1, fileName.length());
}
return fileName;
}
/**
* ๆซๆๆๆclassๆไปถ๏ผๅนถๅฐ่ทฏๅพ่ฝฌๆขไธบpackgeName + className ็ๅฝขๅผ
* @return
*/
public static Set<String> scanClassFiles() {
URL dir = Thread.currentThread().getContextClassLoader().getResource("");
Set<String> fileNameSet = new HashSet<>();
if(dir.getProtocol().equals("file")) {
File pathFile = new File(APP_CLASS_PATH);
getAllClassFile(pathFile, fileNameSet);
}
return fileNameSet;
}
}
<file_sep>/mvcDemo/src/mvc/core/handlers/HandlerFactory.java
package mvc.core.handlers;
import java.lang.annotation.Annotation;
import java.util.Map;
import java.util.Map.Entry;
/**
* ๅๅปบhandlerๅฏน่ฑก๏ผ ๅนถ่ฎพๅฎnextHandler
* @author ying.dong
*
*/
public class HandlerFactory {
//handler ่ฎกๆฐ
private static int countHandlers = 0;
private HandlerFactory() {}
/**
* ๅฎไพๅHandler
* @param handlersClassMap
* @return
* @throws InstantiationException
* @throws IllegalAccessException
*/
public static Handlers getHandler(Map<Class<?>, Annotation> handlersClassMap) throws InstantiationException, IllegalAccessException {
//็ฌฌไธไธช
Handlers firstHandler = null;
//ไธไธไธช
Handlers lastHandler = null;
for(Entry<Class<?>, Annotation> entry: handlersClassMap.entrySet()) {
Handlers tempHandler = (Handlers) entry.getKey().newInstance();
//็ฌฌไธๆฌกๅพช็ฏ็handler ่ฎพ็ฝฎไธบ็ฌฌไธไธช
if(countHandlers == 0) {
firstHandler = tempHandler;
lastHandler = tempHandler;
} else {
//่ฎพ็ฝฎไธไธไธชhandler
lastHandler.nextHandler = tempHandler;
lastHandler = tempHandler;
}
countHandlers++;
}
countHandlers = 0;
return firstHandler;
}
}
<file_sep>/mvcDemo/src/mvc/core/annotations/AnnotationResolver.java
package mvc.core.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* ็จไปฅๆ ๆณจAnnotation็ๅค็ๅจ
* @author ying.dong
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface AnnotationResolver {
}
<file_sep>/README.md
easyMVC
=======
easyMVC for java annotation
<file_sep>/mvcDemo/src/mvc/core/ApplicationContext.java
package mvc.core;
import java.lang.reflect.Method;
import java.util.Map;
import mvc.core.handlers.Handlers;
/**
*
* @author ying.dong
*
*/
public class ApplicationContext {
private static ApplicationContext applicationContext;
//ๅฏนhandler็ๆๆ
private Handlers handler;
//ๅฏนๆ ๅฐ็ๆๆ
private Map<String, Method> requestMappingMap;
//ไฟๅญmethodๅฏนๅบ็Object
private Map<Method, Object> controllerMethodMatchedMap;
//ไฟๅญcontroller็ๅฎไพ
private Map<String, Object> controllerInstanceMap;
private ApplicationContext(){}
public synchronized static ApplicationContext getInstance() {
if(applicationContext == null) {
applicationContext = new ApplicationContext();
}
return applicationContext;
}
public Handlers getHandler() {
return handler;
}
public void setHandler(Handlers handler) {
this.handler = handler;
}
public Map<String, Method> getRequestMappingMap() {
return requestMappingMap;
}
public void setRequestMappingMap(Map<String, Method> requestMappingMap) {
this.requestMappingMap = requestMappingMap;
}
public Map<Method, Object> getControllerMethodMatchedMap() {
return controllerMethodMatchedMap;
}
public void setControllerMethodMatchedMap(
Map<Method, Object> controllerMethodMatchedMap) {
this.controllerMethodMatchedMap = controllerMethodMatchedMap;
}
public Map<String, Object> getControllerInstanceMap() {
return controllerInstanceMap;
}
public void setControllerInstanceMap(Map<String, Object> controllerInstanceMap) {
this.controllerInstanceMap = controllerInstanceMap;
}
}
<file_sep>/mvcDemo/src/mvc/test/handlers/TestHandler.java
package mvc.test.handlers;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mvc.core.annotations.Handler;
import mvc.core.handlers.Handlers;
@Handler
public class TestHandler extends Handlers{
@Override
public void doHandle(HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
System.out.println("----------------่ชๅฎไนhandlerๆง่กโโโโโโ");
}
}
| 900894fb5efcaf012392ecc075da72212737a17f | [
"Markdown",
"Java"
] | 6 | Java | dongyingCN/easyMVC | 625b00c1ae90d8ab0cd20cfc2dd94a4728ca7e5f | ab58e58fd5433f29de274171e4d6bdc6db69a19a |
refs/heads/master | <file_sep>
ElasticFilms is a film search engine made with ElasticSearch and Flask.
<file_sep># Libraries
import pandas as pd
import json
from elasticsearch import Elasticsearch
from flask import Flask, render_template, request
app = Flask(__name__)
#---------------------------------------------------------------------
# Get data frame with data from movies
df = pd.read_csv('western.csv', sep=';')
es = Elasticsearch()
es.indices.create(index="western", ignore=400)
# Index all the movies in ElasticSearch
for i in range(1, len(df.index)):
es.index(index='western', doc_type='movie', body={
'id': i,
'title': df.loc[i]['title'],
'plot': df.loc[i]['plot']
})
#---------------------------------------------------------------------
@app.route('/', methods=["GET", "POST"])
def home():
if request.method == "GET":
return render_template("home.html")
if request.method == "POST":
query = request.form["query"]
# Query with ElasticSearch and get first three items with best score
movies=es.search(
index='western',
body={"query": {
"multi_match": {
"fields": [ "title", "plot" ],
"query": query,
"fuzziness": "AUTO"
}
},
"highlight": {
"fields": {
"title": {"number_of_fragments": 0},
"plot": {"number_of_fragments": 0}
}
}
},
size=3
)
return render_template("home.html", western=movies)
if __name__ == "__main__":
app.run()
# Clear movie index from ElasticSearch
es.indices.delete(index='western', ignore=[400, 404])
| 6d049c3cfc36da8ca8a8e5d07f5adee4203ad83b | [
"Markdown",
"Python"
] | 2 | Markdown | AxelJunes/ElasticFilms | 9fbcfb758ece59a780de88f96a4e06ca3fd5912d | 7b43e40faf4d6ce658ebbbc302d7c7a297fa9d19 |
refs/heads/master | <repo_name>MatusRubicky/DETUZO<file_sep>/DETUZO/app/src/main/java/com/example/matusrubicky/detuzo/GPSLogger.java
package com.example.matusrubicky.detuzo;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import com.getbase.floatingactionbutton.FloatingActionButton;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;
import org.joda.time.DateTime;
import org.joda.time.Hours;
import org.joda.time.Minutes;
import org.joda.time.Seconds;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import io.ticofab.androidgpxparser.parser.domain.TrackPoint;
public class GPSLogger extends FragmentActivity implements OnMapReadyCallback, GPSResultReceiver.Receiver {
GoogleMap mMap;
DecimalFormat f = new DecimalFormat("0.00");
GPSResultReceiver resultReceiver;
Intent intent;
List<TrackPoint> list;
String timeToSend;
DateTime time;
TextView cas;
TextView vzd;
double distance = 0d;
private double lat;
private double lng;
private double ele;
boolean recording = false;
String bikeType = "road"; // road, mtb
String hours;
String minutes;
String seconds;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapGPS);
mapFragment.getMapAsync(this);
list = new ArrayList<>();
cas = (TextView) findViewById(R.id.cas);
vzd = (TextView) findViewById(R.id.vzd);
resultReceiver = new GPSResultReceiver(new Handler());
resultReceiver.setReceiver(this);
final FloatingActionButton start = (FloatingActionButton) findViewById(R.id.start);
start.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!recording) {
recording = true;
onStartService();
time = DateTime.now();
start.setIcon(R.drawable.stop);
} else {
onStopService();
start.setIcon(R.drawable.play);
showDialog();
}
}
});
}
public void onStartService() {
intent = new Intent(this, GPSLoggerService.class);
intent.putExtra("receiverTag", resultReceiver);
time = DateTime.now();
startService(intent);
}
public void onStopService(){
recording = false;
stopService(intent);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
@Override
public void onReceiveResult(int resultCode, Bundle resultData) {
if (Hours.hoursBetween(time, DateTime.now()).getHours() < 10) {
hours = "0" + Hours.hoursBetween(time, DateTime.now()).getHours();
} else {
hours = "" + Hours.hoursBetween(time, DateTime.now()).getHours();
}
if (Minutes.minutesBetween(time, DateTime.now()).getMinutes() % 60 < 10) {
minutes = "0" + Minutes.minutesBetween(time, DateTime.now()).getMinutes() % 60;
} else {
minutes = "" + Minutes.minutesBetween(time, DateTime.now()).getMinutes() % 60;
}
if (Seconds.secondsBetween(time, DateTime.now()).getSeconds() % 60 < 10) {
seconds = "0" + Seconds.secondsBetween(time, DateTime.now()).getSeconds() % 60;
} else {
seconds = "" + Seconds.secondsBetween(time, DateTime.now()).getSeconds() % 60;
}
cas.setText(hours + ":" + minutes + ":" + seconds);
if(Integer.parseInt(seconds)%3 == 0) {
lat = resultData.getDouble("lat");
lng = resultData.getDouble("lng");
ele = resultData.getDouble("ele");
list.add(new TrackPoint.Builder().setLatitude(lat).
setLongitude(lng).setTime(DateTime.now()).setElevation(ele).build());
if (list.size() > 1)
distance += Logic.distance(lat, lng, list.get(list.size() - 2).getLatitude(), list.get(list.size() - 2).getLongitude(), "K");
vzd.setText(f.format(distance) + " km");
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
TrackPoint point = list.get(list.size() - 1);
LatLng ll = new LatLng(point.getLatitude(), point.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(ll).icon(BitmapDescriptorFactory.fromResource(R.drawable.bikemarker)));
//options.add(ll);
builder.include(ll);
//Polyline line = mMap.addPolyline(options);
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 100));
// Remove listener to prevent position reset on camera move.
mMap.setOnCameraChangeListener(null);
}
timeToSend = String.valueOf(Minutes.minutesBetween(time, DateTime.now()).getMinutes());
NotificationCompat.Builder notifBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.record)
.setContentTitle("Recording ride...")
.setContentText(hours + ":" + minutes + ":" + seconds + ", " + f.format(distance) + " km");
Intent targetIntent = new Intent(this, GPSLogger.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notifBuilder.setContentIntent(contentIntent);
notifBuilder.addAction(R.drawable.stopmini, "Stop", contentIntent);
NotificationManager nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nManager.notify(7777, notifBuilder.build());
}
public void showDialog(){
final EditText editTextName = new EditText(this);
new AlertDialog.Builder(this)
.setTitle("Zadajte nรกzov")
.setView(editTextName)
.setPositiveButton("Uloลพiลฅ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
try {
String subor = Logic.saveGPX(list, new Date().toString());
Intent myIntent = new Intent(GPSLogger.this, ScrollingActivity.class);
myIntent.putExtra("cestaKSuboru", subor);
myIntent.putExtra("name", String.valueOf(editTextName.getText()));
myIntent.putExtra("cas", timeToSend+ " min");
myIntent.putExtra("type", bikeType);
startActivity(myIntent);
} catch (IOException e) {
e.printStackTrace();
}
}
})
.setNegativeButton("Storno", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Intent myIntent = new Intent(GPSLogger.this, ScrollingActivity.class);
startActivity(myIntent);
}
})
.show();
}
}<file_sep>/DETUZO/app/src/main/java/com/example/matusrubicky/detuzo/DETUZODatabaseOpenHelper.java
package com.example.matusrubicky.detuzo;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class DETUZODatabaseOpenHelper extends SQLiteOpenHelper {
public DETUZODatabaseOpenHelper(Context context) {
super(context, "DETUZO", null, 8);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE %s (" +
"%s INTEGER PRIMARY KEY AUTOINCREMENT,"+
"%s NAME," + "%s TIME," +"%s SPEED," + "%s ELEVATION," + "%s PATH" +
")";
db.execSQL(String.format(sql,
DETUZO.route.TABLE_NAME,
DETUZO.route._ID,
DETUZO.route.NAME,
DETUZO.route.TIME,
DETUZO.route.SPEED,
DETUZO.route.ELEVATION,
DETUZO.route.PATH
));
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+DETUZO.route.TABLE_NAME);
onCreate(db);
}
public List<String> getAllPaths() {
List<String> list = new ArrayList<>();
String selectQuery = "SELECT "+DETUZO.route.PATH+" FROM " + DETUZO.route.TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
String path = cursor.getString(0);
list.add(path);
} while (cursor.moveToNext());
}
cursor.close();
Collections.reverse(list);
return list;
}
}<file_sep>/DETUZO/app/src/main/java/com/example/matusrubicky/detuzo/MapsActivity.java
package com.example.matusrubicky.detuzo;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import org.xml.sax.SAXException;
import org.xmlpull.v1.XmlPullParserException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import io.ticofab.androidgpxparser.parser.GPXParser;
import io.ticofab.androidgpxparser.parser.domain.Gpx;
import io.ticofab.androidgpxparser.parser.domain.TrackPoint;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private File subor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Bundle extras = getIntent().getExtras();
subor = new File(extras.getString("route"));
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
List<TrackPoint> list = null;
if (subor.getAbsolutePath().endsWith(".gpx")){
list = makeRouteFromGpx(subor.getAbsolutePath());
}else{
list = makeRouteFromXml(subor.getAbsolutePath());
}
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
PolylineOptions options = new PolylineOptions().width(5).color(Color.parseColor("#FF7711")).geodesic(true);
for (int z = 0; z < list.size(); z++) {
TrackPoint point = list.get(z);
LatLng ll = new LatLng(point.getLatitude(), point.getLongitude());
options.add(ll);
builder.include(ll);
}
if (list.size() >1) {
mMap.addPolyline(options);
mMap.addMarker(new MarkerOptions().
position(new LatLng(list.get(0).getLatitude(), list.get(0).getLongitude())).icon(BitmapDescriptorFactory.fromResource(R.drawable.start)));
mMap.addMarker(new MarkerOptions().
position(new LatLng(list.get(list.size() - 1).getLatitude(), list.get(list.size() - 1).getLongitude())).icon(BitmapDescriptorFactory.fromResource(R.drawable.finish)));
mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition arg0) {
// Move camera.
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 50));
// Remove listener to prevent position reset on camera move.
mMap.setOnCameraChangeListener(null);
}
});
}
}
public static List<TrackPoint> makeRouteFromGpx(String subor) {
GPXParser parser = new GPXParser();
Gpx parsedGpx = null;
List<TrackPoint> list = null;
try {
InputStream in = new FileInputStream(subor);
parsedGpx = parser.parse(in);
} catch (IOException | XmlPullParserException e) {
e.printStackTrace();
}
if (parsedGpx == null) {
// error parsing track
} else {
list = parsedGpx.getTracks().get(0).getTrackSegments().get(0).getTrackPoints();
}
return list;
}
public static List<TrackPoint> makeRouteFromXml(String subor) {
try {
return Logic.parseFromXML(subor);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
return null;
}
}<file_sep>/DETUZO/app/build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "com.example.matusrubicky.detuzo"
minSdkVersion 14
targetSdkVersion 23
versionCode 1
versionName "1.0"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:design:23.4.0'
compile 'com.google.android.gms:play-services:9.0.0'
compile 'com.google.maps.android:android-maps-utils:0.3+'
compile 'io.ticofab.androidgpxparser:parser:0.1.4'
compile 'com.nbsp:library:1.08'
compile 'com.android.support:multidex:1.0.0'
compile 'com.getbase:floatingactionbutton:1.10.1'
compile 'junit:junit:4.12'
compile files('src/libs/gpxparser-20130603.jar')
compile 'commons-logging:commons-logging:1.2'
compile 'org.apache.logging.log4j:log4j-core:2.5'
compile 'org.slf4j:slf4j-log4j12:1.7.16'
}
repositories {
maven {
url "http://dl.bintray.com/lukaville/maven"
}
}<file_sep>/DETUZO/app/src/main/java/com/example/matusrubicky/detuzo/GPSLoggerService.java
package com.example.matusrubicky.detuzo;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.os.ResultReceiver;
public class GPSLoggerService extends IntentService implements LocationListener {
private static final long TIME = 1000; //1 seconds
private LocationManager locationManager;
Location loc;
Intent intent;
ResultReceiver rec;
Bundle b;
public GPSLoggerService() {
super(GPSLoggerService.class.getSimpleName());
}
public GPSLoggerService(String name) {
super(name);
}
@Override
protected void onHandleIntent(Intent intent) {
rec = intent.getParcelableExtra("receiverTag");
b = new Bundle();
}
@Override
public void onCreate() {
super.onCreate();
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, TIME, 0, this);
}
@Override
public void onLocationChanged(Location loc) {
if (loc != null) {
double lat = loc.getLatitude();
double lng = loc.getLongitude();
b.putDouble("lat", lat);
b.putDouble("lng", lng);
double time = loc.getTime();
double ele = loc.getAltitude();
b.putDouble("time", time);
b.putDouble("ele", ele);
rec.send(0, b);
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
| 15498526fa5ce08595d615b8d4cd1e96e32231e1 | [
"Java",
"Gradle"
] | 5 | Java | MatusRubicky/DETUZO | dd7d6299e4f10dd4ab151d54220fa86c9b0facf0 | bf17eb36b9adcc530f4367f300707581cb00560a |
refs/heads/master | <file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { pruebaRouting } from './prueba.routing';
import {SmartadminModule} from "../shared/smartadmin.module";
import {pruebaComponent} from "./prueba.component";
import {MorrisGraphModule} from "../shared/graphs/morris-graph/morris-graph.module";
@NgModule({
imports: [
CommonModule,
pruebaRouting,
SmartadminModule,MorrisGraphModule
],
declarations: [pruebaComponent]
})
export class pruebaModule { }
<file_sep>import { Component, OnInit } from '@angular/core';
import {JsonApiService} from "../core/api/json-api.service";
import * as jsPDF from 'jspdf'
import { query } from '../../../node_modules/@angular/core/src/animation/dsl';
@Component({
selector: 'app-prueba',
templateUrl: './prueba.component.html',
styleUrls: ['./prueba.component.css']
})
export class pruebaComponent implements OnInit {
constructor(private JAS : JsonApiService) { }
morrisDemoData:any;
ngOnInit() {
this.JAS.fetch( '/graphs/morris.json').subscribe(data => this.morrisDemoData = data)
console.log(this.morrisDemoData)
}
download() {
var doc = new jsPDF();
doc.text(20, 20, 'Hello world!');
doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');
doc.addPage();
doc.text(20, 20, 'Do you like that?');
// doc.fromHTML(jQuery('#prueba').html(), 15, 15, { 'width': 170, 'elementHandlers': specialElementHandlers });
// Save the PDF
doc.save('Test.pdf');
}
}
<file_sep>import { Routes, RouterModule } from '@angular/router';
import {pruebaComponent} from "./prueba.component";
import {ModuleWithProviders} from "@angular/core";
export const pruebaRoutes: Routes = [
{
path: '',
component: pruebaComponent,
data: {
pageTitle: 'prueba'
}
}
];
export const pruebaRouting: ModuleWithProviders = RouterModule.forChild(pruebaRoutes);
| ec03d1fd7824d889e01cf7d16adf2dc51c5ea600 | [
"TypeScript"
] | 3 | TypeScript | rolandoArdelio/Correlacionador | 7f7120cf0d81267a4bdcc7f43ed539c5c031cc49 | e28dc6724dc6fa72608d59ddb8c64e7ec455a636 |
refs/heads/master | <repo_name>jjzhang166/MessageManager<file_sep>/OpenGL_Intro.cpp
#include <iostream>
#include "core\messageManager.h"
#include <thread>
void cbt1(geManagers::sMessage& msg) { std::cout << "1] Got Message with id " << msg.iUniqueMessageId << std::endl; }
void cbt2(geManagers::sMessage& msg) { std::cout << "2] Got Message with id " << msg.iUniqueMessageId << std::endl; }
void cbt3(geManagers::sMessage& msg) { std::cout << "3] Got Message with id " << msg.iUniqueMessageId << std::endl; }
void cbt4(geManagers::sMessage& msg) { std::cout << "4] Got Message with id " << msg.iUniqueMessageId << std::endl; }
void test() {
geManagers::MessageManager *MsgPumpTest = new geManagers::MessageManager();
MsgPumpTest->RegisterEvent("ExampleEvent1", 1);
MsgPumpTest->RegisterEvent("ExampleEvent2", 2);
MsgPumpTest->RegisterEvent("ExampleEvent3", 3);
MsgPumpTest->RegisterEvent("ExampleEvent4", 4);
std::thread t(&geManagers::MessageManager::Start, MsgPumpTest);
MsgPumpTest->Subscribe(1, cbt1);
MsgPumpTest->Subscribe(2, cbt2);
MsgPumpTest->Subscribe(3, cbt3);
MsgPumpTest->Subscribe(4, cbt4);
int i = 0;
geManagers::sMessage myMessage{ i };
while (i<20) {
Sleep(1);
myMessage.iMessageId = i;
int target = (rand() % 4) + 1;
MsgPumpTest->QueueMessage(target, myMessage);
i++;
}
while (MsgPumpTest->Pending()) { Sleep(1); };
MsgPumpTest->Die();
t.join();
}
int main(){
test();
return 0;
}
<file_sep>/messageManager.h
#ifndef __MESSAGE_MANAGER_H__
#define __MESSAGE_MANAGER_H__
#include <vector>
#include <map>
#include <string>
#include <mutex>
#include <iostream>
#include <deque>
#include <functional>
#include <mutex>
#include <condition_variable>
namespace geManagers {
struct sMessage {
int iUniqueMessageId;
int iMessageId;
};
struct sSubscriber {
int iSubscriberId;
std::function<void(sMessage&)> fnQueueCallback;
};
struct sEvent {
int iEventId;
std::string strEvent;
std::vector<sSubscriber> vRegisteredCallbacks;
std::deque<sMessage> vMessageQueue;
};
class MessageManager {
private:
std::mutex m_dispatchMutex;
std::condition_variable m_queueWait;
std::vector<sEvent> m_EventList;
int m_iUniqueEventTracker;
volatile bool m_bShutdown;
public:
MessageManager() {m_bShutdown = false;}
~MessageManager() = default;
// Create a new event to manage
bool RegisterEvent(std::string strEventName, int iEventId);
// Send message to each registered subscriber of a particular event
void QueueMessage(std::string strEventName, sMessage& targetMessage);
void QueueMessage(int iEventId, sMessage& targetMessage);
// Subscribe to any particular events
bool Subscribe(std::string strEventName, std::function<void(sMessage&)> fnQueueCallback, int iSubscriberId = 0);
bool Subscribe(int iEventId, std::function<void(sMessage&)> fnQueueCallback, int iSubscriberId = 0);
// Destroy a message in any particular event
bool Consume(std::string strEventName, sMessage& targetMessage);
bool Consume(int iEventId, sMessage& targetMessage);
// Primary Running Thread
void Start();
// Logic Control
void Die();
// Check for pending messages overall
bool Pending();
};
bool MessageManager::RegisterEvent(std::string strEventName, int iEventId) {
std::lock_guard<std::mutex> guard(m_dispatchMutex);
for (sEvent& x : m_EventList)
if (x.iEventId == iEventId || x.strEvent == strEventName)
return false;
m_EventList.push_back(sEvent{ iEventId, strEventName });
return true;
}
void MessageManager::QueueMessage(std::string strEventName, sMessage& targetMessage) {
std::lock_guard<std::mutex> guard(m_dispatchMutex);
for (sEvent& x : m_EventList) {
if (x.strEvent == strEventName) {
targetMessage.iUniqueMessageId = m_iUniqueEventTracker;
m_iUniqueEventTracker++;
x.vMessageQueue.push_back(targetMessage);
m_queueWait.notify_all();
}
}
}
void MessageManager::QueueMessage(int iEventId, sMessage& targetMessage) {
std::lock_guard<std::mutex> guard(m_dispatchMutex);
for (sEvent& x : m_EventList) {
if (x.iEventId == iEventId) {
targetMessage.iUniqueMessageId = m_iUniqueEventTracker;
m_iUniqueEventTracker++;
x.vMessageQueue.push_back(targetMessage);
m_queueWait.notify_all();
}
}
}
bool MessageManager::Subscribe(std::string strEventName, std::function<void(sMessage&)> fnQueueCallback, int iSubscriberId) {
std::lock_guard<std::mutex> guard(m_dispatchMutex);
for (sEvent& x : m_EventList) {
if (x.strEvent == strEventName) {
x.vRegisteredCallbacks.push_back(sSubscriber{ iSubscriberId, fnQueueCallback });
return true;
}
}
return false;
}
bool MessageManager::Subscribe(int iEventId, std::function<void(sMessage&)> fnQueueCallback, int iSubscriberId) {
std::lock_guard<std::mutex> guard(m_dispatchMutex);
for (sEvent& x : m_EventList) {
if (x.iEventId == iEventId) {
x.vRegisteredCallbacks.push_back(sSubscriber{ iSubscriberId, fnQueueCallback });
return true;
}
}
return false;
}
bool MessageManager::Consume(std::string strEventName, sMessage& targetMessage) {
std::lock_guard<std::mutex> guard(m_dispatchMutex);
for (sEvent& x : m_EventList) {
if (x.strEvent == strEventName) {
for (std::deque<sMessage>::iterator m = x.vMessageQueue.begin(); m != x.vMessageQueue.end(); m++) {
if (m->iUniqueMessageId == targetMessage.iUniqueMessageId) {
x.vMessageQueue.erase(m);
return true;
}
}
}
}
return false;
}
bool MessageManager::Consume(int iEventId, sMessage& targetMessage) {
std::lock_guard<std::mutex> guard(m_dispatchMutex);
for (sEvent& x : m_EventList) {
if (x.iEventId == iEventId) {
for (std::deque<sMessage>::iterator m = x.vMessageQueue.begin(); m != x.vMessageQueue.end(); m++) {
if (m->iUniqueMessageId == targetMessage.iUniqueMessageId) {
x.vMessageQueue.erase(m);
return true;
}
}
}
}
return false;
}
void MessageManager::Die() {
std::lock_guard<std::mutex> guard(m_dispatchMutex);
m_bShutdown = true;
m_queueWait.notify_all();
}
void MessageManager::Start() {
while (!m_bShutdown) {
std::unique_lock<std::mutex> guard(m_dispatchMutex);
m_queueWait.wait(guard);
for (sEvent& x : m_EventList) {
if (!x.vMessageQueue.empty()) {
for (auto &subscribers : x.vRegisteredCallbacks)
subscribers.fnQueueCallback(x.vMessageQueue.front());
x.vMessageQueue.pop_front();
}
}
}
}
bool MessageManager::Pending() {
std::lock_guard<std::mutex> guard(m_dispatchMutex);
for (sEvent& x : m_EventList) {
if (!x.vMessageQueue.empty()) {
return true;
}
}
return false;
}
};
#endif
<file_sep>/README.md
# MessageManager
Thread safe subscriber based callback solution for things such as game engines.
| 0e9614abc0096b2555e0299f2801c4bb9f970012 | [
"Markdown",
"C++"
] | 3 | C++ | jjzhang166/MessageManager | 6b7f23e96fbb6fc2737d402a88818f384000d224 | 014083bd8303b99d9934944663025eb2af5040ba |
refs/heads/master | <repo_name>Shmik/webframework<file_sep>/requirements.txt
astroid==2.2.5
backcall==0.1.0
decorator==4.3.2
gunicorn==19.9.0
ipdb==0.11
ipython==7.3.0
ipython-genutils==0.2.0
isort==4.3.15
jedi==0.13.3
Jinja2==2.10
lazy-object-proxy==1.3.1
MarkupSafe==1.1.1
mccabe==0.6.1
parso==0.3.4
pexpect==4.6.0
pickleshare==0.7.5
prompt-toolkit==2.0.9
psycopg2-binary==2.7.7
ptyprocess==0.6.0
Pygments==2.3.1
pylint==2.3.1
six==1.12.0
traitlets==4.3.2
typed-ast==1.3.1
wcwidth==0.1.7
WebOb==1.8.5
wrapt==1.11.1
<file_sep>/models/model.py
from models.fields import Field, PrimaryKeyField
class Model():
id = PrimaryKeyField()
@classmethod
def get_name(cls):
return cls.__name__.lower()
@classmethod
def get_table(cls):
return cls.get_name()
@classmethod
def get_fields(cls):
fields_dict = {}
for field_name in dir(cls):
field = getattr(cls, field_name)
if getattr(field, 'db_field', None):
fields_dict[field_name] = field
return fields_dict
<file_sep>/database/migrations.py
import logging
from database.db import get_connection
from psycopg2 import sql
from apps.model_register import ModelRegister
import apps.migrations as app_migrations
import os
model_register = ModelRegister()
MIGRATIONS_PATH = os.path.dirname(app_migrations.__file__)
class MakeMigrations():
def __init__(self):
migrations_table_exists = self.check_table_exists('migration')
if migrations_table_exists:
print('Migrations table exists')
else:
self.create_migrations_table()
def create_migrations_table(self):
print('Creating migrations table')
with get_connection() as conn:
with conn.cursor() as curs:
curs.execute("""
CREATE TABLE migration (
id SERIAL PRIMARY KEY,
name VARCHAR(100)
);
""")
def check_table_exists(self, table_name):
with get_connection() as conn:
with conn.cursor() as curs:
# Check that the migrations table exists.
curs.execute("""
SELECT EXISTS (
SELECT 1 FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = %s
);
""", (table_name,))
table_exists = curs.fetchone()[0]
return table_exists
def get_column_data(self, table_name):
with get_connection() as conn:
with conn.cursor() as curs:
curs.execute("""
SELECT column_name, udt_name, column_default, character_maximum_length
FROM information_schema.columns
WHERE table_schema = 'public'
AND table_name = %s;
""", (table_name,))
column_data = curs.fetchall()
return column_data
def make_all_apps(self):
for model in model_register.get_apps():
self.make_for_model(model)
def make_changes_for_all_apps(self):
for model in model_register.get_apps():
self.alter_model_fields(model)
def make_for_model(self, model):
table_name = model.get_table()
if not self.check_table_exists(table_name):
query = self.build_create_table_query_for_model(model)
self.create_migration_file(query)
def alter_model_fields(self, model):
"""
Only add the ability to add and remove fields
"""
column_names_db = [x[0] for x in self.get_column_data(model.get_table())]
model_fields = model.get_fields()
model_field_names = model_fields.keys()
alteration_queries = []
for field_name, field_class in model.get_fields().items():
if field_name not in column_names_db:
query = sql.SQL("{} ").format(sql.Identifier(field_name)) + field_class.create_sql
if getattr(field_class, 'max_length', None):
query += sql.SQL("({})").format(sql.Literal(field_class.max_length))
add_collumn = sql.SQL("ALTER TABLE {} ADD COLUMN {}" ).format(
sql.Identifier(model.get_table()),
query
)
alteration_queries.append(add_collumn)
for field_name in column_names_db:
if field_name not in model_field_names:
drop_collumn = sql.SQL("ALTER TABLE {} DROP COLUMN {}" ).format(
sql.Identifier(model.get_table()),
sql.Identifier(field_name)
)
alteration_queries.append(drop_collumn)
with get_connection() as conn:
for query in alteration_queries:
self.create_migration_file(query.as_string(conn))
def build_create_table_query_for_model(self, model):
columns = []
for field_name, field_class in model.get_fields().items():
query = sql.SQL("{} ").format(sql.Identifier(field_name)) + field_class.create_sql
if getattr(field_class, 'max_length', None):
query += sql.SQL("({})").format(sql.Literal(field_class.max_length))
columns.append(query)
create_statement = sql.SQL("CREATE TABLE {} ({})" ).format(
sql.Identifier(model.get_table()),
sql.SQL(', ').join(columns)
)
with get_connection() as conn:
return create_statement.as_string(conn)
def get_next_migration_number(self):
"""
Migrations will always start with a 4 digit number which increases.
"""
migration_file_list = os.listdir(MIGRATIONS_PATH)
migration_file_list.remove('__init__.py')
if len(migration_file_list) > 0:
migration_file_list.sort()
return int(migration_file_list[-1][0:4]) + 1
else:
return 0
def create_migration_file(self, query):
next_number = self.get_next_migration_number()
filename = f'{next_number:04}_migration.py'
filepath = f'{MIGRATIONS_PATH}/{filename}'
with open(filepath, 'x') as f:
f.write(query)
class Migrate():
def __init__(self):
self.execute_pending_migrations()
def get_migrations_file_list(self):
migration_file_list = os.listdir(MIGRATIONS_PATH)
migration_file_list.remove('__init__.py')
migration_file_list.sort()
return migration_file_list
def get_completed_migrations_list(self):
with get_connection() as conn:
with conn.cursor() as curs:
curs.execute("""
SELECT name
FROM migration
ORDER BY name
"""
)
column_data = curs.fetchall()
return [result[0] for result in column_data]
def execute_pending_migrations(self):
migration_files = self.get_migrations_file_list()
completed_migrations = self.get_completed_migrations_list()
pending = [filename for filename in migration_files if filename not in completed_migrations]
for filename in pending:
self.execute(filename)
def execute(self, filename):
filepath = f'{MIGRATIONS_PATH}/{filename}'
print (f'Executing migration {filename}')
with open(filepath, 'r') as file:
query = file.read()
with get_connection() as conn:
with conn.cursor() as curs:
# execute migration
curs.execute(query)
# and record completed
print (f'inserting {filename}')
curs.execute("INSERT INTO migration (name) VALUES (%s)", (filename,))
<file_sep>/README.md
# webframework
Building a custom web framework to learn more about how it is done.
I will be roughly following a similar layout to Django<file_sep>/__init__.py
name = "webframework"<file_sep>/views.py
from webob import Response
from jinja2 import Template
from config.jinja import env
def http_404(request):
response = Response()
response.text = 'Http404'
return response
def hello_world(request):
response = Response()
response.text = 'Hello World'
return response
def welcome(request):
response = Response()
template = env.get_template('welcome.html')
rendered = template.render(heading='Welcome to my new page')
response.text = rendered
return response<file_sep>/config/settings.py
DNS = 'dbname=dbname user=myuser password=<PASSWORD>'
INSTALLED_MODELS = [
'person.Person',
]
try:
from .local_settings import *
except ImportError:
pass
<file_sep>/models/fields.py
from psycopg2 import sql
class Field():
db_field = True
class CharField(Field):
udt_name='varchar'
create_sql = sql.SQL('VARCHAR')
def __init__(self, max_length, default=None):
self.max_length = max_length
self.default = None
class TextField(Field):
udt_name='text'
create_sql = sql.SQL('TEXT')
def __init__(self, default=None):
self.max_length = None
self.default = None
class DateTimeField(Field):
udt_name='timestamp'
create_sql = sql.SQL('TIMESTAMP')
def __init__(self, default=None):
self.default = None
class PrimaryKeyField(Field):
udt_name='int4'
create_sql = sql.SQL('serial PRIMARY KEY')
<file_sep>/apps/migrations/0000_migration.py
CREATE TABLE "person" ("first_name" VARCHAR(55), "id" serial PRIMARY KEY, "last_name" VARCHAR(55))<file_sep>/router.py
from urls import urlpatters
from views import http_404
class Router:
def __init__(self):
self.patterns = urlpatters
self.paths, self.views = zip(*urlpatters)
def __call__(self, path):
try:
index = self.paths.index(path)
except:
return http_404
return self.views[index]<file_sep>/apps/models/person.py
from models import Model
from models.fields import CharField
class Person(Model):
first_name = CharField(max_length=55)
last_name = CharField(max_length=55)
<file_sep>/urls.py
from views import hello_world, welcome
urlpatters = [
('/', hello_world),
('/welcome', welcome),
]<file_sep>/apps/model_register.py
import sys
import apps.models
from config.settings import INSTALLED_MODELS
class ModelRegister():
def get_apps(self):
apps = []
for conf in INSTALLED_MODELS:
[module, class_name] = conf.split('.')
klass = getattr(sys.modules[f'apps.models.{module}'], class_name)
apps.append(klass)
return apps
<file_sep>/app.py
from webob import Request, Response
from urls import urlpatters
from router import Router
router = Router()
class App(object):
def __call__(self, environ, start_response):
request = Request(environ)
response = self.handle_request(request)
return response(environ, start_response)
def handle_request(self, request):
view = router(request.path)
return view(request)
<file_sep>/database/db.py
import psycopg2
from config.settings import DNS
def get_connection():
return psycopg2.connect(DNS)
| 566881542dc304d05f3cb5249bc24327365c24a8 | [
"Markdown",
"Python",
"Text"
] | 15 | Text | Shmik/webframework | c37c95255447a63624ce844501dcfb06df32db9a | d0b360545906a65d849d00b19a2c55b09e2354f0 |
refs/heads/master | <repo_name>virendra2202/NewsApp<file_sep>/js/newsListPage.js
var serviceURL = "http://www.app.setevent.in/news/";
var news;
$('#newsListPage').bind('pageinit', function(event) {
getNewsList();
});
function getNewsList() {
$.getJSON(serviceURL + 'newsListPage.php?page=index&callback=?', function(data) {
$('#newsList li').remove();
$.each(data, function(index, news1) {
$('#newsList').append('<li><a onclick=\"window.open(\'newsView.html?id=' + news1.news_id+'&page=index&callback=?'+'\',\'_self\')\">' +
'<img src="'+serviceURL+'img/' + news1.news_picture + '"/>' +
'<h4>' + news1.news_title + '</h4>' +
'<p>' + news1.news_description + '</p></a></li>');
});
$('#newsList').listview('refresh');
});
}
<file_sep>/README.md
NewsApp
=======
NewsApp
All right Reserverd by <NAME>
<file_sep>/js/newsView.js
$(function() {
var serviceURL = "http://www.app.setevent.in/news/";
var news;
$('#newsListPage').bind('pageinit', function(event) {
getEmployeeList();
});
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
function getEmployeeList() {
var id = getUrlVars()["id"];
$.getJSON(serviceURL + 'newsView.php?id='+id+'&page=index&callback=?', function(data) {
$('#newsList li').remove();
//news = data.items;
$.each(data, function(index, news1) {
$('#newsList').append('<li>' +
'<img src="'+serviceURL+'img/' + news1.news_picture + '"/>' +
'<h4>' + news1.news_title + '</h4>' +
'<p>' + news1.news_description + '</p></li>');
});
});
}
getEmployeeList();
});
| ddd75918adcb2ab6fd0f8b34d208ce41fb6459a0 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | virendra2202/NewsApp | 41c9b0d77c57448c397ed30e970631c214727116 | b0721388dbc263e9579f4d258cf1e0a164b66fa9 |
refs/heads/master | <file_sep>package com.test;
import org.junit.Test;
public class EurekaServiceTest {
@Test
public void contextLoads() {
System.out.println("Hello");
}
}
| a2a0713dadb3f76a193706591e2fba02b818e3a7 | [
"Java"
] | 1 | Java | TestGitHub7521/EurekaServerM | 60f2acd39a908aebe012b1f2878fbd2fd19f7ee5 | d83d2e83b9e5c79025d99223f756509b75c7aefb |
refs/heads/master | <repo_name>cheesegits/ThinkfulTube<file_sep>/app.js
$(document).ready(function() {
$('#submitSearch').submit(function(event) {
event.preventDefault();
var searchTerm = $('#text').val();
getRequest(searchTerm);
});
});
//API pull
function getRequest(searchTerm) {
url = 'https://www.googleapis.com/youtube/v3/search';
var params = {
part: 'snippet',
key: '<KEY>',
q: searchTerm
};
$.getJSON(url, params, function(searchTerm) {
showResults(searchTerm);
});
}
//Video object
var searchResult = function(index, value) {
this.index = index;
this.title = value.snippet.title;
this.address = 'https://www.youtube.com/watch?v=' + value.id.videoId;
this.thumbnail = value.snippet.thumbnails.default.url;
}
//Display results
function showResults(results) {
var html = "";
var entries = results.items;
$.each(entries, function(index, value) {
var video = new searchResult(index, value);
html += '<p><a href="' + video.address + '">' + video.title + '</a></p>';
html += '<a href="' + video.address + '"><img src="' + video.thumbnail + '"/></a>';
});
$('#results').html(html);
}
| 2afa39d295fbc867ed94a2256ce16d633b852f8a | [
"JavaScript"
] | 1 | JavaScript | cheesegits/ThinkfulTube | c8427460436305275420c3575e5243edf5d199f6 | d3f2e83b41af30436c9384c36c01cb12b1f06780 |
refs/heads/master | <file_sep>import React, { Fragment } from 'react';
import './App.css';
import NavBar from '../Components/NavBar/NavBar';
import QuestionCardList from '../Components/QuestionCardList/QuestionCardList';
import StartMenu from '../Components/StartMenu/StartMenu.js'
import SubmitButton from '../Components/SubmitButton/SubmitButton';
import ResultsMenu from '../Components/ResultsMenu/ResultsMenu';
const questionsArray = [
'A bat and a ball cost $1.10 in total. The bat costs $1.00 more than the ball. How much does the bat cost?',
'If it takes 5 machines 5 minutes to make 5 widgets, how long would it take 100 machines to make 100 widgets?',
'In a lake, there is a patch of lily pads. Every day, the patch doubles in size. If it takes 48 days for the patch to cover the entire lake, how long would it take for the patch to cover half of the lake?'
];
const answersArray = [
['$1.00', '$0.05', '*$1.05', '$0.10'],
['60 minutes', '100 minutes', '20 minutes', '*5 minutes'],
['24 days', '*47 days', '2 days', '12 days']
];
let userAnswersArray = ['','',''];
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
quizStarted: false,
quizComplete: false,
correctAnswers: 0
}
}
quizStartHandler = () => {
this.setState({ quizStarted: true });
}
submitClickedHandler = () => {
let numberOfCorrectAnswers = 0;
//if blank element found in array, user did not answer a question
userAnswersArray.forEach(answer => {
//if answer is correct, increment
if (answer === 'Correct')
numberOfCorrectAnswers++;
})
this.setState({
correctAnswers: numberOfCorrectAnswers,
quizComplete: true
})
}
radioChangeHandler = (event) => {
let cardID = event.target.value[0];
userAnswersArray[cardID] = event.target.value.substring(1, event.target.value.length - 1);
}
render() {
return (
<div className='container'>
<NavBar timerDoneHandler={this.submitClickedHandler} quizStarted={this.state.quizStarted} quizComplete={this.state.quizComplete}/>
{this.state.quizComplete ?
<ResultsMenu correctAnswers={this.state.correctAnswers} userAnswersArray={userAnswersArray} /> :
<Fragment>
{this.state.quizStarted ?
<div>
<QuestionCardList questions={questionsArray} answers={answersArray} radioChangeHandler={this.radioChangeHandler}/>
<SubmitButton handler={this.submitClickedHandler}/>
</div> :
<StartMenu handler={this.quizStartHandler}/>
}
</Fragment>
}
</div>
);
}
}
export default App;
<file_sep>import React from 'react';
import Button from '@material-ui/core/Button';
import './SubmitButton.css';
const SubmitButton = props => {
return (
<Button onClick={props.handler} className='submit-button' variant='contained' size='large' color='primary'>SUBMIT</Button>
);
}
export default SubmitButton;<file_sep>import React, { Fragment } from 'react';
import './QuestionResult.css';
import DoneIcon from '@material-ui/icons/Done';
import ClearIcon from '@material-ui/icons/Clear';
const QuestionResult = props => {
return (
<div className='answer-container'>
{
props.answer === 'Correct' ?
<DoneIcon style={{ color: 'green' }} /> :
<ClearIcon color='secondary'/>
}
<h4 className='answer-result'>{props.index + 1}.
{props.answer === '' ?
' Incorrect':
' ' + props.answer}
</h4>
</div>
);
}
export default QuestionResult;<file_sep>import React from 'react';
import './StartMenu.css';
import Button from '@material-ui/core/Button'
const StartMenu = props => {
return (
<div className='start-menu'>
<h1 className='start-title'>Ready to take the quiz?</h1>
<p className='start-description'>This quiz is a timed <strong>three</strong> minute, <strong>three</strong> question test of cognitive ability. It was found that only 17% of university students get all three questions correct.</p>
<Button
className='start-button'
size='large'
variant="outlined"
color="primary"
onClick={props.handler}>
START
</Button>
</div>
);
}
export default StartMenu;<file_sep>import React from 'react';
import './ResultsMenu.css';
import LinearProgress from '@material-ui/core/LinearProgress';
import QuestionResult from '../QuestionResult/QuestionResult';
import Button from '@material-ui/core/Button';
const ResultsMenu = props => {
const refreshPage = _ => {
window.location.reload(true);
}
return (
<div className='results-menu'>
<h1 className='results-title'>You scored {Math.round((props.correctAnswers/3)*100) + '%'}</h1>
<LinearProgress className='linear-results' variant='determinate' value={(props.correctAnswers/3)*100}/>
<div className='results-user-answers'>
{props.userAnswersArray.map((answer, i) => {
return <QuestionResult key={i} index={i} answer={answer} />
})}
</div>
<Button
className='take-again-button'
size='large'
variant="outlined"
color="primary"
onClick={refreshPage}>
TAKE AGAIN
</Button>
</div>
);
}
export default ResultsMenu;<file_sep>import React from 'react';
import AppBar from '@material-ui/core/AppBar';
import Typography from '@material-ui/core/Typography';
import ToolBar from '@material-ui/core/Toolbar'
import Timer from '../Timer/Timer';
import './NavBar.css';
const NavBar = props => {
const DisplayTimer = _ => {
if(props.quizStarted && !props.quizComplete) {
return <Timer timerDoneHandler={props.timerDoneHandler} quizStarted={props.quizStarted} quizComplete={props.quizComplete}/>
} else {
return null;
}
}
return (
<AppBar position='fixed'>
<ToolBar>
<Typography variant='h4'>
iQuiz
</Typography>
<DisplayTimer />
</ToolBar>
</AppBar>
);
}
export default NavBar;<file_sep>## What is iQuiz?
iQuiz is a quick and easy way to test one's cognitive ability, it is a three minute, three question quiz that puts your brain to the test. These same questions were given out to a sample of university students with only 17% of them getting all questions right. Think you're up to the challenge? Head over to the site now!
## About the Project
iQuiz was made with HTML, CSS, JS, and the React library. Material-UI was used for styling and components as their style and simplicity is admirable. The project was deployed with create-recat-app and is optimized for performance.
<file_sep>import React from 'react';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import Typography from '@material-ui/core/Typography';
import RadioGroup from '@material-ui/core/RadioGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Radio from '@material-ui/core/Radio';
import { withStyles } from '@material-ui/core/styles';
import { green } from '@material-ui/core/colors';
import './QuestionCard.css';
const QuestionCard = props => {
const BlueRadio = withStyles({
root: {
color: '#default',
'&$checked': {
color: '#3f51b5',
},
},
checked: {},
})((props) => <Radio color="default" {...props} />);
// const setAnswer = (event) => {
// props.userAnswers[props.key] = event.target.value;
// alert(props.userAnswers)
// }
return (
<Card className='question-card'>
<CardContent>
<Typography>
{props.question}
</Typography>
<RadioGroup onChange={props.radioChangeHandler}>
{props.questionAnswers.map((answer, i) => {
return (
<FormControlLabel
key={'answer' + i}
value={ props.cardNumber + ((answer[0] === '*') ? 'Correct' : 'Incorrect') + i }
control={<BlueRadio />}
label={answer.replace('*','')}
/>
);
})}
</RadioGroup>
</CardContent>
</Card>
);
}
export default QuestionCard; | 7301a8b6837c4127bb4354e3851087b4b635efa8 | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | richardnorman/iquiz | a9f1a70b360e12b7fd5cd771de1366cf832c5709 | f32117d0fabadfc0fa7267cbcc89f0f1e2485d9c |
refs/heads/master | <file_sep>
function bulb() {
document.getElementById("eteindre").src="/home/amyniane/Bureau/AMYNA-7/laampe/on.jpg"
}
//fonction pour allumer
function bulboff() {
document.getElementById("eteindre").src="/home/amyniane/Bureau/AMYNA-7/laampe/off.jpg"
}
<file_sep><h1>exercice sur les requettes mysql<h1>
1 afficher la liste des pays ou simplon est prรฉsent?
mysql> select *from pays let join fabrique on id_pays = fabrique.id_pays;
+----+---------+--------+----+----------------+----------------+-----------+-------------------------+---------+
| id | nom | ville | id | nom | adresse | tel | email | id_pays |
+----+---------+--------+----+----------------+----------------+-----------+-------------------------+---------+
| 1 | SENEGAL | Dakar | 1 | <NAME> | corniche ouest | 335678909 | <EMAIL> | 1 |
| 2 | Mali | Bamako | 1 | <NAME> | corniche ouest | 335678909 | <EMAIL> | 1 |
| 3 | Gambie | Banjul | 1 | <NAME> | corniche ouest | 335678909 | <EMAIL> | 1 |
| 4 | France | Paris | 1 | <NAME> | corniche ouest | 335678909 | <EMAIL> | 1 |
| 5 | Espagne | Madrid | 1 | <NAME> | corniche ouest | 335678909 | <EMAIL> | 1 |
| 6 | Chine | Pรฉkin | 1 | <NAME> | corniche ouest | 335678909 | <EMAIL> | 1 |
2 afficher la liste des fabrique de la ville de Dakar?
mysql> select nom from fabrique where id_pays=1;
+---------------+
| nom |
+---------------+
| <NAME> |
+---------------+
3 afficher la liste des pays qui ont au moins deux fabrique?
mysql> select *from pays where ville >='2';
+----+---------+--------+
| id | nom | ville |
+----+---------+--------+
| 1 | SENEGAL | Dakar |
| 2 | Mali | Bamako |
| 3 | Gambie | Banjul |
| 4 | France | Paris |
| 5 | Espagne | Madrid |
| 6 | Chine | Pรฉkin |
+----+---------+--------+
4 afficher le nombre d' apprenant par fabrique ?
5 afficher la liste des rรฉfรฉrentiels par fabrique ?
6 afficher la liste des apprenants qui ont au moins un contrat?
mysql> select *from apprenant left join contrat on id_apprenant = contrat.id_apprenant and type_contrat= 'en poste';
+----+--------+------------+------------+----------------+------+-----------------------+-----------+----------------+------------+-------------+------+-------+--------------+------------+----------+---------------+--------------+---------------------------+
| id | nom | prenom | statut | date_naissance | sexe | email | tel | id_referentiel | id_cohorte | id_fabrique | id | poste | type_contrat | date_debut | date_fin | nom_structure | id_apprenant | situation_professionnelle |
+----+--------+------------+------------+----------------+------+-----------------------+-----------+----------------+------------+-------------+------+-------+--------------+------------+----------+---------------+--------------+---------------------------+
| 1 | NIANE | Amy | apprenante | 1993-07-05 | 1 | <EMAIL> | 777660584 | 1 | 3 | 4 | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
| 2 | NDAO | <NAME> | apprenante | 1998-12-05 | 1 | <EMAIL> | 789860584 | 1 | 2 | 1 | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
| 3 | FAYE | Helene | apprenante | 1985-04-11 | 1 | <EMAIL> | 765429919 | 4 | 3 | 3 | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
| 4 | MARIGO | Mamadou | apprenante | 1990-08-19 | 0 | <EMAIL> | 709876543 | 2 | 4 | 2 | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
| 5 | SIDIBE | Mouhamed | apprenant | 1995-12-19 | 0 | <EMAIL> | 774809873 | 3 | 5 | 5 | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
+----+--------+------------+------------+----------------+------+-----------------------+-----------+----------------+------------+-------------+------+-------+--------------+------------+----------+---------------+--------------+---------------------------+
7 ajouter une table ouvert de type boolean a cohorte
alter table cohorte add ouvert boolean;
Query OK,
0 rows affected (1.17 sec)
8* modifier le type du champ sexe en char(1)
mysql> alter table apprenant modify sexe char(1);
Query OK,
5 rows affected (2.05 sec)
| e5472a728f61c9a17d187592f93fbfe7c904e641 | [
"JavaScript",
"SQL"
] | 2 | JavaScript | AMYNA-7/simplon-p2-amina | 3f05ce0bc5f4445bb6236591110721bc43f04a34 | 6f47246037bf178da010e6bb96a45a634e7bb83a |
refs/heads/master | <repo_name>taherahmed19/BDD<file_sep>/src/test/java/DefiningSteps.java
import io.cucumber.java.bs.A;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class DefiningSteps {
Applicant applicant;
// PageManager pageManager;
/*
@Given("the applicant {string} is on the {string} page")
public void the_applicant_is_on_the_application_page(String applicantId, String page) {
applicant = new Applicant(applicantId);
pageManager = new PageManager(page);
}
@Given("all grades have been verified and predicted for the applicant")
public void all_grades_have_been_verified_and_predicted_for_the_applicant() {
applicant.setGradesPredictedAndVerified();
}
@Given("the applicant enters {int} personal statements with {int} characters")
public void the_applicant_enters_a_personal_statement_with_characters(Integer numPersonalStatements, Integer length) {
applicant.addPersonalStatement(numPersonalStatements, length);
}
@Given("the applicant selects {int} institutions")
public void the_applicant_selects_institutions(Integer numInstitutions) {
applicant.addInstitution(numInstitutions);
}
@When("the applicant clicks the submit button")
public void the_applicant_clicks_the_submit_button() {
pageManager.clickSubmit();
}
@Then("the system does not submit the application")
public void the_system_does_not_submit_the_application() {
assertTrue(applicant.hasNotSubmitted());
}
@Then("the applicant remains on the {string} page")
public void the_applicant_remains_on_the_page(String page) {
assertEquals(pageManager.getPage(), page);
}
@Then("the error output should be {string}")
public void the_error_output_should_be(String output) {
assertEquals(applicant.getErrorOutputMessage(), output);
}
@Then("the successful output should be {string}")
public void the_successful_output_should_be(String output) {
assertEquals(applicant.getSuccessOutputMessage(), output);
}
@Then("the system should submit the application")
public void the_system_should_submit_the_application() {
assertTrue(applicant.hasSubmitted());
}
@Then("the application is redirect to the {string} page")
public void the_application_is_redirect_to_the_page(String page) {
pageManager.setPage("submission details");
assertEquals(pageManager.getPage(), page);
}*/
}
| db7f64ad71cc02b68d57dedd2f0b216c4763d1e2 | [
"Java"
] | 1 | Java | taherahmed19/BDD | 653e4442276971b5cb858d75154a50b570265c2c | bb037d32123801e6fc67268270d11448afa277ff |
refs/heads/master | <repo_name>Anthony-Moss/DoTheThing<file_sep>/routes/openTickets.js
const express = require("express");
const Router = express.Router;
const openTicketsRoutes = Router();
const { openTicketsPage } = require("../controllers/openTickets");
openTicketsRoutes.get("/", openTicketsPage);
module.exports = openTicketsRoutes;
<file_sep>/controllers/login.js
const User = require("../models/user");
const escapeHtml = require("../utils");
async function showLogin(req, res) {
res.render("login", {
locals: {
message: "Please log-in to go to your dashboard.",
email: ""
}
});
}
async function checkLogin(req, res) {
const theEmail = escapeHtml(req.body.email);
const thePassword = escapeHtml(req.body.password);
console.log(theEmail);
console.log(thePassword);
// call the User function that checks username against username in database
// if the username exists, creates an instance of User
const theUser = await User.getByEmail(theEmail);
// get the password from the form (it is .password because that is the name we gave it in HTML)
const passwordIsCorrect = theUser.checkPassword(thePassword);
// use the checkPassword instance method to check if it matches saved password in database
// username and password match what is in the system
console.log(`This is the username: ${theUser.username}`);
if (passwordIsCorrect) {
// then load the dashboard and save the user info in a session
// session is how we will track whether or not user can see the dashboard
// store instance of user in the session
req.session.user = theUser.id;
req.session.save(() => {
res.redirect("/dashboard");
});
// redirect the page to localhost:3001/dashboard
// if the username is incorrect
// if the password is incorrect
} else {
// render login page (index) again with the message password not correct
res.render("login", {
locals: {
email: req.body.email,
message: "Incorrect email/password. Please try again."
}
});
}
}
module.exports = {
showLogin,
checkLogin
};
<file_sep>/routes/login.js
const express = require("express");
const loginRouter = express.Router();
const { showLogin, checkLogin } = require("../controllers/login");
loginRouter.get("/", showLogin);
loginRouter.post("/", checkLogin);
module.exports = loginRouter;
<file_sep>/controllers/request.js
async function showRequestPage(req, res) {
res.render("request");
};
module.exports = {
showRequestPage
};<file_sep>/README.md
# DoTheThing - Ticketing support system to manage .
---
##Contents
---
* What It Is
* What We Used
* MVP
* Stretch Goals
* Authors
* Github Link
##What It Is
---
A support ticketing application built with JavaScript, Node.js, PostgreSQL, HTML and CSS to help track support tickets and ensure completion.
It allows for anyone to create a ticket, tickets are placed into a queue and then allow users to grab or assign the ticket/tasks to themselves
to work on and complete it along with add any notes about the ticket. The application can easily be modified to act as a productivity tool for
employers to track the work of their employees as well.
##What We Used
---
* HTML5
* CSS3
* JavaScript
* Node.js
* PostgreSQL
##MVP (Minimum Viable Product)
---
The MVP for this project changed was definitely ambitious. We had so much that we wanted to do with this application we really
had to think about what all was going to be needed for this application to really make sense. In the end we didn't really get to
spend much time on our stretch goals, but were able to succesfully integrate all MVP features.
Our first MVP iteration included:
* A main landing page for the application.
* A login screen to allow users to log in.
* A submit request page to allow users to submit tickets.
* A user dashboard to see all tickets related to user.
* Tickets page that shows all tickets in different catagories.
* A notes page that will show the details for each ticket along with ability to input notes.
##Stretch Goals
* Create an admin dashboard that would have ability to handle all tickets.
* Add SMS support so when tasks are completed, the ticket submitor would get a text response.
* Adding rating system or upvote to the tickets, to allow for basic urgency tracking.
* Alert system - when new ticket submitted, alert is sent to users.
##Authors
---
* [<NAME>](https://github.com/Anthony-Moss)
* [<NAME>](https://github.com/rebeccauranga)
* [<NAME>](https://github.com/cduhaney1)
##Github Link
---
[Github](https://github.com/Anthony-Moss/DoTheThing)
<file_sep>/models/pendingTickets.js
// Bring in the databse connection.
const db = require("./conn");
const bcrpyt = require("bcryptjs");
// Need a User class.
// Classes should start with an uppercase letter
class PendingTickets {
constructor(id, all_tickets_id, users_id, time_started) {
this.id = id;
this.all_tickets_id = all_tickets_id;
this.users_id = users_id;
this.time_started = time_started;
}
static getAll() {
return db.any(`select * from pending_tickets`).then(arrayOfTickets => {
console.log(arrayOfTickets);
return arrayOfTickets;
});
}
static getByAllTicketsId() {
return db.any(`select p.*, a.issue_desc, a.time_posted from pending_tickets p inner join all_tickets a on p.all_tickets_id=a.id`)
.then(arrayOfPendingTicketsData => {
return arrayOfPendingTicketsData;
});
}
static getAllTicketsIdOfPendingTicket(id) {
return db.one(`select all_tickets_id from pending_tickets where id=${id}`)
.then((ticketId) => {
return ticketId;
});
}
}
module.exports = PendingTickets;
<file_sep>/routes/completedTickets.js
const express = require("express");
const Router = express.Router;
const completedTicketsRoutes = Router();
const { completedTicketsPage, updateCompletedTicketsPage } = require("../controllers/completedTickets");
completedTicketsRoutes.get("/", completedTicketsPage);
completedTicketsRoutes.get("/:id", updateCompletedTicketsPage);
module.exports = completedTicketsRoutes;
<file_sep>/models/details.js
const db = require("./conn");
class Details {
constructor(id, note_content) {
this.id = id;
this.note_content = note_content;
}
static getAll() {
return db.any(`select * from notes`).then(arrayOfNotes => {
console.log(arrayOfNotes);
return arrayOfNotes;
});
}
static getNotesByTicketId(ticketId) {
return db.any('select * from notes where all_tickets_id = $1', [parseInt(ticketId)]).then(arrayOfNotes => {
console.log(arrayOfNotes);
return arrayOfNotes;
});
}
// Should we add a time posted for notes as well?
static newDetailSubmitted(notecontent, users_id, all_tickets_id) {
const timestamp = new Date();
const month = timestamp.getMonth() + 1;
const realMonth = month.toString();
const date = timestamp.getDate().toString();
const year = timestamp.getFullYear().toString();
const hour = timestamp.getHours().toString();
const minute = timestamp.getMinutes().toString();
const second = timestamp.getSeconds().toString();
const entireDate = `${realMonth}/${date}/${year}
${hour}:${minute}:${second}`
return db.none('insert into notes (note_content, users_id, all_tickets_id, time_posted) values ($1, $2, $3, $4)', [notecontent, users_id, all_tickets_id, entireDate]);
}
// Function that will select by id
// static getDetailById(id) {
// return db.one(`select `)
// }
}
module.exports = Details;
<file_sep>/seed.sql
insert into users
(first_name, last_name, email, password)
VALUES
('Anthony', 'Moss', '<EMAIL>', '<PASSWORD>')
;
-- insert into all_tickets
-- (issue_desc, ticket_status, users_id)
-- VALUES
-- ()
-- ;
-- insert into open_tickets
-- (all_tickets_id)
-- VALUES
-- ()
-- ;
-- insert into pending_tickets
-- (all_tickets_id, users_id, time_started)
-- VALUES
-- ()
-- ;
-- insert into completed_tickets
-- (all_tickets_id, users_id, time_ended)
-- VALUES
-- ()
-- ;
-- insert into notes
-- (note_content, all_tickets_id, users_id, time_posted)
-- VALUES
-- ()<file_sep>/routes/request.js
const express = require("express");
const Router = express.Router;
const requestRoutes = Router();
const { showRequestPage } = require("../controllers/request");
requestRoutes.get("/", showRequestPage);
module.exports = requestRoutes;
<file_sep>/controllers/completedTickets.js
const User = require("../models/user");
const completedTickets = require("../models/completedTickets");
const allTickets = require("../models/allTickets")
async function completedTicketsPage(req, res) {
const theUser = await User.getById(req.session.user);
const completedTickets = await allTickets.getAll();
res.render("completedTickets", {
locals: {
firtName: theUser.firstName,
message: "View Completed Tickets Below!",
completedTickets
}
});
}
async function updateCompletedTicketsPage(req, res) {
console.log('The id is ', req.params);
const mainTicketId = parseInt(req.params.id);
console.log(mainTicketId);
await allTickets.updateToCompleted(mainTicketId);
res.redirect('/dashboard');
}
module.exports = {
completedTicketsPage,
updateCompletedTicketsPage
};
<file_sep>/controllers/details.js
const User = require("../models/user");
const allTickets = require("../models/allTickets");
const openTickets = require("../models/openTickets");
const pendingTickets = require("../models/pendingTickets");
const completedTickets = require("../models/completedTickets");
const details = require("../models/details")
// For this function it needs to take in or get a single tickets id from all_tickets then call the getTicketsInfo function
// passing it the ticket id so we can get all information about that ticket to render to page.
async function loadDetailsPage(req, res) {
const user = await User.getById(req.session.user);
console.log('user ', user);
const ticketId = req.params.id;
const ticket = await allTickets.getTicketInfo(ticketId);
const description = allTickets.issue_desc;
console.log('Ticket : ', ticket);
const openTicket = new openTickets(req.body.id);
const detailsArray = await details.getNotesByTicketId(ticketId);
if(openTicket) {
res.render("details", {
locals: {
ticketId,
message: ticketId,
firstName: user.first_name,
ticketDesc: description,
detail: detailsArray
}
});
}
}
async function renderNewDetailsAfterSubmission(req, res) {
const user = await User.getById(req.session.user);
const ticketId = req.params.id;
console.log('THIS IS THE ID! ', ticketId);
const allTheTickets = await allTickets.getTicketInfo(ticketId);
const description = allTheTickets.issue_desc;
console.log('HERE IS THE DESC ', description);
await details.newDetailSubmitted(req.body.note_content, user.id, ticketId, req.body.time_posted);
const detailsArray = await details.getNotesByTicketId(ticketId);
const newDetails = new details(req.body.note_content, req.body.users_id, req.body.all_tickets_id, req.body.time_posted);
if(newDetails) {
res.render("details", {
locals: {
ticketId,
message: ticketId,
firstName: user.first_name,
ticketDesc: description,
ticketCreated: ticketId.timestamp,
detail: detailsArray
}
});
}
}
module.exports = {
loadDetailsPage,
renderNewDetailsAfterSubmission
}<file_sep>/test/test.js
const User = require('../models/user')
const chai = require('chai');
const expect = chai.expect;
const chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised).should();
describe('User model', function () {
it('should be able to retrieve by id', async() => {
const theUser = await User.getById(1);
theUser.should.be.an.instanceOf(User);
});
it('should error if no user by id', async ()=> {
const theUser = await User.getById(27645);
expect(theUser).to.be.null;
});
it('should update the user', async () => {
const theUser = await User.getById(1);
theUser.email = '<EMAIL>';
await theUser.save();
const alsoTheUser = await User.getById(2);
expect(theUser.email).to.equal('<EMAIL>');
});
it ('should be able to check for correct passwords', async () => {
const theUser = await User.getById(1);
theUser.setPassword("<PASSWORD>");
await theUser.save();
const sameUser = await User.getById(1);
const isCorrectPassword = theUser.checkPassword("<PASSWORD>");
expect(isCorrectPassword).to.be.true;
const isNotCorrectPassword = sameUser.checkPassword('<PASSWORD>');
expect(isNotCorrectPassword).to.be.false;
});
it('should encrypt the password', async () => {
const theUser = await User.getById(1);
theUser.setPassword("<PASSWORD>");
expect (theUser.password).not.to.equal('<PASSWORD>');
});
});<file_sep>/schema.sql
create table users (
id serial primary key,
first_name varchar(100),
last_name varchar(100),
email varchar(200),
password varchar(500)
);
create table all_tickets (
id serial primary key,
issue_desc VARCHAR(500),
-- notes_id integer references notes,
time_posted VARCHAR(500),
ticket_status integer,
users_id integer references users
-- open_tickets_id integer references open_tickets,
-- pending_tickets_id integer references pending_tickets,
-- completed_tickets_id integer references completed_tickets
-- do we want to have avail_key, pend_key, completed_key to track ticket as it moves through tables
-- working_status
);
-- do we need all_tickets? can we just have the avail, pending, completed?
create table open_tickets (
id serial primary key,
all_tickets_id integer references all_tickets
-- time in queue
);
create table pending_tickets (
id serial primary key,
all_tickets_id integer references all_tickets,
users_id integer references users,
time_started TIMESTAMP
);
create table completed_tickets (
id serial primary key,
all_tickets_id integer references all_tickets,
users_id integer references users,
time_ended TIMESTAMP
);
create table notes (
id serial primary key,
note_content varchar(250),
users_id integer references users,
all_tickets_id integer references all_tickets,
time_posted VARCHAR(500)
);<file_sep>/models/openTickets.js
// Bring in the databse connection.
const db = require("./conn");
const bcrpyt = require("bcryptjs");
// Need a User class.
// Classes should start with an uppercase letter
class OpenTickets {
constructor(id, all_tickets_id, ticket_status) {
this.id = id;
this.allTicketsId = all_tickets_id;
this.ticket_status = ticket_status;
// this.notes_id = notes_id;
//this.timePosted = time_posted;
// this.pending_tickets_id = pending_tickets_id;
// this.completed_tickets_id = completed_tickets_id;
}
static getAll() {
return db.any(`select * from open_tickets`).then(arrayOfTickets => {
console.log(arrayOfTickets);
return arrayOfTickets;
});
}
static getByAllTicketsId() {
return db
.any(
`select * from open_tickets o inner join all_tickets a on o.all_tickets_id=a.id`
)
.then(arrayOfOpenTicketsData => {
return arrayOfOpenTicketsData;
});
}
static getOneByAllTicketsId(id) {
return db.one(`select * from all_tickets a inner join open_tickets o on a.id=o.all_tickets_id`)
.then((ticketData) => {
return ticketData
})
}
}
module.exports = OpenTickets;
<file_sep>/models/completedTickets.js
// Bring in the databse connection.
const db = require("./conn");
const bcrpyt = require("bcryptjs");
// Need a User class.
// Classes should start with an uppercase letter
class CompletedTickets {
constructor(id, all_tickets_id, users_id, time_ended) {
this.id = id;
this.all_tickets_id = all_tickets_id;
this.users_id = users_id;
this.time_ended = time_ended;
}
static getAll() {
return db.any(`select * from completed_tickets`).then(arrayOfTickets => {
console.log(arrayOfTickets);
return arrayOfTickets;
});
}
static getByAllTicketsId() {
return db
.any(`select * from completed_tickets c inner join all_tickets a on c.all_tickets_id=a.id`)
.then(arrayOfCompletedTicketsData => {
return arrayOfCompletedTicketsData;
});
}
}
module.exports = CompletedTickets;
<file_sep>/routes/createUser.js
const express = require("express");
const createUserRouter = express.Router();
const {
showCreateUser,
checkIfEmailInUse
} = require("../controllers/createUser");
createUserRouter.get("/", showCreateUser);
createUserRouter.post("/", checkIfEmailInUse);
module.exports = createUserRouter;<file_sep>/routes/pendingTickets.js
const express = require("express");
const Router = express.Router;
const pendingTicketsRoutes = Router();
const { pendingTicketsPage, updateOpenTicketsPage } = require("../controllers/pendingTickets");
pendingTicketsRoutes.get("/", pendingTicketsPage);
pendingTicketsRoutes.get("/:id", updateOpenTicketsPage);
module.exports = pendingTicketsRoutes;
<file_sep>/models/allTickets.js
// Bring in the databse connection.
const db = require("./conn");
const bcrpyt = require("bcryptjs");
// Need a User class.
// Classes should start with an uppercase letter
class AllTickets {
constructor(id, issue_desc) {
this.id = id;
this.issueDesc = issue_desc;
}
static getAll() {
return db.any(`select * from all_tickets`)
.then((arrayOfTickets) => {
return arrayOfTickets
});
}
static newIssueSubmitted(issue_desc) {
const timestamp = new Date();
const month = timestamp.getMonth() + 1;
const realMonth = month.toString();
const date = timestamp.getDate().toString();
const year = timestamp.getFullYear().toString();
const hour = timestamp.getHours().toString();
const minute = timestamp.getMinutes().toString();
const second = timestamp.getSeconds().toString();
const entireDate = `${realMonth}/${date}/${year}
${hour}:${minute}:${second}`
const not = null;
return db.none(`insert into all_tickets (issue_desc, time_posted, ticket_status, users_id)
values ('${issue_desc}', '${entireDate}', 0, null)`);
}
// static getTicketInfoByIssue(issueDesc) {
// return db.one('select * from all_tickets a inner join open_tickets o on a.id = o.all_tickets_id where a.issue_desc = $1', [issueDesc])
// .then((ticketData) => {
// return ticketData;
// });
// }
static getTicketInfo(id) {
return db.one('select * from all_tickets t where t.id = $1', [id])
.then((ticketData) => {
console.log(ticketData);
return ticketData;
});
}
// CHANGE STATUS TO 'PENDING'
static async updateToPending(userId, ticketId){
return await db.none('UPDATE all_tickets SET ticket_status = 1, users_id = $1 WHERE id = $2', [userId, ticketId])
}
static async updateToCompleted(id){
return await db.none('UPDATE all_tickets SET ticket_status = 2 WHERE id = $1', [id])
}
// static async
static getOpenTickets(ticket_status) {
return db.any('select * from all_tickets where ticket_status = $1', [ticket_status])
.then((ticketData) => {
console.log(ticketData)
return ticketData;
});
}
static getTicketInfoByUserIdAndStatus(userId, ticket_status) {
return db.any('select * from all_tickets where users_id = $1 and ticket_status = $2', [userId, ticket_status])
.then((ticketData) => {
return ticketData;
});
}
static getTicketPendingTimestamp() {
return db.any(`select p.*, a.issue_desc, a.time_posted from pending_tickets p inner join all_tickets a on p.all_tickets_id=a.id`)
.then(arrayOfPendingTicketsData => {
return arrayOfPendingTicketsData;
});
}
}
module.exports = AllTickets;
<file_sep>/controllers/openTickets.js
// const db = require('./conn');
const User = require("../models/user");
const allTickets = require("../models/allTickets");
async function openTicketsPage(req, res) {
const open = 0;
const theUser = await User.getById(req.session.user);
const allOpenTickets = await allTickets.getOpenTickets(open);
// const joinTables = await allTickets.getTicketPendingTimestamp();
res.render("openTickets", {
locals: {
firtName: theUser.firstName,
message: "View Open Tickets Below!",
tickets: allOpenTickets
// join: joinTables
}
});
}
module.exports = {
openTicketsPage
};<file_sep>/routes/homepage.js
const express = require("express");
const Router = express.Router;
const homepageRoutes = Router();
const { showHomepage } = require("../controllers/homepage");
homepageRoutes.get("/", showHomepage);
module.exports = homepageRoutes;
<file_sep>/models/user.js
// Bring in the databse connection.
const db = require("./conn");
const bcrpyt = require("bcryptjs");
const escapeHtml = require("../utils");
// Need a User class.
// Classes should start with an uppercase letter
class User {
constructor(id, first_name, last_name, email, password) {
// In python, we say "self"
//In Javascript, we say "this"
this.id = id;
this.first_name = first_name;
this.last_name = last_name;
this.email = email;
this.password = password;
}
static delete(id) {
return db.result("delete from users where id=$1", [id]);
}
setPassword(newPassword) {
const salt = bcrpyt.genSaltSync(10);
const hash = bcrpyt.hashSync(newPassword, salt);
this.password = hash;
}
static hashPass(newPassword) {
const salt = bcrpyt.genSaltSync(10);
const hash = bcrpyt.hashSync(newPassword, salt);
return hash;
}
static add(userData) {
//do an insert into the database
// not using ${} because I dont want to interpolate
// using $() so that pg-promise does *safe* interpolation
const firstName = escapeHtml(userData.first_name);
const lastName = escapeHtml(userData.last_name);
const email = escapeHtml(userData.email);
const aPassword = escapeHtml(userData.password);
const hashed = User.hashPass(aPassword);
return db
.one(
`
insert into users
(first_name, last_name, email, password)
values
($1, $2, $3, $4)
returning id, first_name, last_name
`,
[
firstName,
lastName,
email,
hashed
]
)
.then(data => {
return data.id;
});
}
// "static" means that the function is something
// the class can do, but an instance cannot.
static getById(id) {
return db
.one(`select * from users where id=${id}`)
.then(userData => {
//You *must* use the `new` keyword when you call a JavaScript constuctor
const userInstance = new User(
userData.id,
userData.first_name,
userData.last_name,
userData.email,
userData.password
);
return userInstance;
})
.catch(() => {
return null; //signal an invalid value
});
}
static getAll() {
return db.any(`select * from users`).then(arrayOfUsers => {
return arrayOfUsers.map(userData => {
const aUser = new User(
userData.id,
userData.first_name,
userData.last_name,
userData.email,
userData.password
);
return aUser;
});
});
}
save() {
// use. result when you might want a report about
// how many rows got affected
return db.result(
`update users set first_name='${this.first_name}', last_name='${
this.last_name
}', email='${this.email}', password='${<PASSWORD>}' where id=${
this.id
} `
);
}
checkPassword(aPassword) {
//const isCorrect = bcrypt.compareSync(aPassword, this.password);
return bcrpyt.compareSync(aPassword, this.password);
}
// setPassword(newPassword) {
// const salt = bcrpyt.genSaltSync(10);
// const hash = bcrpyt.hashSync(newPassword, salt);
// this.password = hash;
// }
static getByEmail(email) {
return db
.one(`select * from users where email=$1`, [email])
.then(userData => {
const aUser = new User(
userData.id,
userData.first_name,
userData.last_name,
userData.email,
userData.password
);
console.log(`You created a new account with the email ${userData.email}!`);
return aUser;
});
}
static checkEmail(userData) {
const aEmail = escapeHtml(userData.email);
return db.one(`select email from users where email=$1`, [aEmail])
.catch(() => {
return userData; //signals that email is not in database, invalid/nonexistant value
});
}
// get tickets() {
// return db
// .any(`select * from tickets where user_id=${this.id}`)
// .then(arrayOfReviewData => {
// const arrayOfReviewInstances = [];
// arrayOfReviewData.forEach(data => {
// const newInstance = new Review(
// data.id,
// data.score,
// data.content,
// data.restaurant_id,
// data.user_id
// );
// arrayOfReviewInstances.push(newInstance);
// });
// return arrayOfReviewInstances;
// });
}
// async function demo() {
// const user = await User.getByEmail("<EMAIL>");
// user.setPassword("<PASSWORD>");
// await user.save();
// console.log("you did the thing");
// }
// demo();
module.exports = User;
<file_sep>/controllers/allTickets.js
const User = require("../models/user");
const allTickets = require("../models/allTickets");
async function allTicketsPage(req, res) {
const theUser = await User.getById(req.session.user);
const arrayOfTickets = await allTickets.getAll();
res.render("allTickets", {
locals: {
firtName: theUser.firstName,
message: "View All Tickets Below!",
tickets: arrayOfTickets
}
});
}
async function submitRequest(req, res) {
// const theUser = await User.getById(req.session.user);
await allTickets.newIssueSubmitted(req.body.issue_desc);
// console.log(newTicket);
// newTicket;
const newRequests = new allTickets(req.body.issue_desc);
if (newRequests) {
res.render("thankyou", {
locals: {
message: "Welcome!"
}
});
}
}
module.exports = {
allTicketsPage,
submitRequest,
};
| 56d3c437c425695d6d59e3a72e78073f7b17aa68 | [
"JavaScript",
"SQL",
"Markdown"
] | 23 | JavaScript | Anthony-Moss/DoTheThing | a7b5f914802cb3713763b8a6fe496dcc555764d9 | 7e3d53bddff09c11a98ad8adaec4af5287324373 |
refs/heads/master | <file_sep>package utilty;
public class missJava {
/// miss Java soo much!
// I added this line newly from github
}
| a3e1b33e24e077bd785ec538dcf689017ee9375b | [
"Java"
] | 1 | Java | Resho92/Summer_2020_B20_git | 561fa4e4cb3f32dfb75683418280bf8ed3a5896b | 8fee8273c98742c7c6704a67d947662e81654591 |
refs/heads/master | <file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Ethernet_Simulation
{
public partial class mainForm : Form
{
//Global Variables for simulator
Boolean[] VALID_INPUTS = new Boolean[5];
static Random RANDOM_X = new Random();
static Random RANDOM_C = new Random();
static Random RANDOM_S = new Random();
static Random RANDOM_COMPUTER = new Random();
String output_string;
int MAX_WAIT_TIME = 0;
int TOTAL_SLOTS_USED = 0;
Boolean MED_DET = false;
Boolean HIGH_DET = false;
Boolean MAX_OUTPUT = false;
int MAX_OUTPUT_TIME = 100;
DateTime start;
DateTime finish;
public mainForm()
{
InitializeComponent();
}
//Method for when "Begin Simulation" is clicked
private void runBtn_Click(object sender, EventArgs e)
{
int n=0, t=0, k=0, s=0, x = 0;
//Check if the input values are numeric. If so, set respective variable to value
VALID_INPUTS[0] = is_number(nBox.Text);
if (VALID_INPUTS[0])
{
n = Convert.ToInt32(nBox.Text);
}
VALID_INPUTS[1] = is_number(tBox.Text);
if (VALID_INPUTS[1])
{
t = Convert.ToInt32(tBox.Text);
}
VALID_INPUTS[2] = is_number(kBox.Text);
if (VALID_INPUTS[2])
{
k = Convert.ToInt32(kBox.Text);
}
VALID_INPUTS[3] = is_number(sBox.Text);
if (VALID_INPUTS[3])
{
s = Convert.ToInt32(sBox.Text);
}
VALID_INPUTS[4] = is_number(xBox.Text);
if (VALID_INPUTS[4])
{
x = Convert.ToInt32(xBox.Text);
}
//Check if all variables have valid inputs
if (Array.IndexOf(VALID_INPUTS, false) == -1)
{
//All variables are valid. Begin simulation
outputBox.Text = "PLEASE WAIT ...";
begin_simulation(n, t, k, s, x);
}
else
{
//At least one of the inputs are not valid
outputBox.Text = "ERROR WITH INPUT VALUES. PLEASE CHECK VALUES AND RERUN SIMULATION\n";
}
}
//Supporting method for runBtn_Click
//Checks if input string is a number
//Returns Boolean
private bool is_number(string input)
{
//Try and convert the input
try
{
int n = Convert.ToInt32(input);
//Input is a number
return true;
}
catch (FormatException e)
{
Console.WriteLine(e);
}
//Input is not a number
return false;
}
//Runs the simulation from beginning to end using the given values from the user
//Also displays the output of the simulation
private void begin_simulation(int n, int t, int k, int s, int x)
{
//Initial local variables.
int S = s;
MAX_WAIT_TIME = 0; //Stores the maximum waiting time for a computer
TOTAL_SLOTS_USED = 0; //Stores the number of time slots a computer accesses the channel
MAX_OUTPUT = false; //Reset MAX_OUTPUT Boolean
int[] random_computers = new int[x+5]; //Int array that stores the computers that are randomly selected [Array is as big as X input]
int[] back_off_timer = new int[n+1]; //Int array that stores the wait time off all computers [Array is as big as N+1 input]
for(int time=0; time < back_off_timer.Length ; time++)
{
back_off_timer[time] = -1; //Set the wait times for all computers to -1
}
Boolean slotted_machine = false;
int slotted_machine_number = 0;
//Outputs text about simulation
string newsection = "========================================" + Environment.NewLine;
start = DateTime.Now;
outputBox.Text = "NEW SIMULATION: " + start.ToString() + Environment.NewLine;
outputBox.Text += newsection;
outputBox.Text += "The simulation will now run with the following inputs;" + Environment.NewLine;
outputBox.Text += "N = " + n + "\tT = " + t + Environment.NewLine;
outputBox.Text += "K = " + k + "\tS = " + s + Environment.NewLine;
outputBox.Text += "X = " + x + Environment.NewLine;
outputBox.Text += newsection;
//Time slot loop that runs from 0 to T
for (int ti = 0; ti < t; ti++)
{
//Update output flag if time slot equals or passes MAX_OUTPUT_TIME
if(ti >= MAX_OUTPUT_TIME)
{
MAX_OUTPUT = true;
}
if(MED_DET && !MAX_OUTPUT) output_string += "TIME SLOT #" + (ti+1);
slotted_machine_number = Array.IndexOf(back_off_timer, 0);
if (slotted_machine_number > -1)
{
slotted_machine = true;
if (HIGH_DET && !MAX_OUTPUT) output_string += " (TIME SLOT ALSO ASSIGNED TO " + slotted_machine_number + ")";
}
output_string += Environment.NewLine;
//Randomly select number of computers that will attempt to access channel [Random value from 0 to X]
int xi = RANDOM_X.Next(x+1);
//Randomly selected number of computers is 0
if(xi == 0)
{
if (slotted_machine)
{
if (MED_DET && !MAX_OUTPUT) output_string += "ACCESS GRANTED TO COMPUTER " + slotted_machine_number + Environment.NewLine;
//Increase "total slots used" by 1
TOTAL_SLOTS_USED++;
}
else
{
if (MED_DET && !MAX_OUTPUT) output_string += "NO ACCESS TO THE CHANNEL" + Environment.NewLine;
}
}
//Randomly selected nmber of computers is 1
else if(xi == 1)
{
//Randomly select next computer number
int next_computer = get_next_computer(n);
if (slotted_machine)
{
random_computers[0] = next_computer;
random_computers[1] = slotted_machine_number;
int selected_computer = RANDOM_COMPUTER.Next(2);
if (MED_DET && !MAX_OUTPUT) output_string += "ACCESS GRANTED TO COMPUTER " + next_computer + Environment.NewLine;
TOTAL_SLOTS_USED++;
if(selected_computer == 0)
{
//Selected computer was random computer
back_off_timer[random_computers[0]] = next_time_slot(S);
if (HIGH_DET && !MAX_OUTPUT) output_string += " COMPUTER " + random_computers[0] + " BACKED OFF AND NOW HAS A WAIT TIME OF " + back_off_timer[random_computers[0]] + Environment.NewLine;
}
else
{
//selected computer was slotted machine
back_off_timer[random_computers[1]] = next_time_slot(S);
if (HIGH_DET && !MAX_OUTPUT) output_string += " COMPUTER " + random_computers[1] + " BACKED OFF AND NOW HAS A WAIT TIME OF " + back_off_timer[random_computers[1]] + Environment.NewLine;
}
//Double S due to collision
if (S*2 < t)
{
S = S * 2;
}
}
else
{
//Output message and computer that gained access to channel
if (MED_DET && !MAX_OUTPUT) output_string += "ACCESS GRANTED TO COMPUTER " + next_computer + Environment.NewLine;
//Increase "total slots used" by 1
TOTAL_SLOTS_USED++;
}
}
else
{
//Output message
if (MED_DET && !MAX_OUTPUT) output_string += " " + xi + " COMPUTERS ATTEMPTING TO ACCESS THE CHANNEL";
if (HIGH_DET && !MAX_OUTPUT) output_string += " (";
//Loop to select random computers
for (int ci = 0; ci < xi; ci++)
{
//Randomly select next computer number
int next_computer = get_next_computer(n);
//Make sure randomly selected computer is not already in random_computers arrray
while ((Array.IndexOf(random_computers, next_computer)>-1) && (back_off_timer[next_computer] < 1))
{
//Keep randomly choosing a computer number number until it is not in random_computers array
next_computer = get_next_computer(n);
}
//Add randomly selected computer to random_computers array
random_computers[ci] = next_computer;
if (HIGH_DET && !MAX_OUTPUT && (xi-1 == ci))
{
output_string += next_computer + ")";
}
else if (HIGH_DET && !MAX_OUTPUT && (xi - 1 != ci))
{
output_string += next_computer + ", ";
}
}
if(slotted_machine)
{
random_computers[xi] = slotted_machine_number;
}
if (MED_DET && !MAX_OUTPUT) output_string += Environment.NewLine;
//Randomly select a computer from array of computers attempting to access channel
int selected_computer = 0;
if (slotted_machine)
{
selected_computer = RANDOM_COMPUTER.Next(xi+1);
}
else
{
selected_computer = RANDOM_COMPUTER.Next(xi);
}
if (MED_DET && !MAX_OUTPUT) output_string += "ACCESS GRANTED TO COMPUTER " + random_computers[selected_computer] + Environment.NewLine;
//Increase "total slots used" by 1
TOTAL_SLOTS_USED++;
//Loop to update wait_time for computers that did not access channel.
foreach (int comp in random_computers)
{
//Make sure to only update wait_time for computers that were selected AND did not access the channel
if (comp != random_computers[selected_computer] && comp > 0)
{
//Update wait_time for current computer
back_off_timer[comp] = next_time_slot(S);
if (back_off_timer[comp] > MAX_WAIT_TIME)
{
//If the current calculated wait_time is greater than current MAX_WAIT_TIME, set MAX_WAIT_TIME to calculated wait_time
MAX_WAIT_TIME = back_off_timer[comp];
}
//Report updated wait_time for computers
if (HIGH_DET && !MAX_OUTPUT) output_string += " COMPUTER " + comp + " BACKED OFF AND NOW HAS A WAIT TIME OF " + back_off_timer[comp] + Environment.NewLine;
}
}
//Reset the random_computers array
reset_random_computers(random_computers);
//Double S due to collision.
if (S*2 < t)
{
S = S * 2;
}
}
if (MED_DET && (!MAX_OUTPUT)) outputBox.Text += output_string + newsection;
output_string = "";
reduce_wait_timer(back_off_timer);
slotted_machine = false;
//End of Loop
}//End of Simulation
//Display the results of "total bytes sent" and "maximum node wait time"
finish = DateTime.Now;
TimeSpan elapsed = finish.Subtract(start);
outputBox.Text += "SIMULATION COMPLETE: " + finish.ToString() + " (" + elapsed.TotalSeconds + " Second(s))"+ Environment.NewLine;
int bytes = (k * TOTAL_SLOTS_USED);
outputBox.Text += "Total Bytes Sent: " + bytes;
//Converting to Kilobytes
if(bytes > 1024)
{
double kilo = bytes / 1024.00;
outputBox.Text += " / " + kilo.ToString("#.##") +" KB";
}
//Converting to Megabytes
if (bytes > 1048576)
{
double mega = bytes / 1048576.00;
outputBox.Text += " / " + mega.ToString("#.##") +" MB";
}
//Converting to Gigabytes
if (bytes > 1073741824)
{
double giga = bytes / 1073741824.00;
outputBox.Text += " / " + giga.ToString("#.##") +" GB";
}
outputBox.Text += " (" + TOTAL_SLOTS_USED + " slots used)" + Environment.NewLine;
outputBox.Text += "Maximum Wait Time: " + MAX_WAIT_TIME + " time slot(s)" + Environment.NewLine;
}
//Reduces the amount of time slots that a computer should wait
//Called after every time slot
private void reduce_wait_timer(int[] back_off_timer)
{
for(int c = 1; c<back_off_timer.Length; c++)
{
if(back_off_timer[c] > -1)
{
back_off_timer[c]--;
}
}
}
//Resets the random_computers array so that it can be used again
private void reset_random_computers(int[] random_computers)
{
for (int c = 0; c < random_computers.Length; c++)
{
random_computers[c] = 0;
}
}
//Supporting method that randomly selects a computer number from 1 to N
private int get_next_computer(int n)
{
return RANDOM_C.Next(1,n+1);
}
//Picks a random amount of time slots to wait before a computer can attempt to communicate again.
private int next_time_slot(int s)
{
int future_time_slot = RANDOM_S.Next(1,s+1);
return future_time_slot;
}
//Clears output textbox
private void clearBtn_Click(object sender, EventArgs e)
{
outputBox.Text = "";
}
//Supporting method to set detail level in outputbox. Called whenever detail level is changed.
private void Detail_Change(object sender, EventArgs e)
{
//Alot of detail
if (radioButton3.Checked)
{
HIGH_DET = true;
MED_DET = true;
}
//Some detail
else if (radioButton2.Checked)
{
HIGH_DET = false;
MED_DET = true;
}
//No detail
else
{
HIGH_DET = false;
MED_DET = false;
}
}
}
}
<file_sep>Ethernet-Simulator
==================
EEL 5718 Computer Communication Networks Semester project
| 2f3af28ce905f0a93517f00bc78d865655a74e66 | [
"Markdown",
"C#"
] | 2 | C# | kpine002/Ethernet-Simulator | 034d8bb1613c2dd86a5969ce6151e26de247889d | bdbe2ba5350102c406671e2bfb56f2e164956d26 |
refs/heads/master | <repo_name>Kimball-qq/SXshop<file_sep>/apps/trade/views.py
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from utils.permissions import IsOwnerOrReadOnly
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.authentication import SessionAuthentication
from .serializers import ShopCartSerializer
from .models import ShoppingCart
class ShoppingCartViewset(viewsets.ModelViewSet):
"""
่ดญ็ฉ่ฝฆๅ่ฝ
list:่ทๅ่ดญ็ฉ่ฝฆ่ฏฆๆ
create๏ผๅ ๅ
ฅ่ดญ็ฉ่ฝฆ
delete๏ผๅ ้ค่ดญ็ฉ่ฎฐๅฝ
"""
permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
serializer_class = ShopCartSerializer
lookup_field = "goods_id"
def get_queryset(self):
return ShoppingCart.objects.filter(user=self.request.user) | e88c143095b61040eaf0cafedac54be942a4ea98 | [
"Python"
] | 1 | Python | Kimball-qq/SXshop | ee963c88e1a0000124c348e56b76cb332cb1b06b | 25949955171b548de068932c9a5ccccac3203f59 |
refs/heads/master | <repo_name>robo8080/M5Stack_Sokoban<file_sep>/README.md
# M5Stack_Sokoban
MhageGHใใใฎๅๅบซ็ชใM5Stackใซ็งปๆคใใใฆใใใ ใใพใใใ<br><br>
ใชใชใธใใซใฏใใกใใ<br>
Sokoban on esp32 and ILI9328 <https://github.com/MhageGH/esp32_ILI9328_Sokoban><br>
---
### ๅฟ
่ฆใช็ฉ ###
* [M5Stack](http://www.m5stack.com/ "Title") (Grayใงๅไฝ็ขบ่ชใใใพใใใ)<br>
* Arduino IDE (1.8.5ใงๅไฝ็ขบ่ชใใใพใใใ)<br>
* [Arduino core for the ESP32](https://github.com/espressif/arduino-esp32 "Title")
* [M5Stack Library](https://github.com/m5stack/M5Stack.git "Title")
่ฃ่ถณ : ArduinoIDEใธใฎM5StackใใผใใฎใคใณในใใผใซใฏM5Stackใซไปๅฑใฎ่ชฌๆๆธใฎ้ใใซใใฃใฆใไธๆใใใใพใใใงใใใ<br>
M5Stack LibraryใใคใณในใใผใซใใใฐใใผใใชในใใซใM5Stackใ็พใใพใใใ<br>
<br><br><br>
### ๆไฝๆนๆณ ###
<br>
* Aใใฟใณ๏ผๅทฆ็งปๅ<br>
* Bใใฟใณ๏ผไธ็งปๅ<br>
* Cใใฟใณ๏ผๅณ็งปๅ<br>
* AใใฟใณCใใฟใณๅๆๆผใ๏ผไธ็งปๅ<br>
* BใใฟใณCใใฟใณๅๆๆผใ๏ผใชในใฟใผใ<br><br>
ใใฟใณใฎๅๆๆผใใฏๅฐใๆ
ฃใใๅฟ
่ฆใใใใใพใใใ<br>
๏ผใคใฎใใฟใณใๅฐใ้ทใใซๆผใๆใใซใใใจไธๆใใใใจๆใใพใใ<br><br><br>
<file_sep>/M5Stack_Sokoban/M5Stack_Sokoban.ino
//#define WIFI_UDP_CONTROLLER_USE // if you don't use WiFi UDP Controller, delete this line. In the case, you can use serial port controller.
#include <M5Stack.h>
#ifdef WIFI_UDP_CONTROLLER_USE
#include <WiFi.h>
#include <WiFiUdp.h>
#else
#include "WaveAnimation.h"
#endif
#include "Map.h"
#include "BlockImage.h"
#include "WalkAnimation.h"
#include "PushAnimation.h"
#include "StageChangeAnimation.h"
#include "StageLogo.h"
#include "ThankYouLogo.h"
#ifdef WIFI_UDP_CONTROLLER_USE
WiFiUDP udp;
#endif
const uint16_t backgroundColor = 0xC7EF;
uint16_t buffer100x100[100][100];
uint16_t stageLogoImage[41][119];
uint16_t thankYouLogoImage[58][320];
const int h = 30, w = 30;
uint16_t blockImage[h][w];
uint16_t walkingHeight[2 * h][w];
uint16_t walkingWidth[h][2 * w];
uint16_t pushingHeight[3 * h][w];
uint16_t pushingWidth[h][3 * w];
const int transparent = 0x18C3;
int staticMap[mapH][mapW];
int activeMap[mapH][mapW];
enum Dir { UP, RIGHT, DOWN, LEFT };
void fillImage(void *image, int x, int y, int w, int h) {
uint16_t* p = (uint16_t*)image;
M5.Lcd.startWrite(); // Requires start/end transaction now
M5.Lcd.setAddrWindow(x, y, x+w-1, y+h-1);
for ( int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
M5.Lcd.writePixel(p[i*w+j]);
}
}
M5.Lcd.endWrite(); // End last TFT transaction
}
void DrawBlock(int x, int y) {
for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) blockImage[i][j] = blockImages[activeMap[y][x]][i][j];
fillImage(blockImage, x * w , y * h , w, h);
}
void Walk(Dir dir, int x, int y) {
const int numAnimation = 30;
for (int t = 0; t < numAnimation + 1; ++t) {
if (dir == UP) {
for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) walkingHeight[i][j] = blockImages[staticMap[y - 1][x]][i][j];
for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) walkingHeight[h + i][j] = blockImages[staticMap[y][x]][i][j];
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
uint16_t pixel = walkAnimation[t][i][j];
if (pixel != transparent) walkingHeight[(numAnimation - t) * h / numAnimation + i][j] = pixel;
}
}
fillImage(walkingHeight, x * w , (y - 1) * h , w, 2 * h);
}
else if (dir == DOWN) {
for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) walkingHeight[i][j] = blockImages[staticMap[y][x]][i][j];
for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) walkingHeight[h + i][j] = blockImages[staticMap[y + 1][x]][i][j];
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
uint16_t pixel = walkAnimation[t][h - 1 - i][w - 1 - j];
if (pixel != transparent) walkingHeight[t * h / numAnimation + i][j] = pixel;
}
}
fillImage(walkingHeight, x * w , y * h , w, 2 * h);
}
else if (dir == RIGHT) {
for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) walkingWidth[i][j] = blockImages[staticMap[y][x]][i][j];
for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) walkingWidth[i][w + j] = blockImages[staticMap[y][x + 1]][i][j];
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
uint16_t pixel = walkAnimation[t][w - 1 - j][i];
if (pixel != transparent) walkingWidth[i][t * w / numAnimation + j] = pixel;
}
}
fillImage(walkingWidth, x * w , y * h , 2 * w, h);
}
else if (dir == LEFT) {
for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) walkingWidth[i][j] = blockImages[staticMap[y][x - 1]][i][j];
for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) walkingWidth[i][w + j] = blockImages[staticMap[y][x]][i][j];
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
uint16_t pixel = walkAnimation[t][j][h - 1 - i];
if (pixel != transparent) walkingWidth[i][(numAnimation - t) * w / numAnimation + j] = pixel;
}
}
fillImage(walkingWidth, (x - 1) * w , y * h , 2 * w, h);
}
delay(10);
}
}
void Push(Dir dir, int x, int y) {
const int numAnimation = 30;
for (int t = 0; t < numAnimation + 1; ++t) {
if (dir == UP) {
for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) pushingHeight[i][j] = blockImages[staticMap[y - 2][x]][i][j];
for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) pushingHeight[h + i][j] = blockImages[staticMap[y - 1][x]][i][j];
for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) pushingHeight[2 * h + i][j] = blockImages[staticMap[y][x]][i][j];
for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) pushingHeight[(numAnimation - t) * h / numAnimation + i][j] = blockImages[2][i][j];
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
uint16_t pixel = pushAnimation[t][i][j];
if (pixel != transparent) pushingHeight[(numAnimation - t) * h / numAnimation + h + i][j] = pixel;
}
}
fillImage(pushingHeight, x * w , (y - 2) * h , w, 3 * h);
}
else if (dir == DOWN) {
for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) pushingHeight[i][j] = blockImages[staticMap[y][x]][i][j];
for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) pushingHeight[h + i][j] = blockImages[staticMap[y + 1][x]][i][j];
for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) pushingHeight[2 * h + i][j] = blockImages[staticMap[y + 2][x]][i][j];
for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) pushingHeight[t * h / numAnimation + h + i][j] = blockImages[2][i][j];
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
uint16_t pixel = pushAnimation[t][h - 1 - i][w - 1 - j];
if (pixel != transparent) pushingHeight[t * h / numAnimation + i][j] = pixel;
}
}
fillImage(pushingHeight, x * w , y * h , w, 3 * h);
}
else if (dir == RIGHT) {
for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) pushingWidth[i][j] = blockImages[staticMap[y][x]][i][j];
for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) pushingWidth[i][w + j] = blockImages[staticMap[y][x + 1]][i][j];
for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) pushingWidth[i][2 * w + j] = blockImages[staticMap[y][x + 2]][i][j];
for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) pushingWidth[i][t * w / numAnimation + w + j] = blockImages[2][i][j];
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
uint16_t pixel = pushAnimation[t][w - 1 - j][i];
if (pixel != transparent) pushingWidth[i][t * w / numAnimation + j] = pixel;
}
}
fillImage(pushingWidth, x * w , y * h , 3 * w, h);
}
else if (dir == LEFT) {
for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) pushingWidth[i][j] = blockImages[staticMap[y][x - 2]][i][j];
for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) pushingWidth[i][w + j] = blockImages[staticMap[y][x - 1]][i][j];
for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) pushingWidth[i][2 * w + j] = blockImages[staticMap[y][x]][i][j];
for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) pushingWidth[i][(numAnimation - t) * w / numAnimation + j] = blockImages[2][i][j];
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
uint16_t pixel = pushAnimation[t][j][h - 1 - i];
if (pixel != transparent) pushingWidth[i][(numAnimation - t) * w / numAnimation + w + j] = pixel;
}
}
fillImage(pushingWidth, (x - 2) * w , y * h , 3 * w, h);
}
delay(10);
}
for (int i = 0; i < h; ++i) for (int j = 0; j < w; ++j) blockImage[i][j] = blockImages[3][i][j];
if (dir == UP && staticMap[y - 2][x] == 4) {
fillImage(blockImage, x * w , (y - 2) * h , w, h);
delay(300);
}
if (dir == DOWN && staticMap[y + 2][x] == 4) {
fillImage(blockImage, x * w , (y + 2) * h , w, h);
delay(300);
}
if (dir == RIGHT && staticMap[y][x + 2] == 4) {
fillImage(blockImage, (x + 2) * w , y * h , w, h);
delay(300);
}
if (dir == LEFT && staticMap[y][x - 2] == 4) {
fillImage(blockImage, (x - 2) * w , y * h , w, h);
delay(300);
}
}
void StageChange(int stageNumber) {
for (int i = 0; i < 80; ++i) for (int j = 0; j < 233; ++j) stageLogoImage[i][j] = stageLogoImages[stageNumber][i][j];
fillImage(stageLogoImage, 100 , 20 , 119, 41);
for (int l = 0; l < 5; ++l) {
for (int k = 0; k < 12; ++k) {
for (int i = 0; i < 100; ++i) for (int j = 0; j < 100; ++j) buffer100x100[i][j] = stageChangeAnimation[k][i][j];
fillImage(buffer100x100, 110 , 100 , 100, 100);
delay(20);
}
}
}
void ShowThankYou() {
M5.Lcd.fillScreen(backgroundColor);
for (int i = 0; i < 58; ++i) for (int j = 0; j < 320; ++j) thankYouLogoImage[i][j] = thankYouLogo[i][j];
fillImage(thankYouLogoImage, 0 , 20 , 320, 58);
#ifndef WIFI_UDP_CONTROLLER_USE
for (int k = 0; k < 18; ++k) {
for (int i = 0; i < 100; ++i) for (int j = 0; j < 100; ++j) buffer100x100[i][j] = waveAnimation[k][i][j];
fillImage(buffer100x100, 110 , 100 , 100, 100);
delay(20);
}
#endif
}
void setup() {
// initialize the M5Stack object
M5.begin();
M5.Lcd.setBrightness(100);
M5.Lcd.fillScreen(BLACK);
Serial.begin(115200);
#ifdef WIFI_UDP_CONTROLLER_USE
WiFi.softAP("ESP32", "esp32pass");
udp.begin(10000);
#endif
}
struct Point {
int x;
int y;
};
void ReviseMap(Dir dir) {
Point pos[3];
for (int i = 0; i < mapH; ++i) {
for (int j = 0; j < mapW; ++j) {
if (activeMap[i][j] > 5) { // current position
pos[0].x = j;
pos[0].y = i;
}
}
}
if (dir == UP) {
pos[1].x = pos[0].x;
pos[1].y = pos[0].y - 1;
}
else if (dir == RIGHT) {
pos[1].x = pos[0].x + 1;
pos[1].y = pos[0].y;
}
if (dir == DOWN) {
pos[1].x = pos[0].x;
pos[1].y = pos[0].y + 1;
}
else if (dir == LEFT) {
pos[1].x = pos[0].x - 1;
pos[1].y = pos[0].y;
}
pos[2].x = pos[1].x + (pos[1].x - pos[0].x);
pos[2].y = pos[1].y + (pos[1].y - pos[0].y);
if (pos[2].x < 0 || pos[2].x >= mapW || pos[2].y < 0 || pos[2].y >= mapH) pos[2].x = -1; // invalid position
int pic[3];
pic[0] = activeMap[pos[0].y][pos[0].x];
for (int i = 1; i < 3; ++i) if (pos[i].x != -1) pic[i] = activeMap[pos[i].y][pos[i].x];
if (pic[1] == 1) return; // next position is wall.
else if (pic[1] == 4 || pic[1] == 5) { // next position is floor
pic[0] = (pic[0] == 7) ? 4 : 5;
pic[1] = (pic[1] == 4) ? 7 : 6;
Walk(dir, pos[0].x, pos[0].y);
}
else if (pic[1] == 2 || pic[1] == 3) { // next position is box
if (pic[2] == 1 || pic[2] == 2 || pic[2] == 3) return; // next next position is wall or box
else if (pic[2] == 4 || pic[2] == 5) { // next next position is floor
pic[0] = (pic[0] == 7) ? 4 : 5;
pic[1] = (pic[1] == 3) ? 7 : 6;
pic[2] = (pic[2] == 4) ? 3 : 2;
Push(dir, pos[0].x, pos[0].y);
}
}
for (int i = 0; i < 3; ++i) activeMap[pos[i].y][pos[i].x] = pic[i];
//for (int i = 0; i < mapH; ++i) for (int j = 0; j < mapW; ++j) DrawBlock(j, i); // for test
}
bool SerialAction(Dir* dir, bool* restart) {
if(M5.BtnA.wasPressed()) {
delay(300);
M5.update();
if(M5.BtnC.wasPressed()) {
*dir = DOWN;
} else {
*dir = LEFT;
}
return true;
} else if(M5.BtnB.wasPressed()) {
delay(300);
M5.update();
if(M5.BtnC.wasPressed()) {
*restart = true;
return false;
} else {
*dir = UP;
}
return true;
} else if(M5.BtnC.wasPressed()) {
delay(300);
M5.update();
if(M5.BtnA.wasPressed()) {
*dir = DOWN;
} else if(M5.BtnB.wasPressed()) {
*restart = true;
return false;
} else {
*dir = RIGHT;
}
return true;
}
if (!Serial.available()) return false;
char r;
r = Serial.read();
Serial.println(r);
if (r == '8') *dir = UP;
else if (r == '6') *dir = RIGHT;
else if (r == '2') *dir = DOWN;
else if (r == '4') *dir = LEFT;
else if (r == 'r') *restart = true;
if (r == '8' || r == '6' || r == '2' || r == '4') return true;
else return false;
}
#ifdef WIFI_UDP_CONTROLLER_USE
bool UdpAction(Dir* dir, bool* restart) {
if (!udp.parsePacket()) return false;
char r;
r = udp.read(); // key is from 0 to 6 : "โ", "โ", "โ", "โ", "B", "A", "Release A or B"
if (r == 0) *dir = UP;
else if (r == 2) *dir = RIGHT;
else if (r == 3) *dir = DOWN;
else if (r == 1) *dir = LEFT;
else if (r == 4) *restart = true;
if (r == 0 || r == 1 || r == 2 || r == 3) return true;
else return false;
}
#endif
void loop() {
static bool restart = false;
static int stage = 0;
static int prev_stage = -1;
M5.update();
if (stage != prev_stage || restart) {
M5.Lcd.fillScreen(backgroundColor);
StageChange(stage);
for (int i = 0; i < mapH; ++i) for (int j = 0; j < mapW; ++j) activeMap[i][j] = maps[stage][i][j];
for (int i = 0; i < mapH; ++i) {
for (int j = 0; j < mapW; ++j) {
int cell = activeMap[i][j];
if (cell == 2) cell = 5;
else if (cell == 3) cell = 4;
else if (cell == 6) cell = 5;
else if (cell == 7) cell = 4;
staticMap[i][j] = cell;
}
}
for (int i = 0; i < mapH; ++i) for (int j = 0; j < mapW; ++j) DrawBlock(j, i);
delay(1000);
prev_stage = stage;
restart = false;
}
Dir dir;
if (SerialAction(&dir, &restart)) ReviseMap(dir);
#ifdef WIFI_UDP_CONTROLLER_USE
else if (UdpAction(&dir, &restart)) ReviseMap(dir);
#endif
// test
// Dir dir[] = {LEFT, RIGHT, RIGHT, LEFT, LEFT, UP, DOWN, RIGHT, RIGHT, UP, LEFT, UP, LEFT, RIGHT, DOWN, DOWN, LEFT, DOWN, LEFT, DOWN, RIGHT, RIGHT, RIGHT, LEFT, LEFT, UP, UP, RIGHT, UP, UP, LEFT, DOWN, LEFT, DOWN, DOWN, RIGHT, DOWN, UP, LEFT, UP, UP, RIGHT, RIGHT, DOWN, LEFT, DOWN, DOWN, UP, UP, UP, RIGHT, RIGHT, RIGHT, UP, LEFT, DOWN, LEFT, LEFT, DOWN, DOWN, DOWN, RIGHT, RIGHT, UP, RIGHT, UP, UP, LEFT, LEFT, DOWN, RIGHT, LEFT, DOWN};
// static int n = 0;
// if (stage == 0) {
// ReviseMap(dir[n]);
// ++n;
// }
bool stageClear = true;
for (int i = 0; i < mapH; ++i) for (int j = 0; j < mapW; ++j) if (activeMap[i][j] == 2) stageClear = false;
if (stageClear) stage++;
if (stage > 9) {
ShowThankYou();
while (1);
}
}
| 2616f8172e4eb04b532d738964d2fd0eb34e3030 | [
"Markdown",
"C++"
] | 2 | Markdown | robo8080/M5Stack_Sokoban | 0220139e59d4ee9e309470982c754ed420629f6c | e05058e770e195b8c6a49265252311fb643040f1 |
refs/heads/master | <repo_name>mortenterhart/Intelligent_Conductor<file_sep>/src/train/SeatLocation.java
package train;
/**
* An enumeration defining the waggon side on which
* a seat can be located.
*/
public enum SeatLocation {
left, right
}
<file_sep>/src/ticket/TicketProducer.java
package ticket;
import chip.EUChip;
import chip.IRFIDChip;
import chip.USChipAdapter;
import logging.Logger;
import main.Configuration;
import train.Train;
import train.TravelClass;
import train.WaggonSeat;
import voyager.MPhone;
import voyager.Voyager;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* This class is meant to use the {@link ElectronicTicket.TicketBuilder}
* class to produce a list of tickets depending on how
* many seats are available in the train waggon. The
* tickets are filled with example data as depicted in
* the methods below. In addition the created voyagers
* are collected in a list of passengers that can be
* accessed by a getter method.
* <p>
* All methods inside this class are static to provide
* direct access when invoking. Therefore the constructor
* is private so that no instances of this class can be
* created.
*/
public class TicketProducer {
/**
* The Concrete {@link ElectronicTicket.TicketBuilder} instance
*/
private static ElectronicTicket.TicketBuilder builder = new ElectronicTicket.TicketBuilder();
/**
* The instance of the {@link Train}
*/
private static Train train = Train.getInstance();
/**
* The collection of voyagers (passenger list) that is created
* during ticket production.
*/
private static List<Voyager> voyagerList = new ArrayList<>();
/**
* A boolean value denoting whether the tickets were already produced
* or not.
*/
private static boolean ticketsProduced = false;
/**
* Do not allow instantiation.
*/
private TicketProducer() {
}
/**
* Produces tickets that will be registered to the ticket repository
* and creates instances with example data different for the left or
* the right side of the waggon. A ticket is produced for each seat
* the waggon offers.
* <p>
* By default, invalid tickets are also produced to test the conductor.
*/
public static void produceTickets() {
produceTickets(true);
}
/**
* Produces tickets that will be registered to the ticket repository
* and creates instances with example data different for the left or
* the right side of the waggon. A ticket is produced for each seat
* the waggon offers.
*
* @param withInvalidTickets a switch causing invalid tickets to be
* produced or not
*/
public static void produceTickets(boolean withInvalidTickets) {
voyagerList.clear();
Logger.instance.log("--- Started producing tickets for all available seats " +
"(TicketProducer.produceTickets())");
for (WaggonSeat leftSeat : train.getWaggon().getLeftSeats()) {
Voyager leftVoyager = new Voyager("Dr. Left");
leftVoyager.setFingerPrint("Thumbs up");
leftVoyager.setPhone(new MPhone(new EUChip()));
voyagerList.add(leftVoyager);
buildTicket(leftVoyager, TravelClass.FIRST, leftSeat,
randomEnumConstant(Source.class), randomEnumConstant(Destination.class));
Logger.instance.log("> Producing ticket for " + leftSeat.getLocation().name() +
" seat with id " + leftSeat.getSeatId());
}
for (WaggonSeat rightSeat : train.getWaggon().getRightSeats()) {
Voyager rightVoyager = new Voyager("Dr. Right");
rightVoyager.setFingerPrint("Thumbs down");
rightVoyager.setPhone(new MPhone(new USChipAdapter()));
voyagerList.add(rightVoyager);
buildTicket(rightVoyager, TravelClass.SECOND, rightSeat,
randomEnumConstant(Source.class), randomEnumConstant(Destination.class));
Logger.instance.log("> Producing ticket for " + rightSeat.getLocation().name() +
" seat with id " + rightSeat.getSeatId());
}
Logger.instance.newLine();
if (withInvalidTickets) {
produceInvalidTickets();
}
ticketsProduced = true;
}
/**
* Inserts two voyagers whose ticket information are incorrect.
* The intelligent conductor should recognize the invalidity of
* their tickets and remove the stowaways from the train (i.e.
* throwing them out).
*/
private static void produceInvalidTickets() {
Logger.instance.log("--- Producing corrupt tickets to be identified by the conductor " +
"(TicketProducer.produceInvalidTickets())");
// 1. Voyager without a ticket (condition: no ticket registered in TicketRepository)
IRFIDChip euChip = new EUChip();
euChip.writeTicketId(TicketRepository.instance.numberOfTickets + 2);
Voyager fareDodger = new Voyager("<NAME>", "Hopefully nobody notices!",
new MPhone(euChip));
voyagerList.add(fareDodger);
Logger.instance.log("> Producing voyager without building ticket (fare dodger)");
Logger.instance.log(" -> Voyager '" + fareDodger.getName() + "' should be found by " +
"the intelligent conductor");
// 2. Voyager with a counterfeit ticket (condition: ticket id on RFIDChip not matching with any
// of the ids in the repository)
IRFIDChip usAdapter = new USChipAdapter();
Voyager counterfeitTicket = new Voyager("<NAME>", "It's all fake news!",
new MPhone(usAdapter));
buildTicket(counterfeitTicket, TravelClass.SECOND, new WaggonSeat(),
Source.Cologne, Destination.Stuttgart);
// Overwrite chip id set in the ticket builder with an invalid ticket id so that
// the intelligent conductor notices the counterfeit ticket.
usAdapter.writeTicketId(TicketRepository.instance.numberOfTickets + 3);
voyagerList.add(counterfeitTicket);
Logger.instance.log("> Producing voyager with disparate ticket id on RFIDChip that is not " +
"registered in the ticket repository");
Logger.instance.log(" -> Voyager '" + counterfeitTicket.getName() + "' should be found by " +
"the intelligent conductor");
}
/**
* Builds an instance of a ticket by using the internal
* {@link ElectronicTicket.TicketBuilder}.
*
* @param voyager the voyager attached to the ticket
* @param category the travel class attached to the ticket
* @param seat the seat attached to the ticket
* @param srcLocation the source location attached to the ticket
* @param destLocation the destination location attached to the ticket
*/
private static void buildTicket(Voyager voyager, TravelClass category, WaggonSeat seat,
Source srcLocation, Destination destLocation) {
builder.setVoyager(voyager)
.setTravelTime(new Date())
.setTravelCategory(category)
.setSeat(seat)
.setSourceLocation(srcLocation)
.setDestinationLocation(destLocation)
.build();
}
/**
* Selects randomly an enum constant out of the given enum <code>enumType</code>
* and returns it. Uses the random generator {@link random.MersenneTwisterFast}.
*
* @param enumType the class object holding the enumeration type
* @param <E> the type qualifier ensuring the class is a subclass of {@link Enum}<E>
* @return the enumeration constant of type E
*/
private static <E extends Enum<E>> E randomEnumConstant(Class<E> enumType) {
int x = Configuration.instance.mersenneTwister.nextInt(enumType.getEnumConstants().length);
return enumType.getEnumConstants()[x];
}
/**
* Checks if the tickets were already produced once.
*
* @return true if the tickets were already produced, false otherwise.
*/
public static boolean areTicketsProduced() {
return ticketsProduced;
}
/**
* Returns the list of passengers that is built during ticket production.
*
* @return the list of passengers
*/
public static List<Voyager> getListOfPassengers() {
return voyagerList;
}
}
<file_sep>/test/conductor/ScanningDeviceTest.java
package conductor;
import chip.EUChip;
import chip.IRFIDChip;
import chip.USChipAdapter;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import ticket.Destination;
import ticket.ElectronicTicket;
import ticket.Source;
import ticket.TicketRepository;
import train.SeatLocation;
import train.TravelClass;
import train.WaggonSeat;
import voyager.MPhone;
import voyager.Voyager;
import java.util.Date;
public class ScanningDeviceTest {
private static ScanningDevice scanner;
private static IRFIDChip euChip;
private static IRFIDChip usChip;
@BeforeClass
public static void buildInstancesAndRegisterTickets() {
TicketRepository.instance.clear();
ElectronicTicket.TicketBuilder.resetIdCounter();
scanner = new ScanningDevice();
ElectronicTicket.TicketBuilder builder = new ElectronicTicket.TicketBuilder();
WaggonSeat leftSeat = new WaggonSeat(SeatLocation.left);
euChip = new EUChip();
builder.setVoyager(new Voyager("EU citizen", "Thumbs up", new MPhone(euChip)))
.setTravelTime(new Date())
.setTravelCategory(TravelClass.FIRST)
.setSeat(leftSeat)
.setSourceLocation(Source.Cologne)
.setDestinationLocation(Destination.Heidelberg)
.build();
WaggonSeat rightSeat = new WaggonSeat(SeatLocation.right);
usChip = new USChipAdapter();
builder.setVoyager(new Voyager("US citizen", "Thumbs down", new MPhone(usChip)))
.setTravelTime(new Date())
.setTravelCategory(TravelClass.SECOND)
.setSeat(rightSeat)
.setSourceLocation(Source.Hamburg)
.setDestinationLocation(Destination.Munich)
.build();
}
@Test
public void testValidateEUChip() {
Assert.assertTrue(scanner.validateTicket(euChip));
}
@Test
public void testValidateUSChip() {
Assert.assertTrue(scanner.validateTicket(usChip));
}
@Test
public void testReadEUChipId() {
Assert.assertEquals(euChip.readTicketId(), scanner.readChipId(euChip));
}
@Test
public void testReadUSChipId() {
Assert.assertEquals(usChip.readTicketId(), scanner.readChipId(usChip));
}
@Test
public void testGetEUTicket() {
Assert.assertEquals(TicketRepository.instance.getTicket(0), scanner.getTicket(euChip));
}
@Test
public void testGetUSTicket() {
Assert.assertEquals(TicketRepository.instance.getTicket(1), scanner.getTicket(usChip));
}
}
<file_sep>/src/conductor/IntelligentConductor.java
package conductor;
import chip.IRFIDChip;
import logging.Logger;
import main.Configuration;
import ticket.ElectronicTicket;
import ticket.TicketProducer;
import ticket.TicketRepository;
import voyager.Voyager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* The IntelligentConductor is one of the main classes in
* this project and contains the most execution logic. The
* Application caller doesn't need to care about the different
* execution steps because the method <code>doYourJob</code>
* contains the exact order of private execution methods.
*/
public class IntelligentConductor {
/**
* scanner used to validate ticket ids stored on RFID chips and
* to return tickets matching a chip id
*/
private ScanningDevice scanner;
/**
* The list of voyagers the conductor iterates over.
*/
private List<Voyager> passengerList;
public IntelligentConductor() {
scanner = new ScanningDevice();
passengerList = new ArrayList<>();
}
/**
* This method initializes the list of passengers only if the tickets are
* already produced. If so, the list is fetched from the TicketProducer
* and is shuffled to remove the order and to not be able to say that an
* invalid ticket is on a specific location.
*/
public void init() {
Logger.instance.log("--- Fetching list of voyagers to be checked by the conductor " +
"(IntelligentConductor.init())");
if (TicketProducer.areTicketsProduced()) {
passengerList = new ArrayList<>(TicketProducer.getListOfPassengers());
Logger.instance.log("> Tickets were produced, conductor received list of passengers.");
Logger.instance.log("> Shuffling the list of passengers randomly to hide invalid tickets!");
// Shuffle the list to hide invalid tickets (i.e. they should appear to any time) and to
// prevent them to be at a specific location.
Collections.shuffle(passengerList, Configuration.instance.mersenneTwister);
}
}
/**
* Main execution method: Executes all steps the conductor does in the
* correct oder.
*/
public void doYourJob() {
// Output the list of all passengers first
printPassengerList();
Logger.instance.newLine();
// Check all tickets of those passengers
checkTickets();
Logger.instance.newLine();
// Print the remaining tickets after invalid tickets have been removed
printRemainingTickets();
Logger.instance.newLine();
}
/**
* Step 1: Print all boarded passengers and their fingerprints
*/
private void printPassengerList() {
Logger.instance.log("--- Printing all passengers (IntelligentConductor.printPassengerList())");
for (Voyager passenger : passengerList) {
Logger.instance.log("> Passenger '" + passenger.getName() + "' (Fingerprint \"" +
passenger.getFingerPrint() + "\") is on board.");
}
}
/**
* Step 2: Go through the train and check each voyager on ticket availability. If ticket is absent or
* counterfeit, throw that person out of the train.
*/
private void checkTickets() {
Logger.instance.log("--- Checking tickets of passengers (IntelligentConductor.checkTickets())");
for (Voyager passenger : passengerList) {
Logger.instance.log("> Asking passenger '" + passenger.getName() + "' for his/her phone");
if (passenger.hasPhone() && passenger.hasTicketBought()) {
IRFIDChip phoneChip = passenger.getPhone().getChip();
Logger.instance.log("> Scanning RFID Chip of type '" +
phoneChip.getVersion() + "' with scanning device");
if (scanner.validateTicket(phoneChip)) {
Logger.instance.log(" > Passenger '" + passenger.getName() + "' (Fingerprint \"" +
passenger.getFingerPrint() + "\") is registered to a valid ticket.");
Logger.instance.log(" Chip ID: " + scanner.readChipId(phoneChip));
Logger.instance.log(" Ticket information: " + scanner.getTicket(phoneChip).toString());
} else {
Logger.instance.log(" > Invalid ticket recognized: Passenger '" + passenger.getName() +
"' (Fingerprint \"" + passenger.getFingerPrint() + "\") counterfeited his/her ticket!");
Logger.instance.log(" Chip ID " + scanner.readChipId(phoneChip) + " not registered as ticket!");
Logger.instance.log(" ** Throwing passenger '" + passenger.getName() + "' out " +
"and destroying invalid ticket! **");
TicketRepository.instance.removeTicket(passenger);
}
} else {
Logger.instance.log(" > There is a vagabond aboard: <NAME> " + passenger.getName() +
" (Fingerprint \"" + passenger.getFingerPrint() + "\") has no ticket!");
Logger.instance.log(" Chip ID: " + scanner.readChipId(passenger.getPhone().getChip()));
Logger.instance.log(" ** Throwing passenger '" + passenger.getName() + "' out! **");
}
Logger.instance.newLine();
}
}
/**
* Step 3: Output all tickets of remaining passengers and associated information
*/
private void printRemainingTickets() {
Logger.instance.log("--- Printing remaining tickets (IntelligentConductor.printRemainingTickets())");
System.out.println("Registered tickets in ticket repository:");
for (ElectronicTicket ticket : TicketRepository.instance.tickets()) {
Logger.instance.log(String.format("> Ticket %2d:", ticket.getTicketId()));
Logger.instance.log(" voyager: " + ticket.getVoyager().getName());
Logger.instance.log(" travelTime: " + ticket.getTravelTime());
Logger.instance.log(" travelClass: " + ticket.getTravelCategory().name() + " class");
Logger.instance.log(" seat: " + ticket.getSeat().getSeatId() + " on the " +
ticket.getSeat().getLocation().name() + " side of the waggon");
Logger.instance.log(" source: " + ticket.getSourceLocation().name());
Logger.instance.log(" destination: " + ticket.getDestinationLocation().name());
Logger.instance.newLine();
}
}
public List<Voyager> getPassengerList() {
return passengerList;
}
public ScanningDevice getScanner() {
return scanner;
}
}
<file_sep>/src/logging/Logger.java
package logging;
import main.Configuration;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* A logging instance writing all received messages to the
* standard output channel and to a log file specified in
* the {@link Configuration} class.
*/
public enum Logger {
instance;
private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private PrintWriter writer;
/**
* Builds the logger with the log file path specified in the Configuration.
*/
public void init() {
try {
writer = new PrintWriter(new File(Configuration.instance.logFile));
} catch (FileNotFoundException exc) {
System.err.println("Error: Log File '" + Configuration.instance.logFile +
"' could not be created!");
exc.printStackTrace();
}
}
/**
* Writes a message to the log file preceding all new line characters
* with the current date prefix.
*
* @param message the message
*/
public void write(String message) {
String datePrefix = "[" + dateFormat.format(new Date()) + "]: ";
writer.write(datePrefix + message.replaceAll("\n", "\n" + datePrefix) +
Configuration.instance.lineSeparator);
writer.flush();
}
/**
* Logs a message to the log file and the standard output.
*
* @param message the message
*/
public void log(String message) {
write(message);
System.out.println(message);
}
/**
* Writes a new line in the log file and on standard output.
*/
public void newLine() {
write("");
System.out.println();
}
/**
* Closes the logging instance.
*/
public void close() {
writer.close();
}
}
<file_sep>/src/voyager/MPhone.java
package voyager;
import chip.EUChip;
import chip.IRFIDChip;
/**
* The MPhone is a class representing a mobile phone
* with a builtin {@link IRFIDChip}. It implements the
* Bridge Pattern for the <code>chip</code> attribute.
* Each {@link Voyager} has a MPhone as attribute.
* <p>
* When a ticket is built, the ticket id is sent to the
* voyager's MPhone automatically. Then the method
* <code>receiveTicketId()</code> is called to write the
* ticket id into the RFIDChip.
*/
public class MPhone {
/**
* The builtin {@link IRFIDChip} implementing the Bridge Design Pattern
* where the ticket id is stored. This chip reference is used by the scanning
* device to read the chip id. There are two variants of the IRFIDChip:
* <ul>
* <li>{@link chip.USChip} with a special {@link chip.USChipAdapter}</li>
* <li>{@link EUChip}</li>
* </ul>
*/
private IRFIDChip chip;
/**
* Default constructor: The MPhone is created with an {@link EUChip} by default, if
* called without parameter.
*/
public MPhone() {
chip = new EUChip();
}
public MPhone(IRFIDChip chipVariant) {
chip = chipVariant;
}
/**
* Writes the ticket id <code>id</code> onto the {@link IRFIDChip}.
*
* @param id the ticket id to store in the chip
*/
public void receiveTicketId(int id) {
chip.writeTicketId(id);
}
public void setChip(IRFIDChip chip) {
this.chip = chip;
}
public IRFIDChip getChip() {
return chip;
}
@Override
public String toString() {
return "MPhone { chip = " + chip + " }";
}
}
<file_sep>/src/ticket/TicketRepository.java
package ticket;
import conductor.IntelligentConductor;
import conductor.ScanningDevice;
import train.Train;
import voyager.Voyager;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* The central ticket repository as a singleton class realized
* by an enumeration. This class holds the repository where
* producers and builders can register their tickets that are
* assumed to be valid tickets. The {@link IntelligentConductor} and
* the {@link ScanningDevice} can examine the validity of tickets from
* passengers and can look if tickets for specific voyagers or
* ticket ids exist.
* <p>
* The repository memory is organized by mapping the unique ticket
* id to the ticket instance.
* Example: <code>5 -> Ticket { ticketId, voyager, ... }</code>
*/
public enum TicketRepository {
/**
* The central instance of this TicketRepository
*/
instance;
/**
* The total number of tickets constructed (equal to the number of seats).
* The variable is initialized with the total number of seats so that there
* is an equal amount of tickets and corresponding seats.
*/
public final int numberOfTickets = Train.getInstance().getWaggon().getTotalNumberOfSeats();
/**
* The final repository containing all registered tickets. It maps ticket ids to
* the concrete ticket instances and is initialized with a capacity equal to the
* number of tickets.
*/
private final Map<Integer, ElectronicTicket> repository = new HashMap<>(numberOfTickets);
/**
* Registers a new ticket in the ticket repository only if that ticket
* has no instance in the repository already.
*
* @param ticket The ticket to register
* @return true if the ticket has been newly added to the repository, false otherwise.
*/
public boolean registerTicket(ElectronicTicket ticket) {
if (!isTicketRegistered(ticket)) {
repository.put(ticket.getTicketId(), ticket);
return true;
}
return false;
}
/**
* Examines if a given ticket is already registered within the repository or not.
*
* @param ticket the ticket to check
* @return true if the ticket is already registered, false otherwise.
*/
public boolean isTicketRegistered(ElectronicTicket ticket) {
return repository.containsKey(ticket.getTicketId());
}
/**
* Examines if a given ticket id is already registered within the repository or not.
*
* @param ticketId the ticket id to check
* @return true if the ticket id is already registered, false otherwise.
*/
public boolean isTicketRegistered(int ticketId) {
return repository.containsKey(ticketId);
}
/**
* Requests the delivery of the ticket with the designated unique id.
*
* @param ticketId the ticket id
* @return the ticket if the id is registered in the repository, null otherwise.
*/
public ElectronicTicket getTicket(int ticketId) {
return repository.get(ticketId);
}
/**
* Requests the delivery of the ticket for a special voyager and checks if the voyager
* has bought a ticket
*
* @param voyager the voyager to look for
* @return the ticket if the voyager has a ticket in the repository, null otherwise.
*/
public ElectronicTicket getTicket(Voyager voyager) {
for (ElectronicTicket ticket : repository.values()) {
if (ticket.getVoyager() == voyager) {
return ticket;
}
}
return null;
}
/**
* Searches the repository for the specified ticket and returns true if
* the ticket was found, false otherwise.
*
* @param ticket the ticket to search for
* @return true if the ticket is inside this repository, false otherwise.
*/
public boolean contains(ElectronicTicket ticket) {
return repository.containsValue(ticket);
}
/**
* Removes a ticket with the specified id from the repository
*
* @param ticketId the ticket id
* @return true if a ticket was removed, false otherwise.
*/
public boolean removeTicket(int ticketId) {
return repository.remove(ticketId) != null;
}
/**
* Searches for a ticket registered to voyager and removes it if present
*
* @param voyager the voyager whose ticket should be removed
* @return true if the ticket could be found and removed, false otherwise.
*/
public boolean removeTicket(Voyager voyager) {
ElectronicTicket ticket = getTicket(voyager);
return ticket != null && repository.remove(ticket.getTicketId()) != null;
}
/**
* Checks if the specified voyager has a registered ticket in the repository
*
* @param voyager the voyager
* @return true if the voyager has a ticket, false otherwise.
*/
public boolean hasTicketBought(Voyager voyager) {
return getTicket(voyager) != null;
}
/**
* Builds a set containing all ticket id keys of the repository.
*
* @return a set with all ticket ids
*/
public Set<Integer> ticketIdSet() {
return repository.keySet();
}
/**
* Builds a collection of all ticket instances contained in the repository.
*
* @return a collection of all ticket instances
*/
public Collection<ElectronicTicket> tickets() {
return repository.values();
}
/**
* Returns the size of this repository.
*
* @return the number of tickets stored in this repository.
*/
public int size() {
return repository.size();
}
/**
* Clears the underlying repository by removing all ticket mappings.
*/
public void clear() {
repository.clear();
}
}
<file_sep>/src/ticket/IBuilder.java
package ticket;
/**
* Interface for a concrete builder instance
* @param <T> the object type this builder builds
*/
public interface IBuilder<T> {
/**
* Constructs an instance of object of type <code>T</code>
* @return the instance
*/
public T build();
}
<file_sep>/README.md
# Design Patterns Team (DPT) - Intelligent Conductor (T03)
**Used Design Patterns:** Builder, Bridge, Adapter
* Assigned Task: T03 Intelligent Conductor
## Project structure
* [Complete Java Documentation](doc)
* [Bundled Artifact](jar)
* [Log file with all execution information](log)
* [Manifest file](META-INF)
* [Java Source Files](src)
* [JUnit 4 Tests](test)
* [UML Class Diagrams](uml)
* [with Enterprise Architect](uml/enterprise-architect)
* [with Intellij](uml/intellij)
## Assignment of task (T03)
Ein Zug hat einen Waggon. Dieser Waggon hat auf der linken und rechten Seite je 25 Sitzplรคtze โ
getrennt durch einen Gang. Das elektronische Ticket besteht aus den Informationen Reisender
(`name` und `fingerPrint`), Datum, Klasse sowie Strecke von und nach. Ein Builder erstellt das Ticket
und registriert es in einem zentralen Repository. Zusรคtzlich wird das Ticket dem Reisenden auf das
MPhone gesandt. Das MPhone ist mit einem RFID-Chip ausgestattet. Der RFID-Chip existiert in den
Varianten **EU** und **US**. Der intelligente Zugbegleiter besucht sukzessive die belegten Sitzplรคtze und
uฬberpruฬft die Tickets anhand der registrierten Tickets im zentralen Repository. Standardmรครig
liest der intelligente Zugbegleiter den RFID-Chip der Variante EU. Fuฬr das Auslesen des RFID-Chips
der Variante US nutzt der intelligente Zugbegleiter einen Adapter.
## Wichtige Zielsetzungen
1. Wiederholung und Vertiefung des Wissens zu Design Patterns.
2. Praktische Anwendung der Design Patterns auf komplexe Aufgabenstellungen.
3. Optimale Klausurvorbereitung im Hinblick auf eine vorzugsweise sehr gute Bewertung.
## UML Class Diagram
<img src="uml/intellij/Intelligent_Conductor_class_diagram.png" alt="Intelligent Conductor Class Diagram" />
## Wichtige Hinweise
* Pro Team werden zwei Aufgaben bearbeitet.
* Die Zuordnung der zwei Aufgaben zu einem Team erfolgt mit einem Zufallsgenerator.
* Bearbeitung der Aufgaben lokal auf den Rechnern und Nutzung der Templates.
* Studium der Struktur und Funktionsweise der beteiligten Design Patterns.
* Verwendung geeigneter englischer Begriffe fuฬr Namen und Bezeichnungen.
* Modellierung von zwei Klassendiagrammen in Enterprise Architect. Bitte
* nutzen Sie das Theme โDHBWโ (Visual Style -> Visual Appearance -> Diagram).
* legen Sie fuฬr jede Aufgabe ein separates Klassendiagramm an.
* benennen Sie das Klassendiagramm mit task<id>, z.B. task50.
* benennen Sie die Datei mit <team_id>_<task_id>.eap, z.B. 03_50.eap.
* exportieren Sie das Klassendiagramm als PDF-Datei mit einer A4-Seite im Querformat.
* Implementierung einer einwandfrei lauffรคhigen Applikation in Java 8. Bitte
* erstellen Sie ein Paket mit der Bezeichnung taskgroup<team_id>, z.B. taskgroup03.
* erstellen Sie fuฬr jeden Task ein Unterpaket mit der Bezeichnung task<id>, z.B. task50.
* nutzen Sie die camelCase-Notation, um die Lesbarkeit zu vereinfachen.
* Test der Implementierung mit JUnit und Gewรคhrleistung der Funktionsweise.
* Modellierung und Implementierung wird mit je 5 Punkten pro Aufgabe bewertet.
* Erstellung einer vollstรคndigen und verschluฬsselten 7-Zip-Datei unter Beachtung des Prozedere fuฬr die Abgabe von Pruฬfungsleistungen und der Namenskonvention.
* Zeitansatz: 10 Stunden
* Abgabetermin: Sonntag, 18.02.2018
* Bewertung: Testat, 20 Punkte
<file_sep>/doc/ticket/TicketRepository.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_161) on Sun Feb 18 13:24:10 CET 2018 -->
<title>TicketRepository</title>
<meta name="date" content="2018-02-18">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
<script type="text/javascript" src="../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="TicketRepository";
}
}
catch(err) {
}
//-->
var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10,"i5":10,"i6":10,"i7":10,"i8":10,"i9":10,"i10":10,"i11":10,"i12":10,"i13":9,"i14":9};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/TicketRepository.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li><a href="../index-files/index-1.html">Index</a></li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../ticket/TicketProducerTest.html" title="class in ticket"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../ticket/TicketRepositoryTest.html" title="class in ticket"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?ticket/TicketRepository.html" target="_top">Frames</a></li>
<li><a href="TicketRepository.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#enum.constant.summary">Enum Constants</a> | </li>
<li><a href="#field.summary">Field</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#enum.constant.detail">Enum Constants</a> | </li>
<li><a href="#field.detail">Field</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">ticket</div>
<h2 title="Enum TicketRepository" class="title">Enum TicketRepository</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>java.lang.Enum<<a href="../ticket/TicketRepository.html" title="enum in ticket">TicketRepository</a>></li>
<li>
<ul class="inheritance">
<li>ticket.TicketRepository</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>java.io.Serializable, java.lang.Comparable<<a href="../ticket/TicketRepository.html" title="enum in ticket">TicketRepository</a>></dd>
</dl>
<hr>
<br>
<pre>public enum <span class="typeNameLabel">TicketRepository</span>
extends java.lang.Enum<<a href="../ticket/TicketRepository.html" title="enum in ticket">TicketRepository</a>></pre>
<div class="block">The central ticket repository as a singleton class realized
by an enumeration. This class holds the repository where
producers and builders can register their tickets that are
assumed to be valid tickets. The <a href="../conductor/IntelligentConductor.html" title="class in conductor"><code>IntelligentConductor</code></a> and
the <a href="../conductor/ScanningDevice.html" title="class in conductor"><code>ScanningDevice</code></a> can examine the validity of tickets from
passengers and can look if tickets for specific voyagers or
ticket ids exist.
<p>
The repository memory is organized by mapping the unique ticket
id to the ticket instance.
Example: <code>5 -> Ticket { ticketId, voyager, ... }</code></div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="enum.constant.summary">
<!-- -->
</a>
<h3>Enum Constant Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Constant Summary table, listing enum constants, and an explanation">
<caption><span>Enum Constants</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Enum Constant and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../ticket/TicketRepository.html#instance">instance</a></span></code>
<div class="block">The central instance of this TicketRepository</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../ticket/TicketRepository.html#numberOfTickets">numberOfTickets</a></span></code>
<div class="block">The total number of tickets constructed (equal to the number of seats).</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>private java.util.Map<java.lang.Integer,<a href="../ticket/ElectronicTicket.html" title="class in ticket">ElectronicTicket</a>></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../ticket/TicketRepository.html#repository">repository</a></span></code>
<div class="block">The final repository containing all registered tickets.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../ticket/TicketRepository.html#clear--">clear</a></span>()</code>
<div class="block">Clears the underlying repository by removing all ticket mappings.</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../ticket/TicketRepository.html#contains-ticket.ElectronicTicket-">contains</a></span>(<a href="../ticket/ElectronicTicket.html" title="class in ticket">ElectronicTicket</a> ticket)</code>
<div class="block">Searches the repository for the specified ticket and returns true if
the ticket was found, false otherwise.</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code><a href="../ticket/ElectronicTicket.html" title="class in ticket">ElectronicTicket</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../ticket/TicketRepository.html#getTicket-int-">getTicket</a></span>(int ticketId)</code>
<div class="block">Requests the delivery of the ticket with the designated unique id.</div>
</td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code><a href="../ticket/ElectronicTicket.html" title="class in ticket">ElectronicTicket</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../ticket/TicketRepository.html#getTicket-voyager.Voyager-">getTicket</a></span>(<a href="../voyager/Voyager.html" title="class in voyager">Voyager</a> voyager)</code>
<div class="block">Requests the delivery of the ticket for a special voyager and checks if the voyager
has bought a ticket</div>
</td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../ticket/TicketRepository.html#hasTicketBought-voyager.Voyager-">hasTicketBought</a></span>(<a href="../voyager/Voyager.html" title="class in voyager">Voyager</a> voyager)</code>
<div class="block">Checks if the specified voyager has a registered ticket in the repository</div>
</td>
</tr>
<tr id="i5" class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../ticket/TicketRepository.html#isTicketRegistered-ticket.ElectronicTicket-">isTicketRegistered</a></span>(<a href="../ticket/ElectronicTicket.html" title="class in ticket">ElectronicTicket</a> ticket)</code>
<div class="block">Examines if a given ticket is already registered within the repository or not.</div>
</td>
</tr>
<tr id="i6" class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../ticket/TicketRepository.html#isTicketRegistered-int-">isTicketRegistered</a></span>(int ticketId)</code>
<div class="block">Examines if a given ticket id is already registered within the repository or not.</div>
</td>
</tr>
<tr id="i7" class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../ticket/TicketRepository.html#registerTicket-ticket.ElectronicTicket-">registerTicket</a></span>(<a href="../ticket/ElectronicTicket.html" title="class in ticket">ElectronicTicket</a> ticket)</code>
<div class="block">Registers a new ticket in the ticket repository only if that ticket
has no instance in the repository already.</div>
</td>
</tr>
<tr id="i8" class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../ticket/TicketRepository.html#removeTicket-int-">removeTicket</a></span>(int ticketId)</code>
<div class="block">Removes a ticket with the specified id from the repository</div>
</td>
</tr>
<tr id="i9" class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../ticket/TicketRepository.html#removeTicket-voyager.Voyager-">removeTicket</a></span>(<a href="../voyager/Voyager.html" title="class in voyager">Voyager</a> voyager)</code>
<div class="block">Searches for a ticket registered to voyager and removes it if present</div>
</td>
</tr>
<tr id="i10" class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../ticket/TicketRepository.html#size--">size</a></span>()</code>
<div class="block">Returns the size of this repository.</div>
</td>
</tr>
<tr id="i11" class="rowColor">
<td class="colFirst"><code>java.util.Set<java.lang.Integer></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../ticket/TicketRepository.html#ticketIdSet--">ticketIdSet</a></span>()</code>
<div class="block">Builds a set containing all ticket id keys of the repository.</div>
</td>
</tr>
<tr id="i12" class="altColor">
<td class="colFirst"><code>java.util.Collection<<a href="../ticket/ElectronicTicket.html" title="class in ticket">ElectronicTicket</a>></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../ticket/TicketRepository.html#tickets--">tickets</a></span>()</code>
<div class="block">Builds a collection of all ticket instances contained in the repository.</div>
</td>
</tr>
<tr id="i13" class="rowColor">
<td class="colFirst"><code>static <a href="../ticket/TicketRepository.html" title="enum in ticket">TicketRepository</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../ticket/TicketRepository.html#valueOf-java.lang.String-">valueOf</a></span>(java.lang.String name)</code>
<div class="block">Returns the enum constant of this type with the specified name.</div>
</td>
</tr>
<tr id="i14" class="altColor">
<td class="colFirst"><code>static <a href="../ticket/TicketRepository.html" title="enum in ticket">TicketRepository</a>[]</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../ticket/TicketRepository.html#values--">values</a></span>()</code>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Enum">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Enum</h3>
<code>clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>getClass, notify, notifyAll, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ ENUM CONSTANT DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="enum.constant.detail">
<!-- -->
</a>
<h3>Enum Constant Detail</h3>
<a name="instance">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>instance</h4>
<pre>public static final <a href="../ticket/TicketRepository.html" title="enum in ticket">TicketRepository</a> instance</pre>
<div class="block">The central instance of this TicketRepository</div>
</li>
</ul>
</li>
</ul>
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="numberOfTickets">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>numberOfTickets</h4>
<pre>public final int numberOfTickets</pre>
<div class="block">The total number of tickets constructed (equal to the number of seats).
The variable is initialized with the total number of seats so that there
is an equal amount of tickets and corresponding seats.</div>
</li>
</ul>
<a name="repository">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>repository</h4>
<pre>private final java.util.Map<java.lang.Integer,<a href="../ticket/ElectronicTicket.html" title="class in ticket">ElectronicTicket</a>> repository</pre>
<div class="block">The final repository containing all registered tickets. It maps ticket ids to
the concrete ticket instances and is initialized with a capacity equal to the
number of tickets.</div>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="values--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>values</h4>
<pre>public static <a href="../ticket/TicketRepository.html" title="enum in ticket">TicketRepository</a>[] values()</pre>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared. This method may be used to iterate
over the constants as follows:
<pre>
for (TicketRepository c : TicketRepository.values())
System.out.println(c);
</pre></div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>an array containing the constants of this enum type, in the order they are declared</dd>
</dl>
</li>
</ul>
<a name="valueOf-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>valueOf</h4>
<pre>public static <a href="../ticket/TicketRepository.html" title="enum in ticket">TicketRepository</a> valueOf(java.lang.String name)</pre>
<div class="block">Returns the enum constant of this type with the specified name.
The string must match <i>exactly</i> an identifier used to declare an
enum constant in this type. (Extraneous whitespace characters are
not permitted.)</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>name</code> - the name of the enum constant to be returned.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the enum constant with the specified name</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code>java.lang.IllegalArgumentException</code> - if this enum type has no constant with the specified name</dd>
<dd><code>java.lang.NullPointerException</code> - if the argument is null</dd>
</dl>
</li>
</ul>
<a name="registerTicket-ticket.ElectronicTicket-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>registerTicket</h4>
<pre>public boolean registerTicket(<a href="../ticket/ElectronicTicket.html" title="class in ticket">ElectronicTicket</a> ticket)</pre>
<div class="block">Registers a new ticket in the ticket repository only if that ticket
has no instance in the repository already.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>ticket</code> - The ticket to register</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>true if the ticket has been newly added to the repository, false otherwise.</dd>
</dl>
</li>
</ul>
<a name="isTicketRegistered-ticket.ElectronicTicket-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>isTicketRegistered</h4>
<pre>public boolean isTicketRegistered(<a href="../ticket/ElectronicTicket.html" title="class in ticket">ElectronicTicket</a> ticket)</pre>
<div class="block">Examines if a given ticket is already registered within the repository or not.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>ticket</code> - the ticket to check</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>true if the ticket is already registered, false otherwise.</dd>
</dl>
</li>
</ul>
<a name="isTicketRegistered-int-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>isTicketRegistered</h4>
<pre>public boolean isTicketRegistered(int ticketId)</pre>
<div class="block">Examines if a given ticket id is already registered within the repository or not.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>ticketId</code> - the ticket id to check</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>true if the ticket id is already registered, false otherwise.</dd>
</dl>
</li>
</ul>
<a name="getTicket-int-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getTicket</h4>
<pre>public <a href="../ticket/ElectronicTicket.html" title="class in ticket">ElectronicTicket</a> getTicket(int ticketId)</pre>
<div class="block">Requests the delivery of the ticket with the designated unique id.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>ticketId</code> - the ticket id</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the ticket if the id is registered in the repository, null otherwise.</dd>
</dl>
</li>
</ul>
<a name="getTicket-voyager.Voyager-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getTicket</h4>
<pre>public <a href="../ticket/ElectronicTicket.html" title="class in ticket">ElectronicTicket</a> getTicket(<a href="../voyager/Voyager.html" title="class in voyager">Voyager</a> voyager)</pre>
<div class="block">Requests the delivery of the ticket for a special voyager and checks if the voyager
has bought a ticket</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>voyager</code> - the voyager to look for</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the ticket if the voyager has a ticket in the repository, null otherwise.</dd>
</dl>
</li>
</ul>
<a name="contains-ticket.ElectronicTicket-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>contains</h4>
<pre>public boolean contains(<a href="../ticket/ElectronicTicket.html" title="class in ticket">ElectronicTicket</a> ticket)</pre>
<div class="block">Searches the repository for the specified ticket and returns true if
the ticket was found, false otherwise.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>ticket</code> - the ticket to search for</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>true if the ticket is inside this repository, false otherwise.</dd>
</dl>
</li>
</ul>
<a name="removeTicket-int-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>removeTicket</h4>
<pre>public boolean removeTicket(int ticketId)</pre>
<div class="block">Removes a ticket with the specified id from the repository</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>ticketId</code> - the ticket id</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>true if a ticket was removed, false otherwise.</dd>
</dl>
</li>
</ul>
<a name="removeTicket-voyager.Voyager-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>removeTicket</h4>
<pre>public boolean removeTicket(<a href="../voyager/Voyager.html" title="class in voyager">Voyager</a> voyager)</pre>
<div class="block">Searches for a ticket registered to voyager and removes it if present</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>voyager</code> - the voyager whose ticket should be removed</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>true if the ticket could be found and removed, false otherwise.</dd>
</dl>
</li>
</ul>
<a name="hasTicketBought-voyager.Voyager-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>hasTicketBought</h4>
<pre>public boolean hasTicketBought(<a href="../voyager/Voyager.html" title="class in voyager">Voyager</a> voyager)</pre>
<div class="block">Checks if the specified voyager has a registered ticket in the repository</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>voyager</code> - the voyager</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>true if the voyager has a ticket, false otherwise.</dd>
</dl>
</li>
</ul>
<a name="ticketIdSet--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>ticketIdSet</h4>
<pre>public java.util.Set<java.lang.Integer> ticketIdSet()</pre>
<div class="block">Builds a set containing all ticket id keys of the repository.</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>a set with all ticket ids</dd>
</dl>
</li>
</ul>
<a name="tickets--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>tickets</h4>
<pre>public java.util.Collection<<a href="../ticket/ElectronicTicket.html" title="class in ticket">ElectronicTicket</a>> tickets()</pre>
<div class="block">Builds a collection of all ticket instances contained in the repository.</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>a collection of all ticket instances</dd>
</dl>
</li>
</ul>
<a name="size--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>size</h4>
<pre>public int size()</pre>
<div class="block">Returns the size of this repository.</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the number of tickets stored in this repository.</dd>
</dl>
</li>
</ul>
<a name="clear--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>clear</h4>
<pre>public void clear()</pre>
<div class="block">Clears the underlying repository by removing all ticket mappings.</div>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/TicketRepository.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li><a href="../index-files/index-1.html">Index</a></li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../ticket/TicketProducerTest.html" title="class in ticket"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../ticket/TicketRepositoryTest.html" title="class in ticket"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?ticket/TicketRepository.html" target="_top">Frames</a></li>
<li><a href="TicketRepository.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#enum.constant.summary">Enum Constants</a> | </li>
<li><a href="#field.summary">Field</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#enum.constant.detail">Enum Constants</a> | </li>
<li><a href="#field.detail">Field</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| e2491ce1ac5128af89b3fa0504c8772739ef7c82 | [
"Markdown",
"Java",
"HTML"
] | 10 | Java | mortenterhart/Intelligent_Conductor | 9fec0e4d2c5d03b8e3a5641d4855644d1e2ddb40 | ac60172db5028a5143e13fd4267676c5bcf75177 |
refs/heads/master | <file_sep># tic-tac-toe-checker
https://www.codewars.com/kata/525caa5c1bf619d28c000335
<file_sep>def isSolved(board):
for row in board:
if row == [1, 1, 1]:
return 1
if row == [2, 2, 2]:
return 2
for j in range(3):
column = []
for row in board:
column.append(row[j])
if column == [1, 1, 1]:
return 1
if column == [2, 2, 2]:
return 2
diagonal1 = [board[0][0], board[1][1], board[2][2]]
diagonal2 = [board[0][2], board[1][1], board[2][0]]
if diagonal1 == [1, 1, 1] or diagonal2 == [1, 1, 1]:
return 1
if diagonal1 == [2, 2, 2] or diagonal2 == [2, 2, 2]:
return 2
for row in board:
if 0 in row:
return -1
return 0
| 6ae6440c932791b99fca4ee018184c169e8fc7e1 | [
"Markdown",
"Python"
] | 2 | Markdown | kurtportelli/tic-tac-toe-checker | 2e33f60e32cbb398a1aab25ca9aeaaf389ddbd7a | 21cd7e1ec31179f2971862c79f5ba5fdb17f737e |
refs/heads/main | <repo_name>ajcohen125/RobertCracker<file_sep>/password_test.py
#!/usr/bin/python3
#Password crakcing test
#importing stuff
import sys
import itertools #Used to list all possible values
import time #Used to keep time
import hashlib #Used to convert to hash
import getopt
import binascii
import multiprocessing
def main():
global pass_list
global alphabet
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`1234567890!@#$%&?"
file_name = "hashes.txt"
hash_type = "md5"
dict_file = "dict.txt"
max_len = 5
try:
opts, args = getopt.getopt(sys.argv[1:], "he:f:d:m:")
except:
print("Error: missing argument")
show_help()
for opt, arg in opts:
if opt in ['-f']:
file_name = arg
elif opt in ['-h']:
show_help()
elif opt in ['-e']:
hash_type = arg
elif opt in ['-d']:
dict_file = arg
elif opt in ['-m']:
max_len = int(arg)
#reading values from the file
with open (file_name,'r') as infile: #Opens the file to work and closes it after being done
pass_list = infile.readlines() #Makes a list with all the values in the file with one per line
#Removes the "\n" from the values if it exists
for i in range(0,len(pass_list)-1):
if "\n" in pass_list[i]:
temp = pass_list[i]
pass_list[i]= temp[:-1]
print(file_name + " " + hash_type)
start = time.time()
brute_force(file_name,max_len)
end = time.time()
print("Time: {}".format(end-start))
def show_help():
print("Usage")
exit()
def multiprocessing_brute(x):
print("Hashing: {}".format(x))
hashed = (hashlib.md5(x.encode())).hexdigest()
if hashed in pass_list:
print("The password \"{}\" : \"{}\" was cracked".format(x,hashed))
def ntlm(file_name):
print("check NTML hashes")
def brute_force(file_name,max_len):
print("Brute force the hashes")
processes = []
start = time.time() #Stores the start time
for charlength in range(1,max_len): #Length of password to crack
# for password in (''.join(i) for i in itertools.product(alphabet, repeat = charlength)):
print("starting with length {}".format(max_len))
pool = multiprocessing.Pool()
pool.map(multiprocessing_brute, (''.join(i) for i in itertools.product(alphabet, repeat = charlength)))
pool.close()
#hashed = (hashlib.md5(test.encode())).hexdigest() #Converts to a hashed value
#if hashed in pass_list: #Checks to see if the hashed value is in the list
# print("The password \"{}\" : \"{}\" was cracked in {:.2f} seconds".format(test,hashed,time.time()-start))
main()
| 13cabbfe9cbf0180f4850f57944495658e60e6bf | [
"Python"
] | 1 | Python | ajcohen125/RobertCracker | 4fe3124101a55c3d2f3f9ddcab0f4869ac9d64ef | 58249e85dc42391de013f0fc813b32db56c1d265 |
refs/heads/master | <file_sep>๏ปฟusing System.Collections.Generic;
namespace Popflex
{
public class OrderTemplate : AllfleXML.FlexOrder.OrderHeader
{
public List<string> styles = new List<string>();
public string CompanyLogo = @"data:image/gif;base64," + System.Convert.ToBase64String(System.IO.File.ReadAllBytes(@"Resources\Images\Allflex.png"));
public readonly string AllflexLogo = @"data:image/gif;base64," + System.Convert.ToBase64String(System.IO.File.ReadAllBytes(@"Resources\Images\Allflex.png"));
public readonly string DestronLogo = @"data:image/gif;base64," + System.Convert.ToBase64String(System.IO.File.ReadAllBytes(@"Resources\Images\DestronFearing.png"));
public string OrderNumber { get; set; }
public string MasterId { get; set; }
public string OrderDate { get; set; }
public string DueDate { get; set; }
public string Requisitioner { get; set; }
public string PrePaidFreight { get; set; }
public string BillToName { get; set; }
public string BillToAddress1 { get; set; }
public string BillToAddress2 { get; set; }
public string BillToAddress3 { get; set; }
public string BillToCity { get; set; }
public string BillToState { get; set; }
public string BillToPostalCode { get; set; }
public string BillToPhone { get; set; }
public string SubTotal { get; set; }
public string Tax { get; set; }
public string ShippingCharge { get; set; }
public string Total { get; set; }
public new List<OrderLineTemplate> OrderLineHeaders { get; set; }
}
public class OrderLineTemplate : AllfleXML.FlexOrder.OrderLineHeader
{
public string JobNumber { get; set; }
public string SkuDescription { get; set; }
public string UnitPrice { get; set; }
public string SubTotal { get; set; }
}
}
<file_sep>๏ปฟusing System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Popflex.Test
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void PrintSalesOrder()
{
var order = AllfleXML.FlexOrder.Parser.Import(@"TestData\sample2.xml").OrderHeaders.SingleOrDefault();
var tmp = Popflex.Print.SalesOrder(order);
Assert.IsNotNull(tmp);
System.Diagnostics.Process.Start(tmp);
}
}
}
<file_sep>๏ปฟusing System.Linq;
namespace Popflex
{
// TODO: Only display price header on table if any orderLiens contain price. Do not display if no order lines contain price
// TODO: Offset @index for order lines +1
//
public class Print
{
public static string SalesOrder(AllfleXML.FlexOrder.OrderHeader order, string htmlTempalte = null, string outputPath = null)
{
return SalesOrder(MapOrder(order), htmlTempalte, outputPath);
}
private static OrderTemplate MapOrder(AllfleXML.FlexOrder.OrderHeader order)
{
var config = new AutoMapper.MapperConfiguration(
cfg => {
cfg.CreateMap<AllfleXML.FlexOrder.OrderHeader, OrderTemplate>();
cfg.CreateMap<AllfleXML.FlexOrder.OrderLineHeader, OrderLineTemplate>();
}
);
var mapper = config.CreateMapper();
var result = mapper.Map<OrderTemplate>(order);
result.OrderNumber = order.UserDefinedFields.Fields.SingleOrDefault(f => f.Key == "OrderNumber")?.Value;
result.MasterId = order.UserDefinedFields.Fields.SingleOrDefault(f => f.Key == "MasterId")?.Value;
result.OrderDate = order.UserDefinedFields.Fields.SingleOrDefault(f => f.Key == "OrderDate")?.Value;
result.DueDate = order.UserDefinedFields.Fields.SingleOrDefault(f => f.Key == "DueDate")?.Value;
result.Requisitioner = order.UserDefinedFields.Fields.SingleOrDefault(f => f.Key == "Requisitioner")?.Value;
result.PrePaidFreight = order.UserDefinedFields.Fields.SingleOrDefault(f => f.Key == "PrePaidFreight")?.Value;
result.BillToName = order.UserDefinedFields.Fields.SingleOrDefault(f => f.Key == "BillToName")?.Value;
result.BillToAddress1 = order.UserDefinedFields.Fields.SingleOrDefault(f => f.Key == "BillToAddress1")?.Value;
result.BillToAddress2 = order.UserDefinedFields.Fields.SingleOrDefault(f => f.Key == "BillToAddress2")?.Value;
result.BillToAddress3 = order.UserDefinedFields.Fields.SingleOrDefault(f => f.Key == "BillToAddress3")?.Value;
result.BillToCity = order.UserDefinedFields.Fields.SingleOrDefault(f => f.Key == "BillToCity")?.Value;
result.BillToState = order.UserDefinedFields.Fields.SingleOrDefault(f => f.Key == "BillToState")?.Value;
result.BillToPostalCode = order.UserDefinedFields.Fields.SingleOrDefault(f => f.Key == "BillToPostalCode")?.Value;
result.BillToPhone = order.UserDefinedFields.Fields.SingleOrDefault(f => f.Key == "BillToPhone")?.Value;
result.SubTotal = order.UserDefinedFields.Fields.SingleOrDefault(f => f.Key == "SubTotal")?.Value;
result.Tax = order.UserDefinedFields.Fields.SingleOrDefault(f => f.Key == "Tax")?.Value;
result.ShippingCharge = order.UserDefinedFields.Fields.SingleOrDefault(f => f.Key == "ShippingCharge")?.Value;
result.Total = order.UserDefinedFields.Fields.SingleOrDefault(f => f.Key == "Total")?.Value;
var i = 0;
foreach(var orderLine in order.OrderLineHeaders)
{
result.OrderLineHeaders[i].JobNumber = orderLine.UserDefinedFields.Fields.SingleOrDefault(f => f.Key == "JobNumber")?.Value;
result.OrderLineHeaders[i].SkuDescription = orderLine.UserDefinedFields.Fields.SingleOrDefault(f => f.Key == "SkuDescription")?.Value;
result.OrderLineHeaders[i].UnitPrice = orderLine.UserDefinedFields.Fields.SingleOrDefault(f => f.Key == "UnitPrice")?.Value;
result.OrderLineHeaders[i].SubTotal = orderLine.UserDefinedFields.Fields.SingleOrDefault(f => f.Key == "SubTotal")?.Value;
i++;
}
return result;
}
public static string SalesOrder(OrderTemplate order, string htmlTempalte = null, string outputPath = null)
{
if (string.IsNullOrWhiteSpace(htmlTempalte))
{
htmlTempalte = System.IO.File.ReadAllText(@"Resources\salesOrderBody.html");
order.styles.Add(System.IO.File.ReadAllText(@"Resources\bootstrap.min.css"));
order.styles.Add(System.IO.File.ReadAllText(@"Resources\salesOrderStyle.css"));
}
var html = ToHtml(order, htmlTempalte);
// https://www.codeproject.com/articles/12799/print-html-in-c-with-or-without-the-web-browser-co
System.Diagnostics.Process.Start(SaveHTML(html));
return SavePdf(html, outputPath);
}
private static string ToHtml(AllfleXML.FlexOrder.OrderHeader order, string htmlTemplate)
{
var template = HandlebarsDotNet.Handlebars.Compile(htmlTemplate);
return template(order);
}
private static string GetTempHTMLOutputPath()
{
var tmpFile = System.IO.Path.GetTempFileName();
var htmlFile = System.IO.Path.ChangeExtension(tmpFile, ".html");
System.IO.File.Move(tmpFile, htmlFile);
return htmlFile;
}
private static string SaveHTML(string html, string path = null)
{
if (string.IsNullOrWhiteSpace(path)) path = GetTempHTMLOutputPath();
System.IO.File.WriteAllText(path, html);
return path;
}
private static string GetTempPDFOutputPath()
{
var tmpFile = System.IO.Path.GetTempFileName();
var pdfFile = System.IO.Path.ChangeExtension(tmpFile, ".pdf");
System.IO.File.Move(tmpFile, pdfFile);
return pdfFile;
}
private static string SavePdf(string html, string path = null)
{
if (string.IsNullOrWhiteSpace(path)) path = GetTempPDFOutputPath();
var pdfBuffer = HtmlToPdf(html);
System.IO.File.WriteAllBytes(path, pdfBuffer);
return path;
}
private static byte[] HtmlToPdf(string html)
{
var PdfConverter =
new TuesPechkin.ThreadSafeConverter(
new TuesPechkin.PdfToolset(
new TuesPechkin.WinAnyCPUEmbeddedDeployment(
new TuesPechkin.TempFolderDeployment())));
var globalConfig = new TuesPechkin.GlobalSettings
{
//DocumentTitle = "Sales Order",
//PaperSize = System.Drawing.Printing.PaperKind.A4,
//UseCompression = false,
//DPI = 1200,
Margins =
{
All = 0,
Unit = TuesPechkin.Unit.Centimeters
},
//ImageDPI = 1200,
//ImageQuality = 400
};
var document = new TuesPechkin.HtmlToPdfDocument
{
Objects = {
new TuesPechkin.ObjectSettings
{
//WebSettings = new TuesPechkin.WebSettings
//{
// EnableJavascript = true,
// LoadImages = true,
// PrintBackground = true,
// PrintMediaType = true
//},
//LoadSettings = new TuesPechkin.LoadSettings
//{
// BlockLocalFileAccess = false
//},
HtmlText = html,
FooterSettings = new TuesPechkin.FooterSettings
{
FontSize = 8,
RightText = "[page] of [topage]"
}
}
},
GlobalSettings = globalConfig
};
return PdfConverter.Convert(document);
}
}
}
<file_sep># Popflex: Purchase Order Printing from FlexOrders
<img src="https://raw.githubusercontent.com/Allflex/Popflex/master/Popflex.png" alt="Popflex Weasel" width="64" height="64" />
Natural, organic, non-GMO, and gluten free library that will take in a completed FlexOrder from the AllfleXML library, and convert it into a printable HTML document or PDF document by using [Pechkin](https://github.com/gmanny/Pechkin) and [Handlebars.net](https://github.com/rexm/Handlebars.Net).
<sup>Warning: May contain nuts.</sup> | 8fa1b6a25f3ef7e71bc84afe9b8c81f9eb543694 | [
"Markdown",
"C#"
] | 4 | C# | Allflex/Popflex | 58b9e7263edeaef2ead0c47d4ce3f23f7997535d | b9666ea1e43eef5e4b0b14f06452a9f586925c2c |
refs/heads/master | <file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace MED_20180308
{
class Program
{
static void Main(string[] args)
{
string refString = "abcdefghijklmnop";
string hypString = "abbcxefxhxjkllmnp";
MED med = new MED();
med.Run(refString, hypString);
}
}
}<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MED_20180308
{
class MED
{
public int INS { get; private set; } = 0;
public int DEL { get; private set; } = 0;
public int SUB { get; private set; } = 0;
public int REF { get; private set; } = 0;
public int ERR => INS + DEL + SUB;
public int HYP { get; private set; } = 0;
public double ErrorRate => 100.0 * ERR / REF;
public MED() { }
public void Run<T>(IEnumerable<T> refs, IEnumerable<T> hyps, bool useLocal=true)
{
var refArray = refs.ToArray();
var hypArray = hyps.ToArray();
REF = refArray.Length;
HYP = hypArray.Length;
if (REF == 0)
{
throw new Exception("Reference is empty.");
}
if (HYP == 0)
{
throw new Exception("Hypothesis is empty.");
}
else
{
if (useLocal)
{
DpLocal(refArray, hypArray);
}
else
{
var matrix = DP(refArray, hypArray);
BackTrack(matrix, refArray, hypArray);
}
}
}
private void BackTrack<T>(int[,] matrix, T[] refArray, T[] hypArray)
{
int r = refArray.Length;
int h = hypArray.Length;
while (r >= 0 && h >= 0)
{
if (r == 0 && h == 0)
break;
if (r == 0)
{
h--;
INS++;
continue;
}
if (h == 0)
{
r--;
DEL++;
continue;
}
if (refArray[r - 1].Equals(hypArray[h - 1]))
{
r--;
h--;
continue;
}
int current = matrix[r, h];
int preIns = matrix[r, h - 1];
int preDel = matrix[r - 1, h];
int preSub = matrix[r - 1, h - 1];
if (current == preIns + 1)
{
h--;
INS++;
continue;
}
if (current == preDel + 1)
{
r--;
DEL++;
continue;
}
r--;
h--;
SUB++;
}
}
private int[,] DP<T>(T[] refArray, T[] hypArray)
{
int[,] matrix = new int[REF + 1, HYP + 1];
for(int i = 1; i <= REF; i++)
{
matrix[i, 0] = i;
}
for(int j = 1; j <= HYP; j++)
{
matrix[0, j] = j;
}
for (int i = 1; i < REF + 1; i++)
{
for (int j = 1; j < HYP + 1; j++)
{
int left = matrix[i, j - 1] + 1;
int down = matrix[i - 1, j] + 1;
int diag = matrix[i - 1, j - 1] + (refArray[i - 1].Equals(hypArray[j - 1]) ? 0 : 1);
matrix[i, j] = Math.Min(Math.Min(left, down), diag);
}
}
return matrix;
}
private void DpLocal<T>(T[] refArray, T[] hypArray)
{
int n = refArray.Length + 1;
Cell[] Row = new Cell[n];
for (int i = 0; i < n; i++)
Row[i] = new Cell { DEL = i };
for(int i = 1; i < hypArray.Length + 1; i++)
{
var diagCell = Row[0].Clone();
Row[0] = new Cell { INS = i };
for(int j = 1; j < n; j++)
{
var bottomCell = Row[j];
var leftCell = Row[j - 1];
bool equalFlag = refArray[j-1].Equals(hypArray[i-1]);
int diag = diagCell.ERR + (equalFlag ? 0 : 1);
int left = leftCell.ERR + 1;
int bottom = bottomCell.ERR + 1;
int min = Math.Min(diag, Math.Min(left, bottom));
Cell current = new Cell();
if (left == min)
{
current = leftCell.Clone();
current.DEL++;
}
else if (bottom == min)
{
current = bottomCell.Clone();
current.INS++;
}
else
{
current = diagCell.Clone();
if (!equalFlag)
current.SUB++;
}
diagCell = Row[j].Clone();
Row[j] = current.Clone();
}
}
DEL = Row[n - 1].DEL;
INS = Row[n - 1].INS;
SUB = Row[n - 1].SUB;
}
}
class Cell
{
public int INS { get; set; } = 0;
public int SUB { get; set; } = 0;
public int DEL { get; set; } = 0;
public int ERR => INS + SUB + DEL;
public Cell Clone()
{
return new Cell { INS = INS, SUB = SUB, DEL = DEL };
}
}
}
<file_sep>๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace MED_20180308
{
class CheckFolder
{
public void Run(string refPath, string hypPath, string outputPath)
{
var list = CompareRootFolder(refPath, hypPath);
File.WriteAllLines(outputPath, list);
}
private IEnumerable<string> CompareRootFolder(string refRootPath, string hypRootPath)
{
foreach(string refFolderPath in Directory.EnumerateDirectories(refRootPath))
{
string folderName = refFolderPath.Split('\\').Last();
string hypFolderPath = Path.Combine(hypRootPath, folderName);
foreach(var item in CompareFolder(refFolderPath, hypFolderPath))
{
yield return item;
}
}
}
private IEnumerable<string> CompareFolder(string refFolderPath, string hypFolderPath)
{
string folderName = refFolderPath.Split('\\').Last();
var refList = Directory.GetFiles(refFolderPath);
var hypList = Directory.GetFiles(hypFolderPath);
for(int i = 0; i < refList.Length; i++)
{
string hypFilePath = hypList[i];
string refFilePath = refList[i];
yield return CompareFile(refFilePath, hypFilePath, folderName);
}
}
private string CompareFile(string refFilePath, string hypFilePath, string folderName)
{
string refString = File.ReadAllText(refFilePath).Replace("[XXX]", string.Empty);
string hypString = File.ReadAllText(hypFilePath).Replace("[XXX]", string.Empty);
MED med = new MED();
med.Run(refString, hypString);
string refFileName = refFilePath.Split('\\').Last();
string hypFileName = hypFilePath.Split('\\').Last();
return folderName + "\t" + refFileName + "\t" + hypFileName+"\t"
+ med.INS + "\t" + med.DEL + "\t" + med.SUB + "\t"
+ med.ERR + "\t" + med.REF + "\t" + (med.ErrorRate * 100).ToString("0.00");
}
}
}
| c63dfd56d38c4499af05fe3805fef83fe360fe59 | [
"C#"
] | 3 | C# | XiangweiTang/MED_20180308 | 2e5fb7ad223accd5f5839289875a2e7ae58b65b3 | 69b962674e5496d316200d337f5b2a7a93d1987a |
refs/heads/main | <file_sep>class cat(object):
def __init__(self, name,hunger = 0,boredom = 0):
print("ะะพัะฒะธะปะฐัั ะบะพัะบะฐ")
self.name= name
self.hunger=hunger
self.boredom=boredom
def __pass_time(self):
self.hunger +=1
self.boredom +=1
def talk(self):
print("ะผะตะฝั ะทะพะฒัั", self.name,"\n","ะกะฐะผะพััะฒััะฒะธะต : ",self.feel)
self.__pass_time()
def __yeah(self):
print("yeah")
def neyeah(self):
print("neyeah")
self.__yeah()
def eat(self,food = 4,boredom = 4):
print("ะกะฟะฐัะธะฑะพ")
self.boredom -= food
if self.boredom < 0:
self.boredom = 0
self.hunger-=food
if self.hunger < 0:
self.hunger=0
self.__pass_time()
def play(self,fun =4):
print("ะะะ")
self.__pass_time()
def golos(self):
print("ะผัั ะผัั")
self.__pass_time()
@property
def feel(self):
unhappiness = self.hunger + self.boredom
if unhappiness <5:
m="ะะฐะบ ะพะฑััะฝะพ ะฒัะต ะบะปัะฑะฝะธัะฝะพ"
elif 5<= unhappiness <=10:
m="ะฝะพัะผ"
elif 10<=unhappiness<15:
m="ะะพะณะปะพ ะฑััั ะธ ะปัััะต"
else:
m="ะฒัะต ะฟะปะพั
ะพ"
return m
class dog(object):
def __init__(self, name,hunger = 0,boredom = 0):
print("ะะพัะฒะธะปะฐัั ัะพะฑะฐะบะฐ")
self.name= name
self.hunger=hunger
self.boredom=boredom
def __pass_time(self):
self.hunger +=1
self.boredom +=1
def talk(self):
print("ะผะตะฝั ะทะพะฒัั", self.name,"\n","ะกะฐะผะพััะฒััะฒะธะต : ",self.feel)
self.__pass_time()
def __yeah(self):
print("yeah")
def neyeah(self):
print("neyeah")
self.__yeah()
def eat(self,food = 4,boredom = 4):
print("ะกะฟะฐัะธะฑะพ")
self.boredom -= food
if self.boredom < 0:
self.boredom = 0
self.hunger-=food
if self.hunger < 0:
self.hunger=0
self.__pass_time()
def play(self,fun =4):
print("ะะะ")
self.__pass_time()
def golos(self):
print("ะณะฐะฒ ะณะฐะฒ")
self.__pass_time()
@property
def feel(self):
unhappiness = self.hunger + self.boredom
if unhappiness <5:
m="ะะฐะบ ะพะฑััะฝะพ ะฒัะต ะบะปัะฑะฝะธัะฝะพ"
elif 5<= unhappiness <=10:
m="ะฝะพัะผ"
elif 10<=unhappiness<15:
m="ะผะพะณะปะพ ะฑััั ะธ ะปัััะต"
else:
m="ะฒัะต ะฟะปะพั
ะพ"
return m
class rabbit(object):
def __init__(self, name,hunger = 0,boredom = 0):
print("ะะพัะฒะธะปัั ะบัะพะปะธะบ")
self.name= name
self.hunger=hunger
self.boredom=boredom
def __pass_time(self):
self.hunger +=1
self.boredom +=1
def talk(self):
print("ะผะตะฝั ะทะพะฒัั", self.name,"\n","ัะฐะผะพััะฒััะฒะธะต : ",self.feel)
self.__pass_time()
def __yeah(self):
print("yeah")
def neyeah(self):
print("neyeah")
self.__yeah()
def eat(self,food = 4,boredom = 4):
print("ะกะฟะฐัะธะฑะพ")
self.boredom -= food
if self.boredom < 0:
self.boredom = 0
self.hunger-=food
if self.hunger < 0:
self.hunger=0
self.__pass_time()
def play(self,fun =4):
print("ะะะ!")
self.__pass_time()
def golos(self):
print("ัััะบ ัััะบ")
self.__pass_time()
@property
def feel(self):
unhappiness = self.hunger + self.boredom
if unhappiness <5:
m="ะะฐะบ ะพะฑััะฝะพ ะฒัะต ะบะปัะฑะฝะธัะฝะพ"
elif 5<= unhappiness <=10:
m="ะฝะพัะผ"
elif 10<=unhappiness<15:
m="ะผะพะณะปะพ ะฑััั ะธ ะปัััะต"
else:
m="ะฒัะต ะฟะปะพั
ะพ"
return m
def main():
f = None
while f != 0:
x = int(input("ะะฐะฟะธัะธัะต ัะธััั ััะพะฑั ะฒัะฑัะฐัั ะถะธะฒะพัะฝะพะณะพ: 1 - ะัะพะปะธะบ,2 - ะะพัะบะฐ, 3 - ะกะพะฑะฐะบะฐ "))
if x == 1:
crit_name = input("<NAME> ")
crit1 = rabbit(crit_name)
elif x == 2:
crit_name = input("ะะผั ะะพัะบะธ ")
crit1 = cat(crit_name)
elif x == 3:
crit_name = input("ะะผั ะกะพะฑะฐะบะธ ")
crit1 = dog(crit_name)
else:
f = 0
if f !=0:
zapusk(crit1)
def zapusk(u):
choice = None
while choice != 0:
print("""
<NAME>ะฒะตัััะบะฐ
0 - ะัะนัะธ
1 - ัะทะฝะฐัั ะพ ัะฐะผะพััะฒััะฒะธะธ ะทะฒะตัััะบะธ
2 - ะฟะพะบะพัะผะธัั ะทะฒะตัััะบั
3 - ะฟะพะธะณัะฐัั ัะพ ะทะฒะตัััะบะพะน
4 - ะฟะพะฟัะพัะธัั ะณะพะปะพั
""" )
choice=int(input("ะัะฑะธัะฐะนัะต "))
if choice==0:
print("ะะพะบะฐ")
elif choice ==1:
u.talk()
elif choice == 2:
u.eat()
elif choice==3:
u.play()
elif choice==5:
print(u.name)
print(u.boredom)
print(u.hunger)
elif choice == 4:
u.golos()
else:
print("ะขะฐะบะพะณะพ ะฟัะฝะบัะฐ ะฝะตั")
main()
input("Enter,ััะพะฑั ะฒัะนัะธ")
| 6da048a00bc3ad3c4e114ca4327305a33dfcdec0 | [
"Python"
] | 1 | Python | bada20493/- | 5e4350136877809587811b5b2747152589c6f6be | ccba308f4b0940b82bb21f2806be11855dd504ce |
refs/heads/master | <file_sep>package com.alexvak.spring5recipeapp.services;
import com.alexvak.spring5recipeapp.commands.UnitOfMeasureCommand;
import java.util.Set;
public interface UnitOfMeasureService {
Set<UnitOfMeasureCommand> listAllUoms();
}
<file_sep>package com.alexvak.spring5recipeapp.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.NOT_FOUND)
public class RecipeNotFoundException extends RuntimeException {
private static final String NOT_FOUND = "Recipe not found. ID: %s";
public RecipeNotFoundException(Long id) {
this(String.valueOf(id));
}
public RecipeNotFoundException(String id) {
super(String.format(NOT_FOUND, id));
}
}
<file_sep>package com.alexvak.spring5recipeapp.controllers;
import com.alexvak.spring5recipeapp.commands.IngredientCommand;
import com.alexvak.spring5recipeapp.commands.RecipeCommand;
import com.alexvak.spring5recipeapp.commands.UnitOfMeasureCommand;
import com.alexvak.spring5recipeapp.exceptions.RecipeNotFoundException;
import com.alexvak.spring5recipeapp.services.IngredientService;
import com.alexvak.spring5recipeapp.services.RecipeService;
import com.alexvak.spring5recipeapp.services.UnitOfMeasureService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.Objects;
@Slf4j
@Controller
public class IngredientController {
private final RecipeService recipeService;
private final IngredientService ingredientService;
private final UnitOfMeasureService unitOfMeasureService;
public IngredientController(RecipeService recipeService, IngredientService ingredientService,
UnitOfMeasureService unitOfMeasureService) {
this.recipeService = recipeService;
this.ingredientService = ingredientService;
this.unitOfMeasureService = unitOfMeasureService;
}
@GetMapping("/recipe/{recipeId}/ingredients")
public String ingredientsList(@PathVariable String recipeId, Model model) {
log.debug("Getting ingredient list for recipe Id: " + recipeId);
model.addAttribute("recipe", recipeService.findCommandById(Long.valueOf(recipeId)));
return "recipe/ingredient/list";
}
@GetMapping("/recipe/{recipeId}/ingredient/{ingredientId}/show")
public String showIngredient(
@PathVariable String recipeId,
@PathVariable String ingredientId,
Model model) {
log.debug(String.format("Showing ingredient [id:%s] for recipe [id:%s]", ingredientId, recipeId));
model.addAttribute("ingredient",
ingredientService.findByRecipeIdAndIngredientId(Long.valueOf(recipeId), Long.valueOf(ingredientId)));
return "recipe/ingredient/show";
}
@GetMapping("/recipe/{recipeId}/ingredient/{ingredientId}/update")
public String updateRecipeIngredient(
@PathVariable String recipeId,
@PathVariable String ingredientId,
Model model) {
model.addAttribute("ingredient",
ingredientService.findByRecipeIdAndIngredientId(Long.valueOf(recipeId), Long.valueOf(ingredientId)));
model.addAttribute("uomList", unitOfMeasureService.listAllUoms());
return "recipe/ingredient/ingredientform";
}
@GetMapping("/recipe/{recipeId}/ingredient/new")
public String newIngredient(
@PathVariable String recipeId,
Model model) {
RecipeCommand recipeCommand = recipeService.findCommandById(Long.valueOf(recipeId));
if (Objects.isNull(recipeCommand)) {
throw new RecipeNotFoundException(recipeId);
}
IngredientCommand command = new IngredientCommand();
command.setRecipeId(recipeCommand.getId());
model.addAttribute("ingredient", command);
command.setUom(new UnitOfMeasureCommand());
model.addAttribute("uomList", unitOfMeasureService.listAllUoms());
return "recipe/ingredient/ingredientform";
}
@PostMapping("/recipe/{recipeId}/ingredient")
public String saveOrUpdate(@ModelAttribute IngredientCommand command) {
IngredientCommand savedCommand = ingredientService.saveIngredientCommand(command);
log.debug("saved recipe id: " + command.getRecipeId());
log.debug("saved ingredient id: " + command.getId());
return "redirect:/recipe/" + savedCommand.getRecipeId() + "/ingredients";
}
@GetMapping("/recipe/{recipeId}/ingredient/{id}/delete")
public String deleteIngredient(@PathVariable String recipeId, @PathVariable String id) {
log.debug("deleting ingredient id " + id);
ingredientService.deleteById(Long.valueOf(recipeId), Long.valueOf(id));
return "redirect:/recipe/" + recipeId + "/ingredients";
}
}
<file_sep>#!/usr/bin/env bash
docker build -t alexvak/spring5-recipe-app:latest -t alexvak/spring5-recipe-app:$SHA -f ./docker-files/recipe-app/Dockerfile .
docker push alexvak/spring5-recipe-app:latest
docker push alexvak/spring5-recipe-app:$SHA
kubectl apply -f k8s
kubectl set image deployments/recipe-app-deployment recipe-app=alexvak/spring5-recipe-app:$SHA<file_sep>package com.alexvak.spring5recipeapp.converters;
import com.alexvak.spring5recipeapp.commands.CategoryCommand;
import com.alexvak.spring5recipeapp.domain.Category;
import lombok.Synchronized;
import org.springframework.core.convert.converter.Converter;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import java.util.Objects;
@Component
public class CategoryCommandToCategory implements Converter<CategoryCommand, Category> {
@Synchronized
@Nullable
@Override
public Category convert(CategoryCommand categoryCommand) {
if (Objects.isNull(categoryCommand)) {
return null;
}
final Category category = new Category();
category.setId(categoryCommand.getId());
category.setDescription(categoryCommand.getDescription());
return category;
}
}
<file_sep>package com.alexvak.spring5recipeapp.exceptions;
public class UnitOfMeasureNotFoundException extends RuntimeException {
public UnitOfMeasureNotFoundException(Long id) {
super("Unit of measure not found. Id: " + id);
}
}
<file_sep># spring5-recipe-app
Implementation https://recipe.alexvak.com
[](https://travis-ci.org/AlexVak/spring5-recipe-app)
[](https://codecov.io/gh/AlexVak/spring5-recipe-app)
<file_sep>FROM mysql
ENV MYSQL_DATABASE recipe
ENV MYSQL_USER recipe
COPY ./docker-files/mysql/schema-generation-mysql.sql /docker-entrypoint-initdb.d/<file_sep>recipe.description=Description (default)
recipe.cookTime=Cook Time
NotBlank.recipe.description={0} Cannot Be Blank
Size.recipe.description={0} must be between {2} and {1} characters long
Max.recipe.cookTime={0} must be less than {1}
URL.recipe.url=Please provide a valid URL | c73b539e7ceb12e7bed5cfb34c54d25431e75f14 | [
"Markdown",
"INI",
"Java",
"Dockerfile",
"Shell"
] | 9 | Java | AlexVak/spring5-recipe-app | d97c935962ea52698ad3ad9df379ecb4b2bb492f | 0e695a0d6bf9668f156516225c848b022513b444 |
refs/heads/master | <file_sep>#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <DHT.h>
#include <Adafruit_Sensor.h>
#include <Fonts/FreeSans9pt7b.h>
#include <Fonts/FreeSansBold9pt7b.h>
#define dataPin 4
#define DHTTYPE DHT11
DHT dht(dataPin, DHTTYPE);
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET 5
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#define LOGO_HEIGHT 64
#define LOGO_WIDTH 128
void setup()
{
Serial.begin(9600);
dht.begin();
// SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C))
{ // Address 0x3D for 128x64
Serial.println(F("SSD1306 allocation failed"));
for (;;)
; // Don't proceed, loop forever
}
delay(1000);
}
void loop()
{
float h = dht.readHumidity(); // read humidity
float t = dht.readTemperature(); // read temperature
float hic = dht.computeHeatIndex(t, h, false); // compute head index for temp in ยฐC
// Printing the results on the serial monitor
Serial.print("Temperature = ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(" Humidity = ");
Serial.print(h);
Serial.println(" % ");
display.clearDisplay();
display.setTextSize(1); // Draw 2X-scale text
display.setTextColor(WHITE);
display.setFont(&FreeSansBold9pt7b);
display.setCursor(0, 13);
display.print(F("Temp: "));
display.setFont(&FreeSans9pt7b);
display.drawCircle(105, 2, 2, WHITE);
display.print(t);
display.println(F(" C"));
display.setFont(&FreeSansBold9pt7b);
display.print(F("Humid: "));
display.setFont(&FreeSans9pt7b);
display.print(h);
display.println(F("%"));
display.setFont(&FreeSansBold9pt7b);
display.print(F("Feels: "));
display.setFont(&FreeSans9pt7b);
display.print(hic);
display.println(F(" C"));
display.drawCircle(103, 45, 2, WHITE);
display.display();
delay(2000); // Delays 2 secods, as the DHT22 sampling rate is 0.5Hz
} | 539a1628f1685764529f38e3b49887f40e33a3b6 | [
"C++"
] | 1 | C++ | nirvikagarwal/weather-info-machine | 36f64223941b243095ff7b8af2d695b4afe130ad | f4eef574297eeb1b57ded63190a05fcf8c8e6e6e |
refs/heads/master | <file_sep>import os
from itertools import chain
from enum import Enum
class Festival(Enum):
"""Festivals allowed by the clock"""
TOYDAY = 'toy day'
HALLOWEEN = 'halloween'
FIREWORKS = 'fireworks'
KKSLIDER = 'kk slider'
CARNIVALE = 'carnivale'
HARVESTFESTIVAL = 'harvest festival'
BUNNYDAY = 'bunny day'
NEWYEAR = 'new year'
NEWYEARSEVE = 'new years eve'
NONE = 'none'
def main():
"""Check to make sure Album for Animal Crossing Gyroid Clock works"""
album = raw_input('Enter Album you want to check: /Music/')
album = 'Music/' + album.split('/')[0] + '/'
checkfor = ['hour', 'snow_hour', 'rain_hour', 'festival', 'etc']
folder_error_msg = []
all_error = []
if not os.path.isdir(album):
all_error.append(['ERROR: Album does not exit'])
else:
folder_error_msg = check_folders(album, checkfor)
all_error.append(folder_error_msg)
# print folder_error_msg
for i, fol in enumerate(checkfor):
if folder_error_msg[i] is None:
msg = check_songs(fol, album + fol + '/')
all_error.append(msg)
# Print all error messages
all_error = list(chain.from_iterable(all_error))
print '*************************'
for i in all_error:
if i:
print i
print '*************************'
def check_songs(fol, loc):
"""Iterate check through songs given folder"""
err_msg = []
if fol is 'etc':
lists = os.listdir(loc)
if len(lists) == 0:
err_msg.append('ERROR: Need songs in ETC folder')
elif len(lists) < 5:
err_msg.append('WARNING: Consider adding more songs to ETC')
elif fol is 'festival':
err_msg.append('FIXME: need to finish festival check')
else:
# We are now checking an 'hours' folder, ie snow_hour, hour, rain_hour
for i in range(0, 23):
song_f = loc + str(i) + '.mp3'
if not os.path.isfile(song_f):
err_msg.append('ERROR: Missing file: ' + song_f)
return err_msg
def check_folders(album_loc, checkfor):
"""Iterate check through folders"""
dirs = os.listdir(album_loc)
error_msg = [None] * (len(checkfor) + 1)
for i, fol in enumerate(checkfor):
if not os.path.isdir(album_loc + fol):
error_msg[i] = 'ERROR: Missing Album: ' + fol
if len(dirs) > len(checkfor):
error_msg[-1] = 'WARNING: Extra Albums'
return error_msg
if __name__ == '__main__':
main()
<file_sep>from __future__ import division
from datetime import datetime
from enum import Enum
from socket import error as SocketError
from time import sleep
import os
import sys
import signal
import pyowm
import random
import subprocess
import pygame
import config
from csv import reader as csvreader
import check_album
from gpio_handler import gpio_handler
class Weather(Enum):
RAIN = 'rain_hour/'
SNOW = 'snow_hour/'
NONE = 'hour/'
class Festival(Enum):
TOYDAY = 'toy day/'
HALLOWEEN = 'halloween/'
FIREWORKS = 'fireworks/'
KKSLIDER = 'kk slider'
CARNIVALE = 'carnivale/'
HARVESTFESTIVAL = 'harvest festival/'
BUNNYDAY = 'bunny day/'
NEWYEAR = 'new year/'
NEWYEARSEVE = 'new years eve/'
NONE = 'none'
# Initialization parameters of the pygame.mixer
FREQ = 44100
BITSIZE = -16
CHANNELS = 2
BUFFER = 4096
global ch1 # global handle for channel 1 for music
global ch2 # global handle for channel 2 for music
global mus # global music handler
global pigpio # GPIO Object handle
# Notes:
# FIX ME: when ETC plays, title keeps getting reprinted over and over for length of song
def main():
global pigpio
try:
pigpio = gpio_handler()
pigpio.set_PIenable(True) # Set running pin TRUE for daughter board
pigpio.set_Speaker_SHTDWN(True) # Turn on Speaker
# signal.signal(pigpio.callback_SHTDWN, signal_handler) # Signal interrupt if button on daughter board is pressed
except:
print 'Error: PI possibly not connected'
print sys.exc_info()[0]
musicloc = 'Music/' # Location of the Musics folder with all the sounds
cycle = 10 # Max time between songs in seconds
cts_play = True # True for continuous play
allow_albums = config.albums_allowable
tvol = config.time_volume
print 'Loaded in: ' + str(config.albums_allowable)
pygame.mixer.init(FREQ, BITSIZE, CHANNELS, BUFFER)
pygame.init()
global ch1
global ch2
ch1 = pygame.mixer.Channel(0) # for music and songs
ch2 = pygame.mixer.Channel(1) # for sound effects
pygame.mixer.music.set_volume(tvol[datetime.now().hour]/10)
#bootupSong()
# TODO, play bootupsong as a sound effect, which will allow the bootup process to continue
# Then add a wait condition for if/when bootupsong is done playing
dto = datetime.now()
#oldHour = dto.hour # Starts with boot
lastcheckWeather = False
isWeather = Weather.NONE
isFestival = Festival.NONE
day_check = [] # Assumption: There'll never be a day []
play_check = 0
signal.signal(signal.SIGINT, signal_handler)
play_check = check_play_triggers(True, dto.hour, 0)
while 1: # Infinite Main Loop
dt = datetime.now()
hour = dt.hour
ch1.set_volume(tvol[hour]/10)
ch2.set_volume(tvol[hour]/10)
pygame.mixer.music.set_volume(tvol[hour]/10)
minute = dt.minute
if play_check > 0:
if dt.minute > 55 or not lastcheckWeather:
# Checks Weather, returns 'none', 'snow', or 'rain'
isWeather = checkWeather(config.location) # Check weather at location
lastcheckWeather = True
if day_check != dt.day:
# Checks for festivals like Christmas, KK, etc
isFestival = checkFestival(dt)
day_check = dt.day
played = False
while not played:
# Keep choosing songs until something plays
album = random.choice(allow_albums)
songloc = musicloc + album + '/'
check_rigid = True
with open(songloc + 'album_config.txt','r+') as cf_file:
read = csvreader(cf_file, delimiter='=', quotechar='|')
for i in read:
comm_line = [i[0],i[1]]
if 'rigid' in i[0]:
check_rigid = i[1].strip()
if 'freq' in i[0]:
freq_set = int(i[1].strip())
_init = pygame.mixer.get_init()
if freq_set != _init[0]:
pygame.mixer.quit() # Need to quit to reinitialize mixer
pygame.mixer.pre_init(freq_set, _init[1], _init[2])
pygame.mixer.init()
#print pygame.mixer.get_init()
# FIX ME: A bit of a janky way of implementing album prefs
if check_rigid == 'True':
played = chooseMusic_Rigid(songloc, hour, isWeather, isFestival, play_check)
else:
played = chooseMusic_Flexible(songloc, hour, isWeather, isFestival, play_check)
#print 'Loop Entered'
while True:
sound_check_new = check_sound_triggers()
play_check_new = check_play_triggers(cts_play, hour, play_check)
if pigpio.SHTDWN:
signal_handler(signal.SIGINT, 0)
elif play_check > 0 and play_check_new != play_check:
fadeout_time = 3000 # milliseconds
pygame.mixer.music.fadeout(fadeout_time)
# Wait fadeout time + 100 ms
sleep(fadeout_time/1000 + .1)
played = False
# Possibly don't need thise played = False to accurately get the
# loop back to playing new music, I just don't want to wait the
# sleep cycle
else:
sleep(2)
play_check = play_check_new
if not pygame.mixer.music.get_busy():
# Emulate Do-while loop by going t hrough this at least once
#print played
#print 'Loop broken'
break
# If song did not play, new song will be chosen
#oldHour = hour
lastcheckWeather = False
if play_check == 1:
sleep(random.randint(1,cycle)) # Sleeps random integers seconds between 1 and cycle
def check_play_triggers(cts_play, oldHour, old_play_check):
""" play_check returns:
0: 0 is no mode, skip to sleep cycle
1: Cts Play
2: Play the Top of the Hour <----- not fully supported yet
3: Play etc Song
4: Ring bell toll
5: onwards: Not yet used
"""
dt = datetime.now()
hour = dt.hour
minute = dt.minute
play_check = 0
if cts_play: # decide on song for continuous play
#print oldHour
#print hour
#print '---'
if oldHour != hour and minute == 0: # Top of the hour
if config.hrly_preferences['ring_bell']:
play_check = 4
else:
play_check = 3
# play_check = 2 # To be enabled with supported with additional music options
elif minute in [15, 30, 45]:
play_check = 3
else:
play_check = 1
else: # Non-continuous play song decision
if minute == 0:
if config.hrly_preferences['ring_bell']:
play_check = 4
else:
play_check = 2
if minute in [15, 30, 45]:
play_check = 3
else:
play_check = 0
# Assumption: That cycle is < 60s and that a song length is >60s
return play_check
def check_sound_triggers():
minute = datetime.now().minute
fx_fold = 'Music/Resources/effects/'
#if True: # play test, ignore
# crits = fx_fold + 'critters/'
# ff = [crits + '066.wav', crits + '066.wav', crits + '067.wav', crits + '068.wav']
# print 'playing'
# play_sound(ff)
return False
def play_sound(music_file):
# Function call to play sounds in addition to the main music e.g. cicada
played = False
for i in music_file:
if os.path.exists(i):
#print i
soundobj = pygame.mixer.Sound(i)
length = soundobj.get_length()
soundobj.play()
sleep(length + .15)
played = True
print music_file
return played
def play_music(f):
# Play main mixer music function
played = False
try:
if os.path.exists(f):
#print f
pygame.mixer.music.load(f)
# subprocess.Popen(['mpg123', '-q', f]).wait()
pygame.mixer.music.play(0)
played = True
else:
print 'Warning: ' + f + ' Does not exist'
played = False
except:
played = False
return played
def chooseMusic_Rigid(file_loc, hour, isWeather, isFestival, cts):
"""Check festival first, then check weather"""
# FIX ME: Need to organize to respond more accurately to cts states
song_loc = ''
played = False
print file_loc
if cts == 4:
played = ring_bell()
#return played
#FIX ME; Should exit after ring bell or not? Is it find to proceed?
if cts == 3:
etcfol = file_loc + 'etc/'
# Consider: adding a play_sound here
song_loc = etcfol + random.choice(os.listdir(etcfol))
else:
# Else, play main music selection
if isFestival != Festival.NONE:
if isFestival == Festival.KKSLIDER:
musicFile = 'Music/KK/'
kksong = random.choice(os.listdir(musicFile))
musicFile = musicFile + kksong
else:
musicfol = file_loc + 'festival/' + isFestival.value
musicFile = musicfol + random.choice(os.listdir(musicfol))
else:
# Chance arbitrarly set at 10% if etcCheck passes
#-------------------------------------------------------
# Commented out because I didn't like the random chance of other music playing
# I changed it so cts == 3 means play random music on its own timer
# not just randomly within every call
#etcfol = file_loc + 'etc/'
# Check if etc folder exists and there's music
#etcCheck = False
#if os.path.isdir(etcfol) and len(os.listdir(etcfol)) > 0:
# etcCheck = True
#if (etcCheck and ((random.randint(0, 100) < 10) and cts == 1)) or cts == 3:
# musicFile = etcfol + random.choice(os.listdir(etcfol))
#else:
# # musicFile = file_loc + isWeather.value + str(hour) + '.mp3'
# music_fol = file_loc + isWeather.value + str(hour) + '/'
# musicFile = music_fol + random.choice(os.listdir(music_fol))
#-------------------------------------------------------
music_fol = file_loc + isWeather.value + str(hour) + '/'
song_loc = music_fol + random.choice(os.listdir(music_fol))
played = play_music(song_loc)
return played
def chooseMusic_Flexible(song_loc, hour, isWeather, isFestival, cts):
_times = config.flexible_defs
# flexible_defs are the definitions for how the exact hour correlates to
# 'Afternoon', 'Morning', 'Noon', etc
songfile = ''
if cts == 3:
#song_loc = song_loc + 'etc/'
# Consider: adding a play_sound here
songfile = random.choice(os.listdir(song_loc + 'etc/'))
elif cts == 4:
played = ring_bell()
#return played
#elif
if isFestival is not Festival.NONE:
song_loc = song_loc + 'Festival/'
songfile = random.choice(os.listdir(song_loc))
elif hour in _times['Morning']:
song_loc = song_loc + 'Morning/'
songfile = random.choice(os.listdir(song_loc))
elif hour in _times['Noon']:
song_loc = song_loc + 'Noon/'
songfile = random.choice(os.listdir(song_loc))
elif hour in _times['Afternoon']:
song_loc = song_loc + 'Afternoon/'
songfile = random.choice(os.listdir(song_loc))
elif hour in _times['Evening']:
song_loc = song_loc + 'Evening/'
songfile = random.choice(os.listdir(song_loc))
elif hour in _times['Night']:
song_loc = song_loc + 'Night/'
songfile = random.choice(os.listdir(song_loc))
song_loc += songfile
played = play_music(song_loc)
return played
def ring_bell():
"""Plays bell tone """
file_loc = "Music/Resources/Menu/"
bell_song = file_loc + "belltone.mp3"
play_music(bell_song)
#pygame.mixer.music.load(bell_song)
#pygame.mixer.music.play(0)
while pygame.mixer.music.get_busy():
sleep(1)
return True
def bootupSong():
"""Plays a random song in the Menu folder"""
file_loc = 'Music/Resources/Menu/'
start_song = file_loc + 'Nintendo.mp3'
# start_song = file_loc + 'Train_Departure.mp3'
pygame.mixer.music.load(start_song)
pygame.mixer.music.play(0)
while pygame.mixer.music.get_busy():
sleep(1)
def checkWeather(city):
"""Python Open Weather Map, pass it string of city,country"""
#city = 'Jersey City,us'
try:
# Key provided free on openweathermap.org
owm = pyowm.OWM('7fcf1a61a3f873475c5d8ea070c6454b')
weather = owm.weather_at_place(city).get_weather()
status = weather.get_status()
except:
print 'Socket Closed Error'
status = Weather.NONE
return status
if status in ['Drizzle', 'Thunderstorm', 'Rain']:
return Weather.RAIN
elif status == 'Snow':
return Weather.SNOW
else:
return Weather.NONE
def checkFestival(dt):
"""Checks festival dates"""
weekday = dt.weekday() # Returns 0-6 for Day of the Week
month = dt.month
day = dt.day
hour = dt.hour
date = str(dt.date())
carnivale_dates = ['2017-2-27','2018-2-12','2019-3-4','2020-2-24','2021-3-15','2022-2-28']
bunnyday_dates = []
#harvest_dates = ['2016-11-24']
festival = Festival.NONE
# Check for Halloween, Christmas and ...
if day == 25 and month == 12:
# It's Festival
festival = Festival.TOYDAY
elif day == 31 and month == 10:
# It's Halloween
festival = Festival.HALLOWEEN
elif weekday == 5 and hour > 20:
# Slider
festival = Festival.KKSLIDER
elif day == 31 and month == 12:
return Festival.NEWYEARSEVE
elif day == 1 and month == 1:
festival = Festival.NEWYEAR
elif day == 4 and month == 7:
festival = Festival.FIREWORKS
elif date in carnivale_dates:
festival = Festival.CARNIVALE
elif day == 24 and month == 11: # Hardcoded thanksgiving
#elif date in harvest_dates:
festival = Festival.HARVESTFESTIVAL
else:
festival = Festival.NONE
return festival
def signal_handler(signal, frame):
global pigpio
print 'SIGINT Received, quitting program...'
#pygame.mixer.music.fadeout(3000) # Fade music out at 3000 ms
pygame.mixer.quit()
print 'Quiting Pygame Mixer...'
try:
pigpio.cleanup() # Release GPIO before quitting
except:
print 'No GPIO to access'
if frame == 0:
# Frame == 0 is specially passed by daughter board
os.system("sudo shutdown now -h")
else:
sys.exit(0)
if __name__ == "__main__":
main()
<file_sep>#!/bin/bash
# Open Weather Map for weather
# Must obtain API Key from website
pip install pyowm
#apt-get install mpg123
source venv/bin/activate
deactivate
pip install pyyaml
sudo apt-get install python-pygame
<file_sep>#albums_allowable = ['City Folk','Original','New Leaf']
#albums_allowable = ['Original']
#albums_allowable = ['Pokemon RSE','FFCC','Original','City Folk']
#albums_allowable = ['Pokemon RSE', 'FFCC', 'Original', 'City Folk', 'New Leaf']
albums_allowable = ['Pokemon RSE']
flexible_defs = dict(
# Specify which hours, 0 through 23, should belong to these time categories
# The flexible albums will pull music based on these times
Morning = [8, 9, 10, 11],
Noon = [12, 13, 14, 15],
Afternoon = [16, 17, 18, 19],
Evening = [20, 21, 22, 23],
Night = [0, 1, 2, 3, 4, 5, 6, 7],
)
location = "Jersey City, US"
# Default volume level for the hours 0 through 23 from scale 0 (mute) through 10
# [ 0 1 2 3 4 5
# 6 7 8 9 10 11
# 12 13 14 15 16 17
# 18 19 20 21 22 23]
time_volume = [ 0, 0, 0, 0, 1, 2,
3, 5, 6, 7, 8, 8,
9, 9, 9, 9, 9, 9,
8, 8, 7, 6, 5, 4]
cts_preferences = dict(
test = 'test',
)
hrly_preferences = dict(
# If you want the bell to ring before the music plays, set as True
ring_bell = True,
)
<file_sep># Animal-Crossing-Gyroid-Clock version 2A
A Raspberry PI music player that attempts to recreate the animal crossing soundtrack by playing music associated with the time and weather, by <NAME>
Version Gyroid_2A corresponds to development version for Raspberry Pi Zero W adding additional functions of user turning on/off custom album settings as well as improvements to the music selection
2A corresponds to breadboard while Gyroid 2B will correspond to printed board
Setup gpio pwm function 2 for audio
>sudo nano /boot/config.txt
add line dtoverlay=pwm-2chan,pin=18,func=2,pin2=13,func2=4
Setup new user
>sudo addgroup <username> audio
>logout
>login
>sudo raspi-config
3. boot options, B1 Desktop / CLI, B2 Console Autologin Text console, automatically logged in as <username> user
Ensure that the new username is the new account or else it'll remain the default pi usr
Test Audio
>aplay /usr/share/sounds/alsa/Front_Center.wav
Clone Github Directory
>sudo git clone https://github.com/acheu/Animal-Crossing-Gyroid-Clock.git
Install Dependancies
>sudo apt update
>sudo apt install python3-pip
>sudo pip install pyowm
>sudo apt-get install mpg123
>sudo pip install pyyaml
>sudo apt-get install python-pygame
Move Music
>mkdir Animal-Crossing-Gyroid-Clock/Music
from other computer...
>scp myfile.tar.gz pi@192.168.1.x:
<file_sep>try:
import RPi.GPIO as GPIO
except RuntimeError:
print 'RuntimeError: Error accessing RPi Library. Retry as Sudo'
except ImportError:
print 'ImportError: Error accessing RPi Library'
# Pins:
# 29, GPIO 21 --> (0) Spare (Read)
# 31, GPIO 22 --> (1) Volume Wiper (Read)
# 33, GPIO 23 --> (2) RUN reset (Read)
# 35, GPIO 24 --> (3) SHTDWN Comamnd (Read)
# 37, GPIO 25 --> (4) PIenable (Set)
class gpio_handler(object):
def get_Spare(self):
io = GPIO.input(self.chanlist[0])
return io
def get_Volume(self):
io = GPIO.input(self.chanlist[1])
return io
def get_RUN(self):
print 'Error: RUN pin was not intended to be accessed'
def get_SHTDWN(self):
io = GPIO.input(self.chanlist[3])
return io
def callback_SHTDWN(self,channel):
# Send shutdown command
print 'SHTDWN Command Toggled'
# raise KeyboardInterrupt
self.SHTDWN = True
def set_PIenable(self,highlow):
""" Set to Enabled with a highlow == True when program is running """
GPIO.output(self.chanlist[4], highlow)
def cleanup(self):
""" closeout function, releases all gpio resources """
GPIO.cleanup(self.chanlist)
def get_chanlist(self):
""" Return the chanlist """
return self.chanlist
def set_chanlist(self,loc,newchannel):
""" reformat a channel to another channel """
# TODO, add checks and illegal arguments to protect Pi
# TODO actually add the functionality
# self.chanlist(loc) = newchannel
def __init__(self):
""" Create object handle for interfacing with RPi Model B GPIO """
GPIO.setmode(GPIO.BOARD) # Set's GPIO referencing to RPi Board Refdes
self.chanlist = [29, 31, 33, 35, 37] # chanlist 0, 1, 2, 3, 4
GPIO.setup(29, GPIO.IN) # Setup as input to pi
GPIO.setup(31, GPIO.IN) # Setup as input
GPIO.setup(33, GPIO.IN) # Setup as input
GPIO.setup(35, GPIO.IN) # Setup as input
GPIO.setup(37, GPIO.OUT) # Setup as output from pi
self.SHTDWN = False
GPIO.add_event_detect(self.chanlist[1], GPIO.BOTH)
GPIO.add_event_detect(self.chanlist[3], GPIO.FALLING, self.callback_SHTDWN, bouncetime=200)
| 0aaf8b29ffe7f7a010b162bbdf332cd37945d258 | [
"Markdown",
"Python",
"Shell"
] | 6 | Python | acheu/Animal-Crossing-Gyroid-Clock | 33f8c24e658f659bb04673fb32e57526915029aa | 1cb460211d8f3e94536997f5580a798185c6012d |
refs/heads/master | <repo_name>GrahamTheCoder/CodeConverter<file_sep>/ICSharpCode.CodeConverter/CSharp/UsageTypeAnalyzer.cs
๏ปฟusing System.Linq;
using System.Threading.Tasks;
using ICSharpCode.CodeConverter.Util;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Operations;
namespace ICSharpCode.CodeConverter.CSharp
{
internal static class UsageTypeAnalyzer
{
public static bool? HasWriteUsages(this Solution solution, ISymbol symbol)
{
return HasWriteUsagesAsync(solution, symbol).GetAwaiter().GetResult(); //Should do: Inline and use async version everywhere
}
private static async Task<bool?> HasWriteUsagesAsync(Solution solution, ISymbol symbol)
{
var references = await SymbolFinder.FindReferencesAsync(symbol, solution);
var operationsReferencingAsync = references.SelectMany(r => r.Locations).Select(async l => {
var semanticModel = await l.Document.GetSemanticModelAsync();
var syntaxRoot = await l.Document.GetSyntaxRootAsync();
var syntaxNode = syntaxRoot.FindNode(l.Location.SourceSpan);
return semanticModel.GetOperation(syntaxNode);
});
var operationsReferencing = await Task.WhenAll(operationsReferencingAsync);
if (operationsReferencing.Any(IsWriteUsage)) return true;
if (symbol.GetResultantVisibility() == SymbolVisibility.Public) return null;
return false;
}
private static bool IsWriteUsage(IOperation operation)
{
return operation.Parent is IAssignmentOperation a && a.Target == operation
|| operation is IParameterReferenceOperation pro && pro.Parameter.RefKind == RefKind.Ref;
}
}
}<file_sep>/ICSharpCode.CodeConverter/CSharp/ByRefParameterVisitor.cs
๏ปฟusing System;
using System.Collections.Generic;
using System.Text;
using ICSharpCode.CodeConverter.Util;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using VBSyntax = Microsoft.CodeAnalysis.VisualBasic.Syntax;
using VBasic = Microsoft.CodeAnalysis.VisualBasic;
using Microsoft.CodeAnalysis.CSharp;
using System.Linq;
namespace ICSharpCode.CodeConverter.CSharp
{
public class ByRefParameterVisitor : VBasic.VisualBasicSyntaxVisitor<SyntaxList<StatementSyntax>>
{
private readonly VBasic.VisualBasicSyntaxVisitor<SyntaxList<StatementSyntax>> _wrappedVisitor;
private readonly AdditionalLocals _additionalLocals;
private readonly SemanticModel _semanticModel;
private readonly HashSet<string> _generatedNames;
public ByRefParameterVisitor(VBasic.VisualBasicSyntaxVisitor<SyntaxList<StatementSyntax>> wrappedVisitor, AdditionalLocals additionalLocals,
SemanticModel semanticModel, HashSet<string> generatedNames)
{
_wrappedVisitor = wrappedVisitor;
_additionalLocals = additionalLocals;
_semanticModel = semanticModel;
_generatedNames = generatedNames;
}
public override SyntaxList<StatementSyntax> DefaultVisit(SyntaxNode node)
{
throw new NotImplementedException($"Conversion for {VBasic.VisualBasicExtensions.Kind(node)} not implemented, please report this issue")
.WithNodeInformation(node);
}
private SyntaxList<StatementSyntax> AddLocalVariables(VBasic.VisualBasicSyntaxNode node)
{
_additionalLocals.PushScope();
IEnumerable<SyntaxNode> csNodes;
List<StatementSyntax> additionalDeclarations;
try {
csNodes = CreateLocals(node, out additionalDeclarations);
} finally {
_additionalLocals.PopScope();
}
return SyntaxFactory.List(additionalDeclarations.Concat(csNodes));
}
private IEnumerable<SyntaxNode> CreateLocals(VBasic.VisualBasicSyntaxNode node, out List<StatementSyntax> additionalDeclarations)
{
IEnumerable<SyntaxNode> csNodes = _wrappedVisitor.Visit(node);
additionalDeclarations = new List<StatementSyntax>();
if (_additionalLocals.Count() > 0)
{
var newNames = new Dictionary<string, string>();
csNodes = csNodes.Select(csNode => csNode.ReplaceNodes(csNode.GetAnnotatedNodes(AdditionalLocals.Annotation),
(an, _) =>
{
var id = (an as IdentifierNameSyntax).Identifier.ValueText;
newNames[id] = NameGenerator.GetUniqueVariableNameInScope(_semanticModel, _generatedNames, node,
_additionalLocals[id].Prefix);
return SyntaxFactory.IdentifierName(newNames[id]);
})).ToList();
foreach (var additionalLocal in _additionalLocals)
{
var decl = CommonConversions.CreateVariableDeclarationAndAssignment(newNames[additionalLocal.Key],
additionalLocal.Value.Initializer, additionalLocal.Value.Type);
additionalDeclarations.Add(SyntaxFactory.LocalDeclarationStatement(decl));
}
}
return csNodes;
}
public override SyntaxList<StatementSyntax> VisitAddRemoveHandlerStatement(VBSyntax.AddRemoveHandlerStatementSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitAssignmentStatement(VBSyntax.AssignmentStatementSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitCallStatement(VBSyntax.CallStatementSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitContinueStatement(VBSyntax.ContinueStatementSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitDoLoopBlock(VBSyntax.DoLoopBlockSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitEraseStatement(VBSyntax.EraseStatementSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitErrorStatement(VBSyntax.ErrorStatementSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitExitStatement(VBSyntax.ExitStatementSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitExpressionStatement(VBSyntax.ExpressionStatementSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitForBlock(VBSyntax.ForBlockSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitForEachBlock(VBSyntax.ForEachBlockSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitGoToStatement(VBSyntax.GoToStatementSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitLabelStatement(VBSyntax.LabelStatementSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitLocalDeclarationStatement(VBSyntax.LocalDeclarationStatementSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitMultiLineIfBlock(VBSyntax.MultiLineIfBlockSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitOnErrorGoToStatement(VBSyntax.OnErrorGoToStatementSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitOnErrorResumeNextStatement(VBSyntax.OnErrorResumeNextStatementSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitPrintStatement(VBSyntax.PrintStatementSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitRaiseEventStatement(VBSyntax.RaiseEventStatementSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitReDimStatement(VBSyntax.ReDimStatementSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitResumeStatement(VBSyntax.ResumeStatementSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitReturnStatement(VBSyntax.ReturnStatementSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitSelectBlock(VBSyntax.SelectBlockSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitSingleLineIfStatement(VBSyntax.SingleLineIfStatementSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitStopOrEndStatement(VBSyntax.StopOrEndStatementSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitSyncLockBlock(VBSyntax.SyncLockBlockSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitThrowStatement(VBSyntax.ThrowStatementSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitTryBlock(VBSyntax.TryBlockSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitUsingBlock(VBSyntax.UsingBlockSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitWhileBlock(VBSyntax.WhileBlockSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitWithBlock(VBSyntax.WithBlockSyntax node) => AddLocalVariables(node);
public override SyntaxList<StatementSyntax> VisitYieldStatement(VBSyntax.YieldStatementSyntax node) => AddLocalVariables(node);
}
}
| b10015fe01c7b0a46a07bf4bb97559e9dbf3a244 | [
"C#"
] | 2 | C# | GrahamTheCoder/CodeConverter | 3ffc597ffdce991ef0cccf01bd7c884b9d337d6a | a8718adf5bb9fd88c06ee68ad083058b8ce39ddc |
refs/heads/master | <file_sep>var gulp = require('gulp'),
clean = require('gulp-clean'),
livereload = require('gulp-livereload'),
runsequence = require('run-sequence'),
env = require('gulp-env');
require('./gulp')(['scripts', 'vendor', 'server-mock', 'server-proxy', 'test', 'resources']);
gulp.task('set-development-env', function() {
env({
vars: {
GULP_ENV: "debug"
}
})
});
gulp.task('set-production-env', function() {
env({
vars: {
GULP_ENV: "production"
}
})
})
gulp.task('watch', function() {
livereload.listen();
gulp.watch(['app/less/**/*.*'], ['resources']);
gulp.watch(['app/js/**/*.*'], ['scripts']);
//gulp.watch('dist/public/**/*.*').on('change', livereload.changed);
});
gulp.task('dev-proxy', function(callback) {
runsequence('dev', 'server-proxy', 'watch', callback);
});
gulp.task('dev-mock', function(callback) {
runsequence('dev', 'server-mock', 'watch', callback);
});
gulp.task('clean', function() {
return gulp.src(['dist'], {
read: false
})
.pipe(clean());
});
gulp.task('dist', function(callback) {
runsequence('set-production-env', 'clean', ['vendor', 'scripts', 'resources'], callback);
});
gulp.task('dev', function(callback) {
runsequence('set-development-env', 'clean', ['vendor', 'scripts', 'resources'], callback);
});
gulp.task('default', ['dist']);<file_sep>"use strict";
var React = require('react'),
AppActionCreators = require('../../actions/AppActionCreators');
var ModalHeader = React.createClass({
displayName: "ModalHeader",
componentDidMount: function() {
setTimeout(function() {
this.refs.header.getDOMNode().focus();
}.bind(this), 0);
},
render: function() {
var title = (this.props.title) ? <strong>{this.props.title} - </strong> : null;
return (
<div className="modal-header" tabIndex="1" ref="header">
<button type="button" className="close" onClick={this._onCloseClick}
aria-hidden="true" id="modal-close-button">×
</button>
<h3>
{title}{this.props.name}
</h3>
</div>
);
},
_onCloseClick: function() {
AppActionCreators.navigateTo('vessel');
}
});
module.exports = ModalHeader;<file_sep>## Synopsis
The project deliverable is client for big data analytics backend. It is a part of the innovation project.
The brand E.V.A stands for Extraintelligent Verification Assistant.
## Motivation
The main target is to make impression during presentation of the project.
Big data backend functionality supposed to be partitially mocked up.
## Installation
For development purposes:
* `npm install`
* `gulp dev-mock`
* `localhost:8083`
Once started gulp will watch source files and rebuild / referesh when a change takes place.
## API Reference
## Contributors
The project Jira issue tracker can be accessed on [Follow Jira!](http://jira.mc.local/secure/RapidBoard.jspa?rapidView=250)
## TO DO
switchboards generators
<file_sep>"use strict";
var AppDispatcher = require('../dispatcher/AppDispatcher'),
ActionTypes = require('../constants/ActionTypes'),
EventEmitter = require('events').EventEmitter,
assign = require('object-assign'),
CHANGE_EVENT = 'change';
var _dimensions = {width: 0, height: 0};
var _listener;
var WindowStore = assign({}, EventEmitter.prototype, {
getDimensions: function() {
return _dimensions;
},
emitChange: function() {
this.emit(CHANGE_EVENT);
},
addChangeListener: function(callback) {
this.on(CHANGE_EVENT, callback);
if (!_listener) {
console.log("adding window listener");
window.addEventListener('resize', () => {
this._updateDimensions();
this.emitChange();
});
_listener = true;
}
},
removeChangeListener: function(callback) {
this.removeListener(CHANGE_EVENT, callback);
},
_updateDimensions: function() {
_dimensions.width =
window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth;
_dimensions.height =
window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight;
},
dispatcherIndex: AppDispatcher.register(function(payload) {
var action = payload.action;
switch(action.type) {
default:
//no op
}
})
});
module.exports = WindowStore;<file_sep>"use strict";
var React = require('react');
var Router = require('react-router');
var RouteHandler = Router.RouteHandler;
var Tab = require('./Tab');
var Kafka = React.createClass({
displayName: 'Kafka',
render: function() {
return (
<div>
<ul className="nav nav-pills nav-stacked sub-nav">
<Tab to="kafkainfo" params={{clusterId: "internalCluster"}}><strong>Internal cluster</strong></Tab>
<Tab to="kafkainfo" params={{clusterId: "externalCluster"}}><strong>External cluster</strong></Tab>
</ul>
<div className="panel-body">
<div className="row">
<div className="col-md-2">
</div>
<RouteHandler />
</div>
</div>
</div>
);
}
});
module.exports = Kafka;<file_sep>"use strict";
var AppDispatcher = require('../dispatcher/AppDispatcher'),
ActionTypes = require('../constants/ActionTypes'),
EventEmitter = require('events').EventEmitter,
assign = require('object-assign'),
CHANGE_EVENT = 'change',
_ = require('underscore');
var _applicationVersion = "",
_displayAlertMessageDialog = false,
_alert = {};
var AppStore = assign({}, EventEmitter.prototype, {
getApplicationVersion: function() {
return _applicationVersion;
},
getOpenAlertMessageDialog: function() {
return _displayAlertMessageDialog;
},
getAlert: function() {
return _alert;
},
emitChange: function() {
this.emit(CHANGE_EVENT);
},
addChangeListener: function(callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener: function(callback) {
this.removeListener(CHANGE_EVENT, callback);
},
dispatcherIndex: AppDispatcher.register(function(payload) {
var action = payload.action;
switch (action.type) {
case ActionTypes.APPLICATION_VERSION_RECEIVED:
_applicationVersion = action.response.version;
AppStore.emit(CHANGE_EVENT);
break;
case ActionTypes.MESSAGER_RECEIVED:
_alert = action.response.alert;
if (_alert.message) {
_displayAlertMessageDialog = true;
AppStore.emitChange(CHANGE_EVENT);
}
if (!_alert.message && _displayAlertMessageDialog) {
_displayAlertMessageDialog = false;
AppStore.emitChange(CHANGE_EVENT);
}
break;
default:
// no op
}
})
});
module.exports = AppStore;<file_sep>"use strict";
var React = require('react'),
AppActionCreators = require('../actions/AppActionCreators'),
AppStore = require('../stores/AppStore');
var AlertMessageDialog = React.createClass({
displayName: "AlertMessageDialog",
getInitialState: function() {
return {
alert: AppStore.getAlert()
};
},
render: function() {
return (
<div>
<div className="modal fade in" style={{display: "block"}} tabIndex="-1" role="dialog">
<div className="modal-dialog" onClick={this._onDialogClick}>
<div className="modal-content">
<div class="message">
<div className="modal-header">
<h3>{this.state.alert.title}</h3>
</div>
<div className="modal-body">
<div>{this.state.alert.message}</div>
</div>
<div className="modal-footer">
<button className="btn btn-info" onClick={this._onGo}>
Continue test
</button>
</div>
</div>
</div>
</div>
</div>
<div className="modal-backdrop fade in" />
</div>
);
},
handleHotkey: function(evt) {
if (evt.keyCode === KEYCODE_ESC) {
AppActionCreators.handleAlertMessageDialogClose();
}
},
_onDialogClick: function(evt) {
evt.stopPropagation();
},
_onGo: function(evt) {
AppActionCreators.acknowledgeAlert();
}
});
module.exports = AlertMessageDialog;<file_sep>"use strict";
var React = require('react');
var YamerEmbedded = React.createClass({
displayName: 'YammerFeed',
componentDidMount: function() {
yam.connect.embedFeed(
{ container: '#embedded-feed',
network: 'dnvgl.com',
feedType: 'group'//, // can be 'group', 'topic', or 'user'
// feedId: '119112', // feed ID from the instructions above
// config: {
// defaultGroupId: 119112 // specify default group id to post to
// }
}
);
},
render: function() {
return (
<div className="yammer-feed" id="embedded-feed">
</div>
);
}
});
module.exports = YamerEmbedded;<file_sep>"use strict";
var React = require('react'),
router = require('./router');
router.run(function(Handler) {
React.render(<Handler />, document.getElementById("react-view"));
});<file_sep>"use strict";
var EvaStatusServerActionCreators = require('../actions/EvaStatusServerActionCreators');
var EvaStatusAPI = {
requestStatus: function() {
$.get('/status', function(response) {
EvaStatusServerActionCreators.handleEvaStatusSuccess(response);
});
}
};
module.exports = EvaStatusAPI;<file_sep>"use strict";
var NavigationServerActionCreators = require('../actions/NavigationServerActionCreators');
var NavigationAPI = {
requestNavigation: function() {
$.get('/navigation', function(response) {
NavigationServerActionCreators.handleNavigationSuccess(response);
});
}
};
module.exports = NavigationAPI;<file_sep>"use strict";
var React = require('react'),
ConnectionErrorActionCreators = require('../actions/ConnectionErrorActionCreators');
var ErrorModal = React.createClass({
displayName: "ErrorModal",
componentDidMount: function() {
$(".modal-backdrop").addClass("error-modal-backdrop");
},
componentWillUnmount: function() {
$(".modal-backdrop").removeClass("error-modal-backdrop");
},
render: function() {
return (
<div className="modal fade" tabIndex="-1" role="dialog" id="errorModal">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<h3>Error</h3>
</div>
<div className="modal-body">
<div>
Lost connection to backend
</div>
</div>
</div>
</div>
</div>
);
}
});
var modalInstance;
module.exports = {
setError: function() {
if (!modalInstance) {
ConnectionErrorActionCreators.lostConnection();
modalInstance = React.createElement(ErrorModal, {});
React.render(modalInstance, document.getElementById('react-modal'));
$("#errorModal").modal({
backdrop: "static",
keyboard: false
});
document.body.classList.add('hide-scrollbars');
}
},
resetError: function() {
if (modalInstance) {
ConnectionErrorActionCreators.backOnline();
$("#errorModal").modal('hide');
React.unmountComponentAtNode(document.getElementById('react-modal'));
modalInstance = undefined;
document.body.classList.remove('hide-scrollbars');
}
}
};<file_sep>"use strict";
var AppDispatcher = require('../dispatcher/AppDispatcher'),
ActionTypes = require('../constants/ActionTypes'),
EventEmitter = require('events').EventEmitter,
assign = require('object-assign'),
CHANGE_EVENT = 'change',
viewDescriptor = require('../config/view.conf.js'),
d3DataConverter = require('../services/D3ChartsDataConverter');
var _signalsData = {};
var _requestReferesh = false;
var _offline = false;
var getMinMax = function(data) {
var minX1 = [], maxX1 = [], minY1 = [], maxY1 = [];
for (var i = 0; i < data.length; i++) {
var currArray = data[i].values;
minX1.push(d3.min(currArray, function(d) { return d["x"]; }));
maxX1.push(d3.max(currArray, function(d) { return d["x"]; }));
minY1.push(d3.min(currArray, function(d) { return d["y"]; }));
maxY1.push(d3.max(currArray, function(d) { return d["y"]; }));
};
return {minX: d3.min(minX1), maxX: d3.max(maxX1), minY: d3.min(minY1), maxY: d3.max(maxY1)};
};
var convertValue = function(value, seriesLabel) {
var converted = {};
converted.x = new Date(value.time);
converted.y = value[seriesLabel];
return converted;
};
var convertSignalData = function(data) {
var retVal = {data: [], minMax: {}};
var seriesLabel = "";
var oneSeries = {label: seriesLabel, values: []};
var firstElement = data[0];
for (var key in firstElement) {
if (firstElement.hasOwnProperty(key) && key !== "time") {
var seriesLabel = key;
oneSeries.label = seriesLabel;
break;
}
}
for (var i = 0; i < data.length; i++) {
var entry = {};
entry.x = new Date(data[i].time);
entry.y = data[i][seriesLabel];
oneSeries.values.push(entry);
};
retVal.data.push(oneSeries);
retVal.minMax = getMinMax(retVal.data);
return retVal;
};
var pushNewValue = function(signalId, value) {
if (_signalsData[signalId] === undefined) {
return;
}
var converted = convertValue(value, _signalsData[signalId].data[0].label);
_signalsData[signalId].data[0].values.shift();
_signalsData[signalId].data[0].values.push(converted);
_signalsData[signalId].minMax = getMinMax(_signalsData[signalId].data);
}
var SignalStore = assign({}, EventEmitter.prototype, {
getSignalData: function(signalId) {
if (_signalsData[signalId] === undefined) {
return {
data: [{label: "", values: [{x: 0, y: 0}]}],
minMax: {minX: 0, maxX: 0, minY: 0, maxY: 0}
};
}
return _signalsData[signalId];
},
doReferesh: function() {
return _requestReferesh;
},
isOffline: function() {
return _offline;
},
emitChange: function() {
this.emit(CHANGE_EVENT);
},
addChangeListener: function(callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener: function(callback) {
this.removeListener(CHANGE_EVENT, callback);
},
dispatcherIndex: AppDispatcher.register(function(payload) {
var action = payload.action;
switch(action.type) {
case ActionTypes.REQUEST_SIGNAL_DATA_SUCCESS:
var signalId = action.signalId;
_signalsData[signalId] = convertSignalData(action.response);
_requestReferesh = false;
_offline = false;
SignalStore.emit(CHANGE_EVENT);
break;
case ActionTypes.SIGNAL_VALUE_RECEIVED:
pushNewValue(action.signalId, action.data);
SignalStore.emit(CHANGE_EVENT);
break;
case ActionTypes.BACK_ONLINE:
_requestReferesh = true;
SignalStore.emit(CHANGE_EVENT);
break;
case ActionTypes.LOST_CONNECTION:
_offline = true;
SignalStore.emitChange(CHANGE_EVENT);
break;
default:
//no op
break;
}
})
});
module.exports = SignalStore;<file_sep>"use strict";
var mockedJSON = require('./mockedJSON');
module.exports = function(original_array, step_size, signalId){
var ptr = 120;
var listeners = [];
var _signalId = signalId;
var regenerate_time_stamps = function(arr, step_size) {
var ret_val = arr;
var end_date = new Date();
var time_stamp_ms = end_date.valueOf() - step_size * ptr;
for (var i = 0; i < ptr; i++) {
ret_val[i].time = new Date(time_stamp_ms);
time_stamp_ms += step_size;
};
return ret_val;
};
var updated = regenerate_time_stamps(original_array, step_size);
var series_1m = updated.slice(0, 120);
setInterval(function() {
series_1m.shift();
var new_value = updated[ptr];
new_value.time = new Date();
series_1m.push(new_value);
if (ptr > original_array.length - 2) {
ptr = 0;
return;
}
ptr++;
for (var i = 0; i < listeners.length; i++) {
listeners[i](new_value);
};
}, step_size);
return {
getSeries_1m: function() {
return series_1m;
},
addListener: function(callback) {
listeners.push(callback);
return callback;
},
removeListener: function(callback) {
var index = listeners.indexOf(callback);
if (index > -1) {
listeners.splice(index, 1)
}
},
getSignalId: function() {
return signalId;
}
}
}<file_sep>describe('State header', function () {
var scope, serverConnectStub, testsService, observer, hotkeys;
beforeEach(function (_session_, _$window_) {
serverConnectStub = {
observe: function (key, o) {
if (key === 'status') {
observer = o;
}
}
};
testsService = {
};
hotkeys = {
add: function () {},
bindTo: function (scope) { return hotkeys; }
};
module("app");
inject(function ($rootScope, $controller) {
scope = $rootScope.$new();
var controller = $controller('StateHeaderCtrl', {$scope: scope, TestsService: testsService, ServerConnector: serverConnectStub, hotkeys: hotkeys});
});
});
it('Should switch buttons depending on service status', function () {
observer('idle');
expect(scope.isIdle()).toBe(true);
observer('running');
expect(scope.isRunning()).toBe(true);
});
});<file_sep>"use strict";
var express = require('express'),
http = require('http'),
config = require('../../config/server.js'),
socketServer = require('../../config/socketServer.js'),
livereload = require('connect-livereload'),
serverport = 8083;
var mockedJSON = require('../../config/mockedJSON');
var seriesProvider = require('../../config/seriesProvider');
var dataProviders = {
thr1: {
rpm: seriesProvider(mockedJSON.getThr1RPM(), 500, 1),
thrust: seriesProvider(mockedJSON.getThr1Thrust(), 500, 2)
}
}
var app = express(),
server = http.Server(app);
module.exports = function() {
// global controller
app.use(function(req,res,next) {
res.header('X-Frame-Options' , "GOFORIT");
next();
});
app.use(livereload({
port: 35729
}));
app.use(express.static('./dist/public/signature'));
socketServer.setSocketsUp(server, dataProviders);
config.drawRoutes(app, dataProviders);
server.listen(serverport, function() {
console.log('listening on *:' + serverport);
});
};<file_sep>describe('Test info', function() {
var scope, compile, compiledTemplate
var compileDirective = function(test) {
scope.test = test
var tpl = '<test-info test="test"/>'
compiledTemplate = compile(tpl)(scope)
scope.$digest()
}
beforeEach(module('app')) // Needed to load templates
beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope.$new()
compile = $compile
}))
it('Should at least contain some html', function() {
compileDirective({})
var rootElement = compiledTemplate.find('a')
expect(rootElement[0]).toBeDefined()
})
})<file_sep>"use strict";
var AppDispatcher = require('../dispatcher/AppDispatcher'),
ActionTypes = require('../constants/ActionTypes');
var MessagerServerActionCreators = {
handleMessagerReceived: function(response) {
AppDispatcher.handleServerAction({
type: ActionTypes.MESSAGER_RECEIVED,
response: response
});
AppDispatcher.handleServerAction({
type: ActionTypes.WEATHER_RECEIVED,
response: response.weather
});
AppDispatcher.handleServerAction({
type: ActionTypes.ENGINE_STATUS_RECEIVED,
response: response.engineStatus
});
}
};
module.exports = MessagerServerActionCreators;<file_sep>"use strict";
var KafkaInfoServerActionCreators = require('../actions/KafkaInfoServerActionCreators');
var KafkaInfoAPI = {
requestKafkaInfo: function() {
$.get('/kafka/info', function(response) {
KafkaInfoServerActionCreators.handleKafkaInfoSuccess(response);
});
},
requestStartStopProducing: function(topic, requestedState) {
console.log("requesting " + requestedState + " for topic " + topic);
var data = {
topic: topic,
requestedState: requestedState
};
$.post('/kafka/producers/control', data);
},
setProducedModules: function(cluster, producedModules) {
console.log("setting produced modules " + producedModules + " for cluster " + cluster);
var data = {
cluster: cluster,
modules: producedModules
};
$.post('/kafka/producers/control/modules', data);
},
requestThrottle: function(cluster, newValue) {
var throttle = parseInt(newValue);
console.log("setting throttle " + throttle + " for cluster " + cluster);
var data = {
cluster: cluster,
throttle: throttle
};
$.post('/kafka/producers/control/throttle', data);
}
};
module.exports = KafkaInfoAPI;<file_sep>describe('UserInputService', function() {
var create, open, provide, storedObserver
beforeEach(module("app"))
beforeEach(module(function($provide) {
open = jasmine.createSpy('open')
provide = $provide
$provide.value('$modal', {open: open});
$provide.value('TestsService', {getRunningTest: function() {return {}}});
serverConnectStub = {
observe: function(key, o) {
storedObserver = o
},
findTest: function() {
return {}
}
}
$provide.value('ServerConnector', serverConnectStub)
}));
beforeEach(inject(function ($injector) {
create = function() {
return $injector.get('userInputService');
};
}));
it('Can be instantiated', function() {
var cut = create()
expect(cut).toBeDefined()
expect(open).not.toHaveBeenCalled()
})
it('Will show modal if any test has status pending', function() {
var cut = create()
storedObserver({testKey: 'testKey', verificationKey:'verificationKey'})
expect(open).toHaveBeenCalled()
})
})<file_sep>"use strict";
var React = require('react'),
Router = require('react-router');
var Link = Router.Link,
State = Router.State;
var Tab = React.createClass({
displayName: "Tab",
mixins: [State],
render: function() {
var isActive = this.isActive(this.props.to, this.props.params, this.props.query),
activeClass = isActive ? 'active' : '';
return (
<li className={activeClass}>
<Link {...this.props} />
</li>
);
}
});
module.exports = Tab;<file_sep>describe('result icon', function() {
var scope, compile, compiledTemplate
var compileDirective = function(test) {
scope.test = test
var tpl = '<status-cell test="test"/>'
compiledTemplate = compile(tpl)(scope)
scope.$digest()
}
beforeEach(module("app"))
beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope.$new()
compile = $compile
}))
it('Should not display icons for empty statuses', function() {
compileDirective({status: 'waiting'})
var rootElement = compiledTemplate.find('img')
expect(rootElement[0]).toBeDefined()
})
it('Should display only one status element when running and failed', function() {
compileDirective({status: 'running', result: 'failed', progress: 45})
expect(compiledTemplate.length).toBe(1)
})
})<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>
<artifactId>standard</artifactId>
<groupId>com.marinecyb.cybersea.nbm</groupId>
<version>4.1.13-SNAPSHOT</version>
</parent>
<groupId>com.marinecyb.cybersea.nbm.standard</groupId>
<artifactId>signature-client</artifactId>
<name>CyberSea Signature - Client</name>
<build>
<resources>
<resource>
<directory>dist</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>com.github.eirslett</groupId>
<artifactId>frontend-maven-plugin</artifactId>
<version>0.0.23</version>
<executions>
<execution>
<id>install node and npm</id>
<goals>
<goal>install-node-and-npm</goal>
</goals>
<configuration>
<nodeVersion>v0.10.18</nodeVersion>
<npmVersion>1.3.8</npmVersion>
</configuration>
</execution>
<execution>
<id>npm install</id>
<goals>
<goal>npm</goal>
</goals>
</execution>
<execution>
<id>gulp build</id>
<goals>
<goal>gulp</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>2.6.1</version>
<configuration>
<filesets>
<!--fileset>
<directory>node_modules</directory>
</fileset-->
<fileset>
<directory>dist</directory>
</fileset>
</filesets>
</configuration>
</plugin>
</plugins>
</build>
</project>
<file_sep>"use strict";
var React = require('react'),
Chart = require('./Chart');
var CHART_HEIGHT = 275;
var Status = React.createClass({
displayName: "Status",
componentDidMount: function() {
},
componentWillUnmount: function() {
},
getInitialState: function() {
return {};
},
render: function() {
return (
<div>
<div className="row">
<div className="col-lg-6 col-md-12">
<Chart height={CHART_HEIGHT} label="RPM" signalId="1" />
</div>
<div className="col-lg-6 col-md-12">
<Chart height={CHART_HEIGHT} label="Temperature 1" signalId="3" />
</div>
</div>
<div className="row">
<div className="col-lg-6 col-md-12">
<Chart height={CHART_HEIGHT} label="Thrust" signalId="2" />
</div>
<div className="col-lg-6 col-md-12">
<Chart height={CHART_HEIGHT} label="Temperature 2" signalId="4" />
</div>
</div>
</div>
);
},
_onChange: function() {
if (this.isMounted()) {
}
}
});
module.exports = Status;
<file_sep>"use strict";
var AppDispatcher = require('../dispatcher/AppDispatcher'),
ActionTypes = require('../constants/ActionTypes');
var ConnectionErrorActionCreators = {
lostConnection: function() {
AppDispatcher.handleViewAction({
type: ActionTypes.LOST_CONNECTION
});
},
backOnline: function() {
AppDispatcher.handleViewAction({
type: ActionTypes.BACK_ONLINE
});
}
};
module.exports = ConnectionErrorActionCreators;<file_sep>"use strict";
var fs = require('fs'),
manualTestsData = fs.readFileSync("./dev/data/manualTests.json", "utf8"),
simulatorDiagnosticData = fs.readFileSync("./dev/data/simulatorDiagnostic.json", "utf8"),
automaticTestsData = fs.readFileSync("./dev/data/automaticTests.json", "utf8"),
reportsData = fs.readFileSync("./dev/data/reports.json", "utf8"),
connectedClientsData = fs.readFileSync("./dev/data/connectedClients.json", "utf8"),
customData = fs.readFileSync("./dev/data/custom.json", "utf8"),
kafkaData = fs.readFileSync("./dev/data/kafka.json", "utf8"),
navigationData = fs.readFileSync("./dev/data/navigation.json", "utf8"),
weatherDailyData = fs.readFileSync("./dev/data/daily-weather.json", "utf8"),
contactsData = fs.readFileSync("./dev/data/contacts.json", "utf8"),
thr1RPMData = fs.readFileSync("./dev/data/thr1_rpm.json", "utf8"),
thr1ThrustData = fs.readFileSync("./dev/data/thr1_thrust.json", "utf8"),
evaStatusData = fs.readFileSync("./dev/data/evaStatus.json", "utf8"),
manualTests = [],
automaticTests = [],
simulatorDiagnostic = {},
reports = [],
connectedClients = [],
custom = {},
kafkaInfo = {},
navigation = [],
weatherDaily = {},
contacts = {},
thr1RPM = [],
thr1Thrust = [],
evaStatus = {},
customDataWatchers = [],
simulatorDiagnosticWatchers = [],
reportsWatchers = [],
connectedClientsWatchers = [],
automaticTestsWatchers = [],
manualTestsWatchers = [],
kafkaInfoWatchers = [],
navigationWatchers = [],
weatherDailyWatchers = [],
contactsWatchers = [],
evaStatusWatchers = [];
try {
manualTests = JSON.parse(manualTestsData);
simulatorDiagnostic = JSON.parse(simulatorDiagnosticData);
automaticTests = JSON.parse(automaticTestsData);
reports = JSON.parse(reportsData);
connectedClients = JSON.parse(connectedClientsData);
custom = JSON.parse(customData);
kafkaInfo = JSON.parse(kafkaData);
navigation = JSON.parse(navigationData);
weatherDaily = JSON.parse(weatherDailyData);
contacts = JSON.parse(contactsData);
thr1RPM = JSON.parse(thr1RPMData);
thr1Thrust = JSON.parse(thr1ThrustData);
evaStatus = JSON.parse(evaStatusData);
} catch (e) {
console.error(e);
}
var watchTheFile = function(path, callback) {
fs.watch(path, function(event) {
if (event === 'change') {
fs.readFile(path, 'utf8', function(err, data) {
try {
var newValue = JSON.parse(data);
callback(newValue);
} catch (e) {
console.error(e);
}
});
}
});
};
var notifyWatchers = function(watchers) {
return function(newValue) {
watchers.forEach(function(callback) {
callback(newValue);
});
};
};
watchTheFile("./dev/data/manualTests.json", notifyWatchers(manualTestsWatchers));
watchTheFile("./dev/data/automaticTests.json", notifyWatchers(automaticTestsWatchers));
watchTheFile("./dev/data/simulatorDiagnostic.json", notifyWatchers(simulatorDiagnosticWatchers));
watchTheFile("./dev/data/reports.json", "reports", notifyWatchers(reportsWatchers));
watchTheFile("./dev/data/connectedClients.json", notifyWatchers(connectedClientsWatchers));
watchTheFile("./dev/data/custom.json", notifyWatchers(customDataWatchers));
watchTheFile("./dev/data/kafka.json", notifyWatchers(kafkaInfoWatchers));
watchTheFile("./dev/data/navigation.json", notifyWatchers(navigationWatchers));
watchTheFile("./dev/data/daily-weather.json", notifyWatchers(weatherDailyWatchers));
watchTheFile("./dev/data/contacts.json", notifyWatchers(contactsWatchers));
watchTheFile("./dev/data/evaStatus.json", notifyWatchers(evaStatusWatchers));
module.exports = {
getCustomData: function() {
return custom;
},
getSimulatorDiagnostic: function() {
return simulatorDiagnostic;
},
getReports: function() {
return reports;
},
getConnectedClients: function() {
return connectedClients;
},
getAutomaticTests: function() {
return automaticTests;
},
getManualTests: function() {
return manualTests;
},
getRunningTest: function() {
return custom.runningTest;
},
getWeather: function() {
return custom.weather;
},
getEngineStatus: function() {
return custom.engineStatus;
},
getExecutionStatus: function() {
return custom.executionStatus;
},
getKafkaInfo: function() {
return kafkaInfo;
},
getNavigation: function() {
return navigation;
},
getWeatherDaily: function() {
return weatherDaily;
},
getContacts: function() {
return contacts;
},
getThr1RPM: function() {
console.log(thr1RPM);
return thr1RPM.vessel_data[0]['THR1.RpmAct [rpm]'];
},
getThr1Thrust: function() {
return thr1Thrust.vessel_data[0]["THR1.ThrustAct [N]"];
},
getEvaStatus: function() {
return evaStatus;
},
watchCustomData: function(callback) {
customDataWatchers.push(callback);
},
watchSimulatorDiagnostic: function(callback) {
simulatorDiagnosticWatchers.push(callback);
},
watchReports: function(callback) {
reportsWatchers.push(callback);
},
watchConnectedClients: function(callback) {
connectedClientsWatchers.push(callback);
},
watchAutomaticTests: function(callback) {
automaticTestsWatchers.push(callback);
},
watchManualTests: function(callback) {
manualTestsWatchers.push(callback);
},
watchKafkaInfo: function(callback) {
kafkaInfoWatchers.push(callback);
},
watchNavigation: function(callback) {
navigationWatchers.push(callback);
},
watchWeatherDaily: function(callback) {
weatherDailyWatchers.push(callback);
},
watchContacts: function(callback) {
contactsWatchers.push(callback);
},
watchEvaStatus: function(callback) {
evaStatusWatchers.push(callback);
}
};<file_sep>var gulp = require('gulp'),
browserify = require('browserify'),
watchify = require('watchify'),
source = require('vinyl-source-stream'),
buffer = require('vinyl-buffer'),
gutil = require('gulp-util'),
sourcemaps = require('gulp-sourcemaps'),
assign = require('object-assign');
var customOpts = {
entries: ['./app/js/app.js'],
transform: ['reactify'],
extensions: ['.jsx'],
debug: true
};
var opts = assign({}, watchify.args, customOpts);
var b = process.env.GULP_ENV === 'debug' ? watchify(browserify(opts)) : browserify(opts);
b.on('log', gutil.log);
module.exports = function() {
var livereload = process.env.GULP_ENV === 'debug' ? require('gulp-livereload') : require('gulp-empty');
b.bundle()
.on('error', gutil.log.bind(gutil, 'Browserify error'))
.pipe(source('app.js'))
.pipe(buffer())
.pipe(sourcemaps.init({
loadMaps: true
}))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./dist/public/signature/js/'))
.pipe(livereload());
};<file_sep>"use strict";
var AppDispatcher = require('../dispatcher/AppDispatcher'),
ActionTypes = require('../constants/ActionTypes'),
EventEmitter = require('events').EventEmitter,
assign = require('object-assign'),
CHANGE_EVENT = 'change';
var _contactsData = {};
var ContactsStore = assign({}, EventEmitter.prototype, {
getContactsData: function() {
return _contactsData;
},
emitChange: function() {
this.emit(CHANGE_EVENT);
},
addChangeListener: function(callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener: function(callback) {
this.removeListener(CHANGE_EVENT, callback);
},
dispatcherIndex: AppDispatcher.register(function(payload) {
var action = payload.action;
switch(action.type) {
case ActionTypes.REQUEST_CONTACTS_DATA_SUCCESS:
_contactsData = action.response;
ContactsStore.emit(CHANGE_EVENT);
break;
default:
//no op
}
})
});
module.exports = ContactsStore;<file_sep>"use strict";
var React = require('react'),
Router = require('react-router'),
Kafka = require('./components/Kafka'),
KafkaInfo = require('./components/KafkaInfo'),
Vessel = require('./components/Vessel'),
App = require('./components/App'),
Charts = require('./components/Charts'),
ThrusterInfo = require('./components/thruster/ThrusterInfo'),
Status = require('./components/thruster/Status'),
Contacts = require('./components/thruster/Contacts'),
Documents = require('./components/thruster/Documents');
var Route = Router.Route,
Redirect = Router.Redirect,
DefaultRoute = Router.DefaultRoute;
var routes = (
<Route name="app" path="/" handler={App}>
<Route name="vessel" handler={Vessel}>
<Route name="thruster" path="/vessel/thruster/:thrusterId" handler={ThrusterInfo}>
<DefaultRoute name="status" handler={Status} />
<Route name="contacts" path="contacts" handler={Contacts} />
<Route name="documents" path="documents" handler={Documents} />
</Route>
</Route>
<Route name="kafka" handler={Kafka}>
<Route name="kafkainfo" path="/kafka/:clusterId" handler={KafkaInfo} />
<Redirect from="/kafka" to="/kafka/internalCluster" />
</Route>
<Route name="charts" handler={Charts} />
<Redirect from="/" to="vessel" />
</Route>
);
module.exports = routes;<file_sep>"use strict";
var React = require('react'),
KEYCODE_ESC = 27,
VesselStore = require('../../stores/VesselStore'),
hotkey = require('react-hotkey'),
Header = require('./Header'),
Footer = require('./Footer'),
Metadata = require('./Metadata'),
Status = require('./Status'),
AppActionCreators = require('../../actions/AppActionCreators'),
Tab = require('../Tab');
var Router = require('react-router');
var RouteHandler = Router.RouteHandler;
var ThrusterInfo = React.createClass({
displayName: "ThrusterInfo",
mixins: [hotkey.Mixin('handleHotkey')],
contextTypes: {
router: React.PropTypes.func
},
componentWillMount: function() {
document.body.classList.add('hide-scrollbars');
},
componentDidMount: function() {
var thrusterId = this.context.router.getCurrentParams().thrusterId;
VesselStore.addChangeListener(this._onChange);
},
componentWillUnmount: function() {
VesselStore.removeChangeListener(this._onChange);
document.body.classList.remove('hide-scrollbars');
},
getInitialState: function() {
var thrusterId = this.context.router.getCurrentParams().thrusterId;
return {
thruster: VesselStore.getThruster(thrusterId)
};
},
render: function() {
var thruster = this.state.thruster;
var thrusterId = this.context.router.getCurrentParams().thrusterId;
return (
<div onClick={this._onClick}>
<div className="modal fade in" style={{display: "block"}} tabIndex="-1" role="dialog">
<div className="modal-dialog thruster-info" onClick={this._onModalDialogClick}>
<div className="modal-content">
<Header
title="Thruster"
name={thrusterId} tabIndex="1"/>
<div className="modal-body">
<ul className="nav nav-tabs modal-nav">
<Tab to="status" params={{"thrusterId": thrusterId}}>Status</Tab>
<Tab to="contacts" params={{"thrusterId": thrusterId}}>Contacts</Tab>
<Tab to="documents" params={{"thrusterId": thrusterId}}>Documents</Tab>
</ul>
<Metadata />
<RouteHandler />
</div>
</div>
</div>
</div>
<div className="modal-backdrop fade in" />
</div>
);
},
handleHotkey: function(evt) {
if (evt.keyCode === KEYCODE_ESC) {
AppActionCreators.navigateTo('vessel');
}
},
_onClick: function() {
AppActionCreators.navigateTo('vessel');
},
_onModalDialogClick: function(evt) {
evt.stopPropagation();
},
_onChange: function() {
var thrusterId = this.context.router.getCurrentParams().thrusterId;
if (this.isMounted()) {
this.setState({
thruster: VesselStore.getThruster(thrusterId)
});
}
}
});
module.exports = ThrusterInfo;<file_sep>describe('UserMessageService', function() {
var create, open, provide, observer
beforeEach(module("app"))
beforeEach(module(function($provide) {
open = jasmine.createSpy('open')
provide = $provide
$provide.value('$modal', {open: open})
serverConnectStub = {
observe: function(key, o) {
observer = o
}
}
$provide.value('ServerConnector', serverConnectStub)
}));
beforeEach(inject(function ($injector) {
create = function() {
return $injector.get('userMessageService');
};
}));
it('Can be instantiated', function() {
var cut = create()
expect(cut).toBeDefined()
expect(open).not.toHaveBeenCalled()
})
it('Will show popup if there are messages', function() {
var cut = create()
observer({message: 'Warning!'})
expect(open).toHaveBeenCalled()
})
it('Will not popup if there are no messages', function() {
var cut = create()
observer({})
expect(open).not.toHaveBeenCalled()
})
})<file_sep>"use strict";
var React = require('react'),
WindowStore = require('../../stores/WindowStore'),
SignalStore = require('../../stores/SignalStore'),
ChartActionCreators = require('../../actions/ChartActionCreators');
var ReactD3 = require('react-d3-components');
var LineChart = ReactD3.LineChart;
var MARGINS = {top: 10, bottom: 50, left: 50, right: 10}
var Chart = React.createClass({
displayName: "Chart",
componentDidMount: function() {
WindowStore.addChangeListener(this._onChange);
SignalStore.addChangeListener(this._onChange);
ChartActionCreators.requestLatestSignalData(this.props.signalId);
ChartActionCreators.openSignalSocket(this.props.signalId);
this.setState({width: React.findDOMNode(this).offsetWidth});
},
componentWillUnmount: function() {
ChartActionCreators.closeSignalSocket(this.props.signalId);
WindowStore.removeChangeListener(this._onChange);
SignalStore.removeChangeListener(this._onChange);
},
getInitialState: function() {
return {
width: 120,
signalData: SignalStore.getSignalData(this.props.signalId)
}
},
render: function() {
var xScale = d3.time.scale().domain([this.state.signalData.minMax.minX, this.state.signalData.minMax.maxX]).range([0, this.state.width - 70]);
return (
<LineChart
data={this.state.signalData.data}
width={this.state.width}
height={this.props.height}
margin={{top: MARGINS.top, bottom: MARGINS.bottom, left: MARGINS.left, right: MARGINS.right}}
xScale={xScale}
xAxis={{tickValues: xScale.ticks(d3.time.seconds, 10), tickFormat: d3.time.format("%H:%M:%S"), zero: this.props.height - 60}}
yAxis={{label: this.props.label}} />
);
},
_onChange: function() {
if (this.isMounted()) {
if (SignalStore.doReferesh()) {
ChartActionCreators.requestLatestSignalData(this.props.signalId);
}
if (!SignalStore.isOffline()) {
this.setState({
width: React.findDOMNode(this).offsetWidth,
signalData: SignalStore.getSignalData(this.props.signalId)
});
}
}
}
});
module.exports = Chart;<file_sep>"use strict";
var WebSocketFactory = require('./websocket'),
MessagerServerActionCreators = require('../actions/MessagerServerActionCreators');
var _messagerSocket = WebSocketFactory.create('messager');
var _subscription;
module.exports = {
openSocket: function() {
_messagerSocket.open();
_subscription = _messagerSocket.subscribe('messager', MessagerServerActionCreators.handleMessagerReceived);
},
closeSocket: function() {
_messagerSocket.unsubscribe(_subscription);
_messagerSocket.close();
}
};<file_sep>describe('result icon', function() {
var scope, compile, compiledTemplate
var compileDirective = function(test) {
scope.test = test
var tpl = '<result-icon test="test"/>'
compiledTemplate = compile(tpl)(scope)
scope.$digest()
}
beforeEach(module("app"))
beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope.$new()
compile = $compile
}))
it('Should not display icons for empty statuses', function() {
compileDirective({})
var rootElement = compiledTemplate.find('img')
expect(rootElement[0]).toBeDefined()
expect(rootElement.hasClass('ng-hide')).toBeTruthy()
expect(rootElement.attr('ng-src')).toContain('failed')
scope.test.result = 'passed'
scope.$digest()
expect(rootElement.hasClass('ng-hide')).toBeFalsy()
expect(rootElement.attr('ng-src')).toContain('passed')
})
})<file_sep>"use strict";
module.exports = {
create: function(path) {
var websocket,
watchers = [],
echoID,
reconnect = true;
var notify = function(message) {
if (message === undefined || message.header === undefined) {
console.log("received message is not in a proper format: " + message);
return;
}
watchers.forEach(function(watcher) {
if (watcher.event === message.header.event) {
watcher.callback(message.data);
}
});
};
var startEcho = function(errorHandler) {
if (websocket === undefined || websocket.readyState === WebSocket.CLOSED) {
console.log("WebSocket cannot start echoing for it is disonnected");
return;
}
echoID = setInterval(function() {
try {
if (websocket === undefined || websocket.readyState !== WebSocket.OPEN) {
throw new Error('WebSocket is not connected');
}
websocket.send("echo");
if (errorHandler) {
errorHandler.resetError();
}
} catch (err) {
if (errorHandler) {
errorHandler.setError();
}
throw err;
}
}, 1000);
};
var openSocket = function() {
if (websocket !== undefined && websocket.readyState !== WebSocket.CLOSED) {
console.log("WebSocket is already opened");
return;
}
var url = "ws://" + $(location).attr('host') + "/" + path;
websocket = new WebSocket(url);
websocket.onopen = function() {
console.log("WebSocket is connected to " + url);
};
websocket.onmessage = function(event) {
if (event.data === "echo") {
return;
}
try {
var message = JSON.parse(event.data);
notify(message);
} catch (e) {
console.log(e);
}
};
websocket.onclose = function() {
if (reconnect) {
setTimeout(function() {
openSocket();
}, 1000);
}
};
};
return {
open: openSocket,
echo: startEcho,
subscribe: function(event, callback) {
var subscription = {
"event": event,
"callback": callback
};
watchers.push(subscription);
console.log("subscribing to " + subscription.event);
return subscription;
},
unsubscribe: function(subscription) {
var index = watchers.indexOf(subscription);
console.log("unsubscribing from " + subscription.event);
if (index < 0) {
throw ("wtf could not find socket on receive subscription");
}
watchers.splice(index, 1);
},
close: function() {
console.log("WebSocket /" + path + " has been closed");
reconnect = false;
clearInterval(echoID);
websocket.close();
}
};
}
};<file_sep>"use strict";
var React = require('react'),
EvaStatusStore = require('../stores/EvaStatusStore'),
EventsListActionCreators = require('../actions/EventsListActionCreators'),
_ = require('underscore');
var Event = React.createClass({
displayName: 'Event',
render: function() {
var type = "list-group-item";
switch(this.props.event.event_type_id) {
case 1:
type += " list-group-item-success";
break;
case 2:
type += " list-group-item-warning";
break;
case 3:
type += " list-group-item-danger";
break;
default:
//no op
}
return (
<li className={type} onClick={this._onClick}>
<span>{this.props.event.time}</span>
<span> </span>
<span>{this.props.event.description}</span>
</li>
);
},
_onClick: function() {
alert(this.props.event.time + '\n' + this.props.event.description);
}
});
var EventsList = React.createClass({
displayName: 'EventsList',
getInitialState: function() {
return EvaStatusStore.getStatus();
},
componentDidMount: function() {
EvaStatusStore.addChangeListener(this._onChange);
EventsListActionCreators.startEvaStatusRequest();
},
componentWillUnmount: function() {
EvaStatusStore.removeChangeListener(this._onChange);
EventsListActionCreators.stopEvaStatusRequest();
},
render: function() {
var sortedEvents = _.sortBy(this.state.events, function(oneEvent) {
return oneEvent.time;
}).reverse();
var events = <li className="list-group-item" />
events = sortedEvents.map(function(one, index) {
return (<Event key={index} event={one} />);
});
return (
<div id="footer">
<div className="navbar navbar-fixed-bottom">
<div className="events-list">
<ul className="list-group">
{events}
</ul>
</div>
</div>
</div>
);
},
_onChange: function() {
var state = EvaStatusStore.getStatus();
this.setState(state);
console.log(state);
}
});
module.exports = EventsList;<file_sep>"use strict";
module.exports = (function() {
return {
componentWillMount: function() {
console.log('componentWillMount');
this.intervals = [];
},
setInterval: function() {
console.log('setInterval');
this.intervals.push(setInterval.apply(null, arguments));
},
componentWillUnmount: function() {
console.log('componentWillUnmount');
this.intervals.map(clearInterval);
}
};
}());<file_sep>"use strict";
var React = require('react');
var Metadata = React.createClass({
displayName: "ThrusterInfo",
getInitialState: function() {
return {
type: "Tunnel",
vendor: "Panasonic",
description: "Decent one. No complains so far."
};
},
render: function() {
return (
<div className="row metadata">
<div className="col-md-2">
<img src="img/thruster_small.jpg" width="100%"/>
</div>
<div className="col-md-10">
<p><strong style={{color: "#368282"}}>Type: </strong>{this.state.type}</p>
<p><strong style={{color: "#368282"}}>Vendor: </strong>{this.state.vendor}</p>
<p><strong style={{color: "#368282"}}>Description: </strong>{this.state.description}</p>
</div>
</div>
);
}
});
module.exports = Metadata;<file_sep>"use strict";
var AppDispatcher = require('../dispatcher/AppDispatcher'),
ActionTypes = require('../constants/ActionTypes'),
ChartsAPI = require('../utils/ChartsAPI'),
ContactsAPI = require('../utils/ContactsAPI');
var _chartsInterval, _contactsInterval;
var ThrusterActionCreators = {
setChartWidth: function(width) {
AppDispatcher.handleViewAction({
type: ActionTypes.SET_CHART_WIDTH,
width: width
})
},
startContactsDataRequest: function() {
_contactsInterval = setInterval(function() {
ContactsAPI.requestContacts();
}, 1000);
},
stopContactsDataRequest: function() {
clearInterval(_contactsInterval);
}
};
module.exports = ThrusterActionCreators;<file_sep>"use strict";
var _ = require('underscore');
var getMinutes = function(tests) {
var seconds = _.reduce(tests, function(totalSoFar, test) {
if (test.duration) {
return totalSoFar + test.duration;
}
return totalSoFar;
}, 0),
betweenTestsWaitTime = tests.length,
minutes = Math.ceil(seconds / 60) + betweenTestsWaitTime;
return minutes + ' minutes, ' + tests.length + ' tests';
};
module.exports = {
getTotalEstimatedDuration: function(tests, selected) {
var selectedTests = [];
tests.forEach(function(test, index) {
if (selected[index]) {
selectedTests.push(test);
}
});
return getMinutes(selectedTests);
},
getRemainingEstimatedDuration: function(tests, selected) {
var selectedUncompletedTests = [];
tests.forEach(function(test, index) {
if (selected[index] && test.status !== 'completed') {
selectedUncompletedTests.push(test);
}
});
return getMinutes(selectedUncompletedTests);
}
};<file_sep>"use strict";
var WebSocketFactory = require('./websocket'),
connectionErrorHandler = require('../components/ConnectionErrorHandler'),
AppServerActionCreators = require('../actions/AppServerActionCreators');
var _socket = WebSocketFactory.create('websocket'), _subscription;
module.exports = {
requestReset: function() {
$.get('/reset');
},
requestCancelAll: function() {
$.get('/cancelall');
},
requestRunAll: function(mode) {
var params = {};
params.mode = mode;
$.post('/runall', $.param(params));
},
requestRunTests: function(keys, mode) {
var params = {};
params.ids = JSON.stringify(keys);
params.mode = mode;
$.post('/runtests', $.param(params));
},
requestSetScript: function(script) {
var params = {};
params.script = script;
$.post('/setscript', $.param(params));
},
connectServer: function() {
_socket.open();
_socket.echo(connectionErrorHandler);
_subscription = _socket.subscribe('websocket', AppServerActionCreators.handleWebsocketMessageReceived);
},
disconnectServer: function() {
_socket.unsubscribe(_subscription);
_socket.close();
},
requestApplicationVersion: function() {
$.get('/applicationversion', function(response) {
AppServerActionCreators.handleApplicationVersionSuccess(response);
});
},
setReportSettings: function(type, description) {
var data = {
type: type,
description: description
};
$.post('/setreportsettings', data);
},
acknowledgeAlert: function() {
$.post('/acknowledgealert');
}
};<file_sep>"use strict";
var AppDispatcher = require('../dispatcher/AppDispatcher'),
ActionTypes = require('../constants/ActionTypes'),
EventEmitter = require('events').EventEmitter,
assign = require('object-assign'),
CHANGE_EVENT = 'change',
_ = require('underscore');
var _thrusters = [];
var VesselStore = assign({}, EventEmitter.prototype, {
getThrusters: function() {
return _thrusters;
},
getThruster: function(id) {
return _.find(_thrusters, function(one) {
return one.id === id
});
},
emitChange: function() {
this.emit(CHANGE_EVENT);
},
addChangeListener: function(callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener: function(callback) {
this.removeListener(CHANGE_EVENT, callback);
},
dispatcherIndex: AppDispatcher.register(function(payload) {
var action = payload.action;
switch (action.type) {
case ActionTypes.THRUSTERS_RECEIVED:
_thrusters = action.response;
VesselStore.emit(CHANGE_EVENT);
break;
default:
// no op
}
})
});
module.exports = VesselStore;<file_sep>"use strict";
var ServerAPI = require('../utils/ServerAPI'),
MessagerAPI = require('../utils/MessagerAPI'),
AppDispatcher = require('../dispatcher/AppDispatcher'),
ActionTypes = require('../constants/ActionTypes'),
router = require('../router');
var AppActionCreators = {
requestApplicationVersion: function() {
ServerAPI.requestApplicationVersion();
},
connectServer: function() {
ServerAPI.connectServer();
MessagerAPI.openSocket();
},
disconnectServer: function() {
ServerAPI.disconnectServer();
MessagerAPI.closeSocket();
},
requestReportSettings: function(reportType) {
AppDispatcher.handleViewAction({
type: ActionTypes.REQUEST_REPORT_SETTINGS,
reportType: reportType
});
},
handleReportSettingsClose: function() {
AppDispatcher.handleViewAction({
type: ActionTypes.CLOSE_REPORT_SETTINGS
});
},
setReportSettings: function(reportType, description) {
ServerAPI.setReportSettings(reportType, description);
AppDispatcher.handleViewAction({
type: ActionTypes.CLOSE_REPORT_SETTINGS
});
AppDispatcher.handleViewAction({
type: ActionTypes.REPORT_SETTINGS_POSTED
});
},
setScript: function(script) {
ServerAPI.requestSetScript(script);
},
navigateTo: function(url, params) {
router.transitionTo(url, params);
},
acknowledgeAlert: function() {
ServerAPI.acknowledgeAlert();
}
};
module.exports = AppActionCreators;<file_sep>var httpProxy = require('http-proxy'),
express = require('express'),
livereload = require('connect-livereload'),
http = require('http'),
serverport = 8083;
var proxy = httpProxy.createProxyServer({
target: 'http://172.27.48.5:8080/'
});
proxy.on('error', function(err, req, res) {
if (typeof res.writeHead === 'function') {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end('Something went wrong. And we are reporting a custom error message.');
}
});
var restUrl = function(url) {
var restUrls = [
"acknowledgealert",
"aggregatedprogress",
"alerts",
"messages",
"applicationversion",
"cancelall",
"executionstatus",
"finishfmea",
"getReport",
"reportinfo",
"reportlist",
"reset",
"tests",
"resetteststates",
"runall",
"savecomment",
"saveresultoverride",
"setreportsettings",
"setscript",
"userinput",
"files",
"debug",
"status",
"kafka",
"navigation"
];
var isRest = false;
restUrls.forEach(function(restUrl) {
if (url.indexOf(restUrl) !== -1) {
isRest = true;
return;
}
});
return isRest;
};
var proxyMiddleware = function(req, res, next) {
if (restUrl(req.url)) {
proxy.web(req, res);
} else {
next();
}
};
module.exports = function() {
"use strict";
var app = express(),
server = http.createServer(app);
app.use(livereload({
port: 35729
}));
app.use(express.static('./dist/public/signature'));
app.use(proxyMiddleware);
server.on('upgrade', function(req, socket, head) {
proxy.ws(req, socket, head);
});
server.listen(serverport);
};<file_sep>describe('ServerConnector', function() {
var create, Request, timeout, provide
beforeEach(module("app"))
beforeEach(module(function($provide) {
Request = {
get: function(url, callback) {
callback({'hey': 'hopp'})
}
}
provide = $provide
$provide.value('Request', Request)
}));
beforeEach(inject(function ($injector) {
create = function() {
return $injector.get('ServerConnector');
};
}));
it('Receives subscriptions for keywords and notifies on updates', function() {
inject(function($interval) {
var cut = create()
var spy1 = jasmine.createSpy('observer1')
var spy2 = jasmine.createSpy('observer2')
cut.observe('hey', spy1)
cut.observe('hey', spy2)
$interval.flush(1000)
expect(spy1).toHaveBeenCalledWith('hopp')
expect(spy2).toHaveBeenCalledWith('hopp')
})
})
it ('polls server every second for data', function() {
inject(function($interval) {
var get = jasmine.createSpy('request.get')
provide.value('Request', {get: get})
var cut = create()
expect(get.callCount).toBe(1)
$interval.flush(1000)
expect(get.callCount).toBe(2)
$interval.flush(1000)
expect(get.callCount).toBe(3)
})
})
})<file_sep>describe('weather widget', function() {
var scope, compile, compiledTemplate, serverConnector, observer
var compileDirective = function() {
var tpl = '<weather-widget></weather-widget>'
compiledTemplate = compile(tpl)(scope)
scope.$digest()
}
var serverConnectorStub = {
observe: function(key, o) {
if (key == 'weather')
observer = o
}
}
beforeEach(module('app'))
beforeEach(module(function($provide) {
provide = $provide
$provide.value('ServerConnector', serverConnectorStub)
}));
beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope.$new()
compile = $compile
}))
it('should display default (unknown) text about wave height and wind', function() {
compileDirective()
var text = compiledTemplate.text()
expect(text).toContain('- m/s')
expect(text).toContain('- m')
expect(text).toContain('- m/s')
})
it('should connect to server on load', function() {
compileDirective()
expect(observer).toBeDefined()
})
it('should update gui on receiving messages from server', function() {
compileDirective()
observer({windValue: '10', windAngle: '35', waveValue: '14', waveAngle: '125', currentValue: '10', currentAngle: '215'})
scope.$digest()
var text = compiledTemplate.text()
expect(text).toContain('10.00 m/s')
expect(text).toContain('14.00 m')
expect(text).toContain('10.00 m/s')
})
});<file_sep>"use strict";
var React = require('react'),
ContactsStore = require('../../stores/ContactsStore'),
ThrusterActionCreators = require('../../actions/ThrusterActionCreators');
var Contact = React.createClass({
displayName: "Contact",
render: function() {
var contactData = this.props.contactData;
return (
<div className="col-lg-3 col-md-6 col-sm-12">
<div className="well">
<h6>Competence: <strong>{contactData.competence}</strong></h6>
<h6>Name: <strong>{contactData.name}</strong></h6>
<h6>Company: <strong>{contactData.company}</strong></h6>
<h6>Skype: <strong>{contactData.skype}</strong></h6>
<h6>Email: <strong>{contactData.email}</strong></h6>
<h6>Phone: <strong>{contactData.phone}</strong></h6>
</div>
</div>
);
}
});
var Status = React.createClass({
displayName: "Status",
componentDidMount: function() {
ThrusterActionCreators.startContactsDataRequest();
ContactsStore.addChangeListener(this._onChange);
},
componentWillUnmount: function() {
ThrusterActionCreators.stopContactsDataRequest();
ContactsStore.removeChangeListener(this._onChange);
},
getInitialState: function() {
return ContactsStore.getContactsData();
},
render: function() {
var contactsList = <div />
var contacts = this.state.contacts;
if (contacts !== undefined) {
contactsList = contacts.map(function(one, index) {
return (
<Contact contactData={one} key={index}/>
);
});
};
return (
<div className="row">
{contactsList}
</div>
);
},
_onChange: function() {
if (this.isMounted()) {
this.setState(ContactsStore.getContactsData());
}
}
});
module.exports = Status;
<file_sep>"use strict";
var KafkaInfoAPI = require('../utils/KafkaInfoAPI');
var _kafkaInfoInterval;
var KafkaInfoActionCreators = {
startKafkaInfoRequest: function() {
_kafkaInfoInterval = setInterval(function() {
KafkaInfoAPI.requestKafkaInfo();
}, 1000);
},
stopKafkaInfoRequest: function() {
clearInterval(_kafkaInfoInterval);
},
startStopProducing: function(topic, requestedState) {
KafkaInfoAPI.requestStartStopProducing(topic, requestedState);
},
setProducedModules: function(cluster, producedModules) {
console.log("module cb click " + cluster + ": " + producedModules);
KafkaInfoAPI.setProducedModules(cluster, producedModules);
},
throttle: function(topic, newValue) {
KafkaInfoAPI.requestThrottle(topic, newValue);
}
};
module.exports = KafkaInfoActionCreators;<file_sep>"use strict";
var _ = require('underscore');
module.exports = {
prettyTime: function(seconds) {
var sec = Math.floor(seconds);
if (sec === 0) {
return '00:00';
}
if (sec) {
var hours = Math.floor(sec / 3600);
var minutes = Math.floor((sec - (hours * 3600)) / 60);
var seconds = sec - (hours * 3600) - (minutes * 60);
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
if (hours === '00') {
return minutes + ':' + seconds;
}
return hours + ':' + minutes + ':' + seconds;
}
return '';
},
isNumber: function(number) {
return !isNaN(parseFloat(number)) && isFinite(number);
},
prettyNumber: function(newValue) {
if (this.isNumber(newValue)) {
return parseFloat(newValue).toFixed(2);
}
return newValue;
},
rad2deg: function(rads) {
return rads * 180 / Math.PI;
},
capitalizeFirstLetter: function(sentence) {
if (!_.isString(sentence)) {
return sentence;
}
return sentence.charAt(0).toUpperCase() + sentence.slice(1);
}
};<file_sep>"use strict";
var React = require('react'),
Router = require('react-router'),
AppStore = require('../stores/AppStore'),
Navigation = require('./Navigation'),
AppActionCreators = require('../actions/AppActionCreators'),
hotkey = require('react-hotkey'),
_ = require('underscore'),
KeyEventParser = require('../services/KeyEventParser'),
AlertMessageDialog = require('./AlertMessageDialog');
var RouteHandler = Router.RouteHandler;
var App = React.createClass({
displayName: "App",
mixins: [hotkey.Mixin('handleHotkey')],
getInitialState: function() {
return {
applicationVersion: AppStore.getApplicationVersion(),
openAlertMessageDialog: AppStore.getOpenAlertMessageDialog(),
alert: AppStore.getAlert()
};
},
componentDidMount: function() {
AppStore.addChangeListener(this._onChange);
AppActionCreators.requestApplicationVersion();
AppActionCreators.connectServer();
hotkey.activate('keydown');
},
componentWillUnmount: function() {
AppStore.removeChangeListener(this._onChange);
hotkey.disable();
AppActionCreators.disconnectServer();
},
render: function() {
var AlertMessageModal = this.state.openAlertMessageDialog ? <AlertMessageDialog alert={this.state.alert} /> : null;
return (
<div>
{AlertMessageModal}
<Navigation applicationVersion={this.state.applicationVersion} />
<RouteHandler />
</div>
);
},
_onChange: function() {
if (this.isMounted()) {
this.setState({
applicationVersion: AppStore.getApplicationVersion(),
openAlertMessageDialog: AppStore.getOpenAlertMessageDialog(),
alert: AppStore.getAlert()
});
}
},
handleHotkey: function(evt) {
var buttons = KeyEventParser.getButtonsPressed(evt);
if (_.isEqual(['Control', 'Alt', 'K'], buttons)) {
AppActionCreators.navigateTo('kafka');;
}
if (_.isEqual(['Control', 'Alt', 'C'], buttons)) {
AppActionCreators.navigateTo('charts');;
}
if (_.isEqual(['Control', 'Alt', 'V'], buttons)) {
AppActionCreators.navigateTo('vessel');;
}
}
});
module.exports = App;<file_sep>"use strict";
var ChartsServerActionCreators = require('../actions/ChartsServerActionCreators'),
WebSocketFactory = require('./websocket');
var _sockets = {};
var _subscriptions = {};
var ChartsAPI = {
requestCharts: function() {
$.get('/dailyweather', function(response) {
ChartsServerActionCreators.handleChartsSuccess(response);
});
},
requestSignalData: function(signalId) {
$.get('ajax/vessel_data?imo=9368302&signal_id=' + signalId, function(response) {
ChartsServerActionCreators.handleSignalDataSuccess(response, signalId);
});
},
openSignalSocket: function(signalId) {
var socket = WebSocketFactory.create('signal/' + signalId);
_sockets[signalId] = socket;
socket.open();
var subscription = socket.subscribe('signal::' + signalId, function(data) {
ChartsServerActionCreators.handleSignalValueReceived(data, signalId);
});
_subscriptions[signalId] = subscription;
},
closeSignalSocket: function(signalId) {
var socket = _sockets[signalId];
var subscription = _subscriptions[signalId];
socket.unsubscribe(subscription);
socket.close();
_sockets[signalId] = undefined;
_subscriptions[signalId] = undefined;
}
};
module.exports = ChartsAPI;<file_sep>describe('FmeaIntegration', function () {
"use strict";
var ManualTestsService, timeout, provide, scope, compile, compiledTemplate;
var compileDirective = function (test) {
scope.test = test;
var tpl = '<a fmea-click test="test"/>';
compiledTemplate = compile(tpl)(scope);
scope.$digest();
};
beforeEach(module("app"));
beforeEach(module(function ($provide) {
ManualTestsService = {
get: function (url, callback) {
callback({'hey': 'hopp'});
}
};
provide = $provide;
$provide.value('ManualTestsService', ManualTestsService);
}));
beforeEach(inject(function ($rootScope, $compile) {
scope = $rootScope.$new();
compile = $compile;
}));
it ('Opens modal with interactive verifications when clicked', function () {
compileDirective({});
var rootElement = compiledTemplate.find('a');
expect(rootElement).toBeDefined();
});
});
<file_sep>"use strict";
var keyMirror = require('react/lib/keyMirror');
module.exports = keyMirror({
WEATHER_RECEIVED: null,
ENGINE_STATUS_RECEIVED: null,
APPLICATION_VERSION_RECEIVED: null,
WEBSOCKET_MESSAGE_RECEIVED: null,
REQUEST_KAFKA_INFO_SUCCESS: null,
REQUEST_NAVIGATION_SUCCESS: null,
REQUEST_CHARTS_DATA_SUCCESS: null,
THRUSTER_CLICK: null,
CLOSE_THRUSTER_INFO: null,
CANCEL_ALL_PRESSED: null,
MESSAGER_RECEIVED: null,
REQUEST_CONTACTS_DATA_SUCCESS: null,
REQUEST_SIGNAL_DATA_SUCCESS: null,
SIGNAL_VALUE_RECEIVED: null,
REQUEST_EVA_STATUS_SUCCESS: null,
LOST_CONNECTION: null,
BACK_ONLINE: null
});<file_sep>"use strict";
var React = require('react');
var KafkaInfoStore = require('../stores/KafkaInfoStore');
var KafkaInfoActionCreators = require('../actions/KafkaInfoActionCreators');
var _ = require('underscore');
var _optimisticTimeout, _optimistic, _optimisticThrottleTimeout, _optimisticThrottle;
var Schema = React.createClass({
displayName: "Schema",
_pretty: function (json) {
return JSON.stringify(json,null,2);
},
render: function() {
return (
<div className="panel panel-info">
<div className="panel-heading">
<h3 className="panel-title"><strong>Schema</strong></h3>
</div>
<div className="panel-body">
<pre className="text-info">{this._pretty(this.props.schema)}</pre>
</div>
</div>
);
}
});
var Configuration = React.createClass({
displayName: "Configuration",
_requestedState: "Start",
_slider: undefined,
componentDidMount: function() {
this._slider = $('#throttle').slider({
min: 0,
max: 1000,
step: 50,
formatter: function(value) {
return value + 'ms';
}
})
.on('change', this.props.onThrottle);
},
componentWillUnmount: function() {
},
componentWillReceiveProps: function(nextProps) {
this._requestedState = nextProps.info.state === "running" ? "Stop" : "Start";
this._slider.slider('setValue', nextProps.info.throttle);
},
render: function() {
var state = this.props.info.state;
var ellipses = state === "running" ? <span><span className="one">.</span><span className="two">.</span><span className="three">.</span></span> : null;
return (
<div className="panel panel-info">
<div className="panel-heading">
<h3 className="panel-title"><strong>Control</strong></h3>
</div>
<div className="panel-body">
<table className="table table-striped" style={{"tableLayout": "fixed"}}>
<tr>
<td className="text-primary" style={{"width": "20%"}}><strong>Topic</strong></td>
<td>{this.props.info.topic ? this.props.info.topic : "undefined"}</td>
</tr>
<tr>
<td className="text-primary"><strong>State</strong></td>
<td>
{state ? state : "undefined"}{ellipses}
<button type="button" className="btn btn-info" onClick={this._onStartStop}>
{this._requestedState}
</button>
</td>
</tr>
<tr>
<td className="text-primary"><strong>Throttle</strong></td>
<td>
<input id="throttle" data-slider-id='throttleSlider' type="text" data-slider-value={this.props.info.throttle}/>
</td>
</tr>
<tr>
<td className="text-primary"><strong>Broker</strong></td>
<td>{this.props.info.bootstrapServers ? this.props.info.bootstrapServers : "undefined"}</td>
</tr>
<tr>
<td className="text-primary"><strong>Schema</strong></td>
<td>{this.props.info.schemaRegistry ? this.props.info.schemaRegistry : "undefined"}</td>
</tr>
</table>
</div>
</div>
);
},
_onStartStop: function() {
console.log('start / stop producing');
KafkaInfoActionCreators.startStopProducing(this.props.info.topic, this._requestedState);
},
_onThrottle: function(evt) {
KafkaInfoActionCreators.throttle(this.props.info.topic, evt.value.newValue);
}
});
var ModuleRow = React.createClass({
displayName: "ModuleRow",
_onCbClick: function(evt) {
console.log("click " + this.props.selected);
this.props.onModuleCbClick(this.props.group.group, this.props.module, this.props.selected);
},
render: function() {
var module = this.props.module;
var group = this.props.group;
var index = this.props.index;
var selected = this.props.selected;
var modulesNr = this.props.modulesNr;
var stripe = this.props.stripe;
var onCbClick = this._onCbClick;
if (index === 0) {
return (
<tr>
<td className="text-primary" className={stripe} rowSpan={modulesNr}><strong>{group.stepSize + " ms"}</strong></td>
<td>
{module}
</td>
<td>
<input type="checkbox" style={{"cursor": "pointer"}} checked={selected} onChange={onCbClick} />
</td>
</tr>
);
}
return (
<tr key={index} >
<td>
{module}
</td>
<td>
<input type="checkbox" style={{"cursor": "pointer"}} checked={selected} onChange={onCbClick} />
</td>
</tr>
);
}
});
var Modules = React.createClass({
displayName: "Modules",
render: function() {
var modules = this.props.modules;
var produced = this.props.produced;
var onModuleCbClick = this.props.onModuleCbClick;
var groupsList = <tr />;
if (modules !== undefined) {
var stepSizes = Object.keys(modules).map(function(group, index) {
return {
group: group,
stepSize: parseInt(group.split("::")[1])
}
});
var groups = _.sortBy(stepSizes, function(one) {
return one.stepSize;
});
groupsList = groups.map(function(oneGroup, index) {
var sortedModules = _.sortBy(modules[oneGroup.group], function(oneModule) {
return oneModule;
});
var modulesNr = sortedModules.length;
var group = sortedModules.map(function(module, idx) {
var stripe = index % 2 === 0 ? "active" : "";
var producedList = _.flatten(Object.keys(produced).map(function(group, undex) {
return produced[group];
}));
var selected = producedList.indexOf(sortedModules[idx]) >= 0;
return <ModuleRow module={sortedModules[idx]}
group={oneGroup}
index={idx}
modulesNr={modulesNr}
selected={selected}
stripe={stripe}
onModuleCbClick={onModuleCbClick} />
});
return (
{group}
);
});
}
return (
<div className="panel panel-info">
<div className="panel-heading">
<h3 className="panel-title"><strong>Modules</strong></h3>
</div>
<div className="panel-body">
<table className="table table-condensed table-hover">
<tbody>
{groupsList}
</tbody>
</table>
</div>
</div>
);
}
});
var Record = React.createClass({
displayName: "Record",
_pretty: function (json) {
return JSON.stringify(json,null,2);
},
render: function() {
return (
<div className="panel panel-info">
<div className="panel-heading">
<h3 className="panel-title"><strong>Random record</strong></h3>
</div>
<div className="panel-body">
<table className="table table-striped" style={{"tableLayout": "fixed"}}>
<tr>
<td className="text-primary" style={{"width": "20%"}}><strong>Topic</strong></td>
<td>{this.props.record.topic ? this.props.record.topic : "undefined"}</td>
</tr>
<tr>
<td className="text-primary"><strong>Key</strong></td>
<td className="text-primary" style={{"overflow": "hidden", "textOverflow": "ellipsis", "whiteSpace": "nowrap"}}>{this.props.record.key ? this.props.record.key : "undefined"}</td>
</tr>
<tr>
<td colSpan="2"><pre className="text-primary">{this.props.record.value ? this._pretty(this.props.record.value) : "undefined"}</pre></td>
</tr>
</table>
</div>
</div>
);
}
});
var KafkaInfo = React.createClass({
displayName: 'KafkaInfo',
contextTypes: {
router: React.PropTypes.func
},
getInitialState: function() {
return KafkaInfoStore.getKafkaInfo();
},
componentDidMount: function() {
KafkaInfoStore.addChangeListener(this._onChange);
KafkaInfoActionCreators.startKafkaInfoRequest();
},
componentWillUnmount: function() {
KafkaInfoStore.removeChangeListener(this._onChange);
KafkaInfoActionCreators.stopKafkaInfoRequest();
clearTimeout(_optimisticTimeout);
_optimistic = undefined;
clearTimeout(_optimisticThrottleTimeout);
_optimisticThrottle = undefined;
},
render: function() {
var schemaJson = this.state.schema ? JSON.parse(this.state.schema) : {};
var record = this.state.randomRecord ? JSON.parse(this.state.randomRecord) : {};
record.value = record.value ? JSON.parse(record.value) : {};
return (
<div className="col-md-8">
<div className="row">
<div className="col-lg-5 col-md-6">
<Configuration info={this.state} onThrottle={this._onThrottle}/>
<div className="row">
<div className="col-md-12">
<Record record={record} />
</div>
</div>
</div>
<div className="col-lg-4 col-md-6">
<Modules modules={this.state.simulatorModules} produced={this.state.producedModules} onModuleCbClick={this._onModuleCbClick} />
</div>
<div className="col-lg-3 visible-lg">
<Schema schema={schemaJson} />
</div>
</div>
</div>
);
},
_onChange: function() {
var cluster = this.context.router.getCurrentParams().clusterId;
if (this.isMounted() && !_optimistic) {
this.setState(KafkaInfoStore.getKafkaInfo()[cluster]);
}
},
_onModuleCbClick: function(group, module, selected) {
this._doOptimisticUpdate(group, module, selected);
},
_onThrottle: function(evt) {
clearTimeout(_optimisticThrottleTimeout);
var cluster = this.context.router.getCurrentParams().clusterId;
if (!_optimistic) {
_optimistic = KafkaInfoStore.getKafkaInfo()[cluster];
}
_optimistic.throttle = evt.value.newValue;
this.setState(_optimistic);
_optimisticThrottleTimeout = setTimeout(function () {
_optimistic = undefined;
this.setState(KafkaInfoStore.getKafkaInfo()[cluster]);
}.bind(this), 2000);
KafkaInfoActionCreators.throttle(cluster, evt.value.newValue);
},
_doOptimisticUpdate: function(group, module, selected) {
clearTimeout(_optimisticTimeout);
var cluster = this.context.router.getCurrentParams().clusterId;
if (!_optimistic) {
_optimistic = KafkaInfoStore.getKafkaInfo()[cluster];
}
if (selected) {
var moduleIdx = _optimistic.producedModules[group].indexOf(module);
_optimistic.producedModules[group].splice(moduleIdx, 1);
} else {
if (_optimistic.producedModules[group] === undefined) {
_optimistic.producedModules[group] = [module];
} else {
_optimistic.producedModules[group].push(module);
}
}
this.setState(_optimistic);
_optimisticTimeout = setTimeout(function () {
console.log("modules timeout");
_optimistic = undefined;
this.setState(KafkaInfoStore.getKafkaInfo()[cluster]);
}.bind(this), 2000);
KafkaInfoActionCreators.setProducedModules(cluster, _optimistic.producedModules);
}
});
module.exports = KafkaInfo;
<file_sep>"use strict";
var React = require('react'),
ExecutionStatusStore = require('../stores/ExecutionStatusStore');
module.exports = React.createClass({
displayName: "Warnings",
getInitialState: function() {
return {
executionStatus: ExecutionStatusStore.getExecutionStatus()
};
},
componentDidMount: function() {
ExecutionStatusStore.addChangeListener(this._onChange);
},
componentWillUnmount: function() {
ExecutionStatusStore.removeChangeListener(this._onChange);
},
render: function() {
var executionStatus = this.state.executionStatus;
if (executionStatus && executionStatus.dpCommunicator && executionStatus.dpCommunicator.isConnected) {
return null;
}
if (executionStatus && !executionStatus.dpCommunicator) {
return null;
}
return (
<div className="warnings">
<div className="alert alert-danger">
<i className="fa fa-warning fa-fw" />
No connection with DP system
</div>
</div>
);
},
_onChange: function() {
if (this.isMounted()) {
this.setState({
executionStatus: ExecutionStatusStore.getExecutionStatus()
});
}
},
}); | 8fffc0672b1ee1d9dda5305965d31b479f755f8a | [
"JavaScript",
"Maven POM",
"Markdown"
] | 55 | JavaScript | MarineCybernetics/NetworkAnalyzer | 82d9e5bbefda96d5b10edc22cca92b69f69fe4cf | bfbb9e273466c56adb14804dc5a63f3316d80abd |
refs/heads/master | <file_sep>import firebase from "firebase/compat/app" // issue with v9 of firebase
import "firebase/compat/auth"
const app = firebase.initializeApp({
apiKey: process.env.REACT_APP_FB_KEY,
authDomain: process.env.REACT_APP_FB_AUTH,
databaseURL: process.env.REACT_APP_FB_DB_URL,
projectId: process.env.REACT_APP_FB_PID,
storageBucket: process.env.REACT_APP_FB_STB,
messagingSenderId: process.env.REACT_APP_FB_MSID,
appId: process.env.REACT_APP_FB_AID,
measurementId: process.env.REACT_APP_FB_MEID
})
export const auth = app.auth()
export default app<file_sep>import React, { Component } from 'react';
import Movie from './Movie'
import { connect } from 'react-redux';
import { setDataAc } from '../Actions'
class MovieList extends Component {
constructor() {
super()
this.handleDateCacheMovie = this.handleDateCacheMovie.bind(this)
}
componentDidMount() {
let { linkMovie, type } = this.props.other
let linkMovieCopy = [...linkMovie]
linkMovieCopy = 'midnightblue'
this.props.setData(linkMovieCopy, 'linkMovie')
let selectDrop = document.getElementById('types')
selectDrop.value = type
}
componentWillUnmount() {
let { linkMovie } = this.props.other
let linkMovieCopy = [...linkMovie]
linkMovieCopy = 'white'
this.props.setData(linkMovieCopy, 'linkMovie')
}
handleDateCacheMovie = id => {
fetch(`https://www.omdbapi.com/?i=${id}&apikey=3d7eed43`)
.then(response => response.json())
.then(data => {
this.props.clearDates()
this.props.setData({Search: [data]}, 'data')
console.log(data)
console.log('^data')
console.log(this.props)
console.log('^reducer props')
})
}
render() {
let data = this.props.data
let moviesListed;
if (this.props.showDates.length) {
moviesListed = this.props.showDates.map((m, i) => <div className='date-cache' key={i} onClick={() => this.handleDateCacheMovie(m.id)}>{m.hasOwnProperty('rating') ? m.rating : m.year} - {m.title}</div>)
} else if (data.hasOwnProperty('Search')) {
moviesListed = data.Search.filter(m => m.Poster !== 'N/A').map((m, i) => <Movie key={i} data={m} getMovieInfo={this.props.getMovieInfo}/>)
} else {
moviesListed = <div className='title-page'>Find new movies to watch. Randomly or otherwise.</div>
}
return (
<div className='movie-list'>
{moviesListed}
</div>
)
}
}
const mapStateToProps = (state) => ({
data: state.data,
other: state
})
const mapDispatchToProps = (dispatch) => ({
setData: (data, prop) => dispatch(setDataAc([data, prop]))
})
export default connect(mapStateToProps, mapDispatchToProps)(MovieList);
<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { setDataAc } from '../Actions'
class Quiz extends Component {
constructor(props) {
super(props)
this.state = {
questions: [
['Year','Which of these movies was released in X?','Title',1],
['Title','What year was X released?','Year',2],
['Title','Who directed X?','Director',3],
['Director','What movie did X direct?','Title',4],
['Plot','What movie does this plot line belong to?','Title',5],
['Title','What genre is X?','Genre',6],
['Genre','Which of these movies is X?','Title',7],
['Actors','X starred in what movie?','Title',8],
['Title','Who acted in X?','Actors',9],
['Runtime','Which of these movies is the shortest?','Title',10],
['Runtime','Which movie is the longest?','Title',11],
['BoxOffice','Which movie made the most money?','Title',12],
['BoxOffice','What movie made the least money?','Title',13],
['imdbRating','Which movie received the best rating?','Title',14],
['imdbRating','Which movie received the worst rating?','Title',15],
['imdbRating','Which movie received a rating of X?','Title',19],
['Country','Which movie was not made strictly in the USA?','Title',16],
['Country','Which movie was made in X?','Title',17],
['Awards','Which movie has X?','Title',18]
],
qNum: 0,
quiz: false,
question: [],
option1: '',
option2: '',
option3: '',
option4: '',
option5: '',
answer: [],
points: 1,
waitForChange: false,
plotLine: '',
optionColor: ['default', 'default', 'default', 'default', 'default'],
noRepeatedQuestions: ''
}
this.handleClick = this.handleClick.bind(this)
this.quizStart = this.quizStart.bind(this)
this.handleAnswer = this.handleAnswer.bind(this)
}
handleClick() {
this.setState({quiz: !this.state.quiz})
console.log('handleClick')
this.quizStart()
}
quizStart() {
console.log('quizStart')
let movies = this.props.data
let answer, wrongAnswerOne, wrongAnswerTwo, wrongAnswerThree, wrongAnswerFour;
const randomNum = (array) => Math.floor(Math.random() * array.length)
const lookForQuestion = () => {
console.log('lookForQuestion')
let numAnswers = movies.length < 5 ? movies.length : 5
let question = this.state.questions[randomNum(this.state.questions)]
if (question[3] === this.state.noRepeatedQuestions[3] && this.state.noRepeatedQuestions !== 5) {
question = this.state.questions[4]
console.log('repeated')
}
let [ qProp ] = question
let checkPotentialQuestion = movies.filter(m => m[qProp] !== 'N/A')
if (qProp === 'Country' && !checkPotentialQuestion.some(m => m[qProp] !== 'USA')) {
checkPotentialQuestion = []
}
if (movies.length < 5 && checkPotentialQuestion.length >= movies.length && movies.length > 0) {
while (numAnswers) {
let itemSet = setAnswers(checkPotentialQuestion, qProp, numAnswers)
checkPotentialQuestion.splice(itemSet, 1)
numAnswers--
}
return question
} else if (movies.length >= 5 && checkPotentialQuestion.length >= 5) {
while (numAnswers) {
let itemSet = setAnswers(checkPotentialQuestion, qProp, numAnswers)
checkPotentialQuestion.splice(itemSet, 1)
numAnswers--
}
return question
} else {
/* Now any lookForQuestions on the call stack will wait for a return of 'question' */
return lookForQuestion()
}
}
/* setAnswers returns an random index while also setting every wrong and right answer */
const setAnswers = (checkPotentialQuestion, qProp, whichAnswer) => {
let randomIndex = randomNum(checkPotentialQuestion)
switch (whichAnswer) {
case 5:
/* Returns array. Example: [89 mins, {movie object}] */
wrongAnswerFour = [checkPotentialQuestion[randomIndex][qProp],
checkPotentialQuestion[randomIndex]]
break;
case 4:
wrongAnswerThree = [checkPotentialQuestion[randomIndex][qProp],
checkPotentialQuestion[randomIndex]]
break;
case 3:
wrongAnswerTwo = [checkPotentialQuestion[randomIndex][qProp],
checkPotentialQuestion[randomIndex]]
break;
case 2:
wrongAnswerOne = [checkPotentialQuestion[randomIndex][qProp],
checkPotentialQuestion[randomIndex]]
break;
case 1:
answer = [checkPotentialQuestion[randomIndex][qProp],
checkPotentialQuestion[randomIndex]]
break;
default:
console.log('error')
}
return randomIndex
}
/* Returns array. Example: ['Runtime', 'Which is shortest?', 'Title', 10]*/
let actualQuestion = lookForQuestion()
let answerArray = [answer, wrongAnswerOne, wrongAnswerTwo, wrongAnswerThree, wrongAnswerFour]
/* These make it so every answer randomly populates an option */
let answerIndex = randomNum(answerArray)
this.setState({ question: actualQuestion, answer: answer, option1: answerArray[answerIndex], noRepeatedQuestions: actualQuestion })
answerArray.splice(answerIndex, 1)
answerIndex = randomNum(answerArray)
this.setState({ option2: answerArray[answerIndex] })
answerArray.splice(answerIndex, 1)
answerIndex = randomNum(answerArray)
this.setState({ option3: answerArray[answerIndex] })
answerArray.splice(answerIndex, 1)
answerIndex = randomNum(answerArray)
this.setState({ option4: answerArray[answerIndex] })
answerArray.splice(answerIndex, 1)
answerIndex = randomNum(answerArray)
this.setState({ option5: answerArray[answerIndex] })
answerArray.splice(answerIndex, 1)
}
handleAnswer(answer, type, correct, colorIndex) {
let { waitForChange } = this.state
let [ , aObject ] = this.state.answer
let [ aProp ] = this.state.question
console.log(answer)
if (answer[0] === '$') {
answer = answer.split('$').join('').split(',').join('')
}
answer = answer.split(' min')[0]
/* The plot line would disappear during timeOut re-render. Potential fix */
const preservePlotline = () => {
let plotLine = document.getElementsByClassName('plot-line')
if (plotLine.length > 0) {
return plotLine[0].innerText.split('...').join('')
}
return ''
}
const nextQuestion = () => {
let optionColors = [...this.state.optionColor]
optionColors[colorIndex] = 'lime'
this.setState({
optionColor: optionColors,
waitForChange: true,
plotLine: preservePlotline()
})
setTimeout(() => {
optionColors[colorIndex] = 'default'
this.setState(prevState => {
return {
points: prevState.points + 1,
optionColor: optionColors,
waitForChange: false
}
})
this.quizStart()
}, 1000)
}
console.log(aObject[aProp])
console.log(answer)
console.log(type)
console.log('^ aObject[aProp], answer, type')
/* waitForChange prevents the user from clicking more than one option during setTimeout */
if (!waitForChange) {
if(aObject[aProp] === answer && type === 'other') {
nextQuestion()
} else if (correct === answer && type === 'number') {
nextQuestion()
} else if (answer !== 'USA' && type === 'usa') {
nextQuestion()
} else if (aObject[aProp] === answer && type === 'country') {
nextQuestion()
} else {
let optionColors = [...this.state.optionColor]
optionColors[colorIndex] = 'red'
this.setState({
optionColor: optionColors,
waitForChange: true,
plotLine: preservePlotline()
})
setTimeout(() => {
/* Check for highscore first */
let { watched, highscore } = this.props.other
let { points } = this.state
let [ answerTotal, movieTotal] = highscore
if (watched.length === movieTotal && points-1 > answerTotal) {
this.props.setData([points-1, watched.length], 'highscore')
} else if (watched.length > movieTotal && points-1 >= 1) {
this.props.setData([points-1, watched.length], 'highscore')
}
optionColors[colorIndex] = 'default'
this.setState({
quiz: !this.state.quiz,
points: 1,
optionColor: optionColors,
waitForChange: false
})
}, 2500)
}
}
}
componentDidUpdate() {
if (this.state.quiz) {
let movieListSize = document.querySelector('.movie-list')
let questionBlockSize = document.querySelector('.question-block')
if (questionBlockSize.offsetHeight !== movieListSize.offsetHeight) questionBlockSize.style.height = `${movieListSize.offsetHeight}px`
console.log(questionBlockSize.offsetHeight !== movieListSize.offsetHeight)
console.log(movieListSize.offsetHeight)
console.log(questionBlockSize.offsetHeight)
console.log(questionBlockSize.style.height)
}
}
render() {
let { option1, option2, option3, option4, option5, optionColor, waitForChange } = this.state
let [ opOneColor, opTwoColor, opThreeColor, opFourColor, opFiveColor ] = optionColor
let [ qProp, question, aProp ] = this.state.question
let [ answerValue, answerObj ] = this.state.answer
let [ answerTotal, movieTotal ] = this.props.other.highscore
let correctAnswer;
let type = 'other'
if (question) {
correctAnswer = answerObj[aProp]
const sortingNumberAnswers = () => {
let sortThis = []
option1 && sortThis.push(option1[1][qProp])
option2 && sortThis.push(option2[1][qProp])
option3 && sortThis.push(option3[1][qProp])
option4 && sortThis.push(option4[1][qProp])
option5 && sortThis.push(option5[1][qProp])
if (typeof sortThis[0] === 'string') {
if (sortThis[0][0] === '$') {
/* Turns '$100,000' to 100000 */
return sortThis.map(money => {
return money.split('$').join('').split(',').join('')
})
}
/* Turns '120 min' to '120' */
return sortThis.map(s => s.split(' min')[0])
}
return sortThis
}
if (question.includes('released') ||
question.includes('direct') ||
question.includes('genre') ||
question.includes('movies is X') ||
question.includes('star') ||
question.includes('acted') ||
question.includes('movie has') ||
question.includes('rating of')) {
let [ qPieceOne, qPieceTwo ] = question.split('X')
question = `${qPieceOne} ${answerValue} ${qPieceTwo}`
} else if (question.includes('shortest') ||
question.includes('least money') ||
question.includes('worst rating')) {
let sortThis = sortingNumberAnswers()
correctAnswer = sortThis.filter(m => m !== 'N/A').sort((a,b) => a - b)[0]
type = 'number'
} else if (question.includes('longest') ||
question.includes('most money') ||
question.includes('best rating')) {
let sortThis = sortingNumberAnswers()
correctAnswer = sortThis.filter(m => m !== 'N/A').sort((a,b) => b - a)[0]
type = 'number'
} else if (question.includes('plot line')) {
let qPieceOne = question
let slicePoint = Math.floor(Math.random() * answerValue.length)
let plotLineSentence;
if (!waitForChange) {
plotLineSentence = answerValue.slice(slicePoint).length > 40 ? answerValue.slice(slicePoint, slicePoint + 40) : answerValue.slice(0, 40)
} else {
plotLineSentence = this.state.plotLine
}
question = (
<div>
{qPieceOne} <br />
<span className='plot-line'>...{plotLineSentence}...</span>
</div>
)
} else if (question.includes('strictly')) {
type = 'usa'
} else if (question.includes('made in')) {
let [ qPieceOne ] = question.split('X')
question = `${qPieceOne} ${answerValue}?`
type = 'country'
}
}
let clearColor = {}
const setColor = (color) => {
return {
backgroundColor: color,
opacity: .4
}
}
if (!this.state.quiz) {
return (
this.props.data.length > 2 ? <div onClick={this.handleClick} className='quiz-button'>Quiz!</div> : ''
)
} else {
return (
<div className='quiz'>
<h1>Question {this.state.points}: </h1>
<h3>{question}</h3>
<ul>
{option1 ? <li style={opOneColor === 'default' ? clearColor : setColor(opOneColor)} onClick={() => this.handleAnswer(option1[1][qProp], type, correctAnswer, 0)}>{option1[1][aProp]}</li> : ''}
{option2 ? <li style={opTwoColor === 'default' ? clearColor : setColor(opTwoColor)} onClick={() => this.handleAnswer(option2[1][qProp], type, correctAnswer, 1)}>{option2[1][aProp]}</li> : ''}
{option3 ? <li style={opThreeColor === 'default' ? clearColor : setColor(opThreeColor)} onClick={() => this.handleAnswer(option3[1][qProp], type, correctAnswer, 2)}>{option3[1][aProp]}</li> : ''}
{option4 ? <li style={opFourColor === 'default' ? clearColor : setColor(opFourColor)} onClick={() => this.handleAnswer(option4[1][qProp], type, correctAnswer, 3)}>{option4[1][aProp]}</li> : ''}
{option5 ? <li style={opFiveColor === 'default' ? clearColor : setColor(opFiveColor)} onClick={() => this.handleAnswer(option5[1][qProp], type, correctAnswer, 4)}>{option5[1][aProp]}</li> : ''}
</ul>
<div className='high-score'>{answerTotal ? `HIGHSCORE: ${answerTotal} CORRECT WITH ${movieTotal} MOVIES` : ''}</div>
<div className='question-block'></div>
</div>
)
}
}
}
const mapStateToProps = (state) => ({
other: state
})
const mapDispatchToProps = (dispatch) => ({
setData: (data, prop) => dispatch(setDataAc([data, prop]))
})
export default connect(mapStateToProps, mapDispatchToProps)(Quiz);
<file_sep>export const SET_DATA = 'SET_DATA'
export const setDataAc = (data) => ({
type: SET_DATA,
payload: data
})
export const TOGGLE_MODAL = 'TOGGLE_MODAL'
export const toggleModalAc = () => ({
type: TOGGLE_MODAL
})
export const SET_CHOICES = 'SET_CHOICES'
export const setChoicesAc = (data) => ({
type: SET_CHOICES,
payload: data
})
export const ADD_INPUT = 'ADD_INPUT'
export const addInputAc = (input) => ({
type: ADD_INPUT,
payload: input
})
export const GET_MODAL_INFO = 'GET_MODAL_INFO'
export const getModalInfoAc = (data) => ({
type: GET_MODAL_INFO,
payload: data
})
export const TOGGLE_MODAL_LOADING = 'TOGGLE_MODAL_LOADING'
export const toggleModalLoadingAc = () => ({
type: TOGGLE_MODAL_LOADING
})<file_sep>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'react-redux';
import { setDataAc, toggleModalAc } from '../Actions'
const modal = document.getElementById('modal-root')
class Modal extends Component {
constructor(props) {
super(props)
this.state = { more: false, hover: false }
this.moreInfo = this.moreInfo.bind(this)
this.handleMouseOver = this.handleMouseOver.bind(this)
this.handleMouseLeave = this.handleMouseLeave.bind(this)
this.windowHeightChange = this.windowHeightChange.bind(this)
}
el = document.createElement('modal-root')
handleMouseOver() { this.setState({hover: true}) }
handleMouseLeave() { this.setState({hover: false}) }
moreInfo() {
this.setState({ more: !this.state.more })
setTimeout(() => {
let modalInfoButtons = document.querySelector('.modal-info-buttons')
let modalSize = document.querySelector('.modal-info-container').offsetHeight
let check = window.innerHeight + 40 >= modalSize && modalSize < 456
if (!this.state.more && !check) modalInfoButtons.classList.add('temp')
this.windowHeightChange()
}, 10)
}
windowHeightChange() {
let modalSize = document.querySelector('.modal-info-container').offsetHeight
if (window.innerHeight - 40 <= modalSize) document.querySelector('.modal-info-container').style.height = `${window.innerHeight - 40}px`
else if (window.innerHeight + 40 >= modalSize && modalSize < 456) document.querySelector('.modal-info-container').style.height = `${window.innerHeight - 40}px`
if (window.innerHeight < 456 || window.innerWidth < 730) document.querySelector('.modal-info-buttons').classList.remove('temp')
}
componentDidMount() {
modal.appendChild(this.el)
this.windowHeightChange()
let check = window.innerHeight < 456 || window.innerWidth < 730
if (!check) document.querySelector('.modal-info-buttons').classList.add('temp')
document.querySelector('.modal-info-container').style.height = '454px'
window.addEventListener('resize', this.windowHeightChange)
setTimeout(() => this.windowHeightChange(), 10)
}
componentWillUnmount() {
modal.removeChild(this.el)
this.props.setData([ [], 'movieModal' ])
window.removeEventListener('resize', this.windowHeightChange)
}
render() {
let movie = this.props.data.movieModal
let isDataReady = this.props.data.modal
let { maybe, definitely, watched } = this.props.data
let buttons = (
<div className='modal-info-buttons' style={{backgroundColor: this.state.more ? 'midnightblue' : 'black'}}>
<div className='bu' onClick={this.props.toggleModal}>Close</div>
<div className='bu' onClick={this.moreInfo}>{this.state.more ? 'Less Info' : 'More Info'}</div>
</div>
)
let more = (
<div>
<div className='more-info'>
{movie.Writer !== 'N/A' ? <span>writer<br /></span> : ''}
{movie.Writer !== 'N/A' ? <div>{movie.Writer}<br /><br /></div> : ''}
{movie.Actors !== 'N/A' ? <span>actors<br /></span> : ''}
{movie.Actors !== 'N/A' ? <div>{movie.Actors}<br /><br /></div> : ''}
{movie.Awards !== 'N/A' ? <span>awards<br /></span> : ''}
{movie.Awards !== 'N/A' ? <div>{movie.Awards}<br /><br /></div> : ''}
{movie.BoxOffice !== 'N/A' ? <span>box office<br /></span> : ''}
{movie.BoxOffice !== 'N/A' ? <div>{movie.BoxOffice}<br /><br /></div> : ''}
{movie.imdbRating !== 'N/A' ? <span>rating<br /></span> : ''}
{movie.imdbRating !== 'N/A' ? <div>{movie.imdbRating}<br /><br /></div> : ''}
{movie.Language !== 'N/A' ? <span>language<br /></span> : ''}
{movie.Language !== 'N/A' ? <div>{movie.Language}<br /><br /></div> : ''}
{movie.Country !== 'N/A' ? <span>country<br /></span> : ''}
{movie.Country !== 'N/A' ? <div>{movie.Country}<br /><br /></div> : ''}
{movie.Runtime !== 'N/A' ? <span>runtime<br /></span> : ''}
{movie.Runtime !== 'N/A' ? <div>{movie.Runtime}<br /><br /></div> : ''}
</div>
{buttons}
</div>
)
return ReactDOM.createPortal(
<div className='modal'>
<div className='modal-info-container'>
<div className='modal-info-split'>
<div className='image-container' onMouseOver={this.handleMouseOver} onMouseLeave={this.handleMouseLeave}>
<img src={movie.Poster} alt='WOW'/>
<div className='bookmark' style={{visibility: this.state.hover ? 'visible' : 'hidden'}}>
<span className='would-you'>Would you watch this?</span>
<span style={{color: maybe.some(m => m.imdbID === movie.imdbID) ? 'blue' : 'white'}} name='maybe' className='span' onClick={() => this.props.categorize('maybe', movie)}>MAYBE</span>
<span style={{color: definitely.some(m => m.imdbID === movie.imdbID) ? 'blue' : 'white'}} name='definitely' className='span' onClick={() => this.props.categorize('definitely', movie)}>DEFINITELY</span>
<span style={{color: watched.some(m => m.imdbID === movie.imdbID) ? 'blue' : 'white'}} name='watched' className='span' onClick={() => this.props.categorize('watched', movie)}>WATCHED</span>
</div>
</div>
<div className='modal-info'>
{movie.Title !== 'N/A' ? <span>title<br /></span> : ''}
{movie.Title !== 'N/A' ? <div>{movie.Title}<br /><br /></div> : ''}
{movie.Year !== 'N/A' ? <span>year<br /></span> : ''}
{movie.Year !== 'N/A' ? <div>{movie.Year}<br /><br /></div> : ''}
{movie.Director !== 'N/A' ? <span>director<br /></span> : ''}
{movie.Director !== 'N/A' ? <div>{movie.Director}<br /><br /></div> : ''}
{movie.Genre !== 'N/A' ? <span>genre<br /></span> : ''}
{movie.Genre !== 'N/A' ? <div>{movie.Genre}<br /><br /></div> : ''}
{movie.Plot !== 'N/A' ? <span>plot<br /></span> : ''}
{movie.Plot !== 'N/A' ? <div style={this.state.more ? {fontSize: '12pt'} : undefined}>{movie.Plot && !this.state.more ? movie.Plot.split('').slice(0, 200).join('') + ' ...': movie.Plot}<br /><br /></div> : ''}
</div>
</div>
{!this.state.more ? buttons : more}
</div>
<div className='extra-opacity'></div>
</div>,
this.el)
}
}
const mapStateToProps = (state) => ({
data: state
})
const mapDispatchToProps = (dispatch) => ({
setData: (data) => dispatch(setDataAc(data)),
toggleModal: () => dispatch(toggleModalAc())
})
export default connect(mapStateToProps, mapDispatchToProps)(Modal);
<file_sep>import React, { Component } from 'react';
import { BrowserRouter as Router, Link, Route, Switch } from 'react-router-dom';
import './App.css';
import MovieList from './Components/MovieList';
import Maybe from './Components/Maybe.js';
import Definitely from './Components/Definitely.js';
import MyMovies from './Components/MyMovies';
import Modal from './Components/Modal';
import Login from './Components/Login';
import { connect } from 'react-redux';
import { setDataAc, setChoicesAc, addInputAc } from './Actions'
import { auth } from './firebase.js'
class App extends Component {
constructor() {
super()
this.state = {color: 'white', showDates: [], yearOrRating: 'year'}
this.handleSubmit = this.handleSubmit.bind(this)
this.handleChange = this.handleChange.bind(this)
this.randomPageFetch = this.randomPageFetch.bind(this)
this.categorize = this.categorize.bind(this)
this.quoteToFillTheSpace = this.quoteToFillTheSpace.bind(this)
this.toggleHamburger = this.toggleHamburger.bind(this)
this.clearDates = this.clearDates.bind(this)
}
handleChange(e) {
let value = e.target.value
let change = e.target.name
if (change === 'type') {
this.props.setData(value, 'type')
} else if (change === 'title') {
this.props.setData(value, 'title')
} else if (change === 'year' && this.state.yearOrRating === 'year') {
this.props.setData(value, 'year')
let dateCache = this.props.other.dateCache
if ((value.length >= 4) && (dateCache.hasOwnProperty(value) || value[value.length - 1] === 's')) {
this.props.setData([], 'data')
let moviesByDate = []
if (!isNaN(value.slice(0,4)) && value[value.length - 2] === '0' && value[value.length - 1] === 's') {
let years = Object.keys(dateCache).filter(y => y.slice(0,3) === value.slice(0,3))
for (let year of years) {
let movies = Object.keys(dateCache[year])
for (let movie of movies) {
moviesByDate.push(dateCache[year][movie])
}
}
this.setState({showDates: moviesByDate})
console.log(moviesByDate)
} else if (!isNaN(value.slice(0,4)) && value[value.length - 1] !== 's') {
let movies = Object.keys(dateCache[value])
for (let movie of movies) {
moviesByDate.push(dateCache[value][movie])
}
console.log(moviesByDate)
this.setState({showDates: moviesByDate})
}
} else {
console.log('ok')
this.setState({showDates: []})
}
} else if (change === 'year' && this.state.yearOrRating === 'rating') {
this.props.setData(value, 'year')
let ratingCache = this.props.other.ratingCache
let moviesByRating = []
console.log(ratingCache)
if ((!isNaN(value.slice(0,1))) && ((value.length === 1) || (value[value.length - 1] === '+') || (value[value.length - 1] === '-'))) {
console.log('yepperrooo')
this.props.setData([], 'data')
if (value[value.length - 1] === '+' || value[value.length - 1] === '-') {
let ratings = value[value.length - 1] === '+' ? Object.keys(ratingCache).filter(r => r >= value.slice(0,1)) : Object.keys(ratingCache).filter(r => r <= value.slice(0,1))
for (let rating of ratings) {
let movies = Object.keys(ratingCache[rating])
for (let movie of movies) {
moviesByRating.push(ratingCache[rating][movie])
}
}
} else if (ratingCache.hasOwnProperty(value)) {
let movies = Object.keys(ratingCache[value])
for (let movie of movies) {
moviesByRating.push(ratingCache[value.slice(0,1)][movie])
}
}
console.log(moviesByRating)
moviesByRating.sort((a,b) => Number(b.rating) - Number(a.rating))
this.setState({showDates: moviesByRating})
}
} else if (change === 'year-or-rating') {
console.log(change, value)
this.props.setData('', 'year')
this.setState({yearOrRating: value})
}
}
clearDates() { this.setState({showDates: []}) }
randomPageFetch(apiKey, specificPage, movieType, revert = true) {
let fullUrl = 'https://www.omdbapi.com/?s=' + this.props.other.title + '&page=' + specificPage + movieType + '&apikey=' + apiKey
console.log(specificPage)
fetch(fullUrl)
.then(response => response.json())
.then(data => {
console.log(data)
let checkForPosters;
if (data.hasOwnProperty('Search')) { checkForPosters = data.Search.some(m => m.Poster !== 'N/A') }
if (checkForPosters) {
this.props.setData(data, 'data')
this.props.setData(specificPage, 'currentPage')
} else {
if (revert) {
console.log('reverting to backup')
this.props.setData(this.props.other.dataBackup, 'data')
this.props.setData(1, 'currentPage')
}
}
console.log('we made it')
})
}
handleSubmit(e = false) {
e && e.preventDefault()
let maxFetch = 10;
let specificPage = ''
{/* let apiKey = '1012861a' BACKUP KEY */}
let apiKey = '3d7eed43'
let movieType = '&type=movie'
let year = ''
this.setState({showDates: []})
if (this.props.other.year.length === 4 && !isNaN(year)) {
year = '&y=' + this.props.other.year
}
let fullUrl = 'https://www.omdbapi.com/?s=' + this.props.other.title + movieType + year + '&apikey=' + apiKey
const attemptRandomMovieSearch = () => {
let wordBank = this.props.other.wordBank
let random = Math.floor(Math.random() * wordBank.length)
let randomWord = wordBank[random]
console.log(randomWord)
this.props.setData(randomWord, 'title')
console.log(this.props.other.wordBank[random])
fullUrl = 'https://www.omdbapi.com/?s=' + randomWord + movieType + '&apikey=' + apiKey
/* Word retrieved, look for movies with that word as their title */
fetch(fullUrl)
.then(response => response.json())
.then(data => {
let pageCount;
let checkForPosters;
/* If successful, an object with property Search will come back */
if (data.hasOwnProperty('Search')) {
pageCount = Math.ceil(Number(data.totalResults) / 10)
checkForPosters = data.Search.some(m => m.Poster !== 'N/A')
}
specificPage = Math.floor(Math.random() * pageCount) + 1
/* Fetch again, this time with a random page endpoint */
if (pageCount && checkForPosters) {
this.props.setData(data, 'dataBackup')
this.props.setData(pageCount, 'totalPages')
this.randomPageFetch(apiKey, specificPage, movieType)
} else {
/* If no object with property Search, there was an error. Remove word from wordBank. Start over. */
maxFetch--
let wordBankCopy = [...wordBank]
wordBankCopy.splice(random, 1)
this.props.setData(wordBankCopy, 'wordBank')
if (maxFetch) {
attemptRandomMovieSearch()
} else {
alert('No movies found. Better luck next time.')
}
}
})
}
/* Random Movie selected. Use the random word API to fetch a word */
if (this.props.other.type === 'random-movie') {
attemptRandomMovieSearch();
} else if (this.props.other.type === 'random-page') {
console.log(this.props.other.type)
fetch(fullUrl)
.then(response => response.json())
.then(data => {
let pageCount;
data.hasOwnProperty('Error') ? console.log('Error!!!') : pageCount = Math.ceil(Number(data.totalResults) / 10)
specificPage = Math.floor(Math.random() * pageCount) + 1
if (pageCount !== 1 && pageCount > 1) {
this.props.setData(data, 'dataBackup')
this.props.setData(pageCount, 'totalPages')
this.randomPageFetch(apiKey, specificPage, movieType)
}
})
} else {
let pageCount;
if (this.props.other.title !== '') {
console.log('here')
fetch(fullUrl)
.then(response => response.json())
.then(data => {
if (data.hasOwnProperty('Search')) {
pageCount = Math.ceil(Number(data.totalResults) / 10)
}
specificPage = Math.floor(Math.random() * pageCount) + 1
this.props.setData(data, 'data')
this.props.setData(1, 'currentPage')
this.props.setData(pageCount, 'totalPages')
});
}
}
}
switchPage(input) {
console.log('switchPage')
let didPageTurn;
let apiKey = '3d7eed43'
let movieType = '&type=movie'
const pageTurn = () => {
console.log('pageTurn')
this.props.addInput(input)
}
let currentPage = this.props.other.currentPage
let totalPages = this.props.other.totalPages
if (input === 1) {
if (currentPage < totalPages) { pageTurn() }
didPageTurn = true
console.log('forward')
} else {
if (currentPage > 1) { pageTurn() }
didPageTurn = true
console.log('backward')
}
if (didPageTurn) { this.randomPageFetch(apiKey, currentPage + input, movieType, false) }
console.log(this.props.other.currentPage + ' after randomPageFetch')
}
categorize(category, movie) {
let { maybe, definitely, watched } = this.props.other
let copyDef = [...definitely]
let copyMay = [...maybe]
let copyWat = [...watched]
const checker = (array) => {
let saveIndexHere;
return [array.some((m,i) => {
if (m.imdbID === movie.imdbID) {
console.log(i + ' is the index')
saveIndexHere = i
return true
}
return false
}), saveIndexHere]
}
/* Checks if a movie is already in another list. If so, remove (splice) */
if (category === 'maybe' && maybe.every(m => m.imdbID !== movie.imdbID)) {
let [checkDef, indexDef] = checker(copyDef)
let [checkWat, indexWat] = checker(copyWat)
if (checkDef) { copyDef.splice(indexDef, 1) }
if (checkWat) { copyWat.splice(indexWat, 1) }
console.log('1')
this.props.setChoices([[...copyMay, movie], copyDef, copyWat])
} else if (category === 'definitely' && definitely.every(m => m.imdbID !== movie.imdbID)) {
let [checkMay, indexMay] = checker(copyMay)
let [checkWat, indexWat] = checker(copyWat)
if (checkMay) { copyMay.splice(indexMay, 1) }
if (checkWat) { copyWat.splice(indexWat, 1) }
console.log('2')
this.props.setChoices([copyMay, [...copyDef, movie], copyWat])
} else if (category === 'watched' && watched.every(m => m.imdbID !== movie.imdbID)) {
let [checkDef, indexDef] = checker(copyDef)
let [checkMay, indexMay] = checker(copyMay)
if (checkDef) { copyDef.splice(indexDef, 1) }
if (checkMay) { copyMay.splice(indexMay, 1) }
console.log('3')
this.props.setChoices([copyMay, copyDef, [...copyWat, movie]])
} else {
console.log('should be deleted')
let [checkDef, indexDef] = checker(copyDef)
let [checkMay, indexMay] = checker(copyMay)
let [checkWat, indexWat] = checker(copyWat)
console.log(checkDef)
console.log(checkMay)
console.log(checkWat)
console.log('^^')
if (checkDef) { copyDef.splice(indexDef, 1) }
if (checkMay) { copyMay.splice(indexMay, 1) }
if (checkWat) { copyWat.splice(indexWat, 1) }
console.log('4')
this.props.setChoices([copyMay, copyDef, copyWat])
}
}
quoteToFillTheSpace() {
/* fetch('https://thesimpsonsquoteapi.glitch.me/quotes')
.then(response => response.json())
.then(data => {
this.props.setData(data, 'quote')
console.log(data)
})
.catch(err => console.log(err))
*/
}
toggleHamburger() {
if (window.innerWidth <= 500) {
document.getElementById('menu').classList.toggle('change')
document.querySelector('.nav').classList.toggle('change')
document.getElementById('menu-bg').classList.toggle('change-bg')
}
}
componentDidMount() {
console.log('v1.05')
/*
fetch('https://random-word-api.herokuapp.com/all')
.then(response => response.json())
.then(data => {
let random = Math.floor(Math.random() * data.length)
this.props.setData(data, 'wordBank')
console.log(data[random])
})
*/
auth
.onAuthStateChanged(user => {
if (user) {
this.props.setData(user.email, 'user')
console.log('user logged in: ', user)
} else {
this.props.setData('', 'user')
console.log('user logged out: ', user)
}
})
}
render() {
let { linkMovie, linkMaybe, linkDefinitely, linkWatched, linkLogin } = this.props.other
let inputArea = (
<div className='inputs'>
<select name='type' onChange={this.handleChange} id='types'>
<option value='not-random'>Most Relevant</option>
<option value='random-page'>Random Page Results (with your title)</option>
<option value='random-movie'>Random Movies (with random title)</option>
</select>
<form onSubmit={this.handleSubmit}>
<label>Title: <input type='text' name='title' value={this.props.other.title} onChange={this.handleChange} /></label>
<label>
<select name='year-or-rating' onChange={this.handleChange}>
<option value='year'>Year:</option>
<option value='rating'>Rating:</option>
</select>
<input type='text' name='year' value={this.props.other.year} onChange={this.handleChange} />
</label>
{this.state.yearOrRating === 'year' ? <button>SEARCH</button> : ''}
</form>
</div>
)
let pageScroll = (
<div className='scroll-container'>
<div className='scroll'>
<div onClick={() => this.switchPage(-1)}>Backward</div>
<span>{`${this.props.other.currentPage} / ${this.props.other.totalPages}`}</span>
<div onClick={() => this.switchPage(1)}>Forward</div>
</div>
</div>
)
return (
<div className='top-area'>
<Router>
<nav>
<div className='nav'>
<Link style={{color: linkMovie}} className='link' to="/" onClick={this.toggleHamburger}>Movie Finder</Link>
<Link style={{color: linkMaybe}} className='link' to="/Maybe" onClick={this.toggleHamburger}>Maybe</Link>
<Link style={{color: linkDefinitely}} className='link' to="/Definitely" onClick={this.toggleHamburger}>Definitely</Link>
<Link style={{color: linkWatched}} className='link' to="/Watched" onClick={this.toggleHamburger}>Watched</Link>
<Link style={{color: linkLogin}} className='link link-login' to={this.props.user ? "/Logout" : "/Login"} onClick={this.toggleHamburger}>{this.props.user ? "Logout" : "Login"}</Link>
</div>
<div id='menu-bar'>
<div id='menu' onClick={this.toggleHamburger}>
<div id='bar1' className='bar'></div>
<div id='bar2' className='bar'></div>
<div id='bar3' className='bar'></div>
</div>
</div>
<div id='menu-bg' className='menu-bg'></div>
</nav>
<Route exact path='/' render={() => inputArea}/>
<Switch>
<Route exact path='/' render={() => <MovieList newQuote={this.quoteToFillTheSpace} showDates={this.state.showDates} clearDates={this.clearDates}/>} />
<Route path='/Maybe' render={() => <Maybe newQuote={this.quoteToFillTheSpace}/>} />
<Route path='/Definitely' render={() => <Definitely newQuote={this.quoteToFillTheSpace}/>} />
<Route path='/Watched' render={() => <MyMovies newQuote={this.quoteToFillTheSpace}/> } />
<Route path={['/Login', '/Logout']} render={() => <Login /> } />
</Switch>
<Route exact path='/' render={() => this.props.data.hasOwnProperty('Search') && this.props.data.Search.length > 0 ? pageScroll : ''}/>
</Router>
{this.props.modal && !this.props.other.modalLoading ? <Modal getMovieInfo={this.getMovieInfo} categorize={this.categorize} /> : ''}
{this.props.other.modalLoading ? <div className='modal'><div className='loader'></div></div> : ''}
</div>
)
}
}
/* Creates property keywords for the parts of state you need */
const mapStateToProps = (state) => ({
data: state.data,
modal: state.modal,
other: state,
user: state.user
})
/* Wraps the actions and their dispatch into a method */
const mapDispatchToProps = (dispatch) => ({
setData: (data, prop) => dispatch(setDataAc([data, prop])),
setChoices: (data) => dispatch(setChoicesAc(data)),
addInput: (input) => dispatch(addInputAc(input))
})
/* connect tells react-redux to connect this component to the store */
export default connect(mapStateToProps, mapDispatchToProps)(App);
<file_sep>import React, { Component } from 'react';
import Movie from './Movie'
import { connect } from 'react-redux';
import { setDataAc } from '../Actions'
class Maybe extends Component {
componentDidMount() {
let { maybe, linkMaybe } = this.props.data
maybe.length === 0 && this.props.newQuote()
let linkMaybeCopy = [...linkMaybe]
linkMaybeCopy = 'midnightblue'
this.props.setData(linkMaybeCopy, 'linkMaybe')
}
componentWillUnmount() {
let { linkMaybe } = this.props.data
let linkMaybeCopy = [...linkMaybe]
linkMaybeCopy = 'white'
this.props.setData(linkMaybeCopy, 'linkMaybe')
}
render() {
let { maybe, quote, backupQuote } = this.props.data
let random = Math.floor(Math.random() * backupQuote.length)
return (
<div className='movie-list'>
{maybe ? maybe.map((m, i) => <Movie key={i} data={m} getMovieInfo={this.props.getMovieInfo}/>) : ''}
{maybe.length === 0 ? <div className='quote'><div><span className='marks'>"</span>{quote? quote[0].quote : backupQuote[random]}<span className='marks'>"</span></div></div> : ''}
</div>
)
}
}
const mapStateToProps = (state) => ({
data: state
})
const mapDispatchToProps = (dispatch) => ({
setData: (data, prop) => dispatch(setDataAc([data, prop]))
})
export default connect(mapStateToProps, mapDispatchToProps)(Maybe);
<file_sep># Movie Finder App
Find new movies to watch. Randomly or otherwise. Then, if you'd like, take a quiz about the movies you've watched.
## Getting Started
Fork and Clone this Repo to your local computer
### Prerequisites
```
Must have Node installed version 8.13.0 or higher
Must Have NPM installed version 6.4.1 or higher
Must have react-router-dom version 5.1.2 or higher
Must have redux installed version 4.0.5 or higher
Must have react-redux version 7.2.0 or higher
```
### Installing
```
In your terminal run npm install
to install all the dependencies locally to your desktop
```
## Built With
* [React](https://reactjs.org/) - The web framework used
* [Node Package Mananger](https://docs.npmjs.com/cli/install) - Dependency Management
## Author
* **<NAME>** - *Initial work* - (https://github.com/jadedrb/)
## Deployed Link
Check out [Movie Finder](http://knowledgeable-powder.surge.sh/)!
<file_sep>import React, { Component } from 'react';
import Movie from './Movie'
import { connect } from 'react-redux';
import { setDataAc } from '../Actions'
class Definitely extends Component {
componentDidMount() {
let { definitely, linkDefinitely } = this.props.data
definitely.length === 0 && this.props.newQuote()
let linkDefinitelyCopy = [...linkDefinitely]
linkDefinitelyCopy = 'midnightblue'
this.props.setData(linkDefinitelyCopy, 'linkDefinitely')
}
componentWillUnmount() {
let { linkDefinitely } = this.props.data
let linkDefinitelyCopy = [...linkDefinitely]
linkDefinitelyCopy = 'white'
this.props.setData(linkDefinitelyCopy, 'linkDefinitely')
}
render() {
let { definitely, quote, backupQuote } = this.props.data
let random = Math.floor(Math.random() * backupQuote.length)
return (
<div className='movie-list'>
{definitely ? definitely.map((m, i) => <Movie key={i} data={m} getMovieInfo={this.props.getMovieInfo}/>) : ''}
{definitely.length === 0 ? <div className='quote'><div><span className='marks'>"</span>{quote? quote[0].quote : backupQuote[random]}<span className='marks'>"</span></div></div> : ''}
</div>
)
}
}
const mapStateToProps = (state) => ({
data: state
})
const mapDispatchToProps = (dispatch) => ({
setData: (data, prop) => dispatch(setDataAc([data, prop]))
})
export default connect(mapStateToProps, mapDispatchToProps)(Definitely);
| f31f9d35f0ab8da2eab9f0d9f18fc5b775f71b7e | [
"JavaScript",
"Markdown"
] | 9 | JavaScript | jadedrb/movie-finder | e0307f22cb99faa55ad050d924cf3d8125ab6857 | 961fc69504b75b9c217b279ca0a5fd85205b9faf |
refs/heads/master | <file_sep>//
// UpcommingAsyncResponse.swift
// iOSBaseProject
//
// Created by <NAME> on 3/17/16.
// Copyright ยฉ 2016 Codefuel. All rights reserved.
//
import UIKit
class UpcommingAsyncResponse: NSObject, HttpManagerDelegate {
var datasource:AnyObject?
func fillDataSource(result: NetworkRequestResult) {
switch(result){
case .Empty:
self.datasource = []
case .Failure(let error):
print("Error retrieving matchlist: ", error.description)
self.datasource = []
case .Success(let res):
self.datasource = res["data"].rawValue
print("The datasource:", self.datasource)
}
}
}
<file_sep>//
// HttpHandler.swift
// iOSBaseProject
//
// Created by <NAME> on 3/16/16.
// Copyright ยฉ 2016 Codefuel. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
enum NetworkRequestResult {
case Success(JSON) //response JSON
case Empty
case Failure(NSError)
}
protocol HttpManagerDelegate {
func fillDataSource(result:NetworkRequestResult)
}
enum HTTPMethod: String {
case POST, GET
}
struct requestParameters {
let url:ApiUrl
let urlParam:String?
let body:[String:AnyObject]?
let header:[String : String]?
}
enum ApiUrl:String {
//Add your own!
case BASE = "https://somosportpocdev.herokuapp.com/api/v1.0"
case HOME = "index.php"
case COMPETITION = "competition"
case COMPETITIONBYID = "competition/{:id}"
}
class HttpHandler: NSObject {
var delegate:HttpManagerDelegate?
//This is redundant
func urlBuilder(apiService:ApiUrl, urlParam:String?) -> String {
switch(urlParam){
case .None:
// print("\(ApiUrl.BASE.rawValue)/\(apiService.rawValue)/")
return "\(ApiUrl.BASE.rawValue)/\(apiService.rawValue)/"
case .Some(let param):
// print("\(ApiUrl.BASE.rawValue)/\(apiService.rawValue.stringByReplacingOccurrencesOfString("{:id}", withString: param))/")
return "\(ApiUrl.BASE.rawValue)/\(apiService.rawValue.stringByReplacingOccurrencesOfString("{:id}", withString: param))/"
}
}
//TODO:
//Add check for status code, Emtptyness, etc
func customPOSTRequest(parameters: requestParameters) {
Alamofire.request(.POST, urlBuilder(parameters.url, urlParam: parameters.urlParam), parameters: parameters.body, encoding: .JSON, headers: parameters.header)
.responseJSON{
response in
print("Response JSON: \(response.result.value)")
self.delegate?.fillDataSource(.Success(JSON(response.result.value!)))
}
}
func customGETRequest(parameters: requestParameters) {
Alamofire.request(.GET, urlBuilder(parameters.url, urlParam: parameters.urlParam), parameters: parameters.body, encoding: .JSON, headers: parameters.header)
.responseJSON{
response in
print("Response JSON: \(response.result.value)")
self.delegate?.fillDataSource(.Success(JSON(response.result.value!)))
}
}
}
<file_sep>//
// ViewController.swift
// iOSBaseProject
//
// Created by <NAME> on 3/16/16.
// Copyright ยฉ 2016 Codefuel. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.callApiRequest()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController {
func callApiRequest() {
let http:HttpHandler = HttpHandler()
let req:requestParameters = requestParameters(url:ApiUrl.COMPETITIONBYID, urlParam:"1", body:nil, header: nil)
http.customGETRequest(req)
let res = UpcommingAsyncResponse()
http.delegate = res
}
}
| b3acc598393a06dae9469480d7cee0a1c87f71db | [
"Swift"
] | 3 | Swift | 0xjorgev/iOSBaseProject | 14b3270665e77a2409875b78e6ba79331134f547 | d1acba3b2a2a084252385f4e7b326b1ecf2a375d |
refs/heads/master | <repo_name>tamez/FiveTest<file_sep>/FiveTest/ViewController.swift
//
// ViewController.swift
// FiveTest
//
// Created by <NAME> on 9/2/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
import Parse
class ViewController: UIViewController {
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var signInButton:UIButton!
@IBOutlet weak var signUpButton: UIButton!
@IBAction func SignIn(sender: AnyObject) {
}
@IBAction func SignUp(sender: AnyObject) {
var user = PFUser()
user.username = self.usernameTextField.text
user.password = <PASSWORD>
user.signUpInBackgroundWithBlock { (success, error) -> Void in
}
performSegueWithIdentifier("pushTabBar", sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 5e62b6bd1393a771897ff31e5f0679625238a56a | [
"Swift"
] | 1 | Swift | tamez/FiveTest | 74ea3bbf94e7876fce53a6d791c71d979a92fe75 | a734369b6cdf86c09c95ac971debba71627cce90 |
refs/heads/master | <file_sep>import React, { useState } from 'react'
import PropTypes from 'prop-types'
import './styles.css'
import { ReactComponent as LinkIcon } from '../link-icon.svg'
import { ReactComponent as ArrowIcon } from '../arrow.svg'
function Card({ title, description, date, url, openModal }) {
const [isExpanded, expand] = useState(false)
return (
<article className="card">
<header className="card__header">
<h3 className="card__title">{title}</h3>
<button
className="card__button card__button--secondary"
onClick={() => expand(!isExpanded)}>
{ isExpanded ?
<>
Ocultar detalhes da aรงรฃo
<ArrowIcon className="opened" />
</> :
<>
Ver detalhes da aรงรฃo
<ArrowIcon />
</> }
</button>
</header>
{
isExpanded && (
<div className="card__body">
<div className="card__content">
<p className="card__description">{description}</p>
<button
className="card__button card__button--primary"
onClick={() => openModal()}>
Ver mais
</button>
</div>
<footer className="card__footer">
<small className="card__date">
Publicado em: <time pubdate={date}>{date}</time>
</small>
<a href={url} className="card__source" title="Link da matรฉria" target="_blank">
<LinkIcon/>
</a>
</footer>
</div>
)
}
</article>
)
}
Card.propTypes = {
title: PropTypes.string,
description: PropTypes.string,
content: PropTypes.string,
date: PropTypes.string,
url: PropTypes.string,
openModal: PropTypes.func
}
export default Card
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
import './styles.css'
import { ReactComponent as SearchIcon } from '../search-icon.svg'
function SearchBar({ query, onChange, onSubmit }) {
return (
<div className="search">
<form className="search__form" onSubmit={onSubmit}>
<input
type="text"
className="search__input"
value={ query }
onChange={({ target }) => onChange(target.value)}
/>
<button type="submit" className="search__button">
<SearchIcon/>
</button>
</form>
</div>
)
}
SearchBar.propTypes = {
query: PropTypes.string,
onChange: PropTypes.func,
onSubmit: PropTypes.func
}
export default SearchBar
<file_sep>import React, { useState, useEffect } from 'react'
import CardsList from './CardsList'
import SearchBar from './SearchBar'
import Modal from './Modal'
import api from './config'
const renderModal = handleClick => (
<Modal className="modal">
<div className="modal__content">
<p>Tem certeza que deseja ir para a tela?</p>
<div className="modal__options">
<button className="modal__button modal__button--secondary" onClick={handleClick}>
Nรฃo
</button>
<button className="modal__button" onClick={handleClick}>
Sim
</button>
</div>
</div>
</Modal>
)
async function getNews(callback, query) {
const params = {
country: 'br',
apiKey: 'cad91b838deb423e88eb24107cb27bef',
sortBy: 'publishedAt',
pageSize: 10
}
if (query) { params.q = query }
const response = await api.get('top-headlines', { params })
callback(response.data.articles)
}
function App() {
const [news, updateNews] = useState([])
const [query, setQuery] = useState('')
const [modalSelected, switchModal] = useState(false)
const onQueryChange = value => setQuery(value)
const handleSearch = event => {
event.preventDefault()
getNews(updateNews, query)
}
const handleModalClick = () => switchModal(false)
useEffect(() => { getNews(updateNews) }, [])
return (
<>
<div className="container">
<SearchBar
query={query}
onChange={onQueryChange}
onSubmit={handleSearch}
/>
<CardsList
cards={news}
openModal={() => switchModal(true)}
/>
</div>
{ modalSelected && renderModal(handleModalClick) }
</>
)
}
export default App
| 77cef0e23da656e038cd2e37792601c3a6bcc97c | [
"JavaScript"
] | 3 | JavaScript | fabioper/cards-filtering | aa209836f531d4e0fcc6be2b410c97301e62cc94 | b91cc13ceab5520caced40c22bb3df7217e26e21 |
refs/heads/master | <repo_name>rayder13/PyFronius<file_sep>/todo.md
# Todo
Its a todo list... get it done.
## Must do
* ~~Read data from needed of the Fronius endpoints.~~
* Calculate energy produced directly consumed and produced exported to grid outside pv generation.
* Store that data locally, at least long enough to perform calculations.
* Store base and calculated data into a central location for visualisation. Either local db or influx for Graphana/Home Assistant.
## Extras to get to once it actually works
* Calculate cost data
## If I can figure it out
<file_sep>/code/fronius_data.py
# TODO Store Fronius JSON data for calculations?
# TODO Hourly/daily/weekly/monthly production data
# TODO Hourly/daily/weekly/monthly usage data
# TODO Hourly/daily/weekly/monthly relative usage data
# TODO Overall net positive or net negative supply and costing -/+
import json
import requests
import time
import sys
#Set debug on/off ---- maybe set to an arg for release debugging?
isDebug = False
# Fronius API
# Inverter IP/Host address ---- do i need to use meter endpoint or can i calculate everything i need from powerflow endpoint?
inverterAddr = "192.168.20.5"
inverterMtrEndPt = "/solar_api/v1/GetMeterRealtimeData.cgi?Scope=Device&DeviceId=0"
inverterPfEndPt = "/solar_api/v1/GetPowerFlowRealtimeData.fcgi"
# Options
requestInterval = 60 # Should be 60 seconds for remotely accurate readings
energyUsedHrAvg = 0
energyUsedHrRunning = 0
energyUsedHrCount = 0
# Run until closed out by the user or an uncaught error
while True:
try :
# Get Fronius JSON data and loads it into jsonPfData for use
jsonResponse = requests.get("http://" + inverterAddr + inverterPfEndPt)
jsonPfData = json.loads(jsonResponse.text)
# From Fronius API documentation
# P_Grid - this value is null if no meter is enabled ( + from grid , - to grid )
# P_Load - this value is null if no meter is enabled ( + generator , - consumer )
# P_PV - this value is null if inverter is not running ( + production ( default ) )
# So...
# "P_Grid" : 113.05, - drawing 113.05w FROM the grid
# "P_Load" : -1223.05, - total load
# "P_PV" : 1110, PV panels generating 1110w
# Don't catch NULL for P_Load or P_Grid. If these values are null, you don't have a
# meter and can't log the production/usage data anyways
froniusPLoad = jsonPfData['Body']['Data']['Site']['P_Load']
froniusPGrid = jsonPfData['Body']['Data']['Site']['P_Grid']
# Catch NULL as documentation says it will return NULL if the inverter is not running
# e.g PV panels are not producing any power
try :
froniusPPv = jsonPfData['Body']['Data']['Site']['P_Pv']
except KeyError :
froniusPPv = 0
if jsonPfData['Body']['Data']['Site']['P_Load'] >= 0 :
print('Feeding in ' + str(froniusPLoad) + 'w to the grid')
if energyUsedHrCount <= 60 :
energyUsedHrCount += 1
energyUsedHrRunning += int(froniusPLoad)
energyUsedHrAvg = energyUsedHrRunning / energyUsedHrCount
else :
energyUsedHrCount = 1
energyUsedHrRunning = 0
energyUsedHrAvg = 0
print('kWh average for the current hour: ' + str(energyUsedHrAvg))
time.sleep(requestInterval)
elif jsonPfData['Body']['Data']['Site']['P_Load'] < 0 :
print('Drawing ' + str(froniusPLoad * -1) + 'w from the grid')
if energyUsedHrCount <= 60 :
energyUsedHrCount += 1
energyUsedHrRunning += int(froniusPLoad * -1)
energyUsedHrAvg = energyUsedHrRunning / 60
else :
energyUsedHrCount = 1
energyUsedHrRunning = 0
energyUsedHrAvg = 0
print('Wh average for the current hour: ' + str(energyUsedHrAvg))
time.sleep(requestInterval)
except KeyboardInterrupt :
print('Ctrl-C Interrupt detected')
sys.exit()
<file_sep>/README.md
# PyFronius
## Why am i making this?
While I understand there is already a lot of resources available to do this task, I am using it as yet another task to solve while learning Python.
Plus, it allows me to customise to my own needs instead of just starting out as a "one size fits all" script.
| c92e7b32e3b317e26b6beb161f9f2792306a60e9 | [
"Markdown",
"Python"
] | 3 | Markdown | rayder13/PyFronius | 99c633dc909d2e762c2940f743a5ccbd86d193c1 | c948658c5d6256128c37900ff64bff65c53b5e56 |
refs/heads/main | <repo_name>MariyahA/Mariyah_A_ClosureExercise<file_sep>/Mariyah_A_ClosureExercise.playground/Contents.swift
import UIKit
var Mult = {(Num1: Int, Num2: Int) -> Int in
return Num1 * Num2
}
let Product = Mult(123, 2)
print( Product )
| f5ecc7e9f99c961e0685f7c2d64db50135bda000 | [
"Swift"
] | 1 | Swift | MariyahA/Mariyah_A_ClosureExercise | b4816013b5d6eb2f09bc320f8b74cada69567ac3 | 7e2a80f01cc82674862ceb9efd629d6561d0e08f |
refs/heads/master | <repo_name>mikhkita/ur-ksmot-oselok<file_sep>/js/admin.js
var customHandlers = [];
$(document).ready(function(){
var myWidth,
myHeight,
title = window.location.href,
titleVar = ( title.split("localhost").length > 1 )?4:3,
progress = new KitProgress("#FFF",3);
progress.endDuration = 0.3;
title = title.split(/[\/#?]+/);
title = title[titleVar];
$(".yiiPager .page.selected").click(function(){return false;});
$(".modules li[data-name='"+title+"'],.modules li[data-nameAlt='"+title+"']").addClass("active");
function whenResize(){
if( typeof( window.innerWidth ) == 'number' ) {
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth ||
document.documentElement.clientHeight ) ) {
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
$("body,html").css("height",myHeight);
$(".main").css("height",myHeight-50);
}
$(window).resize(whenResize);
whenResize();
if( $.cookie('textarea-rows') ) $("#b-textarea-rows").val($.cookie('textarea-rows'));
$("body").on("change","#b-textarea-rows",changeText);
changeText();
function changeText(){
$("table textarea").attr("rows",$("#b-textarea-rows").val());
$.cookie('textarea-rows',$("#b-textarea-rows").val(), { expires: 7, path: '/' });
}
function bindFancy(){
$(".fancy-img").fancybox({
padding : 0
});
$(".fancy").each(function(){
var $popup = $($(this).attr("data-block")),
$this = $(this);
$this.fancybox({
padding : 0,
content : $popup,
helpers: {
overlay: {
locked: true
}
},
beforeShow: function(){
$popup.find(".custom-field").remove();
if( $this.attr("data-value") ){
var name = getNextField($popup.find("form"));
$popup.find("form").append("<input type='hidden' class='custom-field' name='"+name+"' value='"+$this.attr("data-value")+"'/><input type='hidden' class='custom-field' name='"+name+"-name' value='"+$this.attr("data-name")+"'/>");
}
if( $this.attr("data-beforeShow") && customHandlers[$this.attr("data-beforeShow")] ){
customHandlers[$this.attr("data-beforeShow")]($this);
}
},
afterShow: function(){
if( $this.attr("data-afterShow") && customHandlers[$this.attr("data-afterShow")] ){
customHandlers[$this.attr("data-afterShow")]($this);
}
},
beforeClose: function(){
if( $this.attr("data-beforeClose") && customHandlers[$this.attr("data-beforeClose")] ){
customHandlers[$this.attr("data-beforeClose")]($this);
}
},
afterClose: function(){
if( $this.attr("data-afterClose") && customHandlers[$this.attr("data-afterClose")] ){
customHandlers[$this.attr("data-afterClose")]($this);
}
}
});
});
}
$(".ajax-update,.ajax-create").fancybox({
type: "ajax",
helpers: {
overlay: {
locked: true
},
title : null
},
padding: 0,
margin: 30,
beforeShow: function(){
var $form = $(".fancybox-inner form");
bindForm($form);
bindImageUploader();
bindTinymce();
bindSelectDynamic();
bindAutocomplete();
bindTooltip();
bindDoubleList();
if( $form.attr("data-beforeShow") && customHandlers[$form.attr("data-beforeShow")] ){
customHandlers[$form.attr("data-beforeShow")]($form);
}
},
afterClose:function(){
unbindTinymce();
},
afterShow: function(){
var $form = $(".fancybox-inner form");
bindVariants();
$(".fancybox-inner").find("input").eq(($form.attr("data-input"))?($form.attr("data-input")*1):0).focus();
}
});
$(document).on("click",".ajax-refresh, .ajax-archive",function(){
blockTr($(this).parents("tr"));
$(".qtip").remove();
progress.setColor("#D26A44");
progress.start(3);
$.ajax({
url: $(this).attr("href"),
success: function(msg){
progress.end(function(){
$(".qtip").remove();
setResult(msg);
});
}
});
return false;
});
$(document).on("click",".b-delete-selected,.b-nav-delete",function(){
progress.setColor("#D26A44");
progress.start(3);
var ids = [],
obj = $(this);
if(obj.hasClass("b-delete-selected")) {
for (var i = 0; i < $(".yahoo-list li.selected").length; i++) {
ids.push($("li.selected").eq(i).attr("data-id"));
}
} else {
ids.push(obj.closest("li").attr("data-id"));
}
$("#b-filter-form").append("<input type='hidden' name='delete' value='"+JSON.stringify(ids)+"'>");
$.ajax({
method: "POST",
url: document.location.href.replace("#","")+( (document.location.href.indexOf('?') == -1)?"?":"&" )+"partial=1",// ะกะดะตะปะฐัั ? ะธะปะธ &
data: $("#b-filter-form").serialize(),
beforeSend: function() {
$('.b-delete-selected').hide();
},
success: function(msg){
$(".qtip").remove();
progress.end(function(){
setResult(msg);
$(".qtip").remove();
});
}
});
return false;
});
function blockTr(el){
el.addClass("b-refresh");
el.click(function(){
return false;
});
}
$(document).on("click",".ajax-delete", function(){
var warning = ($(this).attr("data-warning"))?$(this).attr("data-warning"):"ะั ะดะตะนััะฒะธัะตะปัะฝะพ ั
ะพัะธัะต ัะดะฐะปะธัั</br>ะทะฐะฟะธัั?";
warning += ( $(this).parents(".b-table").attr("data-warning") )?"<br><b>"+$(this).parents(".b-table").attr("data-warning")+"</b>":"";
$.fancybox.open({
padding: 0,
content: '<div class="b-popup b-popup-delete"><h1>'+warning+'</h1><div class="row buttons"><input type="button" class="b-delete-yes" value="ะะฐ"><input type="button" onclick="$.fancybox.close();" value="ะะตั"></div></div>'
});
bindDelete($(this).attr("href"));
return false;
});
function setResult(html){
$(".b-main-center").html(html);
setTimeout(function(){
bindFilter();
bindTooltip();
bindAutocomplete();
bindYahoo();
bindFancy();
$(".b-refresh").removeClass("b-refresh").addClass("b-refresh-out");
},100);
}
function bindDelete(url){
$(document).unbind("keypress");
$(document).bind("keypress",function( event ) {
if ( event.which == 13 ) {
$(".fancybox-inner .b-delete-yes").click();
}
});
$(".fancybox-inner .b-delete-yes").click(function(){
progress.setColor("#FFF");
progress.start(3);
url = ( $(".main form").length ) ? (url+"&"+$(".main form").serialize()) : url;
$.ajax({
url: url,
success: function(msg){
progress.end(function(){
setResult(msg);
});
$.fancybox.close();
}
});
});
}
function bindFilter(){
if( $(".main .b-filter").length ){
$(".main form select, .main form input").bind("change",function(){
var $form = $(this).parents("form");
progress.setColor("#D26A44");
progress.start(3);
$.ajax({
url: "?partial=true&"+$form.serialize(),
success: function(msg){
progress.end(function(){
setResult(msg);
history.pushState(null, null, '?'+$form.serialize());
});
}
});
});
$(".main form").submit(function(){
return false;
});
$(".b-clear-filter").click(function(){
$(".main form select,.main form input").val("");
$(".main form select,.main form input").eq(0).trigger("change");
return false;
});
}
}
function bindForm($form){
$(".select2").select2({
placeholder: "",
allowClear: true
});
$form.validate({
ignore: ""
});
$(".numeric").numericInput({ allowFloat: true, allowNegative: true });
$form.submit(function(e,a){
tinymce.triggerSave();
if( $(this).valid() && !$(this).find("input[type=submit]").hasClass("blocked") ){
var $form = $(this),
url = $form.attr("action");
$(this).find("input[type=submit]").addClass("blocked");
if( a == false ){
$form.find("input[type='text'],input[type='number'],textarea").val("");
$form.find("input").eq(0).focus();
}
progress.setColor("#FFF");
progress.start(3);
url = ( $(".main form").length ) ? (url+( (url.split("?").length>1)?"&":"?" )+$(".main form").serialize()) : url;
if( $form.attr("data-beforeAjax") && customHandlers[$form.attr("data-beforeAjax")] ){
customHandlers[$form.attr("data-beforeAjax")]($form);
}
$.ajax({
type: $form.attr("method"),
url: url,
data: $form.serialize(),
success: function(msg){
progress.end(function(){
$form.find("input[type=submit]").removeClass("blocked");
setResult(msg);
});
if( a != false ){
$.fancybox.close();
}
}
});
}else{
$(".fancybox-overlay").animate({
scrollTop : 0
},200);
}
return false;
});
// $(".b-input-image").change(function(){
// if( $(this).val() != "" ){
// $(".b-input-image-add").addClass("hidden");
// $(".b-image-wrap").removeClass("hidden");
// $(".b-input-image-img").css("background-image","url('"+$(".b-input-image-img").attr("data-base")+"/"+$(this).val()+"')");
// }else{
// $(".b-input-image-add").removeClass("hidden");
// $(".b-image-wrap").addClass("hidden");
// }
// });
// // ะฃะดะฐะปะตะฝะธะต ะธะทะพะฑัะฐะถะตะฝะธั
// $(".b-image-delete").click(function(){
// $(".b-image-cancel").attr("data-url",$(".b-input-image").val())// ะกะพั
ัะฐะฝัะตะผ ะฟัะตะดัะดััะตะต ะธะทะพะฑัะฐะถะตะฝะธะต ะดะปั ัะพะณะพ, ััะพะฑั ะผะพะถะฝะพ ะฑัะปะพ ะฒะพัััะฐะฝะพะฒะธัั
// .show();// ะะพะบะฐะทัะฒะฐะตะผ ะบะฝะพะฟะบั ะพัะผะตะฝั ัะดะฐะปะตะฝะธั
// $(".b-input-image").val("").trigger("change");// ะฃะดะฐะปัะตะผ ัััะปะบั ะฝะฐ ัะพัะบั ะธะท ะฟะพะปั
// });
// // ะัะผะตะฝะฐ ัะดะฐะปะตะฝะธั
// $(".b-image-cancel").click(function(){
// $(".b-input-image").val($(".b-image-cancel").attr("data-url")).trigger("change")// ะะพะทะฒัะฐัะฐะตะผ ัะพั
ัะฐะฝะตะฝะฝัั ัััะปะบั ะฝะฐ ะธะทะพะฑัะฐะถะตะฝะธะต ะฒ ะฟะพะปะต
// $(".b-image-cancel").hide(); // ะัััะตะผ ะบะฝะพะฟะบั ะพัะผะตะฝั ัะดะฐะปะตะฝะธั
// });
}
function bindImageUploader(){
$(".b-get-image").click(function(){
$(".b-for-image-form").load($(".b-get-image").attr("data-path"), {}, function(){
$(".upload").addClass("upload-show");
$(".b-upload-overlay").addClass("b-upload-overlay-show")
$(".plupload_cancel,.b-upload-overlay,.plupload_save").click(function(){
$(".b-upload-overlay").removeClass("b-upload-overlay-show");
$(".upload").addClass("upload-hide");
setTimeout(function(){
$(".b-for-image-form").html("");
},400);
return false;
});
$(".plupload_save").click(function(){
$(".b-input-image").val($(".b-input-image-img").attr("data-path")+"/"+$("input[name='uploaderPj_0_tmpname']").val()).trigger("change");
});
});
});
}
/* TinyMCE ------------------------------------- TinyMCE */
function bindTinymce(){
if( $("#tinymce").length ){
tinymce.init({
selector : "#tinymce",
width: '700px',
height: '500px',
language: 'ru',
plugins: 'image table autolink emoticons textcolor charmap directionality colorpicker media contextmenu link textcolor responsivefilemanager',
skin: 'kit-mini',
toolbar: 'undo redo bold italic forecolor alignleft aligncenter alignright alignjustify bullist numlist outdent indent link image',
onchange_callback: function(editor) {
tinymce.triggerSave();
$("#" + editor.id).valid();
},
image_advtab: true ,
external_filemanager_path:"/filemanager/",
filemanager_title:"ะคะฐะนะปะพะฒัะน ะผะตะฝะตะดะถะตั" ,
external_plugins: { "filemanager" : "/filemanager/plugin.min.js"}
});
}
}
function unbindTinymce(){
tinymce.remove();
}
/* TinyMCE ------------------------------------- TinyMCE */
/* Preloader ----------------------------------- Preloader */
function setPreloader(el){
var str = '<div class="circle-cont">';
for( var i = 1 ; i <= 3 ; i++ ) str += '<div class="c-el c-el-'+i+'"></div>';
el.append(str+'</div>').addClass("blocked");
}
function removePreloader(el){
el.removeClass("blocked").find(".circle-cont").remove();
}
/* Preloader ----------------------------------- Preloader */
/* Hot keys ------------------------------------ Hot keys */
var cmddown = false,
ctrldown = false;
function down(e){
// alert(e.keyCode);
if( e.keyCode == 13 && ( cmddown || ctrldown ) ){
if( !$(".b-popup form").length ){
$(".ajax-create").click();
}else{
$(".fancybox-wrap form").trigger("submit",[false]);
}
}
if( e.keyCode == 13 ){
enterVariantsHandler();
}
if( e.keyCode == 91 ) cmddown = true;
if( e.keyCode == 17 ) ctrldown = true;
if( e.keyCode == 27 && $(".fancybox-wrap").length ) $.fancybox.close();
}
function up(e){
if( e.keyCode == 91 ) cmddown = false;
if( e.keyCode == 17 ) ctrldown = false;
}
if( $(".ajax-create").length ){
$(document).keydown(down);
$(document).keyup(up);
}
/* Hot keys ------------------------------------ Hot keys */
/* ะ ะตะดะฐะบัะธัะพะฒะฐะฝะธะต ัะฐะฑะปะธั ------------------------------------ ะ ะตะดะฐะบัะธัะพะฒะฐะฝะธะต ัะฐะฑะปะธั */
function downTable(e,el){
if( e.keyCode == 86 && ( cmddown || ctrldown ) ){
el.val("");
setTimeout(function(){ pasteHandler(el); },10);
}
if( e.keyCode == 91 ) cmddown = true;
if( e.keyCode == 17 ) ctrldown = true;
}
function upTable(e){
if( e.keyCode == 91 ) cmddown = false;
if( e.keyCode == 17 ) ctrldown = false;
}
function pasteHandler(el){
var splitted = el.val().split("\n");
for( i in splitted ){
splitted[i] = splitted[i].split("\t");
}
console.log(splitted);
var table = el.parents("table"),
colCount = el.parents("tr").find("td").length-1,
rowCount = table.find("tr").length-1,
colCur = el.parents("td").index()-1,
rowCur = el.parents("tr").index(),
rowTo = (splitted.length-1 <= rowCount-rowCur)?(splitted.length-1):(rowCount-rowCur),
colTo = (splitted[0].length-1 <= colCount-colCur)?(splitted[0].length-1):(colCount-colCur);
for (var i = 0; i <= rowTo ; i++) {
var rowNum = rowCur + i;
for (var j = 0; j <= colTo ; j++) {
var colNum = colCur + j;
table.find("tr").eq(rowNum).find("td").eq(colNum).find("textarea").val(splitted[i][j]);
}
}
// alert([rowCur,colTo,rowNum,colNum]);
}
if( $(".b-table.b-data").length ){
$(".b-table-td-editable textarea").keydown(function(e){
downTable(e,$(this));
});
$(document).keyup(upTable);
}
/* ะ ะตะดะฐะบัะธัะพะฒะฐะฝะธะต ัะฐะฑะปะธั ------------------------------------ ะ ะตะดะฐะบัะธัะพะฒะฐะฝะธะต ัะฐะฑะปะธั */
/* Autocomplete -------------------------------- Autocomplete */
function bindAutocomplete(){
if( $(".autocomplete").length ){
var i = 0;
$(".autocomplete").each(function(){
i++;
$(this).wrap("<div class='autocomplete-cont'></div>");
var $this = $(this),
data = JSON.parse($this.attr("data-values"));
$this.removeAttr("data-values");
var $cont = $this.parent("div"),
$clone = $this.clone(),
$label = $this.clone();
$clone.removeAttr("required")
.attr("name","clone-"+i)
.attr("class","clone");
$label.removeAttr("required")
.attr("name","label-"+i)
.attr("class","label")
.val($this.attr("data-label"))
.attr("readonly","readonly");
$this.attr("type","hidden").removeClass("autocomplete");
$cont.prepend($clone);
$cont.prepend($label);
if( $this.hasClass("categories") ){
$clone.catcomplete({
minLength: 0,
delay: 0,
source: data,
appendTo: $cont,
select: function( event, ui ) {
$clone.val(ui.item.label);
$label.show().val(ui.item.label);
$this.val(ui.item.val).trigger("change");
return false;
},
focus: function( event, ui ) {
// $(".ui-menu-item").each(function(){
// alert($(this).attr("class"));
// });
}
});
}else{
$clone.autocomplete({
minLength: 0,
delay: 0,
source: data,
appendTo: $cont,
select: function( event, ui ) {
$clone.val(ui.item.label);
$label.show().val(ui.item.label);
$this.val(ui.item.val).trigger("change");
return false;
}
});
}
$clone.blur(function(){
$label.show();
});
$label.on("click focus",function(){
$label.hide();
$clone.val("").select();
if( $this.hasClass("categories") ){
$clone.catcomplete('search');
}else{
$clone.autocomplete('search');
}
});
});
}
}
$.widget( "custom.catcomplete", $.ui.autocomplete, {
_create: function() {
this._super();
this.widget().menu( "option", "items", "> :not(.ui-autocomplete-category)" );
},
_renderMenu: function( ul, items ) {
var that = this,
currentCategory = "";
$.each( items, function( index, item ) {
var li;
if ( item.category != currentCategory ) {
ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
currentCategory = item.category;
}
li = that._renderItemData( ul, item );
if ( item.category ) {
li.attr( "aria-label", item.category + " : " + item.label );
}
});
}
});
/* Autocomplete -------------------------------- Autocomplete */
/* Tooltip ------------------------------------- Tooltip */
function bindTooltip(){
bindTooltipSkin(".b-tooltip, .b-panel-icons-item a,.b-tool, .b-image-nav, .b-help, .b-title","qtip-light");
}
function bindTooltipSkin(selector,skin){
$(selector).qtip('destroy', true);
$(selector).qtip({
position: {
my: 'bottom center',
at: 'top center'
},
style: {
classes: skin+' qtip-shadow qtip-rounded'
},
show: {
delay: 500
}
});
}
/* Tooltip ------------------------------------- Tooltip */
/* Double-list --------------------------------- Double-list */
function bindDoubleList(){
if( $(".double-list").length ){
$("#sortable1").sortable({
connectWith: ".connectedSortable",
update: function( event, ui ) {
customHandlers["sortList"]();
}
}).disableSelection();
$("#sortable2").sortable({
update: function( event, ui ) {
$("#sortable2 span").remove();
$("#sortable2 li").append("<span></span>");
}
}).disableSelection();
customHandlers["sortList"]();
}
}
$("body").on("click",".double-list li span",function(){
$("#sortable1").prepend($(this).parents("li"));
customHandlers["sortList"]();
});
customHandlers["attributesAjax"] = function($form){
$("#sortable1 input").remove();
}
customHandlers["sortList"] = function(){
var min = "&";
$("#sortable1 li").each(function(){
var max = "โ";
$("#sortable1 li").each(function(){
var curId = $(this).attr("data-id");
if(curId < max && curId > min){
max = curId;
}
});
min = max;
$("#sortable1").append($("#sortable1 li[data-id='"+min+"']"));
});
}
/* Double-list --------------------------------- Double-list */
/* Variants ------------------------------------ Variants */
$("body").on("click","#add-variant",function(){
$(".b-variant-cont .error").addClass("hidden");
if( !$("#new-variant").hasClass("hidden") ){
// ะัะปะธ ะฒะฒะพะดะธะปะธ ะฒ ะธะฝะฟัั
var val = $("#new-variant").val();
if( !tryToAddVariant(val) ){
$(".b-variant-cont .error-single").removeClass("hidden");
}
}else{
// ะัะปะธ ะฒะฒะพะดะธะปะธ ะฒ ะธะฝะฟัั textarea
var val = $("#new-variant-list").val(),
tmpArr = val.split("\n"),
tmpError = new Array();
for( var i in tmpArr ){
if( !tryToAddVariant(tmpArr[i]) && tmpArr[i] != "" ){
tmpError.push(tmpArr[i]);
}
}
if( tmpError.length ){
$(".b-variant-cont .error-list").removeClass("hidden");
}
$("#new-variant-list").val(tmpError.join("\n"));
}
$((!$("#new-variant").hasClass("hidden"))?"#new-variant":"#new-variant-list").focus();
updateVariantsSort();
$.fancybox.update();
});
$("body").on("click","#b-variants li span",function(){
if( confirm("ะัะปะธ ัะดะฐะปะธัั ััะพั ะฒะฐัะธะฐะฝั, ัะพ ะฒะพ ะฒัะตั
ัะพะฒะฐัะฐั
, ะณะดะต ะฑัะป ะฒัะฑัะฐะฝ ะธะผะตะฝะฝะพ ััะพั ะฒะฐัะธะฐะฝั ะฑัะดะตั ะฟัััะพะต ะทะฝะฐัะตะฝะธะต ะฐััะธะฑััะฐ. ะะพะดัะฒะตัะดะธัั ัะดะฐะปะตะฝะธะต?") ){
$(this).parents("li").remove();
updateVariantsSort();
$.fancybox.update();
}
});
$("body").on("click",".b-variant-cont .b-set-list",function(){
$("#new-variant-list, .b-variant-cont .b-set-single").show();
$("#new-variant, .b-variant-cont .b-set-list").hide().addClass("hidden");
$("#new-variant-list").focus();
$.fancybox.update();
});
$("body").on("click",".b-variant-cont .b-set-single",function(){
$("#new-variant-list, .b-variant-cont .b-set-single").hide();
$("#new-variant, .b-variant-cont .b-set-list").show().removeClass("hidden");
$("#new-variant").focus();
$.fancybox.update();
});
function tryToAddVariant(val){
val = regexVariant(val);
if( val != "" ){
if( !$("input[data-name='"+val.toLowerCase()+"']").length ){
$("#b-variants ul").append("<li><p>"+val+"</p><span></span><input data-name=\""+val.toLowerCase()+"\" type=\"hidden\" name=\"VariantsNew["+val+"]\" value=\"\"></li>");
$("#new-variant").val("");
return true;
}
}
return false;
}
function regexVariant(val){
var regArr;
switch( $("#new-variant").attr("data-type") ) {
case "float":
regArr = /^[^\d-]*(-{0,1}\d*\.{0,1}\d+)[\D]*$/.exec(val);
break;
case "int":
regArr = /^[^\d-]*(-{0,1}\d+)[\D]*$/.exec(val);
break;
default:
regArr = ["",val];
break;
}
return ( regArr != null )?regArr[1]:"";
}
function updateVariantsSort(){
var i = 0;
$("#b-variants ul li").each(function(){
i+=10;
$(this).find("input").val(i);
});
}
function enterVariantsHandler(){
if( !$(".b-variant-cont input[type='text']").hasClass("hidden") ){
$("#add-variant").click();
}
}
function bindVariants(){
if( $("#b-variants").length ){
$("#b-variants .sortable").sortable({
update: function( event, ui ) {
updateVariantsSort();
}
}).disableSelection();
switch( $("#new-variant").attr("data-type") ) {
case "float":
$("#new-variant").numericInput({ allowFloat: true, allowNegative: true });
break;
case "int":
$("#new-variant").numericInput({ allowFloat: false, allowNegative: true });
break;
}
}
}
/* Variants ------------------------------------ Variants */
/* Dynamic ------------------------------------- Dynamic */
function bindSelectDynamic(){
if( $(".b-select-dynamic").length ){
$(".b-select-dynamic").change(function(){
var $form = $(this).parents("form");
progress.setColor("#FFF");
progress.start(3);
$.ajax({
type: "POST",
url: $form.attr("action"),
data: $form.serialize(),
success: function(msg){
progress.end(function(){
$(".fancybox-inner").html(msg);
bindSelectDynamic();
});
}
});
});
}
}
if( $(".b-dynamic select").length ){
$(".b-dynamic .b-select-all").click(function(){
$(this).parents(".b-dynamic").find("ul li").addClass("selected");
return false;
});
$(".b-dynamic .b-select-none").click(function(){
$(this).parents(".b-dynamic").find("ul li").removeClass("selected");
return false;
});
}
/* Dynamic ------------------------------------- Dynamic */
/* Auction ------------------------------------- Auction */
var refreshTimeout = 5000;
if( $(".b-auction-table").length ){
setTimeout(function run(){
console.log(progress.isBlocked());
if( !progress.isBlocked() ){
$.ajax({
url: $(".b-auction-table").attr("data-url"),
success: function(msg){
setAuctionResults(msg);
console.log("refreshed");
}
});
}
setTimeout(run,refreshTimeout);
},refreshTimeout);
$("body").mousemove(function(){
if( $("td.b-refreshed").length )
$("td.b-refreshed").removeClass("b-refreshed").addClass("b-refreshed-out");
});
}
function setAuctionResults(msg){
var json = JSON.parse(msg);
for( var i in json ){
var tr = $(".b-auction-table tr[data-id='"+json[i].id+"']");
if( json[i].date != tr.find("td[data-field='date']").text() ) tr.find("td[data-field='date']").removeClass("b-refreshed-out").addClass("b-refreshed");
tr.find("td[data-field='date']").html(json[i].date);
if( json[i].current_price != tr.find("td[data-field='current_price']").text() ) tr.find("td[data-field='current_price']").removeClass("b-refreshed-out").addClass("b-refreshed");
tr.find("td[data-field='current_price']").html(json[i].current_price);
if( json[i].state != tr.find("td[data-field='state']").text() ) tr.find("td[data-field='state']").removeClass("b-refreshed-out").addClass("b-refreshed");
tr.find("td[data-field='state']").html(json[i].state);
}
}
/* Auction ------------------------------------- Auction */
/* Yahoo ------------------------------------- Yahoo */
var yahooTog = false;
function checkDelete(){
if( $(".yahoo-list li.selected").length ){
$(".b-delete-selected").show();
}else{
$(".b-delete-selected").hide();
}
if( $(".yahoo-list li").length == $(".yahoo-list li.selected").length ){
$(".b-select-all").text("ะกะฝััั ะฒัะดะตะปะตะฝะธะต");
}else{
$(".b-select-all").text("ะัะดะตะปะธัั ะฒัะต");
}
}
function bindYahoo(){
if( $(".yahoo-list").length ){
$(".b-delete-selected").hide();
$(".b-select-all").click(function(){
if( $(".yahoo-list li").length == $(".yahoo-list li.selected").length ){
$(".yahoo-list li").removeClass("selected");
}else{
$(".yahoo-list li").addClass("selected");
}
checkDelete();
});
$(".yahoo-list li span, .yahoo-list li a").mousedown(function(){
yahooTog = true;
});
$(".yahoo-list li").mouseup(function(){
if( yahooTog ){
yahooTog = false;
return false;
}
yahooTog = false;
$(this).toggleClass("selected");
checkDelete();
});
}
}
if( $(".yahoo-list").length ){
bindYahoo();
}
/* Yahoo ------------------------------------- Yahoo */
/* Filter Pagination ------------------------- Filter Pagination */
if( $(".b-filter-pagination").length ){
$("body").on("click",".b-filter-pagination .yiiPager a",function(){
$("#b-filter-form").attr("action",$(this).attr("href")).submit();
return false;
});
$("body").on("click",".b-clear-filter-form",function(){
$("#b-filter-form input[class!='hidden'], #b-filter-form select[class!='hidden']").remove();
$("#b-filter-form").submit();
return false;
});
$("body").on("change","#b-sort-1",function(){
$("#b-sort-2").val($(this).val());
$("#b-filter-form").submit();
});
$("body").on("change","#b-order-1",function(){
$("#b-order-2").val($(this).val());
$("#b-filter-form").submit();
});
}
/* Filter Pagination ------------------------- Filter Pagination */
function transition(el,dur){
el.css({
"-webkit-transition": "all "+dur+"s ease-in-out", "-moz-transition": "all "+dur+"s ease-in-out", "-o-transition": "all "+dur+"s ease-in-out", "transition": "all "+dur+"s ease-in-out"
});
}
bindFancy();
bindFilter();
bindAutocomplete();
bindTooltip();
bindImageUploader();
});<file_sep>/photodoska/excel.php
<?php
require_once 'Classes/PHPExcel.php'; // ะะพะดะบะปััะฐะตะผ ะฑะธะฑะปะธะพัะตะบั PHPExcel
$uploadDir = "upload/tmp";
$excelDir = "upload/excel";
function WriteExcel($data){
global $excelDir;
$phpexcel = new PHPExcel(); // ะกะพะทะดะฐัะผ ะพะฑัะตะบั PHPExcel
$filename = "example.xlsx";
/* ะะฐะถะดัะน ัะฐะท ะดะตะปะฐะตะผ ะฐะบัะธะฒะฝะพะน 1-ั ัััะฐะฝะธัั ะธ ะฟะพะปััะฐะตะผ ะตั, ะฟะพัะพะผ ะทะฐะฟะธััะฒะฐะตะผ ะฒ ะฝะตั ะดะฐะฝะฝัะต */
$page = $phpexcel->setActiveSheetIndex(0); // ะะตะปะฐะตะผ ะฐะบัะธะฒะฝะพะน ะฟะตัะฒัั ัััะฐะฝะธัั ะธ ะฟะพะปััะฐะตะผ ะตั
foreach($data as $i => $ar){ // ัะธัะฐะตะผ ะผะฐััะธะฒ
foreach($ar as $j => $val){
$page->setCellValueByColumnAndRow($j,$i+1,$val); // ะทะฐะฟะธััะฒะฐะตะผ ะดะฐะฝะฝัะต ะผะฐััะธะฒะฐ ะฒ ััะตะนะบั
$page->getStyleByColumnAndRow($j,$i+1)->getAlignment()->setWrapText(true);
}
}
$page->setTitle("ะคะพัะพะดะพัะบะฐ"); // ะะฐะณะพะปะพะฒะพะบ ะดะตะปะฐะตะผ "Example"
$page->getColumnDimension('C')->setWidth(80);
/* ะะฐัะธะฝะฐะตะผ ะณะพัะพะฒะธัััั ะบ ะทะฐะฟะธัะธ ะธะฝัะพัะผะฐัะธะธ ะฒ xlsx-ัะฐะนะป */
$objWriter = PHPExcel_IOFactory::createWriter($phpexcel, 'Excel2007');
/* ะะฐะฟะธััะฒะฐะตะผ ะฒ ัะฐะนะป */
$objWriter->save($excelDir."/".$filename);
return $excelDir."/".$filename;
}
function DownloadFile($source,$filename) {
if (file_exists($source)) {
if (ob_get_level()) {
ob_end_clean();
}
$arr = explode(".", $source);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$filename.".".array_pop($arr) );
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($source));
readfile($source);
exit;
}
}
function getXLS($xls){
include_once 'Classes/PHPExcel/IOFactory.php';
$objPHPExcel = PHPExcel_IOFactory::load($xls);
$objPHPExcel->setActiveSheetIndex(0);
$aSheet = $objPHPExcel->getActiveSheet();
$array = array();//ััะพั ะผะฐััะธะฒ ะฑัะดะตั ัะพะดะตัะถะฐัั ะผะฐััะธะฒั ัะพะดะตัะถะฐัะธะต ะฒ ัะตะฑะต ะทะฝะฐัะตะฝะธั ััะตะตะบ ะบะฐะถะดะพะน ัััะพะบะธ
//ะฟะพะปััะธะผ ะธัะตัะฐัะพั ัััะพะบะธ ะธ ะฟัะพะนะดะตะผัั ะฟะพ ะฝะตะผั ัะธะบะปะพะผ
foreach($aSheet->getRowIterator() as $row){
//ะฟะพะปััะธะผ ะธัะตัะฐัะพั ััะตะตะบ ัะตะบััะตะน ัััะพะบะธ
$cellIterator = $row->getCellIterator();
//ะฟัะพะนะดะตะผัั ัะธะบะปะพะผ ะฟะพ ััะตะนะบะฐะผ ัััะพะบะธ
$item = array();//ััะพั ะผะฐััะธะฒ ะฑัะดะตั ัะพะดะตัะถะฐัั ะทะฝะฐัะตะฝะธั ะบะฐะถะดะพะน ะพัะดะตะปัะฝะพะน ัััะพะบะธ
foreach($cellIterator as $cell){
//ะทะฐะฝะพัะธะผ ะทะฝะฐัะตะฝะธั ััะตะตะบ ะพะดะฝะพะน ัััะพะบะธ ะฒ ะพัะดะตะปัะฝัะน ะผะฐััะธะฒ
array_push($item, $cell->getCalculatedValue());
}
//ะทะฐะฝะพัะธะผ ะผะฐััะธะฒ ัะพ ะทะฝะฐัะตะฝะธัะผะธ ััะตะตะบ ะพัะดะตะปัะฝะพะน ัััะพะบะธ ะฒ "ะพะฑัะธะน ะผะฐััะฒ ัััะพะบ"
array_push($array, $item);
}
// unlink($xls);
return $array;
}
function cmp($a, $b){
$a = $a[3];
$b = $b[3];
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
$xlsData = getXLS($uploadDir."/".$_POST["uploaderPj_0_tmpname"]); //ะธะทะฒะปะตะฐะตะผ ะดะฐะฝะฝัะต ะธะท XLS
$out = array();
usort($xlsData, "cmp");
for( $i = 1 ; $i < count($xlsData) ; $i++ ){
$row = $xlsData[$i];
if( !isset($out[$row[4]]) ){
$out[$row[4]] = array(array("maxPrice"=>0,"maxId"=>0,"minPrice"=>999999),array());
}
if( $out[$row[4]][0]["maxPrice"] < intval($row[3]) ){
$out[$row[4]][0]["maxPrice"] = intval($row[3]);
$out[$row[4]][0]["maxId"] = $row[0];
}
if( $out[$row[4]][0]["minPrice"] > intval($row[3]) ){
$out[$row[4]][0]["minPrice"] = intval($row[3]);
}
$text = "#".$row[0]." ".$row[1]." ".$row[4];
// $text = "#".$row[0]." ".$row[1]." ".$row[4];
$price = " ะธะทะฝะพั ".round($row[2])."% ".$row[5]."ัั. ".$row[3]." ััะฑ.";
if( isset($row[6]) && $row[6] != "" ){
$text = "<a href=".$row[6]." target='_blank'>".$text."</a>".$price;
}else{
$text .= $price;
}
array_push($out[$row[4]][1],$text);
}
$excel = array(array("โ","ะะฐะณะพะปะพะฒะพะบ","ะขะตะบัั","ะฆะตะฝะฐ","ะขะธะฟ","ะัะพะฒะตัะบะฐ"));
foreach ($out as $j => $ar) {
$id = $ar[0]["maxId"];
$title = $j;
$text = $_POST["header"]."\r\n".implode("\r\n", $ar[1])."\r\n".$_POST["footer"];
$price = $ar[0]["minPrice"];
$type = 1;
$excel[] = array($id,$title,$text,$price,$type,1);
}
// print_r($excel);
$file = WriteExcel($excel);
DownloadFile($file,"PhotoDoska");
?>
<file_sep>/photodoska/js/KitSend.js
function getNextField($form){
var j = 1;
while( $form.find("input[name="+j+"]").length ){
j++;
}
return j;
}
$(document).ready(function(){
var rePhone = /^\+\d \(\d{3}\) \d{3}-\d{2}-\d{2}$/,
tePhone = '+7 (999) 999-99-99';
$.validator.addMethod('customPhone', function (value) {
return rePhone.test(value);
});
$(".ajax").parents("form").each(function(){
$(this).validate({
rules: {
email: 'email',
phone: 'customPhone'
}
});
if( $(this).find("input[name=phone]").length ){
$(this).find("input[name=phone]").mask(tePhone,{placeholder:" "});
}
});
$(".fancy").each(function(){
var $popup = $($(this).attr("data-block")),
$this = $(this);
$this.fancybox({
padding : 0,
content : $popup,
beforeShow: function(){
$popup.find(".custom-field").remove();
if( $this.attr("data-value") ){
var name = getNextField($popup.find("form"));
$popup.find("form").append("<input type='hidden' class='custom-field' name='"+name+"' value='"+$this.attr("data-value")+"'/><input type='hidden' class='custom-field' name='"+name+"-name' value='"+$this.attr("data-name")+"'/>");
}
}
});
});
$(".b-go").click(function(){
var block = $( $(this).attr("data-block") ),
off = $(this).attr("data-offset")||50;
$("body, html").animate({
scrollTop : block.offset().top-off
},800);
return false;
});
$(".fancy-img").fancybox({
padding : 0
});
$(".ajax").parents("form").submit(function(){
if( $(this).find("input.error").length == 0 ){
var $this = $(this),
data = $this.serialize(),
$thanks = $($this.attr("data-block"));
$.ajax({
type: $(this).attr("method"),
url: $(this).attr("action"),
data: data,
success: function(msg){
var $form;
if( msg == "1" ){
$form = $thanks;
}else{
$form = $("#b-popup-error");
}
$this.find("input[type=text],textarea").val("");
$.fancybox.open({
content : $form,
padding : 0
});
}
});
}
return false;
});
});<file_sep>/photodoska/test.php
<?
$arr = array("ะะฐะณะพะปะพะฒะพะบ","ะะพะปะธัะตััะฒะพ","ะะธะฐะผะตัั","ะะพะดะตะปั ะดะธัะบะฐ","ะจะธัะธะฝะฐ ะดะธัะบะฐ","ะัะปะตั","ะกะฒะตัะปะพะฒะบะฐ","ะะฟะธัะฐะฝะธะต","ะะธะด ัะพัะณะพะฒ","ะะปะธั-ัะตะฝะฐ","ะัะพะฒะตัะบะฐ","ะะพัะพะด");
$word = "ะจะธัะธะฝะฐ";
foreach ($arr as $i => $val) {
$eq = similar_text($word,$val);
$percent = round(($eq/similar_text($val,$val)+$eq/similar_text($word,$word))/2*100);
echo $percent."% ".$val."<br>";
}
?><file_sep>/protected/controllers/IntegrateController.php
<?php
class IntegrateController extends Controller
{
private $params = array(
"TIRE" => array(
"GOOD_TYPE_ID" => 1,
"TITLE_CODE" => 100,
"HEADER" => "HEADER_T",
"FOOTER" => "FOOTER_T",
"JOIN" => array(7,8,9),
"ADVERT_TITLE_CODE" => 13,
"NAME_ROD" => "ะจะธะฝั",
"NAME_ROD_MN" => "ะจะธะฝ",
),
"DISC" => array(
"GOOD_TYPE_ID" => 2,
"TITLE_CODE" => 86,
"TEXT_CODE" => 87,
"NAME_ROD" => "ะะธัะบะฐ",
"NAME_ROD_MN" => "ะะธัะบะพะฒ",
)
);
public function filters()
{
return array(
'accessControl'
);
}
public function accessRules()
{
return array(
array('allow',
'users'=>array('*'),
),
);
}
// ะคะพัะพะดะพัะบะฐ ------------------------------------------------------------- ะคะพัะพะดะพัะบะฐ
public function actionGeneratePdQueue(){
Log::debug("ะะฐัะฐะปะพ ะณะตะฝะตัะฐัะธะธ ะพัะตัะตะดะธ ะฒัะบะปะฐะดะบะธ ะฝะฐ ัะพัะพะดะพัะบั");
$photodoska = new Photodoska();
$photodoska->auth();
$photodoska->deleteAdverts(trim($this->getParam("PHOTODOSKA","MAIN_ADVERT")));
$this->generatePdQueue($this->getGroups("TIRE"),"TIRE");
$this->generatePdQueue($this->getItems("DISC"),"DISC");
Log::debug("ะะพะฝะตั ะณะตะฝะตัะฐัะธะธ ะพัะตัะตะดะธ ะฒัะบะปะฐะดะบะธ ะฝะฐ ัะพัะพะดะพัะบั");
}
public function actionPdNext(){
// return false;
$photodoska = new Photodoska();
$this->publicateNext($photodoska,"TIRE");
$this->publicateNext($photodoska,"DISC");
}
public function publicateNext($photodoska,$good_type_code){
$model = PdQueue::model()->find(array("order"=>"id ASC","condition"=>"good_type_id='".$this->params[$good_type_code]["GOOD_TYPE_ID"]."'"));
if( $model ){
Log::debug("ะัะบะปะฐะดะบะฐ ".strtolower($this->params[$good_type_code]["NAME_ROD"])." ะฝะฐ ัะพัะพะดะพัะบั ".$model->title);
$filename = Yii::app()->params['tempFolder']."-photodoska/".md5(time().rand()."asd").".jpg";
$resizeObj = new Resize($model->image);
$resizeObj -> resizeImage(800, 600, 'auto');
$resizeObj -> saveImage($filename, 100);
$model->delete();
if( !$photodoska->isAuth() ) $photodoska->auth();
// echo "<h3>".$model->title."</h3><img width=300 src='/".$filename."'><br>";
$photodoska->addAdvert($filename,$model->title,$model->text,trim($this->getParam("PHOTODOSKA","PHONE")),$model->price);
unlink($filename);
sleep(10);
Log::debug("ะะพะฝะตั ะฒัะบะปะฐะดะบะธ ".strtolower($this->params[$good_type_code]["NAME_ROD"])." ะฝะฐ ัะพัะพะดะพัะบั ".$model->title);
}else{
Log::debug("ะะตั ".strtolower($this->params[$good_type_code]["NAME_ROD_MN"])." ะดะปั ะฒัะบะปะฐะดะบะธ ะฝะฐ ัะพัะพะดะพัะบั");
}
}
public function generatePdQueue($adverts,$good_type_code){
PdQueue::model()->deleteAll("good_type_id='".$this->params[$good_type_code]["GOOD_TYPE_ID"]."'");
// $i = 1;
foreach ($adverts as $advert) {
$model = new PdQueue();
$model->title = $advert["TITLE"];
$model->text = $advert["TEXT"];
$model->price = $advert["PRICE"];
$model->image = $advert["IMAGE"];
$model->good_type_id = $this->params[$good_type_code]["GOOD_TYPE_ID"];
if( !$model->save() ){
Log::debug("ะัะธะฑะบะฐ ะดะพะฑะฐะฒะปะตะฝะธั ะทะฐะดะฐะฝะธั ะฒ ะพัะตัะตะดั: PHOTODOSKA ".$good_type_code." ".$title);
}
// $photodoska->addAdvert(Yii::app()->params['tempFolder']."/photodoska.jpg",$advert["TITLE"],$advert["TEXT"],trim($this->getParam("PHOTODOSKA","PHONE")),$advert["PRICE"]);
// if( $i >= 1 ) return;
// $i++;
}
}
public function getGroups($good_type_code){
$curParams = $this->params[$good_type_code];
$model = GoodType::model()->with('goods.fields.variant','goods.fields.attribute')->findByPk($curParams["GOOD_TYPE_ID"])->goods;
$result = array();
foreach ($model as $item) {
$tog = true;
foreach ($curParams["JOIN"] as $field)
if( !(isset($item->fields_assoc[intval($field)]) && $item->fields_assoc[intval($field)]->value != 0) ) $tog = false;
if( $tog && ( (isset($item->fields_assoc[27]) && intval($item->fields_assoc[27]->variant_id) == 1056) || (isset($item->fields_assoc[46]) && intval($item->fields_assoc[46]->value) == 1) ) ){
$title = Interpreter::generate($curParams["ADVERT_TITLE_CODE"],$item);
if( !isset($result[$title]) ) $result[$title] = array();
array_push($result[$title], $item);
}
}
$header = $this->replaceToBr($this->getParam("PHOTODOSKA",$curParams["HEADER"]));
$footer = $this->replaceToBr($this->getParam("PHOTODOSKA",$curParams["FOOTER"]));
foreach ($result as $key => $group) {
$price = $this->findPrice($group);
if( $price != false ){
$result[$key] = array(
"TEXT" => $header."<br>".$this->generateList($group,$curParams["TITLE_CODE"]).$footer,
"TITLE" => $key,
"PRICE" => $price,
"IMAGE" => substr($this->findImage($group),1)
);
}else{
unset($result[$key]);
}
}
return $result;
}
public function getItems($good_type_code){
$curParams = $this->params[$good_type_code];
$model = GoodType::model()->with('goods.fields.variant','goods.fields.attribute')->findByPk($curParams["GOOD_TYPE_ID"])->goods;
$result = array();
if( $model )
foreach ($model as $key => $item) {
if( (isset($item->fields_assoc[27]) && intval($item->fields_assoc[27]->variant_id) == 1056) || (isset($item->fields_assoc[46]) && intval($item->fields_assoc[46]->value) == 1) ){
array_push($result, array(
"TEXT" => $this->replaceToBr(Interpreter::generate($curParams["TEXT_CODE"],$item)),
"TITLE" => Interpreter::generate($curParams["TITLE_CODE"],$item),
"PRICE" => $item->fields_assoc[20]->value,
"IMAGE" => substr($this->getImages($item)[0],1)
)
);
}
}
return $result;
}
public function generateList($group,$interpreter_id){
$out = "";
for( $j = 0 ; $j < count($group); $j++ ) {
$min = 999999;
$min_id = 0;
foreach ($group as $i => $item) {
if( intval($item->fields_assoc[20]->value) < $min ){
$min_id = $i;
$min = intval($item->fields_assoc[20]->value);
}
}
if( $min != 0 )
$out .= Interpreter::generate($interpreter_id,$group[$min_id])."<br>";
unset($group[$min_id]);
}
return $out;
}
public function findPrice($group){
$min = 999999;
foreach ($group as $i => $item) {
$price = intval($item->fields_assoc[20]->value);
if( $price < $min && $price != 0 ){
$min = $price;
}
}
return ( $min == 999999 )?false:$min;
}
public function findImage($group){
foreach ($group as $item) {
$images = $this->getImages($item);
if( count($images) != 0 ) return $images[0];
}
return "";
}
// ะคะพัะพะดะพัะบะฐ ------------------------------------------------------------- ะคะพัะพะดะพัะบะฐ
// ะัะพะผ ------------------------------------------------------------------ ะัะพะผ
public function actionDromUp(){
Log::debug("ะะฐัะฐะปะพ ะฐะฒัะพะฟะพะดะฝััะธั ะดัะพะผ");
$drom = new Drom();
$users = $this->getParam("DROM","USERS");
$users = explode("\n", $users);
foreach ($users as $value) {
$user = explode(" ", $value);
$drom->setUser($user[0],$user[1]);
$drom->upAdverts();
}
Log::debug("ะะพะฝัะฐะปะพ ะฐะฒัะพะฟะพะดะฝััะธั ะดัะพะผ");
}
// ะัะพะผ ------------------------------------------------------------------ ะัะพะผ
// Yahoo ----------------------------------------------------------------- Yahoo
public function actionYahooBids(){
return false;
$model = YahooCategory::model()->findAll(array("order"=>"id ASC"));
foreach ($model as $item)
$this->parseCategory($item,true);
}
public function actionYahooAll(){
return false;
$category = $this->getNextCategory();
$this->parseCategory($category);
}
public function getNextCategory(){
$cur_cat_id = intval($this->getParam("YAHOO","CURRENT_CATEGORY"));
$model = YahooCategory::model()->findAll(array("order"=>"id ASC"));
$first = NULL;
$next = false;
foreach ($model as $item) {
if( $first === NULL ) $first = $item;
if( $next ){
$this->setParam("YAHOO","CURRENT_CATEGORY",$item->id);
return $item;
}
if( intval($item->id) == $cur_cat_id ) $next = true;
}
$this->setParam("YAHOO","CURRENT_CATEGORY",$first->id);
return $first;
}
public function parseCategory($category, $bids = false){
$yahoo = new Yahoo();
$tog = true;
$page = $yahoo->getNextPage($category->code,intval($category->max_price*$this->courses["USD"]),( ($bids)?"a":"d" ));
while( $page && $tog ){
$sellers = array();
foreach ($page["items"] as $key => $item)
if( !in_array($item->Seller->Id, $sellers) ) array_push($sellers, $item->Seller->Id);
$this->updateSellers($sellers);
$sellers_id = $this->getSellersID($sellers);
foreach ($page["items"] as &$item){
$item->Seller->Id = $sellers_id[$item->Seller->Id];
}
$this->updateLots($page["items"],$category->id);
Log::debug($category->name." ะกััะฐะฝะธัะฐ: ".$yahoo->getLastPage());
if( $bids ){
$tog = ( intval(array_pop($page["items"])->Bids) > 0 )?true:false;
}else{
$tog = ( intval(array_pop($page["items"])->Bids) == 0 )?true:false;
}
$page = $yahoo->getNextPage($category->code,intval($category->max_price*$this->courses["USD"]),( ($bids)?"a":"d" ));
}
Log::debug($category->name." ะะฐััะธะฝะณ ะทะฐะฒะตััะตะฝ. ะะพะปะธัะตััะฒะพ ะฟะพะปััะตะฝะฝัั
ัััะฐะฝะธั: ".$yahoo->getLastPage()-1);
}
public function getSellersID($sellers){
$model = Yii::app()->db->createCommand()->select("id, name")->from(YahooSeller::tableName())->where(array('in', 'name', $sellers))->queryAll();
$result = array();
foreach ($model as $seller) {
$result[$seller["name"]] = $seller["id"];
}
return $result;
}
public function updateSellers($sellers){
$sql = "INSERT IGNORE INTO `".YahooSeller::tableName()."` (`id`,`name`) VALUES ";
$exist = Yii::app()->db->createCommand()->select("id, name")->from(YahooSeller::tableName())->where(array('in', 'name', $sellers))->queryAll();
$values = array();
foreach ($sellers as $key => $seller) {
if( !$this->existSeller($seller,$exist) ){
array_push($values, "(NULL,'".addslashes(trim($seller))."')");
}
}
if( count($values) ){
$sql .= implode(",", $values);
Yii::app()->db->createCommand($sql)->execute();
}
}
public function existSeller($seller,$exist){
foreach ($exist as $sel)
if( $sel["name"] == $seller ) return true;
return false;
}
public function updateLots($items,$category_id){
$tableName = YahooLot::tableName();
$values = array();
foreach ($items as $item) {
if( $item->IsReserved == "false" ){
$bidorbuy = (isset($item->BidOrBuy))?intval($item->BidOrBuy):0;
array_push($values, array(NULL, $item->AuctionID, addslashes($item->Title), date("Y-m-d H:i:s", time()), $item->Image, intval($item->CurrentPrice), $bidorbuy, $item->Bids, $this->convertTime($item->EndTime), $category_id, $item->Seller->Id, 0));
}
}
$update = array("update_time","cur_price","bid_price","bids","end_time");
$this->updateRows(YahooLot::tableName(),$values,$update);
}
public function convertTime($time){
return date("Y-m-d H:i:s", date_timestamp_get(date_create(substr(str_replace("T", " ", $time), 0, strpos($time, "+"))))-3*60*60);
}
// Yahoo ----------------------------------------------------------------- Yahoo
public function actionAdminIndex(){
}
}
<file_sep>/protected/extensions/Injapan.php
<?
Class Injapan {
function __construct() {
}
public function getFields($code, $max_price, $state = NULL){
include_once Yii::app()->basePath.'/extensions/simple_html_dom.php';
$result = array("main"=>array(),"other"=>array());
$html = file_get_html("https://injapan.ru/auction/".$code.".html");
// ะะพะปััะตะฝะธะต ะทะฐะณะพะปะพะฒะบะฐ ะปะพัะฐ
$query = $html->find('.auction tr td[class=l]');
$result["main"]["name"] = $query[0]->innertext;
// ะะพะปััะตะฝะธะต ะดะฐัั ะพะบะพะฝัะฐะฝะธั ะฐัะบัะธะพะฝะฐ
$query = $html->find('#rowInfoEnddate td[class=l]');
$arr = explode(" ",strip_tags($query[0]->innertext));
$d = explode("/",$arr[0]);
$result["main"]["date"] = date("Y-m-d H:i:s", strtotime($d[2]."-".$d[1]."-".$d[0]." ".$arr[1].":00") + 3*60*60);
// ะะพะปััะตะฝะธะต ะฟะตัะฒะพะน ัะพัะพะณัะฐัะธะธ
$query = $html->find('.left_previews td img');
$result["main"]["image"] = $query[0]->src;
// ะะพะปััะตะฝะธะต ัะฐะณะฐ ััะฐะฒะบะธ
$query = $html->find("#spanInfoStep");
$arr = explode("<span", $query[0]->innertext);
$result["other"]["step"] = intval(preg_replace("/[^0-9]/", '', $arr[0] ));
// ะะพะปััะตะฝะธะต ัะตะบััะตะน ัะตะฝั ะปะพัะฐ
$query = $html->find("#spanInfoPrice strong");
$result["main"]["current_price"] = intval(str_replace(" ", "", strip_tags($query[0]->innertext)));
$result["main"]["state"] = ( intval($result["main"]["current_price"]) + intval($result["other"]["step"]) > intval($max_price) )?5:0;
// ะฃัะพัะฝะตะฝะธะต ัะพััะพัะฝะธั ะฐัะบัะธะพะฝะฐ. ะะฐะฒะตััะตะฝ ะธะปะธ ะฝะต ะทะฐะฒะตััะตะฝ
$query = $html->find("#bidplace input[name=account]");
if( !isset($query[0]) ) $result["main"]["state"] = ( $result["main"]["current_price"] <= $max_price && ($state == 2 || $state == 6) )?6:3;
return $result;
}
}
?><file_sep>/protected/controllers/ShopController.php
<?php
class ShopController extends Controller
{
public $layout='//layouts/shop';
public $params = array(
1 => array(
"NAME" => "ะจะธะฝั",
"TITLE_CODE" => 50,
"TITLE_2_CODE" => 13,
"DESCRIPTION_CODE" => 74,
"GARANTY_CODE" => 77,
"PRICE_CODE" => 95,
"ORDER" => 120
),
2 => array(
"NAME" => "ะะธัะบะธ",
"TITLE_CODE" => 53,
"TITLE_2_CODE" => 54,
"DESCRIPTION_CODE" => 75,
"GARANTY_CODE" => 78,
"PRICE_CODE" => 94,
"ORDER" => 121
));
public function filters()
{
return array(
'accessControl'
);
}
public function accessRules()
{
return array(
array('allow',
'actions'=>array('filter'),
'roles'=>array('manager'),
),
array('allow',
'actions'=>array('index', 'detail','contacts','mail'),
'users'=>array('*'),
),
array('deny',
'users'=>array('*'),
),
);
}
public function actionIndex($countGood = false)
{
$count=0;
$condition="";
$check = array();
isset($_GET['type']) ? $_GET['type'] : $_GET['type'] = 1;
$type = ($_GET['type']==1) ? "tires": "discs";
$criteria=new CDbCriteria();
$criteria->with = array('good' => array('select'=> false));
$criteria->condition = 'attribute_id=20 AND good.good_type_id='.$_GET['type'];
$criteria->select = array('int_value');
$criteria->order = 'int_value ASC';
$model = GoodAttribute::model()->findAll($criteria);
$price_min = $model[0]->int_value;
$price_max = array_pop($model)->int_value;
$imgs = array_values(array_diff(scandir(Yii::app()->params["imageFolder"]."/".$type), array('..', '.', 'Thumbs.db','default-big.png','default.jpg')));
$temp = "0";
if(count($imgs)) {
$temp = "";
foreach ($imgs as $value) {
$temp.="'".$value."',";
}
$temp = substr($temp, 0, -1);
}
$criteria=new CDbCriteria();
$criteria->select = 'id,good_type_id';
$criteria->with = array('fields' => array('select'=> array('attribute_id','varchar_value')));
$criteria->condition = 'good_type_id='.$_GET['type'].' AND (fields.attribute_id=3 AND fields.varchar_value IN('.$temp.'))';
$model=Good::model()->findAll($criteria);
$goods_no_photo = array();
foreach ($model as $good) {
array_push($goods_no_photo, $good->id);
}
isset($_GET['Good_page']) ? $_GET['Good_page'] : $_GET['Good_page'] = 1;
isset($_GET['price-min']) ? $_GET['price-min'] : $_GET['price-min'] = $price_min;
isset($_GET['price-max']) ? $_GET['price-max'] : $_GET['price-max'] = $price_max;
$criteria=new CDbCriteria();
$criteria->select = 'id';
$criteria->group = 'fields.good_id';
$criteria->with = array('fields' => array('select'=> array('variant_id','attribute_id','int_value')));
// $criteria->addInCondition("id",$goods_no_photo);
$criteria->condition = '(good_type_id='.$_GET['type'].' AND fields.attribute_id=20 AND fields.int_value>='.$_GET['price-min'].' AND fields.int_value<='.$_GET['price-max'].' )';
if(isset($_GET['arr']))
foreach ($_GET['arr'] as $id => $arr) {
foreach ($arr as $value) {
$check[$value] = true;
$criteria->addCondition('fields.variant_id='.$value,'OR');
}
$count++;
}
$criteria->having = 'COUNT(fields.id)>='.($count+1);
$model=Good::model()->findAllbyPk($goods_no_photo,$criteria);
$goods_id = array();
foreach ($model as $good) {
array_push($goods_id, $good->id);
}
if( (isset($_GET['arr'][5]) && (count($_GET['arr'][5]) > 1)) ||
(isset($_GET['arr'][31]) && (count($_GET['arr'][31]) > 1)) ||
(isset($_GET['arr'][32]) && (count($_GET['arr'][32]) > 1))
) {
$model=Good::model()->findAllbyPk($goods_id);
foreach ($model as $key => $good) {
$count = array();
foreach ($good->fields as $attr) {
foreach ($check as $value => $item) {
if($attr->variant_id == $value) $count[$attr->attribute_id] = true;
}
}
if(count($count) < count($_GET['arr'])) {
unset($model[$key]);
}
}
$goods_id = array();
foreach ($model as $good) {
array_push($goods_id, $good->id);
}
}
$sort = (isset($_GET['sort']['id'])) ? $_GET['sort'] : NULL;
$goods = $this->sort($goods_id,$sort);
$count = $goods['count'];
$pages = $goods['pages'];
$goods = $goods['model'];
if( !$countGood ) {
// $criteria=new CDbCriteria();
// $criteria->condition = 'list=1';
// $criteria->select = array('id');
// if($_GET['type']==1) {
// $criteria->with = array(
// 'variants'
// => array(
// 'select' => array('int_value','varchar_value','float_value'),
// 'condition' => 'attribute_id=7 OR attribute_id=8 OR attribute_id=9 OR attribute_id=23 OR attribute_id=16 OR attribute_id=27'
// )
// );
// }
// if($_GET['type']==2) {
// $criteria->with = array(
// 'variants'
// => array(
// 'select' => array('int_value','varchar_value','float_value'),
// 'condition' => 'attribute_id=6 OR attribute_id=9 OR attribute_id=5 OR attribute_id=31 OR attribute_id=32 OR attribute_id=27'
// )
// );
// }
// $model = Attribute::model()->findAll($criteria);
// foreach ($model as $attr) {
// $temp = array();
// foreach ($attr->variants as $i => $variant) {
// $temp[$i]['variant_id'] = $variant->id;
// $temp[$i]['value'] = $variant->value;
// if(isset($check[$variant->id])) {
// $temp[$i]['checked'] = "checked";
// } else {
// $temp[$i]['checked'] = "";
// }
// }
// $filter[$attr->id] = $temp;
// }
$criteria=new CDbCriteria();
$criteria->with = array(
'good'
=> array(
'select' => false,
'condition' => 'good_type_id='.$_GET['type']
),
'variant' => array(
'select' => false
)
);
$criteria->condition = 't.attribute_id=9 OR t.attribute_id=27 OR t.attribute_id=28 OR ';
if($_GET['type']==1) {
$criteria->condition .= 't.attribute_id=7 OR t.attribute_id=8 OR t.attribute_id=23 OR t.attribute_id=16';
}
if($_GET['type']==2) {
$criteria->condition .= 't.attribute_id=6 OR t.attribute_id=5 OR t.attribute_id=31 OR t.attribute_id=32';
}
$criteria->addInCondition("good.id",$goods_no_photo);
$criteria->group = 't.variant_id';
$criteria->order = 'variant.sort ASC';
$model = GoodAttribute::model()->findAll($criteria);
$filter = array();
foreach ($model as $i => $item) {
if(!isset($filter[$item->attribute_id])) {
$filter[$item->attribute_id] = array();
$temp = array();
}
$temp['variant_id'] = $item->variant_id;
$temp['value'] = $item->value;
if(isset($check[$item->variant_id])) {
$temp['checked'] = "checked";
} else {
$temp['checked'] = "";
}
array_push($filter[$item->attribute_id], $temp);
}
$this->render('index',array(
'goods'=>$goods,
'filter' =>$filter,
'price_min' => $price_min,
'price_max' => $price_max,
'pages' => $pages
));
} else {
echo $count;
}
}
public function sort($goods_id,$attr = NULL) {
$criteria=new CDbCriteria();
$criteria->order = 't.id DESC';
if($attr) {
$criteria->with = ($attr['id'] != 20) ? array('fields' => array('select'=> array('attribute_id')),"fields.variant"=> array('select' => array('sort'))) : array('fields' => array('select'=> array('variant_id','attribute_id','int_value')));
$criteria->together = true;
$criteria->group = 'fields.good_id';
$sort = $attr['sort_type'];
$criteria->condition = 'fields.attribute_id='.$attr['id'];
$criteria->order = ($attr['id'] != 20) ? 'variant.sort '.$sort : 'fields.int_value '.$sort;
}
$criteria->addInCondition("t.id",$goods_id);
$dataProvider = new CActiveDataProvider('Good', array(
'criteria'=>$criteria,
'pagination'=>array(
'pageSize'=>13
)
));
$goods = $dataProvider->getData();
if($attr) {
$goods_id = array();
foreach ($goods as $good) {
array_push($goods_id, $good->id);
}
$goods = Good::model()->findAllbyPk($goods_id);
usort($goods, function($a, $b) use($attr) {
$a = (is_array($a->fields_assoc[$attr['id']])) ? $a->fields_assoc[$attr['id']][0]->value : $a->fields_assoc[$attr['id']]->value;
$b = (is_array($b->fields_assoc[$attr['id']])) ? $b->fields_assoc[$attr['id']][0]->value : $b->fields_assoc[$attr['id']]->value;
if ($a == $b) {
return 0;
}
if($attr['sort_type'] == "DESC") return ($a > $b) ? -1 : 1; else return ($a < $b) ? -1 : 1;
});
}
return array('model' => $goods,'count' => $dataProvider->getTotalItemCount(), 'pages' => $dataProvider->getPagination());
}
public function actionDetail($partial = false,$id = NULL)
{
if($id) {
$good = Good::model()->with("fields")->find("good_type_id=".$_GET['type']." AND fields.attribute_id=3 AND fields.varchar_value='".$id."'");
$good = Good::model()->findByPk($good->id);
$this->title = Interpreter::generate($this->params[$_GET['type']]["TITLE_CODE"], $good);
$this->description = $this->keywords = Interpreter::generate($this->params[$_GET['type']]["DESCRIPTION_CODE"], $good);
$imgs = $this->getImages($good);
if( !$partial ){
$this->render('detail',array(
'good'=>$good,
'imgs'=>$imgs
));
}else{
$this->renderPartial('detail',array(
'good'=>$good,
'imgs'=>$imgs
));
}
}
}
public function actionContacts()
{
$this->render('contacts');
}
public function actionCount()
{
$goods=Good::model()->findAllbyPk($goods_id,$criteria);
}
public function loadModel($id)
{
$model=Good::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
public function actionMail(){
require_once("phpmail.php");
$email_admin = $this->getParam("SHOP","EMAILS");
$from = "<NAME>";
$email_from = "<EMAIL>";
$deafult = array("name"=>"ะะผั","phone"=>"ะขะตะปะตัะพะฝ", "email"=>"E-mail");
$fields = array();
if( count($_POST) ){
foreach ($deafult as $key => $value){
if( isset($_POST[$key]) ){
$fields[$value] = $_POST[$key];
}
}
$i = 1;
while( isset($_POST[''.$i]) ){
$fields[$_POST[$i."-name"]] = $_POST[''.$i];
$i++;
}
$subject = $_POST["subject"];
foreach ($fields as $key => $value){
$message .= "<div><p><b>".$key.": </b>".$value."</p></div>";
}
$message .= "<div><p><b>ะขะพะฒะฐั: </b><a target='_blank' href='".$_POST["good-url"]."'>".$_POST["good"]."</a></p></div>";
$message .= "</div>";
if(send_mime_mail("ะกะฐะนั ".$from,$email_from,$name,$email_admin,'UTF-8','UTF-8',$subject,$message,true)){
echo "1";
}else{
echo "0";
}
}
}
}
<file_sep>/protected/extensions/Yahon.php
<?
Class Yahon {
private $cookies = NULL;
function __construct() {
}
public function auth() {
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, "https://www.yahon.ru/auth");
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'set_login'=>'svc1',
'set_pass'=>'<PASSWORD>',
// 'set_login'=>'<EMAIL>',
// 'set_pass'=>'<PASSWORD>',
'set_from'=>'',
'to_remain_here'=>'Y'
));
$content = curl_exec($ch);
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $content, $result);
$this->cookies = implode(';', $result[1]);
Log::debug("Yahon.php 30 ัััะพะบะฐ. ะะพัะปะต ะฐะฒัะพัะธะทะฐัะธะธ cookies = ".$this->cookies); file_put_contents(Yii::app()->basePath."/logs/sniper/auth.txt", $content);
curl_close($ch);
}
public function isAuth() {
return ($this->cookies !== NULL);
}
public function setBid($lot_number,$cur_price,$step,$max_price) {
$cur_price = intval($cur_price);
$step = intval($step);
$max_price = intval($max_price);
if($this->cookies === NULL) return "ะะฒัะพัะธะทะฐัะธั ะฝะต ะฟัะพะนะดะตะฝะฐ";
$bid = (($cur_price+$step*2)<=$max_price) ? ($cur_price+$step) : ( (($cur_price+$step)<=$max_price) ? $max_price : 0);
Log::debug("Yahon.php 44 ัััะพะบะฐ. bid = ".$bid);
if($bid===0) {
return array('result' => 5);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, "https://www.yahon.ru/yahoo/bid_preview");
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'user_rate'=>$bid,
'quantity'=>'1',
'lot_no'=>$lot_number
));
curl_setopt($ch, CURLOPT_COOKIE, $this->cookies);
$content = curl_exec($ch);
file_put_contents(Yii::app()->basePath."/logs/sniper/bid_preview.txt", $content);
preg_match_all('/.(input [^>]*)/m', $content, $result);
$fields = array(
'comments' => '',
'deliveryType' =>'2',
'nocash' => '0.21847357973456382'
);
foreach ($result[1] as $key => $value) {
if($key!=0) {
preg_match_all('/.*name="([^"]*)".*/',$value,$name);
preg_match_all('/.*value="([^"]*)".*/',$value,$val);
$fields[$name[1][0]] = $val[1][0];
}
}
Log::debug("Yahon.php 77 ัััะพะบะฐ. signature = ".$fields["signature"]." token = ".$fields["token"]);
if(!isset($fields["signature"])) {
return array('result' => 4);
}
// $fields['user_rate'] = 500;
curl_setopt($ch, CURLOPT_URL, "https://www.yahon.ru/yahoo/bid_place");
curl_setopt($ch, CURLOPT_POSTFIELDS,$fields);
$content = curl_exec($ch);
file_put_contents(Yii::app()->basePath."/logs/sniper/bid_place.txt", $content);
preg_match_all('/.*signature=([^"]*)".*/',$content,$sign);
preg_match_all('/.*token=([^&]*)&.*/',$content,$token);
$params = array();
$fields["signature"] = $sign[1][0];
$fields["token"] = $token[1][0];
foreach ($fields as $key => $value) {
$params[] = $key."=".$value;
}
Log::debug("Yahon.php 99 ัััะพะบะฐ. params = ".implode("&", $params));
curl_setopt($ch, CURLOPT_COOKIE, $this->cookies.";lotViewMode=1");
curl_setopt($ch, CURLOPT_URL,"https://www.yahon.ru/modules/yahoo_auction/data_request/rate.php?".implode("&", $params));
curl_setopt($ch, CURLOPT_POST, 0);
$content = curl_exec($ch);
file_put_contents(Yii::app()->basePath."/logs/sniper/rate.txt", $content);
curl_close($ch);
if(mb_stripos($content,"ะกัะฐะฒะบะฐ ะฟัะธะฝััะฐ",0,"UTF-8")) {
return array('price' => $bid, 'result' => 2);
} else {
return array('price' => $bid, 'result' => 0);
}
}
}
?><file_sep>/protected/components/Controller.php
<?php
/**
* Controller is the customized base controller class.
* All controller classes for this application should extend from this base class.
*/
class Controller extends CController
{
/**
* @var string the default layout for the controller view. Defaults to 'column1',
* meaning using a single column layout. See 'protected/views/layouts/column1.php'.
*/
public $layout='admin';
public $scripts = array();
public $courses = array("USD" => 120);
/**
* @var array context menu items. This property will be assigned to {@link CMenu::items}.
*/
public $menu=array();
public $title="Godzilla Wheels";
public $description="Godzilla Wheels";
public $keywords="Godzilla Wheels";
/**
* @var array the breadcrumbs of the current page. The value of this property will
* be assigned to {@link CBreadcrumbs::links}. Please refer to {@link CBreadcrumbs::links}
* for more details on how to specify this property.
*/
public $breadcrumbs = array();
public $interpreters = array();
public $user;
public $cache = array();
public $start;
public $render;
public $debugText = "";
public $settings = array();
public $adminMenu = array();
public function init() {
parent::init();
date_default_timezone_set("Asia/Novosibirsk");
$this->user = User::model()->with("role")->findByPk(Yii::app()->user->id);
$model = ModelNames::model()->findAll(array("order" => "sort ASC"));
$this->adminMenu["items"] = $this->removeExcess($model,true);
foreach ($this->adminMenu["items"] as $key => $value) {
if( $value->admin_menu == 0 ){
unset($this->adminMenu["items"][$key]);
}else{
$this->adminMenu["items"][$key] = $this->toLowerCaseModelNames($value);
}
}
$this->adminMenu["cur"] = $this->toLowerCaseModelNames(ModelNames::model()->find(array("condition" => "code = '".Yii::app()->controller->id."'")));
$this->start = microtime(true);
$this->getInterpreters();
if( !Yii::app()->user->isGuest ) $this->checkModelAccess();
}
public function beforeRender($view){
parent::beforeRender($view);
$this->render = microtime(true);
$this->debugText = "Controller ".round(microtime(true) - $this->start,4);
return true;
}
public function afterRenderPartial(){
parent::afterRenderPartial();
$this->debugText = ($this->debugText."<br>View ".round(microtime(true) - $this->render,4));
}
public function getUserRole(){
return $this->user->role->code;
}
public function getUserRoleRus() {
return $this->user->role->name;
}
public function getUserRoleFromModel(){
$user = User::model()->findByPk(Yii::app()->user->id);
return $user->role->code;
}
public function toLowerCaseModelNames($el){
if( !$el ) return false;
$el->vin_name = mb_strtolower($el->vin_name, "UTF-8");
$el->rod_name = mb_strtolower($el->rod_name, "UTF-8");
return $el;
}
public function insertValues($tableName,$values){
if( !count($values) ) return true;
$structure = array();
foreach ($values[0] as $key => $value) {
$structure[] = "`".$key."`";
}
$structure = "(".implode(",", $structure).")";
$sql = "INSERT INTO `$tableName` ".$structure." VALUES ";
$vals = array();
foreach ($values as $value) {
$item = array();
foreach ($value as $el) {
$item[] = "'".addslashes($el)."'";
}
$vals[] = "(".implode(",", $item).")";
}
$sql .= implode(",", $vals);
return Yii::app()->db->createCommand($sql)->execute();
}
public function replaceToBr($str){
return str_replace("\n", "<br>", $str);
}
public function getInterpreters(){
$tmp = array();
$model = Interpreter::model()->findAll();
foreach ($model as $item) {
$tmp[$item->id.""] = $item;
}
$this->interpreters = $tmp;
}
public function getListValue($list_id,$attrs){
$i = "list_".$list_id;
if( !isset($this->cache[$i]) ){
$model = Dictionary::model()->with("values")->findByPk($list_id);
$tmp = array( "ATTRS" => array(), "VALUES" => array() );
$tmp["ATTRS"]["attr_1"] = $model->attribute_id_1;
foreach ($model->values as $key => $value) {
$tmp["VALUES"][$value->attribute_1] = $value->value;
}
$this->cache[$i] = $tmp;
}
if( isset($attrs[$this->cache[$i]["ATTRS"]["attr_1"]]) ){
if( is_array($attrs[$this->cache[$i]["ATTRS"]["attr_1"]]) ){
foreach ($attrs[$this->cache[$i]["ATTRS"]["attr_1"]] as $key => &$value) {
$value = (isset($this->cache[$i]["VALUES"][$value->variant_id]))?$this->cache[$i]["VALUES"][$value->variant_id]:"";
}
return implode("/", $attrs[$this->cache[$i]["ATTRS"]["attr_1"]]);
}else{
return (isset($this->cache[$i]["VALUES"][$attrs[$this->cache[$i]["ATTRS"]["attr_1"]]->variant_id]))?$this->cache[$i]["VALUES"][$attrs[$this->cache[$i]["ATTRS"]["attr_1"]]->variant_id]:"";
}
}
return "";
}
public function getTableValue($table_id,$attrs){
$i = "table_".$table_id;
if( !isset($this->cache[$i]) ){
$model = Table::model()->with("values")->findByPk($table_id);
$tmp = array( "ATTRS" => array(), "VALUES" => array() );
$tmp["ATTRS"]["attr_1"] = $model->attribute_id_1;
$tmp["ATTRS"]["attr_2"] = $model->attribute_id_2;
foreach ($model->values as $key => $value) {
if( !isset($tmp["VALUES"][$value->attribute_1]) ) $tmp["VALUES"][$value->attribute_1] = array();
$tmp["VALUES"][$value->attribute_1][$value->attribute_2] = $value->value;
}
$this->cache[$i] = $tmp;
}
return ( isset($attrs[$this->cache[$i]["ATTRS"]["attr_1"]]->variant_id) && isset($attrs[$this->cache[$i]["ATTRS"]["attr_2"]]->variant_id) && isset($this->cache[$i]["VALUES"][$attrs[$this->cache[$i]["ATTRS"]["attr_1"]]->variant_id][$attrs[$this->cache[$i]["ATTRS"]["attr_2"]]->variant_id]) )?$this->cache[$i]["VALUES"][$attrs[$this->cache[$i]["ATTRS"]["attr_1"]]->variant_id][$attrs[$this->cache[$i]["ATTRS"]["attr_2"]]->variant_id]:"";
}
public function getCubeValue($cube_id,$attrs){
$i = "cube_".$cube_id;
if( !isset($this->cache[$i]) ){
$model = Cube::model()->with("values")->findByPk($cube_id);
$tmp = array( "ATTRS" => array(), "VALUES" => array() );
$tmp["ATTRS"]["attr_1"] = $model->attribute_id_1;
$tmp["ATTRS"]["attr_2"] = $model->attribute_id_2;
$tmp["ATTRS"]["attr_3"] = $model->attribute_id_3;
foreach ($model->values as $key => $value) {
if( !isset($tmp["VALUES"][$value->attribute_1]) ) $tmp["VALUES"][$value->attribute_1] = array();
if( !isset($tmp["VALUES"][$value->attribute_1][$value->attribute_2]) ) $tmp["VALUES"][$value->attribute_1][$value->attribute_2] = array();
$tmp["VALUES"][$value->attribute_1][$value->attribute_2][$value->attribute_3] = $value->value;
}
$this->cache[$i] = $tmp;
}
return (isset($attrs[$this->cache[$i]["ATTRS"]["attr_1"]]->variant_id) && isset($attrs[$this->cache[$i]["ATTRS"]["attr_2"]]->variant_id) && isset($attrs[$this->cache[$i]["ATTRS"]["attr_3"]]->variant_id) && isset($this->cache[$i]["VALUES"][$attrs[$this->cache[$i]["ATTRS"]["attr_1"]]->variant_id][$attrs[$this->cache[$i]["ATTRS"]["attr_2"]]->variant_id][$attrs[$this->cache[$i]["ATTRS"]["attr_3"]]->variant_id]))?$this->cache[$i]["VALUES"][$attrs[$this->cache[$i]["ATTRS"]["attr_1"]]->variant_id][$attrs[$this->cache[$i]["ATTRS"]["attr_2"]]->variant_id][$attrs[$this->cache[$i]["ATTRS"]["attr_3"]]->variant_id]:"";
}
public function getVarValue($cube_id){
$i = "var_".$cube_id;
if( !isset($this->cache[$i]) ){
$model = Vars::model()->findByPk($cube_id);
$this->cache[$i] = (isset($model->value))?$model->value:"";
}
return $this->cache[$i];
}
public function checkAccess($model, $return = false){
$rule_codes = explode(",", $model->rule_code);
if( $return ){
foreach ($rule_codes as $rule_code)
if( Yii::app()->user->checkAccess(trim($rule_code)) ) return true;
return false;
}else{
$access = false;
foreach ($rule_codes as $rule_code)
if( Yii::app()->user->checkAccess(trim($rule_code)) ) $access = true;
if( !$access ) throw new CHttpException(403,'ะะพัััะฟ ะทะฐะฟัะตัะตะฝ');
}
}
public function checkModelAccess($return = false,$model_code = false){
$model_code = ($model_code)?$model_code:( (isset($this->adminMenu["cur"]->code))?$this->adminMenu["cur"]->code:false );
if( !$model_code ) return true;
if( $this->user->usr_models == "" || $model_code == "" ) return true;
$models = explode(",", $this->user->usr_models);
if( $return ){
foreach ($models as $model)
if( trim($model) == trim($model_code) ) return true;
return false;
}else{
$access = false;
foreach ($models as $model)
if( trim($model) == trim($model_code) ) $access = true;
if( !$access ) throw new CHttpException(403,'ะะพัััะฟ ะทะฐะฟัะตัะตะฝ');
}
}
public function getDynObjects($dynamic,$good_type_id){
$criteria = new CDbCriteria();
$criteria->with = array("goodTypes","variants");
$criteria->condition = "goodTypes.good_type_id=".$good_type_id." AND dynamic=1";
$modelDyn = Attribute::model()->findAll($criteria);
foreach ($modelDyn as $key => $value) {
$curObj = AttributeVariant::model()->findByPk($dynamic[$value->id]);
$dynObjects[$value->id] = (object) array("value"=>$curObj->value,"variant_id"=>$curObj->id);
}
return $dynObjects;
}
public function removeExcess($model,$menu = false){
foreach ($model as $key => $item) {
if( !$this->checkAccess( $item, true ) || ( $menu && !$this->checkModelAccess( true, $item->code ) ) ) unset($model[$key]);
}
return array_values($model);
}
public function cutText($str, $max_char = 255){
if( mb_strlen($str,"UTF-8") >= $max_char-3 ){
$str = mb_substr($str, 0, $max_char-3,"UTF-8")."...";
}
return $str;
}
public function declOfNum($number, $titles){
$cases = array (2, 0, 1, 1, 1, 2);
return $number." ".$titles[ ($number%100 > 4 && $number %100 < 20) ? 2 : $cases[min($number%10, 5)] ];
}
public function getTextTime($sec){
$min = intval($sec/60);
$hours = floor($min/60)%(24);
$days = floor($min/24/60);
$minutes = $min%60;
$sec = $sec%60;
if( $days ){
$out = $days."ะด. ";
}else{
$out = "";
}
if( $hours ){
$out .= $hours."ั. ";
}
if( $minutes && !$days ){
$out .= $minutes."ะผ. ";
}
if( $sec && !$days && !$hours ){
$out .= $sec."ั.";
}
return trim($out);
}
public function DownloadFile($source,$filename) {
if (file_exists($source)) {
if (ob_get_level()) {
ob_end_clean();
}
$arr = explode(".", $source);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$filename.".".array_pop($arr) );
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($source));
readfile($source);
exit;
}
}
public function implodeValues($arr){
$out = array();
foreach ($arr as $key => $value) {
$out[] = $value->value;
}
return implode("/",$out);
}
public function getParam($category,$code){
if( $this->settings == NULL ) $this->getSettings();
$category_code = mb_strtoupper($category,"UTF-8");
$param_code = mb_strtoupper($code,"UTF-8");
return ( isset($this->settings[$category_code][$param_code]) )?$this->settings[$category_code][$param_code]:"";
}
public function setParam($category,$code,$value){
$model = Settings::model()->with("category")->find("category.code='".$category."' AND t.code='".$code."'");
$model->value = $value;
$this->settings[$category][$code] = $value;
return $model->save();
}
public function getSettings(){
$model = Category::model()->findAll();
foreach ($model as $category) {
foreach ($category->settings as $param) {
$category_code = mb_strtoupper($category->code,"UTF-8");
$param_code = mb_strtoupper($param->code,"UTF-8");
if( !isset($this->settings[$category_code]) ) $this->settings[$category_code] = array();
$this->settings[$category_code][$param_code] = $param->value;
}
}
}
public function getImages($good, $number = NULL)
{
$imgs = array();
$path = Yii::app()->params["imageFolder"];
$code = $good->fields_assoc[3]->value;
if($good->good_type_id==1) $path .= "/tires/";
if($good->good_type_id==2) $path .= "/discs/";
$dir = $path.$code;
if (is_dir($dir)) {
$imgs = array_values(array_diff(scandir($dir), array('..', '.', 'Thumbs.db')));
$dir = Yii::app()->request->baseUrl."/".$path.$code;
if(count($imgs)) {
if($number) {
for ($i=0; $i < $number; $i++) {
$imgs[$i] = $dir."/".$imgs[$i];
}
} else {
foreach ($imgs as $key => &$value) {
$value = $dir."/".$value;
}
}
} else {
array_push($imgs, Yii::app()->request->baseUrl."/".$path."/default.jpg");
}
}
else {
array_push($imgs, Yii::app()->request->baseUrl."/".$path."/default.jpg");
}
return $imgs;
}
public function updateRows($table_name,$values = array(),$update){
$result = true;
if( count($values) ){
$query = Yii::app()->db->createCommand("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '".$table_name."'")->query();
$structure = array();
$primary_keys = array();
$columns = array();
$vals = array();
while($next = $query->read()){
array_push($columns, "`".$next["COLUMN_NAME"]."`");
if( $next["COLUMN_KEY"] == "PRI" ) array_push($primary_keys, "`".$next["COLUMN_NAME"]."`");
$structure[$next["COLUMN_NAME"]] = $next["COLUMN_TYPE"]." ".(($next["IS_NULLABLE"] == "NO" && $next["EXTRA"] != "auto_increment")?"NOT ":"")."NULL";
}
$structure[0] = "PRIMARY KEY (".implode(",", $primary_keys).")";
$tmpName = "tmp_".md5(rand().time());
Yii::app()->db->createCommand()->createTable($tmpName, $structure, 'ENGINE=InnoDB');
$sql = "INSERT INTO `$tmpName` (".implode(",", $columns).") VALUES ";
foreach ($values as $arr) {
$strArr = array();
foreach ($arr as $item) {
array_push($strArr, ( $item === NULL )?"NULL":("'".$item."'"));
}
array_push($vals, "(".implode(",", $strArr).")");
}
$sql .= implode(",", $vals);
foreach ($update as &$item) {
$item = " ".$table_name.".".$item." = ".$tmpName.".".$item;
}
if( Yii::app()->db->createCommand($sql)->execute() ){
$sql = "INSERT INTO `$table_name` SELECT * FROM `$tmpName` ON DUPLICATE KEY UPDATE".implode(",", $update);
$result = Yii::app()->db->createCommand($sql)->execute();
Yii::app()->db->createCommand()->dropTable($tmpName);
}else $result = false;
}
return $result;
}
}<file_sep>/protected/views/good/_form.php
<div class="form b-good-form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'faculties-form',
'enableAjaxValidation'=>false,
)); ?>
<?php echo $form->errorSummary($model); ?>
<div class="clearfix">
<? foreach ($model->type->fields as $item): ?>
<div class="row">
<label><?=$item->attribute->name?></label>
<? if($item->attribute->list): ?>
<? if($item->attribute->multi): ?>
<? $selected = array(); if(!empty($result[$item->attribute_id])) foreach ($result[$item->attribute_id] as $multi) $selected[$multi] = array('selected' => 'selected'); ?>
<?php echo Chtml::dropDownList("Good_attr[".$item->attribute_id."]", "", CHtml::listData(AttributeVariant::model()->findAll(array("condition" => "attribute_id=".$item->attribute_id,"order" => "sort ASC")), 'id', $item->attribute->type->code.'_value'),array('class'=> 'select2','multiple' => 'true', 'options' => $selected)); ?>
<? else: ?>
<?php echo Chtml::dropDownList("Good_attr[".$item->attribute_id."][single]", $result[$item->attribute_id], CHtml::listData(AttributeVariant::model()->findAll(array("condition" => "attribute_id=".$item->attribute_id,"order" => "sort ASC")), 'id', $item->attribute->type->code.'_value'),array('class'=> 'select2',"empty" => "ะะต ะทะฐะดะฐะฝะพ")); ?>
<? endif; ?>
<? else:?>
<?php echo Chtml::textField("Good_attr[".$item->attribute_id."]",$result[$item->attribute_id],array('maxlength'=>255)); ?>
<?endif;?>
</div>
<? endforeach; ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'ะะพะฑะฐะฒะธัั' : 'ะกะพั
ัะฐะฝะธัั'); ?>
<input type="button" onclick="$.fancybox.close(); return false;" value="ะัะผะตะฝะธัั">
</div>
<?php $this->endWidget(); ?>
</div><!-- form --><file_sep>/protected/views/data/adminDictionaryEdit.php
<h1><?=$model->name?></h1>
<a href="<?php echo $this->createUrl('/'.$this->adminMenu["cur"]->code.'/admindictionary')?>" class="b-link-back">ะะฐะทะฐะด</a>
<?php $form=$this->beginWidget('CActiveForm', array( 'id'=>'b-matrix-form' )); ?>
<a href="#" onclick="$(this).parents('form').submit(); return false;" class="b-butt b-top-butt">ะกะพั
ัะฐะฝะธัั</a>
<table class="b-table" border="1">
<? if( count($data) ): ?>
<? foreach ($data as $i => $item): ?>
<tr>
<td class="tleft"><?=$item->value?></td>
<td class="b-table-td-editable">
<input type="hidden" name="Values[<?=$i?>][attribute_1]" value="<?=$item->id?>">
<input type="text" name="Values[<?=$i?>][value]" value="<?=((isset($values[$item->id]))?$values[$item->id]:"")?>">
</td>
</tr>
<? endforeach; ?>
<? else: ?>
<tr>
<td colspan=10>ะัััะพ</td>
</tr>
<? endif; ?>
</table>
<?php $this->endWidget(); ?><file_sep>/protected/views/good/adminIndex.php
<h1><?=$name?></h1>
<?php $form=$this->beginWidget('CActiveForm'); ?>
<table class="b-table" border="1">
<tr>
<th> </th>
<? foreach ($fields as $field): ?>
<th><? echo $field->attribute->name; ?></th>
<? endforeach; ?>
</tr>
<? if( count($data) ): ?>
<? foreach ($data as $i => $item): ?>
<tr>
<td><a href="<?php echo Yii::app()->createUrl('/good/adminupdate',array('id'=>$item->id,'goodTypeId' => $_GET['goodTypeId'],'Good_page' => ($pages->currentPage+1) ))?>" class="ajax-form ajax-update b-tool b-tool-update" title="ะ ะตะดะฐะบัะธัะพะฒะฐัั"></a></td>
<? foreach ($fields as $field): ?>
<td>
<? if( isset($item->fields_assoc[$field->attribute->id]) ): ?>
<? if( is_array($item->fields_assoc[$field->attribute->id]) ): ?>
<? foreach ($item->fields_assoc[$field->attribute->id] as $attr): ?>
<div><?=$attr->value?></div>
<? endforeach; ?>
<? else: ?>
<div><?=$item->fields_assoc[$field->attribute->id]->value?></div>
<? endif; ?>
<? endif; ?>
</td>
<? endforeach; ?>
</tr>
<? endforeach; ?>
<? else: ?>
<tr>
<td colspan=10>ะัััะพ</td>
</tr>
<? endif; ?>
</table>
<?php $this->endWidget(); ?>
<?php $this->widget('CLinkPager', array(
'header' => '',
'lastPageLabel' => 'ะฟะพัะปะตะดะฝัั »',
'firstPageLabel' => '« ะฟะตัะฒะฐั',
'pages' => $pages,
'prevPageLabel' => '< ะฝะฐะทะฐะด',
'nextPageLabel' => 'ะดะฐะปะตะต >'
)) ?><file_sep>/protected/views/attribute/_form.php
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'faculties-form',
'enableAjaxValidation'=>false,
)); ?>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->textField($model,'name',array('maxlength'=>255,'required'=>true)); ?>
<?php echo $form->error($model,'name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'attribute_type_id'); ?>
<?php echo $form->DropDownList($model,'attribute_type_id',CHtml::listData(AttributeType::model()->findAll(array('order'=>'id ASC')), 'id', 'name')); ?>
<?php echo $form->error($model,'attribute_type_id'); ?>
</div>
<div class="row">
<?php echo $form->CheckBox($model,'multi',array("class"=>"b-checkbox")); ?>
<?php echo $form->labelEx($model,'multi'); ?>
<?php echo $form->error($model,'multi'); ?>
</div>
<div class="row">
<?php echo $form->CheckBox($model,'list',array("class"=>"b-checkbox")); ?>
<?php echo $form->labelEx($model,'list'); ?>
<?php echo $form->error($model,'list'); ?>
</div>
<div class="row">
<?php echo $form->CheckBox($model,'dynamic',array("class"=>"b-checkbox")); ?>
<?php echo $form->labelEx($model,'dynamic'); ?>
<?php echo $form->error($model,'dynamic'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'width'); ?>
<?php echo $form->textField($model,'width',array('maxlength'=>255,'required'=>true,'class'=>'numeric')); ?>
<?php echo $form->error($model,'width'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'ะะพะฑะฐะฒะธัั' : 'ะกะพั
ัะฐะฝะธัั'); ?>
<input type="button" onclick="$.fancybox.close(); return false;" value="ะัะผะตะฝะธัั">
</div>
<?php $this->endWidget(); ?>
</div><!-- form --><file_sep>/avito/index.php
<?
include_once(dirname(__FILE__).'/simple_html_dom.php');
$html = new simple_html_dom();
$ch = curl_init();
$url = "https://www.avito.ru/profile/login";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_REFERER, "https://www.avito.ru");
curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__).'/cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__).'/cookie.txt');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'next'=>'/profile',
'login'=>'<EMAIL>',
'password'=>'<PASSWORD>'
));
curl_exec( $ch );
$url = "https://www.avito.ru/additem/image";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'image'=>'@'.dirname(__FILE__)."/1.jpg"
));
$image_id = json_decode(curl_exec( $ch ))->id;
$url = "https://www.avito.ru/additem";
curl_setopt($ch, CURLOPT_URL, $url);
$html = str_get_html(curl_exec( $ch ));
$token = array();
$token['name'] = $html->find('input[name^=token]',0)->name;
$token['value'] = $html->find('input[name^=token]',0)->value;
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
$token['name'] => $token['value'],
'email'=>'<EMAIL>',
'authState'=>'phone-edit',
'private' => 1,
'seller_name' => "ะะปะฐะดะธัะปะฐะฒ",
'phone' => '8+952+896-09-88',
'root_category_id' => 1,
'category_id' => 10,
'params[5]' => 19,
'params[709]' => 10048,
'location_id' => 657600,
'metro_id' => "",
'district_id' => "",
'road_id' => "",
'params[733]' => 10359,
'params[734]' => 10376,
'params[731]' => 10312,
'params[732]' => 10340,
'title' => 'ะจะธะฝั',
'description' => 'ะจะธะฝั',
'price' => 1000,
'images[]' => $image_id,
'rotate['.$image_id.']' => 0,
'image' => "",
'videoUrl' => "",
'service_code' => 'free'
));
$html = str_get_html(curl_exec( $ch ));
$captcha = $html->find('.form-captcha-image',0)->src;
curl_setopt($ch, CURLOPT_URL, 'https://www.avito.ru'.$captcha);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$out = curl_exec($ch);
$image_sv = dirname(__FILE__).'/123.jpg';
file_put_contents($image_sv, $out);
$url = "http://rucaptcha.com/in.php";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'key'=>'0b07ab2862c1ad044df277cbaf7ceb99',
'file'=> '@'.$image_sv
));
$captcha = curl_exec($ch);
while ($captcha == 'ERROR_NO_SLOT_AVAILABLE') {
sleep(5);
$captcha = curl_exec($ch);
}
if(strpos($captcha, "|") !== false) {
$captcha = substr($captcha, 3);
$url = "http://rucaptcha.com/res.php?";
$params = array(
'key' => '0b07ab2862c1ad044df277cbaf7ceb99',
'action' => 'get',
'id' => $captcha
);
$url .= urldecode(http_build_query($params));
curl_setopt($ch, CURLOPT_URL, $url);
$captcha = curl_exec($ch);
while ($captcha == 'CAPCHA_NOT_READY') {
sleep(1);
$captcha = curl_exec($ch);
}
if(strpos($captcha, "|") !== false) {
$captcha = substr($captcha, 3);
$url = "https://www.avito.ru/additem/confirm";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'captcha' => $captcha,
'done' => "",
'subscribe-position' => '0'
));
print_r(curl_exec($ch));
} else {
die($captcha."ะ ะะกะจะะคะ ะะะะ ะะ ะะ ะะจะะ");
}
} else {
die($captcha."ะะะะขะงะ ะะ ะะขะะ ะะะะะะกะฌ");
}
curl_close($ch);
?>
<file_sep>/protected/extensions/Curl.php
<?
Class Curl {
public $cookie;
function __construct() {
$this->cookie = md5(rand().time());
$this->removeCookies();
}
public function request($url,$post = NULL){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
// curl_setopt($ch, CURLOPT_MAXFILESIZE, 1024*1024*10);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
if (!is_dir(dirname(__FILE__).'/cookies')) mkdir(dirname(__FILE__).'/cookies',0777, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__).'/cookies/'.$this->cookie.'.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__).'/cookies/'.$this->cookie.'.txt');
if( $post != NULL ){
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
}
$result = curl_exec($ch);
curl_close( $ch );
return $result;
}
public function removeCookies(){
if( file_exists(dirname(__FILE__).'/cookies/'.$this->cookie.'.txt') )
unlink(dirname(__FILE__).'/cookies/'.$this->cookie.'.txt');
}
}
?><file_sep>/photodoska/js/main.js
$(document).ready(function(){
var maxfiles = 1,
error = false;
$("#uploaderPj").pluploadQueue({
runtimes : 'html5',
url : "upload.php",
max_file_size : '30mb',
max_file_count: maxfiles,
chunk_size : '1mb',
unique_names : true,
multi_selection:false,
resize: {
width: 800,
height: 600
},
filters : [
{title : "Documents", extensions : "xls,xlsx"}
],
init : {
FilesAdded: function(up, files) {
for( var i = up.files.length-1 ; i > 0 ; i-- ){
if( i >= maxfiles ) up.files.splice(i,1);
}
if (up.files.length >= maxfiles) {
$('.plupload_add').hide();
$('#uploaderPj').addClass("blocked_brow");
}
$(".max-files-count").html( maxfiles - up.files.length );
},
FilesRemoved: function(up, files) {
$(".max-files-count").html( maxfiles - up.files.length );
if (up.files.length < maxfiles) {
$('.plupload_add').show();
$('#uploaderPj').removeClass("blocked_brow");
}
},
UploadComplete: function(){
if( !error ){
$(".plupload_save").click();
$(".b-save-buttons").fadeIn(300);
}
},
FileUploaded: function(upldr, file, object) {
var myData;
try {
myData = eval(object.response);
} catch(err) {
myData = eval('(' + object.response + ')');
}
if( myData.result != "success" ){
error = true;
alert(myData.error.message);
}
}
}
});
if( !maxfiles ){
$('.plupload_add').addClass("plupload_disabled");
$('#uploaderPj').addClass("blocked_brow");
}
// $(".plupload_save").click(function(){
// alert($("input[name='uploaderPj_0_tmpname']").val());
// });
});<file_sep>/protected/controllers/AttributeController.php
<?php
class AttributeController extends Controller
{
public function filters()
{
return array(
'accessControl'
);
}
public function accessRules()
{
return array(
array('allow',
'actions'=>array('adminIndex','adminCreate','adminUpdate','adminDelete','adminEdit'),
'roles'=>array('manager'),
),
array('allow',
'actions'=>array('index'),
'users'=>array('*'),
),
array('deny',
'users'=>array('*'),
),
);
}
public function actionAdminCreate()
{
$model=new Attribute;
if(isset($_POST['Attribute']))
{
$model->attributes=$_POST['Attribute'];
if($model->save()){
$this->actionAdminIndex(true);
return true;
}
}
$this->renderPartial('adminCreate',array(
'model'=>$model,
));
}
public function actionAdminUpdate($id)
{
$model=$this->loadModel($id);
if(isset($_POST['Attribute']))
{
$model->attributes=$_POST['Attribute'];
if($model->save())
$this->actionAdminIndex(true);
}else{
$this->renderPartial('adminUpdate',array(
'model'=>$model,
));
}
}
public function actionAdminEdit($id)
{
$model=$this->loadModel($id);
if( isset($_POST['Edit']) )
{
$this->updateVariants($model);
$this->actionAdminIndex(true);
}else{
$this->renderPartial('adminEdit',array(
'model'=>$model,
));
}
}
public function actionAdminDelete($id)
{
$this->loadModel($id)->delete();
$this->actionAdminIndex(true);
}
public function actionAdminIndex($partial = false)
{
if( !$partial ){
$this->layout='admin';
}
$filter = new Attribute('filter');
$criteria = new CDbCriteria();
if (isset($_GET['Attribute']))
{
$filter->attributes = $_GET['Attribute'];
foreach ($_GET['Attribute'] AS $key => $val)
{
if ($val != '')
{
if( $key == "name" ){
$criteria->addSearchCondition('name', $val);
}else{
$criteria->addCondition("$key = '{$val}'");
}
}
}
}
$criteria->order = 'id DESC';
$model = Attribute::model()->findAll($criteria);
if( !$partial ){
$this->render('adminIndex',array(
'data'=>$model,
'filter'=>$filter,
'labels'=>Attribute::attributeLabels()
));
}else{
$this->renderPartial('adminIndex',array(
'data'=>$model,
'filter'=>$filter,
'labels'=>Attribute::attributeLabels()
));
}
}
public function actionIndex($id){
$model = Rubric::model()->findByPk($id);
$this->render('index',array(
'data'=>$model->houses,
'title'=>$model->rub_name
));
}
public function loadModel($id)
{
$model=Attribute::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
public function updateVariants($model){
$tableName = AttributeVariant::tableName();
if( count($model->variants) ){
$modelArr = array();
foreach ($model->variants as $key => $value) {
$modelArr[$value->id] = $value->sort;
}
if( isset($_POST["Variants"]) ){
$delArr = array_diff_key($modelArr,$_POST["Variants"]);
}else{
$delArr = $modelArr;
}
$this->deleteVariants($delArr);
if( isset($_POST["Variants"]) ){
$tmpName = "tmp_".md5(rand().time());
Yii::app()->db->createCommand()->createTable($tmpName, array(
'id' => 'int NOT NULL',
'int_value' => 'int NULL',
'varchar_value' => 'varchar(255) NULL',
'float_value' => 'float NULL',
'attribute_id' => 'int NULL',
'sort' => 'int NOT NULL',
0 => 'PRIMARY KEY (`id`)'
), 'ENGINE=InnoDB');
$sql = "INSERT INTO `$tmpName` (`id`,`attribute_id`,`sort`) VALUES ";
$values = array();
foreach ($_POST["Variants"] as $key => $value) {
$values[] = "('".$key."','".$model->id."','".$value."')";
}
$sql .= implode(",", $values);
if( Yii::app()->db->createCommand($sql)->execute() ){
$sql = "INSERT INTO `$tableName` SELECT * FROM `$tmpName` ON DUPLICATE KEY UPDATE $tableName.sort = $tmpName.sort";
$result = Yii::app()->db->createCommand($sql)->execute();
Yii::app()->db->createCommand()->dropTable($tmpName);
}
}
}
if( isset($_POST["VariantsNew"]) ){
$sql = "INSERT INTO `$tableName` (`attribute_id`,`".$model->type->code."_value`,`sort`) VALUES ";
$values = array();
foreach ($_POST["VariantsNew"] as $key => $value) {
$values[] = "('".$model->id."','".$key."','".$value."')";
}
$sql .= implode(",", $values);
Yii::app()->db->createCommand($sql)->execute();
}
}
public function deleteVariants($delArr){
if( count($delArr) ){
$pks = array();
foreach ($delArr as $key => $value) {
$pks[] = $key;
}
$model = AttributeVariant::model()->findAllByPk($pks);
foreach ($model as $key => $value) {
$value->delete();
}
}
}
public function getArrayFromModel($model){
}
}
<file_sep>/protected/views/export/adminDynamic.php
<h1>ะัะฑะพั ะดะธะฝะฐะผะธัะตัะบะธั
ะฟะฐัะฐะผะตััะพะฒ</h1>
<?php $form=$this->beginWidget('CActiveForm',array("action"=>$this->createUrl('/export/adminpreview',array('id'=>$id)))); ?>
<div class="b-choose-dynamic">
<div class="clearfix">
<? foreach ($data as $key => $value): ?>
<div class="left b-dynamic b-choosable">
<p><label>ะัะธะผะตั</label></p>
<?php echo CHtml::dropDownList('dynamic['.$value->attribute->id.']', $value->attribute->variants[0]->id, CHtml::listData($value->attribute->variants, 'id', 'value')); ?>
<input type="hidden" name="dynamic_values[<?=$value->attribute->id?>]" value="">
<div class="b-error">ะัะถะฝะพ ะฒัะฑัะฐัั ั
ะพัั ะฑั ะพะดะธะฝ ะฟะฐัะฐะผะตัั</div>
<ul class="b-dynamic-values b-choosable-values">
<? foreach ($value->attribute->variants as $variant): ?>
<li data-id="<?=$variant->id?>" class="selected"><?=$variant->value?></li>
<? endforeach; ?>
</ul>
<div class="b-select-buttons">
<a href="#" class="b-select-all" style="margin-right: 10px;">ะัะดะตะปะธัั ะฒัะต</a>
<a href="#" class="b-select-none">ะกะฝััั ะฒัะดะตะปะตะฝะธะต</a>
</div>
</div>
<? endforeach; ?>
</div>
</div>
<a href="#" onclick="$('form').submit(); return false;" class="b-butt">ะะฐะปะตะต</a>
<?php $this->endWidget(); ?><file_sep>/test.php
<?
function getArrayValue($value,$type){
if( $value[0] == "{" && $value[strlen($value)-1] == "}" ){
$tmp = explode("|", substr($value, 1,-1));
$value = ($type == "REPLACE")?[0=>array(),1=>array()]:[];
foreach ($tmp as $v) {
$arr = explode("=", $v);
if( count($arr) == 2 ){
if( $type == "REPLACE" ){
$value[0][] = trim($arr[0]);
$value[1][] = trim($arr[1]);
}else{
$value[trim($arr[0])] = trim($arr[1]);
}
}else{
die("ะ ะฟะฐัะฐะผะตััะต \"".$type."\" ะพััััััะฒัะตั ะทะฝะฐะบ \"=\" ะธะปะธ ะพะฝ ะฟัะธัััััะฒัะตั ะฑะพะปััะต ะพะดะฝะพะณะพ ัะฐะทะฐ");
}
}
return $value;
}else{
die("ะััััััะฒัะตั ะพะดะฝะฐ ะธะปะธ ะพะฑะต ัะบะพะฑะพัะบะธ \"{}\" ั ะทะฝะฐัะตะฝะธั ะฟะฐัะฐะผะตััะฐ \"".$type."\"");
}
}
$attr = array(3=>"7821",23=>"ะะตัะพ",17=>23,7=>"225",8=>"45",9=>"18",26=>"ะฑ/ั",27=>"ะขะพะผัะบ");
$template = "#[+ATTR=3+] [+ATTR=23;ALT={ะะตัะพ=ะะตัะฝะธะต|ะะธะผะฐ=ะะธะผะฝะธะต}+] [+ATTR=17;FLOAT=2;REPLACE={,=.}+] [+ATTR=7+]/[+ATTR=8+]/[+ATTR=9+] [+ATTR=26+] ะฒ [+ATTR=27;ALT={ะขะพะผัะบ=ะขะพะผัะบะต|ะะพะฒะพัะธะฑะธััะบ=ะะพะฒะพัะธะฑะธััะบะต}+]";
preg_match_all("~\[\+([^\+\]]+)\+\]~", $template, $matches);
$rules = $matches[1];
foreach ($rules as $i => $rule) {
$tmp = explode(";", $rule);
$params = [];
foreach ($tmp as $param) {
$index = stripos($param, "=");
if( $index > 0 ){
$key = substr($param,0,$index);
$value = substr($param, $index+1);
$params[trim($key)] = trim($value);
}else{
die("ะััััััะฒัะตั ะทะฝะฐะบ \"=\" ั ะฟะฐัะฐะผะตััะฐ \"".$param."\"");
}
}
if( isset($params["ALT"]) ){
$params["ALT"] = getArrayValue($params["ALT"],"ALT");
}
if( isset($params["REPLACE"]) ){
$params["REPLACE"] = getArrayValue($params["REPLACE"],"REPLACE");
}
if( isset($params["ATTR"]) ){
$val = ( isset($attr[intval($params["ATTR"])]) )?$attr[intval($params["ATTR"])]:"";
$val = ( isset($params["FLOAT"]) )?number_format((float)$val,intval($params["FLOAT"])):$val;
if( isset($params["REPLACE"]) ){
$val = str_replace($params["REPLACE"][0], $params["REPLACE"][1], $val);
}
$matches[1][$i] = ( isset($params["ALT"]) && isset($params["ALT"][$val]) )?$params["ALT"][$val]:$val;
}else{
die("ะััััััะฒัะตั ะฟะฐัะฐะผะตัั \"ATTR\"");
}
}
$result = str_replace($matches[0], $matches[1], $template);
print_r($result);
?><file_sep>/protected/views/interpreter/_form.php
<div class="form b-full-width">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'faculties-form',
'enableAjaxValidation'=>false,
)); ?>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->textField($model,'name',array('maxlength'=>255,'required'=>true)); ?>
<?php echo $form->error($model,'name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'good_type_id'); ?>
<?php echo $form->dropDownList($model, 'good_type_id', CHtml::listData(GoodType::model()->findAll(), 'id', 'name')); ?>
<?php echo $form->error($model,'good_type_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'category_id'); ?>
<?php echo $form->dropDownList($model, 'category_id', CHtml::listData(Category::model()->findAll(), 'id', 'name')); ?>
<?php echo $form->error($model,'category_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'template'); ?>
<?php echo $form->textArea($model,'template',array('maxlength'=>20000,'required'=>true,'style'=>'height: 300px;')); ?>
<?php echo $form->error($model,'template'); ?>
</div>
<? if( Yii::app()->user->checkAccess("rootActions") ): ?>
<div class="row">
<?php echo $form->labelEx($model,'rule_code'); ?>
<?php echo $form->DropDownList($model,'rule_code',CHtml::listData(Rule::model()->findAll(array('order'=>'name ASC')), 'code', 'name')); ?>
<?php echo $form->error($model,'rule_code'); ?>
</div>
<? endif; ?>
<div class="row">
<?php echo $form->labelEx($model,'width'); ?>
<?php echo $form->textField($model,'width',array('maxlength'=>255,'required'=>true,'class'=>'numeric')); ?>
<?php echo $form->error($model,'width'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'ะะพะฑะฐะฒะธัั' : 'ะกะพั
ัะฐะฝะธัั'); ?>
<input type="button" onclick="$.fancybox.close(); return false;" value="ะัะผะตะฝะธัั">
</div>
<?php $this->endWidget(); ?>
</div><!-- form --><file_sep>/protected/controllers/InterpreterController.php
<?php
class InterpreterController extends Controller
{
public function filters()
{
return array(
'accessControl'
);
}
public function accessRules()
{
return array(
array('allow',
'actions'=>array('adminIndex','adminCreate','adminUpdate','adminDelete','adminPreview'),
'roles'=>array('manager'),
),
array('deny',
'users'=>array('*'),
),
);
}
public function actionAdminCreate()
{
$model=new Interpreter;
if(isset($_POST['Interpreter']))
{
$model->attributes=$_POST['Interpreter'];
if($model->save()){
$this->actionAdminIndex(true);
return true;
}
}
$this->renderPartial('adminCreate',array(
'model'=>$model,
));
}
public function actionAdminUpdate($id)
{
$model=$this->loadModel($id);
$this->checkAccess($model);
if(isset($_POST['Interpreter']))
{
$model->attributes=$_POST['Interpreter'];
if($model->save())
$this->actionAdminIndex(true);
}else{
$this->renderPartial('adminUpdate',array(
'model'=>$model,
));
}
}
public function actionAdminDelete($id)
{
$this->checkAccess( Interpreter::model()->findByPk($id) );
$this->loadModel($id)->delete();
$this->actionAdminIndex(true);
}
public function actionAdminIndex($partial = false)
{
if( !$partial ){
$this->layout='admin';
}
$filter = new Interpreter('filter');
$criteria = new CDbCriteria();
if (isset($_GET['Interpreter']))
{
$filter->attributes = $_GET['Interpreter'];
foreach ($_GET['Interpreter'] AS $key => $val)
{
if ($val != '')
{
$criteria->addSearchCondition($key, $val);
}
}
}
$criteria->order = 'id DESC';
$model = Interpreter::model()->findAll($criteria);
if( !$partial ){
$this->render('adminIndex',array(
'data'=>$model,
'filter'=>$filter,
'labels'=>Interpreter::attributeLabels()
));
}else{
$this->renderPartial('adminIndex',array(
'data'=>$model,
'filter'=>$filter,
'labels'=>Interpreter::attributeLabels()
));
}
}
public function actionAdminPreview($id)
{
$inter = Interpreter::model()->findByPk($id);
$criteria = new CDbCriteria();
$criteria->condition = "good_type_id=".$inter->good_type_id;
$criteria->limit = 30;
$criteria->with = array("fields.variant");
$model = Good::model()->findAll($criteria);
$criteria = new CDbCriteria();
$criteria->with = array("goodTypes","variants");
$criteria->condition = "goodTypes.good_type_id=".$inter->good_type_id." AND dynamic=1";
$modelDyn = Attribute::model()->findAll($criteria);
$dynamic = array();
$dynObjects = array();
foreach ($modelDyn as $key => $value) {
$current = ( isset($_POST["dynamic"][$value->id]) )?$_POST["dynamic"][$value->id]:$value->variants[0]->id;
$curObj = AttributeVariant::model()->findByPk($current);
$dynamic[$value->id] = array("CURRENT" => $curObj->id, "ALL" => $value->variants);
$dynObjects[$value->id] = (object) array("value"=>$curObj->value,"variant_id"=>$curObj->id);
}
$data = array();
foreach ($model as $item) {
$data[] = array("ID"=>$item->fields_assoc[3]->value,"VALUE"=>$this->replaceToBr(Interpreter::generate($id,$item,$dynObjects)));
}
$this->renderPartial('adminPreview',array(
'data'=>$data,
'dynamic'=>$dynamic
));
}
public function loadModel($id)
{
$model=Interpreter::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
}
<file_sep>/protected/extensions/Drom.php
<?
Class Drom {
private $login = "";
private $password = "";
public $curl;
function __construct() {
$this->curl = new Curl();
}
public function setUser($login,$password){
$this->login = $login;
$this->password = $password;
}
public function auth($redirect = ""){
$this->curl->removeCookies();
$params = array(
'sign' => $this->login,
'password' => $this->password
);
return iconv('windows-1251', 'utf-8', $this->curl->request("https://www.farpost.ru/sign?mode=openid&return=".urlencode($redirect)."&login_by_password=1",$params));
}
public function upAdverts(){
$links = $this->parseExpired();
$upLinks = array();
Log::debug("ะะพะปัะทะพะฒะฐัะตะปั ".$this->login." ".count($links)." ะฝะตะฐะบัะธะฒะฝัั
ะพะฑััะฒะปะตะฝะธะน");
foreach ($links as $key => $value) {
$index = floor($key/50);
$upLinks[$index] = $upLinks[$index]."&bulletin%5B".$value."%5D=on";
}
foreach ($upLinks as $key => $value) {
$url = "http://baza.drom.ru/bulletin/service-configure?return_to=%2Fpersonal%2Fnon_active%2Fbulletins%3Fpage%3D2&from=personal.non_active&applier%5BprolongBulletin%5D=prolongBulletin".$value."=on¬e=";
$this->curl->request($url);
}
}
public function parseExpired(){
include_once Yii::app()->basePath.'/extensions/simple_html_dom.php';
$html = str_get_html($this->auth("http://baza.drom.ru/personal/non_active/bulletins"));
$links = array();
$pageLinks = $html->find('.bullNotPublished');
$page = 1;
while(count($pageLinks)){
foreach($pageLinks as $element){
$exp = $element->find(".expired");
if( count($exp) )
array_push($links, $element->find(".bulletinLink",0)->getAttribute("name"));
}
$page++;
$html = str_get_html(iconv('windows-1251', 'utf-8', $this->curl->request("http://baza.drom.ru/personal/non_active/bulletins?page=".$page)));
$pageLinks = $html->find('.bullNotPublished');
}
return $links;
}
public function addAdvert($params,$images){
$options = $this->setOptions($params);
$advert_id = json_decode($this->curl->request("http://baza.drom.ru/api/1.0/save/bulletin",$options))->id;
$this->updateAdvert($advert_id,$params,$images);
$this->curl->request("http://baza.drom.ru/bulletin/".$advert_id."/draft/publish?from=draft.publish",array('from'=>'adding.publish'));
}
public function updateAdvert($advert_id,$params,$images = NULL) {
if($images) {
foreach ($images as &$image_path) {
$image_path = json_decode($this->curl->request("http://baza.drom.ru/upload-image-jquery",array('up[]' => '@'.Yii::app()->basePath.DIRECTORY_SEPARATOR.'..'.$image_path)))->id;
}
$params['images'] = array('images' => $images);
}
$options = $this->setOptions($params,$advert_id);
$this->curl->request("http://baza.drom.ru/api/1.0/save/bulletin",$options);
}
public function deleteAdverts($arr) {
include_once Yii::app()->basePath.'/extensions/simple_html_dom.php';
$html = str_get_html($this->curl->request('https://baza.drom.ru/bulletin/service-configure?ids='.$arr[0].'&applier=deleteBulletin'));
$del_arr = array(
'applier' => 'deleteBulletin',
'uid' => $html->find('input[name="uid"]', 0)->value,
'price' => 0,
'order_id' => 0,
'return_to' => ''
);
foreach ($arr as $key => $value) {
$del_arr['bulletin['.$value.']']= 'on';
}
$this->curl->request('https://baza.drom.ru/bulletin/service-apply',$del_arr);
}
public function setOptions($params,$advert_id = NULL) {
$options = array(
'cityId' => $params['cityId'],
'bulletinType'=>'bulletinRegular',
'directoryId'=> $params['dirId'],
'fields'=> $params
);
if($advert_id) {
if(isset($params['images'])) {
$options['images'] = $params['images'];
}
$options['id'] = $advert_id;
}
$options = array('changeDescription' => json_encode($options));
$options['client_type'] = ($advert_id) ? 'v2:editing' : "v2:adding";
return $options;
}
}
?><file_sep>/protected/controllers/DesktopController.php
<?php
class DesktopController extends Controller
{
public function filters()
{
return array(
'accessControl'
);
}
public function accessRules()
{
return array(
array('allow',
'actions'=>array('adminIndex','adminCreate','adminUpdate','adminDelete'),
'roles'=>array('manager'),
),
array('deny',
'users'=>array('*'),
),
);
}
public function actionAdminCreate()
{
$model=new Desktop;
if(isset($_POST['Desktop']))
{
$model->attributes=$_POST['Desktop'];
if($model->save()){
$this->actionAdminIndex(true);
return true;
}
}
$this->renderPartial('adminCreate',array(
'model'=>$model,
));
}
public function actionAdminUpdate($id)
{
$model=$this->loadModel($id);
$this->checkAccess($model);
if(isset($_POST['Desktop']))
{
$model->attributes=$_POST['Desktop'];
if($model->save())
$this->actionAdminIndex(true);
}else{
$this->renderPartial('adminUpdate',array(
'model'=>$model,
));
}
}
public function actionAdminDelete($id)
{
$this->checkAccess( Desktop::model()->findByPk($id) );
$this->loadModel($id)->delete();
$this->actionAdminIndex(true);
}
public function actionAdminIndex($partial = false)
{
if( !$partial ){
$this->layout='admin';
}
$filter = new Desktop('filter');
$criteria = new CDbCriteria();
if (isset($_GET['Desktop']))
{
$filter->attributes = $_GET['Desktop'];
foreach ($_GET['Desktop'] AS $key => $val)
{
if ($val != '')
{
$criteria->addSearchCondition($key, $val);
}
}
}
$criteria->order = 'sort ASC, name ASC';
$model = Desktop::model()->findAll($criteria);
foreach ($model as $key => $value) {
if(!$this->checkAccess($value,true)) unset($model[$key]);
}
if( !$partial ){
$this->render('adminIndex',array(
'data'=>$model,
'filter'=>$filter,
'labels'=>Desktop::attributeLabels()
));
}else{
$this->renderPartial('adminIndex',array(
'data'=>$model,
'filter'=>$filter,
'labels'=>Desktop::attributeLabels()
));
}
}
public function loadModel($id)
{
$model=Desktop::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
}
<file_sep>/protected/controllers/DromController.php
<?php
class DromController extends Controller
{
private $drom_params = array(
"1" => array(
"subject" => array("type" => 'inter',"id" => 8),
"cityId" => array("type" => 'inter',"id" => 31),
"goodPresentState" => array("type" => 'inter',"id" => 102),
"model" => array("type" => 'inter',"id" => 12),
"inSetQuantity" => array("type" => 'attr',"id" => 28),
"wheelSeason" => array("type" => 'inter',"id" => 101),
"wheelTireWear" => array("type" => 'attr',"id" => 29),
"year" => array("type" => 'attr',"id" => 10),
"wheelSpike" => array("type" => 'inter',"id" => 104),
"price" => array("type" => 'inter',"id" => 45),
"marking" => array("type" => 'inter',"id" => 13),
"text" => array("type" => 'inter',"id" => 10),
"pickupAddress" => array("type" => 'inter',"id" => 40),
"localPrice" => array("type" => 'inter',"id" => 39),
"minPostalPrice" => array("type" => 'inter',"id" => 38),
"comment" => array("type" => 'inter',"id" => 72),
"guarantee" => array("type" => 'inter',"id" => 73),
),
"2" => array(
"price" => array("type" => 'inter',"id" => 22),
"subject" => array("type" => 'inter',"id" => 17),
"cityId" => array("type" => 'inter',"id" => 30),
"goodPresentState" => array("type" => 'inter',"id" => 103),
"model" => array("type" => 'inter',"id" => 92),
"condition" => array("type" => 'inter',"id" => 108),
"wheelDiameter" => array("type" => 'attr',"id" => 9),
"inSetQuantity" => array("type" => 'attr',"id" => 28),
"wheelPcd" => array("type" => 'attr',"id" => 5),
"price" => array("type" => 'inter',"id" => 22),
"wheelWeight" => array("type" => 'attr',"id" => 34),
"diskHoleDiameter" => array("type" => 'attr',"id" => 33),
"disc_width" => array("type" => 'inter',"id" => 93),
"disc_et" => array("type" => 'attr',"id" => 32),
"text" => array("type" => 'inter',"id" => 21),
"pickupAddress" => array("type" => 'inter',"id" => 41),
"localPrice" => array("type" => 'inter',"id" => 37),
"minPostalPrice" => array("type" => 'inter',"id" => 36),
"comment" => array("type" => 'inter',"id" => 32),
"guarantee" => array("type" => 'inter',"id" => 29),
)
);
public function filters()
{
return array(
'accessControl'
);
}
public function accessRules()
{
return array(
array('allow',
'users'=>array('*'),
),
);
}
// ะัะพะผ ------------------------------------------------------------------ ะัะพะผ
public function actionCreate(){
$good = Good::model()->find("id=1181");
$images = $this->getImages($good);
$dynamic = array( 38 => 1081, 37 => 869);
$drom = new Drom();
$drom->setUser("79528960988","aeesnb33");
$drom->auth("http://baza.drom.ru/personal/");
$drom->addAdvert($this->getParams($good,$dynamic),$images);
$drom->curl->removeCookies();
}
public function actionUpdate($images = NULL){
$url = "http://tomsk.baza.drom.ru/n1011-letnjaja-para-yokohama-dna-ecos-es300-215-40-17-japan-b-u-38913568.html";
$advert_id = substr($url, strrpos($url, "-")+1,-5);
$good = Good::model()->find("id=1181");
if($images) $images = $this->getImages($good);
$dynamic = array( 38 => 1081, 37 => 869);
$drom = new Drom();
$drom->setUser("79528960988","aeesnb33");
$drom->auth("http://baza.drom.ru/personal/");
$drom->updateAdvert($advert_id,$this->getParams($good,$dynamic),$images);
$drom->curl->removeCookies();
}
public function actionDelete(){
$drom = new Drom();
$drom->setUser("79528960988","aeesnb33");
$drom->auth("http://baza.drom.ru/personal/");
$drom->deleteAdverts(array("38916734","38916795"));
$drom->curl->removeCookies();
}
// ะัะพะผ ------------------------------------------------------------------ ะัะพะผ
public function getParams($good,$dynamic) {
foreach ($this->drom_params[$good->good_type_id] as $key => $value) {
if($value['type']=="attr") {
if(isset($good->fields_assoc[$value['id']])) {
if(is_array($good->fields_assoc[$value['id']])) {
foreach ($good->fields_assoc[$value['id']] as $i => $item) {
if($key=='wheelPcd') {
$item = explode("*", $item->value);
$item[1] = number_format ($item[1],2);
$params[$key][$i] = $item[1]."x".$item[0];
}else $params[$key][$i] = $item->value;
}
} else if($key=='wheelPcd') {
$pcd = explode("*", $good->fields_assoc[$value['id']]->value);
$pcd[1] = number_format ($pcd[1],2);
$params[$key] = $pcd[1]."x".$pcd[0];
} else $params[$key] = $good->fields_assoc[$value['id']]->value;
} else $params[$key] = null;
} else {
$params[$key] = Interpreter::generate($value['id'],$good,$this->getDynObjects($dynamic,$good->good_type_id));
}
}
$params['model'] = array($params["model"],0,0);
$params['price'] = array($params["price"],"RUB");
$params['quantity'] = 1;
$params['contacts'] = array("email" => "","is_email_hidden" => false,"contactInfo" => "+79528960999");
$params['delivery'] = array("pickupAddress" => $params['pickupAddress'],"localPrice" => $params['localPrice'],"minPostalPrice" => $params['minPostalPrice'],"comment" => $params['comment']);
unset($params['pickupAddress'],$params['localPrice'],$params['minPostalPrice'],$params['comment']);
if($good->good_type_id== "1") {
$params['dirId'] = 234;
$params['predestination'] = "regular";
}
if($good->good_type_id== "2") {
$params['dirId'] = 235;
$disc_width = explode("/",$params['disc_width']);
$params['discParameters'] = array();
foreach ($disc_width as $i => $value) {
$params['discParameters'][$i]["disc_width"] = $value;
if(is_array($params['disc_et'])) {
$params['discParameters'][$i]["disc_et"] = (isset($params['disc_et'][$i])) ? $params['disc_et'][$i] : null;
} else $params['discParameters'][0]["disc_et"] = $params['disc_et'];
}
if(is_array($params['disc_et']))
foreach ($params['disc_et'] as $j => $value) {
$params['discParameters'][$j]["disc_width"] = (isset($disc_width[$j])) ? $disc_width[$j] : null;
$params['discParameters'][$j]["disc_et"] = $value;
}
unset($params['disc_width'],$params['disc_et'],$disc_width);
}
return $params;
}
public function actionAdminIndex(){
}
}
| 4221c56ee2b67803780b80a29f2d666d30f69968 | [
"JavaScript",
"PHP"
] | 24 | JavaScript | mikhkita/ur-ksmot-oselok | eebe5514e13bcea0ee17a54e32784c3af87b1578 | 1a212eae519ac1844513549c317b66b5ef93c310 |
refs/heads/master | <repo_name>jaweria332/MLAssignment3<file_sep>/Income Prediction by monthly experience.py
#importing necessary libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Reading the given dataset
data = pd.read_csv('E:\\python\\assignment 2\\monthlyexp vs incom.csv')
x = data.iloc[:, 0:1].values
y = data.iloc[:, 1].values
#Dividing dataset of first state into training and test
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2, random_state = 0)
#Fitting linear regression to dataset
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(x_train, y_train)
#Fitting Polynomial regression to dataset
from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree = 6)
x_poly = poly_reg.fit_transform(x)
poly_reg.fit(x_poly, y)
lin_reg = LinearRegression()
lin_reg.fit(x_poly, y)
# Visualising the Scattered dataset
plt.scatter(x_train, y_train, color = 'red')
plt.title('Months Experience VS Income (Training set)')
plt.xlabel('Months Experience')
plt.ylabel('Income')
plt.show()
#Visualizing the Polynomial Regression Result
plt.scatter(x_train, y_train, color = 'red')
plt.plot(x, lin_reg.predict(poly_reg.fit_transform(x)), color = 'blue')
plt.title('Months Experience VS Income (Training set)')
plt.xlabel('Months Experience')
plt.ylabel('Income')
plt.show()
#To chek accuracy of output using scikit learn Python library
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
#cannot use Rank 1 matrix in scikit learn
x = x.reshape((len(x), 1))
#creating model
reg = LinearRegression()
#Fitting training data
reg = reg.fit(x, y)
#Y prediction
Y_pred = reg.predict (x)
#calculating RMSE and R2 Score
mse = mean_squared_error(y, Y_pred)
rmse = np.sqrt(mse)
r_score = reg.score(x, y)
Accuracy = r_score * 100
print("Accuracy = " + str(Accuracy))<file_sep>/Housing Price VS ID.py
#importing necessary libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Reading the dataset
data = pd.read_csv('E:\\python\\assignment 2\\housing price.csv')
#Seting values to x and y
x = data.iloc[:, 0:1].values
y = data.iloc[:, 1].values
#Diving data into training and test set
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2, random_state=0)
#Fitting Linear Regression to dataset
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(x_train, y_train)
#Predicting the result
y_pred = regressor.predict([[6.5]])
#Visualizing scattered dataset
plt.figure(figsize = (10,7))
plt.scatter(x_train, y_train, color = 'red')
plt.title('Predicting Price using ID')
plt.xlabel('ID')
plt.ylabel('House Price')
plt.show()
#Fitting Polynomial Regression to dataset
from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures (degree = 4)
x_poly = poly_reg.fit_transform(x)
poly_reg.fit(x_poly, y)
lin_reg = LinearRegression()
lin_reg.fit(x_poly, y)
#Visualizing polynomial Regression
plt.figure(figsize = (10,7))
plt.scatter(x_train, y_train, color ='red')
plt.plot(x,lin_reg.predict(poly_reg.fit_transform(x)), color = 'blue')
plt.title('Predicting Price using ID')
plt.xlabel('ID')
plt.ylabel('House Price')
plt.show()
#To chek accuracy of output using scikit learn Python library
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
#cannot use Rank 1 matrix in scikit learn
x = x.reshape((len(x), 1))
#creating model
reg = LinearRegression()
#Fitting training data
reg = reg.fit(x, y)
#Y prediction
Y_pred = reg.predict (x)
#calculating RMSE and R2 Score
mse = mean_squared_error(y, Y_pred)
rmse = np.sqrt(mse)
r_score = reg.score(x, y)
Accuracy = r_score * 100
print("Accuracy = " + str(Accuracy))<file_sep>/50_Startups.py
#importing necessary libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.compose import ColumnTransformer
#Reading the given dataset
data = pd.read_csv('E:\\python\\assignment 2\\50_Startups.csv')
#Retrieving startupsof two states only
dataset = data[(data.State == 'Florida') | (data.State == 'California')]
x = dataset.iloc[:, 0:3].values
y = dataset.iloc[: , 4].values
#Dividing into training and test dataset
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2, random_state = 0)
#Fitting linear regression to data
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(x_train, y_train)
#Predicting the test set result
y_pred = regressor.predict(x_test)
#To chek accuracy of output using scikit learn Python library
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
#creating model
reg = LinearRegression()
#Fitting training data
reg = reg.fit(x, y)
#Y prediction
Y_pred = reg.predict (x)
#calculating RMSE and R2 Score
mse = mean_squared_error(y, Y_pred)
rmse = np.sqrt(mse)
r_score = reg.score(x, y)
Accuracy = r_score * 100
print("Overall Accuracy = " + str(Accuracy))<file_sep>/Temperature.py
#importing necessary libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Reading the given dataset
data = pd.read_csv('E:\\python\\assignment 2\\annual_temp.csv')
x = data.iloc[:, 1:2].values
y = data.iloc[:, 2].values
#Separating temperatures of both states
data1 = data[data.Source == 'GCAG']
data2 = data[data.Source == 'GISTEMP']
#Selecting Rows and columns
x1 = data1.iloc[:, 1:2].values
y1 = data1.iloc[:, 2].values
x2 = data2.iloc[:, 1:2].values
y2 = data2.iloc[:, 2].values
#Dividing dataset of first state into training and test
from sklearn.model_selection import train_test_split
x1_train, x1_test, y1_train, y1_test = train_test_split(x1, y1, test_size = 0.2, random_state = 0)
#Dividing dataset of second state into training and test
from sklearn.model_selection import train_test_split
x2_train, x2_test, y2_train, y2_test = train_test_split(x2, y2, test_size = 0.2, random_state = 0)
#Fitting linear regression to dataset
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(x1_train, y1_train)
#Fitting Polynomial regression to dataset
from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree = 6)
x1_poly = poly_reg.fit_transform(x1)
poly_reg.fit(x1_poly, y1)
lin_reg = LinearRegression()
lin_reg.fit(x1_poly, y1)
#Visualizing the Polynomial Regression Result
plt.scatter(x1_train, y1_train, color = 'red')
plt.plot(x1, lin_reg.predict(poly_reg.fit_transform(x1)), color = 'blue')
plt.title('Temperature of first state')
plt.xlabel('Year')
plt.ylabel('Temperature')
plt.show()
#To chek accuracy of output using scikit learn Python library
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
#cannot use Rank 1 matrix in scikit learn
x1 = x1.reshape((len(x1), 1))
#creating model
reg = LinearRegression()
#Fitting training data
reg = reg.fit(x1, y1)
#Y prediction
Y1_pred = reg.predict (x1)
#calculating RMSE and R2 Score
mse = mean_squared_error(y1, Y1_pred)
rmse = np.sqrt(mse)
r1_score = reg.score(x1, y1)
Accuracy = r1_score * 100
print("Accuracy = " + str(Accuracy))
#Fitting linear regression to dataset
from sklearn.linear_model import LinearRegression
regressor2 = LinearRegression()
regressor2.fit(x2_train, y2_train)
#Fitting Polynomial regression to dataset
from sklearn.preprocessing import PolynomialFeatures
poly_reg_2 = PolynomialFeatures(degree = 6)
x2_poly = poly_reg_2.fit_transform(x2)
poly_reg_2.fit(x2_poly, y2)
lin_reg2 = LinearRegression()
lin_reg2.fit(x2_poly, y2)
#Visualizing the Polynomial Regression Result
plt.scatter(x2_train, y2_train, color = 'orange')
plt.plot(x2, lin_reg2.predict(poly_reg_2.fit_transform(x2)), color = 'purple')
plt.title('Temperature of Second State')
plt.xlabel('Year')
plt.ylabel('Temperature')
plt.show()
#To chek accuracy of output using scikit learn Python library
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
#cannot use Rank 1 matrix in scikit learn
x2 = x2.reshape((len(x2), 1))
#creating model
reg2 = LinearRegression()
#Fitting training data
reg2 = reg2.fit(x2, y2)
#Y prediction
Y2_pred = reg.predict (x2)
#calculating RMSE and R2 Score
mse = mean_squared_error(y2, Y2_pred)
rmse = np.sqrt(mse)
r2_score = reg.score(x2, y2)
Accuracy = r2_score * 100
print("Accuracy = " + str(Accuracy))
#Visualizing result in single graph for comparison
plt.scatter(x1_train, y1_train, color = 'red')
plt.plot(x1, lin_reg.predict(poly_reg.fit_transform(x1)), color = 'blue')
plt.scatter(x2_train, y2_train, color = 'orange')
plt.plot(x2, lin_reg2.predict(poly_reg_2.fit_transform(x2)), color = 'purple')
plt.title('Temperature of two states')
plt.xlabel('Year')
plt.ylabel('Temperature')
plt.show()
#To chek accuracy of output using scikit learn Python library
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
#cannot use Rank 1 matrix in scikit learn
x = x.reshape((len(x), 1))
#creating model
reg = LinearRegression()
#Fitting training data
reg = reg.fit(x, y)
#Y prediction
Y_pred = reg.predict (x)
#calculating RMSE and R2 Score
mse = mean_squared_error(y, Y_pred)
rmse = np.sqrt(mse)
r_score = reg.score(x, y)
Accuracy = r_score * 100
print("Overall Accuracy = " + str(Accuracy))<file_sep>/README.md
Solutions of some Regression Problems using python libraries(i.e numpy, matplotlib, pandas, sklearn).
<file_sep>/Global_CO2.py
#importing necessary libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Reading the given dataset
dataset = pd.read_csv('E:\\python\\assignment 2\\global_co2.csv')
data = dataset[dataset.Year > 1969]
#Selecting Rows and columns
x = data.iloc[:, :1].values
y = data.iloc[:, 1].values
#Dividing dataset of first state into training and test
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 1/3, random_state = 0)
#Fitting linear regression to dataset
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(x_train, y_train)
#Fitting Polynomial regression to dataset
from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree = 4)
x_poly = poly_reg.fit_transform(x)
poly_reg.fit(x_poly, y)
lin_reg = LinearRegression()
lin_reg.fit(x_poly, y)
#Visualizing the Polynomial Regression Result
plt.scatter(x_train, y_train, color = 'red')
plt.plot(x, lin_reg.predict(poly_reg.fit_transform(x)), color = 'blue')
plt.title('Production of Global CO2 for the next few years')
plt.xlabel('Year')
plt.ylabel('Global CO2 Production')
plt.show()
#To chek accuracy of output using scikit learn Python library
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
#cannot use Rank 1 matrix in scikit learn
x = x.reshape((len(x), 1))
#creating model
reg = LinearRegression()
#Fitting training data
reg = reg.fit(x, y)
#Y prediction
Y_pred = reg.predict (x)
#calculating RMSE and R2 Score
mse = mean_squared_error(y, Y_pred)
rmse = np.sqrt(mse)
r2_score = reg.score(x, y)
Accuracy = r2_score * 100
print("Accuracy = " + str(Accuracy)) | 3fd477aa10b62cc3a33edab056bf2aaebbdd69b8 | [
"Markdown",
"Python"
] | 6 | Python | jaweria332/MLAssignment3 | e62c0dc41031259dc97bef5554711033b3020d9d | d683d779ff49ab78f5b654bdb5ad9e14bb5c8c91 |
refs/heads/master | <repo_name>gadelain/projet_opt_FISA3_qt<file_sep>/decrypt.h
#ifndef DECRYPT_H
#define DECRYPT_H
class decrypt
{
public:
decrypt();
};
#endif // DECRYPT_H<file_sep>/decrypt.cpp
#include "decrypt.h"
decrypt::decrypt()
{
}
<file_sep>/crypt.h
#include <string>
#ifndef CRYPT_H
#define CRYPT_H
class crypt
{
public:
crypt();
};
char decale(char, char, int);
std::string decode(std::string, int);
std::string code(std::string, int);
char decale(char c, char debut, int decalage);
int img_import(std::string);
#endif // CRYPT_H
<file_sep>/crypt.cpp
#include "crypt.h"
#include "cimageqt.h"
crypt::crypt()
{
}
char code(char c, int d) {
if (c >= 'a' && c <= 'z')
return decale(c, 'a', d);
else if (c >= 'A' && c <= 'Z')
return decale(c, 'A', d);
else
return c;
}
char decale(char c, char debut, int decalage) {
while (decalage < 0)
decalage += 26;
return debut + (((c - debut) + decalage) % 26);
}
std::string code(std::string texte, int decalage) {
const size_t taille = texte.size();
std::string chaine(texte);
for (size_t i = 0; i < taille; i++)
chaine[i] = code(chaine[i], decalage);
return chaine;
}
std::string decode(std::string texte, int decalage) {
return code(texte, -decalage);
}
int img_import(std::string filepath) {
int nb_cesar;
return nb_cesar;
}
<file_sep>/cimageqt.h
#include <string>
#ifndef CIMAGEQT_H
#define CIMAGEQT_H
class CImageQT
{
private :
int m_iHauteur;
int m_iLargeur;
std::string m_sNom;
unsigned char* m_pucData;
unsigned char** m_ppucPixel;
public:
CImageQT();
CImageQT(const std::string& nom);
unsigned char*& operator() (int i, int j) const {
return m_ppucPixel[i*m_iLargeur+j];
}
unsigned char*& operator() (int i) const {
return m_ppucPixel[i];
}
int lireHauteur() const {
return m_iHauteur;
}
int lireLargeur() const {
return m_iLargeur;
}
std::string lireNom() const {
return m_sNom;
}
int lireNbPixels() const {
return m_iHauteur*m_iLargeur;
}
};
#endif // CIMAGEQT_H
<file_sep>/cimageqt.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <windows.h>
#include <cmath>
#include <vector>
#include "cimageqt.h"
#define MAGIC_NUMBER_BMP ('B'+('M'<<8))
CImageQT::CImageQT()
{
}
CImageQT::CImageQT(const std::string& name) {
BITMAPFILEHEADER header;
BITMAPINFOHEADER infoHeader;
std::ifstream f(name.c_str(),std::ios::in | std::ios::binary); // transformation d'une string en chaรฎne de type C
if (f.is_open()) {
f.read((char*)&header,sizeof(BITMAPFILEHEADER));
if (header.bfType != MAGIC_NUMBER_BMP)
throw std::string("ouverture format BMP impossible ...");
else {
f.read((char*)&infoHeader,sizeof(BITMAPINFOHEADER));
if (infoHeader.biCompression > 0)
throw std::string("Format compresse non supportรฉ...");
else {
if (infoHeader.biBitCount == 24) {
this->m_iHauteur = infoHeader.biHeight;
this->m_iLargeur = infoHeader.biWidth;
this->m_sNom.assign(name.begin(),name.end()-4);
this->m_pucData = new unsigned char[infoHeader.biHeight*infoHeader.biWidth*3];
this->m_ppucPixel = new unsigned char*[infoHeader.biHeight*infoHeader.biWidth];
for (int i=0;i<infoHeader.biHeight*infoHeader.biWidth;i++)
this->m_ppucPixel[i] = &this->m_pucData[3*i];
// gรฉrer multiple de 32 bits via zรฉros รฉventuels ignorรฉs
int complement = (((this->m_iLargeur*3-1)/4) + 1)*4 - this->m_iLargeur*3;
for (int i= m_iHauteur-1; i >= 0; i--) {
for (int j=0;j<m_iLargeur;j++) {
f.read((char*)&this->m_ppucPixel[i*m_iLargeur+j][2],sizeof(char));
f.read((char*)&this->m_ppucPixel[i*m_iLargeur+j][1],sizeof(char));
f.read((char*)&this->m_ppucPixel[i*m_iLargeur+j][0],sizeof(char));
}
char inutile;
for (int k=0; k< complement; k++)
f.read((char*)&inutile,sizeof(char));
}
}
else {
// cas d'une image en niveaux de gris
this->m_iHauteur = infoHeader.biHeight;
this->m_iLargeur = infoHeader.biWidth;
this->m_sNom.assign(name.begin(),name.end()-4);
this->m_pucData = new unsigned char[infoHeader.biHeight*infoHeader.biWidth*3];
this->m_ppucPixel = new unsigned char*[infoHeader.biHeight*infoHeader.biWidth];
for (int i=0;i<infoHeader.biHeight*infoHeader.biWidth;i++)
this->m_ppucPixel[i] = &this->m_pucData[3*i];
// lecture palette
unsigned char* palette=NULL;
palette = new unsigned char[256*4];
for (int indice=0;indice<4*256;indice++)
f.read((char*)&palette[indice],sizeof(char));
// gรฉrer multiple de 32 bits via zรฉros รฉventuels ignorรฉs
int complement = (((this->m_iLargeur-1)/4) + 1)*4 - this->m_iLargeur;
// passage du gris vers la couleur par duplication des valeurs
for (int i= m_iHauteur-1; i >= 0; i--) {
for (int j=0;j<m_iLargeur;j++) {
unsigned char temp;
f.read((char*)&temp,sizeof(char));
this->m_ppucPixel[i*m_iLargeur+j][0]=palette[4*temp+2];
this->m_ppucPixel[i*m_iLargeur+j][1]=palette[4*temp+1];
this->m_ppucPixel[i*m_iLargeur+j][2]=palette[4*temp];
}
char inutile;
for (int k=0; k< complement; k++)
f.read((char*)&inutile,sizeof(char));
}
}
}
}
f.close();
}
else
throw std::string("Ouverture impossible !");
}
<file_sep>/mainwindow.cpp
#include <QFileDialog>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "crypt.h"
#include "cimageqt.h"
int nb_cesar;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_crypt_clicked()
{
QString qs_crypt;
QString qs_decrypt;
std::string string_crypt;
std::string string_decrypt;
qs_crypt = ui->textEdit_crypt->toPlainText();
string_crypt = qs_crypt.toLocal8Bit().constData();
string_decrypt = code(string_crypt, nb_cesar);
qs_decrypt = QString::fromStdString(string_decrypt);
ui->textEdit_decrypt->setText(qs_decrypt);
}
void MainWindow::on_pushButton_parcourir_clicked()
{
QString qs_fileName;
std::string string_fileName;
ui->pushButton_crypt->setEnabled(true);
ui->pushButton_decrypt->setEnabled(true);
qs_fileName = QFileDialog::getOpenFileName(this, tr("Selectionner un fichier"),
"",
tr("Images (*.bmp)"));
string_fileName = qs_fileName.toLocal8Bit().constData();
CImageQT import(string_fileName);
nb_cesar = int(import(0,0));
}
void MainWindow::on_pushButton_decrypt_clicked()
{
QString qs_crypt;
QString qs_decrypt;
std::string string_crypt;
std::string string_decrypt;
qs_decrypt = ui->textEdit_decrypt->toPlainText();
string_decrypt = qs_decrypt.toLocal8Bit().constData();
string_crypt = decode(string_decrypt, nb_cesar);
qs_crypt = QString::fromStdString(string_crypt);
ui->textEdit_crypt->setText(qs_crypt);
}
| 521171643ec07f3dc5999e021523d322fd89cf66 | [
"C++"
] | 7 | C++ | gadelain/projet_opt_FISA3_qt | f472f1c0e82dc8aab46c21247b17f8733fa295fd | e597c45ade67d2f3b36d90317e7890f99b785f5d |
refs/heads/master | <file_sep>(function (window, document) {
function sort(tbody, compareFunction) {
var rows = tbody.children;
if(!rows || !rows[0] || rows.length == 1) return;
var size = rows.length;
var arr = [];
for(var i = 0; i < size; i++) arr.push(rows[i]);
arr.sort(compareFunction);
for(var i = size - 1; i > 0; i--) tbody.insertBefore(arr[i-1], arr[i]);
}
function numConvert(s) {
return s == Number(s) ? Number(s) : s;
}
function asc(idx) {
return function(a, b) {
var a_ = numConvert(a.children[idx].innerText);
var b_ = numConvert(b.children[idx].innerText);
return a_ > b_ ? 1 : -1;
};
}
function desc(idx) {
return function(a, b) {
var a_ = numConvert(a.children[idx].innerText);
var b_ = numConvert(b.children[idx].innerText);
return a_ < b_ ? 1 : -1;
};
}
function sortEvent(tbody, idx) {
var mode = true;
return function(e) {
if(mode) sort(tbody, asc(idx));
else sort(tbody, desc(idx));
mode = !mode;
};
}
var ts = document.getElementsByTagName('table');
for(var i = ts.length; i--; ) {
var ths = ts[i].tHead.getElementsByTagName('th');
for(var j = ths.length; j--; )
ths[j].addEventListener("click", sortEvent(ts[i].tBodies[0], j));
}
}(this, this.document));
<file_sep>(function (window, document) {
var layout = document.getElementById('layout'),
menu = document.getElementById('menu'),
menuLink = document.getElementById('menuLink'),
content = document.getElementById('main');
function toggleClass(element, className) {
var classes = element.className.split(/\s+/),
length = classes.length,
i = 0;
for(; i < length; i++) {
if (classes[i] === className) {
classes.splice(i, 1);
break;
}
}
// The className is not found
if (length === classes.length) {
classes.push(className);
}
element.className = classes.join(' ');
}
function toggleAll(e) {
var active = 'active';
e.preventDefault();
toggleClass(layout, active);
toggleClass(menu, active);
toggleClass(menuLink, active);
}
menuLink.onclick = function (e) {
toggleAll(e);
};
content.onclick = function(e) {
if (menu.className.indexOf('active') !== -1) {
toggleAll(e);
}
};
// function sort(tbody, compareFunction) {
// var rows = tbody.children;
// if(!rows || !rows[0] || rows.length == 1) return;
// var size = rows.length;
// var arr = [];
// for(var i = 0; i < size; i++) arr.push(rows[i]);
// arr.sort(compareFunction);
// for(var i = size - 1; i > 0; i--) tbody.insertBefore(arr[i-1], arr[i]);
// }
// function numConvert(s) {
// return s == Number(s) ? Number(s) : s;
// }
// function asc(idx) {
// return function(a, b) {
// var a_ = numConvert(a.children[idx].innerText);
// var b_ = numConvert(b.children[idx].innerText);
// return a_ > b_ ? 1 : -1;
// };
// }
// function desc(idx) {
// return function(a, b) {
// var a_ = numConvert(a.children[idx].innerText);
// var b_ = numConvert(b.children[idx].innerText);
// return a_ < b_ ? 1 : -1;
// };
// }
// function sortEvent(tbody, idx) {
// var mode = true;
// return function(e) {
// if(mode) sort(tbody, asc(idx));
// else sort(tbody, desc(idx));
// mode = !mode;
// };
// }
// var ts = document.getElementsByTagName('table');
// for(var i = ts.length; i--; ) {
// var ths = ts[i].tHead.getElementsByTagName('th');
// for(var j = ths.length; j--; )
// ths[j].addEventListener("click", sortEvent(ts[i].tBodies[0], j));
// }
}(this, this.document));
| 698284d61d9a9d28fbcbf9990c505fa25a2947a9 | [
"JavaScript"
] | 2 | JavaScript | rskmoi/blackburn | 1151dac92352714f1709331d4ab2e68d76a0fe35 | 5a9023ae9d0f2cb455dd53c8e3dd8253bf41fbe4 |
refs/heads/master | <repo_name>Phumkrit/Tictactoe_digio<file_sep>/app/src/main/java/com/example/xo/History.kt
package com.example.xo
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
class History : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_history)
val log = findViewById<TextView>(R.id.view3)
val view2 = findViewById<TextView>(R.id.showt3)
val move = intent.getSerializableExtra("move")
log.text = move.toString()
val player = intent.getSerializableExtra("player")
view2.text = player.toString()
val button = findViewById<Button>(R.id.tofirstpg)
button.setOnClickListener {
val intent = Intent(this,Firstpg::class.java)
startActivity(intent)
}
}
}<file_sep>/app/src/main/java/com/example/xo/MainActivity.kt
package com.example.tic_tac_toe
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import com.example.xo.History
import com.example.xo.R
class MainActivity : AppCompatActivity() {
//1=Circle 0 =Cross
var activePlayer = 1
var gameIsActive = true
var count = 0
var text = ""
var gameState = intArrayOf(2, 2, 2, 2, 2, 2, 2, 2, 2)
var winningPositions = arrayOf(
intArrayOf(0, 1, 2),
intArrayOf(3, 4, 5),
intArrayOf(6, 7, 8),
intArrayOf(0, 3, 6),
intArrayOf(1, 4, 7),
intArrayOf(2, 5, 8),
intArrayOf(0, 4, 8),
intArrayOf(2, 4, 6)
)
var list: ArrayList<String> = ArrayList()
val player: ArrayList<String> = ArrayList()
fun dropIn(view: View) {
val counter = view as ImageView
val txt = findViewById<TextView>(R.id.winner1)
val layout = findViewById<LinearLayout>(R.id.winner)
val tappedcounter = counter.tag.toString().toInt()
if (gameState[tappedcounter] == 2 && gameIsActive) {
if (activePlayer == 1) {
counter.setImageResource(R.drawable.circle)
activePlayer = 0
player.add("\n CIRCLE Move to \n")
count++
gameState[tappedcounter] = 1
} else {
counter.setImageResource(R.drawable.cross)
activePlayer = 1
player.add("\n CROSS Move to \n")
count++
gameState[tappedcounter] = 0
}
val move = findViewById<Button>(R.id.Move)
move.setOnClickListener {
val intent = Intent(this, History::class.java)
intent.putExtra("move", list)
intent.putExtra("player", player)
startActivity(intent)
}
if (tappedcounter == 0)
text = "Upper left"
else if (tappedcounter == 1)
text = "Upper center"
else if (tappedcounter == 2)
text = "Upper right"
else if (tappedcounter == 3)
text = "Center left"
else if (tappedcounter == 4)
text = "Center"
else if (tappedcounter == 5)
text = "Center right"
else if (tappedcounter == 6)
text = "Bottom left"
else if (tappedcounter == 7)
text = "Bottom Center"
else if (tappedcounter == 8)
text = "Bottom right"
list.add("\n"+text+"\n")
for (winningposition in winningPositions) {
if (gameState[winningposition[0]] == gameState[winningposition[1]] && gameState[winningposition[1]] == gameState[winningposition[2]] && gameState[winningposition[0]] != 2
) {
if (gameState[winningposition[0]] == 0) txt.text =
"Cross Wins!!!"
else if (gameState[winningposition[0]] == 1
) txt.text = "Circle Wins!!!"
layout.visibility = View.VISIBLE
gameIsActive = false
}
}
}
if (gameIsActive && count == 9) {
txt.text = "DRAW"
layout.visibility = View.VISIBLE
gameIsActive = false
}
}
fun playAgain(view: View) {
activePlayer = 1
gameIsActive = true
count = 0
val linearLayout = findViewById<LinearLayout>(R.id.winner)
val gridLayout =
findViewById<GridLayout>(R.id.gridLayout)
for (i in gameState.indices) {
gameState[i] = 2
}
linearLayout.visibility = View.INVISIBLE
for (i in 0 until gridLayout.childCount) {
(gridLayout.getChildAt(i) as ImageView).setImageResource(0) //p t n
}
}
protected override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
<file_sep>/app/src/main/java/com/example/xo/Five.kt
package com.example.xo
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.*
class Five : AppCompatActivity() {
//1=Circle 0 =Cross
var activePlayer = 1
var gameIsActive = true
var count = 0
var text = ""
var gameState = intArrayOf(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)
var winningPosition = arrayOf(
intArrayOf(0, 1, 2, 3, 4),
intArrayOf(5, 6, 7,8 ,9),
intArrayOf(10, 11,12,13,14),
intArrayOf(15,16,17,18,19),
intArrayOf(20,21,22,23,24),
intArrayOf(0, 5,10,15,20),
intArrayOf(1, 6,11,16,21),
intArrayOf(2, 7,12,17,22),
intArrayOf(3, 8,13,18,23),
intArrayOf(4,9,14,19,24),
intArrayOf(0, 6,12,18,24),
intArrayOf(4,8,12,16,20)
)
var list: ArrayList<String> = ArrayList()
val player: ArrayList<String> = ArrayList()
fun dropIn(view: View) {
val counter = view as ImageView
val txt = findViewById<TextView>(R.id.winner1)
val layout = findViewById<LinearLayout>(R.id.winner)
val tappedcounter = counter.tag.toString().toInt()
if (gameState[tappedcounter] == 2 && gameIsActive) {
if (activePlayer == 1) {
counter.setImageResource(R.drawable.circle)
activePlayer = 0
player.add("\n CIRCLE Move to \n")
count++
gameState[tappedcounter] = 1
} else {
counter.setImageResource(R.drawable.cross)
activePlayer = 1
player.add("\n CROSS Move to \n")
count++
gameState[tappedcounter] = 0
}
val move = findViewById<Button>(R.id.Move)
move.setOnClickListener {
val intent = Intent(this@Five, History::class.java)
intent.putExtra("move", list)
intent.putExtra("player", player)
startActivity(intent)
}
if (tappedcounter == 0)
text = "Line1 left corner"
else if (tappedcounter == 1)
text = "Line1 left"
else if (tappedcounter == 2)
text = "Line1 center"
else if (tappedcounter == 3)
text = "Line1 right"
else if (tappedcounter == 4)
text = "Line1 right corner"
else if (tappedcounter == 5)
text = "Line2 left corner"
else if (tappedcounter == 6)
text = "Line2 left"
else if (tappedcounter == 7)
text = "Line2 center"
else if (tappedcounter == 8)
text = "Line2 right"
else if (tappedcounter == 9)
text = "Line2 right corner"
else if (tappedcounter == 10)
text = "Line3 left corner"
else if (tappedcounter == 11)
text = "Line3 left"
else if (tappedcounter == 12)
text = "Line3 center"
else if (tappedcounter == 13)
text = "Line3 right"
else if (tappedcounter == 14)
text = "Line3 right corner"
else if (tappedcounter == 15)
text = "Line4 left corner"
else if (tappedcounter == 16)
text = "Line4 left"
else if (tappedcounter == 17)
text = "Line4 center"
else if (tappedcounter == 18)
text = "Line4 right"
else if (tappedcounter == 19)
text = "Line4 right corner"
else if (tappedcounter == 20)
text = "Line5 left corner"
else if (tappedcounter == 21)
text = "Line5 left"
else if (tappedcounter == 22)
text = "Line5 center"
else if (tappedcounter == 23)
text = "Line5 right"
else if (tappedcounter == 24)
text = "Line5 right corner"
list.add("\n"+text+"\n")
for (winningposition:IntArray in winningPosition) {
if (gameState[winningposition[0]] == gameState[winningposition[1]] && gameState[winningposition[1]] == gameState[winningposition[2]] && gameState[winningposition[0]] != 2
&& gameState[winningposition[2]] == gameState[winningposition[3]] && gameState[winningposition[3]] == gameState[winningposition[4]] ) {
if (gameState[winningposition[0]] == 0) txt.text =
"Cross Wins!!!"
else if (gameState[winningposition[0]] == 1) txt.text =
"Circle Wins!!!"
layout.visibility = View.VISIBLE
gameIsActive = false
}
}
}
if (gameIsActive && count == 25) {
txt.text = "DRAW"
layout.visibility = View.VISIBLE
gameIsActive = false
}
}
fun playAgain(view: View) {
activePlayer = 1
gameIsActive = true
count = 0
val linearLayout = findViewById<LinearLayout>(R.id.winner)
val gridLayout =
findViewById<GridLayout>(R.id.gridLayout)
for (i in gameState.indices) {
gameState[i] = 2
}
linearLayout.visibility = View.INVISIBLE
for (i in 0 until gridLayout.childCount) {
(gridLayout.getChildAt(i) as ImageView).setImageResource(0) //p t n
}
}
protected override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_five)
}
}
<file_sep>/app/src/main/java/com/example/xo/Firstpg.kt
package com.example.xo
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.*
import com.example.tic_tac_toe.*
class Firstpg : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_firstpg)
val button = findViewById<Button>(R.id.three)
button.setOnClickListener{
val intent = Intent(this, MainActivity::class.java)
overridePendingTransition(R.transition.explode,R.transition.explode)
startActivity(intent)
}
val four = findViewById<Button>(R.id.four)
four.setOnClickListener {
val intent4 = Intent(this, FourActivity::class.java)
startActivity(intent4)
}
val five = findViewById<Button>(R.id.five)
five.setOnClickListener {
val intent5 = Intent(this, Five::class.java)
startActivity(intent5)
}
val six = findViewById<Button>(R.id.six)
six.setOnClickListener {
val intent6 = Intent(this, com.example.xo.six::class.java)
startActivity(intent6)
}
val seven = findViewById<Button>(R.id.seven)
seven.setOnClickListener {
val intent7 = Intent(this, Seven::class.java)
startActivity(intent7)
}
val eight = findViewById<Button>(R.id.eight)
eight.setOnClickListener {
val intent8 = Intent(this, Eight::class.java)
startActivity(intent8)
}
val nine = findViewById<Button>(R.id.nine)
nine.setOnClickListener {
val intent9 = Intent(this, com.example.xo.nine::class.java)
startActivity(intent9)
}
val ten = findViewById<Button>(R.id.ten)
ten.setOnClickListener {
val intent10 = Intent(this, com.example.xo.ten::class.java)
startActivity(intent10)
}
}
}<file_sep>/app/src/main/java/com/example/xo/ten.kt
package com.example.xo
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.*
class ten : AppCompatActivity() {
//1=Circle 0 =Cross
var activePlayer = 1
var gameIsActive = true
var count = 0
var text = ""
var gameState = intArrayOf(
2, 2, 2, 2, 2, 2, 2, 2, 2, 2
, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
, 2, 2, 2, 2, 2, 2, 2, 2, 2,2
, 2, 2, 2, 2, 2, 2, 2, 2, 2,2
, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)
var winningPosition = arrayOf(
//Horizential
intArrayOf(0, 1, 2, 3, 4,5,6,7,8,9),
intArrayOf(10,11,12,13,14,15,16,17,18,19),
intArrayOf(20,21,22,23,24,25,26,27,28,29),
intArrayOf(30,31,32,33,34,35,36,37,38,39),
intArrayOf(40,41,42,43,44,45,46,47,48,49),
intArrayOf(50,51,52,53,54,55,56,57,58,59),
intArrayOf(60,61,62,63,64,65,66,67,68,69),
intArrayOf(70,71,72,73,74,75,76,77,78,79),
intArrayOf(80,81,82,83,84,85,86,87,88,89),
intArrayOf(90,91,92,93,94,95,96,97,98,99),
//Vertical
intArrayOf(0,10,20,30,40,50,60,70,80,90),
intArrayOf(1,11,21,31,41,51,61,71,81,91),
intArrayOf(2,12,22,32,42,52,62,72,82,92),
intArrayOf(3,13,23,33,43,53,63,73,83,93),
intArrayOf(4,14,24,34,44,54,64,74,84,94),
intArrayOf(5,15,25,35,45,55,65,75,85,95),
intArrayOf(6,16,26,36,46,56,66,76,86,96),
intArrayOf(7,17,27,37,47,57,67,77,87,97),
intArrayOf(8,18,28,38,48,58,68,78,88,98),
intArrayOf(9,19,29,39,49,59,69,79,89,99),
intArrayOf(0,11,22,33,44,55,66,77,88,99),
intArrayOf(9,18,27,36,45,54,63,72,81,90)
)
var list: ArrayList<String> = ArrayList()
val player: ArrayList<String> = ArrayList()
fun dropIn(view: View) {
val counter = view as ImageView
val txt = findViewById<TextView>(R.id.winner1)
val layout = findViewById<LinearLayout>(R.id.winner)
val tappedcounter = counter.tag.toString().toInt()
if (gameState[tappedcounter] == 2 && gameIsActive) {
if (activePlayer == 1) {
counter.setImageResource(R.drawable.circle)
activePlayer = 0
player.add("\n CIRCLE Move to \n")
count++
gameState[tappedcounter] = 1
} else {
counter.setImageResource(R.drawable.cross)
activePlayer = 1
player.add("\n CROSS Move to \n")
count++
gameState[tappedcounter] = 0
}
val move = findViewById<Button>(R.id.Move)
move.setOnClickListener {
val intent = Intent(this@ten, History::class.java)
intent.putExtra("move", list)
intent.putExtra("player", player)
startActivity(intent)
}
if (tappedcounter == 0)
text = "row 1 column 1"
else if (tappedcounter == 1)
text = "row 1 column 2"
else if (tappedcounter == 2)
text = "row 1 column 3"
else if (tappedcounter == 3)
text = "row 1 column 4"
else if (tappedcounter == 4)
text = "row 1 column 5"
else if (tappedcounter == 5)
text = "row 1 column 6"
else if (tappedcounter == 6)
text = "row 1 column 7"
else if (tappedcounter == 7)
text = "row 1 column 8"
else if (tappedcounter == 8)
text = "row 1 column 9"
else if (tappedcounter == 9)
text = "row 1 column 10"
else if (tappedcounter == 10)
text = "row 2 column 1"
else if (tappedcounter == 11)
text = "row 2 column 2"
else if (tappedcounter == 12)
text = "row 2 column 3"
else if (tappedcounter == 13)
text = "row 2 column 4"
else if (tappedcounter == 14)
text = "row 2 column 5"
else if (tappedcounter == 15)
text = "row 2 column 6"
else if (tappedcounter == 16)
text = "row 2 column 7"
else if (tappedcounter == 17)
text = "row 2 column 8"
else if (tappedcounter == 18)
text = "row 2 column 9"
else if (tappedcounter == 19)
text = "row 2 column 10"
else if (tappedcounter == 20)
text = "row 3 column 1"
else if (tappedcounter == 21)
text = "row 3 column 2"
else if (tappedcounter == 22)
text = "row 3 column 3"
else if (tappedcounter == 23)
text = "row 3 column 4"
else if (tappedcounter == 24)
text = "row 3 column 5"
else if (tappedcounter == 25)
text = "row 3 column 6"
else if (tappedcounter == 26)
text = "row 3 column 7"
else if (tappedcounter == 27)
text = "row 3 column 8"
else if (tappedcounter == 28)
text = "row 3 column 9"
else if (tappedcounter == 29)
text = "row 3 column 10"
else if (tappedcounter == 30)
text = "row 4 column 1"
else if (tappedcounter == 31)
text = "row 4 column 2"
else if (tappedcounter == 32)
text = "row 4 column 3"
else if (tappedcounter == 33)
text = "row 4 column 4"
else if (tappedcounter == 34)
text = "row 4 column 5"
else if (tappedcounter == 35)
text = "row 4 column 6"
else if (tappedcounter == 36)
text = "row 4 column 7"
else if (tappedcounter == 37)
text = "row 4 column 8"
else if (tappedcounter == 38)
text = "row 4 column 9"
else if (tappedcounter == 39)
text = "row 4 column 10"
else if (tappedcounter == 40)
text = "row 5 column 1"
else if (tappedcounter == 41)
text = "row 5 column 2"
else if (tappedcounter == 42)
text = "row 5 column 3"
else if (tappedcounter == 43)
text = "row 5 column 4"
else if (tappedcounter == 44)
text = "row 5 column 5"
else if (tappedcounter == 45)
text = "row 5 column 6"
else if (tappedcounter == 46)
text = "row 5 column 7"
else if (tappedcounter == 47)
text = "row 5 column 8"
else if (tappedcounter == 48)
text = "row 5 column 9"
else if (tappedcounter == 49)
text = "row 5 column 10"
else if (tappedcounter == 50)
text = "row 6 column 1"
else if (tappedcounter == 51)
text = "row 6 column 2"
else if (tappedcounter ==52)
text = "row 6 column 3"
else if (tappedcounter == 53)
text = "row 6 column 4"
else if (tappedcounter == 54)
text = "row 6 column 5"
else if (tappedcounter == 55)
text = "row 6 column 6"
else if (tappedcounter == 56)
text = "row 6 column 7"
else if (tappedcounter == 57)
text = "row 6 column 8"
else if (tappedcounter == 58)
text = "row 6 column 9"
else if (tappedcounter == 59)
text = "row 6 column 10"
else if (tappedcounter == 60)
text = "row 7 column 1"
else if (tappedcounter == 61)
text = "row 7 column 2"
else if (tappedcounter == 62)
text = "row 7 column 3"
else if (tappedcounter == 63)
text = "row 7 column 4"
else if (tappedcounter == 64)
text = "row 7 column 5"
else if (tappedcounter == 65)
text = "row 7 column 6"
else if (tappedcounter == 66)
text = "row 7 column 7"
else if (tappedcounter == 67)
text = "row 7 column 8"
else if (tappedcounter == 68)
text = "row 7 column 9"
else if (tappedcounter == 69)
text = "row 7 column 10"
else if (tappedcounter == 70)
text = "row 8 column 1"
else if (tappedcounter == 71)
text = "row 8 column 2"
else if (tappedcounter == 72)
text = "row 8 column 3"
else if (tappedcounter == 73)
text = "row 8 column 4"
else if (tappedcounter == 74)
text = "row 8 column 5"
else if (tappedcounter == 75)
text = "row 8 column 6"
else if (tappedcounter == 76)
text = "row 8 column 7"
else if (tappedcounter == 77)
text = "row 8 column 8"
else if (tappedcounter == 78)
text = "row 8 column 9"
else if (tappedcounter == 79)
text = "row 8 column 10"
else if (tappedcounter == 80)
text = "row 9 column 1"
else if (tappedcounter == 81)
text = "row 9 column 2"
else if (tappedcounter == 82)
text = "row 9 column 3"
else if (tappedcounter == 83)
text = "row 9 column 4"
else if (tappedcounter == 84)
text = "row 9 column 5"
else if (tappedcounter == 85)
text = "row 9 column 6"
else if (tappedcounter == 86)
text = "row 9 column 7"
else if (tappedcounter == 87)
text = "row 9 column 8"
else if (tappedcounter == 88)
text = "row 9 column 9"
else if (tappedcounter == 89)
text = "row 9 column 10"
else if (tappedcounter == 90)
text = "row 10 column 1"
else if (tappedcounter == 91)
text = "row 10 column 2"
else if (tappedcounter == 92)
text = "row 10 column 3"
else if (tappedcounter == 93)
text = "row 10 column 4"
else if (tappedcounter == 94)
text = "row 10 column 5"
else if (tappedcounter == 95)
text = "row 10 column 6"
else if (tappedcounter == 96)
text = "row 10 column 7"
else if (tappedcounter == 97)
text = "row 10 column 8"
else if (tappedcounter == 98)
text = "row 10 column 9"
else if (tappedcounter == 99)
text = "row 10 column 10"
list.add("\n"+text+"\n")
for (winningposition:IntArray in winningPosition) {
if (gameState[winningposition[0]] == gameState[winningposition[1]] && gameState[winningposition[1]] == gameState[winningposition[2]] && gameState[winningposition[0]] != 2
&& gameState[winningposition[2]] == gameState[winningposition[3]] && gameState[winningposition[3]] == gameState[winningposition[4]] && gameState[winningposition[4]] == gameState[winningposition[5]] ) {
if (gameState[winningposition[0]] == 0) txt.text =
"Cross Wins!!!"
else if (gameState[winningposition[0]] == 1) txt.text =
"Circle Wins!!!"
layout.visibility = View.VISIBLE
gameIsActive = false
}
}
}
if (gameIsActive && count == 100) {
txt.text = "DRAW"
layout.visibility = View.VISIBLE
gameIsActive = false
}
}
fun playAgain(view: View) {
activePlayer = 1
gameIsActive = true
count = 0
val linearLayout = findViewById<LinearLayout>(R.id.winner)
val gridLayout =
findViewById<GridLayout>(R.id.gridLayout)
for (i in gameState.indices) {
gameState[i] = 2
}
linearLayout.visibility = View.INVISIBLE
for (i in 0 until gridLayout.childCount) {
(gridLayout.getChildAt(i) as ImageView).setImageResource(0) //p t n
}
}
protected override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_ten)
}
}
<file_sep>/app/src/main/java/com/example/xo/Seven.kt
package com.example.xo
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.*
class Seven : AppCompatActivity() {
//1=Circle 0 =Cross
var activePlayer = 1
var gameIsActive = true
var count = 0
var text = ""
var gameState = intArrayOf(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2)
var winningPosition = arrayOf(
intArrayOf(0, 1, 2, 3, 4,5,6),
intArrayOf(7,8,9,10,11,12,13),
intArrayOf(14,15,16,17,18,19,20),
intArrayOf(21,22,23,24,25,26,27),
intArrayOf(28,29,30,31,32,33,34),
intArrayOf(35,36,37,38,39,40,41),
intArrayOf(42,43,44,45,46,47,48),
intArrayOf(0, 7,14,21,28,35,42),
intArrayOf(1, 8,15,22,29,36,43),
intArrayOf(2,9,16,23,30,37,44),
intArrayOf(3,10,17,24,31,38,45),
intArrayOf(4,11,18,25,32,39,46),
intArrayOf(5,12,19,26,33,40,47),
intArrayOf(6,13,20,27,34,41,48),
intArrayOf(0,8,16,24,32,40,48),
intArrayOf(6,12,18,24,30,36,42)
)
var list: ArrayList<String> = ArrayList()
val player: ArrayList<String> = ArrayList()
fun dropIn(view: View) {
val counter = view as ImageView
val txt = findViewById<TextView>(R.id.winner1)
val layout = findViewById<LinearLayout>(R.id.winner)
val tappedcounter = counter.tag.toString().toInt()
if (gameState[tappedcounter] == 2 && gameIsActive) {
if (activePlayer == 1) {
counter.setImageResource(R.drawable.circle)
activePlayer = 0
player.add("\n CIRCLE Move to \n")
count++
gameState[tappedcounter] = 1
} else {
counter.setImageResource(R.drawable.cross)
activePlayer = 1
player.add("\n CROSS Move to \n")
count++
gameState[tappedcounter] = 0
}
val move = findViewById<Button>(R.id.Move)
move.setOnClickListener {
val intent = Intent(this@Seven, History::class.java)
intent.putExtra("move", list)
intent.putExtra("player", player)
startActivity(intent)
}
if (tappedcounter == 0)
text = "row 1 column 1"
else if (tappedcounter == 1)
text = "row 1 column 2"
else if (tappedcounter == 2)
text = "row 1 column 3"
else if (tappedcounter == 3)
text = "row 1 column 4"
else if (tappedcounter == 4)
text = "row 1 column 5"
else if (tappedcounter == 5)
text = "row 1 column 6"
else if (tappedcounter == 6)
text = "row 1 column 7"
else if (tappedcounter == 7)
text = "row 2 column 1"
else if (tappedcounter == 8)
text = "row 2 column 2"
else if (tappedcounter == 9)
text = "row 2 column 3"
else if (tappedcounter == 10)
text = "row 2 column 4"
else if (tappedcounter == 11)
text = "row 2 column 5"
else if (tappedcounter == 12)
text = "row 2 column 6"
else if (tappedcounter == 13)
text = "row 2 column 7"
else if (tappedcounter == 14)
text = "row 3 column 1"
else if (tappedcounter == 15)
text = "row 3 column 2"
else if (tappedcounter == 16)
text = "row 3 column 3"
else if (tappedcounter == 17)
text = "row 3 column 4"
else if (tappedcounter == 18)
text = "row 3 column 5"
else if (tappedcounter == 19)
text = "row 3 column 6"
else if (tappedcounter == 20)
text = "row 3 column 7"
else if (tappedcounter == 21)
text = "row 4 column 1"
else if (tappedcounter == 22)
text = "row 4 column 2"
else if (tappedcounter == 23)
text = "row 4 column 3"
else if (tappedcounter == 24)
text = "row 4 column 4"
else if (tappedcounter == 25)
text = "row 4 column 5"
else if (tappedcounter == 26)
text = "row 4 column 6"
else if (tappedcounter == 27)
text = "row 4 column 7"
else if (tappedcounter == 28)
text = "row 5 column 1"
else if (tappedcounter == 29)
text = "row 5 column 2"
else if (tappedcounter == 30)
text = "row 5 column 3"
else if (tappedcounter == 31)
text = "row 5 column 4"
else if (tappedcounter == 32)
text = "row 5 column 5"
else if (tappedcounter == 33)
text = "row 5 column 6"
else if (tappedcounter == 34)
text = "row 5 column 7"
else if (tappedcounter == 35)
text = "row 6 column 1"
else if (tappedcounter == 36)
text = "row 6 column 2"
else if (tappedcounter == 37)
text = "row 6 column 3"
else if (tappedcounter == 38)
text = "row 6 column 4"
else if (tappedcounter == 39)
text = "row 6 column 5"
else if (tappedcounter == 40)
text = "row 6 column 6"
else if (tappedcounter == 41)
text = "row 6 column 7"
else if (tappedcounter == 42)
text = "row 7 column 1"
else if (tappedcounter == 43)
text = "row 7 column 2"
else if (tappedcounter == 44)
text = "row 7 column 3"
else if (tappedcounter == 45)
text = "row 7 column 4"
else if (tappedcounter == 46)
text = "row 7 column 5"
else if (tappedcounter == 47)
text = "row 7 column 6"
else if (tappedcounter == 48)
text = "row 7 column 7"
list.add("\n"+text+"\n")
for (winningposition:IntArray in winningPosition) {
if (gameState[winningposition[0]] == gameState[winningposition[1]] && gameState[winningposition[1]] == gameState[winningposition[2]] && gameState[winningposition[0]] != 2
&& gameState[winningposition[2]] == gameState[winningposition[3]] && gameState[winningposition[3]] == gameState[winningposition[4]] && gameState[winningposition[4]] == gameState[winningposition[5]] ) {
if (gameState[winningposition[0]] == 0) txt.text =
"Cross Wins!!!"
else if (gameState[winningposition[0]] == 1) txt.text =
"Circle Wins!!!"
layout.visibility = View.VISIBLE
gameIsActive = false
}
}
}
if (gameIsActive && count == 49) {
txt.text = "DRAW"
layout.visibility = View.VISIBLE
gameIsActive = false
}
}
fun playAgain(view: View) {
activePlayer = 1
gameIsActive = true
count = 0
val linearLayout = findViewById<LinearLayout>(R.id.winner)
val gridLayout =
findViewById<GridLayout>(R.id.gridLayout)
for (i in gameState.indices) {
gameState[i] = 2
}
linearLayout.visibility = View.INVISIBLE
for (i in 0 until gridLayout.childCount) {
(gridLayout.getChildAt(i) as ImageView).setImageResource(0) //p t n
}
}
protected override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_seven)
}
}
| 3ba15739a9dd2be6e8ac338ef89c46814375f2f8 | [
"Kotlin"
] | 6 | Kotlin | Phumkrit/Tictactoe_digio | e0416abfdf0378bc2e03aec4b8d0b673ca68bfd7 | 84727ee5e40ad85bddc26fcbfaef42ded7ea5b01 |
refs/heads/master | <file_sep>import React from 'react';
import logo from './logo.svg';
import './App.css';
import {Col,Row} from 'react-bootstrap';
import TaskList from './Components/TaskList';
import ButtonComponent from './Components/ButtonComponent';
import MessageComponent from './Components/MessageComponent';
const taskList = [
{id: 1,"details": "Do laundry","completed": false},
{id: 2,details: "Do grocery",completed: false},
{id: 3,details: "Do dishes",completed: false},
{id: 4,details: "Go to gym",completed: false},
{id: 5,details: "Reading",completed: false},
{id: 6,details: "Pick the kids",completed: false},
{id: 7,details: "Car wash",completed: false},
{id: 8,details: "Go for a run",completed: false},
{id: 9,details: "Do grocery2",completed: false},
{id: 10,details: "Do laundry2",completed: false},
{id: 11,details: "Do grocery3",completed: false},
{id: 12,details: "Do grocery4",completed: false},
];
class App extends React.Component{
constructor(props){
super(props);
this.state = {taskList : taskList,tasks :[],counter: 0,style:{display :"none"}};
this.done = this.done.bind(this);
this.showMore = this.showMore.bind(this);
}
componentDidMount(){
let {taskList, counter} = this.state;
let tasks = taskList.slice(0,5);
this.setState({tasks : tasks, counter : counter + 5});
}
showMore = ()=>{
let {taskList,counter} = this.state;
let tasks = counter < taskList.length ?
taskList.slice(0 , counter + 5) :
"";
if(tasks.length > 0){
this.setState({tasks : tasks,counter : counter + 5})
}else{
this.setState({style :{display: "block"},counter : counter + 5})
}
}
done = (id)=>{
let {tasks} = this.state;
let updatedTaskList = tasks.map((val, index)=>{
if((val.id).toString() === id){
val.completed = true;
}
return val;
})
this.setState({tasks : updatedTaskList});
}
render(){
return (
<div className="app">
<Row>
<Col><h4>My tasks todo</h4></Col>
<Col><ButtonComponent text ="Show more" click={this.showMore}/></Col>
</Row>
<TaskList done = {this.done} list = {this.state.tasks}/>
<br/>
<MessageComponent style ={this.state.style}/>
</div>
)
}
}
export default App;
<file_sep>import React from 'react';
const MessageComponent = (props)=>(
<h4 style ={props.style}>No more tasks to show</h4>
)
export default MessageComponent; | b73c07acc71f8e952327f5cc5e8ba91332eda0b6 | [
"JavaScript"
] | 2 | JavaScript | supriyaavg/task-todo-ReactJS | 0a602787d40a292144258ec68393fa3b47e14732 | 7afe00f8f4ca5f64bd0067d1521f115a63ff96b7 |
refs/heads/master | <file_sep>Exploring Negativity in Yelp Reviews of Healthcare Providers
========================================================
author: <NAME>
date: November 20 2015
transition: rotate
font-family: 'Helvetica'
The Data
========================================================
- Yelp Academic Dataset
- JavaScript Object Notation (JSON) format
- Negative Reviews
- Less than 3 stars
- Healthcare Providers
- Categorized as "Health"
Question(s) & Answer(s)
========================================================
Q: Can these reviews be modeled or classified into "types" based on their content?
A: Yes.
Q: Are there any trends within the descriptive language of each "type" of negative review?
A: Yes.
Topics & Top 3 Terms
========================================================
- Topic 1 = shot, horrible, script
- Topic 2 = son, parent, contract
- Topic 3 = store, food, product
- Topic 4 = dont, ear, fax
- Topic 5 = unprofessional, waiting, attitude
- Topic 6 = mother, mri, knee
***
- Topic 7 = appt, fee, collect
- Topic 8 = massag, foot, groupon
- Topic 9 = daughter, wife, ultrasound
- Topic 10 = glass, lens, sale
- Topic 11 = hair, inject, laser
- Topic 12 = dentist, tooth, crown
The Analysis In Practice
========================================================
The modeled data can be split by topic and analyzed for descriptive language ...

The Analysis In Summary
========================================================
1. Reads in and merges JSON data
3. Filters in "bad" reviews
4. Filters in healthcare providers
5. Preps the data as a document term matrix
6. Models the data with mutliple Latent Dirichlet Allocation (LDA) methods
7. Provides diagnostics for model accuracy
8. Models the data with the "best" method
9. Splits the data by topic
10. Tags adjectives to review text
11. Summarizes prevalence of adjectives in each topic
<file_sep># the following script is used to:
# 1. assign topics to reviews
# 2. tag parts of speech
# 3. isolate adjectives
load("data/topicmodels.rds")
# add topic assignment as a variable to review data frame
# create topic_df for joining
topic_df <- data.frame(topic = topics(review_tm_gibbs,1),
id = names(topics(review_tm_gibbs,1)),
stringsAsFactors = FALSE)
# create id variable for joining
bad_reviews$id <- as.character(1:nrow(bad_reviews))
# join the topics to the bad review data frame
library(dplyr)
bad_reviews_2 <- inner_join(bad_reviews, topic_df)
bad_reviews_2$topic <- factor(bad_reviews_2$topic)
summary(bad_reviews_2$topic)
topic_text <- with(bad_reviews_2,
split(text, topic))
# load NLP and openNLP packages
library(openNLP)
library(NLP)
# create a a tagPOS (tag part of speech) function
tagPOS <- function(x, ...) {
s <- as.String(x)
word_token_annotator <- Maxent_Word_Token_Annotator()
a2 <- Annotation(1L, "sentence", 1L, nchar(s))
a2 <- annotate(s, word_token_annotator, a2)
a3 <- annotate(s, Maxent_POS_Tag_Annotator(), a2)
a3w <- a3[a3$type == "word"]
POStags <- unlist(lapply(a3w$features, `[[`, "POS"))
POStagged <- paste(sprintf("%s/%s", s[a3w], POStags), collapse = " ")
list(POStagged = POStagged, POStags = POStags)
}
acqTag <- lapply(topic_text, tagPOS)
adj_list <- list()
for (i in 1:12) {
adj_list[[i]] <- sapply(strsplit(acqTag[[i]][[1]],"[[:punct:]]*/JJ.?"),function(x) sub("(^.*\\s)(\\w+$)", "\\2", x))
names(adj_list)[i] <- paste("Topic", i, sep = " ")
}
# clean up list of adjectives
adj_list_cleaned <- lapply(adj_list, function(x) ifelse(grepl("/", x), NA, x))
adj_list_cleaned <- lapply(adj_list_cleaned, na.exclude)
save(adj_list_cleaned, file = "data/adjectives.rds")
<file_sep>library(jsonlite)
library(dplyr)
library(ggplot2)
# read in business data
filename <- "data/yelp_dataset_challenge_academic_dataset/yelp_academic_dataset_business.json"
business_json <- lapply(readLines(filename), fromJSON)
city_state <- factor(paste(sapply(business_json, '[[', 'city'), ", ",sapply(business_json, '[[', 'state'), sep=""))
stars <- sapply(business_json, '[[', 'stars')
review_count <- sapply(business_json, '[[', 'review_count')
biz_name <- sapply(business_json, '[[', 'name')
biz_name_length <- nchar(biz_name)
biz_category <- sapply(sapply(business_json, '[[', 'categories'), paste, collapse=";")
business_id <- factor(sapply(business_json, '[[', 'business_id'))
biz_df <- data_frame(business_id, biz_name, biz_name_length,stars, review_count, biz_category, city_state)
# read in review data
filename <- "data/yelp_dataset_challenge_academic_dataset/yelp_academic_dataset_review.json"
review_df <- stream_in(file(filename), pagesize = 10000)
bad_reviews <-
right_join(select(biz_df, business_id, biz_category), review_df) %>%
filter(grepl("Health", review_df$biz_category)) %>%
select(-votes, -type) %>%
filter(stars < 3)
save(bad_reviews, file = "data/badreviews.rds")
<file_sep># the following script is used to:
# 1. wrangle adjectives into a data frame
# 2. gather that dataframe to get a count by topic
# 3. plot the counts across all topics
load("data/adjectives.rds")
# create a data frame for plotting
results_df <- data.frame()
for (i in 1:12) {
adj_list_cleaned[[i]] <- tolower(adj_list_cleaned[[i]])
# results_df$topic[i] <- names(adj_list_cleaned)[i]
results_df[i,1] <- names(adj_list_cleaned)[i]
# results_df$n.rude[i] <- sum(adj_list_cleaned[[i]]=="rude")
# results_df[i,2] <- sum(adj_list_cleaned[[i]]=="rude")
# results_df$n.expensive[i] <- sum(adj_list_cleaned[[i]]=="expensive")
results_df[i,2] <- sum(adj_list_cleaned[[i]]=="expensive")
# results_df$n.unprofessional[i] <- sum(adj_list_cleaned[[i]]=="unprofessional")
# results_df[i,4] <- sum(adj_list_cleaned[[i]]=="unprofessional")
# results_df$n.painful[i] <- sum(adj_list_cleaned[[i]]=="painful")
results_df[i,3] <- sum(adj_list_cleaned[[i]]=="painful")
}
names(results_df) <- c("Topic", "Expensive", "Painful")
results_df$Topic <- factor(results_df$Topic)
library(ggplot2)
library(tidyr)
results_df_tidy <- gather(data = results_df, Topic, value=value)
names(results_df_tidy) <- c("Topic", "Term", "Count")
g <- ggplot(results_df_tidy, aes(x=Topic, y=Count, fill=Term)) +
geom_bar(stat="identity", position="dodge") +
ggtitle("Distributions of Terms Across Topics") +
coord_flip()
g
ggsave(filename = "example.png", plot = g)
<file_sep># Yelp Academic
This repository contains R code for topic modeling the [Yelp Academic Dataset](https://www.yelp.com/academic_dataset).
The data preparation and analysis procedures are split among several scripts.
Follow these steps to use the scripts:
1. Create a /data directory
2. Download and unzip the Yelp Academic Dataset as a subdirectory within /data
3. ```source('prep.R')```
4. ```source('modeltopics.R')```
5. ```source('getadjectives.R')```
6. ```source('plotadjectives.R')```<file_sep># load data
load("badreviews.rds")
# load packages
library(tm)
library(topicmodels)
library(slam)
review_vec <- VectorSource(bad_reviews$text)
review_corpus <- Corpus(review_vec)
review_dtm <- DocumentTermMatrix(review_corpus,
control = list(stemming=TRUE,
stopwords = TRUE,
minWordLength = 2,
removeNumbers = TRUE,
removePunctuation = TRUE)
)
# get rid of infrequent terms using term frequency-inverse document frequency
term_tfidf <- tapply(review_dtm$v/row_sums(review_dtm)[review_dtm$i], review_dtm$j, mean) * log2(nDocs(review_dtm)/col_sums(review_dtm > 0))
review_dtm_trimmed <- review_dtm[, term_tfidf >=0.1]
# get rowtotals and then use that vector to subset dtm for rows that have at least one term
rowTotals <- apply(review_dtm_trimmed, 1, sum)
review_dtm_trimmed <- review_dtm_trimmed[rowTotals> 0, ]
# set number of topics and seed
k <- 12
SEED <- 1999
# diagnostic process that creates all four kinds of topic models to compare for accuracy
review_tm_all <-
list(VEM = LDA(review_dtm_trimmed, k=k, control = list(seed=SEED)),
VEM_fixed = LDA(review_dtm_trimmed, k = k, control = list(estimate.alpha = FALSE, seed = SEED)),
Gibbs = LDA(review_dtm_trimmed, k = k, method = "Gibbs", control = list(seed = SEED, burnin = 1000, thin = 100, iter = 1000)))
# computes mean entropy of topic distributions across all documents
# lower values indicate "peakier" distributions
# higher values indicate "smoother" distributions
sapply(review_tm_all, function(x) mean(apply(posterior(x)$topics,1, function(z) - sum(z*log(z)))))
# Gibbs appears smoothest
# use logLik function to compute loglikelihood of all terms in each model
sapply(review_tm_all, logLik)
# Gibbs has best value
# create gibbs sampling model
review_tm_gibbs <- LDA(review_dtm_trimmed, k = k, method = "Gibbs", control = list(seed = SEED, burnin = 1000, thin = 100, iter = 1000))
# look at the top 10 terms in each topic
terms(review_tm_gibbs,10)
save(review_tm_all, review_tm_gibbs, file = "data/topicmodels.rds")
# create wordclouds if you want ...
# library(wordcloud)
#
# pal <- brewer.pal(10,"Spectral")
#
# plot_wordcloud <- function(model, myDtm, index, numTerms) {
#
# model_terms <- terms(model, numTerms)
# model_topics <- topics(model)
#
# terms_i <- model_terms[,index]
# topic_i <- model_topics == index
# dtm_i <- myDtm[topic_i, terms_i]
# frequencies_i <- colSums(as.matrix(dtm_i))
# wordcloud(terms_i, frequencies_i, min.freq = 0, colors = pal, rot.per = 0)
#
# }
# single topic wordcloud
# plot_wordcloud(model = review_tm_gibbs,
# myDtm = review_dtm_trimmed,
# index = 5,
# numTerms = 15)
# png("plots/wordcloud.png", width=1800, height = 1800)
#
# par(mfrow=c(4,3))
# for (i in 1:12) {
# plot_wordcloud(model = review_tm_gibbs,
# myDtm = review_dtm_trimmed,
# index = i,
# numTerms = 10)
# # plot_title <- paste("Topic", i, sep = " ")
# title(main = paste("Topic", i, sep = " "))
# }
#
# dev.off() | c25ecc1b76eef9bd578eedf078ef2930b219658f | [
"Markdown",
"R"
] | 6 | Markdown | vpnagraj/yelp-academic | 506cc32352492ab339353a96252d7de24a7b002c | 332e6796142010c73ff13dd1cda4992a6a18ded0 |
refs/heads/main | <file_sep>import numpy as np
import cv2
img=cv2.imread('lenna.png') #lenna.png ์์กฐ๋ชจ๋๋ก ์ฝ๊ธฐ
cv2.imshow('Lenna', img)
print(img.shape)
#(๋๋น, ๋์ด) ์ง์ ๋ฐฉ์
width = int(img.shape[1]*0.5)
height = int(img.shape[0]*0.5)
img1=cv2.resize(img, dsize=(width, height))#1/2 ์ถ์ ์์
cv2.imshow('Lenna1', img1)
#(๋๋น, ๋์ด) ๋น์จ ์ง์ ๋ฐฉ์
img2=cv2.resize(img, dsize=(0,0), fx=1.0, fy=1.5)#1/2 ์ถ์ ์์
cv2.imshow('Lenna2', img2)
cv2.waitKey(0)
cv2.destroyAllWindows() #์ด๋ ค์๋ ๋ชจ๋ ์ฐฝ ๋ซ๊ธฐ | f2617de93aa0314eb4b284cd169cbce6673edfbf | [
"Python"
] | 1 | Python | asfawe/python-error-code-help-ME- | 00fe9bdf28433ca3d47f707abf402bd25ab2adeb | f2327ee2f3e27f5e641848e65f71d096c119d267 |
refs/heads/main | <repo_name>AjniraNina/typescript-in-5-min<file_sep>/first.ts
let a = 5;
let b = 5;
let c = a + b;
console.log(c);
class Car{
//fields
model: String;
doors: Number;
isElectric: Boolean;
constructor(model: String, doors:Number, isElectric: Boolean){
this.model = model;
this.doors = doors;
this.isElectric= isElectric;
}
displayMake():void{
console.log(
`this car is ${this.model}`);
}
}
const Prius = new Car('Prius', 4, true);
Prius.displayMake(); // This car is Prius
const Tesla = new Car ('Tesla', 2, true);
Tesla.displayMake(); //this is Tesla
interface ICar {
model: String,
make: String,
display(): void
}
<file_sep>/first.js
var a = 5;
var b = 5;
var c = a + b;
console.log(c);
var Car = /** @class */ (function () {
function Car(model, doors, isElectric) {
this.model = model;
this.doors = doors;
this.isElectric = isElectric;
}
Car.prototype.displayMake = function () {
console.log("this car is " + this.model);
};
return Car;
}());
var Prius = new Car('Prius', 4, true);
Prius.displayMake(); // This car is Prius
var Tesla = new Car('Tesla', 2, true);
Tesla.displayMake(); //this is Tesla
<file_sep>/README.md
"# typescript-in-5-min"
| c6c9f3bacfb900b3dd9306ddb66a5f9b46686970 | [
"JavaScript",
"TypeScript",
"Markdown"
] | 3 | TypeScript | AjniraNina/typescript-in-5-min | 14462b43f050333c1c0bf0fbad6552a2faa2af2a | 496b0fdcf85a4c397b0eecaef63fb5ff8eb9fb7c |
refs/heads/master | <file_sep><?php
namespace App;
use Src\Classes\ClassRoutes;
class Dispatch extends ClassRoutes{
#Atributos
private $Method;
private $Param=[];
private $Obj;
protected function getMethod() {return $this->Method; }
public function setMethod($Method) {$this->Method = $Method; }
protected function getParam() {return $this->Method; }
public function setParam($Param) {$this->Method = $Method; }
#Mรฉtodo Construtor
public function __construct()
{
self::addController();
}
#Mรฉtodo de adiรงรฃo de controller
private function addController()
{
$RotaController=$this->getRota();
$NameS="App\\Controller\\{$RotaController}";
$this->Obj=new $NameS;
if(isset($this->parseUrl()[1])){
self::addMethod();
}
}
#Mรฉtodo de adiรงรฃo de mรฉtodo do controller
private function addMethod()
{
if(method_exists($this->Obj, $this->parseUrl()[1])){
$this->setMethod("{$this->parseUrl()[1]}");
self::addParam();
call_user_func_array([$this->Obj,$this->getMethod()],$this->getParam());
}
} | 621789159fb22fa35f86c75175a49d91c5ebf2c1 | [
"PHP"
] | 1 | PHP | claudiobarr/app | 00543f3b4cad3c28b10e1f24b6e9012ec60a678a | 7cf2f4453fb820af5ed2b9eb6d9106bc4ea56d5d |
refs/heads/master | <repo_name>DMscotifer/wk1_homework3<file_sep>/arrays_hashes_quiz.rb
# Homework
## Exercise A
### Given the following data structure:
stops = [ "Croy", "Cumbernauld", "Falkirk High", "Linlithgow", "Livingston", "Haymarket" ]
### Complete these tasks:
# 1. Add `"Edinburgh Waverley"` to the end of the array
stops.push("Edinburgh Waverley")
# 2. Add `"Glasgow Queen St"` to the start of the array
stops.unshift("Glasgow Queen St")
# 3. Add `"Polmont"` at the appropriate point (between `"Falkirk High"` and `"Linlithgow"`)
stops.insert(4, "Polmont")
# 4. Work out the index position of `"Linlithgow"`
result = stops.find_index("Linlithgow")
# 5. Remove `"Livingston"` from the array using its name
stops.delete("Linlithgow")
# 6. Delete `"Cumbernauld"` from the array by index
stops.delete_at(2)
# 7. How many stops there are in the array?
counter = 0
for count in stops
counter += 1
end
# p counter
# 8. How many ways can we return `"Falkirk High"` from the array?
# p stops[2]
# p stops[-5]
# p stops
# 9. Reverse the positions of the stops in the array
# p stops.reverse
# 10. Print out all the stops using a for loop
for station in stops
p station
end
## Exercise B
### Given the following data structure:
users = {
"Jonathan" => {
:twitter => "jonnyt",
:lottery_numbers => [6, 12, 49, 33, 45, 20],
:home_town => "Stirling",
:pets => [
{
:name => "fluffy",
:species => "cat"
},
{
:name => "fido",
:species => "dog"
},
{
:name => "spike",
:species => "dog"
}
]
},
"Erik" => {
:twitter => "eriksf",
:lottery_numbers => [18, 34, 8, 11, 24],
:home_town => "Linlithgow",
:pets => [
{
:name => "nemo",
:species => "fish"
},
{
:name => "kevin",
:species => "fish"
},
{
:name => "spike",
:species => "dog"
},
{
:name => "rupert",
:species => "parrot"
}
]
},
"Avril" => {
:twitter => "bridgpally",
:lottery_numbers => [12, 14, 33, 38, 9, 25],
:home_town => "Dunbar",
:pets => [
{
:name => "monty",
:species => "snake"
}
]
}
}
### Complete these tasks:
# 1. Get Jonathan's Twitter handle (i.e. the string `"jonnyt"`)
p users["Jonathan"][:twitter]
# 2. Get Erik's hometown
p users["Erik"][:home_town]
# 3. Get the array of Erik's lottery numbers
p users["Erik"][:lottery_numbers]
# 4. Get the type of Avril's pet Monty
p users["Avril"][:pets][0][:species]
# 5. Get the smallest of Erik's lottery numbers
sorted_lottery_num = users["Erik"][:lottery_numbers].sort
p smallest_lottery_num = sorted_lottery_num[0]
# 6. Return an array of Avril's lottery numbers that are even
users["Avril"][:lottery_numbers].select {|number| if number % 2 == 0
p number
end
}
# 7. Erik is one lottery number short! Add the number `7` to be included in his lottery numbers
users["Erik"][:lottery_numbers] << 7
p users["Erik"][:lottery_numbers]
# 8. Change Erik's hometown to Edinburgh
users["Erik"][:home_town] = "Edinburgh"
# 9. Add a pet dog to Erik called "Fluffy"
users["Erik"][:pets] << {name: "Fluffy", species: "dog"}
p users["Erik"][:pets]
# 10. Add another person to the users hash
# users << "Alice" => {
# :twitter = "projectalice",
# :lottery_numbers => [11, 4, 23, 48, 9, 25],
# :home_town => "Glasgow",
# :pets => [
# {
# :name => "michelle",
# :species => "viper"
# }
# ]
# }
# users.merge = {"Alice" => {
# :twitter = "projectalice",
# :lottery_numbers => [11, 4, 23, 48, 9, 25],
# :home_town => "Glasgow",
# }}
# p users
# Possible error as a result of ruby version issue
# RUBY ERROR "arrays_hashes_quiz.rb:145: syntax error, unexpected =>, expecting end-of-input"
# users << {:residential => "false"}
# => [{:residential=>"false"}]
## Exercise C
### Given the following data structure:
united_kingdom = [
{
name: "Scotland",
population: 5295000,
capital: "Edinburgh"
},
{
name: "Wales",
population: 3063000,
capital: "Swansea"
},
{
name: "England",
population: 53010000,
capital: "London"
}
]
### Complete these tasks:
# 1. Change the capital of Wales from `"Swansea"` to `"Cardiff"`.
united_kingdom[1][:capital] = "Swansea"
# 2. Create a Hash for Northern Ireland and add it to the `united_kingdom` array (The capital is Belfast, and the population is 1,811,000).
united_kingdom << {
name: "Ireland",
population: 1811000,
capital: "Belfast"
}
p united_kingdom
# 3. Use a loop to print the names of all the countries in the UK.
for country in united_kingdom
p country[:name]
end
# 4. Use a loop to find the total population of the UK.
total_population = 0
for country in united_kingdom
total_population += country[:population]
end
p total_population
| 8ed6dffd7979eda5b79c64b8e04b783546e6171d | [
"Ruby"
] | 1 | Ruby | DMscotifer/wk1_homework3 | 8365df3b7256e33b1a0ee0da3ebb70036dfc5b05 | c730884c11347b6a3efeca7561d42ac267e00af1 |
refs/heads/master | <repo_name>astak16/pikachu-2018-6-5<file_sep>/js/main.js
let code =`
/*
* ไปๅคฉๆๆฅ็ปไธไธช็ฎๅกไธ
* ้ฆๅ
็ป็ฎๅกไธ็็ฎ
*/
.wrapper{
width:100%;
height:165px;
position:relative;
}
/* ็ป้ผปๅญ*/
.nose{
border: 12px solid;
border-radius: 11px;
border-color:black transparent transparent;
position: absolute;
left:50%;
top:28px;
margin-left: -12px;
}
/*็ป็ผ็*/
.eye{
width:49px;
height:49px;
background:#2e2e2e;
position:absolute;
border-radius:50%;
border:2px solid #000000;
}
/*็ฝ่ฒ็็ผ็ */
.eye:before{
content:'';
display: block;
width:24px;
height:24px;
background: white;
position:absolute;
border-radius:50px;
left:6px;
top:-1px;
border:2px solid #000;
}
/* ๅณ็ผ็ๅจๅณ */
.eye.right{
left: 50%;
margin-left:90px;
}
/* ๅทฆ็ผ็ๅจๅทฆ */
.eye.left{
right:50%;
margin-right:90px;
}
/* ๆฅไธๆฅ็ป่ธ่ */
.face{
width:68px;
height:68px;
background:#fc0d1c;
border-radius:50%;
position: absolute;
top:85px;
}
.face.left{
right: 50%;
margin-right:116px;
}
.face.right{
left:50%;
margin-left:116px
}
/* ไธๅดๅ */
.upperLip{
height:25px;
width:80px;
border:2px solid black;
position:absolute;
top:50px;
background: #fde348;
}
.upperLip.left{
right:50%;
border-bottom-left-radius: 40px 25px;
border-top: none;
border-right:none;
transform:rotate(-20deg);
}
.upperLip.right{
left:50%;
border-bottom-right-radius: 40px 25px;
border-top: none;
border-left:none;
transform:rotate(20deg);
}
/* ไธๅดๅ */
.lowerLip-wrapper{
bottom:0;
position: absolute;
left: 50%;
margin-left:-150px;
height:110px;
overflow: hidden;
width:300px;
}
.lowerLip{
height:3500px;
width:300px;
background: #990513;
border-radius: 200px/2000px;
border:2px solid black;
position: absolute;
bottom:0;
overflow: hidden;
}
/* ๆๅๆฅไธไธชๅฏ็ฑ็่ๅคด */
.lowerLip::after{
content: '';
position: absolute;
bottom:-20px;
width:100px;
height:100px;
background:#fc4a62;
left:50%;
margin-left:-50px;
border-radius: 50px;
}
/* ๅฅฝๅฆ๏ผ็ฎๅกไธ็ปๅฎไบ */`
!function(){
function drawPikachu(preCode,code,fn){
let domCode = document.querySelector('#code')
let n = 0
let id = setTimeout(function run(){
domCode.innerHTML = preCode + code.substring(0,n)
styleTag.innerHTML = preCode + code.substring(0,n)
domCode.scrollTop = domCode.scrollHeight
n += 1
if(n < code.length){
setTimeout(run,10)
// fn.call()
}else{
document.getElementById('music').play()
}
},10)
}
drawPikachu('',code)
}.call() | 248ac13a05b397e2f0993207ed84466fce3b1d93 | [
"JavaScript"
] | 1 | JavaScript | astak16/pikachu-2018-6-5 | 8eb0b542eb04a554f2594ce091f5ceb0d1bf7b94 | 5f78ed82dddccfb6018e6a6dd07be3658b743f3e |
refs/heads/master | <file_sep>drop database if exists ssa20142015;
create database ssa20142015
default character set utf8
default collate utf8_general_ci;
use ssa20142015;
create table dojave (
sifra int not null primary key auto_increment,
pas_id int not null,
korisnici_id int not null,
datum datetime
) engine=innodb;
create table pas (
sifra int not null primary key auto_increment,
status_psa int not null,
ime varchar(300),
opis varchar (300),
lokacija varchar(300)
) engine=innodb;
create table status_psa (
sifra int not null primary key auto_increment,
naziv_pas varchar(300)
) engine=innodb;
create table korisnici (
sifra int not null primary key auto_increment,
ime varchar(300),
prezime varchar(300),
email varchar(300),
lozinka varchar(300),
status_korisnika int not null
) engine=innodb;
create table status_korisnika (
sifra int not null primary key auto_increment,
naziv_korisnika varchar(300)
) engine=innodb;
alter table dojave add foreign key(pas_id) references pas(sifra);
alter table pas add foreign key(status_psa) references status_psa(sifra);
alter table dojave add foreign key(korisnici_id) references korisnici(sifra);
alter table korisnici add foreign key(status_korisnika) references status_korisnika(sifra);
insert into status_psa (naziv_pas) values ('izgubljen');
insert into status_psa (naziv_pas) values ('pronaฤen');
insert into status_korisnika (naziv_korisnika) values ('volonter');
insert into status_korisnika (naziv_korisnika) values ('anoniman korisnik');
insert into status_korisnika (naziv_korisnika) values ('korisnik');
insert into pas (status_psa, ime, opis, lokacija) values (2, 'Miki', 'ลกtene hrvatskog ovฤara', 'Retfala');
insert into pas (status_psa, ime, opis, lokacija) values (2, 'Flafi', 'crni mjeลกanac', 'Filozofski fakultet Osijek');
insert into pas (status_psa, ime, opis, lokacija) values (1, NULL, 'mjeลกanac njemaฤkog ovฤara', 'Reisnerova 115');
insert into korisnici (ime, prezime, email, lozinka, status_korisnika) values ('Ana', 'Aniฤ', '<EMAIL>', md5('anaanic123'), 1);
insert into korisnici (ime, prezime, email, lozinka, status_korisnika) values (NULL, NULL, '<EMAIL>', md5('123456789'), 2);
insert into korisnici (ime, prezime, email, lozinka, status_korisnika) values ('Pero', 'Periฤ', '<EMAIL>', md5('perojesuper'), 3);
insert into dojave (pas_id, korisnici_id, datum) values (1, 1, '2015-01-01');
insert into dojave (pas_id, korisnici_id, datum) values (2, 2, '2015-01-01');
insert into dojave (pas_id, korisnici_id, datum) values (3, 3, '2015-01-02');
<file_sep>SSA20142015
===========
Kod s predavanja 07. 01. 2015. u sklopu Osijek Software City Software Startup Academy 2014/2015. Predavanje na temu: Vaลกa prva PHP + JSON + AJAX + JQUERY + FOUNDATION + HTML + CSS aplikacija
Polaznici su upoznati s konkretnim primjerom koji joลก nema razraฤeno aplikacijsko rjeลกenje (primjer u sklopu FFOS inkubatora) za koje su prikazane aktivnosti projektiranje baze podataka, implementacija ERA dijagrama, izrada mreลพnih stranica, Responsive Web Design, kreiranje web aplikacije ( PHP + JSON + AJAX + JQUERY + FOUNDATION + HTML + CSS) te postavljanje aplikacije na server. Zbog obima posla nije bilo moguฤe sve nakucati u realnom vremenu, stoga ฤe se koristiti gotovi dijelovi koda kako bi se prikazao princip. Sav koriลกteni kod nalazi se u ovom repozitoriju.
<file_sep><?php
include_once 'modalAutorizacija.php';
?>
<script src="<?php echo $putanjaApp; ?>js/vendor/jquery.js"></script>
<script src="<?php echo $putanjaApp; ?>js/foundation.min.js"></script>
<script src="<?php echo $putanjaApp; ?>js/md5.js"></script>
<script>
$(document).foundation();
$(function() {
$("#autorizacija").click(
function() {
$("#poruka").html("");
if($("#email").val().trim().length==0){
$("#poruka").html("Email obavezno");
return; //Shor Curcuit
}
if($("#lozinka").val().trim().length==0){
$("#poruka").html("Lozinka obavezno");
return; //Shor Curcuit
}
$.ajax({
type : "POST",
url : "autoriziraj.php",
data : "email=" + $("#email").val()
+ "&lozinka="
+ MD5($("#lozinka").val()),
dataType : "html",
success : function(msg) {
if (msg == "true") {
window.location = "administracija/nadzornaPloca.php";
}
else {
$("#poruka").html("Neispravna kombinacija korisniฤkog imena i lozinke");
}
}
});
return false;
});
});
</script>
<file_sep><?php include_once '../../konfiguracija.php';
if(!isset($_SESSION[$ida . "autoriziran"])){
header("location: ../../index.php");
}
if(isset($_GET["sifra"])){
$izraz = $veza -> prepare("select * from operater where sifra=:sifra");
$izraz -> execute($_GET);
$operater = $izraz -> fetch(PDO::FETCH_OBJ);
}
$greske=array();
if($_POST){
include_once 'kontrola.php';
include_once 'kontrolaLozinkiPromjena.php';
if(empty($greske)){
if(strlen($_POST["lozinka"])>0){
unset($_POST["ponovoLozinka"]);
$_POST["lozinka"] = md5($_POST["lozinka"]);
$izraz = $veza -> prepare("update operater set email=:email,ime=:ime,prezime=:prezime,lozinka=:lozinka where sifra=:sifra;");
}else{
unset($_POST["lozinka"]);
unset($_POST["ponovoLozinka"]);
$izraz = $veza -> prepare("update operater set email=:email,ime=:ime,prezime=:prezime where sifra=:sifra;");
}
$izraz -> execute($_POST);
header("location: index.php");
}else{
$operater=new stdClass();
$operater->sifra=$_POST["sifra"];
$operater->email=$_POST["email"];
$operater->ime=$_POST["ime"];
$operater->prezime=$_POST["prezime"];
}
}
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<title><?php echo $naslovAPP ?> Promjena operatera</title>
<?php
include_once '../../head.php';
?>
</head>
<body>
<?php
include_once '../izbornik.php';
?>
<div class="row">
<div class="large-12 columns">
<div class="panel">
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
<fieldset>
<legend>Upisni podaci</legend>
<label for="email" <?php
$poruka="";
foreach ($greske as $g) {
if($g->element=="email"){
$poruka=$g->poruka;
break;
}
}
if(strlen($poruka)>0){
echo "class=\"error\"";
}
?> >Email
<input type="email" id="email" name="email"
value="<?php echo $operater->email; ?>"/>
<?php
if(strlen($poruka)>0){
echo "<small class=\"error\">" . $poruka . "</small>";
}
?>
</label>
<label for="ime" <?php
$poruka="";
foreach ($greske as $g) {
if($g->element=="ime"){
$poruka=$g->poruka;
break;
}
}
if(strlen($poruka)>0){
echo "class=\"error\"";
}
?> >Ime
<input type="text" id="ime" name="ime"
value="<?php echo $operater->ime; ?>" />
<?php
if(strlen($poruka)>0){
echo "<small class=\"error\">" . $poruka . "</small>";
}
?>
</label>
<label for="prezime" <?php
$poruka="";
foreach ($greske as $g) {
if($g->element=="prezime"){
$poruka=$g->poruka;
break;
}
}
if(strlen($poruka)>0){
echo "class=\"error\"";
}
?> >Prezime
<input type="text" id="prezime" name="prezime"
value="<?php echo $operater->prezime; ?>" />
<?php
if(strlen($poruka)>0){
echo "<small class=\"error\">" . $poruka . "</small>";
}
?>
</label>
<a href="#" class="success button siroko">U sluฤaju ne mijenjanja lozinke polja Lozinka i Lozinka ponovo ostaviti prazna</a>
<label for="lozinka" <?php
$poruka="";
foreach ($greske as $g) {
if($g->element=="lozinka"){
$poruka=$g->poruka;
break;
}
}
if(strlen($poruka)>0){
echo "class=\"error\"";
}
?> >Lozinka
<input type="password" id="lozinka" name="lozinka" />
<?php
if(strlen($poruka)>0){
echo "<small class=\"error\">" . $poruka . "</small>";
}
?>
</label>
<label for="ponovoLozinka" <?php
$poruka="";
foreach ($greske as $g) {
if($g->element=="ponovoLozinka"){
$poruka=$g->poruka;
break;
}
}
if(strlen($poruka)>0){
echo "class=\"error\"";
}
?> >Ponovo lozinka
<input type="password" id="ponovoLozinka" name="ponovoLozinka" />
<?php
if(strlen($poruka)>0){
echo "<small class=\"error\">" . $poruka . "</small>";
}
?>
</label>
<input type="hidden" name="sifra" value="<?php echo $operater->sifra;?>" />
<div class="row">
<div class="large-6 columns">
<a href="index.php" class="alert button siroko">Odustani</a>
</div>
<div class="large-6 columns">
<input class="success button siroko" type="submit" value="Spremi" />
</div>
</div>
</form>
</div>
</div>
<?php
include_once '../skripte.php';
?>
</body>
</html>
<file_sep><?php
if (!preg_match("/^[a-z ,.'-ร รกรขรครฃรฅฤ
ฤฤฤรจรฉรชรซฤฤฏรฌรญรฎรฏลลรฒรณรดรถรตรธรนรบรปรผลณลซรฟรฝลผลบรฑรงฤลกลพรรรรรร
ฤฤฤฤฤรรรรรรรรฤฎลลรรรรรรรรรรลฒลชลธรลปลนรรรลรฤล ลฝโรฐ]+$/i", $_POST["ime"])) {
$g=new stdClass();
$g->element="ime";
$g->poruka="Ime sadrลพi nedozvoljene znakove";
array_push($greske,$g);
}
if (!preg_match("/^[a-z ,.'-ร รกรขรครฃรฅฤ
ฤฤฤรจรฉรชรซฤฤฏรฌรญรฎรฏลลรฒรณรดรถรตรธรนรบรปรผลณลซรฟรฝลผลบรฑรงฤลกลพรรรรรร
ฤฤฤฤฤรรรรรรรรฤฎลลรรรรรรรรรรลฒลชลธรลปลนรรรลรฤล ลฝโรฐ]+$/i", $_POST["prezime"])) {
$g=new stdClass();
$g->element="prezime";
$g->poruka="Prezime sadrลพi nedozvoljene znakove";
array_push($greske,$g);
}
<file_sep><?php include_once '../../konfiguracija.php';
if(!isset($_SESSION[$ida . "autoriziran"])){
header("location: ../../index.php");
}
$greske=array();
if($_POST){
include_once 'kontrola.php';
include_once 'kontrolaLozinkiUnos.php';
if(empty($greske)){
unset($_POST["ponovoLozinka"]);
$_POST["lozinka"] = md5($_POST["lozinka"]);
$izraz = $veza -> prepare("insert into operater(email,ime,prezime,lozinka) values (:email,:ime,:prezime,:lozinka);");
$izraz -> execute($_POST);
header("location: index.php");
// print_r($_POST);
}
}
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<title><?php echo $naslovAPP ?> Unos novog operatera</title>
<?php
include_once '../../head.php';
?>
</head>
<body>
<?php
include_once '../izbornik.php';
?>
<div class="row">
<div class="large-12 columns">
<div class="panel">
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
<fieldset>
<legend>Upisni podaci</legend>
<label for="email" <?php
$poruka="";
foreach ($greske as $g) {
if($g->element=="email"){
$poruka=$g->poruka;
break;
}
}
if(strlen($poruka)>0){
echo "class=\"error\"";
}
?> >Email
<input type="email" id="email" name="email"
value="<?php echo isset($_POST["email"]) ? $_POST["email"] : ""; ?>"/>
<?php
if(strlen($poruka)>0){
echo "<small class=\"error\">" . $poruka . "</small>";
}
?>
</label>
<label for="ime" <?php
$poruka="";
foreach ($greske as $g) {
if($g->element=="ime"){
$poruka=$g->poruka;
break;
}
}
if(strlen($poruka)>0){
echo "class=\"error\"";
}
?> >Ime
<input type="text" id="ime" name="ime"
value="<?php echo isset($_POST["ime"]) ? $_POST["ime"] : ""; ?>" />
<?php
if(strlen($poruka)>0){
echo "<small class=\"error\">" . $poruka . "</small>";
}
?>
</label>
<label for="prezime" <?php
$poruka="";
foreach ($greske as $g) {
if($g->element=="prezime"){
$poruka=$g->poruka;
break;
}
}
if(strlen($poruka)>0){
echo "class=\"error\"";
}
?> >Prezime
<input type="text" id="prezime" name="prezime"
value="<?php echo isset($_POST["prezime"]) ? $_POST["prezime"] : ""; ?>" />
<?php
if(strlen($poruka)>0){
echo "<small class=\"error\">" . $poruka . "</small>";
}
?>
</label>
<label for="lozinka" <?php
$poruka="";
foreach ($greske as $g) {
if($g->element=="lozinka"){
$poruka=$g->poruka;
break;
}
}
if(strlen($poruka)>0){
echo "class=\"error\"";
}
?> >Lozinka
<input type="password" id="lozinka" name="lozinka" />
<?php
if(strlen($poruka)>0){
echo "<small class=\"error\">" . $poruka . "</small>";
}
?>
</label>
<label for="ponovoLozinka" <?php
$poruka="";
foreach ($greske as $g) {
if($g->element=="ponovoLozinka"){
$poruka=$g->poruka;
break;
}
}
if(strlen($poruka)>0){
echo "class=\"error\"";
}
?> >Ponovo lozinka
<input type="password" id="ponovoLozinka" name="ponovoLozinka" />
<?php
if(strlen($poruka)>0){
echo "<small class=\"error\">" . $poruka . "</small>";
}
?>
</label>
<div class="row">
<div class="large-6 columns">
<a href="index.php" class="alert button siroko">Odustani</a>
</div>
<div class="large-6 columns">
<input class="success button siroko" type="submit" value="Spremi" />
</div>
</div>
</form>
</div>
</div>
</div>
<?php
include_once '../skripte.php';
?>
</body>
</html>
<file_sep><nav class="top-bar" data-topbar role="navigation">
<ul class="title-area">
<li class="name">
<h1><a href="<?php echo $putanjaApp; ?>administracija/nadzornaPloca.php">ADMIN</a></h1>
</li>
<!-- Remove the class "menu-icon" to get rid of menu icon. Take out "Menu" to just have icon alone -->
<li class="toggle-topbar menu-icon">
<a href="#"><span>IZBOR</span></a>
</li>
</ul>
<section class="top-bar-section">
<!-- Right Nav Section -->
<ul class="right">
<li class="has-dropdown">
<a href="#">Ostalo</a>
<ul class="dropdown">
<li>
<a href="#">Psi</a>
</li>
<li>
<a href="#">Korisnici</a>
</li>
<li>
<a href="#">Statusi pasa</a>
</li>
<li>
<a href="#">Statusi korisnika</a>
</li>
<li>
<a href="<?php echo $putanjaApp; ?>administracija/operateri/index.php">Operateri</a>
</li>
</ul>
</li>
<li>
<a class="button" href="<?php echo $putanjaApp; ?>administracija/odjava.php">Odjava</a>
</li>
</ul>
<!-- Left Nav Section -->
<ul class="left">
<li>
<a href="<?php echo $putanjaApp; ?>administracija/neobradeneDojave/index.php">Neobraฤene dojave</a>
</li>
</ul>
</section>
</nav><file_sep><?php include_once '../../konfiguracija.php';
if(!isset($_SESSION[$ida . "autoriziran"])){
header("location: ../../index.php");
}
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<title><?php echo $naslovAPP ?> Operateri</title>
<?php
include_once '../../head.php';
?>
</head>
<body>
<?php
include_once '../izbornik.php';
?>
<div class="row">
<div class="large-12 columns">
<div class="panel">
<a class="button siroko" href="unosNovog.php">Dodaj novi</a>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>"
method="POST">
<fieldset>
<legend>Unesite dio email-a, imena ili prezimena</legend>
<input type="text" name="uvjet" value="<?php
echo isset($_POST["uvjet"]) ? $_POST["uvjet"] : "";
?>"
/>
<input type="submit" class="button siroko" value="Traลพi" />
</form>
<table style="width: 100%">
<thead>
<tr>
<th>Email</th>
<th>Ime</th>
<th>Prezime</th>
<th>Akcija</th>
</tr>
</thead>
<tbody><?php
$izraz = $veza -> prepare("select * from operater where email like :uvjet or prezime like :uvjet or ime like :uvjet");
if(!$_POST){
$uvjet="";
}else{
$uvjet=$_POST["uvjet"];
}
$uvjet = "%" . $uvjet . "%";
$izraz->bindParam(":uvjet", $uvjet);
$izraz -> execute();
$rezultati = $izraz -> fetchAll(PDO::FETCH_OBJ);
foreach ($rezultati as $red):
?>
<tr>
<td><?php echo $red -> email; ?></td>
<td><?php echo $red -> ime; ?></td>
<td><?php echo $red -> prezime; ?></td>
<td>
<a href="promjena.php?sifra=<?php echo $red -> sifra; ?>">Promjeni</a>
<a href="brisanje.php?sifra=<?php echo $red -> sifra; ?>">Obriลกi</a>
</td>
</tr>
<?php
endforeach;
$veza = null;
?></tbody>
</table>
</div>
</div>
</div>
<?php
include_once '../skripte.php';
?>
</body>
</html>
<file_sep><?php include_once '../konfiguracija.php'; ?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<?php
include_once '../head.php';
?>
<title><?php echo $naslovAPP; ?> ADMINISTRACIJA</title>
</head>
<body>
ovdje doฤe nadzorna ploฤa
</body>
</html>
<file_sep><?php
if(!$_POST || !isset($_POST['podaci']))
return;
include_once 'konfiguracija.php';
$p=json_decode($_POST['podaci']);
$izraz = $veza->prepare("select * from operater where email=:email and lozinka=:lozinka");
$izraz->bindValue(":email", $p->email );
$izraz->bindValue(":lozinka", $p->lozinka );
$izraz->execute();
$entitet = $izraz->fetch(PDO::FETCH_OBJ);
$odgovor=new stdClass();
if ($entitet!=null){
$_SESSION[$ida . "autoriziran"]=$entitet;
$odgovor->status=true;
$odgovor->stranica="administracija/nadzornaPloca.php";
}
else{
$odgovor->status=false;
$odgovor->poruka="Neispravna kombinacija korisniฤko ime ili lozinka";
}
echo json_encode($odgovor);<file_sep><?php
include_once '../konfiguracija.php';
if (!isset($_SESSION[$ida . "autoriziran"])) {
header("location: ../index.php");
}
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<?php
include_once '../head.php';
?>
<title><?php echo $naslovAPP; ?>
ADMINISTRACIJA</title>
</head>
<body>
<?php
include_once 'izbornik.php';
?>
<div class="row">
<div class="large-12">
<div id="container" style="height: 400px"></div>
</div>
</div>
<?php
include_once 'skripte.php';
?>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/highcharts-3d.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script>
$(function () {
$('#container').highcharts({
chart: {
type: 'pie',
options3d: {
enabled: true,
alpha: 45,
beta: 0
}
},
title: {
text: 'Omjer izgubljenih i pronaฤenih'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
depth: 55,
dataLabels: {
enabled: true,
format: '{point.name}'
}
}
},
series: [{
type: 'pie',
name: 'Udio',
data: [
<?php
$veza->exec("set names utf8");
$izraz = $veza->prepare("select vrsta, count(vrsta) as ukupno from neobradene_dojave group by vrsta;");
$izraz->execute();
$rezultati = $izraz->fetchAll(PDO::FETCH_OBJ);
$s="";
foreach ($rezultati as $r){
$s=$s . "[" . "'" . $r->vrsta . "'," . $r->ukupno . "],";
}
echo $s;
?>
]
}]
});
});
</script>
</body>
</html>
<file_sep><div class="row">
<?php
$izraz = $veza -> prepare("select * from neobradene_dojave where odobreno=1 order by datum desc");
$izraz -> execute();
$rezultati = $izraz -> fetchAll(PDO::FETCH_OBJ);
foreach ($rezultati as $red):
?>
<div class="large-4 columns">
<div class="panel callout radius">
<?php echo $red -> poruka; ?>
<hr />
<a href="#">Viลกe</a>
</div>
</div>
<?php
endforeach;
$veza = null;
?>
</div>
<file_sep><ul class="example-orbit show-for-medium-up" data-orbit>
<?php
$slike = scandir($_SERVER["DOCUMENT_ROOT"] . $putanjaApp . "img/dojave/");
foreach ($slike as $s):
if(substr($s, 0,1)=="."){
continue;
}
?>
<li>
<img style="width: 750px; height: 500px;" src="img/dojave/<?php echo $s ?>">
<div class="orbit-caption">
Dio opisa iz baze. <a href="#">Viลกe</a>
</div>
</li>
<?php
endforeach;
?>
</ul>
<file_sep><?php
include_once 'konfiguracija.php';
//OVO JE PRIMJER SVE U JEDNOJ DATOTECI
$poruke=array();
//nije post preskoฤi, princip Short-Circuit
if(!$_POST){
//iako nepopularna, naredba goto nije loลกa, samo su je ljudi loลกe koristili
goto ostalo;
}
//nije oznaฤena vrsta preskoฤi
if(!isset($_POST["vrsta"])){
array_push($poruke, "Obavezno odabir Izgubljen/Pronaฤen");
goto ostalo;
}
//nije unesena poruka preskoฤi
if(strlen(trim($_POST["poruka"]))==0){
array_push($poruke,"Obavezno Poruka");
goto ostalo;
}
//za debug
//echo "<pre>";
//print_r($_POST);
//echo "</pre>";
//sve je kako treba, radim insert u bazu
$izraz = $veza->prepare("insert into neobradene_dojave (vrsta,poruka,datum) values (:vrsta, :poruka, now());");
$izraz->bindParam(':vrsta', $_POST["vrsta"]);
$izraz->bindParam(':poruka', $_POST["poruka"]);
$izraz->execute();
$zadnji=$veza->lastInsertId();
//ako je postavljena slika spremi je pod ienom dodjeljene ลกifre u bazi
if(!$_FILES){
goto ostalo;
}
//echo "<pre>";
//print_r($_FILES);
//echo "</pre>";
$slike_dir = "img/dojave/";
$ext = pathinfo($_FILES['slika']['name'], PATHINFO_EXTENSION);
$slika_datoteka = $slike_dir . $zadnji . "." . $ext;
echo $slika_datoteka;
move_uploaded_file($_FILES["slika"]["tmp_name"], $slika_datoteka);
header("location: dojavaZaprimljena.php");
ostalo:
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<?php
include_once 'head.php';
?>
<title><?php echo $naslovAPP; ?></title>
</head>
<body>
<?php
include_once 'zaglavlje.php';
?>
<hr class="cisto" />
<div class="row">
<div class="large-8 columns large-push-2">
<h1 class="naslov">DOJAVA</h1>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>" enctype="multipart/form-data">
<fieldset>
<legend>Popunite traลพene podatke</legend>
<div class="row">
<?php if(!empty($poruke)): ?>
<div class="large-12 columns">
<?php foreach ($poruke as $p): ?>
<small class="error"><?php echo $p; ?></small>
<?php endforeach; ?>
</div>
<?php endif; ?>
<div class="large-6 columns">
<input type="radio" name="vrsta" value="izgubljen" id="izgubljen" <?php echo (isset($_POST["vrsta"]) && $_POST["vrsta"]=="izgubljen") ? "checked=\"checked\"" : ""; ?> />
<label for="izgubljen">Izgubljen</label>
</div>
<div class="large-6 columns">
<input type="radio" name="vrsta" value="pronaden" id="pronaden" <?php echo (isset($_POST["vrsta"]) && $_POST["vrsta"]=="pronaden") ? "checked=\"checked\"" : ""; ?> />
<label for="pronaden">Pronaฤen</label>
</div>
</div>
<label for="slika">Slika</label>
<input type="file" name="slika" id="slika" />
<label for="poruka">Poruka</label>
<textarea placeholder="Unesite tekst dojave ovdje" cols="50" rows="20" name="poruka"><?php echo (isset($_POST["poruka"]) && strlen(trim($_POST["poruka"]))>0) ? $_POST["poruka"] : ""; ?></textarea>
<input type="submit" value="Poลกalji" class="button" />
</fieldset>
</form>
</div>
<div class="large-2 columns large-pull-8">
<?php
include_once 'lijevo.php';
?>
</div>
<div class="large-2 columns">
<?php
include_once 'desno.php';
?>
</div>
</div>
<?php
include_once 'skripte.php';
?>
</body>
</html>
<file_sep><?php
include_once '../konfiguracija.php';
if (!isset($_SESSION[$ida . "autoriziran"])) {
header("location: ../index.php");
}
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<?php
include_once '../head.php';
?>
<title><?php echo $naslovAPP; ?>
ADMINISTRACIJA</title>
</head>
<body>
<?php
include_once 'izbornik.php';
?>
<div class="row">
<div class="large-12">
ovdje ฤe doฤi neki zgodan graf
</div>
</div>
<?php
include_once 'skripte.php';
?>
</body>
</html>
<file_sep><?php include_once '../../konfiguracija.php';
if(!isset($_SESSION[$ida . "autoriziran"])){
header("location: ../../index.php");
}
if(isset($_GET["odobreno"]) && isset($_GET["sifra"])){
$izraz = $veza->prepare("update neobradene_dojave set odobreno=:odobreno where sifra=:sifra;");
$izraz->execute($_GET);
}
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<title><?php echo $naslovAPP ?> Operateri</title>
<?php
include_once '../../head.php';
?>
</head>
<body>
<?php
include_once '../izbornik.php';
?>
<div class="row">
<div class="large-12 columns">
<div class="panel">
<form action="<?php echo $_SERVER['PHP_SELF'] ?>"
method="POST">
<fieldset>
<legend>Unesite dio poruke</legend>
<input type="text" name="uvjet" value="<?php
echo isset($_POST["uvjet"]) ? $_POST["uvjet"] : "";
?>"
/>
<input type="submit" class="button siroko" value="Traลพi" />
</form>
<table style="width: 100%">
<thead>
<tr>
<th>Slika</th>
<th>Vrsta</th>
<th>Poruka</th>
<th>Status</th>
<th>Akcija</th>
</tr>
</thead>
<tbody><?php
$izraz = $veza -> prepare("select * from neobradene_dojave where poruka like :uvjet order by odobreno");
if(!$_POST){
$uvjet="";
}else{
$uvjet=$_POST["uvjet"];
}
$uvjet = "%" . $uvjet . "%";
$izraz->bindParam(":uvjet", $uvjet);
$izraz -> execute();
$rezultati = $izraz -> fetchAll(PDO::FETCH_OBJ);
foreach ($rezultati as $red):
?>
<tr>
<td>
<?php
if(file_exists($_SERVER["DOCUMENT_ROOT"] . $putanjaApp . "img/dojave/" . $red -> sifra . ".jpg")): ?>
<img class="slikaPregled" src="<?php echo $putanjaApp; ?>img/dojave/<?php echo $red -> sifra; ?>.jpg" />
<?php endif; ?>
</td>
<td><?php echo $red -> vrsta; ?></td>
<td><?php echo $red -> poruka; ?></td>
<td><?php echo $red -> odobreno; ?></td>
<td>
<?php
if($red -> odobreno): ?>
<a href="<?php echo $_SERVER["PHP_SELF"] ?>?odobreno=0&sifra=<?php echo $red -> sifra; ?>">Zabrani</a>
<?php else:
?>
<a href="<?php echo $_SERVER["PHP_SELF"] ?>?odobreno=1&sifra=<?php echo $red -> sifra; ?>">Odobri</a>
<?php
endif; ?>
</td>
</tr>
<?php
endforeach;
$veza = null;
?></tbody>
</table>
</div>
</div>
</div>
<?php
include_once '../skripte.php';
?>
</body>
</html>
<file_sep><?php
if(!$_POST || !isset($_POST['email']) || !isset($_POST['lozinka']))
return;
include_once 'konfiguracija.php';
$izraz = $veza->prepare("select * from operater where email=:email and lozinka=:lozinka");
$izraz->bindValue(":email", $_POST['email'] );
$izraz->bindValue(":lozinka", $_POST['lozinka'] );
$izraz->execute();
$entitet = $izraz->fetch(PDO::FETCH_OBJ);
if ($entitet!=null){
$_SESSION[$ida . "autoriziran"]=$entitet;
echo "true";
}
else{
echo "false";
}
<file_sep><!doctype html>
<html class="no-js" lang="en">
<head>
<?php
include_once 'head.php';
?>
<title>Azil</title>
</head>
<body>
<?php
include_once 'zaglavlje.php';
?>
<hr class="cisto" />
<div class="row">
<div class="large-8 columns large-push-2">
Dojavi
</div>
<div class="large-2 columns large-pull-8">
<?php
include_once 'lijevo.php';
?>
</div>
<div class="large-2 columns">
<?php
include_once 'desno.php';
?>
</div>
</div>
<?php
include_once 'skripte.php';
?>
</body>
</html>
<file_sep>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Azil aplikacija za predavanje SSA20142015" />
<meta name="keywords" content="azil, udomljavanje, SSA, SSA20142015" />
<meta name="author" content="<NAME>" />
<meta property="og:title" content="Azil aplikacija za predavanje SSA20142015"/>
<meta property="og:type" content="website"/>
<meta property="og:image" content="http://oziz.ffos.hr/SSA20142015/img/slikaDM.png">
<meta property="og:url" content="http://oziz.ffos.hr/SSA20142015/index.php">
<meta property="og:description" content="Polaznici su upoznati s konkretnim primjerom koji joลก nema razraฤeno aplikacijsko rjeลกenje (primjer u sklopu FFOS inkubatora) za koje su prikazane aktivnosti projektiranje baze podataka, implementacija ERA dijagrama, izrada mreลพnih stranica, Responsive Web Design, kreiranje web aplikacije ( PHP + JSON + AJAX + JQUERY + FOUNDATION + HTML + CSS) te postavljanje aplikacije na server. Zbog obima posla nije bilo moguฤe sve nakucati u realnom vremenu, stoga ฤe se koristiti gotovi dijelovi koda kako bi se prikazao princip. Sav koriลกteni kod nalazi se u ovom repozitoriju."/>
<link rel="stylesheet" href="<?php echo $putanjaApp; ?>css/foundation.css" />
<link rel="stylesheet" href="<?php echo $putanjaApp; ?>css/stil.css" />
<script src="<?php echo $putanjaApp; ?>js/vendor/modernizr.js"></script>
<!--== Google Fonts ==-->
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Bree+Serif&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<link rel="shortcut icon" href="<?php echo $putanjaApp; ?>img/favicon.ico" type="image/x-icon" />
<file_sep><div class="row">
<div class="large-2 columns show-for-large-up">
</div>
<div class="large-8 columns">
<div class="row">
<div class="large-3 columns show-for-large-up">
<a href="index.php"><img src="img/konj.jpg"></a>
<!-- <img src="http://lorempixel.com/150/100/animals"> -->
</div>
<div class="large-9 columns">
<h1 class="naslov"><?php echo $naslovAPP; ?></h1>
</div>
</div>
</div>
<div class="large-2 columns">
<a href="#" data-reveal-id="modalAutorizacija" class="button">Login</a>
</div>
</div>
<file_sep><?php
include_once 'modalAutorizacija.php';
?>
<script src="<?php echo $putanjaApp; ?>js/vendor/jquery.js"></script>
<script src="<?php echo $putanjaApp; ?>js/foundation.min.js"></script>
<script src="<?php echo $putanjaApp; ?>js/md5.js"></script>
<script>
$(document).foundation();
$(function() {
$("#autorizacija").click(
function() {
$("#poruka").html("");
if($("#email").val().trim().length==0){
$("#poruka").html("Email obavezno");
return; //Shor Curcuit
}
if($("#lozinka").val().trim().length==0){
$("#poruka").html("Lozinka obavezno");
return; //Shor Curcuit
}
var podaci = {email: $("#email").val(), lozinka: MD5($("#lozinka").val())};
$.ajax({
type : "POST",
url : "autoriziraj.php",
data : "podaci=" + JSON.stringify(podaci),
success : function(msg) {
var odgovor= $.parseJSON(msg);
if (odgovor.status) {
window.location = odgovor.stranica;
}
else {
$("#poruka").html(odgovor.poruka);
}
}
});
return false;
});
});
</script><file_sep><?php include_once '../../konfiguracija.php';
if(!isset($_SESSION[$ida . "autoriziran"])){
header("location: ../../index.php");
}
if(isset($_GET["sifra"])){
$izraz = $veza -> prepare("select * from operater where sifra=:sifra");
$izraz -> execute($_GET);
$operater = $izraz -> fetch(PDO::FETCH_OBJ);
}
if($_POST){
$izraz = $veza -> prepare("delete from operater where sifra=:sifra;");
$izraz -> execute($_POST);
header("location: index.php");
}
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<title><?php echo $naslovAPP ?> Promjena operatera</title>
<?php
include_once '../../head.php';
?>
</head>
<body>
<?php
include_once '../izbornik.php';
?>
<div class="row">
<div class="large-12 columns">
<div class="panel">
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
<fieldset>
<legend>Upisni podaci</legend>
<label for="email">Email</label>
<h1><?php echo $operater->email; ?></h1>
<label for="ime">Ime</label>
<h1><?php echo $operater->ime; ?></h1>
<label for="prezime">Prezime</label>
<h1><?php echo $operater->prezime; ?></h1>
<input type="hidden" name="sifra" value="<?php echo $operater->sifra;?>" />
<div class="row">
<div class="large-6 columns">
<a href="index.php" class="alert button siroko">Odustani</a>
</div>
<div class="large-6 columns">
<input class="success button siroko" type="submit" value="Obriลกi" />
</div>
</div>
</form>
</div>
</div>
</div>
<?php
include_once '../skripte.php';
?>
</body>
</html>
<file_sep><?php
//web
/*
$mysql_host = "localhost";
$mysql_database = "ssa20142015";
$mysql_user = "xxxxxx";
$mysql_password = "<PASSWORD>";
$putanjaApp="/SSA20142015/"; //ako na server ide u root onda je putanjaApp /
*/
//lokalno
$mysql_host = "localhost";
$mysql_database = "ssa20142015";
$mysql_user = "root";
$mysql_password = "<PASSWORD>";
$putanjaApp="/SSA20142015/";
/*
* Identifikacija aplikacije
*/
$ida="SSA20142015_";
/*
* Naslov aplikacije
*/
$naslovAPP="Azil";
//spajanje na bazu
$veza = new PDO("mysql:dbname=" . $mysql_database .
";host=" . $mysql_host .
"",
$mysql_user, $mysql_password);
$veza->exec("SET CHARACTER SET utf8");
$veza->exec("SET NAMES utf8");
//startanje session-a.
session_start();<file_sep>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="<?php echo $putanjaApp; ?>css/foundation.css" />
<link rel="stylesheet" href="<?php echo $putanjaApp; ?>css/stil.css" />
<script src="<?php echo $putanjaApp; ?>js/vendor/modernizr.js"></script>
| 6994564dafd31c8758645780cce7b762024201d5 | [
"Markdown",
"SQL",
"PHP"
] | 24 | SQL | ColdNoney/SSA20142015 | d501f84eaa77221f8aa40ca611bb46bc896325f8 | a5854c7ec4c7fc9224203f3a7a8ab1bc9ba32e86 |
refs/heads/master | <repo_name>dan-mcm/twitch-plays-minesweeper<file_sep>/minesweeper.js
(function () {
document.addEventListener('DOMContentLoaded', function () {
var canvas = document.getElementById('game');
canvas.addEventListener('click', leftClick);
canvas.addEventListener('contextmenu', rightClick);
var ctx = canvas.getContext('2d');
var width = canvas.width;
var height = canvas.height;
var gridSize = 20;
var mineDensity = 0.2;
var axisWidth = 20;
var nw = Math.floor((width - 2 * axisWidth) / gridSize);
var nh = Math.floor((height - 2 * axisWidth) / gridSize);
document.getElementById('size-text').innerText = nw + 'x' + nh;
var cellData = [];
var users = [];
var flags = 0;
var mines = 0;
var explodMines = 0;
var firstDig = true;
// users can mix up the order of X and Y coordinates, we can now figure it out
function parseCoordinates(coordinateA, coordinateB) {
if (coordinateA.charCodeAt(0) <= 57) {
// numbers, letters
return {
x: lettersToNumber(coordinateB),
y: nh - 1 - parseInt(coordinateA, 10)
}
} else {
// letters, numbers
return {
x: lettersToNumber(coordinateA),
y: nh - 1 - parseInt(coordinateB, 10)
}
}
}
var AMOUNT_OF_LETTERS = 26;
function lettersToNumber(letterCoordinate) {
var i, l, code, result;
var amountOfLetters = 1;
var combinationsFor1ToNMinusOneLetters = 0;
var combinationsForNLetter = AMOUNT_OF_LETTERS;
for (i = 1, l = letterCoordinate.length; i < l; ++i) {
++amountOfLetters;
combinationsFor1ToNMinusOneLetters += combinationsForNLetter;
combinationsForNLetter *= AMOUNT_OF_LETTERS;
}
for (i = 0, l = letterCoordinate.length, result = 0; i < l; ++i) {
code = letterCoordinate.charCodeAt(i);
result *= AMOUNT_OF_LETTERS;
if (code >= 97) {
result += (code - 97);
} else {
result += (code - 65);
}
}
return result + combinationsFor1ToNMinusOneLetters;
}
function numberToLetters(number) {
var a, b, i, charCodes;
var amountOfLetters = 1;
var combinationsFor1ToNMinusOneLetters = 0;
var combinationsForNLetter = AMOUNT_OF_LETTERS;
while (combinationsFor1ToNMinusOneLetters + combinationsForNLetter < number + 1) {
++amountOfLetters;
combinationsFor1ToNMinusOneLetters += combinationsForNLetter;
combinationsForNLetter *= AMOUNT_OF_LETTERS;
}
a = 0;
b = number - combinationsFor1ToNMinusOneLetters;
charCodes = [];
for (i = 0; i < amountOfLetters; ++i) {
a = b % AMOUNT_OF_LETTERS;
b = (b - a) / AMOUNT_OF_LETTERS;
charCodes.unshift(a + 65);
}
return String.fromCharCode.apply(String, charCodes);
}
function updateLeaderboard() {
var contents = '';
var leaderBoardNameList = document.getElementById('leaderboard-name-list');
users.sort(function (lhs, rhs) {
if (lhs.score > rhs.score) {
return -1;
}
if (lhs.score < rhs.score) {
return 1;
}
return 0;
});
for (var i = 0, l = Math.min(10, users.length); i < l; ++i) {
var user = users[i];
if (user.score > 0 || user.disqualified) {
// code to have button for revive.... nested function dosen't allow right now...
//contents += '<li style="color:' + users[i].color + ';">' + users[i].displayName + ' (' + users[i].score + (users[i].disqualified ? ', <input id="RIP" type="button" value="rip" onclick="revive(\''+users[i].userName+'\');" />' : '') + ')</li>';
contents += '<li style="color:' + users[i].color + ';">' + users[i].displayName + ' (' + users[i].score + (users[i].disqualified ? ', RIP['+users[i].timeout+']' : '') + ')</li>';
}
}
leaderBoardNameList.innerHTML = contents;
}
function locateUser(userName, createIfNotFound) {
for (var i = 0, l = users.length; i < l; ++i) {
if (users[i].userName === userName) {
return users[i];
}
}
if (createIfNotFound) {
users.push({
userName: userName,
score: 0,
disqualified: false,
timeout: 0,
color: '#000000',
displayName: userName
});
return users[users.length - 1];
} else {
return null;
}
}
function debugRevealAll() {
for (y = 0; y < nh; ++y) {
for (x = 0; x < nw; ++x) {
cellData[y][x].isUncovered = true;
}
}
}
function debugHideAll() {
for (y = 0; y < nh; ++y) {
for (x = 0; x < nw; ++x) {
cellData[y][x].isUncovered = false;
}
}
}
function executeCommand(message, userTypingTheCommand) {
var r = /^!d(?:ig)?\s+(?:(?:([a-zA-Z]+)\s*,?\s*(\d+))|(?:(\d+)\s*,?\s*([a-zA-Z]+)))\s*$/;
var m = message.match(r);
if (m) {
var coordinates = parseCoordinates(m[1] || m[3], m[2] || m[4]);
uncoverTile(coordinates, userTypingTheCommand);
}
r = /^!f(?:lag)?\s+(?:(?:([a-zA-Z]+)\s*,?\s*(\d+))|(?:(\d+)\s*,?\s*([a-zA-Z]+)))\s*$/;
m = message.match(r);
if (m) {
coordinates = parseCoordinates(m[1] || m[3], m[2] || m[4]);
toggleFlag(coordinates, userTypingTheCommand);
}
r = /^!c(?:heck)?\s+(?:(?:([a-zA-Z]+)\s*,?\s*(\d+))|(?:(\d+)\s*,?\s*([a-zA-Z]+)))\s*$/;
m = message.match(r);
if (m) {
coordinates = parseCoordinates(m[1] || m[3], m[2] || m[4]);
checkNumber(coordinates, userTypingTheCommand);
}
r = /^!s(?:tatus)?\s*$/;
m = message.match(r);
if (m) {
showStatus(userTypingTheCommand);
}
if (userTypingTheCommand.userName === BOT_USERNAME || userTypingTheCommand.userName === STREAMER) {
r = /^!reset\s*$/;
m = message.match(r);
if (m) {
initData();
updateLeaderboard();
drawAllTheThings();
}
r = /^!reveal\s*$/;
m = message.match(r);
if (m) {
debugRevealAll();
drawAllTheThings();
}
r = /^!hide\s*$/;
m = message.match(r);
if (m) {
debugHideAll();
drawAllTheThings();
}
r = /^!revive (\S+)\s*$/;
m = message.match(r);
if (m) {
// make sure it is lower case as twitch user names are always lower case (the display name might not be)
revive(m[1].toLowerCase());
}
}
}
function revive(userName){
var toBeRevived = locateUser(userName, false);
if (toBeRevived) {
sentMessageToChat('Reviving ' + toBeRevived.displayName);
toBeRevived.disqualified = false;
toBeRevived.timeout = 0;
updateLeaderboard();
drawAllTheThings();
} else {
sentMessageToChat('User ' + userName + ' not found');
}
}
function disqualify(user, reason){
user.disqualified = true;
user.timeout = AUTO_REVIVE_TIME;
sentMessageToChat(user.displayName + reason);
}
function reviveClock(){
for (var i = 0, l = users.length; i < l; ++i) {
if (users[i].disqualified) {
users[i].timeout--;
if (users[i].timeout <= 0) {
revive(users[i].userName);
}
}
}
updateLeaderboard();
}
function getNeighbours(x, y) {
var neighbours = [];
if (x > 0) {
if (y > 0) {
neighbours.push(cellData[y - 1][x - 1]);
}
neighbours.push(cellData[y][x - 1]);
if (y < nh - 1) {
neighbours.push(cellData[y + 1][x - 1]);
}
}
if (x < nw - 1) {
if (y > 0) {
neighbours.push(cellData[y - 1][x + 1]);
}
neighbours.push(cellData[y][x + 1]);
if (y < nh - 1) {
neighbours.push(cellData[y + 1][x + 1]);
}
}
if (y > 0) {
neighbours.push(cellData[y - 1][x]);
}
if (y < nh - 1) {
neighbours.push(cellData[y + 1][x]);
}
return neighbours;
}
if (CONNECT_TO_CHAT) {
var ws = new WebSocket('wss://irc-ws.chat.twitch.tv:443/', 'irc');
ws.onmessage = function (message) {
if (message !== null) {
var parsed = parseMessage(message.data);
if (parsed !== null) {
if (parsed.command === "PRIVMSG") {
console.log('Got a message ' + JSON.stringify(parsed));
console.log('MSG: ' + parsed.message + ' from ' + parsed.username);
var user = locateUser(parsed.username, true);
var colorRegexMatch = parsed.tags.match(/color=(#[0-9A-Fa-f]{6});/);
if (colorRegexMatch) {
user.color = colorRegexMatch[1];
}
var displayNameRegexMatch = parsed.tags.match(/display-name=([^;]+);/);
if (displayNameRegexMatch) {
user.displayName = displayNameRegexMatch[1];
}
executeCommand(parsed.message, user);
} else if (parsed.command === "PING") {
ws.send("PONG :" + parsed.message);
}
}
}
};
ws.onerror = function (message) {
console.log('Error: ' + message);
};
ws.onclose = function () {
console.log('Disconnected from the chat server.');
};
ws.onopen = function () {
if (ws !== null && ws.readyState === 1) {
console.log('Connecting and authenticating...');
ws.send('CAP REQ :twitch.tv/tags twitch.tv/commands twitch.tv/membership');
ws.send('PASS ' + BOT_OAUTH_TOKEN);
ws.send('NICK ' + BOT_USERNAME);
ws.send('JOIN ' + CHANNEL);
}
};
document.getElementById('offline-command-container').outerHTML = '';
} else {
document.getElementById('offline-command-field').addEventListener('keydown', function (ev) {
if (ev.keyCode === 13) {
// the newline at the end is what we get from twitch chat too so we are better off
// having a realistic imitation here to avoid discovering bugs in regexes later on
executeCommand(ev.target.value + '\r\n', locateUser(STREAMER, true));
}
});
}
function sentMessageToChat(message) {
if (ws) {
ws.send("PRIVMSG " + CHANNEL + " :" + message + '\r\n');
} else {
console.log(message);
}
}
function parseMessage(rawMessage) {
var parsedMessage = {
message: null,
tags: null,
command: null,
original: rawMessage,
channel: null,
username: null
};
if(rawMessage[0] === '@'){
var tagIndex = rawMessage.indexOf(' '),
userIndex = rawMessage.indexOf(' ', tagIndex + 1),
commandIndex = rawMessage.indexOf(' ', userIndex + 1),
channelIndex = rawMessage.indexOf(' ', commandIndex + 1),
messageIndex = rawMessage.indexOf(':', channelIndex + 1);
parsedMessage.tags = rawMessage.slice(0, tagIndex);
parsedMessage.username = rawMessage.slice(tagIndex + 2, rawMessage.indexOf('!'));
parsedMessage.command = rawMessage.slice(userIndex + 1, commandIndex);
parsedMessage.channel = rawMessage.slice(commandIndex + 1, channelIndex);
parsedMessage.message = rawMessage.slice(messageIndex + 1);
} else if(rawMessage.startsWith("PING")) {
parsedMessage.command = "PING";
parsedMessage.message = rawMessage.split(":")[1];
}
return parsedMessage;
}
function initData() {
initBoard(); // make new gameboard
users = []; // clear leaderboard
flags = 0; // new board no flags
explodMines = 0; // new board no exploded mines
updateLeaderboard(); // draw leaderboard area
// fill in game stats
document.getElementById('flags').innerHTML = flags;
document.getElementById('explodMines').innerHTML = explodMines;
document.getElementById('mines').innerHTML = mines - (flags + explodMines);
}
function initBoard(){
var x, y;
cellData = [];
firstDig = true;
mines = 0; // we have 0 mines on the field
for (y = 0; y < nh; ++y) {
var cellDataLine = [];
cellData.push(cellDataLine);
for (x = 0; x < nw; ++x) {
cellDataLine.push({
x: x,
y: y,
isMine: Math.random() < mineDensity,
isExploded: false,
isUncovered: false,
neighbouringMineCount: 0,
isFlagged: false,
coordinates: {x:x, y:y}
});
}
}
for (y = 0; y < nh; ++y) {
for (x = 0; x < nw; ++x) {
var cell = cellData[y][x];
if (!cell.isMine) {
continue;
}
mines++;
var neighbours = getNeighbours(x, y);
for (var i = 0, l = neighbours.length; i < l; ++i) {
++neighbours[i].neighbouringMineCount;
}
}
}
console.log(mines);
}
function clearField() {
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, width, height);
}
function showStatus(userExecutingTheCommand) {
sentMessageToChat('Hello ' + userExecutingTheCommand.displayName + ' you are ' + (userExecutingTheCommand.disqualified ? 'dead for '+userExecutingTheCommand.timeout+' seconds' : 'alive') + ' and have ' + userExecutingTheCommand.score + ' points.');
}
function drawGrid() {
for (var y = 0; y < nh + 1; ++y) {
ctx.strokeStyle = 'black';
ctx.beginPath();
ctx.moveTo(0, gridSize * y);
ctx.lineTo(nw * gridSize, gridSize * y);
ctx.stroke();
ctx.closePath();
}
for (var x = 0; x < nw + 1; ++x) {
ctx.strokeStyle = 'black';
ctx.beginPath();
ctx.moveTo(gridSize * x, 0);
ctx.lineTo(gridSize * x, nh * gridSize);
ctx.stroke();
ctx.closePath();
}
}
function drawMineAt(x, y, isExploded) {
var mineColor = isExploded ? 'red' : 'black';
ctx.strokeStyle = mineColor;
ctx.fillStyle = mineColor;
ctx.beginPath();
ctx.arc((x + 0.5) * gridSize, (y + 0.5) * gridSize, gridSize * 0.25, 0, 2 * Math.PI, false);
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.moveTo(gridSize * (x + 0.1), gridSize * (y + 0.5));
ctx.lineTo(gridSize * (x + 0.9), gridSize * (y + 0.5));
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.moveTo(gridSize * (x + 0.5), gridSize * (y + 0.1));
ctx.lineTo(gridSize * (x + 0.5), gridSize * (y + 0.9));
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.moveTo(gridSize * (x + 0.2), gridSize * (y + 0.2));
ctx.lineTo(gridSize * (x + 0.8), gridSize * (y + 0.8));
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.moveTo(gridSize * (x + 0.8), gridSize * (y + 0.2));
ctx.lineTo(gridSize * (x + 0.2), gridSize * (y + 0.8));
ctx.stroke();
ctx.closePath();
ctx.fillStyle = 'white';
ctx.fillRect(gridSize * (x + 0.5) - 3, gridSize * (y + 0.5) - 3, 2, 2)
}
function drawCoveredCellAt(x, y) {
ctx.fillStyle = 'rgb(128, 128, 128)';
ctx.beginPath();
ctx.moveTo(gridSize * (x + 1), gridSize * y);
ctx.lineTo(gridSize * x + 1, gridSize * (y + 1));
ctx.lineTo(gridSize * (x + 1), gridSize * (y + 1));
ctx.fill();
ctx.closePath();
ctx.fillStyle = 'rgb(240, 240, 240)';
ctx.beginPath();
ctx.moveTo(gridSize * (x + 1), gridSize * y);
ctx.lineTo(gridSize * x, gridSize * (y + 1));
ctx.lineTo(gridSize * x, gridSize * y);
ctx.fill();
ctx.closePath();
ctx.fillStyle = 'rgb(200, 200, 200)';
ctx.fillRect(gridSize * x + 3, gridSize * y + 3, gridSize - 6, gridSize - 6);
}
function drawNeighbourCountAt(x, y, count) {
if (count) {
switch (count) {
case 1:
ctx.fillStyle = 'blue';
break;
case 2:
ctx.fillStyle = 'green';
break;
case 3:
ctx.fillStyle = 'red';
break;
case 4:
ctx.fillStyle = 'rgb(0,0,100)';
break;
case 5:
ctx.fillStyle = 'rgb(100,0,0)';
break;
case 6:
ctx.fillStyle = 'turquoise';
break;
case 7:
ctx.fillStyle = 'purple';
break;
default:
ctx.fillStyle = 'black';
break;
}
ctx.textAlign = 'center';
ctx.font = "16px Arial";
ctx.fillText(count, gridSize * (x + 0.5), gridSize * (y + 0.5));
}
}
function drawFlagAt(x, y) {
ctx.strokeStyle = 'black';
ctx.beginPath();
ctx.moveTo(gridSize * (x + 0.3), gridSize * (y + 0.75));
ctx.lineTo(gridSize * (x + 0.7), gridSize * (y + 0.75));
ctx.moveTo(gridSize * (x + 0.5), gridSize * (y + 0.75));
ctx.lineTo(gridSize * (x + 0.5), gridSize * (y + 0.6));
ctx.stroke();
ctx.closePath();
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.moveTo(gridSize * (x + 0.5), gridSize * (y + 0.6));
ctx.lineTo(gridSize * (x + 0.5), gridSize * (y + 0.2));
ctx.lineTo(gridSize * (x + 0.3), gridSize * (y + 0.4));
ctx.fill();
ctx.closePath();
}
function drawAllTheThings() {
clearField();
drawAxis();
ctx.save();
ctx.transform(1, 0, 0, 1, axisWidth, axisWidth);
drawGrid();
for (var y = 0; y < nh; ++y) {
for (var x = 0; x < nw; ++x) {
var cell = cellData[y][x];
if (!cell.isUncovered) {
drawCoveredCellAt(x, y);
if (cell.isFlagged) {
drawFlagAt(x, y);
}
} else if (cell.isMine) {
drawMineAt(x, y, cell.isExploded);
} else {
drawNeighbourCountAt(x, y, cell.neighbouringMineCount);
}
}
}
ctx.restore();
}
function drawAxis() {
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.font = "11px LM Mono 12";
ctx.strokeStyle = 'black';
ctx.save();
ctx.transform(1, 0, 0, 1, axisWidth, 0);
for (var x = 0; x < nw; ++x) {
ctx.beginPath();
ctx.moveTo(gridSize * (x + 0.5), axisWidth * 0.8);
ctx.lineTo(gridSize * (x + 0.5), axisWidth);
ctx.stroke();
ctx.closePath();
ctx.strokeText(numberToLetters(x), gridSize * (x + 0.5), axisWidth * 0.4);
ctx.beginPath();
ctx.moveTo(gridSize * (x + 0.5), (nh + 1) * gridSize);
ctx.lineTo(gridSize * (x + 0.5), (nh + 1) * gridSize + axisWidth * 0.2);
ctx.stroke();
ctx.closePath();
ctx.strokeText(numberToLetters(x), gridSize * (x + 0.5), (nh + 1) * gridSize + axisWidth * 0.6);
}
ctx.restore();
ctx.save();
ctx.transform(1, 0, 0, 1, 0, axisWidth);
for (var y = 0; y < nh; ++y) {
ctx.beginPath();
ctx.moveTo(axisWidth * 0.8, gridSize * (y + 0.5));
ctx.lineTo(axisWidth, gridSize * (y + 0.5));
ctx.stroke();
ctx.closePath();
ctx.strokeText((nh - 1 - y), axisWidth * 0.4, gridSize * (y + 0.5));
ctx.beginPath();
ctx.moveTo((nw + 1) * gridSize, gridSize * (y + 0.5));
ctx.lineTo((nw + 1) * gridSize + axisWidth * 0.2, gridSize * (y + 0.5));
ctx.stroke();
ctx.closePath();
ctx.strokeText((nh - 1 - y), (nw + 1) * gridSize + axisWidth * 0.6, gridSize * (y + 0.5));
}
ctx.restore();
}
function leftClick(event) {
var mouseX = event.clientX - canvas.offsetLeft - axisWidth;
var mouseY = event.clientY - canvas.offsetTop - axisWidth;
var coordinates = {
x: Math.floor(mouseX / gridSize),
y: Math.floor(mouseY / gridSize)
};
uncoverTile(coordinates, locateUser(STREAMER, true));
}
function mmbClick(event) { // TODO: for some reason cant detect the action of MMB
var mouseX = event.clientX - canvas.offsetLeft - axisWidth;
var mouseY = event.clientY - canvas.offsetTop - axisWidth;
var coordinates = {
x: Math.floor(mouseX / gridSize),
y: Math.floor(mouseY / gridSize)
};
checkNumber(coordinates, locateUser(STREAMER, true));
}
function rightClick(event) {
var mouseX = event.clientX - canvas.offsetLeft - axisWidth;
var mouseY = event.clientY - canvas.offsetTop - axisWidth;
var coordinates = {
x: Math.floor(mouseX / gridSize),
y: Math.floor(mouseY / gridSize)
};
toggleFlag(coordinates, locateUser(STREAMER, true));
}
function uncoverTile(coordinates, user) {
var cell = cellData[coordinates.y][coordinates.x];
if (user.disqualified || cell.isUncovered) {
return;
}
removeFlag(cell.coordinates);
if (cell.isMine) {
if (firstDig) { // if is 1st dig... make new board
initBoard();
uncoverTile(coordinates.x, coordinates.y, user);
return;
}
blowMineUp(cell.coordinates);
disqualify(user,' just hit a mine.');
} else if (cell.neighbouringMineCount === 0) {
cell.isUncovered = true;
var cellCount = expandZeroedArea(coordinates);
user.score += (cellCount + 1);
} else if (!cell.isUncovered) {
cell.isUncovered = true;
user.score += 1;
}
firstDig = false;
updateLeaderboard();
drawAllTheThings();
}
function checkNumber(coordinates, user) {
var otherCell, i, l, hitAMine = false;
var cell = cellData[coordinates.y][coordinates.x];
if (user.disqualified || !cell.isUncovered) {
return;
}
var neighbours = getNeighbours(coordinates.x, coordinates.y);
var count = 0;
for (i = 0, l = neighbours.length; i < l; ++i) {
otherCell = neighbours[i];
if ((otherCell.isMine && otherCell.isUncovered) || otherCell.isFlagged) {
count += 1;
}
}
if (count === cell.neighbouringMineCount) {
for (i = 0, l = neighbours.length; i < l; ++i) {
otherCell = neighbours[i];
if (!otherCell.isUncovered && !otherCell.isFlagged) {
otherCell.isUncovered = true;
if (otherCell.isMine) {
blowMineUp(otherCell.coordinates);
hitAMine = true;
} else if (otherCell.neighbouringMineCount === 0) {
otherCell.isUncovered = true;
removeFlag(otherCell.coordinates);
var cellCount = expandZeroedArea(otherCell.coordinates);
user.score += (cellCount + 1);
} else {
user.score += 1;
}
}
}
if (hitAMine) {
disqualify(user,' just hit a mine. Somebody placed a bad flag.');
// removing all flags, because there are bad flags
for (i = 0, l = neighbours.length; i < l; ++i) {
removeFlag(neighbours[i].coordinates);
}
}
}
updateLeaderboard();
drawAllTheThings();
}
function toggleFlag(coordinates, user) {
var cell = cellData[coordinates.y][coordinates.x];
if (user.disqualified || cell.isUncovered) {
return;
}
if (!cell.isUncovered) {
(cell.isFlagged) ? flags-- : flags++;
document.getElementById('flags').innerHTML = flags;
document.getElementById('mines').innerHTML = mines - (flags + explodMines);
cell.isFlagged = !cell.isFlagged;
drawAllTheThings();
event.preventDefault();
}
}
function removeFlag(coordinates){
var cell = cellData[coordinates.y][coordinates.x];
if (!cell.isUncovered && cell.isFlagged) {
flags--;
document.getElementById('flags').innerHTML = flags;
document.getElementById('mines').innerHTML = mines - (flags + explodMines);
cell.isFlagged = false;
drawAllTheThings();
event.preventDefault();
}
}
function blowMineUp(coordinates){
var cell = cellData[coordinates.y][coordinates.x];
cell.isUncovered = true;
cell.isExploded = true;
explodMines++;
document.getElementById('explodMines').innerHTML = explodMines;
document.getElementById('mines').innerHTML = mines - (flags + explodMines);
}
function isCompleated(){
for (y = 0; y < nh; ++y) {
for (x = 0; x < nw; ++x) {
if (!(cellData[y][x].isUncovered || cellData[y][x].isMine)){
return false;
}
}
}
return true;
}
function expandZeroedArea(coordinates){
var count = 0;
var cell;
var listA = [
cellData[coordinates.y][coordinates.x]
];
var listB;
while (listA.length) {
listB = [];
for (var i = 0, l = listA.length; i < l; ++i) {
cell = listA[i];
var neighbours = getNeighbours(cell.x, cell.y);
for (var j = 0, m = neighbours.length; j < m; ++j) {
cell = neighbours[j];
if (!cell.isUncovered && cell.neighbouringMineCount === 0) {
listB.push(cell);
}
if (!cell.isUncovered) {
++count;
if (cell.isFlagged) removeFlag(cell.coordinates);
cell.isUncovered = true;
}
}
}
listA = listB;
}
return count;
}
initData();
drawAllTheThings();
// init revive clock
setInterval(reviveClock, 1000);
});
})();
| 71688790e6745a69e29ed3831c0e35aedb08a53f | [
"JavaScript"
] | 1 | JavaScript | dan-mcm/twitch-plays-minesweeper | d90fd38b8d48a672fa5f8076879438e8f5898ec3 | b49f76666abb052f0eff36848fcc00f064a6578f |
refs/heads/master | <repo_name>fansin1/Calculator<file_sep>/src/test/kotlin/org/fansin/calculator/CalculatorTest.kt
package org.fansin.calculator
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.doAnswer
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import org.fansin.calculator.operation.Operation
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
class CalculatorTest {
private val plusOperationMock = mock<Operation> {
on { execute(any(), any()) } doAnswer { invocationOnMock ->
invocationOnMock.arguments[0] as Long + invocationOnMock.arguments[1] as Long
}
}
private val calculator = Calculator(
hashMapOf(
"+" to plusOperationMock
)
)
@Test
fun testPlus() {
calculator.nextInput("100")
calculator.nextInput("200")
val res = calculator.nextInput("+")
assertEquals("300", res)
verify(plusOperationMock).execute(100, 200)
}
}<file_sep>/src/main/kotlin/org/fansin/calculator/CalculatorException.kt
package org.fansin.calculator
/**
* Exception from calculator
*/
class CalculatorException(message: String) : Exception(message)<file_sep>/src/main/kotlin/org/fansin/calculator/CalculatorConsole.kt
package org.fansin.calculator
import java.io.BufferedReader
import java.io.Writer
/**
* IO for calculator
*/
class CalculatorConsole(
private val reader: BufferedReader,
private val writer: Writer,
private val calculator: Calculator
) {
/**
* Start reading numbers and operation and writing results
*/
fun start() {
while (true) {
val res = calculator.nextInput(reader.readLine())
if (res != null) {
writer.write(res + "\n")
writer.flush()
}
}
}
}
<file_sep>/src/main/kotlin/org/fansin/calculator/operation/Operation.kt
package org.fansin.calculator.operation
/**
* org.fansin.calculator.Calculator operations like +, -, /, *
*/
interface Operation {
/**
* @return calculate result of operation
*/
fun execute(num1: Long, num2: Long): Long?
}
<file_sep>/src/main/kotlin/org/fansin/calculator/Main.kt
package org.fansin.calculator
import org.fansin.calculator.operation.DivideOperation
import org.fansin.calculator.operation.MinusOperation
import org.fansin.calculator.operation.MultiplyOperation
import org.fansin.calculator.operation.PlusOperation
fun main () {
val operations = hashMapOf(
"+" to PlusOperation(),
"-" to MinusOperation(),
"/" to DivideOperation(),
"*" to MultiplyOperation()
)
CalculatorConsole(
System.`in`.bufferedReader(), System.out.writer(),
Calculator(operations)
).start()
}
<file_sep>/README.md
# Calculator
Calculator (University lab)
How to use:
1) Write first number and press enter
2) Write second number and press enter
3) Write command name and press enter
4) Check result
Supported commands:
+, -, *, /
<file_sep>/src/main/kotlin/org/fansin/calculator/Calculator.kt
package org.fansin.calculator
import org.fansin.calculator.operation.Operation
/**
* Execute commands for 2 numbers
*/
class Calculator(
private val operations: Map<String, Operation>
) {
private var number1 = 0L
private var number2 = 0L
private var currentState = State.Number1
/**
* @param line value to parse
* @return result of operation execution if it was
*/
fun nextInput(line: String): String? {
var res: String? = null
when (currentState) {
State.Number1 -> number1 = parse(line)
State.Number2 -> number2 = parse(line)
State.Operation -> res = execute(line)
}
currentState = currentState.nextState()
return res
}
private fun parse(line: String): Long {
val res = line.toLongOrNull()
if (res == null) {
throw CalculatorException("Wrong number")
} else {
return res
}
}
private fun execute(line: String): String {
val res = operations[line]?.execute(number1, number2)
if (res != null) {
return res.toString()
} else {
throw CalculatorException("Error")
}
}
enum class State(private val nextState: String) {
Number1("Number2"), Number2("Operation"), Operation("Number1");
fun nextState(): State {
return valueOf(nextState)
}
}
}
<file_sep>/src/main/kotlin/org/fansin/calculator/operation/DivideOperation.kt
package org.fansin.calculator.operation
class DivideOperation : Operation {
override fun execute(num1: Long, num2: Long): Long? {
if (num2 == 0L) {
return null
}
return num1 / num2
}
}<file_sep>/src/main/kotlin/org/fansin/calculator/operation/PlusOperation.kt
package org.fansin.calculator.operation
class PlusOperation : Operation {
override fun execute(num1: Long, num2: Long) = num1 + num2
}<file_sep>/src/main/kotlin/org/fansin/calculator/operation/MultiplyOperation.kt
package org.fansin.calculator.operation
class MultiplyOperation : Operation {
override fun execute(num1: Long, num2: Long) = num1 * num2
}
| 34c7a9214632bf4ccaf3b44b6143103d590c63bc | [
"Markdown",
"Kotlin"
] | 10 | Kotlin | fansin1/Calculator | bd08e69a56a03d05fbe00d1aac26fb1ba148db15 | 671f8109c4e00ee83aa8c6a55156ffd910519efb |
refs/heads/main | <repo_name>kboston91/weather-app<file_sep>/assets/js/script.js
// var forecastDiv = document.querySelector(".five-day");
var cityHistory = JSON.parse(localStorage.getItem("city")) || [];
var citiesEl = document.querySelector("#history");
var currentDiv = document.querySelector("#current-weather")
// get history div
$("#search-button").on("click", function () {
var searchValue = $("#city-search").val();
console.log(searchValue);
if (!cityHistory.includes(searchValue)){
cityHistory.push(searchValue);
localStorage.setItem("city", JSON.stringify(cityHistory));
};
$("#current-weather").html("");
$("#five-day").html("");
fetch(
`https://api.openweathermap.org/geo/1.0/direct?q=${searchValue}&limit=5&appid=ab19f30213045455e1ed3db1fcc7e2c1`
)
.then(function (response) {
return response.json();
})
.then(function (data) {
console.log(data);
fetchWeather(data[0]);
});
renderHistory(searchValue);
});
// var loadCityHistory = function () {
// citiesEl.innerHTML = "";
// for (let i = 0; i < cityHistory.length; i++) {
// var historyItem = document.createElement("a");
// // <input type="text" readonly class="form-control-plaintext" id="staticEmail" value="<EMAIL>"></input>
// historyItem.setAttribute("class", );
// historyItem.setAttribute("id", "past-city");
// historyItem.innerText = cityHistory[i];
// var recent = cityHistory[i];
// console.log(recent);
// citiesEl.append(historyItem);
// }
// };
function renderHistory() {
// Retrieve the last email and password from localStorage using `getItem()`
// citiesEl.innerHTML = "";
// // If they are null, return early from this function
// if (cityHistory.length > 0) {
// // either loop through array
// for(let i=0; i<cityHistory.length; i++) {
// return cityHistory[i]
// }
// // or display array as it
// // modify text content of div to show caityHistory
// var citiesEl = document.querySelector("#history");
citiesEl.innerHTML = "";
for (let i = 0; i < cityHistory.length; i++) {
var historyItem = document.createElement("div");
historyItem.setAttribute("class", "col my-1 bg-light text-secondary text-capitalize p-0 rounded text-center border");
historyItem.setAttribute("id", "past-city");
var historyContent = document.createElement("p");
historyContent.setAttribute("class", "justify-content-center");
historyItem.innerText = cityHistory[i];
historyContent.append(historyItem);
citiesEl.append(historyContent);
};
// Set the text of the 'userEmailSpan' and 'userPasswordSpan' to the corresponding values from localStorage
// history.textContent = city;
};
console.log(cityHistory);
// renderHistory();
let currentFunction = function(forecastData) {
var cityName = $("#city-search").val();
colDiv2 = $(`<div id="colDiv2">`).addClass("col my-1 p-1");
console.log(forecastData);
let cardDiv2 = $(`<div id="cardDiv2">`)
.addClass("card border col")
.css({ height: "275px" });
let cardBody2 = $(`<div id="cardBody2">`).addClass("card-body justify-content-center py-2");
let cardTitle2 = $(`<div id="cardTitle2">`).addClass("card-title text-capitalize h3");
// let cardImage = $(`div id="cardImage">`).addClass("card-image");
var d = new Date(forecastData.dt * 1000); // The 0 there is the key, which sets the date to the epoch
// let dateTime = d.setUTCSeconds(forecastData[i].dt);
console.log(d);
// cardTitle2.text((d.getMonth()+1) + "/" + d.getDate() + "/" + d.getFullYear());
cardTitle2.text( `${cityName} ` + (d.getMonth()+1) + "/" + d.getDate() + "/" + d.getFullYear());
let cardTemp2 = $(`<div id="cardTemp2">`).addClass("card-temp text-bold");
cardTemp2.text("Temp: " + forecastData.temp + "ยฐF");
let cardIcon2 = $(`<div id="cardIcon2">`).addClass("card-icon");
cardIcon2.val(forecastData.weather[0].icon);
var iconCode = forecastData.weather[0].icon;
var iconUrl = "http://openweathermap.org/img/w/" + iconCode + ".png";
console.log('iconurl', iconUrl);
let iconImg = $(`<img id="icon" src="${iconUrl}" alt="weather icon">`);
// $(`#icon-${i}`).attr('src', iconUrl);
console.log(iconImg);
// document.querySelector('#icon'+i).setAttribute('src', iconUrl);
let cardWind2 = $(`<div id="cardWind2">`).addClass("card-wind");
cardWind2.text("Wind: " + forecastData.wind_speed);
let cardHumidity2 = $(`<div id="cardHumidity2">`).addClass("card-humidity");
cardHumidity2.text("Humidity: " + forecastData.humidity);
let cardUV2 = $(`<div id="cardUV2">`).addClass("");
cardUV2.text("UV Index: " + forecastData.uvi);
if(forecastData.uvi <= 2){
cardUV2.addClass('bg-success col-2');
}else if(forecastData.uvi > 2 && forecastData.uvi < 6){
cardUV2.addClass('bg-warning col-2');
}else if(forecastData.uvi >= 6 && forecastData.uvi < 8){
cardUV2.addClass('bg-warning col-2');
}else if(forecastData.uvi >= 8){
cardUV2.addClass('bg-dark text-danger col-2');
};
// let eventImageEl = $(`<img id="eventImg-5">`).addClass('card-img');
// eventImageEl.attr('src', eventImgUrl);
cardBody2.append(cardTitle2);
cardIcon2.append(iconImg);
cardBody2.append(cardIcon2);
cardBody2.append(cardTemp2);
cardBody2.append(cardWind2);
cardBody2.append(cardHumidity2);
cardBody2.append(cardUV2);
cardDiv2.append(cardBody2);
colDiv2.append(cardDiv2);
$("#current-weather").append(colDiv2);
};
let forecastFunction = function (forecastData) {
for (let i = 0; i < 5; i++) {
let colDiv = $(`<div id="colDiv">`).addClass("col my-1 p-1");
let cardDiv = $(`<div id="cardDiv">`)
.addClass("card border col bg-secondary")
.css({ height: "200px" });
let cardBody = $(`<div id="cardBody">`).addClass("card-body justify-content-center py-2");
let cardTitle = $(`<div id="cardTitle">`).addClass("card-title");
// let cardImage = $(`div id="cardImage">`).addClass("card-image");
var d = new Date(forecastData[i].dt * 1000); // The 0 there is the key, which sets the date to the epoch
// let dateTime = d.setUTCSeconds(forecastData[i].dt);
console.log(d);
cardTitle.text((d.getMonth()+1) + "/" + d.getDate() + "/" + d.getFullYear());
let cardTemp = $(`<div id="cardTemp">`).addClass("card-temp");
cardTemp.text("Temp:" + forecastData[i].temp.max + "ยฐF");
let cardIcon = $(`<div id="cardIcon">`).addClass("card-icon");
cardIcon.val(forecastData[i].weather[0].icon);
var iconCode = forecastData[i].weather[0].icon;
var iconUrl = "http://openweathermap.org/img/w/" + iconCode + ".png";
console.log('iconurl', iconUrl);
let iconImg = $(`<img id="icon-${i}" src="${iconUrl}" alt="weather icon">`);
// $(`#icon-${i}`).attr('src', iconUrl);
console.log(iconImg);
// document.querySelector('#icon'+i).setAttribute('src', iconUrl);
let cardWind = $(`<div id="cardWind">`).addClass("card-wind");
cardWind.text("Wind:" + forecastData[i].wind_speed);
let cardHumidity = $(`<div id="cardHumidity">`).addClass("card-humidity");
cardHumidity.text("Humidity:" + forecastData[i].humidity);
let cardUV = $(`<div id="cardUV">`).addClass("card-uv");
cardUV.text("UV Index:" + forecastData[i].uvi);
// let eventImageEl = $(`<img id="eventImg-5">`).addClass('card-img');
// eventImageEl.attr('src', eventImgUrl);
cardBody.append(cardTitle);
cardIcon.append(iconImg);
cardBody.append(cardIcon);
cardBody.append(cardTemp);
cardBody.append(cardWind);
cardBody.append(cardHumidity);
cardBody.append(cardUV);
cardDiv.append(cardBody);
colDiv.append(cardDiv);
$("#five-day").append(colDiv);
}
};
//main card container
var fetchWeather = function (location) {
var { lat, lon } = location;
var city = location.name;
console.log(arguments);
fetch(
`https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&units=imperial&exclude=minutely,hourly&appid=ab19f30213045455e1ed3db1fcc7e2c1`
)
.then(function (response) {
return response.json();
})
.then(function (data) {
console.log("weather", data);
forecastFunction(data.daily);
currentFunction(data.current);
//after this we render the current weather and forecast.
});
};
// create renderweather function
// let renderWeather = function (currentData) {
// console.log(currentData);
// }
// renderweather();
// inside the ;function, create a card that displays the city, current date, and weather icon
// display the temp wind humidity and uv index with dynamic color changing based on uv index
//create renderforecast function
//inside the function, create forloop to dynamically create bootstrap cards
// each card needs these elements in this order
//first div is bootstrap column
// second div is card
//third div is card-body
// inside card-body h5 tag to display the date
//image tag to display icon
//p tags display temp, wind, and humidity
// appendchild to html
<file_sep>/README.md
# weather-app

## Description
In this project I fetch data from the openweather API to display the temperature, wind speed, uvi, humidity, and weather icon associated with the city searched. I am given the current weather for the city, as welll as a 5 day forecast. Any city I search is stored in localstorage and displayed on the screen.
## Table of Contents
If your README is very long, add a table of contents to make it easy for users to find what they need.
* [Installation](#installation)
* [Usage](#usage)
* [License](#license)
* [Contributing](#contributing)
* [Test](#test)
* [Questions](#questions)
## Installation
[https://kboston91.github.io/weather-app/](https://kboston91.github.io/weather-app/)
## Usage
Anyone may use this app to display the weather.
## License
MIT
[MIT License](https://opensource.org/licenses/MIT)
## Contributing
Made by <NAME>
## Test
Click the link to the website, enter a city, press search.
## Questions
[GitHub](https://github.com/kboston91)
If you have any questions, please reach out to me at this email address: <<EMAIL>>
| 8f84665d48d8ae64bbeaae173485d0061aa7c1c5 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | kboston91/weather-app | 6ec6f4062d375cfcc87dea8bf9e368ff077fbee5 | c1b7ce10ee70afdf0db8a7bf9c5c2099cceb1669 |
refs/heads/master | <file_sep># JavaFeatures
project to play with java
<file_sep>package main.java.org.banjalive.JavaFeatures;
import com.google.common.base.Stopwatch;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
/**
* Created by a.lebedjko on 2017.01.04..
*/
public class JavaFeatures {
private static final Logger log = LoggerFactory.getLogger(JavaFeatures.class);
public final String constant = "const";
public static void main(String[] args) {
testNewVsValueOf_New();
testNewVsValueOf_ValueOf();
System.out.println();
concatWithPlus();
concatWithAppend();
concatWithAppendStringBuffer();
System.out.println();
numberTypeConversionCastByPlus();
numberTypeConversionCastByValueOf();
charToIntGetNumericalValue();
charToIntGetDigit();
stringToByteConstructor();
stringToByteValueOf();
stringToByteParseByte();
stringToBytesGetBytes();
stringPadZeroesFromLeftWithPlus();
stringPadZeroesFromLeftWithStringBuilder();
stringPadZeroesFromLeftWithStringUtils();
integerPadZeroesFromLeft(1, 7);
// System.out.println(convertCustomerBirthDateToDateComparisonFormatUAT("01101981").getConvertedDates());
// System.out.println(convertCustomerBirthDateToDateComparisonFormatUAT("431210").getConvertedDates());
// System.out.println(convertCustomerBirthDateToDateComparisonFormatUAT("19741007").getConvertedDates());
// System.out.println(convertCustomerBirthDateToDateComparisonFormatUAT("603786294").getConvertedDates());
// System.out.println(convertCustomerBirthDateToDateComparisonFormatUAT("9208920877").getConvertedDates());
// System.out.println(convertCustomerBirthDateToDateComparisonFormatUAT("19741007").getConvertedDates());
//
// System.out.println(convertCustomerIdToDateComparisonFormat("19780725129").getConvertedDates());
// System.out.println(convertCustomerIdToDateComparisonFormat("207807251298").getConvertedDates());
//
//
// System.out.println(isCompareNotApplicableOrCustomerIdMatchesBirthDate("", ""));
// System.out.println(isCompareNotApplicableOrCustomerIdMatchesBirthDate("197507034770", "03071975"));
// System.out.println(isCompareNotApplicableOrCustomerIdMatchesBirthDate("197410077841", "741007"));
// System.out.println(isCompareNotApplicableOrCustomerIdMatchesBirthDate("196904290100", "29.04.1969"));
// System.out.println(isCompareNotApplicableOrCustomerIdMatchesBirthDate("", "29.04.1969"));
// System.out.println(isCompareNotApplicableOrCustomerIdMatchesBirthDate("196905290100", "29.04.1969"));
// System.out.println(isCompareNotApplicableOrCustomerIdMatchesBirthDate("197207118295", "11071972"));
// System.out.println(convertCustomerIdToDateComparisonFormat("7807251298").getConvertedDates());
// System.out.println(convertCustomerBirthDateToDateComparisonFormatUAT("20170212").getConvertedDates());
System.out.println(testArithmetical());
System.out.println(testBitwise());
System.out.println(org.apache.commons.lang3.StringUtils.trim("Aรๆฑ\uD801\uDC00001"));
System.out.println(compareVectors1());
System.out.println(compareVectors2());
}
public static boolean compareVectors1() {
Vector<Integer> integerVector = new Vector<Integer>();
Vector<String> stringVectorector = new Vector<String>();
return integerVector.getClass() == stringVectorector.getClass();
}
public static boolean compareVectors2() {
Vector<Integer> integerVector = new Vector<Integer>();
Vector<String> stringVectorector = new Vector<String>();
return integerVector.getClass().equals(stringVectorector.getClass());
}
public static int testBitwise() {
Stopwatch timer = Stopwatch.createStarted();
int x = 10950;
x += (x << 5) + 1;
timer.stop();
System.out.println("testBitwise() -> That took " + timer.toString());
return x;
}
public static int testArithmetical() {
Stopwatch timer = Stopwatch.createStarted();
int x = 10950;
x = x * 5 + 1;
timer.stop();
System.out.println("testArithmetical() -> That took " + timer.toString());
return x;
}
public static void testNewVsValueOf_New() {
Stopwatch timer = Stopwatch.createStarted();
Integer i = new Integer(100);
Long l = new Long(100);
String s = new String("A");
System.out.println("testNewVsValueOf_New() -> That took " + timer.stop());
}
public static void testNewVsValueOf_ValueOf() {
Stopwatch timer = Stopwatch.createStarted();
Integer i = Integer.valueOf(100);
Long l = 100L;//ััะพ ัะพะถะต ัะฐะผะพะต ััะพ Long.valueOf(100L);
String s = "A";
timer.stop();
System.out.println("testNewVsValueOf_ValueOf() -> That took " + timer.toString());
}
public static void stringPadZeroesFromLeftWithPlus() {
Stopwatch timer = Stopwatch.createStarted();
String s = "1";
while (s.length() < 7) {
s = "0" + s;
}
timer.stop();
System.out.println("stringPadZeroesFromLeftWithPlus -> That took " + timer.toString());
}
public static void stringPadZeroesFromLeftWithStringBuilder() {
Stopwatch timer = Stopwatch.createStarted();
StringBuilder s = new StringBuilder("1");
while (s.length() < 7) {
s.insert(0, "0");
}
timer.stop();
System.out.println("stringPadZeroesFromLeftWithStringBuilder -> That took " + timer.toString());
}
public static void stringPadZeroesFromLeftWithStringUtils() {
Stopwatch timer = Stopwatch.createStarted();
String s = "1";
StringUtils.leftPad(s, 7, "0");
timer.stop();
System.out.println("stringPadZeroesFromLeftWithStringUtils -> That took " + timer.toString());
}
public static String integerPadZeroesFromLeft(int in, int fill) {
Stopwatch timer = Stopwatch.createStarted();
boolean negative = false;
int value, len = 0;
if (in >= 0) {
value = in;
} else {
negative = true;
value = -in;
in = -in;
len++;
}
if (value == 0) {
len = 1;
} else {
for (; value != 0; len++) {
value /= 10;
}
}
StringBuilder sb = new StringBuilder();
if (negative) {
sb.append('-');
}
for (int i = fill; i > len; i--) {
sb.append('0');
}
sb.append(in);
timer.stop();
System.out.println("integerPadZeroesFromLeft -> That took " + timer.toString());
return sb.toString();
}
public static String concatWithPlus() {
//ะผะตะดะปะตะฝะฝะพ
String[] fields = new String[]{"a", "b", "c", "e", "f", "g", "h", "i", "j"};
Stopwatch timer = Stopwatch.createStarted();
String s = "";
for (int i = 0; i < fields.length; i++) {
s = s + fields[i];
}
timer.stop();
System.out.println("concatWithPlus -> That took " + timer.toString());
return s;
}
@NotNull
public static String concatWithAppend() {
//ะฑััััะพ
String[] fields = new String[]{"a", "b", "c", "e", "f", "g", "h", "i", "j"};
Stopwatch timer = Stopwatch.createStarted();
StringBuilder s = new StringBuilder();
for (int i = 0; i < fields.length; i++) {
s.append(fields[i]);
}
timer.stop();
System.out.println("concatWithAppend -> That took " + timer.toString());
return s.toString();
}
public static String concatWithAppendStringBuffer() {
//ะฑััััะพ
String[] fields = new String[]{"a", "b", "c", "e", "f", "g", "h", "i", "j"};
Stopwatch timer = Stopwatch.createStarted();
StringBuffer s = new StringBuffer();
for (int i = 0; i < fields.length; i++) {
s.append(fields[i]);
}
timer.stop();
System.out.println("concatWithAppendStringBuffer -> That took " + timer.toString());
return s.toString();
}
public static void numberTypeConversionCastByPlus() {
Stopwatch timer = Stopwatch.createStarted();
int a = 12;
String s = a + "";
timer.stop();
System.out.println("numberTypeConversionCastByPlus -> That took " + timer.toString());
}
public static void numberTypeConversionCastByValueOf() {
Stopwatch timer = Stopwatch.createStarted();
int a = 12;
String s = String.valueOf(a);
timer.stop();
System.out.println("numberTypeConversionCastByValueOf -> That took " + timer.toString());
}
public static void charToIntGetNumericalValue() {
Stopwatch timer = Stopwatch.createStarted();
char ch = '9';
// c ะธัะฟะพะปัะทะพะฒะฐะฝะธะตะผ ะผะตัะพะดะฐ getNumericValue
// ะบะปะฐััะฐ Character
int i1 = Character.getNumericValue(ch);
timer.stop();
System.out.println("charToIntGetNumericalValue -> That took " + timer.toString());
}
public static void charToIntGetDigit() {
Stopwatch timer = Stopwatch.createStarted();
char ch = '9';
// c ะธัะฟะพะปัะทะพะฒะฐะฝะธะตะผ ะผะตัะพะดะฐ digit ะบะปะฐััะฐ Character
int i2 = Character.digit(ch, 10);
timer.stop();
System.out.println("charToIntGetDigit -> That took " + timer.toString());
}
public static byte stringToByteConstructor() {
Stopwatch timer = Stopwatch.createStarted();
byte b1 = 0;
try {
b1 = new Byte("10");
} catch (NumberFormatException e) {
System.err.println("ะะตะฒะตัะฝัะน ัะพัะผะฐั ัััะพะบะธ!");
}
timer.stop();
System.out.println("stringToByteConstructor -> That took " + timer.toString());
return b1;
}
public static byte stringToByteValueOf() {
Stopwatch timer = Stopwatch.createStarted();
Byte b2 = 0;
String str1 = "111";
try {
b2 = Byte.valueOf(str1);
} catch (NumberFormatException e) {
System.err.println("ะะตะฒะตัะฝัะน ัะพัะผะฐั ัััะพะบะธ!");
}
timer.stop();
System.out.println("stringToByteValueOf -> That took " + timer.toString());
return b2;
}
public static byte stringToByteParseByte() {
Stopwatch timer = Stopwatch.createStarted();
byte b = 0;
String str2 = "100";
try {
b = Byte.parseByte(str2);
} catch (NumberFormatException e) {
System.err.println("ะะตะฒะตัะฝัะน ัะพัะผะฐั ัััะพะบะธ, ัะฑะปัะดะพะบ!");
}
timer.stop();
System.out.println("stringToByteParseByte -> That took " + timer.toString());
return b;
}
public static byte stringToBytesGetBytes() {
Stopwatch timer = Stopwatch.createStarted();
byte b = 0;
String str2 = "100";
try {
b = str2.getBytes()[1];
} catch (NumberFormatException e) {
System.err.println("ะะตะฒะตัะฝัะน ัะพัะผะฐั ัััะพะบะธ!");
}
timer.stop();
System.out.println("stringToBytesGetBytes -> That took " + timer.toString().trim());
return b;
}
public static DateConversionResult convertCustomerBirthDateToDateComparisonFormatUAT(String customerBirthDate) {
Stopwatch timer = Stopwatch.createStarted();
DateConversionResult dateConversionResult = new DateConversionResult();
if (StringUtils.isEmpty(customerBirthDate)) {
return dateConversionResult;
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("ddMMyy");
// check for format dMMyyXXXX
if (customerBirthDate.length() == 9) {
customerBirthDate = customerBirthDate.substring(0, 5);
}
try {
Date newDate;
if (NumberUtils.isDigits(customerBirthDate)) {
newDate = DateUtils.parseDateStrictly(customerBirthDate, "ddMMyyyy", "ddMMyy", "yyMMdd", "yyyyMMdd",
"dMMyy");
} else {
newDate = DateUtils.parseDateStrictly(customerBirthDate, "dd.MM.yyyy");
}
dateConversionResult.setConvertedDate(simpleDateFormat.format(newDate));
dateConversionResult.setConverted(true);
} catch (ParseException e) {
log.error("Unable to convert date string \"" + customerBirthDate + "\"");
}
System.out.println("convertCustomerBirthDateToDateComparisonFormatUAT -> That took " + timer.toString());
return dateConversionResult;
}
private static DateConversionResult convertCustomerIdToDateComparisonFormat(String customerId) {
Stopwatch timer = Stopwatch.createStarted();
DateConversionResult dateConversionResult = new DateConversionResult();
if (StringUtils.isEmpty(customerId) || !NumberUtils.isDigits(customerId)) {
return dateConversionResult;
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyMMdd");
String dateString;
// try to convert only if customer id length is not less than 8
// characters
if (!(customerId.length() < 8)) {
if (!(customerId.length() < 12) && customerId.startsWith("19") || customerId.startsWith("20")) {
dateString = customerId.substring(2, 8);
} else {
dateString = customerId.substring(0, 6);
}
try {
// Date newDate = simpleDateFormat.parse(dateString);
Date newDate = DateUtils.parseDateStrictly(dateString, "yyMMdd");
dateConversionResult.setConvertedDate(simpleDateFormat.format(newDate));
dateConversionResult.setConverted(true);
} catch (ParseException e) {
log.error("Unable to convert date string \"" + dateString + "\"");
}
}
System.out.println("convertCustomerIdToDateComparisonFormat -> That took " + timer.toString());
return dateConversionResult;
}
private static boolean isCompareNotApplicableOrCustomerIdMatchesBirthDate(String customerId, String customerBirthDate) {
Stopwatch timer = Stopwatch.createStarted();
DateConversionResult birthDateConversionResult = !StringUtils.isEmpty(customerBirthDate)
? convertCustomerBirthDateToDateComparisonFormatUAT(customerBirthDate) : null;
DateConversionResult customerIdConversionResult = !StringUtils.isEmpty(customerId)
? convertCustomerIdToDateComparisonFormat(customerId) : null;
if (birthDateConversionResult != null && customerIdConversionResult != null
&& birthDateConversionResult.isConverted() && customerIdConversionResult.isConverted()) {
System.out.println("isCompareNotApplicableOrCustomerIdMatchesBirthDate -> That took " + timer.toString());
return birthDateConversionResult.getConvertedDate().equals(customerIdConversionResult.getConvertedDate());
} else {
System.out.println("isCompareNotApplicableOrCustomerIdMatchesBirthDate -> That took " + timer.toString());
return true;
}
}
// public static DateConversionResult convertCustomerBirthDateToDateComparisonFormat(Customer customer,
// HistoryLog historyLog) {
// DateConversionResult dateConversionResult = new DateConversionResult();
// String customerBirthDate = customer.getCustomerId();
// if (StringUtils.isEmpty(customerBirthDate)) {
// return dateConversionResult;
// }
//
// try {
// Date newDate;
// // setup minYear and maxYear
// SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
// Calendar cal = Calendar.getInstance();
// int minYear = Integer.parseInt(yearFormat.format(cal.getTime())) - 150;
// int maxYear = Integer.parseInt(yearFormat.format(cal.getTime()));
//
// // check for format dMMyyXXXX
// if (customerBirthDate.length() == 9) {
// customerBirthDate = customerBirthDate.substring(0, 5);
// newDate = DateUtils.parseDateStrictly(customerBirthDate, "dMMyy");
//
// // check if input date format is numeric
// } else if (NumberUtils.isDigits(customerBirthDate)) {
// // when numeric and length between 6 and 7 characters try
// // formats "yyMMdd" and "ddMMyy"
// if (!(customerBirthDate.length() < 6) && customerBirthDate.length() < 8) {
//
// int yyDigits = Integer.parseInt(customerBirthDate.substring(0, 2));
// int ddDigits = Integer.parseInt(customerBirthDate.substring(4, 6));
//
// if (!(yyDigits < 31 && ddDigits < 31)) {
// if (yyDigits > 31 && ddDigits < 31) {
// newDate = DateUtils.parseDateStrictly(customerBirthDate, "yyMMdd");
// } else {
// newDate = DateUtils.parseDateStrictly(customerBirthDate, "ddMMyy");
// }
//
// } else {
// historyLog.logError(
// "Unable to convert date string \"" + customerBirthDate
// + "\", since it can be represented in two conflicting formats \"yyMMdd\" and \"ddMMyy\" simultaneosly",
// customer.getCustomerNo());
// return dateConversionResult;
// }
// // if not less than 8
// } else if (!(customerBirthDate.length() < 8)) {
// int yyyyDigits = Integer.parseInt(customerBirthDate.substring(0, 4));
// int mmDigits = Integer.parseInt(customerBirthDate.substring(4, 6));
// int ddDigits = Integer.parseInt(customerBirthDate.substring(6, 8));
//
// if (yyyyDigits > minYear && yyyyDigits < maxYear && mmDigits < 13 && ddDigits < 32) {
// newDate = DateUtils.parseDateStrictly(customerBirthDate, "yyyyMMdd");
// } else {
// newDate = DateUtils.parseDateStrictly(customerBirthDate, "ddMMyyyy");
// }
// } else {
// newDate = DateUtils.parseDateStrictly(customerBirthDate, "dMMyy");
// }
//
// } else {
// newDate = DateUtils.parseDateStrictly(customerBirthDate, "dd.MM.yyyy");
// }
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyMMdd");
// dateConversionResult.setConvertedDate(simpleDateFormat.format(newDate));
// dateConversionResult.setConverted(true);
// } catch (ParseException e) {
// historyLog.logError("Unable to convert date string \"" + customerBirthDate + "\"",
// customer.getCustomerNo());
// }
//
// return dateConversionResult;
// }
}
<file_sep>package main.java.org.banjalive.JavaFeatures;
import java.util.*;
/**
* Created by a.lebedjko on 2017.03.15..
*/
interface AdvancedArithmetic{
int divisor_sum(int n);
}
class MyCalculator implements AdvancedArithmetic{
public int divisor_sum(int n){
// Final result of summation of divisors
int result = 0;
// find all divisors which divides 'num'
for (int i=2; i<=java.lang.Math.sqrt(n); i++)
{
// if 'i' is divisor of 'num'
if (n%i==0)
{
// if both divisors are same then add
// it only once else add both
if (i==(n/i))
result += i;
else
result += (i + n/i);
}
}
// Add 1 to the result as 1 is also a divisor and number itself
result = (n == 1) ? result + n : result + n + 1;
return (result + 1 + n);
}
}
class Solution{
public static void main(String []args){
MyCalculator my_calculator = new MyCalculator();
System.out.print("I implemented: ");
ImplementedInterfaceNames(my_calculator);
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.print(my_calculator.divisor_sum(n) + "\n");
sc.close();
}
/*
* ImplementedInterfaceNames method takes an object and prints the name of the interfaces it implemented
*/
static void ImplementedInterfaceNames(Object o){
Class[] theInterfaces = o.getClass().getInterfaces();
for (int i = 0; i < theInterfaces.length; i++){
String interfaceName = theInterfaces[i].getName();
System.out.println(interfaceName);
}
}
}
| 2be86bdf75a4326ddb9565fc5874fc3f7fc1c71a | [
"Markdown",
"Java"
] | 3 | Markdown | ALebedjko/JavaFeatures | 5cb5e77f78205f61ff6a5f6f61eddb3e094064c7 | 4ce3c09c0947c154f7ad141e7c4b354939938027 |
refs/heads/master | <file_sep># Telegraph Clone
App to anonymously record your stories, notes and articles. Just click [Telegraph clone](https://telegraph-story.herokuapp.com/)
The ability to edit a post within 24 hours.
# What's inside
The application is deployed on [heroku](https://heroku.com) using Flask framework.
# Run locally
Use Venv or virtualenv for insulation project. Virtualenv example:
```
$ python virtualevn myenv
$ source myenv/bin/activate
```
Install requirements:
```
pip install -r requirements.txt
```
Run gunicorn:
At the root of the project
```
gunicorn server:app
```
and simple [click](http://localhost:8000)
# Project Goals
The code is written for educational purposes. Training course for web-developers - [DEVMAN.org](https://devman.org)
<file_sep>import os
BASEDIR = os.path.abspath(os.path.dirname(__file__))
DB_DIR = os.path.abspath(os.path.join(BASEDIR, 'test.db'))
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + DB_DIR
SQLALCHEMY_TRACK_MODIFICATIONS = False<file_sep>from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Story(db.Model):
id_story = db.Column(db.Integer, primary_key=True)
author_id = db.Column(db.String(64), index=True)
slug = db.Column(db.String(32))
story_title = db.Column(db.String(128))
story_signature = db.Column(db.String(64))
story_body = db.Column(db.Text)
def __repr__(self):
return '<Story {}>'.format(self.story_title)<file_sep>import os
from flask import Flask
from .models import db
app = Flask(__name__)
app.config.from_object('config')
db.app = app
db.init_app(app)
if not os.path.exists('test.db'):
db.create_all()
from . import views<file_sep>from flask import render_template, request, redirect, url_for, make_response, abort
import uuid
from re import sub
from project import app, db
from .models import Story
HOURS_LIVE_COOKIES = 24
MAX_AGE_LIVE_COOKIES = HOURS_LIVE_COOKIES * 60 * 60
BAD_REQUEST = 404
FORBIDDEN = 403
def get_slug(title, uuid ):
slug = sub('[\s/]', '_', title)
slug = slug + '_' + uuid[:7]
return slug
def update_text(edit_text):
stories = db.session.query(Story)
text_update = stories.filter_by(slug=edit_text['slug'])
text_update.update(edit_text)
db.session.commit()
@app.route('/', methods=['GET', 'POST'])
def add_story():
if request.method == 'POST':
author_id = request.cookies.get('cookie')
if not author_id:
author_id = str(uuid.uuid4())
slug_uuid = str(uuid.uuid4())
story_title = request.form.get('header')
story_signature = request.form.get('signature')
story_body = request.form.get('body')
slug = get_slug(story_title, slug_uuid)
db.session.add(Story(author_id=author_id,
slug=slug,
story_title=story_title,
story_signature=story_signature,
story_body=story_body))
db.session.commit()
new_story = make_response(redirect(url_for('view_text',
slug=slug)))
new_story.set_cookie('author_id', author_id,
max_age=MAX_AGE_LIVE_COOKIES)
return new_story
else:
return render_template('form.html')
@app.route('/<slug>')
def view_text(slug):
author_id = request.cookies.get('author_id')
story = db.session.query(Story).filter(Story.slug == slug).first_or_404()
return render_template('story.html',story=story, author_id=author_id)
@app.route('/edit/<slug>', methods=['GET', 'POST'])
def edit_text(slug):
author_id = request.cookies.get('author_id')
story = db.session.query(Story).filter(Story.slug == slug).first()
if author_id != story.author_id:
abort(FORBIDDEN)
if request.method == 'POST':
story_title = request.form.get('header')
story_signature = request.form.get('signature')
story_body = request.form.get('body')
edit_text = {'story_title':story_title,
'story_signature':story_signature,
'story_body':story_body,
'slug':slug}
update_text(edit_text)
return render_template('form.html', story=story)
@app.errorhandler(BAD_REQUEST)
def page_not_found(e):
return render_template('404.html'), BAD_REQUEST
@app.errorhandler(FORBIDDEN)
def page_not_found(e):
return render_template('403.html'), FORBIDDEN | 0eb6fa51cf7506d81dfabd6e2a3f6482048163d2 | [
"Markdown",
"Python"
] | 5 | Markdown | DjaPy/24_telegraph | 43797974dcd6875a79ca7baadbedc83241833c6b | fd84eb862b7d843b19a703b16a09c5d54b780b4b |
refs/heads/master | <repo_name>osamie/TCP_sockets--<file_sep>/src/TCPClient.java
//TCPClient.java
import java.io.*;
import java.net.*;
class TCPClient
{
public static void main(String argv[]) throws Exception
{
String FromServer;
String ToServer;
int portnumber = 5000;
Socket clientSocket = new Socket("localhost", portnumber);
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
PrintWriter outToServer = new PrintWriter(
clientSocket.getOutputStream(),true);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
while (true)
{
FromServer = inFromServer.readLine();
if (FromServer.equals("~inventory~")){
//throw new RuntimeException("inventory!!!");
while (inFromServer.ready()){
System.out.println(inFromServer.readLine() + "\n");
}
}
//System.out.print("received from server: " + FromServer + "\n" );
if ( FromServer.equals("quit"))
{
System.out.println("Server is shutting down \n Quitting... ");
clientSocket.close();
break;
}
else
{
System.out.println(" \n ***RECIEVED:*** \n" + FromServer);
System.out.println("\n ***MESSAGE TO SERVER:***");
ToServer = inFromUser.readLine();
if (ToServer.equals("quit")||ToServer.equals("QUIT")||ToServer.equals("q"))
{
outToServer.println (ToServer) ;
clientSocket.close();
break;
}
String cmd;
if (ToServer.equals("B#")){
//cmd = ToServer.substring(4);
outToServer.println(ToServer);
//String readMonitor = "";
//while ((inFromServer.ready())){// && !(readMonitor.contains("$$"))){
//readMonitor = inFromServer.readLine();
System.out.println("MAKING PURCHASE...");
Thread.sleep(1000); //waiting for server response
System.out.println( inFromServer.readLine() + "\n");
//}
}
//if (ToServer.startsWith()("quit")
else
{
outToServer.println(ToServer);
}
}
}
}
}
<file_sep>/src/TCPServer.java
//TCPServer.java
import java.io.*;
import java.net.*;
class TCPServer
{
public static String fromclient;
static String toclient;
static int portnumber = 5000;
static ServerSocket Server;
public static String updateQty(String Bcode){
//Charset charset = Charset.forName("US-ASCII");
String itemCode = Bcode.replace('B', ' ');
itemCode = itemCode.trim();
try {
File oldFile = new File("inventory.txt");
BufferedReader in = new BufferedReader(new FileReader(oldFile));
String str;
StringBuffer sb = new StringBuffer();
while(in.ready()){
str = in.readLine();
if (str.startsWith(itemCode)){
String [] arr = str.split("\t");
int q = Integer.parseInt(arr[arr.length-1]);
//q++;
arr[arr.length-1] = "" + (q+1);
sb.append(arr);
continue;
//in.close();
//return str;
}
sb.append(str);
}
if (oldFile.exists()){
oldFile.delete();
oldFile.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(oldFile));
out.write(sb.toString());
out.close();
}
in.close();
} catch (IOException e) {
System.err.print(" oh oh ");
}
return "item not found!";
}
public static void sendInventory(Socket s){
File myFile = new File("inventory.txt");
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
// Do exception handling
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
BufferedOutputStream outToClient = new BufferedOutputStream(s.getOutputStream());
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0, mybytearray.length);
outToClient.flush();
//outToClient.close();
//s.close(); DONT THINK I NEED TO CLOSE THE SOCKET JUST YET!
// File sent, exit
return;
} catch (IOException ex) {
// Do exception handling
}
}
public static boolean isItemCode(String str){
if ((str.startsWith("B#"))&& (str.length()==6)){
//TODO : pre check if the remaining 4 characters are numbers
return true;
}
return false;
}
public static void main(String argv[]) throws Exception
{
Server = new ServerSocket (portnumber);
System.out.println ("TCPServer Waiting for client on port " + portnumber);
while(true)
{
Socket connected = Server.accept();
System.out.println( " THE CLIENT"+" "+
connected.getInetAddress() +":"+connected.getPort()+" IS CONNECTED ");
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader (connected.getInputStream()));
PrintWriter outToClient =
new PrintWriter(
connected.getOutputStream(),true);
//outToClient.print("************************\n");
//outToClient.print("**********YOU ARE CONNECTED TO THE SERVER**********");
//outToClient.print("************************\n");
while ( true )
{
System.out.println("\n ***MESSAGE TO CLIENT:***");
toclient = inFromUser.readLine();
if ( toclient.equals ("quit"))
{
outToClient.println(toclient);
connected.close();
break;
}
else
{
outToClient.println(toclient);
}
fromclient = inFromClient.readLine();
//if ( isItemCode(fromclient)){
if (fromclient.startsWith("B#")){
if (fromclient.length() == 2){
outToClient.println("incorrect purchase code. Try again! ");
continue;
}
System.out.println("scanning inventory for item...\n");
Thread.sleep(990);
String itemCode = fromclient.replace('B',' ');
itemCode = itemCode.trim();
outToClient.println(updateQty(itemCode));
System.out.println("Item " + fromclient + " has been updated in the inventory.");
outToClient.println("Item " + fromclient + " has been updated in the inventory. \n $$");
}
if ( fromclient.equals("i") || fromclient.equals("I") ){
sendInventory(connected);
//outToClient.println("Here is the inventory!");
//while(readInventory().ready()){
//outToClient.println(readInventory().readLine());
//}
System.out.println("\n ***just sent inventory to client*** \n");
}
if ( fromclient.equals("quit")|| fromclient.equals("QUIT") || fromclient.equals("q") )
{
System.out.println("Client has disconnected from the socket\n CLOSING CONNECTION.... \n" );
connected.close();
break;
}
else
{
System.out.println( "\n ***RECEIVED:*** \n" + fromclient );
}
}
}
}
}
| 934b8975afa2559f46175f8968ca9a4a98fbad84 | [
"Java"
] | 2 | Java | osamie/TCP_sockets-- | 81eaeb864674eb48d39f3eba02eb26b50f462c90 | 624f8f1de21519d6456452c7ce7866e6b1a0fc8f |
refs/heads/master | <repo_name>kuuku123/IPL_LeaderBoard<file_sep>/src/main/java/io/javabrains/ipldashboard/controller/TeamController.java
package io.javabrains.ipldashboard.controller;
import java.time.LocalDate;
import java.util.List;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.javabrains.ipldashboard.model.League_Match;
import io.javabrains.ipldashboard.model.Team;
import io.javabrains.ipldashboard.repository.MatchRepository;
import io.javabrains.ipldashboard.repository.TeamRepository;
import lombok.RequiredArgsConstructor;
@RestController
@RequiredArgsConstructor
@CrossOrigin
public class TeamController {
private final TeamRepository teamRepository;
private final MatchRepository matchRepository;
@GetMapping("/team/{teamName}")
public Team getTeam(@PathVariable String teamName) {
Team team = teamRepository.findByTeamName(teamName);
List<League_Match> result = matchRepository.findLatestMatchesByTeam(teamName, 4);
team.setMatches(result);
return team;
}
@GetMapping("/team")
public Iterable<Team> getAllTeam() {
List<Team> result = this.teamRepository.findAll();
return result;
}
@GetMapping("/team/{teamName}/matches")
public List<League_Match> getMatchesForTeam(@PathVariable String teamName,
@RequestParam int year) {
LocalDate startDate = LocalDate.of(year,1,1);
LocalDate endDate = LocalDate.of(year+1,1,1);
// return matchRepository.getByTeam1AndDateBetweenOrTeam2AndDateBetweenOrderByDateDesc(teamName,startDate,endDate, teamName, startDate, endDate);
return matchRepository.getMatchesByTeamBetweenDates(teamName, startDate, endDate);
}
}
<file_sep>/src/main/java/io/javabrains/ipldashboard/data/MatchDataProcessor.java
package io.javabrains.ipldashboard.data;
import java.time.LocalDate;
import io.javabrains.ipldashboard.model.League_Match;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
public class MatchDataProcessor implements ItemProcessor<MatchInput, League_Match> {
private static final Logger log = LoggerFactory.getLogger(MatchDataProcessor.class);
@Override
public League_Match process(final MatchInput matchInput) throws Exception {
League_Match leagueMatch = new League_Match();
leagueMatch.setId(Long.parseLong(matchInput.getId()));
leagueMatch.setCity(matchInput.getCity());
leagueMatch.setDate(LocalDate.parse(matchInput.getDate()));
leagueMatch.setPlayerOfMatch(matchInput.getPlayer_of_match());
leagueMatch.setVenue(matchInput.getVenue());
String firstInningsTeam, secondInningsTeam;
if ("bat".equals(matchInput.getToss_decision()))
{
firstInningsTeam = matchInput.getToss_winner();
secondInningsTeam = matchInput.getToss_winner().equals(matchInput.getTeam1())
? matchInput.getTeam2() : matchInput.getTeam1();
}
else
{
secondInningsTeam = matchInput.getToss_winner();
firstInningsTeam = matchInput.getToss_winner().equals(matchInput.getTeam1())
? matchInput.getTeam2() : matchInput.getTeam1();
}
leagueMatch.setTeam1(firstInningsTeam);
leagueMatch.setTeam2(secondInningsTeam);
leagueMatch.setTossWinner(matchInput.getToss_winner());
leagueMatch.setMatchWinner(matchInput.getWinner());
leagueMatch.setTossDecision(matchInput.getToss_decision());
leagueMatch.setResult(matchInput.getResult());
leagueMatch.setResultMargin(matchInput.getResult_margin());
leagueMatch.setUmpire1(matchInput.getUmpire1());
leagueMatch.setUmpire2(matchInput.getUmpire2());
return leagueMatch;
}
}
<file_sep>/src/frontend/src/components/TeamTile.js
import React from "react";
import {Link} from "react-router-dom";
import "./styles/TeamTile.scss";
const TeamTile = ({ teamName }) => {
return (
<div className="TeamTile">
<h1>
<Link to={`/teams/${teamName}`}>{teamName}</Link>
</h1>
</div>
);
};
export default TeamTile;
<file_sep>/src/frontend/src/pages/TeamPage.js
import React, { useEffect, useState, useRef } from "react";
import { useParams } from "react-router-dom";
import MatchDetailCard from "../components/MatchDetailCard";
import MatchSmallCard from "../components/MatchSmallCard";
import "./styles/TeamPage.scss";
import { PieChart } from "react-minimal-pie-chart";
import {Link} from 'react-router-dom';
const TeamPage = () => {
const [team, setTeam] = useState({ matches: [] });
const { teamName } = useParams();
const winRefs = useRef();
const loseRefs = useRef();
const defaultLabelStyle = {
fontSize: '17px',
};
function MouseEnter(r) {
r.current.classList.add("touched");
}
function MouseLeave(r) {
r.current.classList.remove("touched");
}
useEffect(() => {
try {
const fetchTeam = async () => {
const response = await fetch(`${process.env.REACT_APP_API_ROOT_URL}/team/${teamName}`);
const data = await response.json();
setTeam(data);
};
fetchTeam();
} catch (error) {
console.log(error);
}
}, [teamName]);
if (!team || !team.teamName) {
return <h1>Team not found</h1>;
}
return (
<div className="TeamPage">
<div className="team-name-section">
<h1>{team.teamName}</h1>
</div>
<h1 className="Win-loss-section">
<span
ref={winRefs}
className="Wins"
onMouseEnter={() => MouseEnter(winRefs)}
onMouseLeave={() => MouseLeave(winRefs)}
>
Wins
</span>
/
<span
ref={loseRefs}
className="Losses"
onMouseEnter={() => MouseEnter(loseRefs)}
onMouseLeave={() => MouseLeave(loseRefs)}
>
Losses
</span>
<PieChart
data={[
{
title: "Loss",
value: team.totalMatches - team.totalWins,
color: "#a34d5d",
},
{ title: "Win", value: team.totalWins, color: "#4da375" },
]}
viewBoxSize={[130, 90]}
center={[80, 50]}
label={({ dataEntry }) => `${dataEntry.title} : ${dataEntry.value}` }
labelStyle={{
...defaultLabelStyle,
}}
/>
</h1>
<div>
<h1>
<Link to={`/`}>Home</Link>
</h1>
</div>
<div className="match-detail-section">
<div className="body2">
<div className="words word-1">
<span>Latest Matches</span>
</div>
</div>
<MatchDetailCard
teamName={team.teamName}
match={team.matches[0]}
></MatchDetailCard>
</div>
{team.matches.slice(1).map((match) => {
return (
<MatchSmallCard
teamName={team.teamName}
key={match.id}
match={match}
></MatchSmallCard>
);
})}
<div className="more-link">
<Link to={`/teams/${teamName}/matches/${process.env.REACT_APP_DATA_END_YEAR}`}>More ></Link>
</div>
</div>
);
};
export default TeamPage;
<file_sep>/src/main/java/io/javabrains/ipldashboard/repository/MatchRepository.java
package io.javabrains.ipldashboard.repository;
import java.time.LocalDate;
import java.util.List;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import io.javabrains.ipldashboard.model.League_Match;
public interface MatchRepository extends JpaRepository<League_Match, Long> {
List<League_Match> getByTeam1OrTeam2OrderByDateDesc(String teamName1, String teamName2,
Pageable pageable);
default List<League_Match> findLatestMatchesByTeam(String teamName, int count) {
return getByTeam1OrTeam2OrderByDateDesc(teamName, teamName, PageRequest.of(0, count));
}
@Query("select m from League_Match m where (m.team1 = :teamName or m.team2 = :teamName) and m.date between :dateStart and :dateEnd order by date desc")
List<League_Match> getMatchesByTeamBetweenDates(@Param("teamName") String teamName,
@Param("dateStart") LocalDate dateStart, @Param("dateEnd") LocalDate dateEnd);
// List<League_Match> getByTeam1AndDateBetweenOrTeam2AndDateBetweenOrderByDateDesc(String
// teamName1, LocalDate date1 , LocalDate date2,String teamName2,LocalDate date3 , LocalDate
// date4);
}
<file_sep>/README.md
# IPL_LeaderBoard
Spring + JPA + react (+scss) + mysql (full stack application)
aws beanstalk url = http://iplleaderboard-env.eba-dnzxne4v.ap-northeast-2.elasticbeanstalk.com/#/
to run this in local\
open 2 terminal\
first in current directory run command ".\gradlew bootRun"<br />
second go to src/frontend/ and run command "yarn start"<br />

| 4205afddfe9908addda7dfa547c59563140c600c | [
"JavaScript",
"Java",
"Markdown"
] | 6 | Java | kuuku123/IPL_LeaderBoard | 3560b10209b380215496337cbc47f373578b303d | f2b8657a600c241dbdc51f84d96ff667058b440c |
refs/heads/master | <file_sep>library(raster)
library(tidyverse)
# unconditional simulations on a 100 x 100 grid using gstat
library(gstat)
library(doParallel)
#Generate presence/absence observations that simulate either a good (low error)
#or bad (high error) forecast.
#p : a vector of probabilites
#error: int between 0-1
observation_from_probability = function(p, error){
add_or_subtract = sample(c(1,-1),length(p), replace=TRUE)
random_errors = rnorm(length(p), mean = error, sd = 0.01) * add_or_subtract
obs = ifelse(p + random_errors <= 0.5, 0, 1)
return(obs)
}
#Testing the above function
#r = data.frame()
#for(this_error in rbeta(1000, 1,1)){
# probs = rbeta(100,1,1)
# obs = observation_from_probability(probs, error=this_error)
# r = r %>%
# bind_rows(data.frame('error' = this_error, 'brier'=mean((probs-obs)^2),'brier2'=verification::brier(obs, probs)$bs,
# 'brier_reliability'=verification::brier(obs, probs)$bs.reliability,'auc'=Metrics::auc(obs, probs)))
#}
#plot(r)
#Create a raster of random spatially correlated probabilites
get_random_prob_layer = function(size=100){
# create structure
xy <- expand.grid(1:size, 1:size)
names(xy) <- c("x","y")
# define the gstat object (spatial model)
g.dummy <- gstat(formula=z~1, locations=~x+y, dummy=T, beta=1, model=vgm(psill=0.025,model="Exp",range=5), nmax=20)
# make simulation based on the stat object
yy <- predict(g.dummy, newdata=xy, nsim=1)
#Scale from 0 to 1
yy$sim1 = with(yy, (sim1 - min(sim1)) / (max(sim1) - min(sim1)))
# show one realization
gridded(yy) = ~x+y
yy = raster(yy)
return(yy)
}
#Total cost for observations which were not forecasted to be true. forecast_raster may be a larger grain size than
calculate_loss_cost = function(forecast_raster, observation_raster, L){
fn = (as.vector(observation_raster)==1 & as.vector(forecast_raster)==0)
total_loss_area = sum(fn)
total_loss = total_loss_area * L
return(total_loss)
}
##################################################
numProcs=2
cl=makeCluster(numProcs)
registerDoParallel(cl)
##################################################
original_extent = 128
total_km2 = original_extent^2
spatial_scales = c(1,2,4,8,16,32, 64)
num_runs = 2
treatment_cost = 10
possible_loss_costs = 10 / seq(0.11, 1, 0.01)
#Add in denser estimates for low values of C/L
possible_loss_costs = c(possible_loss_costs, 10 / seq(0.001, 0.1, 0.001))
results = foreach(run_i = 1:num_runs, .combine=rbind, .packages=c('dplyr','gstat','raster')) %dopar% {
results_this_run = data.frame()
for(model_forecast_error in c(0.01, 0.02, 0.05, 0.1, 0.2, 0.3)){
probability_surface = get_random_prob_layer(size=original_extent)
observations = raster::calc(probability_surface, fun=function(x){return(observation_from_probability(x, error=model_forecast_error))})
for(loss_cost in possible_loss_costs){
binary_forecast = raster::calc(probability_surface, fun = function(x){(x>(treatment_cost / loss_cost)) * 1})
smallest_grain_cost_perfect = (sum(as.vector(observations)) * treatment_cost) / total_km2
smallest_grain_cost_never = (sum(as.vector(observations)) * loss_cost) / total_km2
smallest_grain_cost_maximimum = min(treatment_cost, smallest_grain_cost_never)
for(this_spatial_scale in spatial_scales){
#Upscale the raster, then return back to the 1x1 resolution for comparison against 1x1 observation
if(this_spatial_scale > 1){
binary_forecast_upscaled = disaggregate(aggregate(binary_forecast, fact=this_spatial_scale, fun=max), fact=this_spatial_scale)
} else {
binary_forecast_upscaled = binary_forecast
}
this_scale_treatment_cost = (sum(as.vector(binary_forecast_upscaled)) * treatment_cost)
this_scale_loss_cost = calculate_loss_cost(forecast_raster = binary_forecast_upscaled, observation_raster = observations, L = loss_cost)
this_scale_expense = (this_scale_treatment_cost + this_scale_loss_cost) / total_km2
results_this_run = results_this_run %>%
bind_rows(data.frame('forecast_error' = model_forecast_error,
'a' = treatment_cost / loss_cost,
'spatial_scale' = this_spatial_scale,
'expense_max' = smallest_grain_cost_maximimum,
'expense_perfect' = smallest_grain_cost_perfect,
'expense_forecast' = this_scale_expense,
'run'=run_i))
}
}
}
return(results_this_run)
}
results$value = with(results, (expense_max - expense_forecast) / (expense_max - expense_perfect))
write.csv(results, 'spatial_cost_loss_sim_results.csv', row.names = FALSE)
<file_sep>library(tidyverse)
#################################
#The cost loss curves for the toy example
toy_example = read.csv('toy_example_data.csv')
treatment_cost = 10
possible_loss_costs = 10 / seq(0.11, 1, 0.01)
total_km2 = 16
smallest_grain_expense_perfect = (7 * treatment_cost) / total_km2
smallest_grain_expense_always = treatment_cost
values = data.frame()
for(this_scale in c(1,2)){
data_subset = toy_example %>% filter(spatial_scale == this_scale)
for(loss_cost in possible_loss_costs){
smallest_grain_never = 7 * loss_cost / total_km2
smallest_grain_maximum = min(smallest_grain_never, smallest_grain_expense_always)
this_grain_tp_fp_expense = sum(data_subset$prediction) * treatment_cost
this_grain_fn_expense = sum(data_subset$presence==1 & data_subset$prediction==0) * loss_cost
this_grain_expense = (this_grain_fn_expense + this_grain_tp_fp_expense) / total_km2
a = treatment_cost/loss_cost
values = values %>%
bind_rows(data.frame(spatial_scale = this_scale, expense_forecast = this_grain_expense, expense_max = smallest_grain_maximum,
expense_perfect = smallest_grain_expense_perfect, a=a))
}
}
values$value = with(values, (expense_max - expense_forecast) / (expense_max - expense_perfect))
ggplot(values, aes(x=a, y=value, group=as.factor(spatial_scale), color=as.factor(spatial_scale))) +
geom_line(size=1.5) +
ylim(0,1) +
theme_bw()
<file_sep>library(tidyverse)
results_averaged = results %>%
group_by(spatial_scale, a, forecast_error) %>%
summarise(value = mean(value)) %>%
ungroup()
#############################################
ggplot(filter(results_averaged, value>0), aes(y=value, x=a, color=as.factor(spatial_scale), group=as.factor(spatial_scale))) +
geom_point() +
geom_line() +
facet_grid(forecast_error~., scales='free_y')
| 57487b05bf6456bf1465b63142c434e85badece4 | [
"R"
] | 3 | R | sdtaylor/cost_loss_stuff | 1687a3b368baf6038f1e1f6f2a232db6c69b8434 | 94acba907ac804b30ced54adb6e2e8bca786b483 |
refs/heads/master | <repo_name>Viper2910/chechIfPalindrome<file_sep>/src/CheckIfPalindrome.java
import java.util.Scanner;
public class CheckIfPalindrome{
// Take input from user.
public static String getInputFromUser(){
String input;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the string to check if it is a palindrome: \n");
input = scanner.nextLine();
return input;
}
//Reverse input given bu user.
public static String reverseInputGivenByUser(String input){
StringBuilder reversedInput = new StringBuilder();
for (int i = input.length()-1; i >= 0; i--){
reversedInput.append(input.charAt(i));
}
return reversedInput.toString();
}
//Check if input string is the same as reversed input.
public static boolean checkIfInputIsPalindrome(String input, String reversedInput){
boolean isPalindrome = (input.equals(reversedInput)) ? true : false;
return isPalindrome;
}
//Give answer to user
public static void giveAnswerToUser(boolean isPalindrome){
String answer = (isPalindrome == true) ? "Given input is palindrome. \n\n" : "Given input is not a palindrome.\n\n";
System.out.println(answer);
}
}<file_sep>/README.md
# chechIfPalindrome
check if string is palingrome
TODO
simple program allowing user to input string. Program should check if that string is palindrome.
| 4953fba4369de5f5ffe6085a13e113d88796c322 | [
"Markdown",
"Java"
] | 2 | Java | Viper2910/chechIfPalindrome | 6880743c5dbbc1bdbab04e595c46e4d82ada1b4e | 30a3411f3d1467628be16e18cd1af4ebde8c7d1c |
refs/heads/master | <file_sep>import SpriteKit
class MenuScene: SKScene {
var startLabel: SKLabelNode!
var informationLabel: SKLabelNode!
override func didMove(to view: SKView) {
let background = SKSpriteNode(imageNamed: "background.jpg")
background.position = CGPoint(x: 512, y: 384)
background.blendMode = .replace
background.zPosition = -1
addChild(background)
startLabel = SKLabelNode(fontNamed: "Chalkduster")
startLabel.text = "Start"
startLabel.setScale(2)
startLabel.position = CGPoint(x:512 , y:410)
addChild(startLabel)
informationLabel = SKLabelNode(fontNamed: "Chalkduster")
informationLabel.text = "Information"
informationLabel.setScale(2)
informationLabel.position = CGPoint(x:512 , y:280)
addChild(informationLabel)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let location = touch.location(in: self)
let objects = nodes(at: location)
if objects.contains(startLabel) {
let gameScene = GameScene(size: self.size)
self.view?.presentScene(gameScene)
} else if objects.contains(informationLabel){
let informationScene = InformationScene(size: self.size)
self.view?.presentScene(informationScene)
}
}
}
}
<file_sep>import SpriteKit
class InformationScene: SKScene {
var scoreLabel: SKLabelNode!
var obstacleLabel: SKLabelNode!
var noteLabel: SKLabelNode!
var backLabel: SKLabelNode!
override func didMove(to view: SKView) {
let background = SKSpriteNode(imageNamed: "background.jpg")
background.position = CGPoint(x: 512, y: 384)
background.blendMode = .replace
background.zPosition = -1
addChild(background)
scoreLabel = SKLabelNode(fontNamed: "Chalkduster")
scoreLabel.text = "Scoring:"
scoreLabel.fontColor = UIColor.yellow
scoreLabel.position = CGPoint(x: 80, y: 615)
addChild(scoreLabel)
addChild(createMultiLineText(textToPrint: "-To earn points the ball must hit obstacles before it lands on the green\n\n slots. Points will be calculated depending on the number of\n\nobstacles it hits.", fontSize: 24, fontName: "Chalkduster", fontPosition: CGPoint(x: 512, y: 580)))
addChild(createMultiLineText(textToPrint: "\n-You will lose 1 point if the ball lands on the red slots unless you hit\n\n 3 obstacles before you land.", fontSize: 24, fontName: "Chalkduster", fontPosition: CGPoint(x: 500, y: 455)))
obstacleLabel = SKLabelNode(fontNamed: "Chalkduster")
obstacleLabel.text = "How to add obstacles:"
obstacleLabel.position = CGPoint(x: 220, y: 340)
obstacleLabel.fontColor = UIColor.yellow
addChild(obstacleLabel)
addChild(createMultiLineText(textToPrint: "You should press on the Edit to change to edit mode. Then\n\nyou can add obstacles by pressing on the screen.", fontSize: 24, fontName: "Chalkduster", fontPosition: CGPoint(x: 500, y: 305)))
noteLabel = SKLabelNode(fontNamed: "Chalkduster")
noteLabel.text = "Notes:"
noteLabel.position = CGPoint(x: 76, y: 200)
noteLabel.fontColor = UIColor.yellow
addChild(noteLabel)
addChild(createMultiLineText(textToPrint: "-The ball will be transported to the top of the screen\n\nif it hits two different rainbows.\n\n-You will get an extra ball if a ball lands on the green slots.\n\n-You should press above half of the screen to create a ball", fontSize: 20, fontName: "Chalkduster", fontPosition: CGPoint(x: 400, y: 160)))
backLabel = SKLabelNode(fontNamed: "Chalkduster")
backLabel.text = "Back"
backLabel.horizontalAlignmentMode = .right
backLabel.position = CGPoint(x: 980, y: 700)
addChild(backLabel)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let location = touch.location(in: self)
let objects = nodes(at: location)
if objects.contains(backLabel) {
let menuScene = MenuScene(size: self.size)
self.view?.presentScene(menuScene)
}
}
}
func createMultiLineText(textToPrint:String, fontSize:CGFloat, fontName:String, fontPosition:CGPoint )->SKNode{
// create node to hold the text block
let textBlock = SKNode()
//create array to hold each line
let textArr = textToPrint.components(separatedBy: "\n")
// loop through each line and place it in an SKNode
var lineNode: SKLabelNode
for line: String in textArr {
lineNode = SKLabelNode(fontNamed: fontName)
lineNode.text = line
lineNode.fontSize = fontSize
lineNode.fontName = fontName
lineNode.position = CGPoint(x: fontPosition.x,y: fontPosition.y - CGFloat(textBlock.children.count ) * fontSize)
textBlock.addChild(lineNode)
}
// return the sknode with all of the text in it
return textBlock
}
}
<file_sep># Peggle-Game
## This is a very simple 2D game, but includes sprites, physics and collisions, HUD, animations, etc.
<img src="screenshots/main_menu.png">
<img src="screenshots/information_screen.png">
<img src="screenshots/edit_mode.png">
<img src="screenshots/game_play.png">
<file_sep>import SpriteKit
import GameplayKit
class GameScene: SKScene, SKPhysicsContactDelegate{
var scoreLabel: SKLabelNode!
var ballsLeftLabel: SKLabelNode!
var restartLabel: SKLabelNode!
var backButton: SKLabelNode!
var rainbowCounter = 0
var isThereAnyBall: Bool = true
var ballsLeft = 5 {
didSet {
ballsLeftLabel.text = "Balls Left: \(ballsLeft)"
}
}
var score = 0 {
didSet {
scoreLabel.text = "Score: \(score)"
}
}
var editLabel: SKLabelNode!
var editingMode: Bool = false {
didSet {
if editingMode {
editLabel.text = "Done"
} else {
editLabel.text = "Edit"
}
}
}
override func didMove(to view: SKView) {
let background = SKSpriteNode(imageNamed: "background.jpg")
background.position = CGPoint(x: 512, y: 384)
background.blendMode = .replace
background.zPosition = -1
addChild(background)
physicsWorld.contactDelegate = self
physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
makeBouncer(at: CGPoint(x: 0, y: 0))
makeBouncer(at: CGPoint(x: 256, y: 0))
makeBouncer(at: CGPoint(x: 512, y: 0))
makeBouncer(at: CGPoint(x: 768, y: 0))
makeBouncer(at: CGPoint(x: 1024, y: 0))
makeSlot(at: CGPoint(x: 128, y: 0), isGood: true)
makeSlot(at: CGPoint(x: 384, y: 0), isGood: false)
makeSlot(at: CGPoint(x: 640, y: 0), isGood: true)
makeSlot(at: CGPoint(x: 896, y: 0), isGood: false)
scoreLabel = SKLabelNode(fontNamed: "Chalkduster")
scoreLabel.text = "Score: 0"
scoreLabel.horizontalAlignmentMode = .right
scoreLabel.position = CGPoint(x: 895, y: 700)
addChild(scoreLabel)
backButton = SKLabelNode(fontNamed: "Chalkduster")
backButton.text = "Back"
backButton.position = CGPoint(x: 970, y: 700)
addChild(backButton)
editLabel = SKLabelNode(fontNamed: "Chalkduster")
editLabel.text = "Edit"
editLabel.position = CGPoint(x: 80, y: 700)
addChild(editLabel)
restartLabel = SKLabelNode(fontNamed: "Chalkduster")
restartLabel.text = ""
restartLabel.position = CGPoint(x: 512, y: 384)
addChild(restartLabel)
ballsLeftLabel = SKLabelNode(fontNamed: "Chalkduster")
ballsLeftLabel.text = "Balls Left: 5"
ballsLeftLabel.position = CGPoint(x: 300, y: 700)
addChild(ballsLeftLabel)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let location = touch.location(in: self)
let objects = nodes(at: location)
if objects.contains(backButton){
let menuScene = MenuScene(size: self.size)
self.view?.presentScene(menuScene)
}
if ballsLeft > 0 {
if objects.contains(editLabel) {
editingMode = !editingMode
} else {
if editingMode {
let touchedNode = self.atPoint(location)
if touchedNode.name == "box"{
touchedNode.removeFromParent()
} else{
drawBox(at: location)
}
} else {
if location.y >= 500 {
drawBall(at: location)
ballsLeft -= 1
}
}
}
} else {
if !isThereAnyBall{
restart()
}
}
}
}
func drawBox(at position: CGPoint){
let size = CGSize(width: GKRandomDistribution(lowestValue: 16, highestValue: 128).nextInt(), height: 16)
let box = SKSpriteNode(color: RandomColor(), size: size)
box.zRotation = RandomCGFloat(min: 0, max: 3)
box.position = position
box.physicsBody = SKPhysicsBody(rectangleOf: box.size)
box.physicsBody?.isDynamic = false
box.name = "box"
addChild(box)
}
func drawBall(at position: CGPoint){
let colors = ["Blue", "Cyan", "Green", "Grey", "Purple", "Red", "Yellow"]
let rand = RandomInt(min: 0, max: 6)
let ball = SKSpriteNode(imageNamed: "ball\(colors[rand])")
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width / 2.0)
ball.physicsBody!.contactTestBitMask = ball.physicsBody!.collisionBitMask
ball.physicsBody?.restitution = 0.4
ball.position = position
ball.name = "ball"
ball.userData = ["countHittedObstacles" : 0]
addChild(ball)
}
func didBegin(_ contact: SKPhysicsContact) {
guard let nodeA = contact.bodyA.node else { return }
guard let nodeB = contact.bodyB.node else { return }
if nodeA.name == "ball" {
collisionBetween(ball: nodeA, object: nodeB)
} else if nodeB.name == "ball" {
collisionBetween(ball: nodeB, object: nodeA)
}
}
func makeBouncer(at position: CGPoint) {
let bouncer = SKSpriteNode(imageNamed: "bouncer")
bouncer.position = position
bouncer.physicsBody = SKPhysicsBody(circleOfRadius: bouncer.size.width / 2.0)
bouncer.physicsBody?.isDynamic = false
bouncer.name = "bouncer\(rainbowCounter)"
addChild(bouncer)
rainbowCounter += 1
}
func makeSlot(at position: CGPoint, isGood: Bool) {
var slotBase: SKSpriteNode
var slotGlow: SKSpriteNode
if isGood {
slotBase = SKSpriteNode(imageNamed: "slotBaseGood")
slotGlow = SKSpriteNode(imageNamed: "slotGlowGood")
slotBase.name = "good"
} else {
slotBase = SKSpriteNode(imageNamed: "slotBaseBad")
slotGlow = SKSpriteNode(imageNamed: "slotGlowBad")
slotBase.name = "bad"
}
slotBase.position = position
slotGlow.position = position
slotBase.physicsBody = SKPhysicsBody(rectangleOf: slotBase.size)
slotBase.physicsBody?.isDynamic = false
addChild(slotBase)
addChild(slotGlow)
let spin = SKAction.rotate(byAngle: .pi, duration: 10)
let spinForever = SKAction.repeatForever(spin)
slotGlow.run(spinForever)
}
func collisionBetween(ball: SKNode, object: SKNode) {
if object.name == "bouncer0" || object.name == "bouncer1" || object.name == "bouncer2" || object.name == "bouncer3" || object.name == "bouncer4"{
ball.userData?.setValue(true, forKey: "\(object.name!)")
let count = ball.userData!.count
if count >= 3 {
ball.userData?.removeObject(forKey: "bouncer0")
ball.userData?.removeObject(forKey: "bouncer1")
ball.userData?.removeObject(forKey: "bouncer2")
ball.userData?.removeObject(forKey: "bouncer3")
ball.userData?.removeObject(forKey: "bouncer4")
ball.run(SKAction.moveTo(y: 700, duration: 0.0))
}
} else if object.name == "box" {
var val = ball.userData?.value(forKey: "countHittedObstacles") as! Int
val += 1
ball.userData?.setValue(val, forKey: "countHittedObstacles")
object.removeFromParent()
} else if object.name == "good" {
ballsLeft += 1
destroy(ball: ball)
score += ball.userData?.value(forKey: "countHittedObstacles") as! Int
} else if object.name == "bad" {
destroy(ball: ball)
if !(ball.userData?.value(forKey: "countHittedObstacles") as! Int >= 3) {
score -= 1
}
}
}
func destroy(ball: SKNode) {
if let fireParticles = SKEmitterNode(fileNamed: "FireParticles") {
fireParticles.position = ball.position
addChild(fireParticles)
}
ball.removeFromParent()
if ballsLeft == 0 {
restartLabel.text = "Press anywhere to restart the game"
isThereAnyBall = false
let scale = SKAction.scale(by: 0.8, duration: 0.5)
let reverseScale = scale.reversed()
let actions = [scale, reverseScale]
let sequence = SKAction.sequence(actions)
restartLabel.run(sequence)
}
}
func restart(){
ballsLeft = 5
isThereAnyBall = true
restartLabel.text = ""
score = 0
for child in self.children{
if child.name == "box"{
child.removeFromParent()
}
}
}
}
| 36d506aa5081af8682f1b622bd773cfdc8e0fa1d | [
"Swift",
"Markdown"
] | 4 | Swift | HakanKOCAK/Peggle-Game | 7679aac31eefc09a8c8debb7fcb89e14d122f0b6 | 06f33d606abd9f3b93398c850bc6e9e20dfa7e80 |
refs/heads/main | <repo_name>wisnusamp/SampBot2<file_sep>/bot.js
const { Client, MessageEmbed, Channel, Message } = require('discord.js');
const client = new Client;
global.config = require("./config.json")
const query = require("samp-query");
const getServerPing = require('./src/samp.js')
const prefix = "!";
let Samp_IP = "172.16.17.32";
let Samp_Port = 7777;
var channelid = '837571530904043601';
var options = {
host: Samp_IP,
port: Samp_Port
}
var s;
client.on('ready', () => {
console.log(`Bot ${client.user.tag} is going online!!`);
UpdateStatus();setInterval(UpdateStatus,30000)
});
function UpdateStatus()
{
const randpesan = [
"DEWATA ROLEPLAY",
"#DEWATARP",
"Join us @dewatarp.xyz"
];
const randommes = Math.floor(Math.random() * (randpesan.length));
const newRandomMes = randpesan[randommes];
const randstatus = [
"PLAYING",
"STREAMING",
"LISTENING",
"COMPETING",
"WATCHING"
]
const randomstats = Math.floor(Math.random() * (randstatus.length));
const newRandomStats = randstatus[randomstats]
query(options, function(error, response){
if(error)
{
status = "SERVER OFFLINE";
client.user.setActivity(status, {type: `${newRandomStats}`});
}
else
{
status = `${response['online']} Players | ${newRandomMes}`;
client.user.setActivity(status, {type: `${newRandomStats}`});
}
})
}
function getServerInfo(msg)
{
getServerPing("s1.dewatarp.xyz", 7777, function(error,response){
if(!error)
{
spg = `${response}ms`
}
})
const randpesan = [
"**```DEWATA ROLEPLAY```**",
"**```#DEWATARP```**",
"**```Join us @dewatarp.xyz```**"
];
const randommes = Math.floor(Math.random() * (randpesan.length));
const newRandomMes = randpesan[randommes];
query(options, function(error, response){
if(error)
{
const embedColor = 0xff0000;
const logMessage = {
embed: {
title: 'DEWATA ROLEPLAY',
color: embedColor,
url: 'https://dewatarp.xyz/',
fields: [
{ name: '**Server Name**', value: 'Dewata Roleplay', inline: false },
{ name: '**Website**', value: 'https://dewatarp.xyz/', inline: false },
{ name: '**IP**', value: 'dewatarp.xyz', inline: false },
{ name: '**Gamemode**', value: 'DRP v2.1.3b', inline: false },
{ name: '**Language**', value: 'Bahasa Indonesia', inline: false },
{ name: '**Status**', value: '๐ดOffline', inline: false },
{ name: '**Players**', value: '0/100', inline: false },
{ name: '**Ping**', value: '0ms', inline: false },
{ name: '**Pesan**', value: `${newRandomMes}`, inline: false },
],
thumbnail: {
url: 'https://dewatarp.xyz/DEWATA.png',
},
timestamp: new Date(),
footer: {
text: 'DEWATA ROLEPLAY',
}
}
}
msg.edit(logMessage);
}
else
{
const embedColor = 0x800080;
const logMessage = {
embed: {
title: 'DEWATA ROLEPLAY',
color: embedColor,
url: 'https://dewatarp.xyz/',
fields: [
{ name: '**Server Name**', value: response['hostname'], inline: false },
{ name: '**Website**', value: 'https://dewatarp.xyz/', inline: false },
{ name: '**IP**', value: 'dewatarp.xyz', inline: false },
{ name: '**Gamemode**', value: response['gamemode'], inline: false },
{ name: '**Language**', value: response['mapname'], inline: false },
{ name: '**Status**', value: ':green_circle:Online', inline: false },
{ name: '**Players**', value: `${response['online']}/${response['maxplayers']}`, inline: false },
{ name: '**Ping**', value: `${spg}`, inline: false },
{ name: '**Pesan**', value: `${newRandomMes}`, inline: false },
],
thumbnail: {
url: 'https://dewatarp.xyz/DEWATA.png',
},
timestamp: new Date(),
footer: {
text: 'DEWATA ROLEPLAY',
}
}
}
msg.edit(logMessage);
}
})
}
function ServerStatus(msg)
{
getServerPing("s1.dewatarp.xyz", 7777, function(error,response){
if(!error)
{
spg = `${response}ms`
}
})
query(options, function(error, response){
if(error)
{
const embedColor = 0xff0000;
const logMessage = {
embed: {
title: 'DEWATA ROLEPLAY',
color: embedColor,
url: 'https://dewatarp.xyz/',
fields: [
{ name: '**Server Name**', value: 'Dewata Roleplay', inline: false },
{ name: '**Website**', value: 'https://dewatarp.xyz/', inline: false },
{ name: '**IP**', value: 'dewatarp.xyz', inline: false },
{ name: '**Gamemode**', value: 'DRP v2.1.3b', inline: false },
{ name: '**Language**', value: 'Bahasa Indonesia', inline: false },
{ name: '**Status**', value: '๐ดOffline', inline: false },
{ name: '**Players**', value: '0/100', inline: false },
{ name: '**Ping**', value: '0ms', inline: false },
],
thumbnail: {
url: 'https://dewatarp.xyz/DEWATA.png',
},
timestamp: new Date(),
footer: {
text: 'DEWATA ROLEPLAY',
}
}
}
msg.channel.send(logMessage);
}
else
{
const embedColor = 0x800080;
const logMessage = {
embed: {
title: 'DEWATA ROLEPLAY',
color: embedColor,
url: 'https://dewatarp.xyz/',
fields: [
{ name: '**Server Name**', value: response['hostname'], inline: false },
{ name: '**Website**', value: 'https://dewatarp.xyz/', inline: false },
{ name: '**IP**', value: 'dewatarp.xyz', inline: false },
{ name: '**Gamemode**', value: response['gamemode'], inline: false },
{ name: '**Language**', value: response['mapname'], inline: false },
{ name: '**Status**', value: ':green_circle:Online', inline: false },
{ name: '**Players**', value: `${response['online']}/${response['maxplayers']}`, inline: false },
{ name: '**Ping**', value: `${spg}`, inline: false },
],
thumbnail: {
url: 'https://dewatarp.xyz/DEWATA.png',
},
timestamp: new Date(),
footer: {
text: 'DEWATA ROLEPLAY',
}
}
}
msg.channel.send(logMessage);
}
})
}
function helpinfo(msg)
{
const embedColor = 0x800080;
const logMessage = {
embed: {
title: 'List Command',
color: embedColor,
fields: [
{ name: `**\`\`\`${prefix}help\`\`\`**`, value: '**list cmd**', inline: false },
{ name: `**\`\`\`${prefix}status\`\`\`**`, value: '**get server status**', inline: false },
{ name: `**\`\`\`${prefix}players\`\`\`**`, value: '**get players online**', inline: false },
{ name: `**\`\`\`${prefix}start\`\`\`**`, value: '**starting a live stats**', inline: false },
{ name: `**\`\`\`${prefix}takerole [IC NAME]\`\`\`**`, value: '**Taking some role on guild**', inline: false },
{ name: `**\`\`\`${prefix}stop\`\`\`**`, value: '**stop live stats**', inline: false },
{ name: `**\`\`\`${prefix}ping\`\`\`**`, value: '**getting ping**', inline: false },
],
thumbnail: {
url: 'https://dewatarp.xyz/DEWATA.png',
},
timestamp: new Date(),
footer: {
text: 'Join us @dewatarp.xyz',
}
}
}
msg.channel.send(logMessage);
}
client.on('message', msg => {
if(msg.content.charAt(0) == prefix)
{
const request = msg.content.substr(1);
let command, parameters = [];
if(request.indexOf(" ") !== -1)
{
command = request.substr(0, request.indexOf(" "));
parameters = request.split(" ");
parameters.shift();
}
else
{
command = request;
}
switch(command.toLowerCase())
{
case "players":
msg.channel.send(`Checking players...`)
.then(msg => {
setTimeout(function(){
query(options, function (error, response) {
if(error)
{
msg.edit(`Server is now offline`)
}
else
{
msg.edit(`Players: ${response['online']}`)
}
})
}, 1000)
})
break;
case "status":
ServerStatus(msg);
break;
case "start":
if(msg.member.roles.cache.has('805471217565433927'))
{
msg.channel.bulkDelete(1)
msg.channel.send('ONLINE STATUS')
.then(msg => {
s = setInterval(function() {
getServerInfo(msg)
}, 2000)
})
}
else
{
msg.reply("You don't have permission")
}
break;
case "stop":
if(msg.member.roles.cache.has('805471217565433927'))
{
if(!s)
{
msg.reply("I Can't find any live Statistics running")
}
else
{
msg.react('๐')
clearInterval(s)
}
}
else
{
msg.reply("You don't have permission")
}
break;
case "takerole"://805473200422649876
if(msg.channel.id != '813750075736981534') return
if(msg.member.roles.cache.find(rs => rs.id == '805473200422649876')) return
if(msg.channel.type == "dm") return msg.channel.send("You can't use that on dm!!")
let role = msg.guild.roles.cache.find(r => r.id == "805473200422649876");
let member = msg.mentions.members.first();
if(!parameters.length) return msg.channel.send("Please input your rp name")
const nick = "[WARGA] " + parameters.join(" ")
if(nick.length > 32) return msg.channel.send("Your name is to long")
/*try {
msg.member.roles.add(role);
msg.channel.send("**YOU GAIN ROLE <@&805473200422649876>, AND WELCOME TO DEWATA ROLEPLAY**")
} catch{
msg.reply("I Can't Add roles for this user");
console.log(Error);
};
try{
msg.member.setNickname(nick);
}
catch{
msg.reply("I Can't change the nickname for this user");
console.log(Error)
};*/
msg.member.roles.add(role).catch(console.log("Error Addng role"))
msg.member.setNickname(nick).catch(console.log("Error cange nick"))
break;
case "ping":
var svping;
getServerPing("s1.dewatarp.xyz", 7777, function(error,response){
if(error)
{
svping = `Server Ping: 0ms`
}
else
{
svping = `Server Ping: ${response}ms`
}
})
msg.channel.send("Calculating ping...")
.then(message => {
setTimeout(function(){
var ping = message.createdTimestamp - msg.createdTimestamp
message.edit(`Latency: ${ping}ms\n${svping}`)
}, 1000)
})
break;
case "tendang":
if(msg.member.roles.cache.has('805471217565433927'))
{
if(msg.mentions.members.first()){
msg.mentions.members.first().kick().catch(msg.reply("I Can't kick this user"));
}
else
{
msg.reply("Plesae tag someone, EX:```!tendang @Alpa#1234```")
}
}
else
{
msg.reply("You don't have permission")
}
break;
case "help":
helpinfo(msg)
break;
}
}
})
client.login(config.token); | 580b4840ddfdb1e47f7c62f7f2acb443302ca2ca | [
"JavaScript"
] | 1 | JavaScript | wisnusamp/SampBot2 | 2d423ccdb78f5d769054a012832e40d8ee3c16d7 | e6521a378537ea574cc87760635c740af393f880 |
refs/heads/master | <repo_name>wayne666/LRU<file_sep>/README.md
# LRU
## Description
Simple LRU implementation of container/list
## Installation
$ go get github.com/wayne666/LRU
## Usage
l := LRU.New(capacity)
l.Set(key, value) // Set key value
l.Get(key) // Get value of key
l.Purge() // Purge all cache
<file_sep>/lru_test.go
package LRU
import (
"testing"
)
func TestNew(t *testing.T) {
l := New(8)
if l.capacity != 8 {
t.Errorf("New failed")
}
}
func TestSetGet(t *testing.T) {
l := New(8)
for i := 0; i < 10; i++ {
l.Set(i, i)
}
if _, _, ok := l.Get(0); ok == false {
t.Errorf("Get error")
}
}
func TestPurge(t *testing.T) {
l := New(8)
for i := 0; i < 10; i++ {
l.Set(i, i)
}
l.Purge()
if len(l.items) != 0 || l.list.Len() != 0 {
t.Errorf("Purge failed")
}
}
<file_sep>/lru.go
package LRU
import (
"container/list"
)
type LRU struct {
capacity int
list *list.List
items map[interface{}]*list.Element
}
type Entry struct {
key interface{}
value interface{}
}
func New(capacity int) *LRU {
if capacity < 0 {
panic("Capacity must greater than 0")
}
return &LRU{capacity: capacity, list: list.New(), items: make(map[interface{}]*list.Element)}
}
func (l *LRU) Set(key, value interface{}) bool {
if elem, ok := l.items[key]; ok {
l.list.MoveToFront(elem)
return false
}
entry := &Entry{key, value}
elem := l.list.PushBack(entry)
l.items[key] = elem
if l.list.Len() > l.capacity {
l.removeOldest()
}
return true
}
func (l *LRU) Get(key interface{}) (interface{}, interface{}, bool) {
if elem, ok := l.items[key]; ok {
l.list.MoveToFront(elem)
return key, l.items[key].Value, true
}
return nil, nil, false
}
func (l *LRU) Purge() {
for key, _ := range l.items {
delete(l.items, key)
}
l.list.Init()
}
func (l *LRU) removeOldest() bool {
elem := l.list.Back()
if elem != nil {
elemInterface := l.list.Remove(elem)
delete(l.items, elemInterface.(*Entry).key)
return true
}
return false
}
| a0eeb059dcec5833e1069e90dd6c8cf6f3587470 | [
"Markdown",
"Go"
] | 3 | Markdown | wayne666/LRU | 800e867369405aa08ee60e55f8af8bf1e18df1ff | d6c61a9840248ee5003b9e6c6b53d61d1c9f12d3 |
refs/heads/main | <repo_name>kmh8827/Eat-da-burger<file_sep>/README.md
# Eat-The-Burger <img align="right" src=" ">

Deployed Application: https://hellman-eat-the-burger.herokuapp.com/
### Description
This program allows a user to create burgers and then eat them
## Table of Contents
[Description](#description)
[Installation](#installation)
[Usage](#usage)
[Contribution](#contributing)
[Test Instructions](#test-instructions)
[Questions](#questions)
[Licensing](#licensing)
### Installation
No installation required, simply go to the website
### Usage
Type into the field and click the create button to make a burger, then click the eat button to eat it
### Contributing
Contact me at my email address
### Test Instructions
Simply try out the program
## Questions
### Email Address
For further questions contact me at: <EMAIL>
### Github Address
github.com/kmh8827
### Licensing
No Licensing
<file_sep>/db/seeds.sql
insert into burgers (burger_name, devoured) values ('hamburger', true);
insert into burgers (burger_name, devoured) values ('cheesburger', true);
insert into burgers (burger_name, devoured) values ('doublehamburger', false);
insert into burgers (burger_name, devoured) values ('doublecheeseburger', false);<file_sep>/public/assets/js/burgers.js
document.addEventListener('DOMContentLoaded', (event) => {
// Makes sure the DOM haS loaded
if (event) {
console.log('DOM loaded');
}
const eatBtn = document.querySelectorAll('.changeBurger');
// Checks to see if an Eat Button exists
if (eatBtn) {
eatBtn.forEach((button) => {
button.addEventListener('click', (e) => {
console.log('devoured');
const id = e.target.getAttribute('data-id');
// Changes the devoured value of Selected Burger to True
const newDevoured = {
devoured: true
};
fetch(`/api/burgers/${id}`, {
method: 'PUT',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(newDevoured),
}).then((response) => {
if (response.ok) {
location.reload('/');
} else {
alert('Uh-Oh');
}
});
});
});
}
const createBtn = document.getElementById('createBurger');
// Checks for the create Button
if (createBtn) {
createBtn.addEventListener('submit', (e) => {
e.preventDefault();
// Gets the burger ID
const newBurger = {
burger_name: document.getElementById('burgerName').value
};
fetch('/api/burgers', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(newBurger),
}).then(() => {
document.getElementById('burgerName').value = '';
location.reload();
});
});
}
}); | 8b484d613b5c2f1536ca1ae16717263d4d0da702 | [
"Markdown",
"SQL",
"JavaScript"
] | 3 | Markdown | kmh8827/Eat-da-burger | 4267a9098182068f42dff7537cd8a046f3f0429f | 986029bf840303c00d1eb6d379ce75701e503c05 |
refs/heads/master | <repo_name>kentanvictor/Bmob_Sample_lost_found<file_sep>/app/src/main/java/com/bmob/lostfound/config/Constants.java
package com.bmob.lostfound.config;
/** ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ
* @ClassName: Constants
* @Description: TODO
* @author smile
* @date 2014-5-21 ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ3:25:51
*/
public class Constants {
public static String Bmob_APPID = "e9bbe5f23a1aa1d60d525871e1d7db99";// bmob sdk๏ฟฝ๏ฟฝAPPID
public static final int REQUESTCODE_ADD = 1;//๏ฟฝ๏ฟฝ๏ฟฝสง๏ฟฝ๏ฟฝ/๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ
}
<file_sep>/README.md
# Bmobๅฎไพ
**ไธ้จ็จๆฅๅญฆไน ๅฆไฝ่ฐ็จapkไฝฟๅพ่ช่บซ็ๅบ็จๅฏไปฅ่ฟๆฅๅฐๅๅฐ**
| 8f00e991f0cf180691c51fccce7bc80f40294cee | [
"Markdown",
"Java"
] | 2 | Java | kentanvictor/Bmob_Sample_lost_found | 8a321d9ffa6174f69969ecec236b5ea13f6962da | 7acf7d54876d77c5956fb691609b11e9eec12e13 |
refs/heads/master | <repo_name>dengweiping4j/sms-ui<file_sep>/src/pages/403.js
import React from 'react';
export default () => (
<div style={{ height: '100vh', width: '100%' }}>
ๆฒกๆๆ้ๅฆ~
</div>
);
<file_sep>/src/components/UserCard/UserCard.js
import React, { Component } from 'react';
import { Avatar, Dropdown, Menu } from 'antd';
import styles from './UserCard.less';
class UserCord extends Component {
constructor(props) {
super(props);
this.state = {};
}
toUserDetail = () => {
};
render() {
const { user = {} } = this.props;
const menu = (
<Menu className={styles['menu']}>
<Menu.Item className={styles['item']}><img src={'/images/password-u.svg'} className={styles['img']} width={20} />ไฟฎๆนๅฏ็ </Menu.Item>
<Menu.Item className={styles['item']}><img src={'/images/logout.svg'} className={styles['img']} width={17} style={{marginLeft:'4px'}}/>้ๅบ็ปๅฝ</Menu.Item>
</Menu>
);
return <div>
<Dropdown overlay={menu} arrow>
<a onClick={() => this.toUserDetail()}>
<Avatar size={40} alt={'ๅคดๅ'}>
{user.userName.substr(0, 1)}
</Avatar>
<a className={styles['user-name']}>{user.userName}</a>
</a>
</Dropdown>
</div>;
}
}
export default UserCord;
| ed5b1fd2620e271ac3ee11a9c735f57287135f4b | [
"JavaScript"
] | 2 | JavaScript | dengweiping4j/sms-ui | 86ed2e9735ac0e3585238f2ee40da767a67f420b | 1eb120c6bf26ab990df92066dc247e6f3afa3cbc |
refs/heads/main | <file_sep>package br.com.zupacademy.jessica.casadocodigo.repositories;
import br.com.zupacademy.jessica.casadocodigo.models.Categoria;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CategoriaRepository extends CrudRepository<Categoria, Long> {
}
<file_sep># Programa Orange Talents #3
## Desafio 01 - API Casa do Cรณdigo
<file_sep>package br.com.zupacademy.jessica.casadocodigo.controllers;
import br.com.zupacademy.jessica.casadocodigo.models.Autor;
import br.com.zupacademy.jessica.casadocodigo.repositories.AutorRepository;
import br.com.zupacademy.jessica.casadocodigo.requests.CadastrarAutorRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
@RestController
@RequestMapping(path = "autores")
public class AutorController {
private final AutorRepository repository;
public AutorController(AutorRepository repository) {
this.repository = repository;
}
@PostMapping
public ResponseEntity<?> cadastrarAutor(@Valid @RequestBody CadastrarAutorRequest request) {
Autor autor = repository.save(request.toModel());
return new ResponseEntity<>(autor, HttpStatus.OK);
}
}
<file_sep>package br.com.zupacademy.jessica.casadocodigo.requests;
import br.com.zupacademy.jessica.casadocodigo.models.Estado;
import br.com.zupacademy.jessica.casadocodigo.models.Pais;
import br.com.zupacademy.jessica.casadocodigo.requests.validators.EstadoUnicoPorPais;
import br.com.zupacademy.jessica.casadocodigo.requests.validators.MustBeUnique;
import javax.validation.constraints.NotBlank;
@EstadoUnicoPorPais
public class CadastrarEstadoRequest {
@NotBlank(message = "Nome do Estado รฉ obrigatorio")
// @MustBeUnique(domainClass = Estado.class, fieldName = "nome", message = "Estado jรก cadastrado") ?
private String nome;
private Pais pais;
public Estado toModel() { return new Estado(nome, pais); }
public String getNome() { return nome; }
public Pais getPais () { return pais; }
}
<file_sep>package br.com.zupacademy.jessica.casadocodigo.repositories;
import br.com.zupacademy.jessica.casadocodigo.models.Pais;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PaisRepository extends CrudRepository<Pais, Long> {
}
<file_sep>package br.com.zupacademy.jessica.casadocodigo.controllers;
import br.com.zupacademy.jessica.casadocodigo.models.Livro;
import br.com.zupacademy.jessica.casadocodigo.repositories.LivroRepository;
import br.com.zupacademy.jessica.casadocodigo.requests.CadastrarLivroRequest;
import br.com.zupacademy.jessica.casadocodigo.responses.DetalheLivroResponse;
import br.com.zupacademy.jessica.casadocodigo.responses.LivroResponse;
import org.hibernate.annotations.NotFound;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping(path ="livros" )
@Transactional
public class LivroController {
private final LivroRepository repository;
private final EntityManager em;
public LivroController(LivroRepository repository, EntityManager em) {
this.repository = repository;
this.em = em;
}
@PostMapping
public ResponseEntity<?> cadastrarLivro(@Valid @RequestBody CadastrarLivroRequest request) {
Livro livro = repository.save(request.toModel());
em.refresh(livro);
return new ResponseEntity<>(livro, HttpStatus.OK);
}
@GetMapping
public ResponseEntity<?> listarLivros(){
List<LivroResponse> livros = new ArrayList<>();
for (Livro livro : repository.findAll()) {
livros.add(new LivroResponse(livro.getId(), livro.getTitulo()));
}
return new ResponseEntity<>(livros, HttpStatus.OK);
}
@GetMapping(value = "/{id}")
public ResponseEntity<?> detalhe(@PathVariable("id") Long id){
Optional<Livro> optional = repository.findById(id);
if (optional.isPresent()){
Livro livro = optional.get();
return new ResponseEntity<>(new DetalheLivroResponse(livro.getId(), livro.getTitulo(),
livro.getResumo(), livro.getAutor().getNome(), livro.getAutor().getDescricao(),
livro.getPreco(), livro.getSumario(), livro.getPaginas(), livro.getIsbn()), HttpStatus.OK);
}
return ResponseEntity.notFound().build();
}
}
| 45c65e234b7c8b85dcea7440d742e617d95178a3 | [
"Markdown",
"Java"
] | 6 | Java | jehevlin/orange-talents-03-template-casa-do-codigo | 5843cd42a8531c268da64a39064dbfa0638bceff | a6aa4826c95a76802ab2f4168b3a5d57c99601fb |
refs/heads/main | <file_sep>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import defaultImage from '../ImageGallery/default.jpg'
//ะผะตัะพะด ัะพะทะดะฐัั ะฟะพััะฐะป ะธะท ัะตะฐะบั ะดะพะผะฐ
import { createPortal } from 'react-dom';
import './Modal.css';
const modalRoot = document.querySelector('#modal-root');
//ะทะฐะบัััะธะต ะฟะพ ะตัะบะตะนะฟ
export default class Modal extends Component {
//ะฟัะธ ะผะพะฝัะธัะพะฒะฐะฝะธะธ
componentDidMount() {
//console.log('Modal componentDidMount');
window.addEventListener('keydown', this.handleKeyDown);
}
//ะฟัะธ ัะฐะทะผะฐะฝัะธัะพะฒะฐะฝะธะธ ัะธััะธะผ
componentWillUnmount() {
// console.log('Modal componentWillUnmount');
window.removeEventListener('keydown', this.handleKeyDown);
}
handleKeyDown = e => {
if (e.code === 'Escape') {
console.log('ะะฐะถะฐะปะธ ESC, ะฝัะถะฝะพ ะทะฐะบัััั ะผะพะดะฐะปะบั');
//ะฒัะทะฒะฐะปะธ ะฟัะพะฟั
this.props.onClose();
}
};
handleBackdropClick = event => {
this.props.onClose();
};
render() {
const { largeImageURL } = this.props;
return createPortal(
<div className="Overlay" onClick={this.handleBackdropClick}>
<div className="Modal" onClick={e => { e.stopPropagation() }}>
<img src={largeImageURL} alt={largeImageURL} />
</div>
</div>, modalRoot,
);
}
}
Modal.defaultProps = {
largeImageURL: defaultImage,
};
Modal.propTypes = {
largeImage: PropTypes.string,
};
<file_sep>import React from 'react';
import "react-loader-spinner/dist/loader/css/react-spinner-loader.css";
import Loader from "react-loader-spinner";
export default class App extends React.Component {
render() {
return (
<div style={{textAlign: "center", display: "block" }}>
<Loader
text-align="center"
display="block"
type="Puff"
color="#00BFFF"
height={40}
width={40}
timeout={3000} //3 secs
/>
</div>
);
}
}
;
<file_sep>import axios from 'axios';
import PropTypes from 'prop-types';
const fetchHits = ({ searchQuery = '', currentPage = 1, pageSize = 12 }) => {
return axios
.get(`https:pixabay.com/api/?q=${searchQuery}&page=${currentPage}&key=20314649-0be4b13706b99da5b0e7a5a44&image_type=photo&orientation=horizontal&per_page=${pageSize}`,)
.then(response =>
response.data.hits);
};
fetchHits.propTypes = {
searchQuery: PropTypes.string.isRequired,
currentPage: PropTypes.number,
pageSize: PropTypes.number
};
export default { fetchHits }; | 372ecf39af475b35770feffd0fc351066383309a | [
"JavaScript"
] | 3 | JavaScript | Olha-Starykova/goit-react-hw-03-image-finder | 85a918bcba979555a83b42f8098c7f59c4b4787b | 802ac2b102526d73202c5251dfd8079e8d3267f6 |
refs/heads/master | <repo_name>Lochoa11/Lin<file_sep>/README.md
# Lin
<h1>Creating my personal Website</h1><file_sep>/controllers/index.js
const express = require('express');
const router = express.Router();
const bio = require('./bio')
const pricing = require('./pricing')
const signup = require('./signup')
const login = require('./login')
router.use('/alt', require('./alt'));
router.use('/', require('./home'));
router.use('/bio', bio)
router.use('/pricing', pricing)
router.use('/signup', signup)
router.use('/login', login)
module.exports = router;
<file_sep>/public/images/photosOfMe/readme.md
<h4>Photos taken here are all the same aspect ratio </h4> | 0641450834f8e1d9870275bd707a6bac5ac86f02 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | Lochoa11/Lin | d7200e5d38ba098ab77f2cfc76a404179aff9c52 | 9fda50c8275cca17751a08e59e10fadd495d0156 |
refs/heads/master | <file_sep>import React from "react";
import _ from "lodash";
import "./currencyList.scss";
export default function CurrencyList(props) {
const { currencyListItems, currencyName } = props;
return (
<>
<h2 className="header2">List Of Current Exchange Rates:</h2>
<div className="container">
<ul className="currency currency__name">
{currencyName.map((item) => (
<li className="currency__name--item">{item}</li>
))}
</ul>
<ul className="currency currency__dollar">
{_.toArray(currencyListItems).map((item) => (
<li className="currency__dollar--item">{item}</li>
))}
</ul>
</div>
</>
);
}
| 25bc1ed2d74463bd235ee2a4fe590a93e31a9ac0 | [
"JavaScript"
] | 1 | JavaScript | LucasBernardini/currency-conversion | 778c1d6c91ff63e6eb274133e6fd5b58d5a94990 | 60c1bdb708401c7cac56db00dbde7a7cabb05e40 |
refs/heads/main | <repo_name>msc2488/School_District_Analysis<file_sep>/PyCitySchools.py
#!/usr/bin/env python
# coding: utf-8
# In[1]:
# Add the Pandas dependency.
import pandas as pd
# In[2]:
# Files to load
school_data_to_load = "Resources/schools_complete.csv"
student_data_to_load = "Resources/students_complete.csv"
# In[3]:
# Read the school data file and store it in a Pandas DataFrame.
school_data_df = pd.read_csv(school_data_to_load)
school_data_df
# In[4]:
#View first five rows of dataframe
school_data_df.head()
# In[5]:
#view last five rows of dataframe
scool_data_df.tail()
# In[6]:
#view last five rows of dataframe
school_data.df.tail()
# In[7]:
#view last five rows of dataframe
school_data_df.tail()
# In[8]:
# Read the student data file and store it in a Pandas DataFrame.
student_data_df = pd.read_csv(student_data_to_load)
student_data_df.head()
# In[ ]:
<file_sep>/README.md
# School_District_Analysis
School district analysis using Pandas and Juptyer
| 26e81f5e6384672b6445b52e255e9d7c0d4ce7fd | [
"Markdown",
"Python"
] | 2 | Python | msc2488/School_District_Analysis | ddcb223ac23e4f2178abe825344a8d18fae9c405 | 75dc83c188ea7416288a9bb99c14873e4188133c |
refs/heads/master | <repo_name>harissergio/gittut<file_sep>/script.R
#This is a test
#load dataset
students_df <-read.csv("C:/gittut/data/students.csv")
# Look at a summary() of students3
summary(students_df)
# View a histogram of the absences variable
hist(students_df$absences)
# Load libraries
library(ggplot2)
# Load students dataset
students_df <- read.csv("data/students.csv")
# Look at a summary() of students3
summary(students_df)
# View a histogram of the absences variable
ggplot(students_df, aes(students_df$absences)) +
geom_histogram() +
labs(title = "Histogram for absences of Students") +
labs(x = "Absences", y = "Count")
# View a histogram of the absences variable
ggplot(students_df, aes(students_df$absences)) +
geom_histogram(fill = "blue") +
labs(title = "Histogram for absences of Students") +
labs(x = "Absences", y = "Count")
| ed1526c7147613055df5d7c8696ac63eb7cf71fd | [
"R"
] | 1 | R | harissergio/gittut | 94bc35c8ca25a64a5eb467b5ca0939776ae4bae9 | fcff8281d25fd378248da8c03f5b0d67947659c6 |
refs/heads/master | <repo_name>Rahul1907/hubilo<file_sep>/src/components/UsersList.jsx
import React, { useState } from 'react'
import {connect} from 'react-redux'
import {useSelector,useDispatch} from 'react-redux'
import {delUser,deleteMltp} from './Actions/index'
import AddUser from './AddUser';
function UsersList(props) {
const dispatch = useDispatch();
const AllUsers = useSelector((state)=> state.users)
const delUserFun =(e)=>{
dispatch(delUser(e.target.name));
}
const addTodelete=(e)=>{
var name=e.target.name
var userIds=delUserId;
if(e.target.checked){
userIds['ids'].push(name);
}
else{
const ind=userIds['ids'].indexOf(name)
if(ind>-1){
userIds['ids'].splice(ind,1)
}
}
addUserId(prev=>({...prev,userIds}))
}
const deleteIdPass=()=>{
var Ids=delUserId['ids'];
dispatch(deleteMltp(Ids));
delUserId['ids']=[];
}
const [delUserId,addUserId]=useState({ids:[]});
const[delmtp,setMtp]=useState(false);
const [editbtn,setEditBtn]=useState(false)
return (
<div style={{margin:'10px'}}>
<h1>Users</h1>
{AllUsers.map(x=>{
return <div key={x.id}>
<li>Name :<b>{x.name}</b> </li>
<li>Email : <b>{x.email}</b></li>
<li>DOB : <b>{x.dob}</b></li>
<li>Porfolio : <b>{x.portfolio}</b></li>
<li>Hobbies : <b>{x.hobbies}</b></li>
<li>Gender : <b>{x.gender}</b></li>
<li>Skills : <b>{x.skills}</b></li>
{delmtp &&
<div class="form-check">
<input class="form-check-input" type="checkbox" value={x.id} id={x.id} name={x.id} onClick={(e)=>addTodelete(e)}/>
<label class="form-check-label" for={x.id}>
want to Delete ?
</label>
</div>
}
<button onClick={e=>delUserFun(e)} className="btn btn-danger" name={x.id}>Delete</button>
<button onClick={()=>setEditBtn(!editbtn)} className="btn btn-success" name={x.id}>Edit</button>
{editbtn && <div>
<AddUser datapass={x} editDo={editbtn}/>
</div>}
{/* {Object.values(delUserId).length > 1 && <button className="btn btn-dark" onClick={deleteIdPass}> Delete Selected </button> } */}
{/* <button onClick={e=>}>Edit </button> */}
</div>
})}
{AllUsers && AllUsers.length > 1
&& <button className="btn btn-primary" onClick={()=>setMtp(!delmtp)}> Delete Multiple</button>
}
{delUserId['ids'] && delUserId['ids'].length>1 && <button className="btn btn-dark" onClick={deleteIdPass}> Delete Selected </button> }
</div>
)
}
export default connect(
null,
{delUser,deleteMltp}
)(UsersList)
<file_sep>/src/store.js
import { createStore } from 'redux'
import rootReducer from './components/reducers/rootreducers'
const store = createStore(rootReducer);
export default store<file_sep>/src/components/reducers/usersReducer.js
import uuid from 'uuid/dist/v4'
const initialState=[
];
const usersReducer=(state=initialState,action)=>{
switch(action.type){
case 'addUser':
return [...state,{
id:uuid(),
name:action.payload.name,
email:action.payload.email,
dob:action.payload.dob,
portfolio:action.payload.portfolio,
hobbies:action.payload.hobbies,
gender:action.payload.gender,
skills:action.payload.skills,
}]
case 'delUser':
const copyState=[...state];
const i= copyState.findIndex(x=>x.id===action.payload.id);
copyState.splice(i,1);
return [...copyState];
case 'editUser':
const editState=[...state];
const j=editState.findIndex(x=>x.id===action.payload.id);
Object.keys(editState[j]).map(x=>{
editState[j][x]=action.payload[x]
})
return [...editState];
case 'deleteMultiple':
const delState=[...state];
var arr= action.payload;
arr.map(x=>{
const i= delState.findIndex(ab=>ab.id===x);
delState.splice(i,1)
})
return[...delState]
default:
return state;
}
}
export default usersReducer | 4b293a42cf9a8f66b895be102c2d9a375a02420d | [
"JavaScript"
] | 3 | JavaScript | Rahul1907/hubilo | 7ac3eda54e56bfab690c41498698576e4e17d17c | 17b61da5f56b84505bae29cf3ad31b0d3f8f7383 |
refs/heads/master | <repo_name>danfergo/FeupVolley<file_sep>/Assets/OnGroundTouch.cs
๏ปฟusing UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class OnGroundTouch : MonoBehaviour {
private Rigidbody rb;
private GameController gameController;
void Start(){
rb = GetComponent<Rigidbody>();
gameController = GetComponent<GameController> ();
}
void OnCollisionExit(Collision collision){
Transform other = collision.gameObject.transform;
if(other.name == "Ground")
{
if(rb.position.z > 9)
{
gameController.pointTo (0);
}
else
{
gameController.pointTo (1);
}
}
}
}
<file_sep>/Assets/Scripts/TouchUp.cs
๏ปฟusing UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class TouchUp : MonoBehaviour {
private Vector3 airTargetPosition;
private Vector3 groundTargetPosition;
private float airStrikeHeight = 7.0f;
private Rigidbody rb;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody>();
airTargetPosition = new Vector3 (4.5f, 9.0f, 9f); // x position is not relevant since it's the players x velocity
groundTargetPosition = new Vector3 (4.5f, 8f, 9f); // x position is not relevant since it's the players x velocity
}
void OnCollisionExit(Collision collision){
Transform other = collision.gameObject.transform;
//Debug.Log (other.tag);
if (other.tag == "Player") {
//Rigidbody otherRb = collision.gameObject.GetComponent<Rigidbody>();
if (other.transform.position.y < airStrikeHeight) {
Vector3 assistedVelocity = (airTargetPosition - other.position).normalized * 10.0f;
rb.velocity = assistedVelocity; // new Vector3(rb.velocity.normalized.x * 15.0f, assistedVelocity.y, assistedVelocity.z);
} else {
// Debug.Log ("Down Strike!");
Vector3 assistedVelocity = (groundTargetPosition - other.position).normalized * 10.0f;
rb.velocity = assistedVelocity; // new Vector3(rb.velocity.normalized.x * 20.0f, assistedVelocity.y, assistedVelocity.z);
}
}
}
}
<file_sep>/Assets/GameController.cs
๏ปฟusing UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GameController : MonoBehaviour {
//related to UI updates
public Transform winningMessage;
public Transform player1;
public Transform player2;
public GameObject ballFallPositionHelper;
public Text [] playersScores;
public Text [] playersNames;
public Transform [] pointToMessages;
private Rigidbody rb;
private int [] pointCounters = {0,0};
private float sleepingDuration = 1.0f;
float sleepingBetweenTurns = -1;
int gameStartedBy = 1;
void Start(){
rb = this.GetComponent<Rigidbody> ();
RestartGame ();
sleepingBetweenTurns = sleepingDuration; // start immediately
}
private void setWinner(string winnerMessage){
foreach (Transform msg in winningMessage) {
Text txt = msg.gameObject.GetComponent<Text> ();
if(txt) txt.text = winnerMessage;
}
winningMessage.gameObject.SetActive(true);
ballFallPositionHelper.SetActive (false);
}
public void pointTo(int id){
if (++pointCounters [id] == 5) {
setWinner (playersNames [id].text + " wins!");
positionBallForPlayer (id == 0 ? 1 : 0);
sleepingBetweenTurns = -1; // stop ball indefinitely
} else {
positionBallForPlayer (gameStartedBy == 0 ? 1 : 0);
pointToMessages [id].gameObject.SetActive (true);
ballFallPositionHelper.SetActive (false);
}
playersScores[id].text = pointCounters[id].ToString();
}
private void positionBallForPlayer(int id){
this.transform.position = new Vector3 (4.5f, 12f, id*9f + 4.5f);
rb.velocity = new Vector3(0,0,0);
rb.angularVelocity = new Vector3(0,0,0);
rb.isKinematic = true;
sleepingBetweenTurns = 0;
}
private void resume(){
rb.isKinematic = false;
pointToMessages [0].gameObject.SetActive (false);
pointToMessages [1].gameObject.SetActive (false);
player1.position = new Vector3 (4.5f, 1f, 4.5f);
player2.position = new Vector3 (4.5f, 1f, 13.5f);
ballFallPositionHelper.SetActive (true);
}
void Update(){
if (sleepingBetweenTurns >= 0) {
sleepingBetweenTurns += Time.deltaTime;
if (sleepingBetweenTurns > sleepingDuration) {
resume ();
sleepingBetweenTurns = -1;
}
}
}
public void RestartGame(){
pointCounters[0] = 0;
pointCounters[1] = 0;
winningMessage.gameObject.SetActive(false);
resume ();
}
}
<file_sep>/Assets/Scripts/SlowGravity.cs
๏ปฟusing UnityEngine;
using System.Collections;
public class SlowGravity : MonoBehaviour {
Rigidbody rb;
public float antiGravity;
private LineRenderer lineRenderer;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody>();
lineRenderer = GetComponent<LineRenderer>();
}
// Update is called once per frame
void FixedUpdate () {
if (GetComponent<Rigidbody>().useGravity)
rb.AddForce(Physics.gravity* -1 * antiGravity * rb.mass);
// predict(this.transform.position, this.GetComponent<Rigidbody>().velocity, new Vector3(0, -10, 0));
}
/* void OnCollisionExit(Collision other) {
// if(other === )
Debug.Log("xxx");
}*/
void predict(Vector3 initialPosition, Vector3 initialVelocity, Vector3 gravity) {
Vector3 last_pos = initialPosition;
Vector3 velocity = initialVelocity;
lineRenderer.SetVertexCount(1);
lineRenderer.SetPosition(0, last_pos);
int i = 1;
int hitCounter = 0;
while (i < 3000)
{
velocity += gravity * Time.fixedDeltaTime;
RaycastHit hit, realHit;
if (Physics.SphereCast(last_pos,1.25f , (last_pos + (velocity * Time.fixedDeltaTime)), out hit))
{
Physics.Linecast (last_pos, hit.point, out realHit);
Debug.Log (realHit.normal);
Debug.Log(Vector3.Reflect(velocity , realHit.normal));
velocity = Vector3.Reflect(velocity * 0.9f, realHit.normal);
last_pos = hit.point;
hitCounter++;
if (hitCounter == 2) {
return;
}
//hit.collider.gameObject
}
lineRenderer.SetVertexCount(i + 1);
lineRenderer.SetPosition(i, last_pos);
last_pos += velocity * Time.fixedDeltaTime;
i++;
}
/* int numSteps = 5; // for example
Vector3 velocity = initialVelocity;
Vector3 last_pos = initialPosition;
lineRenderer.SetVertexCount(1);
lineRenderer.SetPosition(0, last_pos);
int i = 1;
while (i < numSteps)
{
velocity += gravity * Time.fixedDeltaTime;
RaycastHit hit;
if (Physics.Linecast(velocity, (velocity + (initialVelocity * Time.fixedDeltaTime)), out hit))
{
velocity = Vector3.Reflect(initialVelocity * 0.5f, hit.normal);
last_pos = hit.point;
}
lineRenderer.SetVertexCount(i + 1);
lineRenderer.SetPosition(i, last_pos);
last_pos += velocity * Time.fixedDeltaTime;
i++;
}*/
}
void UpdateTrajectory(Vector3 initialPosition, Vector3 initialVelocity, Vector3 gravity)
{
int numSteps = 15; // for example
float timeDelta = .5f / initialVelocity.magnitude; // for example
lineRenderer.SetVertexCount(numSteps);
Vector3 position = initialPosition;
Vector3 velocity = initialVelocity;
for (int i = 0; i < numSteps; ++i)
{
lineRenderer.SetPosition(i, position);
position += velocity * timeDelta + 0.5f * gravity * timeDelta * timeDelta;
velocity += gravity * timeDelta;
}
}
}
<file_sep>/Assets/Scripts/AudienceController.cs
๏ปฟusing UnityEngine;
using System.Collections;
public class AudienceController : MonoBehaviour {
private string[] names = { "idle", "applause", "applause2", "celebration", "celebration2", "celebration3" };
// Use this for initialization
void Start () {
Animation[] AudienceMembers = gameObject.GetComponentsInChildren<Animation>();
foreach (Animation anim in AudienceMembers)
{
string thisAnimation = names[Random.Range(0, 5)];
anim.wrapMode = WrapMode.Loop;
anim.GetComponent<Animation>().CrossFade(thisAnimation);
anim[thisAnimation].time = Random.Range(0f, 3f);
}
}
// Update is called once per frame
void Update()
{
}
}
<file_sep>/Assets/powerUpController.cs
๏ปฟusing UnityEngine;
using System.Collections;
using UnityStandardAssets.Characters.ThirdPerson;
using UnityEngine.UI;
public class powerUpController : MonoBehaviour
{
public GameObject player1, player2;
public GameObject canvasText, shadow;
private enum powerUps { NoDie, lowJump, lowSpeed,Null }
private powerUps current_powerup;
private bool playerWithPowerUp;
private float spawnPowerUp, time_playerhadwithpowerup;
private int player_to_give_powerUp; // [1|2]
// Use this for initialization
void Start()
{
playerWithPowerUp = false;
spawnPowerUp = 0;
time_playerhadwithpowerup = 0;
current_powerup = powerUps.Null;
}
// Update is called once per frame
void Update()
{
// Rotate cube for neat(ish) purposes
transform.RotateAround(transform.position, new Vector3(0, 0, 1), Time.deltaTime * 90f);
// Check if a power needs to stop
if ( (playerWithPowerUp && Time.time - time_playerhadwithpowerup > 10) || (!playerWithPowerUp && Time.time - spawnPowerUp > 10))
{
spawnPowerUp = Time.time;
if (playerWithPowerUp)
{
usePowerUps(player_to_give_powerUp, false);
current_powerup = powerUps.Null;
playerWithPowerUp = false;
}
}
// Check if a powerUp can spawn
if (current_powerup == powerUps.Null)
{
// can generate a powerUp
if (Random.Range(0, 1000) == 1)
{
current_powerup = (powerUps)Random.Range(0, System.Enum.GetNames(typeof(powerUps)).Length - 1);
spawnPowerUp = Time.time;
}
}
// Check if we need to render the object
GetComponent<MeshRenderer>().enabled = current_powerup != powerUps.Null && !playerWithPowerUp;
GetComponent<Collider>().enabled = current_powerup != powerUps.Null && !playerWithPowerUp;
}
void OnTriggerEnter(Collider obj)
{
if (obj.gameObject.tag == "Ball")
{
player_to_give_powerUp = playerImpact.playerCollision;
time_playerhadwithpowerup = Time.time;
playerWithPowerUp = true;
usePowerUps(player_to_give_powerUp, true);
canvasText.SetActive(true);
canvasText.GetComponent<Text>().text = current_powerup.ToString();
shadow.SetActive(true);
shadow.GetComponent<Text>().text = current_powerup.ToString();
StartCoroutine(desactivateCanvas());
}
}
void usePowerUps(int player, bool activate)
{
switch (current_powerup)
{
case powerUps.lowJump:
if (player == 1)
{
if (activate)
player2.GetComponentInChildren<ThirdPersonCharacter>().m_JumpPower = 5f;
else
player2.GetComponentInChildren<ThirdPersonCharacter>().m_JumpPower = 10f;
}
else
{
if (activate)
player1.GetComponentInChildren<ThirdPersonCharacter>().m_JumpPower = 5f;
else
player1.GetComponentInChildren<ThirdPersonCharacter>().m_JumpPower = 10f;
}
break;
case powerUps.NoDie:
playerImpact.activePowerUp = activate;
playerImpact.playerWithNoDie = player;
break;
case powerUps.lowSpeed:
if (player == 1)
{
if (activate)
player2.GetComponentInChildren<ThirdPersonCharacter>().m_MoveSpeedMultiplier = 0.8f;
else
player2.GetComponentInChildren<ThirdPersonCharacter>().m_JumpPower = 1.2f;
}
else
{
if (activate)
player1.GetComponentInChildren<ThirdPersonCharacter>().m_JumpPower = 0.8f;
else
player1.GetComponentInChildren<ThirdPersonCharacter>().m_JumpPower = 1.2f;
}
break;
default:
break;
}
}
IEnumerator desactivateCanvas()
{
yield return new WaitForSeconds(2);
canvasText.SetActive(false);
shadow.SetActive(false);
}
}
<file_sep>/Assets/playerImpact.cs
๏ปฟusing UnityEngine;
using System.Collections;
public class playerImpact : MonoBehaviour {
public static int playerCollision;
public static int playerWithNoDie;
public static bool activePowerUp;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (playerWithNoDie == 1 && transform.position.z < 9)
{
if (transform.position.y < 4 && activePowerUp)
{
transform.position = new Vector3(transform.position.x, 4.1f, transform.position.z);
}
} else if (playerWithNoDie == 2 && transform.position.z > 9)
{
if (transform.position.y < 4 && activePowerUp)
{
transform.position = new Vector3(transform.position.x, 4.1f, transform.position.z);
}
}
}
void OnCollisionEnter(Collision obj)
{
if (obj.gameObject.tag == "Player")
{
if (obj.gameObject.name == "ThirdPersonController1")
playerCollision = 1;
else playerCollision = 2;
}
}
}
<file_sep>/Assets/Scripts/CameraController.cs
๏ปฟusing UnityEngine;
public class CameraController : MonoBehaviour
{
public Camera thisCamera;
public GameObject ball;
public GameObject player1, player2;
public GameObject net;
public float speed;
private float anguloFeito, originalFieldOfView;
private bool initialMove = true, alreadyLooking = false, rotatePlayer, didCheer = false;
private Vector3 Camera_initialPosition, Camera_initialRotation;
private int playerOnFocus;
private int playerWithTheboo;
// Use this for initialization
void Start()
{
rotatePlayer = false;
playerOnFocus = 1;
anguloFeito = 0;
originalFieldOfView = thisCamera.fieldOfView;
Camera_initialPosition = thisCamera.transform.position;
Camera_initialRotation = thisCamera.transform.eulerAngles;
transform.LookAt(net.transform.position);
playerWithTheboo = Random.Range(1, 3);
GameObject.FindGameObjectWithTag("Ball").GetComponent<Rigidbody>().useGravity = false;
//initialMove = false;
}
// Update is called once per frame
void Update()
{
if (initialMove)
{
// Show Player 2 on camera
if (anguloFeito > 90)
{
if (playerOnFocus == 1)
{
if (playerWithTheboo == 1)
playBooSound();
else playCheerSound();
playerCamera(player1);
}
else
{
if (playerWithTheboo == 1)
playCheerSound();
else playBooSound();
playerCamera(player2);
}
}
else
{
transform.RotateAround(net.transform.position, Vector3.up, speed * Time.deltaTime);
anguloFeito += speed * Time.deltaTime;
}
} else {
transform.position = Camera_initialPosition;
transform.eulerAngles = Camera_initialRotation;
transform.LookAt(net.transform.position);
GameObject.FindGameObjectWithTag("Ball").GetComponent<Rigidbody>().useGravity = true;
adjustingCamera();
}
}
void playerCamera(GameObject player)
{
float z = 4f, angle = 80;
if (player2 == player)
{
z = 13.5f;
angle = -120;
}
// Change camera position
transform.position = new Vector3(15, 5, z);
transform.eulerAngles = new Vector3(13, -85, 1.6f);
// Make the player look directly to the camera
if (!rotatePlayer)
{
player.transform.LookAt (thisCamera.transform.position);
rotatePlayer = true;
}
// Make the player start the animation
if (!alreadyLooking)
{
player.GetComponent<Animator>().SetBool("Inicio", true);
transform.LookAt(player.transform.position);
alreadyLooking = true;
}
if (player.GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).IsName("Cheer"))
{
didCheer = true;
}
if (didCheer && player.GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).IsName("Grounded") && player.GetComponent<Animator>().GetBool("Inicio"))
{
if (player == player2)
{
// Initial animation is over
initialMove = false;
}
playerOnFocus = 2;
player.GetComponent<Animator>().SetBool("Inicio", false);
didCheer = false;
player.transform.Rotate(new Vector3(0, - angle, 0));
rotatePlayer = false;
alreadyLooking = false;
// Avoid any reload.
}
}
// Play boo sound
void playBooSound()
{
AudioSource[] temp = GameObject.FindGameObjectWithTag("Boo_Sound").GetComponents<AudioSource>();
AudioSource[] temp_1 = GameObject.FindGameObjectWithTag("Cheer_Sound").GetComponents<AudioSource>();
AudioSource[] temp_2 = GameObject.FindGameObjectWithTag("General_Sound").GetComponents<AudioSource>();
// Play boo sound
for (var i = 0; i < temp.Length; i++)
{
if (!temp[i].isPlaying)
{
temp[i].volume = 0.3f;
temp[i].Play();
}
}
// Stop Cheer sound if playing
for (var i = 0; i < temp_1.Length; i++)
{
if (temp_1[i].isPlaying)
{
temp_1[i].volume = 0.0f;
temp_1[i].Stop();
}
}
// Reduce the ambient sound
for (var i = 0; i < temp_2.Length; i++)
{
if (temp_2[i].isPlaying)
{
temp_2[i].volume = 0.1f;
}
}
}
// Play Cheer sound
void playCheerSound()
{
AudioSource[] temp = GameObject.FindGameObjectWithTag("Boo_Sound").GetComponents<AudioSource>();
AudioSource[] temp_1 = GameObject.FindGameObjectWithTag("Cheer_Sound").GetComponents<AudioSource>();
AudioSource[] temp_2 = GameObject.FindGameObjectWithTag("General_Sound").GetComponents<AudioSource>();
// Stop boo sound
for (var i = 0; i < temp.Length; i++)
{
if (temp[i].isPlaying)
{
temp[i].volume = 0.0f;
temp[i].Stop();
}
}
// Play Cheer sound if playing
for (var i = 0; i < temp_1.Length; i++)
{
if (!temp_1[i].isPlaying)
{
temp_1[i].volume = 0.4f;
temp_1[i].Play();
}
}
// Reduce the ambient sound
for (var i = 0; i < temp_2.Length; i++)
{
if (temp_2[i].isPlaying)
{
temp_2[i].volume = 0.1f;
}
}
}
// Adjusting camera according to ball position
void adjustingCamera()
{
if (ball.transform.position.y >= 9)
{
// Check if ball is going up
if (ball.GetComponent<Rigidbody>().velocity.y > 0)
{
thisCamera.fieldOfView = Mathf.Lerp(thisCamera.fieldOfView, 70, Time.deltaTime * speed);
} else
{
thisCamera.fieldOfView = Mathf.Lerp(thisCamera.fieldOfView, 40, Time.deltaTime * speed);
}
}
}
}<file_sep>/Assets/Scripts/Helpers.cs
๏ปฟusing UnityEngine;
using System.Collections;
public class Helpers : MonoBehaviour {
public Transform ballPositionHelper;
public Transform ballFallPositionHelper;
public Vector3 ballFallPosition;
// Use this for initialization
void Start () {
ballPositionHelper.position = new Vector3 (transform.position.x, 0.1f, transform.position.z);
ballFallPositionHelper.position = new Vector3 (ballPositionHelper.position.x, 0.1f, ballPositionHelper.position.z);
ballFallPosition = ballFallPositionHelper.position;
}
// Update is called once per frame
void Update(){
// ball position helper
ballPositionHelper.position = new Vector3(transform.position.x, 0.1f ,transform.position.z);
float helperZoom = transform.position.y == 0 ? transform.localScale.x : transform.localScale.x / transform.position.y;
ballPositionHelper.localScale = new Vector3 (helperZoom, 0.0f, helperZoom);
//ball fall final position helper
Vector3 bfP = predictBallFallPosition(this.transform.position, this.GetComponent<Rigidbody>().velocity, new Vector3(0, -10, 0));
if (bfP.x > 0) {
ballFallPosition = new Vector3 (bfP.x, 0.1f, bfP.z);
}
float step = 20.0f * Time.deltaTime;
ballFallPositionHelper.position = Vector3.MoveTowards (ballFallPositionHelper.position, ballFallPosition, step);
}
Vector3 predictBallFallPosition(Vector3 initialPosition, Vector3 initialVelocity, Vector3 gravity) {
Vector3 last_pos = initialPosition;
Vector3 velocity = initialVelocity;
int hitCounter = 0;
for (int i = 0; i < 300; i++) {
velocity += gravity * Time.fixedDeltaTime;
RaycastHit hit;
// Debug.Log ((float)gameObject.GetComponent<SphereCollider> ().radius);
float maxDistance = (velocity * Time.fixedDeltaTime).magnitude;
if (Physics.SphereCast(last_pos,0.75f, velocity * Time.fixedDeltaTime,out hit, maxDistance)) {
//hitted = Physics.Linecast(last_pos + velocity * Time.fixedDeltaTime, sphereHit.point, out hit);
//Debug.Log ("shpere hit: " + sphereHit.collider.gameObject.transform.name);
//Debug.Log ("Hit! " + sphereHit.point);
// Debug.Log ("Hitted: " + hitted);
//Debug.Log ("Hitted: " + hit.collider.gameObject.transform.name);
velocity = Vector3.Reflect (velocity , hit.normal);
last_pos = hit.point;
//if(hitted)
if (hit.collider.gameObject.transform.name == "Ground" || hit.collider.gameObject.transform.name=="Sphere"
|| hit.collider.gameObject.transform.tag == "Player") {
return last_pos;
}
hitCounter++;
if (hitCounter == 5) {
break;
}
}
last_pos += velocity * Time.fixedDeltaTime;
}
return new Vector3(-999.0f, -999.0f, -999.0f);
}
}
| ad14e329f648576e713a85503bf16be9b59e3790 | [
"C#"
] | 9 | C# | danfergo/FeupVolley | e1d3365320b0f35698a92d3826d21d190aed1a78 | d8035be0c1cdd73ec434db43cb6946b90c2e1507 |
refs/heads/master | <file_sep>from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return render(request,'home/home.html')
def contact(request):
return render(request,'home/contact.html')
def draw(request):
return render(request,'home/draw.html')
| d4fa2f2842ee4667e3def6cd3b8343a309f70fcf | [
"Python"
] | 1 | Python | mostly-dumb/hi | 1b6d894e5ee1c025021a865fea68e92a4fb91ca0 | 952ce3e1e845dc453dcac78e65e1edc6ffd434af |
refs/heads/main | <repo_name>addy123d/covidResource<file_sep>/public/main.js
console.log("Welcome to covid resource !");
const city = document.querySelector("#city");
const generateLink = document.querySelector("#linkGenerate");
const checkVerify = document.querySelector("#verify");
const unverifyTweets = document.querySelector("#unverify");
checkVerify.addEventListener("click", () => {
if (checkVerify.checked) {
alert("Keep this unchecked for small cities !");
}
})
// Link generation
const generationContainer = document.querySelector(".contain");
// Multiselect Logic !
function btnToggle() {
document.getElementById("Dropdown").classList.toggle("show");
}
// Prevents menu from closing when clicked inside
document.getElementById("Dropdown").addEventListener('click', function (event) {
// alert("click outside");
event.stopPropagation();
});
// Closes the menu in the event of outside click
window.onclick = function (event) {
if (!event.target.matches('.dropbutton')) {
var dropdowns =
document.getElementsByClassName("dropdownmenu-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
// Items collection !
const items = [];
function itemclick(i) {
items.push(i);
console.log("Items :", items);
}
// Generate Item url !
function generateItemURL(items) {
let url = "(";
for (let i = 0; i < items.length; i++) {
url += items[i];
url += "+OR+"
}
url += ")";
return url.replace(/OR\s$/g, "");
}
function addVerify() {
let option;
if (checkVerify.checked) {
option = "verified+";
} else {
option = "";
}
console.log("Option : ", option);
return option;
}
function unverifyURL() {
let option = "";
if (unverifyTweets.checked) {
option += `+-`;
option += '"not+verified"';
option += "+-";
option += '"unverified"';
} else {
option = "";
}
return option;
}
// CSS list
const itemsList = document.querySelector("#list");
const showList = document.querySelector(".show");
const showList2 = document.querySelector(".show-2");
// https://twitter.com/search?q=verified+Mumbai+%28bed+OR+beds+OR+icu+OR+oxygen+OR+ventilator+OR+ventilators+OR+fabiflu+OR+remdesivir%29+-%22not+verified%22+-%22unverified%22+-%22needed%22+-%22required%22&f=live
generateLink.addEventListener("click", () => {
if (city.value === "") {
alert("Please Enter City Name !");
} else {
if (document.querySelector("#other_item").value != "") {
items.push(document.querySelector("#other_item").value);
}
console.log("Item URL : ", generateItemURL(items));
let url = "https://twitter.com/search?q=";
url += addVerify();
url += city.value.replace(/\s/g, "") + "+";
url += generateItemURL(items);
url += unverifyURL();
url += "&f=live"
console.log(url);
showList2.style.display = "none";
showList.style.display = "none";
document.querySelector(".page").classList.toggle("active");
generationContainer.classList.toggle("active");
document.querySelector("#twitter_link").value = url;
}
});
document.querySelector("#back").addEventListener("click", () => {
document.querySelector(".page").classList.toggle("active");
generationContainer.classList.toggle("active");
location.reload();
})
// Vist Twitter Page
document.querySelector("#button").addEventListener("click", () => {
window.open(document.querySelector("#twitter_link").value);
})
showList.addEventListener("click", () => {
itemsList.classList.toggle("active");
document.querySelector(".page").classList.toggle("active");
});
showList2.addEventListener("click", () => {
itemsList.classList.toggle("active");
document.querySelector(".page").classList.toggle("active");
});
function showItem() {
document.querySelector("#number").innerText = items.length;
document.querySelector("#number-2").innerText = items.length;
let html = "";
for (let i = 0; i < items.length; i++) {
html += `<li>${items[i]}</li>`;
}
itemsList.innerHTML = html;
} | 7954703b4879ece025b920e4f1b346137f5d2ee1 | [
"JavaScript"
] | 1 | JavaScript | addy123d/covidResource | 2e258c940dc4d8b484f25f4866449d0ca62cae12 | 6f3120dddea86a28dca575be071c3d7f85eeba37 |
refs/heads/master | <repo_name>fvillena/psychology_nlp<file_sep>/src/models/download_embeddings.sh
wget -P ../../models/ http://cs.famaf.unc.edu.ar/~ccardellino/SBWCE/SBW-vectors-300-min5.bin.gz
tar zxvf ../../models/SBW-vectors-300-min5.bin.gz.tar.gz
rm ../../models/SBW-vectors-300-min5.bin.gz.tar.gz
<file_sep>/README.md
# Natural Language Processing in Psychology
To prepare the environment first you have to download the Spanish Billion Words Embeddings
* `http://cs.famaf.unc.edu.ar/~ccardellino/SBWCE/SBW-vectors-300-min5.bin.gz`
* `https://cs.famaf.unc.edu.ar/~ccardellino/SBWCE/SBW-vectors-300-min5-skipgram.txt.bz2`
Extract and locate both files on `/models/` . Then move the raw datasets into `/data/raw/` .
<file_sep>/src/data/make_fluency_dataset.py
import numpy as np
import pandas as pd
import re
import os
import json
def removeSpaces(word):
word = re.sub(r' +$','',word)
word = re.sub(r'^ +','',word)
word = re.sub(r' +','_',word)
return word
raw_data = pd.ExcelFile(r'../../data/raw/Registro Fluidez 7 prueba mac.xlsx')
sheets = raw_data.sheet_names
for sheet in sheets:
pd.read_excel(raw_data, sheet).to_csv(
r'../../data/interim/interim_fluency_'+sheet+'.csv',
encoding='utf-8',
index=False,
header=False
)
semantic_fluency = {sheet:{} for sheet in sheets if not sheet.endswith('_color')}
for csv in os.listdir(r'../../data/interim/'):
if not csv.endswith('_color.csv'):
with open(r'../../data/interim/'+csv, encoding='utf-8') as file:
with open(r'../../data/interim/'+csv.replace('.csv','_color.csv'), encoding='utf-8') as color:
color_lines = color.readlines()
for line_number,line in enumerate(file):
line = line.rstrip().split(',')
if line[0] != '':
test = csv.replace('interim_fluency_','').replace('.csv','')
subject = int(float(line[0])) if '.' in line[0] else int(line[0])
words = line[1:]
words = [removeSpaces(word) for word in words if len(word)>0]
correct = color_lines[line_number].rstrip().split(',')[1:][:len(words)]
correct = [False if color == "6" else True for color in correct]
semantic_fluency[test][subject] = {}
# print(test)
# print(subject)
# print(len(words))
# print(len(correct))
# print('#####')
assert(len(words) == len(correct))
semantic_fluency[test][subject]['words'] = words
semantic_fluency[test][subject]['correct'] = correct
with open(r'../../data/processed/semantic_fluency.json', 'w', encoding='utf-8') as json_file:
json.dump(semantic_fluency, json_file, indent=4, ensure_ascii=False) | 97678d5ef2361959887e2b77b2be1eff2174b303 | [
"Markdown",
"Python",
"Shell"
] | 3 | Shell | fvillena/psychology_nlp | 05bef6b0c0a4b2470f1ac5a660c01aa90f085adb | 9973e7dd208bd19741ae359c8e9f69fbaabb8f09 |
refs/heads/master | <repo_name>hana00033/taku20183<file_sep>/config/routes.rb
Rails.application.routes.draw do
devise_for :users
get "lessons/index" => "lessons#index"
get "lessons/about" => "lessons#about"
get "lessons/graph" => "lessons#graph"
get "lessons/credit" => "lessons#credit"
get "lessons/monday" => "lessons#monday"
get "lessons/thuesday" => "lessons#thuesday"
get "lessons/wednesday" => "lessons#wednesday"
get "lessons/thursday" =>"lessons#thursday"
get "lessons/friday" => "lessons#friday"
get "lessons/saturday" => "lessons#saturday"
get '/lessons/:id/edit2', to: 'lessons#edit2', as: 'edit2_lesson'
patch '/lessons/:id/plus', to: 'lessons#plus', as: 'plus_lesson'
resources :lessons
get 'home/index' => "home#index"
authenticated :users do
root :to => "lessons#index"
end
unauthenticated :users do
root :to => "home#index"
end
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
<file_sep>/db/migrate/20180808084445_add_defauls_to_lessons.rb
class AddDefaulsToLessons < ActiveRecord::Migration[5.2]
def change
change_column_default :lessons, :absence_count, 0
end
end
<file_sep>/db/migrate/20180808075935_create_lessons.rb
class CreateLessons < ActiveRecord::Migration[5.2]
def change
create_table :lessons do |t|
# userใขใใซใฎuser_idใซ็ตใณใคใใใใใๅฟ
่ฆ
t.integer :user_id, null: true
#ๆๆฅญๅ
t.string :name, null: true
# ่ชฌๆ
t.text :description, null: true
# ๆๆๅ
t.string :teacher_name, null: true
# ๅไฝ
t.integer :credit, null: true
# ๅญฆๅนด
t.integer :grade, null: true
# ๅญฆๆ
t.integer :term, null: true
#ๆๆฅ
t.integer :week, null: true
#ไฝ้ใ
t.integer :period, null: true
#ๆฌ ๅธญๆฐ
t.float :absence_count, null: true
t.timestamps
end
end
end
<file_sep>/app/controllers/lessons_controller.rb
class LessonsController < ApplicationController
#่ช่จผๆธใฟใงใใใใจใ็ขบ่ช
before_action :authenticate_user!
def index
@lessons = current_user.lessons
end
def show
@lesson = target_lesson params[:id]
end
def new
@lesson = Lesson.new
end
def create
@lesson = current_user.lessons.new lesson_params
@lesson.save!
redirect_to @lesson
end
def edit
@lesson = target_lesson params[:id]
end
def update
@lesson = target_lesson params[:id]
@lesson.update(lesson_params)
redirect_to @lesson
end
def destroy
@lesson = target_lesson params[:id]
@lesson.destroy
redirect_to lessons_url
end
def about
@lesson = target_lesson params[:id]
end
def graph
@lesson = target_lesson params[:id]
end
def credit
@amount = 0
@lessons = current_user.lessons
@lessons.each do |lesson|
@amount += lesson.credit.to_i
end
@am = current_user.amount_credit.to_i
gon.data1 = [@amount , @am - @amount]
end
def monday
@lessons = current_user.lessons.where(week: 0)
gon.absence1 = []
gon.name1 = []
if @lessons
@lessons.each do |lesson|
gon.absence1 = gon.absence1.push(lesson.absence_count)
gon.name1 = gon.name1.push(lesson.name)
end
@a = gon.name1
@b = gon.absence_count1
end
end
def thuesday
@lessons = current_user.lessons.where(week: 1)
gon.absence2 = []
gon.name2 = []
if @lessons
@lessons.each do |lesson|
gon.absence2 = gon.absence2.push(lesson.absence_count)
gon.name2 = gon.name2.push(lesson.name)
end
@a = gon.name2
@b = gon.absence_count2
end
end
def wednesday
@lessons = current_user.lessons.where(week: 2)
gon.absence3 = []
gon.name3 = []
if @lessons
@lessons.each do |lesson|
gon.absence3 = gon.absence3.push(lesson.absence_count)
gon.name3 = gon.name3.push(lesson.name)
end
@a = gon.name3
@b = gon.absence_count3
end
end
def thursday
@lessons = current_user.lessons.where(week: 3)
gon.absence4 = []
gon.name4 = []
if @lessons
@lessons.each do |lesson|
gon.absence4 = gon.absence4.push(lesson.absence_count)
gon.name4 = gon.name4.push(lesson.name)
end
@a = gon.name4
@b = gon.absence_count4
end
end
def friday
@lessons = current_user.lessons.where(week: 4)
gon.absence5 = []
gon.name5 = []
if @lessons
@lessons.each do |lesson|
gon.absence5 = gon.absence5.push(lesson.absence_count)
gon.name5 = gon.name5.push(lesson.name)
end
@a = gon.name5
@b = gon.absence_count5
end
end
def saturday
@lessons = current_user.lessons.where(week: 5)
gon.absence6 = []
gon.name6 = []
if @lessons
@lessons.each do |lesson|
gon.absence6 = gon.absence6.push(lesson.absence_count)
gon.name6 = gon.name6.push(lesson.name)
end
@a = gon.name6
@b = gon.absence_count6
end
end
def edit2
@lesson = target_lesson params[:id]
# @lesson = Lesson.find(params[:id])
end
def plus
@lesson = target_lesson params[:id]
@lesson.absence_count = 5.0;
@lesson.update(lesson_params)
redirect_to edit2_lesson_path
end
private
def target_lesson lesson_id
current_user.lessons.where(id: lesson_id).take
end
def lesson_params
params.require(:lesson).permit(:name, :description, :teacher_name, :credit, :grade, :term, :week, :period, :absence_count)
end
end
| 5ee71cd72fa5455f72e111aa80b983c82a466b23 | [
"Ruby"
] | 4 | Ruby | hana00033/taku20183 | a5f8badaa26e4e815242ff741256151366a3b196 | 4bff3f2c315b106397b911db47228dbf7fc3406a |
refs/heads/master | <repo_name>sahiltorkadi/cognizant-training-practice<file_sep>/Sahil/Pixogram-master/pixogram/1st.html
<!DOCTYPE html>
<html>
<title>css programe</title>
<style>
h1#abc {color:orange; font-size:80px;}
h1#xyz {color:green; font-size:65px;}
h1#mno {color:red; font-size:48px;}
</style>
<body>
<h1>HTML tags with id selector<span>#</span></h1>
<hr>
<h1 id="abc"<xmp>h1</xmp> tag with id="abc"</h1>
<h1 id="xyz"<xmp>h1</xmp> tag with id="xyz"</h1>
<h1 id="mno"<xmp>h1</xmp> tag with id="mno"</h1>
</body>
</html><file_sep>/Sahil/workspace/CTS/src/com/cts/practice/Pattern.java
package com.cts.practice;
public class Pattern
{
public void pattern1(int rows)
{
int i,j;
for (i = 1; i <= rows; i++)
{
for ( j = i; j <= rows; j++)
{
System.out.printf(" ");
}
for (j = 1; j <= i; j++)
{
System.out.printf("%d",j);
}
for (j = i-1; j >= 1; j--)
{
System.out.printf("%d",j);
}
System.out.println();
}
}
public void pattern2(int rows)
{
int n = 5;
for (int i = 0; i < n; i++) {
int number = 1;
System.out.printf("%" + (n - i) * 2 + "s", "");
for (int j = 0; j <= i; j++)
{
System.out.printf("%4d", number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
public class Words
{
}
public class Expand
{
}
}
<file_sep>/Sahil/workspace/CTS/src/com/cts/client/MyApp.java
package com.cts.client;
import java.util.Scanner;
import com.cts.practice.ArrayImpl;
import com.cts.practice.Calculate;
import com.cts.practice.Pattern;
public class MyApp
{
public static void main(String[] args)
{
System.out.println("1.Pattern");
System.out.println("2.Calculate");
System.out.println("3.ArrayImpl");
System.out.println("Enter your choice=");
Scanner sc= new Scanner(System.in);
int ch = sc.nextInt();
switch(ch)
{
case 1:
System.out.println("Enter number of rows you want");
int rows = sc.nextInt();
System.out.println("Your Pattern Is=");
Pattern p1 = new Pattern();
p1.pattern1(rows);
System.out.println("");
p1.pattern2(rows);
break;
case 2:
System.out.println("Enter number=");
int number = sc.nextInt();
Calculate c1=new Calculate();
c1.reverse(number);
break;
case 3:
/*System.out.println("Enter number=");
int numbers= sc.nextInt();*/
ArrayImpl A1 = new ArrayImpl();
A1.Average();
break;
default:
System.out.println("Enter correct choice=");
}
sc.close();
}
}
<file_sep>/angular backup/forms/FormModelWay/src/app/media/media.component.ts
import { Component, OnInit } from '@angular/core';
import { media } from '../model/media.model';
@Component({
selector: 'app-media',
templateUrl: './media.component.html',
styleUrls: ['./media.component.css']
})
export class MediaComponent implements OnInit {
medias : Array<media>;
ngOnInit(): void {
}
constructor() {
this.medias = [
new media("img1","background-image","bg","Nature"),
new media("img2","logo-image","logo","face"),
new media("img3","gif-image","gif","welcome")
]
}
addNewMedia(media:media):void{
this.medias.push(media);
}
}
<file_sep>/java/bootTest/target/classes/application.properties
server.port=9089
server.servlet.context.path=/bootTest
info.app.name=bootTest
info.app.description=This is spring boot application
info.app.version=SNAPSHOT
info.app.developer=TEAM
info.teamdetails.name1=First
info.teamdetails.name2=Second
info.teamdetails.name3=Third
managemnet.endpointa.we.explosure.include=*
<file_sep>/java/Practice/src/Number.java
import java.util.Scanner;
public class Number {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter the number=");
Scanner sc = new Scanner(System.in);
int number=sc.nextInt();
System.out.println("the number is="+number);
sc.close();
}
}
<file_sep>/angular backup/prj3/src/app/direct/direct.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'direct',
templateUrl: './direct.component.html',
styleUrls: ['./direct.component.css']
})
export class DirectComponent implements OnInit {
name:string;
age:number;
email:string;
constructor()
{
this.name="abc";
this.age=23;
this.email="<EMAIL>";
}
changeval(){
this.name="xyz";
this.age=25;
this.email="<EMAIL>";
}
ngOnInit() {
}
}
<file_sep>/cal-script.js
<script>
var inputX = document.getElementById('x'),
inputY = document.getElementById('y'),
output = document.getElementById('output');
var showOutput = function(value) {
output.innerHTML = value;
}
var operation = function(operationName) {
var x = getInputs(inputX),
y = getInputs(inputY);
if (isNaN(x) || isNaN(y)) {
return;
}
};
</script> <file_sep>/Sahil/workspace/Enumeration/src/com/cts/enumeration/Theater.java
package com.cts.enumeration;
import java.util.Scanner;
public enum Theater
{
DIMOND,
GOLD,
SILVER;
public void getRate()
{
Scanner sc = new Scanner(System.in);
int ch = sc.nextInt();
System.out.println("1.Dimond seat");
System.out.println("2.Gold seat");
System.out.println("3.Silver seat");
switch (ch)
{
case 1:
System.out.println("100");
break;
case 2:
System.out.println("80");
break;
case 3:
System.out.println("60");
break;
default:
System.out.println("Invalid choice");
break;
}
sc.close();
}
}
<file_sep>/java/Practice/src/Quiz.java
import java.util.Scanner;
public class Quiz
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
System.out.println("Do you want to play quiz??(Y/N)=");
Scanner sc1 = new Scanner(System.in);
String ans=sc1.next();
if (ans.equalsIgnoreCase("Y"))
{
System.out.println("Q.1) What is the capital of India???");
System.out.println("1) Delhi");
System.out.println("2) Mumbai");
System.out.println("3) Chennai");
System.out.printf("ANSWER=");
int ch=sc1.nextInt();
switch (ch)
{
case 1:
System.out.println("That's right!");
break;
case 2:
System.out.println("Wrong!");
break;
case 3:
System.out.println("Wrong!");
break;
default:
System.out.println("***Invalid choice please enter valid choice***");
break;
}
System.out.println("Q.2) Can you store the value \"dog\" in a variable of type int???");
System.out.println("1) Yes");
System.out.println("2) No");
System.out.printf("ANSWER=");
int choice=sc1.nextInt();
switch (choice)
{
case 1:
System.out.println("Sorry, \"dog\" is a string. ints can only store numbers.");
break;
case 2:
System.out.println("Thats Correct!");
break;
default:
System.out.println("***Invalid choice please enter valid choice***");
break;
}
System.out.println("Q.3) What is the result of 9+9/3?");
System.out.println("1) 6");
System.out.println("2) 12");
System.out.println("3) 15/3");
System.out.printf("ANSWER=");
int ch1=sc1.nextInt();
switch (ch1)
{
case 1:
System.out.println("Thats Correct!");
break;
case 2:
System.out.println("wrong!!");
break;
case 3:
System.out.println("wrong!!");
break;
default:
System.out.println("***Invalid choice please enter valid choice***");
break;
}
}
else if(ans.equalsIgnoreCase("N"))
{
System.out.println("OK!! User does not want to play quiz.");
}
else
{
System.out.println("Try Again With (Y/N) only !");
}
sc1.close();
}
}
<file_sep>/java/mavenweb-hibernate-entity/src/main/java/com/cts/training/mavenweb/entity/User.java
package com.cts.training.mavenweb.entity;
import java.time.LocalDateTime;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.util.MimeType;
@Entity
@Table(name = "Users")
public class User {
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", password=" + password + ", email=" + email + ", firstname="
+ firstname + ", lastname=" + lastname + ", dob=" + dob + ", profilepic=" + profilepic + ", createdon="
+ createdon + ", updatedon=" + updatedon + "]";
}
@Id // primary key
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "name")
private String name;
@Column
private String password;
@Column
private String email;
@Column
private String firstname ;
@Column
private String lastname;
@Column
private Date dob;
@Column
private MimeType profilepic;
@Column
private LocalDateTime createdon;
@Column
private LocalDateTime updatedon;
protected Integer getId() {
return id;
}
protected void setId(Integer id) {
this.id = id;
}
protected String getName() {
return name;
}
protected void setName(String name) {
this.name = name;
}
protected String getPassword() {
return password;
}
protected void setPassword(String password) {
this.password = password;
}
protected String getEmail() {
return email;
}
protected void setEmail(String email) {
this.email = email;
}
protected String getFirstname() {
return firstname;
}
protected void setFirstname(String firstname) {
this.firstname = firstname;
}
protected String getLastname() {
return lastname;
}
protected void setLastname(String lastname) {
this.lastname = lastname;
}
protected Date getDob() {
return dob;
}
protected void setDob(Date dob) {
this.dob = dob;
}
protected MimeType getProfilepic() {
return profilepic;
}
protected void setProfilepic(MimeType profilepic) {
this.profilepic = profilepic;
}
protected LocalDateTime getCreatedon() {
return createdon;
}
protected void setCreatedon(LocalDateTime createdon) {
this.createdon = createdon;
}
protected LocalDateTime getUpdatedon() {
return updatedon;
}
protected void setUpdatedon(LocalDateTime updatedon) {
this.updatedon = updatedon;
}
}
<file_sep>/Assignment 1/my project/src/com/cts/assignment1/Quiz.java
package com.cts.assignment1;
import java.util.Scanner;
public class Quiz
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
System.out.println("Do you want to play quiz??(Y/N)");
Scanner sc1 = new Scanner(System.in);
String ans=sc1.next();
if(ans==Y)
{
String Delhi;
String Mumbai;
String Chennai;
System.out.println("1) What is the capital of India???");
System.out.println("1) Delhi");
System.out.println("2) Mumbai");
System.out.println("3) Chennai");
Scanner sc2 = new Scanner(System.in);
int ch=sc2.nextInt();
L1:
switch (ch)
{
case 1:
System.out.println("That's right!");
break;
case 2:
System.out.println("Wrong!");
break;
case 3:
System.out.println("Wrong!");
break;
default:
System.out.println("***Invalid choice please enter valid choice***");
break;
continue L1;
}
System.out.println("2) Can you store the value \"dog\" in a variable of type int???");
System.out.println("1) Yes");
System.out.println("2) No");
Scanner sc3 = new Scanner(System.in);
int choice=sc3.nextInt();
L2:
switch (choice)
{
case 1:
System.out.println("Sorry, \"dog\" is a string. ints can only store numbers.");
break;
case 2:
System.out.println("Thats Correct!");
break;
default:
System.out.println("***Invalid choice please enter valid choice***");
break;
continue L2;
}
System.out.println("3) What is the result of 9+9/3?");
System.out.println("1) 6");
System.out.println("2) 12");
System.out.println("3) 15/3");
Scanner sc4 = new Scanner(System.in);
int ch1=sc4.nextInt();
L3:
switch (ch1)
{
case 1:
System.out.println("Thats Correct!");
break;
case 2:
System.out.println("wrong!!");
break;
case 3:
System.out.println("wrong!!");
break;
default:
System.out.println("***Invalid choice please enter valid choice***");
break;
continue L3;
}
else
{
System.out.println("***Invalid input please enter valid answer***");
}
}
}
<file_sep>/angular backup/TestCases/src/app/testcases/calculator.spec.ts
import { Calculator } from "./calculator"
describe("Testing function calc1 of Calculator", ()=>{
beforeAll(()=>{
})
beforeEach(()=>{
})
afterAll(()=>{
})
afterEach(()=>{
})
it('Testing calc1 for negative values', ()=>{
let calc = new Calculator();
let response = calc.calc1(-5);
expect(response).toBe(0);
})
it('Testing calc1 for positive values', ()=>{
let calc = new Calculator();
let response = calc.calc1(5);
expect(response).toBe(6);
})
it('Testing calc1 for log 10 values',()=>{
let calc =new Calculator();
let response = calc.calc1(4);
expect(response).toBe(5);
})
})<file_sep>/java/mavenweb-hibernate-entity/src/main/java/com/cts/training/mavenweb/entity/Comments.java
package com.cts.training.mavenweb.entity;
import java.time.LocalDateTime;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "Comments")
public class Comments {
@Id // primary key
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Id // F_key
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer mediaid;
@Id // F_key
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer userid;
@Column
private String comment;
@Column
private LocalDateTime createdon;
@Column
private LocalDateTime updatedon;
protected Integer getId() {
return id;
}
protected void setId(Integer id) {
this.id = id;
}
protected Integer getMediaid() {
return mediaid;
}
protected void setMediaid(Integer mediaid) {
this.mediaid = mediaid;
}
protected Integer getUserid() {
return userid;
}
protected void setUserid(Integer userid) {
this.userid = userid;
}
protected String getComment() {
return comment;
}
protected void setComment(String comment) {
this.comment = comment;
}
protected LocalDateTime getCreatedon() {
return createdon;
}
protected void setCreatedon(LocalDateTime createdon) {
this.createdon = createdon;
}
protected LocalDateTime getUpdatedon() {
return updatedon;
}
protected void setUpdatedon(LocalDateTime updatedon) {
this.updatedon = updatedon;
}
}
<file_sep>/angular backup/forms/FormModelWay/src/app/model/media.model.ts
export class media{
title:string;
description:string;
tag:string;
img:string;
constructor(title:string,description:string,tag:string,img:string)
{
this.title=title;
this.description=description;
this.tag=tag;
this.img=img;
}
}
<file_sep>/angular backup/calculator/src/app/calculator/calculator.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'calculator',
templateUrl: './calculator.component.html',
styleUrls: ['./calculator.component.css']
})
export class CalculatorComponent implements OnInit {
num1:number;
num2:number;
res:number;
add(num1:HTMLInputElement,num2:HTMLInputElement,res:HTMLInputElement)
{
this.num1=parseInt(num1.value);
this.num2=parseInt(num2.value);
this.res=this.num1+this.num2;
}
sub(num1:HTMLInputElement,num2:HTMLInputElement,res:HTMLInputElement)
{
this.num1=parseInt(num1.value);
this.num2=parseInt(num2.value);
this.res=this.num1-this.num2;
}
mul(num1:HTMLInputElement,num2:HTMLInputElement,res:HTMLInputElement)
{
this.num1=parseInt(num1.value);
this.num2=parseInt(num2.value);
this.res=this.num1*this.num2;
}
div(num1:HTMLInputElement,num2:HTMLInputElement,res:HTMLInputElement)
{
this.num1=parseInt(num1.value);
this.num2=parseInt(num2.value);
this.res=this.num1/this.num2;
}
clear(num1:HTMLInputElement,num2:HTMLInputElement,res:HTMLInputElement)
{
num1.value=" ";
num2.value=" ";
res.value="";
}
ngOnInit() {
}
}
<file_sep>/java/mavenweb-hibernate-entity/src/main/java/com/cts/training/mavenweb/entity/Actions.java
package com.cts.training.mavenweb.entity;
import java.time.LocalDateTime;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "Actions")
public class Actions {
@Id // primary key
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Id // F_key
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer mediaid;
@Id // F_key
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer userid;
@Column
private boolean status;
@Column
private LocalDateTime createdon;
@Column
private LocalDateTime updatedon;
protected Integer getId() {
return id;
}
protected void setId(Integer id) {
this.id = id;
}
protected Integer getMediaid() {
return mediaid;
}
protected void setMediaid(Integer mediaid) {
this.mediaid = mediaid;
}
protected Integer getUserid() {
return userid;
}
protected void setUserid(Integer userid) {
this.userid = userid;
}
protected boolean isStatus() {
return status;
}
protected void setStatus(boolean status) {
this.status = status;
}
protected LocalDateTime getCreatedon() {
return createdon;
}
protected void setCreatedon(LocalDateTime createdon) {
this.createdon = createdon;
}
protected LocalDateTime getUpdatedon() {
return updatedon;
}
protected void setUpdatedon(LocalDateTime updatedon) {
this.updatedon = updatedon;
}
@Override
public String toString() {
return "Actions [id=" + id + ", mediaid=" + mediaid + ", userid=" + userid + ", status=" + status
+ ", createdon=" + createdon + ", updatedon=" + updatedon + "]";
}
}
<file_sep>/angular backup/media/3 component/src/app/media-entry/media-entry.component.ts
import { media } from '../model/media.model';
import { EventEmitter, Output, OnInit, Component } from '@angular/core';
@Component({
selector: 'app-media-entry',
templateUrl: './media-entry.component.html',
styleUrls: ['./media-entry.component.css']
})
export class MediaEntryComponent implements OnInit {
@Output()
submit_info : EventEmitter<media>;
constructor() {
this.submit_info = new EventEmitter();
}
saveMedia(txtTitle:HTMLInputElement, txtDescription:HTMLInputElement, txtTag:HTMLInputElement,txtImg:HTMLInputElement):void{
let newmedia = new media(txtTitle.value, txtDescription.value, txtTag.value,txtImg.value);
this.submit_info.emit(newmedia);
txtTitle.value = "";
txtDescription.value = "";
txtTag.value = "";
txtImg.value = "";
}
ngOnInit(){
}
}
<file_sep>/java/WebProject/src/com/cts/training/web/Loginserve.java
package com.cts.training.web;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class Loginserve
*/
@WebServlet("/Loginserve")
public class Loginserve extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Loginserve() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String name=request.getParameter("name");
String pass=request.getParameter("pass");
request.setAttribute("username", name.toUpperCase());
request.setAttribute("pass", pass.concat("Check"));
HttpSession session = request.getSession();
session.setAttribute("username", name.toUpperCase());
session.setAttribute("pass", pass.concat("Check"));
ServletContext context = this.getServletContext();
context.setAttribute("username", name.toUpperCase());
context.setAttribute("pass", pass.concat("Check"));
//PrintWriter writer=response.getWriter();
if(name.equals("sahil")&& pass.equals("s<PASSWORD>"))
{
/*
writer.write("<h1>Welcome</h1>");
*/
/*
response.sendRedirect("welcome.html");
*/
this.getServletContext().getRequestDispatcher("welcome.jsp").forward(request, response);
}
else {
/*
writer.write("<h1>Invalid</h1>");
*/
/*
response.sendRedirect("error.html");
*/
this.getServletContext().getRequestDispatcher("error.html").forward(request, response);
}
}
}
<file_sep>/README.md
# cognizant-training-practice | a0778d834b46af53690dab7c26f41117da8131c7 | [
"HTML",
"JavaScript",
"Markdown",
"INI",
"Java",
"TypeScript"
] | 20 | HTML | sahiltorkadi/cognizant-training-practice | c372512521865e396e5afbda8e7560b2387d8309 | 54c3fab8a717874f217725c333ad9fca5a866ff9 |
refs/heads/master | <file_sep>require 'acceptance/acceptance_helper'
feature 'Vote for answer', %q{
In order to be able vote for the answer
As an user
I want to be able vote for the answer
} do
given(:user) { create(:user)}
given(:answer) { create(:answer) }
scenario 'Authenticate user vote up for answer', js: true do
sign_in(user)
visit question_path(answer.question)
within("div#answer#{answer.id} > .vote") do
expect(page).to have_css ".vote-up"
find(:css, ".vote-up").click
within(".vote-count") do
expect(page).to have_content "1"
end
end
end
scenario "Author of answer can't vote for answer", js: true do
sign_in(user)
author_answer = create(:answer, user: user)
visit question_path(author_answer.question)
within("div#answer#{author_answer.id} > .vote") do
expect(page).to_not have_css ".vote-up"
expect(page).to_not have_css ".vote-down"
end
end
describe 'Authenticate user vote for answer only one time' do
scenario "vote up", js: true do
sign_in(user)
visit question_path(answer.question)
within("div#answer#{answer.id} > .vote") do
expect(page).to have_css ".vote-up"
within(".vote-count") do
expect(page).to have_content "0"
end
find(:css, ".vote-up").click
wait_for_ajax
find(:css, ".vote-up").click
wait_for_ajax
within(".vote-count") do
expect(page).to have_content "0"
end
end
end
scenario "vote down", js: true do
sign_in(user)
answer.votes << create(:vote, user: user, votable: answer, value: 1)
answer.votes << create(:vote, user: create(:user), votable: answer, value: 1)
visit question_path(answer.question)
within("div#answer#{answer.id} > .vote") do
expect(page).to have_css ".vote-down"
within(".vote-count") do
expect(page).to have_content "2"
end
find(:css, ".vote-down").click
wait_for_ajax
find(:css, ".vote-down").click
wait_for_ajax
within(".vote-count") do
expect(page).to have_content "1"
end
end
end
scenario "vote down after vote up", js: true do
sign_in(user)
visit question_path(answer.question)
within("div#answer#{answer.id} > .vote") do
within(".vote-count") do
expect(page).to have_content "0"
end
find(:css, ".vote-up").click
wait_for_ajax
find(:css, ".vote-down").click
wait_for_ajax
within(".vote-count") do
expect(page).to have_content "-1"
end
end
end
scenario "vote up after vote down", js: true do
sign_in(user)
visit question_path(answer.question)
within("div#answer#{answer.id} > .vote") do
within(".vote-count") do
expect(page).to have_content "0"
end
find(:css, ".vote-down").click
wait_for_ajax
find(:css, ".vote-up").click
wait_for_ajax
within(".vote-count") do
expect(page).to have_content "1"
end
end
end
end
scenario 'Non-authenticate user ties vote for answer', js: true do
visit question_path(answer.question)
within("div#answer#{answer.id}") do
expect(page).to_not have_css(".vote_up")
expect(page).to_not have_css(".vote_down")
end
end
end<file_sep>require 'acceptance/acceptance_helper'
feature 'Add files to question', %q{
I order to be able illustrate my question
As an authenticate user
I want to be add files to question
} do
given(:user) { create(:user)}
scenario 'User add files to question', js: true do
sign_in(user)
visit new_question_path
fill_in 'Title', with: 'Title 1'
fill_in 'Body', with: 'Body 1'
within(:xpath, "//div[@id='attachments']/div[@class='nested-fields'][1]/div[@class='field']") do
attach_file 'File', "#{Rails.root}/spec/spec_helper.rb"
end
click_on 'add file'
within(:xpath, "//div[@id='attachments']/div[@class='nested-fields'][2]/div[@class='field']") do
attach_file 'File', "#{Rails.root}/spec/rails_helper.rb"
end
click_on 'Create'
expect(page).to have_link"spec_helper.rb", href: "/uploads/attachment/file/1/spec_helper.rb"
expect(page).to have_link"rails_helper.rb", href: "/uploads/attachment/file/2/rails_helper.rb"
end
end<file_sep>require 'acceptance/acceptance_helper'
feature 'Removal of the author questions', %q{
In order to be able to remove my questions
As an authenticated user
I want to be able to remove my questions
} do
given(:user) { create(:user) }
given(:question) { create(:question_with_answers, user: user) }
scenario 'Authenticated author delete your question' do
sign_in(user)
question
visit questions_path
expect(page).to have_content question.title
visit question_path(question)
click_on 'Delete question'
expect(page).to have_content 'Your question successfully deleted.'
expect(current_path).to eq questions_path
expect(page).to_not have_content question.title
end
scenario 'Authenticated author can not delete other question' do
sign_in(user)
qpath = question_path(create(:question, user: create(:user)))
visit qpath
expect(page).to_not have_link 'Delete question'
end
scenario 'Non-authenticated user can not delete question' do
visit question_path(question)
expect(page).to_not have_link "Delete question"
end
end<file_sep>class DailyDigestJob < ApplicationJob
queue_as :default
def perform
digest = Question.digest.map { |question| { title: question.title, url: question_url(question) }}
User.all.find_each.each do |user|
DailyMailer.digest(user, digest).deliver_later
end
end
end
<file_sep>require 'rails_helper'
describe Ability do
subject(:ability) { Ability.new(user)}
describe "for guest" do
let(:user) { nil }
it { should be_able_to :read, :all }
it { should_not be_able_to :manage, :all }
end
describe "for admin" do
let(:user) { create(:user, admin: true) }
it { should be_able_to :manage, :all}
end
describe "for user" do
let(:user) { create(:user) }
let(:other_user) { create(:user) }
let(:question) { create(:question, user: user) }
let(:other_question) { create(:question, user: other_user) }
let(:answer) { create(:answer, user: user) }
let(:other_answer) { create(:answer, user: other_user) }
let(:subscription1) { user.subscribe(question) }
let(:subscription2) { user.subscribe(other_question) }
let(:other_subscription1) { other_user.subscribe(question) }
let(:other_subscription2) { other_user.subscribe(other_question) }
it { should_not be_able_to :manage, :all }
it { should be_able_to :read, :all }
it { should be_able_to :create, Question }
it { should be_able_to :create, Answer }
it { should be_able_to :create, Comment }
it { should be_able_to :manage, Vote }
it { should be_able_to :manage, create(:attachment, attachable: question, attachable_type: "Question") }
it { should_not be_able_to :manage, create(:attachment, attachable: other_question, attachable_type: "Question") }
it { should be_able_to :manage, create(:attachment, attachable: answer, attachable_type: "Answer") }
it { should_not be_able_to :manage, create(:attachment, attachable: other_answer, attachable_type: "Answer") }
it { should be_able_to :manage, Authorization }
it { should be_able_to :vote_up, other_question }
it { should_not be_able_to :vote_up, question }
it { should be_able_to :vote_up, other_answer }
it { should_not be_able_to :vote_up, answer }
it { should be_able_to :vote_down, other_question }
it { should_not be_able_to :vote_down, question }
it { should be_able_to :vote_down, other_answer }
it { should_not be_able_to :vote_down, answer }
it { should be_able_to [:update, :destroy, :edit], question }
it { should_not be_able_to [:update, :destroy, :edit], other_question }
it { should be_able_to [:update, :destroy, :edit], answer }
it { should_not be_able_to [:update, :destroy, :edit], other_answer }
it { should be_able_to [:update, :destroy], create(:comment, commentable: question,
commentable_type: "Question", user: user) }
it { should_not be_able_to [:update, :destroy], create(:comment, commentable: question,
commentable_type: "Question", user: other_user) }
it { should be_able_to :accept, create(:answer, question: question) }
it { should_not be_able_to :accept, create(:answer, question: question, accept: true) }
it { should_not be_able_to :accept, create(:answer, question: other_question) }
it { should be_able_to :create, Subscription }
it { should be_able_to :destroy, subscription1 }
it { should be_able_to :destroy, subscription2 }
it { should_not be_able_to :destroy, other_subscription1 }
it { should_not be_able_to :destroy, other_subscription2 }
end
end<file_sep>require 'rails_helper'
RSpec.describe NotifySubscribersJob, type: :job do
describe "should send notify to the subscribers" do
let!(:question) { create(:question) }
let(:subscriptions) { create_list(:subscription, 2, question: question) }
let(:answer) { create(:answer, question: question) }
it 'when a update question' do
Subscription.where.not(user_id: question.user).each { |subscription| expect(DailyMailer).to receive(:notify_update_question).with(subscription.user, question).and_call_original }
NotifySubscribersJob.perform_now(question)
end
it 'exclude the author of the question when a update question' do
Subscription.all.each { |subscription| expect(DailyMailer).to_not receive(:notify_update_question).with(subscription.user, question).and_call_original }
NotifySubscribersJob.perform_now(question)
end
it 'when a new answer' do
Subscription.all.each { |subscription| expect(DailyMailer).to receive(:notify_new_answer).with(subscription.user, answer).and_call_original }
NotifySubscribersJob.perform_now(answer)
end
end
end
<file_sep>class NotifySubscribersJob < ApplicationJob
queue_as :default
def perform(object)
question = object.is_a?(Question) ? object : object.question
question.subscriptions.find_each.each do |subscription|
if object.is_a? Question
DailyMailer.notify_update_question(subscription.user, object).deliver_later unless subscription.user.author_of?(object)
else
DailyMailer.notify_new_answer(subscription.user, object).deliver_later
end
end
end
end
<file_sep>shared_examples_for "Searched" do
it 'for class' do
expect(ThinkingSphinx).to receive(:search).with('text text', classes: classes)
Search.by_condition(condition, 'text text')
end
end<file_sep>require 'acceptance/acceptance_helper'
feature 'Removal of the author answers', %q{
In order to be able to remove my answers
As an authenticated user
I want to be able to remove my answers
} do
given(:user) { create(:user) }
given(:question) { create(:question_with_answers, user: user) }
scenario 'Authenticated author delete your answer', js: true do
sign_in(user)
qpath = question_path(question)
visit qpath
answer_css = "#answer#{question.answers.first.id}"
within answer_css do
click_on "Delete"
end
expect(page).to have_content 'Answer was successfully destroyed.'
expect(current_path).to eq qpath
expect(page).to_not have_selector(answer_css)
end
scenario 'Authenticated author can not delete other answer', js: true do
sign_in(user)
answer = create(:answer, user: create(:user), question: question)
visit question_path(question)
within "#answer#{answer.id}" do
expect(page).to_not have_link "Delete"
end
end
scenario 'Non-authenticated user can not delete answers', js: true do
visit question_path(question)
question.answers.each do |answer|
within "#answer#{answer.id}" do
expect(page).to_not have_link "Delete"
end
end
end
end<file_sep>class DailyMailer < ApplicationMailer
def digest(user, questions)
@questions = questions
mail( to: user.email,
subject: t('daily_mailer.digest.subject'))
end
def notify_new_answer(user, answer)
@answer = answer
@question = answer.question
mail( to: user.email,
subject: "New answer for question '#{@question.title}'")
end
def notify_update_question(user, question)
@question = question
mail( to: user.email,
subject: "The content of the question '#{question.title}' has been updated")
end
end
<file_sep>FactoryGirl.define do
sequence :title do |n|
"Question #{n}"
end
sequence :body do |n|
"Body #{n}"
end
factory :question do
user
title
body
factory :question_with_answers do
transient do
answers_count 5
end
after :create do |question, evaluator|
FactoryGirl.create_list(:answer, evaluator.answers_count, question: question, user: evaluator.user)
end
end
factory :question_with_attachments do
transient do
count 5
end
after :create do |question, evaluator|
FactoryGirl.create_list(:attachment, evaluator.count, attachable: question)
end
end
end
factory :invalid_question, class: "Question" do
title nil
body nil
end
end<file_sep>require 'rails_helper'
RSpec.describe User, type: :model do
it { should have_many(:questions).dependent(:destroy)}
it { should have_many(:answers).dependent(:destroy)}
it { should have_many(:authorizations).dependent(:destroy)}
it { should have_many(:subscriptions).dependent(:destroy)}
it { should validate_presence_of :email}
it { should validate_presence_of :password}
describe 'method author_of?' do
let(:user) { create(:user) }
let(:answer) { create(:answer) }
context 'with valid attributes' do
it 'author of Answer' do
expect(user).to be_author_of(create(:answer, user: user))
end
it 'non-author of Answer' do
expect(user).to_not be_author_of(answer)
end
end
context 'with invalid attributes' do
it 'Answer with nil user_id' do
answer.user_id = nil
expect(user).to_not be_author_of(answer)
end
it 'model is nil' do
expect(user).to_not be_author_of(nil)
end
it 'fake model without field user_id' do
expect(user).to_not be_author_of("")
end
end
end
describe ".find_for_oauth" do
let!(:user) { create(:user) }
let(:auth) { OmniAuth::AuthHash.new(provider: "facebook", uid: "123456") }
context "user already has authorization" do
it "returns the user" do
user.authorizations.create(provider: auth.provider, uid: auth.uid)
expect(User.find_for_omniauth(auth)).to eq user
end
end
context "user has not authorization" do
context "user already exists" do
let(:auth) { OmniAuth::AuthHash.new(provider: "facebook", uid: "123456", info: { email: user.email })}
it "does not create new user" do
expect{ User.find_for_omniauth(auth) }.to_not change(User, :count)
end
it "creates new record for authorization" do
expect{ User.find_for_omniauth(auth) }.to change(Authorization, :count).by(1)
end
it "creates authorization with provider and uid" do
authorization = User.find_for_omniauth(auth).authorizations.first
expect(authorization.provider).to eq auth.provider
expect(authorization.uid).to eq auth.uid
end
it "returns the user" do
expect(User.find_for_omniauth(auth)).to be_a(User)
end
end
context "user does not exists" do
let(:auth) { OmniAuth::AuthHash.new(provider: "facebook", uid: "123456", info: { email: "<EMAIL>" })}
it "create new record user" do
expect{ User.find_for_omniauth(auth) }.to change(User, :count).by(1)
end
it "returns new user" do
expect(User.find_for_omniauth(auth)).to be_a(User)
end
it "fills user email" do
user = User.find_for_omniauth(auth)
expect(user.email).to eq auth.info.email
end
it "creates new record for authorization" do
expect{ User.find_for_omniauth(auth) }.to change(Authorization, :count).by(1)
end
it "creates authorization with provider and uid" do
authorization = User.find_for_omniauth(auth).authorizations.first
expect(authorization.provider).to eq auth.provider
expect(authorization.uid).to eq auth.uid
end
end
context "user does not exists and social network does not return email" do
let(:auth) { OmniAuth::AuthHash.new(provider: "twitter", uid: "123456", info: { email: "" })}
it "create new record user" do
expect{ User.find_for_omniauth(auth) }.to change(User, :count).by(1)
end
it "returns new user" do
expect(User.find_for_omniauth(auth)).to be_a(User)
end
it "fills user email with temp email" do
user = User.find_for_omniauth(auth)
expect(user.email_verified?).to eq false
end
it "creates new record for authorization" do
expect{ User.find_for_omniauth(auth) }.to change(Authorization, :count).by(1)
end
it "creates authorization with provider and uid" do
authorization = User.find_for_omniauth(auth).authorizations.first
expect(authorization.provider).to eq auth.provider
expect(authorization.uid).to eq auth.uid
end
end
end
end
describe "work with email" do
let!(:user) { create(:user) }
let(:auth) { OmniAuth::AuthHash.new(provider: "facebook", uid: "123456") }
scenario "#create_temp_email" do
user.update(email: User.create_temp_email(auth))
expect(user.email).to match User::TEMP_EMAIL_REGEX
end
describe "#email_verified?" do
scenario "with empty email" do
user.email = ""
expect(user.email_verified?).to eq false
end
scenario "with temp email" do
user.update(email: User.create_temp_email(auth))
expect(user.email_verified?).to eq false
end
scenario "with valid email" do
user.update(email: "<EMAIL>")
expect(user.email_verified?).to eq true
end
scenario "with non-confirmed email" do
user.update(email: "<EMAIL>", confirmed_at: nil)
expect(user.email_verified?).to eq false
end
end
describe "#temp_email?" do
scenario "with temp email" do
user.email = User.create_temp_email(auth)
expect(user.temp_email?).to eq true
end
scenario "with valid email" do
expect(user.temp_email?).to eq false
end
scenario "with empty email" do
expect(user.temp_email?).to eq false
end
end
describe "#update_email" do
scenario "without block" do
user.update_email(email: "<EMAIL>")
expect(user.confirmed?).to eq false
expect(user.email).to eq "<EMAIL>"
end
scenario "with block" do
expect(user.update_email(email: "<EMAIL>"){1+1}).to eq 2
expect(user.confirmed?).to eq false
expect(user.email).to eq "<EMAIL>"
end
end
scenario "#create_authorization" do
expect { user.create_authorization(auth) }.to change(Authorization, :count).by(1)
end
describe "#move_authorizations" do
scenario "from existing user" do
user2 = create(:user)
user2.create_authorization(auth)
expect(user.authorizations.count).to eq 0
res = user.move_authorizations(user2) { 1+1 }
expect(user.authorizations.count).to eq 1
expect(res).to eq 2
end
describe "from nil user" do
scenario "without block" do
expect { user.move_authorizations(nil) }.to_not raise_error
end
scenario "with block" do
expect( user.move_authorizations(nil) {1+1} ).to eq nil
end
end
end
describe "#update_params" do
describe "email of existing user" do
scenario "verify status" do
user2 = create(:user)
user2.email = User.create_temp_email(auth)
user2.save
user_status = user2.update_params(email: user.email)
expect(user_status[:status]).to eq :existing
expect(user_status[:user]).to eq user
end
scenario "remove user2" do
user2 = create(:user)
user2.email = User.create_temp_email(auth)
user2.save
user2.update_params(email: user.email)
expect { user2.reload }.to raise_exception(ActiveRecord::RecordNotFound)
end
end
end
describe "email of new user" do
scenario "verify status" do
user2 = create(:user)
user2.email = User.create_temp_email(auth)
user2.save
user_status = user2.update_params(email: "<EMAIL>")
expect(user_status[:status]).to eq :new
expect(user_status[:user]).to eq user2
expect(user2.email).to eq "<EMAIL>"
end
scenario "number of users unchanged" do
user2 = create(:user)
user2.email = User.create_temp_email(auth)
user2.save
expect { user2.update_params(email: "<EMAIL>") }.to_not change(User, :count)
end
end
end
describe "#subscribe_of?" do
let(:user) { create(:user) }
let(:question) { create(:question) }
describe "from existing user" do
scenario "not exists subscription" do
expect(user.subscribe_of?(question)).to eq false
end
scenario "exists subscription" do
user.subscribe(question)
expect(user.subscribe_of?(question)).to eq true
end
end
end
describe "#subscribe" do
let(:user) { create(:user) }
let!(:question) { create(:question) }
let!(:users) { create_list(:user, 3) }
scenario 'change subscriptions' do
expect { user.subscribe(question) }.to change(Subscription, :count).by(1)
end
scenario 'double subscribe returns an existing subscription' do
subscription = user.subscribe(question)
expect(user.subscribe(question)).to eq subscription
end
scenario 'return subscription object' do
expect(user.subscribe(question)).to be_a(Subscription)
end
scenario "several users can subscribe to the question" do
expect { users.each {|user| user.subscribe(question) } }.to change(Subscription, :count).by(3)
end
end
describe "#unsubscribe" do
let(:user) { create(:user) }
let(:question) { create(:question) }
scenario 'change subscriptions' do
user.subscribe(question)
expect { user.unsubscribe(question) }.to change(Subscription, :count).by(-1)
end
end
describe "#subscription_of" do
let(:user) { create(:user) }
let(:question) { create(:question) }
let!(:subscription) { user.subscribe(question) }
it "get user subscription of question" do
expect(user.subscription_of(question)).to eq subscription
end
end
end
<file_sep>require 'acceptance/acceptance_helper'
feature 'Subscribe to update question', %q{
In order to be able to receive notifications about the update of the question
As an authenticated user
I want to be able to subscribe an question
} do
given(:user) { create(:user) }
describe 'Authenticate user' do
describe "Author of question" do
given!(:question) { create(:question, user: user) }
before do
sign_in user
visit question_path(question)
end
describe "unsubscribe" do
scenario 'see unsubscribe link' do
within '.question' do
expect(Subscription.count).to eq 1
expect(page).to have_link('Unsubscribe')
end
end
scenario 'tried to unsubscribe on question', js: true do
within '.question' do
expect(page).to_not have_link('Subscribe')
click_on 'Unsubscribe'
wait_for_ajax
expect(page).to_not have_link('Unsubscribe')
expect(page).to have_link("Subscribe")
end
end
end
end
describe "non-author of question" do
given!(:question) { create(:question) }
describe "subscribe" do
before do
sign_in user
visit question_path(question)
end
scenario 'see subscribe link' do
within '.question' do
expect(page).to have_link('Subscribe')
end
end
scenario 'tried to subscribe on question', js: true do
within '.question' do
expect(page).to_not have_link('Unsubscribe')
click_on 'Subscribe'
wait_for_ajax
expect(page).to_not have_link('Subscribe')
expect(page).to have_link("Unsubscribe")
end
end
scenario "rendered subscribe on question" do
user.subscribe(question)
visit question_path(question)
expect(page).to_not have_link('Subscribe')
expect(page).to have_link("Unsubscribe")
end
end
describe "unsubscribe" do
before do
sign_in user
user.subscribe(question)
visit question_path(question)
end
scenario 'see unsubscribe link' do
within '.question' do
expect(page).to have_link('Unsubscribe')
end
end
scenario 'tried to unsubscribe on question', js: true do
within '.question' do
expect(page).to_not have_link('Subscribe')
click_on 'Unsubscribe'
wait_for_ajax
expect(page).to_not have_link('Unsubscribe')
expect(page).to have_link("Subscribe")
end
end
end
end
end
describe "Non-authenticate user" do
given!(:question) { create(:question, user: user) }
before do
visit question_path(question)
end
scenario 'does not see subscriber links' do
within '.question' do
expect(page).to_not have_link('Subscribe')
expect(page).to_not have_link('Unsubscribe')
end
end
end
end
<file_sep>require 'acceptance/acceptance_helper'
feature 'Right answer', %q{
In order to be able to solve my problem
As an user
I want to be able to see first the right answer
} do
given(:question) { create(:question) }
given(:user) { question.user }
given!(:answer1) { create(:answer, question: question, user: user, id: 1) }
given!(:answer2) { create(:answer, question: question, user: user, id: 2) }
given!(:answer3) { create(:answer, question: question, user: user, id: 3, accept: true) }
before do
visit question_path(question)
end
scenario "first in list answers" do
first_answer = first(:xpath, "//div[@class='answers']/div[1]")
expect(first_answer[:id]).to eq "answer3"
within first_answer do
expect(page).to_not have_link('Accept')
expect(page).to have_selector("span.accept")
end
end
end
<file_sep>json.body_html renderer.render(
partial: "answers/answer",
locals: { answer: answer }
)
json.user_id current_user.id<file_sep>class Search
CONDITIONS = %w{Any Questions Answers Comments Users}
def self.by_condition(condition, query)
query = ThinkingSphinx::Query.escape(query)
if CONDITIONS.include?(condition) && condition!="Any"
singular = condition.singularize
klasses = [singular.constantize]
else
klasses = [Question, Answer, Comment, User]
end
ThinkingSphinx.search query, :classes => klasses
end
end<file_sep>class Vote < ApplicationRecord
belongs_to :user
belongs_to :votable, polymorphic: true, optional: true
validates :votable_id, :votable_type, presence: true
validates :user_id, uniqueness: { scope: [:votable_id, :votable_type] }
validates :value, inclusion: [1, -1]
before_create :update_rating
before_destroy :update_rating_destroy
private
def update_rating
votable.increment!(:rating, value)
end
def update_rating_destroy
votable.decrement!(:rating, value)
end
end
<file_sep>FactoryGirl.define do
factory :answer do
user
question
body
accept false
rating 0
factory :answer_with_attachments do
transient do
count 5
end
after :create do |answer, evaluator|
FactoryGirl.create_list(:attachment, evaluator.count, attachable: answer)
end
end
end
factory :invalid_answer, class: "Answer" do
user nil
question nil
body nil
end
end
<file_sep>module Votable
extend ActiveSupport::Concern
included do
has_many :votes, as: :votable, dependent: :destroy
end
def vote_up!(user)
vote_change(user, :up)
end
def vote_down!(user)
vote_change(user, :down)
end
def vote_up_exists?(user)
votes.exists?(user_id: user.id, value: 1)
end
def vote_down_exists?(user)
votes.exists?(user_id: user.id, value: -1)
end
def vote_exists?(user)
votes.exists?(user_id: user.id)
end
def vote_reset!(user)
votes.where(user_id: user.id).destroy_all
end
def vote_rating
reload_attribute(:rating)
rating
end
private
def reload_attribute(attr)
value = self.class.where(id: id).select(attr).first[attr]
self[attr] = value
end
def vote_change(user, act)
unless user&.author_of?(self)
vote_act = vote_action(user)
vote_reset!(user)
if vote_act != act
votes.create(user: user, value: (act == :up ? 1 : -1))
end
end
end
def vote_action(user)
vote = votes.where(user_id: user.id).first
(vote.value == 1 ? :up : :down) if vote
end
end
<file_sep>FactoryGirl.define do
sequence(:email) do |n|
"<EMAIL>"
end
factory :user do
email
password "<PASSWORD>"
confirmed_at Time.now
end
end
<file_sep>require 'acceptance/acceptance_helper'
feature 'Search', %q{
In order to be able find results by request string
As an user
I want to be able send find's string
} do
describe "with Questions" do
it_behaves_like "Searchable" do
let(:condition) { "Questions" }
let(:query) { "question" }
let!(:data) { [
{model: "Questions", attr: :title, objects: create_list(:question, 10)},
]}
end
end
describe "with Answers" do
it_behaves_like "Searchable" do
let(:condition) { "Answers" }
let(:query) { "body" }
let!(:data) { [
{model: "Answers", attr: :body, objects: create_list(:answer, 10)},
]}
end
end
describe "with Comments" do
it_behaves_like "Searchable" do
let(:condition) { "Comments" }
let(:query) { "comment" }
let!(:data) { [
{model: "Comments", attr: :body, objects: create_list(:comment, 10, commentable: create(:question),
commentable_type: "Question")},
]}
end
end
describe "with Users" do
it_behaves_like "Searchable" do
let(:condition) { "Users" }
let(:query) { "text*" }
let!(:data) { [
{model: "Users", attr: :email, objects: 10.times.map {|i| create(:user, email: "<EMAIL>")}}
]}
end
end
describe "with Any" do
it_behaves_like "Searchable" do
let!(:text) { "search-text" }
let(:condition) { "Any" }
let(:query) { "text*" }
let!(:data) { [
{model: "Questions", attr: :title, objects: create_list(:question, 3, body: text)},
{model: "Answers", attr: :body, objects: create_list(:answer, 3, body: text)},
{model: "Comments", attr: :body, objects: create_list(:comment, 3, commentable: create(:question),
commentable_type: "Question", body: text)},
{model: "Users", attr: :email, objects: 3.times.map {|i| create(:user, email: "<EMAIL>")}}
]}
end
end
end<file_sep>require 'acceptance/acceptance_helper'
feature "User can write an comment to a question", %q{
In order to be able to clarify the problem
As an user
I want to be able to write an comment to the question
} do
given(:user) { create(:user) }
given(:question) { create(:question) }
describe "Authenticated user" do
scenario 'write comment to question', js: true do
sign_in(user)
visit question_path(question)
expect(page).to have_content question.title
expect(page).to have_content question.body
within("div#question#{question.id} div.comments") do
fill_in 'ะะฐั ะบะพะผะผะตะฝัะฐัะธะน', with: 'text text'
click_on 'Add comment'
wait_for_ajax
within('textarea#comment_body') do
expect(page).to_not have_content 'text text'
end
end
expect(page).to have_content 'Your comment successfully added.'
expect(page).to have_content 'text text'
end
scenario 'see comments for question', js: true do
sign_in(user)
3.times { question.comments << create(:comment, commentable: question, user: user) }
visit question_path(question)
within("div#question#{question.id} div.comments") do
question.comments.each do |comment|
expect(page).to have_content comment.body
end
end
end
scenario 'to be fill comment with invalid data', js: true do
sign_in(user)
visit question_path(question)
expect(page).to have_content question.title
expect(page).to have_content question.body
within("div#question#{question.id} div.comments") do
fill_in 'ะะฐั ะบะพะผะผะตะฝัะฐัะธะน', with: ''
click_on 'Add comment'
wait_for_ajax
end
expect(page).to have_content 'Body can\'t be blank'
end
end
describe "Non-authenticated user" do
scenario 'see comments for question', js: true do
3.times { question.comments << create(:comment, commentable: question, user: user) }
visit question_path(question)
within("div#question#{question.id} div.comments") do
question.comments.each do |comment|
expect(page).to have_content comment.body
end
end
end
scenario 'can not write comment to question', js: true do
visit question_path(question)
within("div#question#{question.id} div.comments") do
expect(page).to_not have_selector "form#new_comment"
end
end
end
context "multiple sessions" do
given!(:question2) { create(:question) }
scenario "comment on question appears on another user's page", js: true do
Capybara.using_session('user') do
sign_in user
visit question_path(question)
expect(page).to have_content question.title
expect(page).to have_content question.body
end
Capybara.using_session('guest') do
visit question_path(question)
end
Capybara.using_session('guest2') do
visit question_path(question2)
end
Capybara.using_session('user') do
within("div#question#{question.id} div.comments") do
fill_in 'ะะฐั ะบะพะผะผะตะฝัะฐัะธะน', with: 'text text'
click_on 'Add comment'
wait_for_ajax
end
expect(page).to have_content 'Your comment successfully added.'
expect(page).to have_content 'text text'
end
Capybara.using_session('guest') do
expect(page).to have_content 'text text'
end
Capybara.using_session('guest2') do
expect(page).to_not have_content 'text text'
end
end
end
end<file_sep>module Voted
extend ActiveSupport::Concern
included do
before_action :set_votable, only: [:vote_up, :vote_down]
end
def vote_up
@votable.vote_up!(current_user)
respond_to do |format|
format.json { render json: {object_klass: @votable.class.name.downcase, object_id: @votable.id, count: @votable.vote_rating}.to_json }
end
end
def vote_down
@votable.vote_down!(current_user)
respond_to do |format|
format.json { render json: {object_klass: @votable.class.name.downcase, object_id: @votable.id, count: @votable.vote_rating}.to_json }
end
end
private
def model_klass
controller_name.classify.constantize
end
def set_votable
@votable = model_klass.find(params[:id])
end
end<file_sep>require 'acceptance/acceptance_helper'
feature "View question and associated answers", %q{
In order to be able solved my problem
As an user
I want to be able to view the question and answers to it
} do
given(:user) { create(:user) }
let(:question) { create(:question_with_answers) }
scenario 'Authenticated user can view question and associated answers' do
sign_in(user)
visit question_path(question)
expect(page).to have_content question.title
expect(page).to have_content question.body
question.answers do |answer|
expect(page).to have_content answer.body
end
end
scenario 'Non-authenticated user can view question and associated answers' do
visit question_path(question)
expect(page).to have_content question.title
expect(page).to have_content question.body
question.answers do |answer|
expect(page).to have_content answer.body
end
end
end<file_sep>FactoryGirl.define do
factory :vote do
user
value nil
end
end
<file_sep>require 'acceptance/acceptance_helper'
feature "User can write an comment to a answer", %q{
In order to be able to clarify the answer
As an user
I want to be able to write an comment to the answer
} do
given(:user) { create(:user) }
given!(:question) { create(:question_with_answers) }
given(:answer) { question.answers.first}
describe "Authenticated user" do
scenario 'write comment to answer', js: true do
sign_in(user)
visit question_path(question)
question.answers.each_with_index do |answer, i|
text = "comment text #{i}"
within("div#answer#{answer.id} div.comments") do
fill_in 'ะะฐั ะบะพะผะผะตะฝัะฐัะธะน', with: text
click_on 'Add comment'
wait_for_ajax
within('textarea#comment_body') do
expect(page).to_not have_content text
end
end
expect(page).to have_content 'Your comment successfully added.'
within("div#answer#{answer.id} div.comments") do
expect(page).to have_content text
end
end
end
scenario 'see comments for answer', js: true do
sign_in(user)
3.times { answer.comments << create(:comment, commentable: answer, user: user) }
visit question_path(question)
within("div#answer#{answer.id} div.comments") do
answer.comments.each do |comment|
expect(page).to have_content comment.body
end
end
end
scenario 'to be fill comment with invalid data', js: true do
sign_in(user)
visit question_path(question)
within("div#answer#{answer.id} div.comments") do
fill_in 'ะะฐั ะบะพะผะผะตะฝัะฐัะธะน', with: ''
click_on 'Add comment'
wait_for_ajax
end
expect(page).to have_content 'Body can\'t be blank'
end
end
describe "Non-authenticated user" do
scenario 'see comments for answer', js: true do
3.times { answer.comments << create(:comment, commentable: answer, user: user) }
visit question_path(question)
within("div#answer#{answer.id} div.comments") do
answer.comments.each do |comment|
expect(page).to have_content comment.body
end
end
end
scenario 'can not write comment to question', js: true do
visit question_path(question)
within("div#answer#{answer.id} div.comments") do
expect(page).to_not have_selector "form#new_comment"
end
end
end
context "multiple sessions" do
given!(:question2) { create(:question) }
scenario "comment on answer appears on another user's page", js: true do
Capybara.using_session('user') do
sign_in user
visit question_path(question)
expect(page).to have_content question.title
expect(page).to have_content question.body
end
Capybara.using_session('guest') do
visit question_path(question)
end
Capybara.using_session('guest2') do
visit question_path(question2)
end
Capybara.using_session('user') do
within("div#answer#{answer.id} div.comments") do
fill_in 'ะะฐั ะบะพะผะผะตะฝัะฐัะธะน', with: 'text text'
click_on 'Add comment'
wait_for_ajax
end
expect(page).to have_content 'Your comment successfully added.'
expect(page).to have_content 'text text'
end
Capybara.using_session('guest') do
expect(page).to have_content 'text text'
end
Capybara.using_session('guest2') do
expect(page).to_not have_content 'text text'
end
end
end
end<file_sep>require "application_responder"
class ApplicationController < ActionController::Base
self.responder = ApplicationResponder
respond_to :html
include ApplicationHelper
protect_from_forgery with: :exception
before_action :ensure_signup_complete, only: [:new, :create, :update, :destroy]
check_authorization :unless => :devise_controller?
rescue_from CanCan::AccessDenied do |exception|
redirect_to root_url, alert: exception.message
end
def ensure_signup_complete
# ะฃะฑะตะถะดะฐะตะผัั, ััะพ ัะธะบะป ะฝะต ะฑะตัะบะพะฝะตัะฝัะน
return if action_name == 'finish_signup' || (controller_name=="sessions" && action_name=="destroy")
Rails.logger.info("controller name: #{controller_name}")
Rails.logger.info("action name: #{action_name}")
# ะ ะตะดะธัะตะบั ะฝะฐ ะฐะดัะตั 'finish_signup' ะตัะปะธ ะฟะพะปัะทะพะฒะฐัะตะปั
# ะฝะต ะฟะพะดัะฒะตัะดะธะป ัะฒะพั ะฟะพััั
if current_user&.temp_email?
redirect_to finish_signup_path(current_user)
end
end
end
<file_sep>require 'acceptance/acceptance_helper'
feature "User sign out", %q{
In order to be able to finish the work with the system
As an authenticated user
I want to be able to sign out
} do
given(:user) { create(:user) }
scenario 'Registered user try to sign out' do
sign_in(user)
visit questions_path
click_on 'Log out'
expect(page).to have_content 'Signed out successfully.'
expect(current_path).to eq root_path
end
scenario 'An unregistered user attempts to log out of the system' do
visit questions_path
expect(page).to_not have_content 'Log out'
end
end<file_sep>require 'rails_helper'
RSpec.describe CommentsController, type: :controller do
let!(:question) { create(:question) }
# let(:comment) { create(:comment, ) }
describe 'POST #create' do
sign_in_user
context 'with valid attributes' do
subject { post :create, params: { question_id: question.id, comment: attributes_for(:comment) }, format: :json }
it 'assigns the requested object to @commentable' do
subject
expect(assigns(:commentable)).to eq question
end
it 'saves the new comment to database' do
expect { subject }.to change(question.comments, :count).by(1)
end
it 'current user link to the new comment' do
subject
expect(assigns("comment").user).to eq @user
end
it 'render template create' do
subject
expect(response).to render_template "comments/create"
comment = question.comments.first
expect(response.body).to be_json_eql(@user.id).at_path("user_id")
expect(response.body).to be_json_eql(comment.id).at_path("id")
expect(response.body).to be_json_eql(question.id).at_path("commentable_id")
expect(response.body).to be_json_eql(question.class.name.to_json).at_path("commentable_type")
expect(response.body).to be_json_eql(comment.body.to_json).at_path("body")
end
end
context 'with invalid attributes' do
it 'does not save the answer' do
expect { post :create, params: { question_id: question.id, comment: attributes_for(:invalid_comment), format: :json }}.to_not change(Answer, :count)
end
it 'render template create' do
post :create, params: { question_id: question.id, comment: attributes_for(:invalid_comment), format: :json }
expect(response).to have_http_status(422)
end
end
end
end<file_sep>require 'rails_helper'
describe Answer do
it { should belong_to :user}
it { should belong_to :question}
it { should have_many(:attachments).dependent(:destroy) }
it { should have_many(:comments).dependent(:destroy) }
it { should accept_nested_attributes_for :attachments }
it { should validate_presence_of :body}
it { should have_db_column(:accept) }
it { should have_many(:votes).dependent(:destroy) }
it_behaves_like "votable"
describe 'accept answer' do
let(:question) { create(:question) }
let!(:answer1) { create(:answer, question: question, id: 3) }
let!(:answer2) { create(:answer, question: question, accept: true, id: 2) }
let!(:answer3) { create(:answer, question: question, id: 1) }
let!(:answer4) { create(:answer, question: question, accept: true) }
context 'with valid attributes' do
context 'accept answer1' do
it { expect { answer4.accept! }.to_not change { answer4.reload.accept }.from(true) }
it { expect { answer4.accept! }.to change { answer2.reload.accept }.from(true).to(false) }
it { expect { answer1.accept! }.to change { answer1.reload.accept }.from(false).to(true) }
it { expect { answer1.accept! }.to change { answer2.reload.accept }.from(true).to(false) }
it { expect { answer1.accept! }.to_not change { answer3.reload.accept }.from(false) }
end
end
context 'with invalid attributes' do
context 'answer not belongs to question' do
subject { lambda { create(:answer, question: create(:question)).accept! } }
it { should_not change { answer1.reload.accept }.from(false) }
it { should_not change { answer2.reload.accept }.from(true) }
end
end
end
describe "send notify mail to the subscribers user" do
describe "valid attributes" do
let(:answer) { build(:answer) }
it 'with new answer' do
expect(NotifySubscribersJob).to receive(:perform_later).with(answer).and_call_original
answer.save
end
end
describe "invalid attributes" do
let(:answer) { build(:invalid_answer) }
it 'with new answer' do
expect(NotifySubscribersJob).to_not receive(:perform_later).with(answer).and_call_original
answer.save
end
end
end
end<file_sep>require 'rails_helper'
RSpec.describe AnswersController, type: :controller do
let(:answer) { create(:answer) }
let(:question) { create(:question) }
describe 'POST #create' do
sign_in_user
context 'with valid attributes' do
let(:question) { create(:question) }
it 'saves the new answer to database' do
expect { post :create, params: { question_id: question, answer: attributes_for(:answer) }, format: :js }.to change(question.answers, :count).by(1)
end
it 'current user link to the new answer' do
post 'create', params: { question_id: question, answer: attributes_for(:answer), format: :js }
expect(assigns("answer").user).to eq @user
end
it 'render template create' do
post :create, params: { question_id: question, answer: attributes_for(:answer), format: :js }
expect(response).to render_template :create
end
end
context 'with invalid attributes' do
it 'does not save the answer' do
expect { post :create, params: { question_id: question, answer: attributes_for(:invalid_answer), format: :js }}.to_not change(Answer, :count)
end
it 'render template create' do
post :create, params: { question_id: question, answer: attributes_for(:invalid_answer), format: :js }
expect(response).to render_template :create
end
end
end
describe 'PATCH #update' do
sign_in_user
let!(:answer) { create(:answer, user: @user) }
context 'with valid attributes' do
it 'assigns the requested answer to @answer' do
patch :update, params: {id: answer, answer: {body: 'Body new'}, format: :js}
expect(assigns(:answer)).to eq answer
end
it 'change answer attributes' do
patch :update, params: {id: answer, answer: {body: 'Body new'}, format: :js}
answer.reload
expect(answer.body).to eq 'Body new'
end
it 'render updated template' do
patch :update, params: {id: answer, answer: {body: 'Body new'}, format: :js}
expect(response).to render_template :update
end
end
context 'with invalid attributes' do
it 'does not change answer attributes' do
body = answer.body
patch :update, params: {id: answer, answer: attributes_for(:invalid_answer).merge(question_id: nil), format: :js}
answer.reload
expect(answer.body).to eq body
expect(answer.question).to_not eq nil
end
it 'render updated template' do
patch :update, params: {id: answer, answer: attributes_for(:invalid_answer).merge(question_id: nil), format: :js}
expect(response).to render_template :update
end
end
end
describe 'DELETE #destroy' do
sign_in_user
it 'deletes answer of author' do
answer = create(:answer, user: @user)
expect {delete :destroy, params: {id: answer, format: :js}}.to change(Answer, :count).by(-1)
end
it 'user can not delete answer of other author' do
answer1 = create(:answer, user: create(:user), question: answer.question)
expect {delete :destroy, params: {id: answer1, format: :js}}.to_not change(Answer, :count)
end
it 'redirects to question view' do
answer = create(:answer, user: @user)
delete :destroy, params: {id: answer, format: :js}
expect(response).to render_template :destroy
end
end
describe 'PATCH #accept' do
sign_in_user
context "Author of question" do
let!(:question) { create(:question, user: @user) }
let!(:answer) { create(:answer, question: question) }
it 'assigns the requested answer to @answer' do
patch :accept, params: {id: answer, format: :js}
expect(assigns(:answer)).to eq answer
end
it 'change answer accept attribute' do
expect(answer.accept).to eq false
patch :accept, params: {id: answer, format: :js}
answer.reload
expect(answer.accept).to eq true
end
it 'reset accept field of other answers from the question' do
answer2 = create(:answer, question: question, accept: true)
answer3 = create(:answer, question: question, accept: true)
patch :accept, params: {id: answer, format: :js}
answer.reload
answer2.reload
answer3.reload
expect(answer.accept).to eq true
expect(answer2.accept).to eq false
expect(answer3.accept).to eq false
end
it 'render accept template' do
patch :accept, params: {id: answer, format: :js}
expect(response).to render_template :accept
end
end
context "Non-author of question" do
it 'current user is not the author of the question' do
expect(@user).to_not eq question.user
end
it 'assigns the requested answer to @answer' do
patch :accept, params: {id: answer, format: :js}
expect(assigns(:answer)).to eq answer
end
it 'not change answer accept attribute' do
expect(answer.accept).to eq false
patch :accept, params: {id: answer, format: :js}
answer.reload
expect(answer.accept).to eq false
end
it 'not reset accept field of other answers from the question' do
answer2 = create(:answer, question: question, accept: true)
answer3 = create(:answer, question: question, accept: true)
patch :accept, params: {id: answer, format: :js}
answer.reload
answer2.reload
answer3.reload
expect(answer.accept).to eq false
expect(answer2.accept).to eq true
expect(answer3.accept).to eq true
end
it 'redirect to root path' do
patch :accept, params: {id: answer, format: :js}
#expect(response).to render_template :accept
expect(response).to redirect_to root_url
end
end
end
it_behaves_like "voted" do
let(:object) { answer }
end
end
<file_sep>require 'rails_helper'
RSpec.describe QuestionsController, type: :controller do
let(:question) { create(:question) }
describe 'GET #index' do
subject { get :index }
it 'populates an array of all questions' do
questions = create_list(:question, 2)
subject
expect(assigns(:questions)).to eq questions
end
it 'renders index view' do
subject
expect(response).to render_template :index
end
end
describe 'GET #show' do
describe "non-authenticate user" do
before { get :show, params: {id: question} }
it 'assigns the requested question to @question' do
expect(assigns(:question)).to eq question
end
it 'assigns the votes to @question.votes' do
user = create(:user)
vote = create(:vote, user: user, votable: question, value: 1)
expect(assigns(:question).votes).to eq [vote]
end
it 'build a new Attachment to @answer.attachments' do
expect(assigns(:answer).attachments.first).to be_a_new(Attachment)
end
it 'renders show view' do
expect(response).to render_template :show
end
end
describe "authenticate user" do
sign_in_user
let!(:subscription) { @user.subscribe(question) }
before { get :show, params: {id: question} }
it 'assigns the subscription to @subscription' do
expect(assigns(:subscription)).to eq subscription
end
end
end
describe 'GET #new' do
sign_in_user
before { get :new }
it 'assigns a new Question to @question' do
expect(assigns(:question)).to be_a_new(Question)
end
it 'build a new Attachment to @question.attachments' do
expect(assigns(:question).attachments.first).to be_a_new(Attachment)
end
it 'renders new view' do
expect(response).to render_template :new
end
end
describe 'GET #edit' do
sign_in_user
before { get :edit, params: {id: question} }
it 'assigns the requested question to @question' do
expect(assigns(:question)).to eq question
end
it 'renders edit view' do
expect(response).to render_template :edit
end
end
describe 'POST #create' do
sign_in_user
context 'with valid attributes' do
it 'saves the new question to database' do
expect { post :create, params: { question: attributes_for(:question) }}.to change(Question, :count).by(1)
end
it 'current user link to the new question' do
post 'create', params: { question: attributes_for(:question) }
expect(assigns("question").user).to eq @user
end
it 'redirects to show view' do
post :create, params: { question: attributes_for(:question) }
expect(response).to redirect_to question_path(assigns(:question))
end
end
context 'with invalid attributes' do
it 'does not save the question' do
expect { post :create, params: { question: attributes_for(:invalid_question) }}.to_not change(Question, :count)
end
it 're-renders new view' do
post :create, params: { question: attributes_for(:invalid_question) }
expect(response).to render_template :new
end
end
end
describe 'PATCH #update' do
sign_in_user
let!(:question) { create(:question, user: @user) }
context 'with valid attributes' do
it 'assigns the requested question to @question' do
patch :update, params: {id: question, question: {title:'Title new', body: 'Body new'}}
expect(assigns(:question)).to eq question
end
it 'change question attributes' do
patch :update, params: {id: question, question: {title:'Title new', body: 'Body new'}}
question.reload
expect(question.title).to eq 'Title new'
expect(question.body).to eq 'Body new'
end
it 'redirects to the updated question' do
patch :update, params: {id: question, question: {title:'Title new', body: 'Body new'}}
expect(response).to redirect_to question
end
end
context 'with invalid attributes' do
let!(:title) { question.title }
let!(:body) { question.body }
it 'does not change question attributes' do
patch :update, params: {id: question, question: attributes_for(:invalid_question)}
question.reload
expect(question.title).to eq title
expect(question.body).to eq body
end
it 're-renders edit view' do
patch :update, params: {id: question, question: attributes_for(:invalid_question)}
expect(response).to render_template :edit
end
end
end
describe 'DELETE #destroy' do
sign_in_user
it 'only author can be delete question' do
question = create(:question, user: @user)
expect {delete :destroy, params: {id: question}}.to change(Question, :count).by(-1)
end
it 'user can not delete question of other author' do
question1 = create(:question, user: create(:user))
expect {delete :destroy, params: {id: question1}}.to_not change(Question, :count)
end
it 'redirects to index view' do
question = create(:question, user: @user)
delete :destroy, params: {id: question}
expect(response).to redirect_to questions_path
end
end
it_behaves_like "voted" do
let(:object) { question }
end
end
<file_sep>class CommentsController < ApplicationController
before_action :authenticate_user!
before_action :load_commentable
after_action :publish_comment, only: %i[create]
authorize_resource
respond_to :json
def create
respond_with(@comment = @commentable.comments.create(comment_params.merge(user: current_user)))
end
private
def comment_params
params.require(:comment).permit(:commentable_id, :commentable_type, :body)
end
def load_commentable
if params.key? :question_id
@commentable = Question.find(params[:question_id])
else
@commentable = Answer.find(params[:answer_id])
end
end
def publish_comment
return if @comment.errors.any?
if @commentable.is_a?(Question)
question_id = @commentable.id
else
question_id = @commentable.question.id
end
ActionCable.server.broadcast(
"questions/#{question_id}/comments",
renderer.render(
partial: "comments/data",
locals: { comment: @comment }
)
)
end
end
<file_sep>require 'acceptance/acceptance_helper'
feature 'Add files to answer', %q{
I order to be able illustrate my answer
As an authenticate user
I want to be add files to answer
} do
given(:user) { create(:user)}
given(:question) { create(:question) }
scenario 'User add files to answer', js: true do
sign_in(user)
visit question_path(question)
fill_in 'Body', with: 'Body 1'
within(:xpath, "//div[@id='attachments']/div[@class='nested-fields'][1]/div[@class='field']") do
attach_file 'File', "#{Rails.root}/spec/spec_helper.rb"
end
click_on 'add file'
within(:xpath, "//div[@id='attachments']/div[@class='nested-fields'][2]/div[@class='field']") do
attach_file 'File', "#{Rails.root}/spec/rails_helper.rb"
end
click_on 'Ask answer'
expect(page).to have_link"spec_helper.rb", href: "/uploads/attachment/file/1/spec_helper.rb"
expect(page).to have_link"rails_helper.rb", href: "/uploads/attachment/file/2/rails_helper.rb"
end
end<file_sep>require "rails_helper"
shared_examples_for "voted" do
describe 'PATCH #vote' do
sign_in_user
context "User vote for object" do
context "vote up" do
it 'assigns the requested question to @question' do
patch :vote_up, params: {id: object, format: :json}
expect(assigns(:votable)).to eq object
end
it 'change to up +1 vote' do
expect { patch :vote_up, params: {id: object, format: :json} }.to change(Vote, :count).by(1)
end
it 'render vote to json' do
patch :vote_up, params: {id: object, format: :json}
expect(response).to be_success
expect(response.body).to be_json_eql(object.class.name.downcase.to_json).at_path("object_klass")
expect(response.body).to be_json_eql(object.id).at_path("object_id")
expect(response.body).to be_json_eql(object.votes.count).at_path("count")
end
end
context "vote down" do
it 'assigns the requested votable to object' do
patch :vote_down, params: {id: object, format: :json}
expect(assigns(:votable)).to eq object
end
it 'change to down -1 vote' do
vote = create(:vote, votable: object, value: 1)
patch :vote_down, params: {id: object, format: :json}
expect(object.vote_rating).to eq 0
expect(object.votes.count).to eq 2
end
it 'empty votes to change to down -1 vote' do
expect { patch :vote_down, params: {id: object, format: :json} }.to change(Vote, :count).by(1)
end
it 'render vote to json' do
patch :vote_down, params: {id: object, format: :json}
expect(response).to be_success
expect(response.body).to be_json_eql(object.class.name.downcase.to_json).at_path("object_klass")
expect(response.body).to be_json_eql(object.id).at_path("object_id")
expect(response.body).to be_json_eql(object.vote_rating).at_path("count")
end
end
end
context "Author of object can't vote for object" do
let!(:object1) { create(object.class.name.downcase.to_sym, user: @user) }
it 'to not change vote up' do
expect { patch :vote_up, params: {id: object1, format: :json} }.to_not change(Vote, :count)
end
it 'to not change vote down' do
object1.votes << create(:vote, user: @user, votable: object1, value: -1)
expect { patch :vote_down, params: {id: object1, format: :json} }.to_not change(Vote, :count)
end
end
context 'Authenticate user vote up for object only one time' do
it 'to vote up' do
expect do
patch :vote_up, params: {id: object, format: :json}
patch :vote_up, params: {id: object, format: :json}
end.to_not change(Vote, :count)
end
it 'to vote down' do
object.votes << create(:vote, user: @user, votable: object, value: 1)
object.votes << create(:vote, user: create(:user), votable: object, value: 1)
expect(object.vote_rating).to eq 2
patch :vote_down, params: {id: object, format: :json}
patch :vote_down, params: {id: object, format: :json}
expect(object.vote_rating).to eq 1
expect(object.votes.count).to eq 1
end
end
context 'Authenticated user can cancel' do
it 'vote up' do
expect do
patch :vote_up, params: {id: object, format: :json}
patch :vote_up, params: {id: object, format: :json}
end.to_not change(Vote, :count)
end
it 'vote down' do
expect do
patch :vote_down, params: {id: object, format: :json}
patch :vote_down, params: {id: object, format: :json}
end.to_not change(Vote, :count)
end
end
end
end<file_sep>require 'acceptance/acceptance_helper'
feature "User can write an answer to a question", %q{
In order to be able to help solve the problem
As an user
I want to be able to write an answer to the question
} do
given(:user) { create(:user) }
given(:question) { create(:question) }
fscenario 'Authenticated user answer to question', js: true do
sign_in(user)
visit question_path(question)
expect(page).to have_content question.title
expect(page).to have_content question.body
fill_in 'Body', with: 'text text'
click_on 'Ask answer'
wait_for_ajax
expect(page).to have_content 'Answer was successfully created'
expect(page).to have_content 'text text'
end
scenario 'Authenticated user to be fill answer invalid data', js: true do
sign_in(user)
visit question_path(question)
expect(page).to have_content question.title
expect(page).to have_content question.body
fill_in 'Body', with: ''
click_on 'Ask answer'
wait_for_ajax
expect(page).to have_content 'Body can\'t be blank'
end
scenario 'Non-authenticated user can not answer to question', js: true do
visit question_path(question)
expect(page).to_not have_content 'Ask answer'
end
context "multiple sessions" do
given!(:question2) { create(:question) }
scenario "answer on question appears on another user's page", js: true do
Capybara.using_session('user') do
sign_in user
visit question_path(question)
expect(page).to have_content question.title
expect(page).to have_content question.body
end
Capybara.using_session('guest') do
visit question_path(question)
end
Capybara.using_session('guest2') do
visit question_path(question2)
end
Capybara.using_session('user') do
within("form.new_answer") do
fill_in 'Body', with: 'text text'
click_on 'Ask answer'
wait_for_ajax
end
expect(page).to have_content 'Answer was successfully created'
expect(page).to have_content 'text text'
end
Capybara.using_session('guest') do
expect(page).to have_content 'text text'
end
Capybara.using_session('guest2') do
expect(page).to_not have_content 'text text'
end
end
end
end<file_sep>require "rails_helper"
RSpec.describe DailyMailer, type: :mailer do
describe ".digest" do
let(:user) { create(:user) }
let(:questions_hash) { 2.times.map {|i| {title: "Title #{i}", url: "/questions/#{i}"} } }
let(:mail1) { DailyMailer.digest(user, questions_hash) }
it "assigns question_hash to @questions" do
mail :digest, user, questions_hash
expect(assigns(:questions).map { |question| question.symbolize_keys }).to eq questions_hash
end
it "renders the headers" do
expect(mail1.subject).to eq("New questions for last 24h")
expect(mail1.to).to eq [user.email]
expect(mail1.from).to eq(["<EMAIL>"])
end
it "renders the body" do
questions_hash.each do |question|
expect(mail1.body.encoded).to match("#{question[:title]}")
expect(mail1.body.encoded).to match("#{question[:url]}")
end
end
end
describe ".notify_new_answer" do
let!(:answer) { create(:answer) }
let(:question) { answer.question }
let(:user) { answer.question.user }
let(:mail1) { DailyMailer.notify_new_answer(user, answer) }
it "assigns answer to @answer" do
mail :notify_new_answer, user, answer
expect(assigns(:answer)).to eq answer
expect(assigns(:question)).to eq question
end
it "renders the headers" do
expect(mail1.subject).to eq("New answer for question '#{question.title}'")
expect(mail1.to).to eq [user.email]
expect(mail1.from).to eq(["<EMAIL>"])
end
it "renders the body" do
expect(mail1.body.encoded).to match("#{answer.body}")
expect(mail1.body.encoded).to match("#{question_url(question)}")
end
end
describe ".notify_update_question" do
let!(:question) { create(:question) }
let(:user) { question.user }
let(:mail1) { DailyMailer.notify_update_question(user, question) }
it "assigns question to @question" do
mail :notify_update_question, user, question
expect(assigns(:question)).to eq question
end
it "renders the headers" do
expect(mail1.subject).to eq("The content of the question '#{question.title}' has been updated")
expect(mail1.to).to eq [user.email]
expect(mail1.from).to eq(["<EMAIL>"])
end
it "renders the body" do
expect(mail1.body.encoded).to match("#{question.body}")
expect(mail1.body.encoded).to match("#{question_url(question)}")
end
end
end
<file_sep>json.(comment, :id, :commentable_id, :commentable_type, :body)
json.body_html ApplicationController.render(
partial: "comments/comment",
locals: { comment: comment }
)
json.messages flash.to_h
json.user_id current_user.id<file_sep>class Question < ApplicationRecord
include Votable
belongs_to :user
has_many :answers, dependent: :destroy
has_many :attachments, as: :attachable, dependent: :destroy
has_many :comments, as: :commentable, dependent: :destroy
has_many :subscriptions, dependent: :destroy
validates :title, :body, presence: true
accepts_nested_attributes_for :attachments, reject_if: :all_blank
after_update :update_question
after_create :subscribe_question
def self.digest
Question.all.where("created_at >= ?", Time.zone.now.beginning_of_day)
end
private
def update_question
NotifySubscribersJob.perform_later(self)
end
def subscribe_question
self.user.subscribe(self)
end
end
<file_sep>require 'acceptance/acceptance_helper'
feature 'Create question', %q{
In order to be able get answer
As an user
I want to be able ask question
} do
given(:user) { create(:user)}
scenario 'Authenticate user ask question' do
sign_in(user)
visit questions_path
click_on 'Ask question'
fill_in 'Title', with: 'Title 1'
fill_in 'Body', with: 'Body 1'
click_on 'Create'
expect(page).to have_content 'Title 1'
expect(page).to have_content 'Body 1'
expect(page).to have_content 'Your question successfully created.'
end
scenario 'Authenticate user ask invalid question' do
sign_in(user)
visit questions_path
click_on 'Ask question'
fill_in 'Title', with: ''
fill_in 'Body', with: 'Body 1'
click_on 'Create'
expect(page).to have_content 'Title can\'t be blank'
end
scenario 'Non-authenticate user ties ask question' do
visit questions_path
expect(page).to_not have_content 'Ask question'
expect(page).to have_content "Log in"
end
context "multiple sessions" do
scenario "question appears on another user's page", js: true do
Capybara.using_session('user') do
sign_in user
visit questions_path
end
Capybara.using_session('user2') do
sign_in create(:user)
visit questions_path
end
Capybara.using_session('guest') do
visit questions_path
end
Capybara.using_session('user') do
click_on 'Ask question'
fill_in 'Title', with: 'Title 1'
fill_in 'Body', with: 'Body 1'
click_on 'Create'
expect(page).to have_content 'Title 1'
expect(page).to have_content 'Body 1'
expect(page).to have_content 'Your question successfully created.'
end
Capybara.using_session('guest') do
expect(page).to have_content 'Title 1'
end
Capybara.using_session('user2') do
expect(page).to have_content 'Title 1'
end
end
end
end<file_sep>class ApplicationJob < ActiveJob::Base
include Rails.application.routes.url_helpers
protected
def default_url_options
Rails.application.config.x.active_job.default_url_options
end
end
<file_sep>require 'rails_helper'
shared_examples_for "votable" do
let!(:model) { described_class }
let!(:user) { create(:user) }
describe '#votes' do
let!(:object) { create(model.to_s.underscore.to_sym) }
it 'vote up' do
expect { object.vote_up!(user) }.to change(Vote, :count).by(1)
end
it 'vote down' do
expect { object.vote_down!(user) }.to change(Vote, :count).by(1)
end
it 'vote rating' do
object.vote_up!(user)
object.vote_down!(user)
expect(object.vote_rating).to eq -1
end
it 'vote up exists' do
object.vote_up!(user)
expect(object.vote_up_exists?(user)).to eq true
expect(object.vote_exists?(user)).to eq true
end
it 'vote down exists' do
object.vote_down!(user)
expect(object.vote_down_exists?(user)).to eq true
expect(object.vote_exists?(user)).to eq true
end
it 'vote reset' do
object.vote_up!(user)
object.vote_reset!(user)
expect(object.vote_rating).to eq 0
end
describe 'Author of question' do
it 'can not vote up for him' do
expect { object.vote_up!(object.user) }.to_not change(Vote, :count)
end
it 'can not vote down for him' do
expect { object.vote_down!(object.user) }.to_not change(Vote, :count)
end
end
describe "Authenticate user vote for object only one time" do
it "vote up" do
expect do
object.vote_up!(user)
object.vote_up!(user)
end.to_not change(Vote, :count)
end
it "vote down" do
expect do
object.vote_down!(user)
object.vote_down!(user)
end.to_not change(Vote, :count)
end
it 'vote down after vote up' do
object.vote_up!(user)
expect(object.vote_up_exists?(user)).to eq true
object.vote_down!(user)
expect(object.vote_up_exists?(user)).to eq false
expect(object.vote_down_exists?(user)).to eq true
end
it 'vote up after vote down' do
object.vote_down!(user)
expect(object.vote_down_exists?(user)).to eq true
object.vote_up!(user)
expect(object.vote_down_exists?(user)).to eq false
expect(object.vote_up_exists?(user)).to eq true
end
it "can't cancel someone else's vote" do
object.vote_down!(create(:user))
object.vote_up!(user)
expect(object.vote_rating).to eq 0
object.vote_reset!(user)
expect(object.vote_rating).to eq -1
end
end
describe "Authenticated user can cancel" do
it "vote up" do
expect do
object.vote_up!(user)
object.vote_up!(user)
end.to_not change(Vote, :count)
end
it "vote down" do
expect do
object.vote_down!(user)
object.vote_down!(user)
end.to_not change(Vote, :count)
end
end
describe 'Auto update static rating field on object' do
it 'to vote up' do
object.vote_up!(user)
object.reload
expect(object.rating).to eq 1
end
it 'to vote down' do
object.vote_down!(user)
object.reload
expect(object.rating).to eq -1
end
end
end
end
<file_sep>class User < ApplicationRecord
TEMP_EMAIL_PREFIX = 'qna2017@me'
TEMP_EMAIL_REGEX = /\Aqna2017@me/
has_many :questions, dependent: :destroy
has_many :answers, dependent: :destroy
has_many :authorizations, dependent: :destroy
has_many :subscriptions, dependent: :destroy
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :confirmable,
:recoverable, :rememberable, :trackable, :validatable,
:omniauthable, omniauth_providers: [:facebook, :twitter]
def author_of?(model)
model.user_id == id if model.respond_to?(:user_id)
end
def subscribe_of?(model)
model.subscriptions.exists?(user_id: self.id)
end
def subscribe(model)
model.subscriptions.find_or_create_by(user: self)
end
def unsubscribe(model)
model.subscriptions.where(user: self).destroy_all
end
def subscription_of(model)
model.subscriptions.where(user: self).first
end
def self.find_for_omniauth(auth)
authorization = Authorization.where(provider: auth.provider, uid: auth.uid).first
return authorization.user if authorization
email = auth.info.email.nil? || auth.info.email.empty? ? create_temp_email(auth) : auth.info.email
user = User.where(email: email).first
unless user
password = Devise.friendly_token[0,20]
user = User.new(email: email, password: <PASSWORD>, password_confirmation: <PASSWORD>)
if user.temp_email?
user.skip_confirmation!
end
user.save
end
user.create_authorization(auth)
user
end
def self.create_temp_email(auth)
"#{TEMP_EMAIL_PREFIX}-#{auth.uid}-#{auth.provider}.com"
end
def email_verified?
!(self.email.empty? || temp_email?) && confirmed?
end
def temp_email?
self.email.match?(TEMP_EMAIL_REGEX)
end
def update_email(params)
if update(params.merge(confirmed_at: nil))
send_confirmation_instructions
yield if block_given?
end
end
def move_authorizations(user)
if user
user.authorizations.each do |authorization|
self.authorizations.create(authorization.attributes.except("id", "created_at",
"updated_at"))
end
user.destroy!
yield if block_given?
end
end
def create_authorization(auth)
self.authorizations.create(provider: auth.provider, uid: auth.uid)
end
def update_params(params)
email = params[:email]
user = User.find_by_email(email)
if user
user.move_authorizations(self) do
return {status: :existing, user: user }
end
else
self.update_email(params) do
return {status: :new, user: self }
end
end
end
end
<file_sep>require 'rails_helper'
RSpec.describe Search, type: :model do
describe '.by_condition' do
it_behaves_like "Searched" do
let(:classes) { [Question] }
let(:condition) { "Questions"}
end
it_behaves_like "Searched" do
let(:classes) { [Answer] }
let(:condition) { "Answers"}
end
it_behaves_like "Searched" do
let(:classes) { [Comment] }
let(:condition) { "Comments"}
end
it_behaves_like "Searched" do
let(:classes) { [User] }
let(:condition) { "Users"}
end
it_behaves_like "Searched" do
let(:classes) { [Question, Answer, Comment, User] }
let(:condition) { "Any"}
end
it_behaves_like "Searched" do
let(:classes) { [Question, Answer, Comment, User] }
let(:condition) { "Unknow"}
end
end
end<file_sep>require 'acceptance/acceptance_helper'
feature 'Accept answer', %q{
In order to be able to accept right answer solved problem
As an author of question
I want to be able to accept an answer to the question
} do
describe 'Author of question' do
given(:question) { create(:question) }
given(:user) { question.user }
given!(:other_user) { create(:user) }
given!(:answer) { create(:answer, question: question, user: other_user, body: "Answer [accept]") }
given!(:answer2) { create(:answer, question: question, user: other_user) }
given!(:answer3) { create(:answer, question: question, user: other_user, accept: true) }
before do
sign_in user
visit question_path(question)
end
scenario 'see accept link' do
within '.answers' do
expect(page).to have_link('Accept')
end
end
scenario 'accept answer', js: true do
within "div#answer#{answer.id}" do
click_on 'Accept'
wait_for_ajax
expect(page).to_not have_link('Accept')
expect(page).to have_selector("span.accept")
end
[answer2, answer3].each do |a|
within "div#answer#{a.id}" do
expect(page).to have_link('Accept')
expect(page).to_not have_selector("span.accept")
end
end
end
scenario 'accept other answer', js: true do
# accept answer
within "div#answer#{answer.id}" do
click_on 'Accept'
wait_for_ajax
expect(page).to_not have_link('Accept')
expect(page).to have_selector("span.accept")
end
[answer2, answer3].each do |a|
within "div#answer#{a.id}" do
expect(page).to have_link('Accept')
expect(page).to_not have_selector("span.accept")
end
end
# accept answer3
within "div#answer#{answer3.id}" do
click_on 'Accept'
wait_for_ajax
expect(page).to_not have_link('Accept')
expect(page).to have_selector("span.accept")
end
[answer2, answer].each do |a|
within "div#answer#{a.id}" do
expect(page).to have_link('Accept')
expect(page).to_not have_selector("span.accept")
end
end
end
end
describe 'Non author of question' do
given(:user) { create(:user) }
given(:question) { create(:question, user: create(:user))}
given!(:answer) { create(:answer, question: question, user: create(:user) ) }
before do
sign_in user
visit question_path(question)
end
scenario "don't see accept link" do
within '.answers' do
expect(page).to_not have_link('Accept')
end
end
end
describe 'Non-authenticated user' do
given(:question) { create(:question) }
given(:user) { question.user }
given!(:answer) { create(:answer, question: question, user: user) }
scenario 'can not see accept link on answer of question' do
visit question_path(question)
within '.answers' do
expect(page).to_not have_link('Accept')
end
end
end
end<file_sep>== README
ะัะพะตะบั "ะกะธััะตะผะฐ ะฒะพะฟัะพัะพะฒ ะธ ะพัะฒะตัะพะฒ" โ ะฟะพะทะฒะพะปัััะธะน ะฟะพะปัะทะพะฒะฐัะตะปัะผ ะทะฐะดะฐัั ะฒะพะฟัะพั ะธะปะธ ะพัะฒะตัะธัั ะฝะฐ ัะถะต ะทะฐะดะฐะฝะฝัะต ะฒะพะฟัะพัั. ะััั ะพะฑััะตะฝะธั ั 15.05.17
ะ ะฐะทัะฐะฑะพัะฐะฝะฝัะน ะฒ ัะฐะผะบะฐั
ะพะฑััะตะฝะธั ะฒ ัะบะพะปะต Thinknetica ะฟะพ ะบัััั "ะัะพัะตััะธะพะฝะฐะปัะฝะฐั ัะฐะทัะฐะฑะพัะบะฐ ะฝะฐ Ruby on Rails"(http://www.thinknetica.com/ror_advanced)<file_sep>require 'acceptance/acceptance_helper'
feature 'User sign up', %q{
In order to be able to ask question
As an user
I want to be able to sign up
} do
given(:user) { create(:user) }
scenario 'Registered user try to sign up' do
sign_in(user)
expect(page).to have_content 'Signed in successfully.'
expect(current_path).to eq root_path
visit new_user_registration_path
expect(page).to have_content 'You are already signed in.'
end
scenario 'Non-registered user try to sign up' do
visit new_user_registration_path
fill_in 'Email', with: '<EMAIL>'
fill_in 'Password', with: '<PASSWORD>'
fill_in 'Password confirmation', with: '<PASSWORD>'
click_on 'Sign up'
expect(page).to have_content "A message with a confirmation link has been sent to your email address"
open_email('<EMAIL>')
current_email.click_link 'Confirm my account'
expect(page).to have_content 'Your email address has been successfully confirmed.'
fill_in 'Email', with: '<EMAIL>'
fill_in 'Password', with: '<PASSWORD>'
click_on 'Log in'
expect(page).to have_content 'Signed in successfully.'
end
scenario 'Non-registered user try to sign up with invalid data' do
visit new_user_registration_path
fill_in 'Password', with: '<PASSWORD>'
fill_in 'Password confirmation', with: '<PASSWORD>'
click_on 'Sign up'
expect(page).to have_content "Email can't be blank"
end
end<file_sep>require 'sidekiq/web'
Rails.application.routes.draw do
authenticate :user, lambda { |u| u.admin? } do
mount Sidekiq::Web => '/sidekiq'
end
use_doorkeeper
devise_for :users, controllers: { omniauth_callbacks: 'omniauth_callbacks' }
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
concern :votable do
member do
patch 'vote_up'
patch 'vote_down'
end
end
resources :questions, concerns: [:votable] do
resources :answers, shallow: true, except: %i[index show new edit], concerns: [:votable] do
patch 'accept', on: :member
resources :comments, only: %i[create]
end
resources :comments, only: %i[create]
end
resources :subscriptions, only: %i[create destroy]
resources :attachments, only: [:destroy]
match '/users/:id/finish_signup' => 'users#finish_signup', via: [:get, :patch], as: :finish_signup
match '/users/:id', to: 'users#show', via: 'get', as: :user
get '/search' => 'searches#search'
root 'questions#index'
namespace :api do
namespace :v1 do
resources :profiles do
get :me, on: :collection
end
resources :questions do
resources :answers, only: [:index, :show, :create], shallow: true
end
end
end
mount ActionCable.server => '/cable'
end
<file_sep>shared_examples_for "Searchable" do
scenario 'find objects', js: true do
ThinkingSphinx::Test.run do
index
visit questions_path
within '.search' do
fill_in 'query', with: query
select condition, from: :condition
click_on 'Search'
wait_for_ajax
end
data.each do |value|
within ".search-results" do
value[:objects].each do |object|
expect(page).to have_content object.send(value[:attr])
end
end
end
end
end
end<file_sep>require 'rails_helper'
RSpec.describe AttachmentsController, type: :controller do
describe 'DELETE #destroy' do
sign_in_user
let!(:question) { create(:question, user: @user) }
let!(:attachment) { create(:attachment, attachable: question) }
it 'assigns the requested attachment to @attachment' do
delete :destroy, params: {id: attachment, format: :js}
expect(assigns(:attachment)).to eq attachment
end
it 'delete attachment of question' do
expect {delete :destroy, params: {id: attachment, format: :js}}.to change(Attachment, :count).by(-1)
end
it 'user can not delete attachament of other author' do
attachment = create(:attachment, attachable: create(:question, user: create(:user)))
expect {delete :destroy, params: {id: attachment, format: :js}}.to_not change(Attachment, :count)
end
it 'render destroy template' do
delete :destroy, params: {id: attachment, format: :js}
expect(response).to render_template :destroy
end
end
end<file_sep>require 'acceptance/acceptance_helper'
feature 'Remove files from answer', %q{
I order to be able remove file from my answer
As an author of answer
I want to be remove files from answer
} do
given!(:user) { create(:user) }
given!(:answer) { create(:answer_with_attachments, count: 1) }
scenario 'Author delete files from answer', js: true do
sign_in(answer.user)
visit question_path(answer.question)
within("div#answer_attachments > div#attachment1") do
click_on 'remove file'
wait_for_ajax
end
expect(page).to_not have_link "spec_helper.rb"
end
scenario 'Non-author can\'t delete files from answer', js: true do
expect(answer.user).to_not eq user
sign_in(user)
visit question_path(answer.question)
within("#answer_attachments") do
expect(page).to_not have_link"remove file"
end
end
end<file_sep>require 'acceptance/acceptance_helper'
feature 'Remove files from question', %q{
I order to be able remove file from my question
As an author of question
I want to be remove files from question
} do
given!(:user) { create(:user) }
given!(:question) { create(:question_with_attachments, count: 1) }
scenario 'Author delete files from question', js: true do
sign_in(question.user)
visit question_path(question)
within("#attachment1") do
click_on 'remove file'
wait_for_ajax
end
expect(page).to_not have_link "spec_helper.rb"
end
scenario 'Non-author can\'t delete files from question', js: true do
expect(question.user).to_not eq user
sign_in(user)
visit question_path(question)
within("#attachments1") do
expect(page).to_not have_link"remove file"
end
end
end<file_sep>require 'rails_helper'
RSpec.describe DailyDigestJob, type: :job do
let(:users) { create_list(:user, 1) }
let!(:questions) { create_list(:question, 2, user: users.first)}
let!(:questions_hash) do
questions.each.map { |question| {title: question.title, url: question_url(question)} }
end
it 'should send daily digest to all users' do
users.each { |user| expect(DailyMailer).to receive(:digest).with(user, questions_hash).and_call_original }
DailyDigestJob.perform_now
end
end
def question_url(obj)
"http://localhost:3000/questions/#{obj.id}"
end
<file_sep>require 'acceptance/acceptance_helper'
feature "User can view a list of questions", %q{
In order to be able to solve my problem
As an user
I want to be able to view a list of questions
} do
given(:user) { create(:user) }
scenario 'Authenticated user can view a list of questions' do
sign_in(user)
questions = create_list(:question, 5)
visit questions_path
questions.each do |q|
expect(page).to have_content(q.title)
end
end
scenario 'Non-authenticated user can view a list of questions' do
questions = create_list(:question, 5)
visit questions_path
questions.each do |q|
expect(page).to have_content(q.title)
end
end
end<file_sep>require 'rails_helper'
RSpec.describe Subscription, type: :model do
it { should belong_to :user}
it { should belong_to :question}
describe 'Number of questions that can be subscribed to the user' do
let!(:user) { create(:user) }
let!(:questions) { create_list(:question, 5)}
it 'is unlimited' do
expect { questions.each {|question| user.subscribe(question)} }.to change(Subscription, :count).by(5)
end
end
end
<file_sep>require 'rails_helper'
RSpec.describe SearchesController, type: :controller do
describe 'GET #search' do
let!(:questions) { create_list(:question, 10) }
let(:query) { "question" }
subject { get :search, params: { query: query, condition: "Questions", format: :js } }
it 'call search' do
expect(Search).to receive(:by_condition).with("Questions", query)
subject
end
end
end<file_sep>class Answer < ApplicationRecord
include Votable
belongs_to :user
belongs_to :question
has_many :attachments, as: :attachable, dependent: :destroy
has_many :comments, as: :commentable, dependent: :destroy
validates :body, presence: true
accepts_nested_attributes_for :attachments, reject_if: :all_blank
default_scope { order(accept: :desc, id: :asc) }
after_create :new_answer
def accept!
transaction do
question.answers.where('id != ?', id).update_all(accept: false)
update!(accept: true)
end
end
private
def new_answer
NotifySubscribersJob.perform_later(self)
end
end
<file_sep>require 'rails_helper'
RSpec.describe Vote, type: :model do
it { should belong_to :user }
it { should belong_to :votable }
it { should validate_presence_of :votable_id }
it { should validate_presence_of :votable_type }
it '' do
create(:vote, votable: create(:question), value: 1)
should validate_uniqueness_of(:user_id).scoped_to(:votable_id, :votable_type)
end
it "should allow valid values" do
[1,-1].each do |v|
should allow_value(v).for(:value)
end
end
it { should_not allow_value(0).for(:value) }
it { should_not allow_value(nil).for(:value) }
end
<file_sep>class Comment < ApplicationRecord
belongs_to :user
belongs_to :commentable, polymorphic: true, optional: true
validates :commentable_id, :commentable_type, :body, presence: true
default_scope { order(id: :asc) }
end
<file_sep>class Api::V1::BaseController < ApplicationController
before_action :doorkeeper_authorize!
alias_attribute :current_user, :current_resource_owner
respond_to :json
protected
def current_resource_owner
@current_resource_owner ||= User.find(doorkeeper_token.resource_owner_id) if doorkeeper_token&.resource_owner_id
end
end<file_sep>require 'rails_helper'
describe Question do
it { should belong_to :user}
it { should have_many(:answers).dependent(:destroy)}
it { should have_many(:attachments).dependent(:destroy) }
it { should have_many(:votes).dependent(:destroy) }
it { should have_many(:comments).dependent(:destroy) }
it { should have_many(:subscriptions).dependent(:destroy) }
it { should validate_presence_of :title}
it { should validate_presence_of :body}
it { should accept_nested_attributes_for :attachments }
describe ".digest" do
let!(:questions_today) { create_list(:question, 2) }
let!(:question_yesterday) { create(:question, created_at: 1.day.ago) }
it 'return all question in today' do
expect(Question.all.size).to eq 3
expect(Question.digest).to match_array(questions_today)
end
end
it_behaves_like "votable"
describe "send notifications to subscribers" do
let(:question) { create(:question) }
it 'when updating a question' do
expect(NotifySubscribersJob).to receive(:perform_later).with(question).and_call_original
question.update(body: "new body")
end
end
describe "subscription is created" do
let(:question) { build(:question) }
scenario "when you save a new question" do
expect(question.user).to receive(:subscribe).with(question).and_call_original
question.save
end
end
end<file_sep>require 'acceptance/acceptance_helper'
feature 'Vote for question', %q{
In order to be able vote for the question
As an user
I want to be able vote for the question
} do
given(:user) { create(:user)}
given(:question) { create(:question) }
scenario 'Authenticate user vote up for question', js: true do
sign_in(user)
visit question_path(question)
within(".vote") do
expect(page).to have_css ".vote-up"
find(:css, ".vote-up").click
within(".vote-count") do
expect(page).to have_content "1"
end
end
end
scenario "Author of question can't vote for question", js: true do
sign_in(user)
author_question = create(:question, user: user)
visit question_path(author_question)
within(".vote") do
expect(page).to_not have_css ".vote-up"
expect(page).to_not have_css ".vote-down"
end
end
describe 'Authenticate user vote for question only one time' do
scenario "vote up", js: true do
sign_in(user)
visit question_path(question)
within("div#question#{question.id} > .vote") do
expect(page).to have_css ".vote-up"
within(".vote-count") do
expect(page).to have_content "0"
end
find(:css, ".vote-up").click
wait_for_ajax
find(:css, ".vote-up").click
wait_for_ajax
within(".vote-count") do
expect(page).to have_content "0"
end
end
end
scenario "vote down", js: true do
sign_in(user)
question.votes << create(:vote, user: user, votable: question, value: 1)
question.votes << create(:vote, user: create(:user), votable: question, value: 1)
visit question_path(question)
within("div#question#{question.id} > .vote") do
expect(page).to have_css ".vote-down"
within(".vote-count") do
expect(page).to have_content "2"
end
find(:css, ".vote-down").click
wait_for_ajax
find(:css, ".vote-down").click
wait_for_ajax
within(".vote-count") do
expect(page).to have_content "1"
end
end
end
scenario "vote down after vote up", js: true do
sign_in(user)
visit question_path(question)
within("div#question#{question.id} > .vote") do
within(".vote-count") do
expect(page).to have_content "0"
end
find(:css, ".vote-up").click
wait_for_ajax
find(:css, ".vote-down").click
wait_for_ajax
within(".vote-count") do
expect(page).to have_content "-1"
end
end
end
scenario "vote up after vote down", js: true do
sign_in(user)
visit question_path(question)
within("div#question#{question.id} > .vote") do
within(".vote-count") do
expect(page).to have_content "0"
end
find(:css, ".vote-down").click
wait_for_ajax
find(:css, ".vote-up").click
wait_for_ajax
within(".vote-count") do
expect(page).to have_content "1"
end
end
end
end
describe 'Authenticated user can cancel vote for question' do
scenario "vote up", js: true do
sign_in(user)
visit question_path(question)
within("div#question#{question.id} > .vote") do
expect(page).to have_css ".vote-up"
within(".vote-count") do
expect(page).to have_content "0"
end
find(:css, ".vote-up").click
wait_for_ajax
within(".vote-count") do
expect(page).to have_content "1"
end
find(:css, ".vote-up").click
wait_for_ajax
within(".vote-count") do
expect(page).to have_content "0"
end
end
end
scenario "vote down", js: true do
sign_in(user)
visit question_path(question)
within("div#question#{question.id} > .vote") do
expect(page).to have_css ".vote-down"
within(".vote-count") do
expect(page).to have_content "0"
end
find(:css, ".vote-down").click
wait_for_ajax
within(".vote-count") do
expect(page).to have_content "-1"
end
find(:css, ".vote-down").click
wait_for_ajax
within(".vote-count") do
expect(page).to have_content "0"
end
end
end
end
scenario 'Non-authenticate user ties vote for question', js: true do
visit question_path(question)
expect(page).to_not have_css(".vote_up")
expect(page).to_not have_css(".vote_down")
end
end<file_sep>require 'acceptance/acceptance_helper'
feature 'Edit question', %q{
In order to be able to update post
As an authenticated user
I want to be able to edit an question
} do
given(:user) { create(:user) }
describe 'Author' do
given!(:question) { create(:question, user: user) }
before do
sign_in user
visit question_path(question)
end
scenario 'see edit link' do
within '.question' do
expect(page).to have_link('Edit')
end
end
scenario 'edit question', js: true do
within '.question' do
expect(page).to_not have_selector("form.edit_question")
click_on 'Edit'
expect(page).to_not have_link('Edit')
expect(page).to have_selector("textarea")
fill_in 'Body', with: 'new question'
click_on 'Save'
expect(page).to_not have_selector("form.edit_question")
expect(page).to have_link('Edit')
expect(page).to_not have_content(question.body)
expect(page).to have_content('new question')
end
end
end
describe 'Non author' do
given!(:question) { create(:question, user: create(:user) ) }
before do
sign_in user
visit question_path(question)
end
scenario "don't see edit link" do
within '.question' do
expect(page).to_not have_link('Edit')
end
end
scenario "don't see update form" do
within '.question' do
expect(page).to_not have_selector("form.edit_question")
expect(page).to_not have_link('Save')
end
end
end
end<file_sep>class AnswersController < ApplicationController
include Voted
before_action :authenticate_user!
before_action :load_answer, only: [:update, :destroy, :accept]
before_action :load_question, only: [:create]
after_action :publish_answer, only: [:create]
authorize_resource
respond_to :js
def create
@answer = @question.answers.create(answer_params.merge(user: current_user))
errors_to_flash @answer
respond_with @answer
end
def update
@answer.update(answer_params)
respond_with @answer
end
def destroy
respond_with(@answer.destroy!)
end
def accept
respond_with(@answer.accept!)
end
private
def load_answer
@answer = Answer.find(params[:id])
end
def load_question
@question = Question.find_by_id(params[:question_id])
end
def answer_params
params.require(:answer).permit(:question_id, :body, attachments_attributes: [:file])
end
def publish_answer
return if @answer.errors.any?
ActionCable.server.broadcast(
"questions/#{@question.id}/answers",
renderer.render(
partial: "answers/data",
locals: { answer: @answer }
)
)
end
end
<file_sep>require 'acceptance/acceptance_helper'
feature 'Edit answer', %q{
In order to be able to fix mistake
As an authenticated user
I want to be able to edit an answer to the question
} do
#given!(:question) { create(:question_with_answers, answers_count: 1) }
given!(:question) { create(:question) }
given!(:user) { question.user }
describe 'Author' do
given!(:answer) { create(:answer, question: question, user: user) }
before do
sign_in user
visit question_path(question)
end
scenario 'see edit link' do
within '.answers' do
expect(page).to have_link('Edit')
end
end
scenario 'edit answer', js: true do
within "#answer#{answer.id}" do
expect(page).to_not have_selector("form.edit_answer")
click_on 'Edit'
expect(page).to_not have_link('Edit')
expect(page).to have_selector("form.edit_answer")
fill_in 'Body', with: 'new answer'
click_on 'Save'
expect(page).to_not have_selector("form.edit_answer")
expect(page).to have_link('Edit')
expect(page).to_not have_content(answer.body)
expect(page).to have_content('new answer')
end
end
end
describe 'Non author' do
given!(:answer) { create(:answer, question: question, user: create(:user) ) }
before do
sign_in user
visit question_path(question)
end
scenario "don't see edit link" do
within '.answers' do
expect(page).to_not have_link('Edit')
end
end
scenario "don't see update form" do
within "#answer#{answer.id}" do
expect(page).to_not have_selector("form.edit_answer")
expect(page).to_not have_link('Save')
end
end
end
end<file_sep>class SearchesController < ApplicationController
skip_authorization_check
respond_to :js
def search
query = params[:query]
@results = Search.by_condition(params[:condition], query)
end
end | e53140d547c9233a7c49038b7d849fa35d288214 | [
"RDoc",
"Ruby"
] | 66 | Ruby | rustamakhmetov/qna2017 | 83a594a7f7c8f28be8214237cf4806b6c06ac2fa | afae281212a994fa297e9ef4ee5c69a4b793e512 |
refs/heads/master | <file_sep>package ru.geekbrains.spring.lesson1.models;
public class CartItem {
}
<file_sep>package ru.geekbrains.spring.lesson1.models;
public class UnknownEntityException extends Exception {
}
<file_sep>package ru.geekbrains.spring.lesson1.repository;
import org.springframework.stereotype.Component;
import ru.geekbrains.spring.lesson1.models.Product;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@Component
public class ProductRepository {
private List<Product> productList = new ArrayList<>();
public ProductRepository() {
}
@PostConstruct
public void init(){
productList.add(new Product(1l, "apple", 50.0));
productList.add(new Product(2l, "lemon", 75.0));
productList.add(new Product(3l, "orange", 100.0));
productList.add(new Product(4l, "pumpkin", 40.0));
productList.add(new Product(5l, "lemon", 55.0));
System.out.println("test PostConstruct");
}
public List<Product> findAll(){
return Collections.unmodifiableList(productList);
}
public void addProduct(Product product){
productList.add(product);
}
}
| e8d4f200387c0ca24024b866a211687b69b537c2 | [
"Java"
] | 3 | Java | ashulyaev93/homework1-Spring | 7b6d40e6e2b64a9a1ec494aebd39f3591deed88f | 67fb0a1caff6ab56250679162c9a10ec9875c4c7 |
refs/heads/master | <file_sep># README
## Api description
URL | Method | Desc
:------------------------------------ | :----- | :-------
/account/setpassword | `POST` | ่ฎพ็ฝฎๅฏ็
/account/forgetpassword | `POST` | ๅฟ่ฎฐๅฏ็ ้็ฝฎๅฏ็
/v1.0/account/resetpassword | `POST` | ้็ฝฎๅฏ็
## URL parameter
key | Requried | type | description
-------- | -------- | ------ | -----------
min_time | y | string | ๆๆฐๆ้ปๆถ้ด
## Response json
key | Requried | type | description
---- | -------- | ------ | -------------
code | y | number | ่ฟๅ็ถๆ็
data | y | object | ่ฟๅ็ๆฐๆฎ๏ผๅ
ๅ
ๅซ็จๆทๆฐๆฎ
### dataๆฐๆฎ่ฏดๆ
key | Requried | type | description
--------- | -------- | ----- | -----------
blocklist | y | array | ๆ้ปๅ่กจ
#### 1. blockๆฐๆฎ่ฏดๆ
key | Requried | type | description
---------------- | -------- | ------ | -----------
block_time | y | string | ๆ้ปๆถ้ด
uid | y | number | uid
avatar_thumbnail | y | string | ๅคดๅ็ผฉ็ฅๅพ
name | y | string | ๆต็งฐ
## 3. ๆฅๅฃๅ่กจ
### 3.1 POST /account/setpassword
AUTH:True
่ฏทๆฑๅๆฐ
key | Requried | type | description
-------- | -------- | ------ | -----------
phone | y | string | ๆๆบๅท็
password | y | string | ๅฏ็
captcha | y | string | ้ช่ฏ็ ้ช่ฏ
### 3.2 POST /account/forgetpassword
AUTH:True
่ฏทๆฑๅๆฐ
key | Requried | type | description
-------- | -------- | ------ | -----------
phone | y | string | ๆๆบๅท็
password | y | string | ๅฏ็
captcha | y | string | ้ช่ฏ็ ้ช่ฏ
### 3.3 POST `/v1.0/account/resetpassword`
AUTH:True
่ฏทๆฑๅๆฐ
key | Requried | type | description
------------ | -------- | ------ | -----------
new_password | y | string | ๆฐๅฏ็
old_password | y | string | ๆงๅฏ็
[ๅๅฐ้กถ้จ](#readme)
[API desc](#api-description)
[dataๆฐๆฎ่ฏดๆ](#dataๆฐๆฎ่ฏดๆ)
[blockๆฐๆฎ่ฏดๆ](#1-blockๆฐๆฎ่ฏดๆ)
[resetpassword](#33-post-v10accountresetpassword)
[forgetpassword](#32-post-accountforgetpassword)
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:lewsan
import logging
import multiprocessing
import functools
import psycopg2
import psycopg2.extras
from psycopg2._psycopg import IntegrityError
formats = '[%(asctime)s] %(message)s'
formatter = logging.Formatter(formats)
ch = logging.StreamHandler()
ch.setFormatter(formatter)
fh = logging.FileHandler('log.txt')
fh.setFormatter(formatter)
put_fh = logging.FileHandler('write_log.txt')
put_fh.setFormatter(formatter)
logger = logging.getLogger()
query_logger = logging.getLogger('query')
write_logger = logging.getLogger('write')
for _logger in [logger, query_logger, write_logger]:
_logger.addHandler(fh)
_logger.addHandler(ch)
TEST = True
if TEST:
pg_read_shard = {
1: 'dbname=sneaky user=sneaky password=<PASSWORD> host=172.16.10.133',
2: 'dbname=sneaky user=sneaky password=<PASSWORD> host=172.16.10.162',
3: 'dbname=sneaky user=sneaky password=<PASSWORD> host=172.16.10.168',
}
pg_write_shard = {
1: 'dbname=sneaky user=sneaky password=<PASSWORD> host=172.16.10.133',
2: 'dbname=sneaky user=sneaky password=<PASSWORD> host=172.16.10.162',
3: 'dbname=sneaky user=sneaky password=<PASSWORD> host=172.16.10.168',
}
else:
pg_master = 'dbname=sneaky user=sneaky password=<PASSWORD> host=192.168.100.109 port=5436'
pg_shard = {
1: 'dbname=sneaky user=sneaky password=<PASSWORD> host=192.168.100.109 port=5436',
2: 'dbname=sneaky user=sneaky password=<PASSWORD> host=192.168.100.110 port=5436',
}
NORMAL = 0
LIKED = 1
LIKE = 2
FRIEND = 3
STRANGER_BLOCKED = 4
FRD_BLOCKED = 7
STRANGER_BLOCK = 8
FRD_BLOCK = 11
STRANGER_INTER_BLOCK = 12
FRD_INTER_BLOCK = 15
def get_in_tuple(args):
args = list(args)
if len(args) == 1:
args.append(args[0])
return tuple(args)
def split_list(data, page_size=100):
count_all = len(data)
if count_all % page_size > 0:
page_count = count_all / page_size + 1
else:
page_count = count_all / page_size
pieces = [data[each * page_size: (each + 1) * page_size] for each in range(page_count)]
return pieces
class DBManager(object):
READ_CONNS = {}
WRITE_CONNS = {}
def __init__(self):
self.setup_read_conns()
self.setup_write_conns()
def setup_read_conns(self):
for shard_id, params in pg_read_shard.iteritems():
conn = psycopg2.connect(params)
self.READ_CONNS[shard_id] = conn
def setup_write_conns(self):
for shard_id, params in pg_write_shard.iteritems():
conn = psycopg2.connect(params)
self.WRITE_CONNS[shard_id] = conn
def query_all(self, query_sql):
results = []
try:
for conn in self.READ_CONNS.itervalues():
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
page_count = cur.execute(query_sql)
results.extend(cur.fetchall())
except:
self.setup_read_conns()
for conn in self.READ_CONNS.itervalues():
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
page_count = cur.execute(query_sql)
results.extend(cur.fetchall())
finally:
cur.close()
return results
def query_master(self, query_sql):
results = []
try:
conn = self.READ_CONNS[1]
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
page_count = cur.execute(query_sql)
results = cur.fetchall()
except:
self.setup_read_conns()
conn = self.READ_CONNS[1]
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
page_count = cur.execute(query_sql)
results = cur.fetchall()
finally:
cur.close()
return results
def write(self, sql_data):
for shard_id, sql_lst in sql_data.iteritems():
conn = self.WRITE_CONNS[shard_id]
cursor = conn.cursor()
for sql in sql_lst:
try:
cursor.execute(sql)
conn.commit()
except psycopg2.IntegrityError:
conn.rollback()
except psycopg2.InternalError:
conn.commit()
except Exception as e:
write_logger.error(e)
self.setup_write_conns()
conn = self.WRITE_CONNS[shard_id]
cursor = conn.cursor()
cursor.execute(sql)
conn.commit()
finally:
write_logger.info('finish: {}'.format(sql))
def close_all(self):
for conn in self.READ_CONNS.itervalues():
conn.close()
for conn in self.WRITE_CONNS.itervalues():
conn.close()
db_manager = DBManager()
PAGE_SIZE = 500
INSERT_REL_SQL = "insert into pw_relation_new (uid,tuid,relation_type,update_time,create_time) VALUES (%s,%s,%s,'%s','%s')"
INSERT_LIKE_SQL = "insert into pw_like_relation_temp (uid,tuid,relation_type,tuser_name,tuser_note,update_time,create_time) VALUES (%s,%s,%s,%s,%s,'%s','%s')"
def get_block_list(uid_lst, tuid_lst):
query_sql = 'select uid,tuid from pw_block ' \
'where uid in {} and tuid in {}'.format(get_in_tuple(uid_lst), get_in_tuple(tuid_lst))
results = db_manager.query_master(query_sql)
return [(res['uid'], res['tuid']) for res in results]
def get_contact_data(uid_lst, tuid_lst):
query_sql = 'select uid,tuid from pw_contact ' \
'where state!=1 and uid in {} and tuid in {}'.format(get_in_tuple(uid_lst), get_in_tuple(tuid_lst))
results = db_manager.query_all(query_sql)
return [(res['uid'], res['tuid']) for res in results]
def get_shard_data(uid_lst):
query_sql = 'select shard_id,shard_key from pw_user_shard where shard_key in {}'.format(get_in_tuple(uid_lst))
results = db_manager.query_master(query_sql)
return {res['shard_key']: res['shard_id'] for res in results}
def get_user_info(uid_lst):
query_sql = 'select uid,name from pw_user where uid in {}'.format(get_in_tuple(uid_lst))
results = db_manager.query_all(query_sql)
return {res['uid']: res['name'] or '' for res in results}
def get_contact_note_data(uids, tuids):
query_sql = 'select uid,tuid,note from pw_contact_note where uid in {} and tuid in {}'.format(
get_in_tuple(uids), get_in_tuple(tuids))
results = db_manager.query_all(query_sql)
return {(res['uid'], res['tuid']): res['note'] for res in results if res['uid'] != res['tuid']}
def deal_block_data(block_data, rev_block_list=None, contact_list=None, shard_data=None):
results = {}
for block in block_data:
uid = block['uid']
tuid = block['tuid']
user_shard_id = shard_data.get(uid)
tuser_shard_id = shard_data.get(tuid)
if not user_shard_id or not tuser_shard_id:
continue
user_shard_data = results.setdefault(user_shard_id, [])
tuser_shard_data = results.setdefault(tuser_shard_id, [])
update_time = create_time = block['update_time']
user_relation_type = tuser_relation_type = NORMAL
if (uid, tuid) in contact_list:
if (uid, tuid) in rev_block_list:
user_relation_type = tuser_relation_type = FRD_INTER_BLOCK
else:
user_relation_type = FRD_BLOCK
tuser_relation_type = FRD_BLOCKED
else:
if (uid, tuid) in rev_block_list:
user_relation_type = tuser_relation_type = STRANGER_INTER_BLOCK
else:
user_relation_type = STRANGER_BLOCK
tuser_relation_type = STRANGER_BLOCKED
user_shard_data.append(INSERT_REL_SQL % (uid, tuid, user_relation_type, update_time, create_time))
tuser_shard_data.append(INSERT_REL_SQL % (tuid, uid, tuser_relation_type, update_time, create_time))
return results
def sync_block_data(page_size=PAGE_SIZE):
logger.info('sync_block_data start...')
index = 0
POOL = multiprocessing.Pool(processes=3)
while True:
offset = index * page_size
query_sql = 'select uid,tuid,update_time from pw_block limit {} offset {}'.format(page_size, offset)
query_logger.info('get_block_data limit:{},offset:{},sql:{}'.format(page_size, offset, query_sql))
results = db_manager.query_all(query_sql)
if not results:
break
uid_lst = []
tuid_lst = []
for res in results:
uid_lst.append(res['uid'])
tuid_lst.append(res['tuid'])
reverse_block_uids = get_block_list(tuid_lst, uid_lst)
contact_lst = get_contact_data(uid_lst, tuid_lst)
shard_data = get_shard_data(set(uid_lst + tuid_lst))
query_logger.info('get_block_data end, limit :{}, offset:{}, sql{}'.format(page_size, offset, query_sql))
pieces = split_list(results)
func = functools.partial(deal_block_data, rev_block_list=reverse_block_uids, contact_list=contact_lst,
shard_data=shard_data)
results = POOL.map(func, pieces)
write_logger.info('sync_block_data insert start...')
for res in results:
db_manager.write(res)
write_logger.info('sync_block_data inserting,num :{} finished'.format(len(res)))
write_logger.info('sync_block_data insert end')
index += 1
POOL.close()
POOL.join()
def deal_contact_data(contact_data, user_data, note_data, shard_data):
results = {}
for contact in contact_data:
try:
uid = contact['uid']
tuid = contact['tuid']
user_shard_id = shard_data.get(uid)
tuser_shard_id = shard_data.get(tuid)
if not user_shard_id or not tuser_shard_id:
continue
user_shard_data = results.setdefault(user_shard_id, [])
tuser_shard_data = results.setdefault(tuser_shard_id, [])
update_time = create_time = contact['create_time']
user_relation_type = tuser_relation_type = FRIEND
user_name = user_data.get(uid, '')
tuser_name = user_data.get(tuid, '')
user_note = note_data.get((tuid, uid), '')
tuser_note = note_data.get((uid, tuid), '')
user_shard_data.append(INSERT_REL_SQL % (uid, tuid, user_relation_type, update_time, create_time))
user_shard_data.append(
INSERT_LIKE_SQL % (uid, tuid, user_relation_type, tuser_name, tuser_note, update_time, create_time))
tuser_shard_data.append(INSERT_REL_SQL % (tuid, uid, tuser_relation_type, update_time, create_time))
tuser_shard_data.append(
INSERT_LIKE_SQL % (tuid, uid, tuser_relation_type, user_name, user_note, update_time, create_time))
except:
import traceback
traceback.print_exc()
raise
return results
def sync_contact_data(page_size=PAGE_SIZE):
index = 0
POOL = multiprocessing.Pool(processes=3)
while True:
offset = index * page_size
query_sql = 'select uid,tuid,create_time from pw_contact where state=0 order by uid,tuid limit {} offset {}'.format(
page_size, offset)
results = db_manager.query_all(query_sql)
if not results:
break
uid_lst = []
tuid_lst = []
for res in results:
uid_lst.append(res['uid'])
tuid_lst.append(res['tuid'])
all_uids = set(uid_lst + tuid_lst)
shard_data = get_shard_data(all_uids)
pieces = split_list(results)
user_data = get_user_info(all_uids)
note_data = get_contact_note_data(all_uids, all_uids)
func = functools.partial(deal_contact_data, user_data=user_data, note_data=note_data, shard_data=shard_data)
res = POOL.map(func, pieces)
print res
index += 1
POOL.close()
POOL.join()
def deal_like_req_data(like_req_data, user_data, shard_data):
results = {}
for like_req in like_req_data:
uid = like_req['uid']
tuid = like_req['tuid']
user_shard_id = shard_data.get(uid)
tuser_shard_id = shard_data.get(tuid)
if not user_shard_id or not tuser_shard_id:
continue
user_shard_data = results.setdefault(user_shard_id, [])
tuser_shard_data = results.setdefault(tuser_shard_id, [])
update_time = create_time = like_req['update_time']
user_relation_type = LIKE
tuser_relation_type = LIKED
user_name = user_data.get(uid, '')
tuser_name = user_data.get(tuid, '')
user_shard_data.append(INSERT_REL_SQL % (uid, tuid, user_relation_type, update_time, create_time))
user_shard_data.append(
INSERT_LIKE_SQL % (uid, tuid, user_relation_type, tuser_name, '', update_time, create_time))
tuser_shard_data.append(INSERT_REL_SQL % (tuid, uid, tuser_relation_type, update_time, create_time))
tuser_shard_data.append(
INSERT_LIKE_SQL % (tuid, uid, tuser_relation_type, user_name, '', update_time, create_time))
return results
def sync_like_req(page_size=PAGE_SIZE):
index = 0
POOL = multiprocessing.Pool(processes=3)
while True:
offset = index * page_size
query_sql = 'select uid,tuid,update_time from pw_contact_request where state=0 order by uid,tuid limit {} offset {}'.format(
page_size, offset)
results = db_manager.query_all(query_sql)
if not results:
break
uid_lst = []
tuid_lst = []
for res in results:
uid_lst.append(res['uid'])
tuid_lst.append(res['tuid'])
all_uids = set(uid_lst + tuid_lst)
shard_data = get_shard_data(all_uids)
pieces = split_list(results)
user_data = get_user_info(all_uids)
func = functools.partial(deal_contact_data, user_data=user_data, shard_data=shard_data)
res = POOL.map(func, pieces)
print res
index += 1
POOL.close()
POOL.join()
if __name__ == '__main__':
sync_block_data()
# sync_contact_data()
# sync_like_req()
db_manager.close_all()
| 5762a354b32ae67a72d849f740ee46396ee8cbcd | [
"Markdown",
"Python"
] | 2 | Markdown | Andy0526/test_sync | 1c840de24b5a83b024b6a932c6829d51760be3dd | 7ff4c5c2b763ccc40c85f9041253a6bf6ed4e5fc |
refs/heads/master | <repo_name>NovoaJoseR/hola-mundo<file_sep>/hola_mundo.c
/* Esto sรญ es un fichero en C */
/* prueba de GitHub */
#include <stdio.h>
int main (void)
{
printf("Hola Mundo\n");
return(0);
}
/* Se acabรณ*/
<file_sep>/README.md
# hola_mundo
primer programa en mi GitHub , bueno realmente esto es un fichero de comentarios, el programa estรก en el otro fichero "hola_mundo.c"
El fichero hola_mundo es el que escribe "hola mundo" en el terminal.
Una vez escrito este programa en un ordenador o en la web de GitHub, nos vamos a una mรกquina con Linux, y ahรญ abrimos un terminal, una vez ahรญ se ejecuta git clone con el path a este repositorio, en este caso es:
$ git clone https://github.com/NovoaJoseR/hola-mundo.git
Luego aparecerรก el directorio debajo de donde estรกbamos, nos vamos ahรญ con el comando:
$ cd hola-mundo/
Vemos lo que tiene con ls y observamos que estรกn este fichero de comantarios README.md mรกs el del programa hola_mundo.c
Luego compilamos con gcc (que tenemos ya instalado desde hace tiempo en nuestro Linux), se compila asรญ:
$ gcc -o hola hola_mundo.c
Con eso el fichero de salida se llamarรก hola, y es el ejecutable, que para que saque el mensaje por el terminal tenemos que ejecutarlo asรญ:
$ ./hola
Y sale en la siguiente lรญnea el mensaje.
Y eso es todo.
Tambiรฉn lo pruebo en MAC y funciona igual, ademรกs como me he instalado el GitHub desktop para MAC, lo puedo llevar directamente, pero de momento prefiero hacerlo con la lรญnea de comandos a partir de una ventana de terminal ya que me parece un tanto extraรฑo el desktop.
| 0778163179576338596ebfad5c7fa692e8184d90 | [
"Markdown",
"C"
] | 2 | C | NovoaJoseR/hola-mundo | 7314d88fd6c07a0ba0eb485a3de7e5e3ccc3a896 | 9eaa73c6e65433c9d829a8c1353a93a77cebb868 |
refs/heads/master | <file_sep>#include <stdio.h>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include "opencv2/imgcodecs.hpp"
#include <opencv2/highgui.hpp>
#include <opencv2/ml.hpp>
using namespace cv;
using namespace std;
int main()
{
//์ด๋ฏธ์ง ํ๋ฐฑ์ผ๋ก ๋ง๋ฆ
Mat image0 = imread("41006.jpg");
Mat image;
cvtColor(image0, image, CV_BGR2GRAY);
const int width = image.cols;
const int height = image.rows;
// vec์ ์ ์ฅ๋ feature Point๋ฅผ txt ํ์ผ์ ์ ์ฅ
errno_t err;
FILE *fp;
err = fopen_s(&fp,"svm_predictions.txt", "r");
char s[100];
// ์ธ๊ณฝ์ ๋ถ๋ถ์ ๋ํด ์ฒ๋ฆฌ
int cnt = 0;
while (!feof(fp))
{
fgets(s, 80, fp);
if (s[0] != '-') {
int first = s[0] - 48;
if (first >= 1)
{
//printf("%d\n ", first);
int x = cnt % (width - 16) + 8;
int y = cnt / (width - 16) + 8;
circle(image0, Point(x, y), 1, Scalar(0, 255, 0), 1);
}
}
cnt++;
}
imshow("image", image0);
waitKey(0);
imwrite("result.jpg", image0);
//ํ์ผ ๋ซ๊ธฐ
fclose(fp);
return 0;
}
<file_sep>#include <stdio.h>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include "opencv2/imgcodecs.hpp"
#include <opencv2/highgui.hpp>
#include <opencv2/ml.hpp>
#include <vector>
#include <math.h>
#include <stdlib.h>
#include <random>
using namespace cv;
using namespace std;
#define Octave 2
#define Gaussian 6
// feature_P๋ฅผ ์ ์ฅํ ๊ตฌ์กฐ์ฒด, Point์ radius๋ก ๊ตฌ์ฑ๋จ
struct feature_P
{
int x;
int y;
int radius;
};
void* LBP(Mat& image, int x, int y, int *result)
{
int cnt = 0;
int standard = image.at<uchar>(y, x);
for (int m = y - 7; m <= y + 7; m++)
for (int n = x - 7; n <= x + 7; n++)
{
// ์ค๊ฐ์ ์ ์บ์ฌ
if (n == x && m == y)
continue;
if (standard > image.at<uchar>(m, n))
result[cnt++] = 0;
else
result[cnt++] = 1;
}
return result;
}
int main()
{
//์ด๋ฏธ์ง ํ๋ฐฑ์ผ๋ก ๋ง๋ฆ
Mat image0 = imread("41006.jpg");
Mat image;
cvtColor(image0, image, CV_BGR2GRAY);
const int width = image.cols;
const int height = image.rows;
vector<feature_P> vec;
// vec์ ์ ์ฅ๋ feature Point๋ฅผ txt ํ์ผ์ ์ ์ฅ
errno_t err;
FILE *fp;
err = fopen_s(&fp,"test_LBP.txt", "w");
for (int i = 8; i < height - 8; i++)
{
for (int j = 8; j < width - 8; j++)
{
int result[224];
LBP(image, j, i, result);
fprintf(fp, "0 ");
for (int n = 0; n < 224; n++)
fprintf(fp, "%d:%d ", n + 1, result[n]);
fprintf(fp, "\n");
}
}
//ํ์ผ ๋ซ๊ธฐ
fclose(fp);
return 0;
}
<file_sep>#include <stdio.h>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include "opencv2/imgcodecs.hpp"
#include <opencv2/highgui.hpp>
#include <opencv2/ml.hpp>
#include <vector>
#include <math.h>
#include <stdlib.h>
#include <random>
#include <io.h>
#include <string>
using namespace cv;
using namespace std;
#define Octave 2
#define Gaussian 6
struct OctaveGroup//ํ ์ฅํ๋ธ ๊ทธ๋ฃน๋น ๊ฐ์ง๊ณ ์๋ ์ ๋ณด ๊ฐ์ฐ์์ ํํฐ, DoG ์ฑ๋, ํคํฌ์ธํธ
{
Mat gaussianFliter[Gaussian];//ํ ์ฅํ๋ธ ๋น ๊ฐ์ง๊ณ ์๋ Gaussian Filter
Mat DoGChannel[Gaussian - 1];//ํ ์ฅํ๋ธ ๋น ๊ฐ์ง๊ณ ์๋ DoG Channel์ Gaussian-1๊ฐ.
};
// feature_P๋ฅผ ์ ์ฅํ ๊ตฌ์กฐ์ฒด, Point์ radius๋ก ๊ตฌ์ฑ๋จ
struct feature_P
{
int x;
int y;
int radius;
};
int CheckSigSize(double sig)//Sig๋ฅผ ์ด์ฉํ์ฌ ๊ฐ์ ๊ณ์ฐํด์ผ Size๋ฅผ ๊ณ์ฐํด์ผ ๋๋๋ฐ ๋น๋ฒํ๊ฒ ์ฐ์ฌ์ ๋ฐ๋ก ํจ์๋ฅผ ๋ฌถ์.
{
int size;//์ถ๋ ฅํ ๋ง์คํฌ ์ฌ์ด์ฆ
size = ceil(6 * sig);//6*sig์ ์ฌ๋ฆผ์๋ฅผ ๋ง์คํฌ ์ฌ์ด์ฆ๋ก ์์ ์ค์
if (size % 2 == 0)//๋ง์ฝ ์ง์์ผ ๊ฒฝ์ฐ
size++;//1์ ๋ํจ
return size;//๋ง์คํฌ ์ฌ์ด์ฆ return;
}
void SIFT(Mat& gray,vector<feature_P>& vec)
{
OctaveGroup octave[Octave];
double beforeSig; //์ด์ Sig์์ ๋น๊ต๋ฅผ ์ด์ฉํ์ฌ sqrt(sig_n+1^2 - sig_n^2)๋ฅผ ๊ตฌํ๊ธฐ ์ํ ์ฉ๋.
for (int i = 0; i < Octave; ++i)
{
for (int j = 0; j < Gaussian; ++j)
{
double sig;
int size;
if (j == 0)//์ฒซ ๊ฐ์ฐ์์ ํํฐ์ผ ๊ฒฝ์ฐ.
{
if (i != 0)//0์ฅํ๋ธ๊ฐ ์๋ ๊ฒฝ์ฐ
{
pyrDown(octave[i - 1].gaussianFliter[3], octave[i].gaussianFliter[j],
Size(octave[i - 1].gaussianFliter[3].cols / 2, octave[i - 1].gaussianFliter[3].rows / 2));//์ด์ ์ฅํ๋ธ์ 4๋ฒ์งธ ์ด๋ฏธ์ง๋ฅผ ์ถ์ํ์ฌ ๊ฐ์ ธ์จ๋ค.
beforeSig = 1.6;//Sig๋ 1.6์ด์๋ ๊ฒ์ผ๋ก ๊ฐ์ .
}
else//0 ์ฅํ๋ธ์ผ ๊ฒฝ์ฐ, ์๋ณธ ์ด๋ฏธ์ง์ sig 1.6 ๊ฐ์ ์ด์ฉํ์ฌ ํํฐ๋ง.
{
sig = 1.6;//์ฒซ๋ฒ์งธ ์ด๋ฏธ์ง๋ Sig๊ฐ 1.6.
size = CheckSigSize(sig);//Sig ๊ฐ์ ๋ฐ๋ฅธ ๋ง์คํฌ ์ฌ์ด์ฆ ํ์ธ
GaussianBlur(gray, octave[i].gaussianFliter[j], Size(size, size), sig, sig);//๊ฐ์ฐ์์ ๋ธ๋ฌ.
beforeSig = sig;//Sig ๊ธฐ๋ก
}
}
else
{
sig = beforeSig * pow(2.0, 1.0 / 3.0);//Sig_n+1 = Sig_n * k. k = 2^(1/3)์ ๋ํ ์ฝ๋
double currentSig = sqrt(pow(sig, 2) - pow(beforeSig, 2));//sqrt(Sig_n+1^2 - Sig_n^2)์ ๋ํ ์ฝ๋.
size = CheckSigSize(currentSig);//Sig ๊ฐ์ ๋ฐ๋ฅธ ๋ง์คํฌ ์ฌ์ด์ฆ ํ์ธ
GaussianBlur(octave[i].gaussianFliter[j - 1], octave[i].gaussianFliter[j], Size(size, size), currentSig, currentSig);//์ด์ ๊ฐ์ฐ์์ ํํฐ๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ํ ๊ฐ์ฐ์์ ๋ธ๋ฌ.
beforeSig = sig;//Sig ๊ธฐ๋ก
}
}
}
for (int i = 0; i < Octave; ++i)//๋ชจ๋ ์ฅํ๋ธ์์ ์ฒ๋ฆฌ.
{
for (int j = 0; j < Gaussian - 1; ++j)//DoG ์ฑ๋์ ๊ฐ์๋ Gaussian - 1
{
//octave[i].DoGChannel[j] = octave[i].gaussianFliter[j + 1] - octave[i].gaussianFliter[j];
absdiff(octave[i].gaussianFliter[j + 1], octave[i].gaussianFliter[j], octave[i].DoGChannel[j]);
}
}
for (int o = 0; o < Octave; ++o)//๋ชจ๋ ์ฅํ๋ธ์์ ์คํ.
{
for (int d = 1; d < Gaussian - 2; ++d)//DoG๋ฅผ ๋น๊ตํ ๋, 0๋ฒ์งธ์ ๋งจ ๋ง์ง๋ง์ ์ฌ์ฉํ์ง ์๋๋ค. DoG๊ฐ์๋ Gaussian-1์ด๋ฏ๋ก Gaussian-2๋ก ์ค์
{
for (int i = 1; i < octave[o].DoGChannel[d].rows - 1; ++i)//์ฒซ ์ด๊ณผ ๋ ์ด, ์ฒซ ํ๊ณผ ๋ ํ์ ๊ธฐ์ค์ผ๋ก ์ผ์ง ์๋๋ค. ์ฅํ๋ธ๋ง๋ค rows, cols๊ฐ์ด ๋ค๋ฅด๋ค.
{
for (int j = 1; j < octave[o].DoGChannel[d].cols - 1; ++j)
{
int neighbor[26];//26๊ฐ์ ์ด์๊ฐ์ ์ฝ์
ํ ๋ฐฐ์ด
int n = 0;//๋ฐฐ์ด ๋ฒํธ.
int value = octave[o].DoGChannel[d].at<uchar>(i, j);//ํ์ฌ ๊ธฐ์ค์ ๊ฐ.
for (int t = -1; t <= 1; ++t)//26๊ฐ๋ ๊ฐ๊ฐ ์ฑ๋๋ณ๋ก 3x3 ๊ณต๊ฐ์ ๊ฐ์ ๋ฐ์์จ๋ค. ์์ ์ ๊ธฐ์ค์ผ๋ก -1๋ถํฐ +1๊น์ง์ ๊ฐ์ ๋ฐ์์ค๋ฏ๋ก ๋ค์๊ณผ ๊ฐ์ for๋ฌธ์ผ๋ก ๋์
.
{
for (int tt = -1; tt <= 1; ++tt)
{
neighbor[n++] = octave[o].DoGChannel[d - 1].at<uchar>(i + t, j + tt);//๊ธฐ์ค ์์น๋ณด๋ค ์์ DoG์ฑ๋์ ๊ฐ ๋ฐ์์ค๊ธฐ.
neighbor[n++] = octave[o].DoGChannel[d + 1].at<uchar>(i + t, j + tt);//๊ธฐ์ค ์์น๋ณด๋ค ํ์ DoG์ฑ๋์ ๊ฐ ๋ฐ์์ค๊ธฐ.
if (t != 0 || tt != 0)//๊ธฐ์ค๊ณผ ๊ฐ์ ์์น์ ๊ฐ์ ๋ฐฐ์ด์ ๋ฃ์ง ์๋๋ค.
{
neighbor[n++] = octave[o].DoGChannel[d].at<uchar>(i + t, j + tt);//๊ธฐ์ค DoG์ฑ๋์ ๊ฐ ๋ฐ์์ค๊ธฐ
}
}
}
int max = neighbor[0];//max, min์ ์ด๊ธฐ๊ฐ์ผ๋ก ์ฒซ neighbor๊ฐ ์ฝ์
.
int min = neighbor[0];
for (int x = 1; x < 26; ++x)//min, max ๋น๊ต
{
if (max < neighbor[x])
{
max = neighbor[x];
}
else if (min > neighbor[x])
{
min = neighbor[x];
}
}
if (value > max || value < min)//๊ทน์ ์ผ ๊ฒฝ์ฐ
{
feature_P tmp;
tmp.x = j * pow(2, o);
tmp.y = i * pow(2, o);
tmp.radius = 1.6*pow(2, (o + d) / 3.0);
vec.push_back(tmp);
//circle(image, Point(j*pow(2, o), i*pow(2, o)), 1.6*pow(2, (o + d) / 3.0), Scalar(0, 255, 0), 1);//์ ๊ทธ๋ฆฌ๊ธฐ. ๋ฐ์ง๋ฆ์ scale ๊ฐ์ด๋ฉฐ 1.6*2^((Octave num + DoGlayer Num)/3.0)
}
}
}
}
}
}
// 15*15 block
void* LBP(Mat& image, int x, int y, int *result)
{
int cnt = 0;
int standard = image.at<uchar>(y, x);
for(int m = y - 7; m <= y + 7; m++)
for (int n = x - 7; n <= x + 7; n++)
{
// ์ค๊ฐ์ ์ ์บ์ฌ
if (n == x && m == y)
continue;
if (standard > image.at<uchar>(m, n))
result[cnt++] = 0;
else
result[cnt++] = 1;
}
return result;
}
int main()
{
//์ ์ฅํ txt ํ์ผ
errno_t err;
FILE *fp;
err = fopen_s(&fp, "train_Data.txt", "w");
// ๋๋ ํ ๋ฆฌ ๋ด ํ์ผ ์ฝ์ด์ค๋ path
string path = "C:\\Users\\user\\Desktop\\train\\*.jpg";
struct _finddata_t fd;
intptr_t handle;
if ((handle = _findfirst(path.c_str(), &fd)) == -1L)
cout << "No file in directory!" << endl;
do
{
path = "C:\\Users\\user\\Desktop\\train";
string fullFileName = path + "\\" + fd.name;
cout << fullFileName << endl;
//์ด๋ฏธ์ง ํ๋ฐฑ์ผ๋ก ๋ง๋ฆ
Mat image0 = imread(fullFileName.c_str());
if (image0.empty()) //์ ๋๋ก ์์ฝํ๋ฉด ์์ธ์ฒ๋ฆฌ
continue;
Mat image;
cvtColor(image0, image, CV_BGR2GRAY);
const int width = image.cols;
const int height = image.rows;
// feature point๋ฅผ ์ ์ฅํ vec ์ ์ธ
vector<feature_P> vec;
// SIFT ํจ์๋ฅผ ์ด์ฉํด feature Point๋ฅผ ์ถ์ถํด์ค๋ค.
SIFT(image, vec);
int count = 0;
// ํด๋์ค๊ฐ 1์ธ feature vector๋ฅผ ์ ์ฅ
for (int i = 0; i < vec.size(); i++) {
if (vec.at(i).x > 8 && vec.at(i).x < width - 8 && vec.at(i).y > 8 && vec.at(i).y < height - 8)
{
fprintf(fp, "+1 ");
int result[224];
LBP(image, vec.at(i).x, vec.at(i).y, result);
for (int n = 0; n < 224; n++)
fprintf(fp, "%d:%d ", n + 1, result[n]);
fprintf(fp, "\n");
count++;
}
}
// ๋๋ฏธ ๋ฐ์ดํฐ ์์ฑ
int i = 0;
while(i <= count)
{
fprintf(fp, "-1 ");
// ๋๋ค x,y์ขํ๋ฅผ ์์ฑ
int x = rand() % (width - 16) + 8;
int y = rand() % (height - 16) + 8;
for (int it = 0; it < vec.size(); it++)
if (vec.at(it).x == x && vec.at(it).y == y)
continue;
int fake[224];
LBP(image, x, y, fake);
for (int n = 0; n < 224; n++)
fprintf(fp, "%d:%d ", n + 1, fake[n]);
fprintf(fp, "\n");
i++;
}
} while (_findnext(handle, &fd) == 0);
_findclose(handle);
//ํ์ผ ๋ซ๊ธฐ
fclose(fp);
return 0;
}
<file_sep>
### SVM
- LBP๋ก ์ด๋ฏธ์ง์ feature๋ฅผ ๋ฝ๊ณ ์ด๋ฅผ SVM์ ํตํด ํน์ง์ ์ธ์ง ์๋์ง ํ์ต์์ผ ํน์ง์ ์ ๊ฒ์ถํด๋ด๋ ํ๋ก์ ํธ์
๋๋ค.
- ๊ธฐ์กด SIFT์ ๋นํด์ 70%์ ๋์ ์ฑ๋ฅ๋ฐ์ ๋์ค์ง ์์ง๋ง SVM์ ์ ์ฒด์ ์ธ work flow์ ๋ํด ์ ์ ์๋ ํ๋ก์ ํธ์
๋๋ค.
# SVM
###### - Work Flow
###### 1. DB ์ถ์ถ
SVM์ ํ์ต์ํค๊ธฐ ์ํ DB๋ฅผ ๋ง๋ค๊ธฐ ์ํด BSD500 ์ด๋ฏธ์ง๋ฅผ ์ฌ์ฉํ์๋ค. C++ ์ฝ๋๋ก ํด๋ ๋ด ๋ชจ๋ ์ด๋ฏธ์ง ํ์ผ์ ์ฝ์ด์ค๊ณ , ์ฝ์ด์จ ์ด๋ฏธ์ง์์ SIFT๋ฅผ ์ด์ฉํด Feature Point๋ฅผ ์ถ์ถํด Vector์ ์ขํ๋ฅผ ์ ์ฅํ๋ค. ์ ์ฅ๋ ์ขํ์ LBP ๋ฒกํฐ๋ฅผ ๊ณ์ฐํ๋ค. LBP ๋ฒกํฐ ์ถ์ถ์๋ 15 x 15 ๋ธ๋ก์ ์ฌ์ฉํ์์ผ๋ฉฐ, ์ค๊ฐ ๊ฐ๊ณผ ๋น๊ตํด ์์ผ๋ฉด 0, ํฌ๋ฉด 1์ ๋ถ์ฌํ๋ 224์ฐจ์์ ๋ฒกํฐ๋ฅผ ๋ง๋ค์ด๋ธ๋ค. SIFT Featrue Point์ ๋ฒกํฐ๋ ํด๋์ค 1(ํน์ง์ )์ผ๋ก ๋ถ๋ฅ์์ผ train_Data.txt๋ผ๋ ํ์ผ์ ์ ์ฅ๋๋ค. ์ ์ฅ ๋ฐฉ์์โ1 1:LBP[0] 2:LBP[1] 3:LBP[2] .... 224:LBP[223]โ์ด๋ค. ์ฌ๊ธฐ์ SVM ์ด์ง ๋ถ๋ฅ๊ธฐ๋ 1ํด๋์ค์ -1 ํด๋์ค ๋ ๊ฐ๋ก ๋๋์ด ์ง๋๋ฐ, 1ํด๋์ค๋ Feature Point ํด๋์ค์ด๊ณ , -1์ Feature Point๊ฐ ์๋ ํด๋์ค์ด๋ค. ์ด๋ ํ์ต์ ์ํด์๋ -1 ํด๋์ค ๋ํ ๋ง๋ค์ด์ผ ํ๋๋ฐ, Feature Point๊ฐ ์๋ ์ขํ๋ฅผ ์์๋ก ์์ฑํ๋ฉฐ, ๊ทธ ๊ฐ์๋ Feature Point์ ๊ฐ์์ ๊ฐ์์ผ ํ๋ค.(๊ฐ์ง ์์ผ๋ฉด ๋ถ๋ฅ๊ฐ ์ ๋๋ก ๋์ง ์์์ ํ์ธํ์)
###### 2. SVM Train(svm_learn.exe)
SVM์ SVMlight๋ฅผ ์ฌ์ฉํ์์ผ๋ฉฐ, exe ํ์ผ๋ก ๋์ด์์ด, Data_set๋ง ์ ๋ง๋ค์ด ์ฃผ๋ฉด ์์์ ํ์ต์ ์์ผ์ค๋ค.
SVMlight๊ฐ ์ ์ฅ๋ ํด๋์ ๋ค์ด๊ฐ cmd ์์์ svmlight.exe train_Data.txt๋ช
๋ น์ด๋ฅผ ์ณ์ฃผ๋ฉด, ์๋์ผ๋ก ํ์ต์ด ์์๋๋ค. ์ดํ SVM_model์ด๋ผ๋ ํ์ผ์ด ํ์ต๋์ด ๋์จ๋ค.

###### 3. Test(test_extractor.cpp, svm_classify.exe, test_rendering.cpp)
Test๋ BSD test ๋ฐ์ดํฐ์
์ค ํ ์ฅ์ ๊ณจ๋์ผ๋ฉฐ, test ์ด๋ฏธ์ง์์ ๋ชจ๋ ํฝ์
์ LBP ๋ฒกํฐ๋ฅผ ๊ตฌํ๋ค. ๊ตฌํด์ง LBP ๋ฒกํฐ๋ test.txt ํ์ผ๋ก ์ ์ฅ๋๋ค.
์ ์ฅ๋ LBP ๋ฒกํฐ๋ ํ์ต๋ SVM์ ํต๊ณผํด ํด๋น ๊ฐ์ด Feature Point์ธ์ง ์๋์ง ํ๋ณํ๋ ์ ํ๋ ๊ฐ์ ์ถ์ถํด ๋ธ๋ค.
์ถ์ถ๋ ์ ํ๋ ๊ฐ์ ์ฝ์ด ๋ค์ฌ, test ์ด๋ฏธ์ง ์์์ ๋ ๋๋ง ํด์ค๋ค. ์ฌ๊ธฐ์ ์ ํ๋ ๊ฐ์ด 1์ผ์ ํด๋์ค 1, Feature Point๋ผ๋ ์๋ฆฌ์์ผ๋ก test ์ด๋ฏธ์ง์ ๋ ๋๋ง ํด์ค๋ค.
- work flow

- origin

- SIFT

- LBP_SVM

- origin

- SIFT

- LBP_SVM

| ef9acf935ac7069636dfe5ea7a693200bd7a4338 | [
"Markdown",
"C++"
] | 4 | C++ | chacha95/OpenCV_Project | 295a8d0a1acc558d12137753702a313518e68d4b | 5844ecbb62c849c2c4333bfb552f048b57646ee7 |
refs/heads/master | <repo_name>ofrohn/d3-celestial<file_sep>/src/svg.js
/* global d3, Celestial, projections, poles, getData, getPlanet, getMwbackground, getAngles, getWidth, getGridValues, has, isArray, halfฯ, symbols, starnames, dsonames, bvcolor, settings, formats, transformDeg, euler, Round */
function exportSVG(fname) {
var doc = d3.select("body").append("div").attr("id", "d3-celestial-svg").attr("style", "display: none"),
svg = d3.select("#d3-celestial-svg").append("svg"), //.attr("style", "display: none"),
m = Celestial.metrics(),
cfg = settings.set(),
path = cfg.datapath,
proj = projections[cfg.projection],
rotation = getAngles(cfg.center),
center = [-rotation[0], -rotation[1]],
scale0 = proj.scale * m.width/1024,
projection = Celestial.projection(cfg.projection).rotate(rotation).translate([m.width/2, m.height/2]).scale([m.scale]),
adapt = cfg.adaptable ? Math.sqrt(m.scale/scale0) : 1,
culture = (cfg.culture !== "" && cfg.culture !== "iau") ? cfg.culture : "",
circle, id;
svg.selectAll("*").remove();
var defs = svg.append("defs");
if (proj.clip) {
projection.clipAngle(90);
}
circle = d3.geo.circle().angle([179.95]).origin(center);
svg.attr("width", m.width).attr("height", m.height);
// .attr("viewBox", " 0 0 " + (m.width) + " " + (m.height));
var groupNames = ['background', 'milkyWay', 'milkyWayBg', 'gridLines', 'constBoundaries',
'planesequatorial', 'planesecliptic', 'planesgalactic', 'planessupergalactic',
'constLines', 'mapBorder','stars', 'dsos', 'planets', 'gridvaluesLon', 'gridvaluesLat',
'constNames', 'starDesignations', 'starNames', 'dsoNames', 'planetNames', 'horizon', 'daylight'],
groups = {}, styles = {};
for (var i=0; i<groupNames.length; i++) {
// inkscape:groupmode="layer", inkscape:label="Ebene 1"
groups[groupNames[i]] = svg.append('g').attr({"id": groupNames[i], ":inkscape:groupmode": "layer", ":inkscape:label": groupNames[i]});
styles[groupNames[i]] = {};
}
var graticule = d3.geo.graticule().minorStep([15,10]);
var map = d3.geo.path().projection(projection);
var q = d3.queue(2);
groups.background.append("path").datum(circle).attr("class", "background").attr("d", map);
styles.background.fill = cfg.background.fill;
if (cfg.lines.graticule.show) {
if (cfg.transform === "equatorial") {
groups.gridLines.append("path").datum(graticule)
.attr("class", "gridLines")
.attr("d", map);
styles.gridLines = svgStyle(cfg.lines.graticule);
} else {
Celestial.graticule(groups.gridLines, map, cfg.transform);
styles.gridLines = svgStyle(cfg.lines.graticule);
}
if (has(cfg.lines.graticule, "lon") && cfg.lines.graticule.lon.pos.length > 0) {
var jlon = {type: "FeatureCollection", features: getGridValues("lon", cfg.lines.graticule.lon.pos)};
groups.gridvaluesLon.selectAll(".gridvalues_lon")
.data(jlon.features)
.enter().append("text")
.attr("transform", function(d, i) { return point(d.geometry.coordinates); })
.text( function(d) { return d.properties.value; } )
.attr({dy: ".5em", dx: "-.75em", class: "gridvaluesLon"});
styles.gridvaluesLon = svgTextStyle(cfg.lines.graticule.lon);
}
if (has(cfg.lines.graticule, "lat") && cfg.lines.graticule.lat.pos.length > 0) {
var jlat = {type: "FeatureCollection", features: getGridValues("lat", cfg.lines.graticule.lat.pos)};
groups.gridvaluesLat.selectAll(".gridvalues_lat")
.data(jlat.features)
.enter().append("text")
.attr("transform", function(d, i) { return point(d.geometry.coordinates); })
.text( function(d) { return d.properties.value; } )
.attr({dy: "-.5em", dx: "-.75em", class: "gridvaluesLat"});
styles.gridvaluesLat = svgTextStyle(cfg.lines.graticule.lat);
}
}
//Celestial planes
for (var key in cfg.lines) {
if (has(cfg.lines, key) && key != "graticule" && cfg.lines[key].show !== false) {
id = "planes" + key;
groups[id].append("path")
.datum(d3.geo.circle().angle([90]).origin(poles[key]) )
.attr("class", id)
.attr("d", map);
styles[id] = svgStyle(cfg.lines[key]);
}
}
//Milky way outline
if (cfg.mw.show) {
q.defer(function(callback) {
d3.json(path + "mw.json", function(error, json) {
if (error) callback(error);
var mw = getData(json, cfg.transform);
var mw_back = getMwbackground(mw);
groups.milkyWay.selectAll(".mway")
.data(mw.features)
.enter().append("path")
.attr("class", "milkyWay")
.attr("d", map);
styles.milkyWay = svgStyle(cfg.mw.style);
if (!has(cfg.background, "opacity") || cfg.background.opacity > 0.95) {
groups.milkyWayBg.selectAll(".mwaybg")
.data(mw_back.features)
.enter().append("path")
.attr("class", "milkyWayBg")
.attr("d", map);
styles.milkyWayBg = {"fill": cfg.background.fill,
"fill-opacity": cfg.background.opacity };
}
callback(null);
});
});
}
//Constellation boundaries
if (cfg.constellations.bounds) {
q.defer(function(callback) {
d3.json(path + filename("constellations", "borders"), function(error, json) {
if (error) callback(error);
var conb = getData(json, cfg.transform);
if (Celestial.constellation) {
var re = new RegExp("\\b" + Celestial.constellation + "\\b");
}
groups.constBoundaries.selectAll(".bounds")
.data(conb.features)
.enter().append("path")
.attr("class", function(d) { return (Celestial.constellation && d.ids.search(re) !== -1) ? "constBoundariesSel" : "constBoundaries"; })
.attr("d", map);
styles.constBoundaries = svgStyle(cfg.constellations.boundStyle);
styles.constBoundariesSel = {"fill": "none",
"stroke": cfg.constellations.boundStyle.stroke,
"stroke-width": cfg.constellations.boundStyle.width * 1.5,
"stroke-opacity": 1,
"stroke-dasharray": "none"};
callback(null);
});
});
}
//Constellation lines
if (cfg.constellations.lines) {
q.defer(function(callback) {
d3.json(path + filename("constellations", "lines"), function(error, json) {
if (error) callback(error);
var conl = getData(json, cfg.transform);
groups.constLines.selectAll(".lines")
.data(conl.features)
.enter().append("path")
.attr("class", function(d) { return "constLines" + d.properties.rank; })
.attr("d", map);
var dasharray = has(cfg.constellations.lineStyle, "dash") ? cfg.constellations.lineStyle.dash.join(" ") : "none";
styles.constLines1 = {"fill": "none", "stroke": cfg.constellations.lineStyle.stroke[0],
"stroke-width": cfg.constellations.lineStyle.width[0],
"stroke-opacity": cfg.constellations.lineStyle.opacity[0],
"stroke-dasharray": dasharray};
styles.constLines2 = {"fill": "none", "stroke": cfg.constellations.lineStyle.stroke[1],
"stroke-width": cfg.constellations.lineStyle.width[1],
"stroke-opacity": cfg.constellations.lineStyle.opacity[1],
"stroke-dasharray": dasharray};
styles.constLines3 = {"fill": "none", "stroke": cfg.constellations.lineStyle.stroke[2],
"stroke-width": cfg.constellations.lineStyle.width[2],
"stroke-opacity": cfg.constellations.lineStyle.opacity[2],
"stroke-dasharray": dasharray};
callback(null);
});
});
}
// Map border
q.defer(function(callback) {
var rot = projection.rotate();
projection.rotate([0,0,0]);
groups.mapBorder.append("path")
.datum(graticule.outline)
.attr("class", "mapBorder")
.attr("d", map);
styles.mapBorder = {"fill": "none", "stroke": cfg.background.stroke, "stroke-width": cfg.background.width, "stroke-opacity": 1, "stroke-dasharray": "none" };
projection.rotate(rot);
callback(null);
});
//Constellation names or designation
if (cfg.constellations.names) {
q.defer(function(callback) {
d3.json(path + filename("constellations"), function(error, json) {
if (error) callback(error);
var conn = getData(json, cfg.transform);
groups.constNames.selectAll(".constnames")
.data(conn.features.filter( function(d) {
return clip(d.geometry.coordinates) === 1;
}))
.enter().append("text")
.attr("class", function(d) { return "constNames" + d.properties.rank; })
.attr("transform", function(d, i) { return point(d.geometry.coordinates); })
.text( function(d) { return constName(d); } );
styles.constNames1 = {"fill": cfg.constellations.nameStyle.fill[0],
"fill-opacity": cfg.constellations.nameStyle.opacity[0],
"font": cfg.constellations.nameStyle.font[0],
"text-anchor": svgAlign(cfg.constellations.nameStyle.align)};
styles.constNames2 = {"fill": cfg.constellations.nameStyle.fill[1],
"fill-opacity": cfg.constellations.nameStyle.opacity[1],
"font": cfg.constellations.nameStyle.font[1],
"text-anchor": svgAlign(cfg.constellations.nameStyle.align)};
styles.constNames3 = {"fill": cfg.constellations.nameStyle.fill[2],
"fill-opacity": cfg.constellations.nameStyle.opacity[2],
"font": cfg.constellations.nameStyle.font[2],
"text-anchor": svgAlign(cfg.constellations.nameStyle.align)};
callback(null);
});
});
}
//Stars
if (cfg.stars.show) {
q.defer(function(callback) {
d3.json(path + cfg.stars.data, function(error, json) {
if (error) callback(error);
var cons = getData(json, cfg.transform);
groups.stars.selectAll(".stars")
.data(cons.features.filter( function(d) {
return d.properties.mag <= cfg.stars.limit;
}))
.enter().append("path")
.attr("class", function(d) { return "stars" + starColor(d.properties.bv); })
.attr("d", map.pointRadius( function(d) {
return d.properties ? starSize(d.properties.mag) : 1;
}));
styles.stars = svgStyle(cfg.stars.style);
var range = bvcolor.domain();
for (i=Round(range[1],1); i<=Round(range[0],1); i+=0.1) {
styles["stars" + Math.round(i*10).toString()] = {"fill": bvcolor(i)};
}
if (cfg.stars.designation) {
groups.starDesignations.selectAll(".stardesigs")
.data(cons.features.filter( function(d) {
return d.properties.mag <= cfg.stars.designationLimit*adapt && clip(d.geometry.coordinates) === 1;
}))
.enter().append("text")
.attr("transform", function(d) { return point(d.geometry.coordinates); })
.text( function(d) { return starDesignation(d.id); })
.attr({dy: ".85em", dx: ".35em", class: "starDesignations"});
styles.starDesignations = svgTextStyle(cfg.stars.designationStyle);
}
if (cfg.stars.propername) {
groups.starNames.selectAll(".starnames")
.data(cons.features.filter( function(d) {
return d.properties.mag <= cfg.stars.propernameLimit*adapt && clip(d.geometry.coordinates) === 1;
}))
.enter().append("text")
.attr("transform", function(d) { return point(d.geometry.coordinates); })
.text( function(d) { return starPropername(d.id); })
.attr({dy: "-.5em", dx: "-.35em", class: "starNames"});
styles.starNames = svgTextStyle(cfg.stars.propernameStyle);
}
callback(null);
});
});
}
//Deep space objects
if (cfg.dsos.show) {
q.defer(function(callback) {
d3.json(path + cfg.dsos.data, function(error, json) {
if (error) callback(error);
var cond = getData(json, cfg.transform);
groups.dsos.selectAll(".dsos")
.data(cond.features.filter( function(d) {
return clip(d.geometry.coordinates) === 1 &&
(d.properties.mag === 999 && Math.sqrt(parseInt(d.properties.dim)) > cfg.dsos.limit*adapt ||
d.properties.mag !== 999 && d.properties.mag <= cfg.dsos.limit);
}))
.enter().append("path")
.attr("class", function(d) { return "dsos" + d.properties.type; })
.attr("transform", function(d) { return point(d.geometry.coordinates); })
.attr("d", function(d) { return dsoSymbol(d.properties); });
styles.dsos = svgStyle(cfg.dsos.style);
for (key in cfg.dsos.symbols) {
if (!has(cfg.dsos.symbols, key)) continue;
id = "dsos" + key;
styles[id] = { "fill-opacity": cfg.dsos.style.opacity, "stroke-opacity": cfg.dsos.style.opacity };
if (has(cfg.dsos.symbols[key], "stroke")) {
styles[id].fill = "none";
styles[id].stroke = cfg.dsos.colors ? cfg.dsos.symbols[key].stroke : cfg.dsos.style.stroke;
styles[id]["stroke-width"] = cfg.dsos.colors ? cfg.dsos.symbols[key].width : cfg.dsos.style.width;
} else {
styles[id].stroke = "none";
styles[id].fill = cfg.dsos.colors ? cfg.dsos.symbols[key].fill : cfg.dsos.style.fill;
}
}
if (cfg.dsos.names) {
groups.dsoNames.selectAll(".dsonames")
.data(cond.features.filter( function(d) {
return clip(d.geometry.coordinates) === 1 &&
(d.properties.mag == 999 && Math.sqrt(parseInt(d.properties.dim)) > cfg.dsos.nameLimit ||
d.properties.mag != 999 && d.properties.mag <= cfg.dsos.nameLimit);
}))
.enter().append("text")
.attr("class", function(d) { return "dsoNames " + d.properties.type; })
.attr("transform", function(d) { return point(d.geometry.coordinates); })
.text( function(d) { return dsoName(d); })
.attr({dy: "-.5em", dx: ".35em"});
styles.dsoNames = {"fill-opacity": cfg.dsos.style.opacity,
"font": cfg.dsos.nameStyle.font,
"text-anchor": svgAlign(cfg.dsos.nameStyle.align)};
for (key in cfg.dsos.symbols) {
if (!has(cfg.dsos.symbols, key)) continue;
styles[key] = {"fill": cfg.dsos.colors ? cfg.dsos.symbols[key].fill : cfg.dsos.style.fill };
}
}
callback(null);
});
});
}
//Planets
if ((cfg.location || cfg.formFields.location) && cfg.planets.show && Celestial.origin) {
q.defer(function(callback) {
var dt = Celestial.date(),
o = Celestial.origin(dt).spherical(),
jp = {type: "FeatureCollection", features: []},
jlun = {type: "FeatureCollection", features: []};
Celestial.container.selectAll(".planet").each(function(d) {
var id = d.id(), r = 12,
p = d(dt).equatorial(o);
p.ephemeris.pos = transformDeg(p.ephemeris.pos, euler[cfg.transform]); //transform;
if (clip(p.ephemeris.pos) === 1) {
if (id === "lun")
jlun.features.push(createEntry(p));
else
jp.features.push(createEntry(p));
}
});
if (cfg.planets.symbolType === "disk") {
groups.planets.selectAll(".planets")
.data(jp.features)
.enter().append("path")
.attr("transform", function(d) { return point(d.geometry.coordinates); })
.attr("d", function(d) {
var r = (has(cfg.planets.symbols[d.id], "size")) ? (cfg.planets.symbols[d.id].size - 1) * adapt : null;
return planetSymbol(d.properties, r);
})
.attr("class", function(d) { return "planets " + d.id; });
} else {
groups.planets.selectAll(".planets")
.data(jp.features)
.enter().append("text")
.attr("transform", function(d) { return point(d.geometry.coordinates); })
.text( function(d) { return d.properties.symbol; })
.attr("class", function(d) { return "planets " + d.id; })
.attr({dy: ".35em"});
}
// Special case for Moon crescent
if (jlun.features.length > 0) {
if (cfg.planets.symbolType === "letter") {
groups.planets.selectAll(".moon")
.data(jlun.features)
.enter().append("text")
.attr("transform", function(d) { return point(d.geometry.coordinates); })
.text( function(d) { return d.properties.symbol; })
.attr("class", function(d) { return "planets " + d.id; })
.attr({dy: ".35em"});
} else {
var rl = has(cfg.planets.symbols.lun, "size") ? (cfg.planets.symbols.lun.size - 1) * adapt : 11 * adapt;
groups.planets.selectAll(".dmoon")
.data(jlun.features)
.enter().append("path")
.attr("class", "darkluna" )
.attr("transform", function(d) { return point(d.geometry.coordinates); })
.attr("d", function(d) { return d3.svg.symbol().type("circle").size(rl*rl)(); });
groups.planets.selectAll(".moon")
.data(jlun.features)
.enter().append("path")
.attr("class", function(d) { return "planets " + d.id; })
.attr("transform", function(d) { return point(d.geometry.coordinates); })
.attr("d", function(d) { return moonSymbol(d.properties, rl); });
}
}
styles.planets = svgTextStyle(cfg.planets.symbolStyle);
styles.planets.font = planetFont(cfg.planets.symbolStyle.font);
styles.darkluna = {"fill": "#557"};
for (key in cfg.planets.symbols) {
if (!has(cfg.planets.symbols, key)) continue;
styles[key] = {"fill": cfg.planets.symbols[key].fill};
}
//Planet names
if (cfg.planets.names) {
groups.planetNames.selectAll(".planetnames")
.data(jp.features)
.enter().append("text")
.attr("transform", function(d) { return point(d.geometry.coordinates); })
.text( function(d) { return d.properties.name; })
.attr({dy: ".85em", dx: "-.35em"})
.attr("class", function(d) { return "planetNames " + d.id; });
if (jlun.features.length > 0) {
groups.planetNames.selectAll(".moonname")
.data(jlun.features)
.enter().append("text")
.attr("transform", function(d) { return point(d.geometry.coordinates); })
.text( function(d) { return d.properties.name; })
.attr({dy: ".85em", dx: "-.35em"})
.attr("class", function(d) { return "planetNames " + d.id; });
}
}
styles.planetNames = svgTextStyle(cfg.planets.nameStyle);
callback(null);
});
}
if ((cfg.location || cfg.formFields.location) && cfg.daylight.show && proj.clip) {
q.defer(function(callback) {
var sol = getPlanet("sol");
if (sol) {
var up = Celestial.zenith(),
solpos = sol.ephemeris.pos,
dist = d3.geo.distance(up, solpos),
pt = projection(solpos),
daylight = d3.geo.circle().angle([179.95]).origin(solpos);
groups.daylight.append("path").datum(daylight)
.attr("class", "daylight")
.attr("d", map);
styles.daylight = svgSkyStyle(dist, pt);
if (clip(solpos) === 1 && dist < halfฯ) {
groups.daylight.append("circle")
.attr("cx", pt[0])
.attr("cy", pt[1])
.attr("r", 5)
.style("fill", "#fff");
}
}
callback(null);
});
}
if ((cfg.location || cfg.formFields.location) && cfg.horizon.show && !proj.clip) {
q.defer(function(callback) {
var horizon = d3.geo.circle().angle([90]).origin(Celestial.nadir());
groups.horizon.append("path").datum(horizon)
.attr("class", "horizon")
.attr("d", map);
styles.horizon = svgStyle(cfg.horizon);
callback(null);
});
}
if (Celestial.data.length > 0) {
Celestial.data.forEach( function(d) {
if (has(d, "save")) {
q.defer(function(callback) {
d.save();
callback(null);
});
}
});
}
// Helper functions
function clip(coords) {
return proj.clip && d3.geo.distance(center, coords) > halfฯ ? 0 : 1;
}
function point(coords) {
return "translate(" + projection(coords) + ")";
}
function filename(what, sub, ext) {
var cult = (has(formats[what], culture)) ? "." + culture : "";
ext = ext ? "." + ext : ".json";
sub = sub ? "." + sub : "";
return what + sub + cult + ext;
}
function svgStyle(s) {
var res = {};
res.fill = s.fill || "none";
res["fill-opacity"] = s.opacity !== null ? s.opacity : 1;
res.stroke = s.stroke || "none";
res["stroke-width"] = s.width !== null ? s.width : 0;
res["stroke-opacity"] = s.opacity !== null ? s.opacity : 1;
if (has(s, "dash")) res["stroke-dasharray"] = s.dash.join(" ");
else res["stroke-dasharray"] = "none";
res.font = s.font || null;
return res;
}
function svgTextStyle(s) {
var res = {};
res.stroke = "none";
res.fill = s.fill || "none";
res["fill-opacity"] = s.opacity !== null ? s.opacity : 1;
//res.textBaseline = s.baseline || "bottom";
res["text-anchor"] = svgAlign(s.align);
res.font = s.font || null;
return res;
}
function svgStyleA(rank, s) {
var res = {};
rank = rank || 1;
res.fill = isArray(s.fill) ? s.fill[rank-1] : null;
res["fill-opacity"] = isArray(s.opacity) ? s.opacity[rank-1] : 1;
res.stroke = isArray(s.stroke) ? s.stroke[rank-1] : null;
res["stroke-width"] = isArray(s.width) ? s.width[rank-1] : null;
res["stroke-opacity"] = isArray(s.opacity) ? s.opacity[rank-1] : 1;
res["text-anchor"] = svgAlign(s.align);
res.font = isArray(s.font) ? s.font[rank-1] : null;
//res.textBaseline = s.baseline || "bottom";
return res;
}
function svgSkyStyle(dist, pt) {
var factor, color1, color2, color3,
upper = 1.36,
lower = 1.885;
if (dist > lower) return {fill: "transparent"};
if (dist <= upper) {
color1 = "#daf1fa";
color2 = "#93d7f0";
color3 = "#57c0e8";
factor = -(upper-dist) / 10;
} else {
factor = (dist - upper) / (lower - upper);
color1 = d3.interpolateLab("#daf1fa", "#e8c866")(factor);
color2 = d3.interpolateLab("#93c7d0", "#ff854a")(factor);
color3 = d3.interpolateLab("#57b0c8", "#6caae2")(factor);
}
var gradient = groups.daylight.append("radialGradient")
.attr("cx", pt[0])
.attr("cy", pt[1])
.attr("fr", "0")
.attr("r", "300")
.attr("id", "skygradient")
.attr("gradientUnits", "userSpaceOnUse");
gradient.append("stop").attr("offset", "0").attr("stop-color", color1);
gradient.append("stop").attr("offset", 0.2+0.4*factor).attr("stop-color", color2);
gradient.append("stop").attr("offset", "1").attr("stop-color", color3);
return {"fill": "url(#skygradient)", "fill-opacity": skyTransparency(factor, 1.4)};
}
function skyTransparency(t, a) {
return 0.9 * (1 - ((Math.pow(Math.E, t*a) - 1) / (Math.pow(Math.E, a) - 1)));
}
function svgAlign(s) {
if (!s) return "start";
if (s === "center") return "middle";
if (s === "right") return "end";
return "start";
}
function dsoSymbol(p) {
var size = dsoSize(p.mag, p.dim) || 9,
type = dsoShape(p.type);
if (d3.svg.symbolTypes.indexOf(type) !== -1) {
return d3.svg.symbol().type(type).size(size)();
} else {
return d3.svg.customSymbol().type(type).size(size)();
}
}
function dsoShape(type) {
if (!type || !has(cfg.dsos.symbols, type)) return "circle";
else return cfg.dsos.symbols[type].shape;
}
function dsoSize(mag, dim) {
if (!mag || mag === 999) return Math.pow(parseInt(dim) * cfg.dsos.size * adapt / 7, 0.5);
return Math.pow(2 * cfg.dsos.size * adapt - mag, cfg.dsos.exponent);
}
function dsoName(d) {
//return p[cfg.dsos.namesType];
var lang = cfg.dsos.namesType, id = d.id;
if (lang === "desig" || !has(dsonames, id)) return d.properties.desig;
return has(dsonames[id], lang) ? dsonames[id][lang] : d.properties.desig;
}
function dsoColor(p) {
if (cfg.dsos.colors === true) return svgStyle(cfg.dsos.symbols[p.type]);
return svgStyle(cfg.dsos.style);
}
function starDesignation(id) {
if (!has(starnames, id)) return "";
return starnames[id][cfg.stars.designationType];
}
function starPropername(id) {
var lang = cfg.stars.propernameType;
if (!has(starnames, id)) return "";
return has(starnames[id], lang) ? starnames[id][lang] : starnames[id].name;
}
function starSize(mag) {
if (mag === null) return 0.1;
var d = cfg.stars.size * adapt * Math.exp(cfg.stars.exponent * (mag + 2));
return Math.max(d, 0.1);
}
function starColor(bv) {
if (!cfg.stars.colors || isNaN(bv)) return "";
return Math.round(bv*10).toString();
}
function constName(d) {
return d.properties[cfg.constellations.namesType];
}
function moonSymbol(p, r) {
var size = r ? r*r : 121;
return d3.svg.customSymbol().type("crescent").size(size).ratio(p.age)();
}
function planetSymbol(p, r) {
var size = r ? r*r : planetSize(p.mag);
return d3.svg.symbol().type("circle").size(size)();
}
function planetFont(s) {
var size = s.replace(/(^\D*)(\d+)(\D.+$)/i,'$2');
size = Math.round(adapt * size);
return s.replace(/(^\D*)(\d+)(\D.+$)/i,'$1' + size + '$3');
}
function planetSize(m) {
var mag = m || 2;
var r = 4 * adapt * Math.exp(-0.05 * (mag+2));
return Math.max(r, 2);
}
function createEntry(o) {
var res = {type: "Feature", "id":o.id, properties: {}, geometry:{}};
res.properties.name = o[cfg.planets.namesType];
if (cfg.planets.symbolType === "symbol" || cfg.planets.symbolType === "letter")
res.properties.symbol = cfg.planets.symbols[res.id][cfg.planets.symbolType];
res.properties.mag = o.ephemeris.mag || 10;
if (res.id === "lun") {
res.properties.age = o.ephemeris.age;
res.properties.phase = o.ephemeris.phase;
}
res.geometry.type = "Point";
res.geometry.coordinates = o.ephemeris.pos;
return res;
}
function createStyles() {
var res = "";
for (var key in styles) {
if (!has(styles, key)) continue;
res += " ." + key + stringifyStyle(styles[key]);
}
return "/*\u003c![CDATA[*/\n" + res + "\n/*]]\u003e*/";
}
function stringifyStyle(s) {
var res = " {";
for (var key in s) {
if (!has(s, key)) continue;
res += key + ":" + s[key] + "; ";
}
return res + "} ";
}
q.await(function(error) {
if (error) throw error;
var svg = d3.select("#d3-celestial-svg svg")
.attr("title", "D3-Celestial")
.attr("version", 1.1)
.attr("encoding", "UTF-8")
.attr("xmlns", "http://www.w3.org/2000/svg")
.attr("xmlns:xlink", "http://www.w3.org/1999/xlink")
.attr("xmlns:sodipodi", "http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd")
.attr("xmlns:inkscape", "http://www.inkscape.org/namespaces/inkscape")
.attr("viewBox", " 0 0 " + (m.width) + " " + (m.height));
defs.append("style")
.attr("type", "text\/css")
.text(createStyles());
/*defs.append(":sodipodi:namedview")
.attr(":inkscape:window-width", m.width+200)
.attr(":inkscape:window-height", m.height)
.attr(":inkscape:window-maximized", "1");*/
if (fname) {
var blob = new Blob([svg.node().outerHTML], {type:"image/svg+xml;charset=utf-8"});
var a = d3.select("body").append("a").node();
a.download = fname || "d3-celestial.svg";
a.rel = "noopener";
a.href = URL.createObjectURL(blob);
a.click();
d3.select(a).remove();
} else if (exportCallback !== null) {
exportCallback(svg.node().outerHTML);
}
d3.select("#d3-celestial-svg").remove();
});
}
var customSvgSymbols = d3.map({
'ellipse': function(size, ratio) {
var s = Math.sqrt(size),
rx = s*0.666, ry = s/3;
return 'M' + (-rx) + ',' + (-ry) +
' m' + (-rx) + ',0' +
' a' + rx + ',' + ry + ' 0 1,0' + (rx * 2) + ',0' +
' a' + rx + ',' + ry + ' 0 1,0' + (-(rx * 2)) + ',0';
},
'marker': function(size, ratio) {
var s = size > 48 ? size / 4 : 12,
r = s/2, l = r-3;
return 'M ' + (-r) + ' 0 h ' + l +
' M 0 ' + (-r) + ' v ' + l +
' M ' + r + ' 0 h ' + (-l) +
' M 0 ' + r + ' v ' + (-l);
},
'cross-circle': function(size, ratio) {
var s = Math.sqrt(size),
r = s/2;
return 'M' + (-r) + ',' + (-r) +
' m' + (-r) + ',0' +
' a' + r + ',' + r + ' 0 1,0' + (r * 2) + ',0' +
' a' + r + ',' + r + ' 0 1,0' + (-(r * 2)) + ',0' +
' M' + (-r) + ' 0 h ' + (s) +
' M 0 ' + (-r) + ' v ' + (s);
},
'stroke-circle': function(size, ratio) {
var s = Math.sqrt(size),
r = s/2;
return 'M' + (-r) + ',' + (-r) +
' m' + (-r) + ',0' +
' a' + r + ',' + r + ' 0 1,0' + (r * 2) + ',0' +
' a' + r + ',' + r + ' 0 1,0' + (-(r * 2)) + ',0' +
' M' + (-s-2) + ',' + (-s-2) + ' l' + (s+4) + ',' + (s+4);
},
"crescent": function(size, ratio) {
var s = Math.sqrt(size),
r = s/2,
ph = 0.5 * (1 - Math.cos(ratio)),
e = 1.6 * Math.abs(ph - 0.5) + 0.01,
dir = ratio > Math.PI ? 0 : 1,
termdir = Math.abs(ph) > 0.5 ? dir : Math.abs(dir-1);
return 'M ' + (-1) + ',' + (-1) +
' m 1,' + (-r+1) +
' a' + r + ',' + r + ' 0 1 ' + dir + ' 0,' + (r * 2) +
' a' + (r*e) + ',' + r + ' 0 1 ' + termdir + ' 0,' + (-(r * 2)) + 'z';
}
});
d3.svg.customSymbol = function() {
var type, size = 64, ratio = d3.functor(1);
function symbol(d,i) {
return customSvgSymbols.get(type.call(this,d,i))(size.call(this,d,i), ratio.call(this,d,i));
}
symbol.type = function(_) {
if (!arguments.length) return type;
type = d3.functor(_);
return symbol;
};
symbol.size = function(_) {
if (!arguments.length) return size;
size = d3.functor(_);
return symbol;
};
symbol.ratio = function(_) {
if (!arguments.length) return ratio;
ratio = d3.functor(_);
return symbol;
};
return symbol;
};
var exportCallback = null;
Celestial.exportSVG = function(callback) {
if (!callback) return;
exportCallback = callback;
exportSVG();
};<file_sep>/src/canvas.js
/* global Celestial */
var Canvas = {};
Canvas.symbol = function () {
// parameters and default values
var type = d3.functor("circle"),
size = d3.functor(64),
age = d3.functor(Math.PI), //crescent shape 0..2Pi
color = d3.functor("#fff"),
text = d3.functor(""),
padding = d3.functor([2,2]),
pos;
function canvas_symbol(context) {
draw_symbol[type()](context);
}
var draw_symbol = {
"circle": function(ctx) {
var s = Math.sqrt(size()),
r = s/2;
ctx.arc(pos[0], pos[1], r, 0, 2 * Math.PI);
ctx.closePath();
return r;
},
"square": function(ctx) {
var s = Math.sqrt(size()),
r = s/1.7;
ctx.moveTo(pos[0]-r, pos[1]-r);
ctx.lineTo(pos[0]+r, pos[1]-r);
ctx.lineTo(pos[0]+r, pos[1]+r);
ctx.lineTo(pos[0]-r, pos[1]+r);
ctx.closePath();
return r;
},
"diamond": function(ctx) {
var s = Math.sqrt(size()),
r = s/1.5;
ctx.moveTo(pos[0], pos[1]-r);
ctx.lineTo(pos[0]+r, pos[1]);
ctx.lineTo(pos[0], pos[1]+r);
ctx.lineTo(pos[0]-r, pos[1]);
ctx.closePath();
return r;
},
"triangle": function(ctx) {
var s = Math.sqrt(size()),
r = s/Math.sqrt(3);
ctx.moveTo(pos[0], pos[1]-r);
ctx.lineTo(pos[0]+r, pos[1]+r);
ctx.lineTo(pos[0]-r, pos[1]+r);
ctx.closePath();
return r;
},
"ellipse": function(ctx) {
var s = Math.sqrt(size()),
r = s/2;
ctx.save();
ctx.translate(pos[0], pos[1]);
ctx.scale(1.6, 0.8);
ctx.beginPath();
ctx.arc(0, 0, r, 0, 2 * Math.PI);
ctx.closePath();
ctx.restore();
return r;
},
"marker": function(ctx) {
var s = Math.sqrt(size()),
r = s/2;
ctx.moveTo(pos[0], pos[1]-r);
ctx.lineTo(pos[0], pos[1]+r);
ctx.moveTo(pos[0]-r, pos[1]);
ctx.lineTo(pos[0]+r, pos[1]);
ctx.closePath();
return r;
},
"cross-circle": function(ctx) {
var s = Math.sqrt(size()),
r = s/2;
ctx.moveTo(pos[0], pos[1]-s);
ctx.lineTo(pos[0], pos[1]+s);
ctx.moveTo(pos[0]-s, pos[1]);
ctx.lineTo(pos[0]+s, pos[1]);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(pos[0], pos[1]);
ctx.arc(pos[0], pos[1], r, 0, 2 * Math.PI);
ctx.closePath();
return r;
},
"stroke-circle": function(ctx) {
var s = Math.sqrt(size()),
r = s/2;
ctx.moveTo(pos[0], pos[1]-s);
ctx.lineTo(pos[0], pos[1]+s);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(pos[0], pos[1]);
ctx.arc(pos[0], pos[1], r, 0, 2 * Math.PI);
ctx.closePath();
return r;
},
"crescent": function(ctx) {
var s = Math.sqrt(size()),
r = s/2,
ag = age(),
ph = 0.5 * (1 - Math.cos(ag)),
e = 1.6 * Math.abs(ph - 0.5) + 0.01,
dir = ag > Math.PI,
termdir = Math.abs(ph) > 0.5 ? dir : !dir,
moonFill = ctx.fillStyle,
darkFill = ph < 0.157 ? "#669" : "#557";
ctx.save();
ctx.fillStyle = darkFill;
ctx.beginPath();
ctx.moveTo(pos[0], pos[1]);
ctx.arc(pos[0], pos[1], r, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
ctx.fillStyle = moonFill;
ctx.beginPath();
ctx.moveTo(pos[0], pos[1]);
ctx.arc(pos[0], pos[1], r, -Math.PI/2, Math.PI/2, dir);
ctx.scale(e, 1);
ctx.arc(pos[0]/e, pos[1], r, Math.PI/2, -Math.PI/2, termdir);
ctx.closePath();
ctx.fill();
ctx.restore();
return r;
}
};
canvas_symbol.type = function(_) {
if (!arguments.length) return type;
type = d3.functor(_);
return canvas_symbol;
};
canvas_symbol.size = function(_) {
if (!arguments.length) return size;
size = d3.functor(_);
return canvas_symbol;
};
canvas_symbol.age = function(_) {
if (!arguments.length) return age;
age = d3.functor(_);
return canvas_symbol;
};
canvas_symbol.text = function(_) {
if (!arguments.length) return text;
text = d3.functor(_);
return canvas_symbol;
};
canvas_symbol.position = function(_) {
if (!arguments.length) return;
pos = _;
return canvas_symbol;
};
return canvas_symbol;
};
Celestial.Canvas = Canvas;
/*var color = "#fff", angle = 0, align = "center", baseline = "middle", font = "10px sans-serif", padding = [0,0], aPos, sText;
canvas.text = function () {
function txt(ctx){
ctx.fillStyle = color;
ctx.textAlign = align;
ctx.textBaseline = baseline;
//var pt = projection(d.geometry.coordinates);
if (angle) {
canvas.save();
canvas.translate(aPos[0], aPos[1]);
canvas.rotate(angle);
canvas.fillText(sText, 0, 0);
canvas.restore();
} else
canvas.fillText(sText, aPos[0], aPos[1]);
}
txt.angle = function(x) {
if (!arguments.length) return angle * 180 / Math.PI;
color = x * Math.PI / 180;
return txt;
};
txt.color = function(s) {
if (!arguments.length) return color;
color = s;
return txt;
};
txt.align = function(s) {
if (!arguments.length) return align;
align = s;
return txt;
};
txt.baseline = function(s) {
if (!arguments.length) return baseline;
baseline = s;
return txt;
};
txt.padding = function(a) {
if (!arguments.length) return padding;
padding = a;
return txt;
};
txt.text = function(s) {
if (!arguments.length) return sText;
sText = s;
return txt;
};
txt.font = function(s) {
if (!arguments.length) return font;
font = s;
return txt;
};
txt.style = function(o) {
if (!arguments.length) return;
if (o.fill) color = o.fill;
if (o.font) font = o.font;
return txt;
};
}
function ctxPath(d) {
var pt;
//d.map( function(axe, i) {
context.beginPath();
for (var i = 0; i < d.length; i++) {
pt = projection(d[i]);
if (i === 0)
context.moveTo(pt[0], pt[1]);
else
context.lineTo(pt[0], pt[1]);
}
context.fill();
}
function ctxText(d, ang) {
var pt = projection(d.geometry.coordinates);
if (ang) {
canvas.save();
canvas.translate(pt[0], pt[1]);
canvas.rotate(Math.PI/2);
canvas.fillText(txt, 0, 0);
canvas.restore();
} else
canvas.fillText(d.properties.txt, pt[0], pt[1]);
}
*/<file_sep>/make.js
var shell = require('shelljs/make'),
ug = require('uglify-js'),
fs = require('fs'),
vm = require('vm'),
//tar = require('tar-fs'),
//zlib = require('zlib'),
version = require('./package.json').version,
copy = "// Copyright 2015-2020 <NAME> https://github.com/ofrohn, see LICENSE\n",
begin = "!(function() {",
end = "this.Celestial = Celestial;\n})();",
filename = './celestial',
filelist = [
'./src/celestial.js',
'./src/projection.js',
'./src/transform.js',
'./src/horizontal.js',
'./src/add.js',
'./src/get.js',
'./src/config.js',
'./src/canvas.js',
'./src/util.js',
'./src/form.js',
'./src/location.js',
'./src/kepler.js',
'./src/moon.js',
'./src/svg.js',
'./src/datetimepicker.js',
'./lib/d3.geo.zoom.js',
'./lib/d3-queue.js'
],
FINAL = true;
target.all = function() {
target.test();
target.build();
};
target.test = function() {
cd('src');
//jshint linting
ls("*.js").forEach(function(file) {
if (exec('jshint ' + file).code !== 0) {
echo('JSHINT FAILED');
exit(0);
}
});
echo('JSHint tests passed');
cd('..');
//run tests
/* cd('test');
ls("*-test.js").forEach(function(file) {
if (exec('node ' + file).code !== 123) {
echo('TEST FAILED for ' + file);
exit(0);
}
});
echo('Unit tests passed');
cd('..');*/
};
target.build = function() {
vm.runInThisContext(fs.readFileSync('./src/celestial.js', 'utf-8'), './src/celestial.js');
echo('V' + Celestial.version);
if (!FINAL) filename += Celestial.version;
if (version !== Celestial.version)
exec("npm version " + Celestial.version);
var file = cat(filelist);
file = copy + begin + file.replace(/\/\* global.*/g, '') + end;
file.to(filename + '.js');
echo('Minifying');
var out = ug.minify(filename + '.js');
echo(out.error || "OK");
fs.writeFileSync(filename + '.min.js', copy + out.code);
/*var read = ug.parse(fs.readFileSync(filename + '.js', "utf8"));
read.figure_out_scope();
var comp = read.transform( UglifyJS.Compressor(); );
comp.figure_out_scope();
comp.compute_char_frequency();
comp.mangle_names();
var out = comp.print_to_string();
fs.writeFileSync(filename + '.min.js', out);
*/
//echo('Writing data');
// zip data + prod. code + css
/*tar.pack('./', {
entries: ['celestial.css', 'readme.md', 'LICENSE', 'celestial.min.js', 'celestial.js', 'images/dtpick.png', 'data', 'demo', 'lib/d3.min.js', 'lib/d3.geo.projection.min.js']
})
.pipe(zlib.createGzip())
.pipe(fs.createWriteStream(filename + '.tar.gz'))
*/
echo('Done');
};<file_sep>/src/form.js
/* global Celestial, settings, globalConfig, formats, formats_all, $, px, has, isNumber, isObject, isArray, findPos, transformDeg, euler, exportSVG, parentElement */
//display settings form in div with id "celestial-form"
function form(cfg) {
var config = settings.set(cfg);
var prj = Celestial.projections(), leo = Celestial.eulerAngles();
var div = d3.select(parentElement + " ~ #celestial-form");
//if div doesn't exist, create it
if (div.size() < 1) {
//var container = (config.container || "celestial-map");
div = d3.select(parentElement).select(function() { return this.parentNode; }).append("div").attr("id", "celestial-form");
}
var ctrl = div.append("div").attr("class", "ctrl");
var frm = ctrl.append("form").attr("id", "params").attr("name", "params").attr("method", "get").attr("action" ,"#");
//Map parameters
var col = frm.append("div").attr("class", "col").attr("id", "general");
col.append("label").attr("title", "Map width in pixel, 0 indicates full width").attr("for", "width").html("Width ");
col.append("input").attr("type", "number").attr("maxlength", "4").attr("max", "20000").attr("min", "0").attr("title", "Map width").attr("id", "width").attr("value", config.width).on("change", resize);
col.append("span").html("px");
col.append("label").attr("title", "Map projection, (hemi) indicates hemispherical projection").attr("for", "projection").html("Projection");
var sel = col.append("select").attr("id", "projection").on("change", reproject);
var selected = 0;
var list = Object.keys(prj).map( function (key, i) {
var n = prj[key].clip && prj[key].clip === true ? prj[key].n + " (hemi)" : prj[key].n;
if (key === config.projection) selected = i;
return {o:key, n:n};
});
sel.selectAll('option').data(list).enter().append('option')
.attr("value", function (d) { return d.o; })
.text(function (d) { return d.n; });
sel.property("selectedIndex", selected);
selected = 0;
col.append("label").attr("title", "Coordinate space in which the map is displayed").attr("for", "transform").html("Coordinates");
sel = col.append("select").attr("id", "transform").on("change", reload);
list = Object.keys(leo).map(function (key, i) {
if (key === config.transform) selected = i;
return {o:key, n:key.replace(/^([a-z])/, function(s, m) { return m.toUpperCase(); } )};
});
sel.selectAll("option").data(list).enter().append('option')
.attr("value", function (d) { return d.o; })
.text(function (d) { return d.n; });
sel.property("selectedIndex", selected);
col.append("br");
col.append("label").attr("title", "Center coordinates long/lat in selected coordinate space").attr("for", "centerx").html("Center");
col.append("input").attr("type", "number").attr("id", "centerx").attr("title", "Center right ascension/longitude").attr("max", "24").attr("min", "0").attr("step", "0.1").on("change", turn);
col.append("span").attr("id", "cxunit").html("h");
//addList("centerx", "ra");
col.append("input").attr("type", "number").attr("id", "centery").attr("title", "Center declination/latitude").attr("max", "90").attr("min", "-90").attr("step", "0.1").on("change", turn);
col.append("span").html("\u00b0");
col.append("label").attr("title", "Orientation").attr("for", "centerz").html("Orientation");
col.append("input").attr("type", "number").attr("id", "centerz").attr("title", "Center orientation").attr("max", "180").attr("min", "-180").attr("step", "0.1").on("change", turn);
col.append("span").html("\u00b0");
col.append("label").attr("for", "orientationfixed").attr("class", "advanced").html("Fixed");
col.append("input").attr("type", "checkbox").attr("id", "orientationfixed").attr("class", "advanced").property("checked", config.orientationfixed).on("change", apply);
col.append("label").attr("title", "Center and zoom in on this constellation").attr("for", "constellation").html("Show");
col.append("select").attr("id", "constellation").on("change", showConstellation);
setCenter(config.center, config.transform);
// Stars
col = frm.append("div").attr("class", "col").attr("id", "stars");
col.append("label").attr("class", "header").attr("for", "stars-show").html("Stars");
col.append("input").attr("type", "checkbox").attr("id", "stars-show").property("checked", config.stars.show).on("change", apply);
col.append("label").attr("for", "stars-limit").html("down to magnitude");
col.append("input").attr("type", "number").attr("id", "stars-limit").attr("title", "Star display limit (magnitude)").attr("value", config.stars.limit).attr("max", "6").attr("min", "-1").attr("step", "0.1").on("change", apply);
col.append("label").attr("for", "stars-colors").html("with spectral colors");
col.append("input").attr("type", "checkbox").attr("id", "stars-colors").property("checked", config.stars.colors).on("change", apply);
col.append("label").attr("for", "stars-color").html("or default color ");
col.append("input").attr("type", "color").attr("autocomplete", "off").attr("id", "stars-style-fill").attr("title", "Star color").property("value", config.stars.style.fill).on("change", apply);
col.append("br");
var names = formats.starnames[config.culture] || formats.starnames.iau;
for (var fld in names) {
if (!has(names, fld)) continue;
var keys = Object.keys(names[fld]);
if (keys.length > 1) {
//Select List
col.append("label").attr("for", "stars-" + fld).html("Show");
selected = 0;
col.append("label").attr("title", "Type of star name").attr("id", "label-propername").attr("for", "stars-" + fld + "Type").html(function () { return fld === "propername" ? "proper names" : ""; });
sel = col.append("select").attr("id", "stars-" + fld + "Type").attr("class", function () { return fld === "propername" ? "advanced" : ""; }).on("change", apply);
list = keys.map(function (key, i) {
if (key === config.stars[fld + "Type"]) selected = i;
return {o:key, n:names[fld][key]};
});
sel.selectAll("option").data(list).enter().append('option')
.attr("value", function (d) { return d.o; })
.text(function (d) { return d.n; });
sel.property("selectedIndex", selected);
col.append("input").attr("type", "checkbox").attr("id", "stars-" + fld).property("checked", config.stars[fld]).on("change", apply);
} else if (keys.length === 1) {
//Simple field
col.append("label").attr("for", "stars-" + fld).html(" " + names[fld][keys[0]]);
col.append("input").attr("type", "checkbox").attr("id", "stars-" + fld).property("checked", config.stars[fld]).on("change", apply);
}
col.append("label").attr("for", "stars-" + fld + "Limit").html("down to mag");
col.append("input").attr("type", "number").attr("id", "stars-" + fld + "Limit").attr("title", "Star name display limit (magnitude)").attr("value", config.stars[fld + "Limit"]).attr("max", "6").attr("min", "-1").attr("step", "0.1").on("change", apply);
}
col.append("br");
col.append("label").attr("for", "stars-size").attr("class", "advanced").html("Stellar disk size: base");
col.append("input").attr("type", "number").attr("id", "stars-size").attr("class", "advanced").attr("title", "Size of the displayed star disk; base").attr("value", config.stars.size).attr("max", "100").attr("min", "0").attr("step", "0.1").on("change", apply);
col.append("label").attr("for", "stars-exponent").attr("class", "advanced").html(" * e ^ (exponent");
col.append("input").attr("type", "number").attr("id", "stars-exponent").attr("class", "advanced").attr("title", "Size of the displayed star disk; exponent").attr("value", config.stars.exponent).attr("max", "3").attr("min", "-1").attr("step", "0.01").on("change", apply);
col.append("span").attr("class", "advanced").text(" * (magnitude + 2)) [* adaptation]");
enable($form("stars-show"));
// DSOs
col = frm.append("div").attr("class", "col").attr("id", "dsos");
col.append("label").attr("class", "header").attr("title", "Deep Space Objects").attr("for", "dsos-show").html("DSOs");
col.append("input").attr("type", "checkbox").attr("id", "dsos-show").property("checked", config.dsos.show).on("change", apply);
col.append("label").attr("for", "dsos-limit").html("down to mag");
col.append("input").attr("type", "number").attr("id", "dsos-limit").attr("title", "DSO display limit (magnitude)").attr("value", config.dsos.limit).attr("max", "6").attr("min", "0").attr("step", "0.1").on("change", apply);
col.append("label").attr("for", "dsos-colors").html("with symbol colors");
col.append("input").attr("type", "checkbox").attr("id", "dsos-colors").property("checked", config.dsos.colors).on("change", apply);
col.append("label").attr("for", "dsos-color").html("or default color ");
col.append("input").attr("type", "color").attr("autocomplete", "off").attr("id", "dsos-style-fill").attr("title", "DSO color").property("value", config.dsos.style.fill).on("change", apply);
col.append("br");
names = formats.dsonames[config.culture] || formats.dsonames.iau;
for (fld in names) {
if (!has(names, fld)) continue;
var dsoKeys = Object.keys(names[fld]);
col.append("label").attr("for", "dsos-" + fld).html("Show");
selected = 0;
col.append("label").attr("title", "Type of DSO name").attr("for", "dsos-" + fld + "Type").attr("class", "advanced").html("");
sel = col.append("select").attr("id", "dsos-" + fld + "Type").attr("class", "advanced").on("change", apply);
list = dsoKeys.map(function (key, i) {
if (key === config.stars[fld + "Type"]) selected = i;
return {o:key, n:names[fld][key]};
});
sel.selectAll("option").data(list).enter().append('option')
.attr("value", function (d) { return d.o; })
.text(function (d) { return d.n; });
sel.property("selectedIndex", selected);
col.append("label").attr("for", "dsos-" + fld).html("names");
col.append("input").attr("type", "checkbox").attr("id", "dsos-" + fld).property("checked", config.dsos[fld]).on("change", apply);
}
col.append("label").attr("for", "dsos-nameLimit").html("down to mag");
col.append("input").attr("type", "number").attr("id", "dsos-nameLimit").attr("title", "DSO name display limit (magnitude)").attr("value", config.dsos.nameLimit).attr("max", "6").attr("min", "0").attr("step", "0.1").on("change", apply);
col.append("br");
col.append("label").attr("for", "dsos-size").attr("class", "advanced").html("DSO symbol size: (base");
col.append("input").attr("type", "number").attr("id", "dsos-size").attr("class", "advanced").attr("title", "Size of the displayed symbol: base").attr("value", config.dsos.size).attr("max", "100").attr("min", "0").attr("step", "0.1").on("change", apply);
col.append("label").attr("for", "dsos-exponent").attr("class", "advanced").html(" * 2 [* adaptation] - magnitude) ^ exponent");
col.append("input").attr("type", "number").attr("id", "dsos-exponent").attr("class", "advanced").attr("title", "Size of the displayed symbol; exponent").attr("value", config.dsos.exponent).attr("max", "3").attr("min", "-1").attr("step", "0.01").on("change", apply);
enable($form("dsos-show"));
// Constellations
col = frm.append("div").attr("class", "col").attr("id", "constellations");
col.append("label").attr("class", "header").html("Constellations");
//col.append("input").attr("type", "checkbox").attr("id", "constellations-show").property("checked", config.constellations.show).on("change", apply);
names = formats.constellations[config.culture] || formats.constellations.iau;
for (fld in names) {
if (!has(names, fld)) continue;
var nameKeys = Object.keys(names[fld]);
if (nameKeys.length > 1) {
//Select List
col.append("label").attr("for", "constellations-" + fld).html("Show");
selected = 0;
col.append("label").attr("title", "Language of constellation names").attr("for", "constellations-" + fld + "Type").attr("class", "advanced").html("");
sel = col.append("select").attr("id", "constellations-" + fld + "Type").attr("class", "advanced").on("change", apply);
list = nameKeys.map(function (key, i) {
if (key === config.constellations[fld + "Type"]) selected = i;
return {o:key, n:names[fld][key]};
});
sel.selectAll("option").data(list).enter().append('option')
.attr("value", function (d) { return d.o; })
.text(function (d) { return d.n; });
sel.property("selectedIndex", selected);
col.append("label").attr("for", "constellations-" + fld).html("names");
col.append("input").attr("type", "checkbox").attr("id", "constellations-" + fld).property("checked", config.constellations[fld]).on("change", apply);
} else if (nameKeys.length === 1) {
//Simple field
col.append("label").attr("for", "constellations-" + fld).attr("class", "advanced").html(" " + names[fld][nameKeys[0]]);
col.append("input").attr("type", "checkbox").attr("id", "constellations-" + fld).attr("class", "advanced").property("checked", config.constellations[fld]).on("change", apply);
}
}
col.append("label").attr("for", "constellations-lines").html(" lines");
col.append("input").attr("type", "checkbox").attr("id", "constellations-lines").property("checked", config.constellations.lines).on("change", apply);
col.append("label").attr("for", "constellations-bounds").html(" boundaries");
col.append("input").attr("type", "checkbox").attr("id", "constellations-bounds").property("checked", config.constellations.bounds).on("change", apply);
enable($form("constellations-names"));
// graticules & planes
col = frm.append("div").attr("class", "col").attr("id", "lines");
col.append("label").attr("class", "header").html("Lines");
col.append("label").attr("title", "Latitude/longitude grid lines").attr("for", "lines-graticule").html("Graticule");
col.append("input").attr("type", "checkbox").attr("id", "lines-graticule-show").property("checked", config.lines.graticule.show).on("change", apply);
col.append("label").attr("for", "lines-equatorial").html("Equator");
col.append("input").attr("type", "checkbox").attr("id", "lines-equatorial-show").property("checked", config.lines.equatorial.show).on("change", apply);
col.append("label").attr("for", "lines-ecliptic").html("Ecliptic");
col.append("input").attr("type", "checkbox").attr("id", "lines-ecliptic-show").property("checked", config.lines.ecliptic.show).on("change", apply);
col.append("label").attr("for", "lines-galactic").html("Galactic plane");
col.append("input").attr("type", "checkbox").attr("id", "lines-galactic-show").property("checked", config.lines.galactic.show).on("change", apply);
col.append("label").attr("for", "lines-supergalactic").html("Supergalactic plane");
col.append("input").attr("type", "checkbox").attr("id", "lines-supergalactic-show").property("checked", config.lines.supergalactic.show).on("change", apply);
// Other
col = frm.append("div").attr("class", "col").attr("id", "other");
col.append("label").attr("class", "header").html("Other");
col.append("label").attr("for", "mw-show").html("Milky Way");
col.append("input").attr("type", "checkbox").attr("id", "mw-show").property("checked", config.mw.show).on("change", apply);
col.append("label").attr("for", "mw-style-fill").attr("class", "advanced").html(" color");
col.append("input").attr("type", "color").attr("id", "mw-style-fill").attr("class", "advanced").attr("title", "Milky Way color").attr("value", config.mw.style.fill).on("change", apply);
col.append("label").attr("for", "mw-style-opacity").attr("class", "advanced").html(" opacity");
col.append("input").attr("type", "number").attr("id", "mw-style-opacity").attr("class", "advanced").attr("title", "Transparency of each Milky Way layer").attr("value", config.mw.style.opacity).attr("max", "1").attr("min", "0").attr("step", "0.01").on("change", apply);
col.append("label").attr("for", "advanced").html("Advanced options");
col.append("input").attr("type", "checkbox").attr("id", "advanced").property("checked", config.advanced).on("change", apply);
col.append("br");
col.append("label").attr("for", "background-fill").html("Background color");
col.append("input").attr("type", "color").attr("id", "background-fill").attr("title", "Background color").attr("value", config.background.fill).on("change", apply);
col.append("label").attr("for", "background-opacity").attr("class", "advanced").html("opacity");
col.append("input").attr("type", "number").attr("id", "background-opacity").attr("class", "advanced").attr("title", "Background opacity").attr("value", config.background.opacity).attr("max", "1").attr("min", "0").attr("step", "0.01").on("change", apply);
col.append("label").attr("title", "Star/DSO sizes are increased with higher zoom-levels").attr("for", "adaptable").attr("class", "advanced").html("Adaptable object sizes");
col.append("input").attr("type", "checkbox").attr("id", "adaptable").attr("class", "advanced").property("checked", config.adaptable).on("change", apply);
// General language setting
var langKeys = formats_all[config.culture];
selected = 0;
col.append("label").attr("title", "General language setting").attr("for", "lang").html("Object names ");
sel = col.append("select").attr("id", "lang").on("change", apply);
list = langKeys.map(function (key, i) {
if (key === config.lang) selected = i;
return {o:key, n:formats.constellations[config.culture].names[key]};
});
list = [{o:"---", n:"(Select language)"}].concat(list);
sel.selectAll("option").data(list).enter().append('option')
.attr("value", function (d) { return d.o; })
.text(function (d) { return d.n; });
sel.property("selectedIndex", selected);
col = frm.append("div").attr("class", "col").attr("id", "download");
col.append("label").attr("class", "header").html("Download");
col.append("input").attr("type", "button").attr("id", "download-png").attr("value", "PNG Image").on("click", function() {
var a = d3.select("body").append("a").node(),
canvas = document.querySelector(parentElement + ' canvas');
a.download = getFilename(".png");
a.rel = "noopener";
a.href = canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream');
a.click();
d3.select(a).remove();
});
col.append("input").attr("type", "button").attr("id", "download-svg").attr("value", "SVG File").on("click", function() {
exportSVG(getFilename(".svg"));
return false;
});
setLimits();
setUnit(config.transform);
setVisibility(cfg);
showAdvanced(config.advanced);
function resize() {
var src = this,
w = src.value;
if (testNumber(src) === false) return;
config.width = w;
Celestial.resize({width:w});
}
function reload() {
var src = this,
trans = src.value,
cx = setUnit(trans, config.transform);
if (cx !== null) config.center[0] = cx;
config.transform = trans;
settings.set(config);
Celestial.reload(config);
}
function reproject() {
var src = this;
if (!src) return;
config.projection = src.value;
settings.set(config);
Celestial.reproject(config);
}
function turn() {
if (testNumber(this) === false) return;
if (getCenter() === false) return;
Celestial.rotate(config);
}
function getCenter() {
var cx = $form("centerx"), cy = $form("centery"), cz = $form("centerz"),
rot = [];
if (!cx || !cy) return;
if (config.transform !== "equatorial") config.center[0] = parseFloat(cx.value);
else {
var vx = parseFloat(cx.value);
config.center[0] = vx > 12 ? vx * 15 - 360 : vx * 15;
}
config.center[1] = parseFloat(cy.value);
var vz = parseFloat(cz.value);
config.center[2] = isNaN(vz) ? 0 : vz;
return cx.value !== "" && cy.value !== "";
}
function getFilename(ext) {
var dateFormat = d3.time.format("%Y%m%dT%H%M%S%Z"),
filename = "d3-celestial",
dt = Celestial.date();
if (dt) filename += dateFormat(dt);
return filename + ext;
}
function showConstellation() {
var id = this.value;
if (!id) return;
showCon(id);
}
function showCon(id) {
var z, anims = [],
config = globalConfig;
if (id === "---") {
Celestial.constellation = null;
z = Celestial.zoomBy();
if (z !== 1) {
anims.push({param:"zoom", value:1/z, duration:0});
}
Celestial.animate(anims, false);
//Celestial.redraw();
return;
}
if (!isObject(Celestial.constellations) || !has(Celestial.constellations, id)) return;
var con = Celestial.constellations[id];
//transform according to settings
var center = transformDeg(con.center, euler[config.transform]);
config.center = center;
setCenter(config.center, config.transform);
//config.lines.graticule.lat.pos = [Round(con.center[0])];
//config.lines.graticule.lon.pos = [Round(con.center[1])];
//Celestial.apply(config);
//if zoomed, zoom out
z = Celestial.zoomBy();
if (z !== 1) anims.push({param:"zoom", value:1/z, duration:0});
//rotate
anims.push({param:"center", value:center, duration:0});
//and zoom in
var sc = 1 + (360/con.scale); // > 10 ? 10 : con.scale;
anims.push({param:"zoom", value:sc, duration:0});
Celestial.constellation = id;
//Object.assign(globalConfig, config);
Celestial.animate(anims, false);
}
function apply() {
var value, src = this;
//Get current configuration
Object.assign(config, settings.set());
switch (src.type) {
case "checkbox": value = src.checked; enable(src); break;
case "number": if (testNumber(src) === false) return;
value = parseFloat(src.value); break;
case "color": if (testColor(src) === false) return;
value = src.value; break;
case "text": if (src.id.search(/fill$/) === -1) return;
if (testColor(src) === false) return;
value = src.value; break;
case "select-one": value = src.value; break;
}
if (value === null) return;
set(src.id, value);
if (src.id === "dsos-style-fill") {
set("dsos-style-stroke", value);
set("dsos-nameStyle-fill", value);
} else if (src.id === "constellations-namesType") {
listConstellations();
} else if (src.id === "lang") {
setLanguage(value);
} else if (src.id === "advanced") {
showAdvanced(value);
}
getCenter();
Object.assign(globalConfig, config);
Celestial.apply(config);
}
function set(prop, val) {
var a = prop.split("-");
switch (a.length) {
case 1: config[a[0]] = val; break;
case 2: config[a[0]][a[1]] = val; break;
case 3: config[a[0]][a[1]][a[2]] = val; break;
default: return;
}
}
function setLanguage(lang) {
Object.assign(config, globalConfig);
config.lang = lang;
var keys = ["constellations", "planets"];
for (var i=0; i < keys.length; i++) {
if (has(formats[keys[i]][config.culture].names, lang)) config[keys[i]].namesType = lang;
else if (has(formats[keys[i]][config.culture].names, "desig")) config[keys[i]].namesType = "desig";
else config[keys[i]].namesType = "name";
}
if (has(formats.dsonames[config.culture].names, lang)) config.dsos.namesType = lang;
else config.dsos.namesType = "desig";
if (has(formats.starnames[config.culture].propername, lang)) config.stars.propernameType = lang;
else config.stars.propernameType = "desig";
//update cont. list
Object.assign(globalConfig, config);
update();
listConstellations();
return config;
}
function update() {
// Update all form fields
d3.selectAll(parentElement + " ~ #celestial-form input, " + parentElement + " ~ #celestial-form select").each( function(d, i) {
if (this === undefined) return;
var id = this.id;
// geopos -> lat, lon
if (id === "lat" || id === "lon") {
if (isArray(config.geopos)) this.value = id === "lat" ? config.geopos[0] : config.geopos[1];
// center -> centerx, centery
} else if (id.search(/center/) !== -1) {
if (isArray(config.center)) {
switch (id) {
case "centerx": this.value = config.center[0]; break;
case "centery": this.value = config.center[1]; break;
case "centerz": this.value = config.center[2] || 0; break;
}
}
} else if (id === "datetime" || id === "hr" || id === "min" || id === "sec" || id === "tz") {
return;//skip, timezone?
} else if (this.type !== "button") {
var value = get(id);
switch (this.type) {
case "checkbox": this.checked = value; enable(id); break;
case "number": if (testNumber(this) === false) break;
this.value = parseFloat(get(id)); break;
case "color": if (testColor(this) === false) break;
this.value = value; break;
case "text": if (id.search(/fill$/) === -1) break;
if (testColor(this) === false) break;
this.value = value; break;
case "select-one": this.value = value; break;
}
}
});
}
function get(id) {
var a = id.split("-");
switch (a.length) {
case 1: return config[a[0]];
case 2: return config[a[0]][a[1]];
case 3: return config[a[0]][a[1]][a[2]];
default: return;
}
}
Celestial.updateForm = update;
Celestial.showConstellation = showCon;
Celestial.setLanguage = function(lang) {
var cfg = settings.set();
if (formats_all[config.culture].indexOf(lang) !== -1) cfg = setLanguage(lang);
return cfg;
};
}
// Dependend fields relations
var depends = {
"stars-show": ["stars-limit", "stars-colors", "stars-style-fill", "stars-designation", "stars-propername", "stars-size", "stars-exponent"],
"stars-designation": ["stars-designationType", "stars-designationLimit"],
"stars-propername": ["stars-propernameLimit", "stars-propernameType"],
"dsos-show": ["dsos-limit", "dsos-colors", "dsos-style-fill", "dsos-names", "dsos-size", "dsos-exponent"],
"dsos-names": ["dsos-namesType", "dsos-nameLimit"],
"mw-show": ["mw-style-opacity", "mw-style-fill"],
"constellations-names": ["constellations-namesType"],
"planets-show": ["planets-symbolType", "planets-names"],
"planets-names": ["planets-namesType"]
};
// De/activate fields depending on selection of dependencies
function enable(source) {
var fld = source.id, off;
switch (fld) {
case "stars-show":
off = !$form(fld).checked;
for (var i=0; i< depends[fld].length; i++) { fldEnable(depends[fld][i], off); }
/* falls through */
case "stars-designation":
off = !$form("stars-designation").checked || !$form("stars-show").checked;
for (i=0; i< depends["stars-designation"].length; i++) { fldEnable(depends["stars-designation"][i], off); }
/* falls through */
case "stars-propername":
off = !$form("stars-propername").checked || !$form("stars-show").checked;
for (i=0; i< depends["stars-propername"].length; i++) { fldEnable(depends["stars-propername"][i], off); }
break;
case "dsos-show":
off = !$form(fld).checked;
for (i=0; i< depends[fld].length; i++) { fldEnable(depends[fld][i], off); }
/* falls through */
case "dsos-names":
off = !$form("dsos-names").checked || !$form("dsos-show").checked;
for (i=0; i< depends["dsos-names"].length; i++) { fldEnable(depends["dsos-names"][i], off); }
break;
case "planets-show":
off = !$form(fld).checked;
for (i=0; i< depends[fld].length; i++) { fldEnable(depends[fld][i], off); }
/* falls through */
case "planets-names":
off = !$form("planets-names").checked || !$form("planets-show").checked;
for (i=0; i< depends["planets-names"].length; i++) { fldEnable(depends["planets-names"][i], off); }
break;
case "constellations-names":
case "mw-show":
off = !$form(fld).checked;
for (i=0; i< depends[fld].length; i++) { fldEnable(depends[fld][i], off); }
break;
}
}
// Enable/disable field d to status off
function fldEnable(d, off) {
var node = $form(d);
if (!node) return;
node.disabled = off;
node.style.color = off ? "#999" : "#000";
node.previousSibling.style.color = off ? "#999" : "#000";
//if (node.previousSibling.previousSibling && node.previousSibling.previousSibling.tagName === "LABEL")
// node.previousSibling.previousSibling.style.color = off ? "#999" : "#000";
}
// Error notification
function popError(nd, err) {
var p = findPos(nd);
d3.select("#error").html(err).style( {top:px(p[1] + nd.offsetHeight + 1), left:px(p[0]), opacity:1} );
nd.focus();
}
//Check numeric field
function testNumber(node) {
var v, adj = node.id === "hr" || node.id === "min" || node.id === "sec" ? 1 : 0;
if (node.validity) {
v = node.validity;
if (v.typeMismatch || v.badInput) { popError(node, node.title + ": check field value"); return false; }
if (v.rangeOverflow || v.rangeUnderflow) { popError(node, node.title + " must be between " + (parseInt(node.min) + adj) + " and " + (parseInt(node.max) - adj)); return false; }
} else {
v = node.value;
if (!isNumber(v)) { popError(node, node.title + ": check field value"); return false; }
v = parseFloat(v);
if (v < node.min || v > node.max ) { popError(node, node.title + " must be between " + (node.min + adj) + " and " + (+node.max - adj)); return false; }
}
d3.select("#error").style( {top:"-9999px", left:"-9999px", opacity:0} );
return true;
}
//Check color field
function testColor(node) {
var v;
if (node.validity) {
v = node.validity;
if (v.typeMismatch || v.badInput) { popError(node, node.title + ": check field value"); return false; }
if (node.value.search(/^#[0-9A-F]{6}$/i) === -1) { popError(node, node.title + ": not a color value"); return false; }
} else {
v = node.value;
if (v === "") return true;
if (v.search(/^#[0-9A-F]{6}$/i) === -1) { popError(node, node.title + ": not a color value"); return false; }
}
d3.select("#error").style( {top:"-9999px", left:"-9999px", opacity:0} );
return true;
}
function setUnit(trans, old) {
var cx = $form("centerx");
if (!cx) return null;
if (old) {
if (trans === "equatorial" && old !== "equatorial") {
cx.value = (cx.value/15).toFixed(1);
if (cx.value < 0) cx.value += 24;
} else if (trans !== "equatorial" && old === "equatorial") {
cx.value = (cx.value * 15).toFixed(1);
if (cx.value > 180) cx.value -= 360;
}
}
if (trans === 'equatorial') {
cx.min = "0";
cx.max = "24";
$form("cxunit").innerHTML = "h";
} else {
cx.min = "-180";
cx.max = "180";
$form("cxunit").innerHTML = "\u00b0";
}
return cx.value;
}
function setCenter(ctr, trans) {
var cx = $form("centerx"), cy = $form("centery"), cz = $form("centerz");
if (!cx || !cy) return;
if (ctr === null || ctr.length < 1) ctr = [0,0,0];
if (ctr.length <= 2 || ctr[2] === undefined) ctr[2] = 0;
//config.center = ctr;
if (trans !== "equatorial") cx.value = ctr[0].toFixed(1);
else cx.value = ctr[0] < 0 ? (ctr[0] / 15 + 24).toFixed(1) : (ctr[0] / 15).toFixed(1);
cy.value = ctr[1].toFixed(1);
cz.value = ctr[2] !== null ? ctr[2].toFixed(1) : 0;
settings.set({center: ctr});
}
// Set max input limits depending on data
function setLimits() {
var t, rx = /\d+(\.\d+)?/g,
s, d, res = {s:6, d:6},
config = Celestial.settings();
d = config.dsos.data;
//test dso limit
t = d.match(rx);
if (t !== null) {
res.d = parseFloat(t[t.length-1]);
}
if (res.d !== 6) {
$form("dsos-limit").max = res.d;
$form("dsos-nameLimit").max = res.d;
}
s = config.stars.data;
//test star limit
t = s.match(rx);
if (t !== null) {
res.s = parseFloat(t[t.length-1]);
}
if (res.s != 6) {
$form("stars-limit").max = res.s;
$form("stars-designationLimit").max = res.s;
$form("stars-propernameLimit").max = res.s;
}
return res;
}
// Options only visible in advanced mode
//"stars-designationType", "stars-propernameType", "stars-size", "stars-exponent", "stars-size", "stars-exponent", //"constellations-namesType", "planets-namesType", "planets-symbolType"
function showAdvanced(showit) {
var vis = showit ? "inline-block" : "none";
d3.select(parentElement + " ~ #celestial-form").selectAll(".advanced").style("display", vis);
d3.select(parentElement + " ~ #celestial-form").selectAll("#label-propername").style("display", showit ? "none" : "inline-block");
}
function setVisibility(cfg, which) {
var vis, fld;
if (!has(cfg, "formFields")) return;
if (which && has(cfg.formFields, which)) {
d3.select(parentElement + " ~ #celestial-form").select("#" + which).style( {"display": "none"} );
return;
}
// Special case for backward compatibility
if (cfg.form === false && cfg.location === true) {
d3.select(parentElement + " ~ #celestial-form").style("display", "inline-block");
for (fld in cfg.formFields) {
if (!has(cfg.formFields, fld)) continue;
if (fld === "location") continue;
d3.select(parentElement + " ~ #celestial-form").select("#" + fld).style( {"display": "none"} );
}
return;
}
// hide if not desired
if (cfg.form === false) d3.select(parentElement + " ~ #celestial-form").style("display", "none");
for (fld in cfg.formFields) {
if (!has(cfg.formFields, fld)) continue;
if (fld === "location") continue;
vis = cfg.formFields[fld] === false ? "none" : "block";
d3.select(parentElement + " ~ #celestial-form").select("#" + fld).style( {"display": vis} );
}
}
function listConstellations() {
var sel = d3.select(parentElement + " ~ #celestial-form").select("#constellation"),
list = [], selected = 0, id, name, config = globalConfig;
Celestial.container.selectAll(".constname").each( function(d, i) {
id = d.id;
if (id === config.constellation) selected = i;
name = d.properties[config.constellations.namesType];
if (name !== id) name += " (" + id + ")";
list.push({o:id, n:name});
});
if (list.length < 1 || sel.length < 1) {
setTimeout(listConstellations, 1000);
return;
}
list = [{o:"---", n:"(Select constellation)"}].concat(list);
sel.selectAll('option').remove();
sel.selectAll('option').data(list).enter().append('option')
.attr("value", function (d) { return d.o; })
.text(function (d) { return d.n; });
sel.property("selectedIndex", selected);
//$form("constellation").firstChild.disabled = true;
//Celestial.constellations = list;
}
function $form(id) { return document.querySelector(parentElement + " ~ #celestial-form" + " #" + id); }
<file_sep>/test/projection-test.js
var shell = require('shelljs/global'),
fs = require('fs'),
assert = require('assert'),
vm = require('vm'),
shell = require('shelljs'),
jsdom = require("jsdom").jsdom,
includes = ['../lib/d3.js', '../lib/d3.geo.projection.js', '../src/config.js', '../src/util.js', '../src/projection.js'];
global.document = jsdom("Testing"),
global.window = document.parentWindow;
global.Celestial = {};
includes.forEach(function(file) {
vm.runInThisContext(fs.readFileSync(file, 'utf-8'), file);
});
//Method exists
assert.ok(Celestial.hasOwnProperty("projection"));
//Returns valid projection
assert.ok(Celestial.projection("aitoff"));
//Returns error
//assert.throws(Celestial.projection(), Error);
shell.exit(123);
<file_sep>/test/transform-test.js
var shell = require('shelljs/global'),
fs = require('fs'),
assert = require('assert'),
vm = require('vm'),
shell = require('shelljs'),
jsdom = require("jsdom").jsdom,
includes = ['../lib/d3.js', '../lib/d3.geo.projection.js', '../src/transform.js'],
result;
var Round = function(val) { return (Math.round(val*1000)/1000); };
global.document = jsdom("Testing"),
global.window = document.parentWindow;
global.Celestial = {};
includes.forEach(function(file) {
vm.runInThisContext(fs.readFileSync(file, 'utf-8'), file);
});
//Euler angles in radians
assert.deepEqual(euler.galactic.map(Round), [-2.917, 1.097, 2.146]);
assert.deepEqual(euler.add("test", [10,10,10]).map(Round), [10*deg2rad, 10*deg2rad, 10*deg2rad].map(Round));
//Method exists
assert.ok(Celestial.hasOwnProperty("graticule"));
//Zero case without euler angles, return unchanged
assert.deepEqual(transformDeg([0,0]).map(Round), [0,0]);
assert.deepEqual(transformDeg([75,40]).map(Round), [75,40].map(Round));
//Transform to galactic coordinates
assert.deepEqual(transformDeg([0,0], euler.galactic).map(Round), [96.337, -60.189].map(Round));
//Transform to galactic coordinates 2
assert.deepEqual(transformDeg([75,40], euler.galactic).map(Round), [165.579, -1.461].map(Round));
//Transform to ecliptic coordinates
assert.deepEqual(transformDeg([75,40], euler.ecliptic).map(Round), [78.022, 17.182].map(Round));
//Transform to supergalactic coordinates
assert.deepEqual(transformDeg([75,40], euler.supergalactic).map(Round), [1.735, -28.194].map(Round));
//Transform to galactic coordinates, radians
assert.deepEqual(transform([75*deg2rad,40*deg2rad], euler.galactic).map(Round), [165.579*deg2rad, -1.461*deg2rad].map(Round));
//Transform to ecliptic coordinates, radians
assert.deepEqual(transform([75*deg2rad,40*deg2rad], euler.ecliptic).map(Round), [78.022*deg2rad, 17.182*deg2rad].map(Round));
//Transform to supergalactic coordinates, radians
assert.deepEqual(transform([75*deg2rad,40*deg2rad], euler.supergalactic).map(Round), [1.735*deg2rad, -28.195*deg2rad].map(Round));
shell.exit(123);
<file_sep>/readme.md
# Celestial map with D3.js
Interactive, adaptable celestial map done with the [D3.js](http://d3js.org/) visualization library. So, GeoJSON for sky stuff. Which surprisingly nobody has done yet, it seems.
Features display of stars and deep sky objects (DSOs) with a selectable magnitude limit up to 6, or choose different GeoJSON data source for higher magnitudes. Also shows constellations with names, lines and/or boundaries, the Milky Way band and grid lines. Alternate coordinate spaces e.g. ecliptc, galactic or supergalactic are also possible. Full support for zoom and rotation with mouse or gestures.
Since it uses D3.js and HTML5 canvas, it needs a modern browser with canvas support, so any recent flavor of Chrome/Firefox/Safari/Opera or IE 9 and above should suffice. Check out the demo at <a href="http://armchairastronautics.blogspot.com/p/skymap.html">armchairastronautics.blogspot.com</a> or clone/download it for local usage, which works with Chrome if it is started with command line parameter `--allow-file-access-from-files` to load local json files. Or use a local web server environment, quite easy to do with node.js.
__Demos__:
[Simple map](https://ofrohn.github.io/celestial-demo/map.html) with editable configuration
[Interactive form](https://ofrohn.github.io/celestial-demo/viewer.html) map viewer with all config options
[Wall map](https://ofrohn.github.io/celestial-demo/wallmap.html) for printing
[Setting time/location](https://ofrohn.github.io/celestial-demo/location.html) and see the current sky
[Animated planets](https://ofrohn.github.io/celestial-demo/planets-animation.html) moving about the ecliptic
[Starry sky](https://ofrohn.github.io/celestial-demo/sky.html) just the stars
[Alternative Stars](https://ofrohn.github.io/celestial-demo/altstars.html) different way to display stars
[Summer triangle](https://ofrohn.github.io/celestial-demo/triangle.html) adding data
[Supernova remnants](https://ofrohn.github.io/celestial-demo/snr.html) adding point data
[Traditional Chinese constellation](https://ofrohn.github.io/celestial-demo/chinese.html) a different culture altogether
\([Source files on github](./demo/)\)
__Some more examples__:
[Embedded interactive form](https://armchairastronautics.blogspot.com/p/skymap.html)
[Spinning sky globe](https://armchairastronautics.blogspot.com/2016/04/interactive-skymap-version-05.html)
[The Milky Way halo, globular clusters & satellite galaxies](https://armchairastronautics.blogspot.com/p/milky-way-halo.html)
[The Local Group of galaxies](https://armchairastronautics.blogspot.com/p/local-group.html)
[Asterisms with locations & time selection](https://armchairastronautics.blogspot.com/p/asterisms.html)
[Asterisms with zoom & pan](https://armchairastronautics.blogspot.com/2016/05/asterisms-interactive-and-with.html)
[Zoom & pan animations](https://armchairastronautics.blogspot.com/2016/06/and-here-is-d3-celestial-057-with.html)
[A different kind of Messier marathon](https://armchairastronautics.blogspot.com/2016/07/a-different-kind-of-messier-marathon.html)
[Show coordinates, DSO colors, Download button](https://armchairastronautics.blogspot.com/2019/08/d3-celestial-showboating_25.html)
[Geolocator gadget part I: Geolocator globe](https://armchairastronautics.blogspot.com/2019/11/d3-celestial-geolocator.html) - [Part II: Daylight sky](https://armchairastronautics.blogspot.com/2019/12/d3-celestial-sky-color.html) - [Part III: Geomarker](https://armchairastronautics.blogspot.com/2019/12/d3-celestial-geomarker.html) - [Part IV: Night sky](http://armchairastronautics.blogspot.com/2020/01/d3-celestial-gelolocator-night-sky.html)
### Usage
* On your HTML add a div with some id, e.g.: `<div id="celestial-map"></div>`.
* Optionally add a div with the id "celestial-form" if you are going to use some of the built-in forms: `<div id="celestial-form"></div>`.
* Include the d3-celestial script, available as `celestial.js` or `celestial.min.js`.
* Include the necessary d3 scripts: `d3.min.js` and `d3.geo.projection.min.js`. Available on the `lib` subfolder in this repository or from the official d3.js server `http://d3js.org/`.
* On your script display the map with `Celestial.display(config)`. Remember to indicate the id of the div where the map will be shown. Check and edit the following default configuration file.
```js
var config = {
width: 0, // Default width, 0 = full parent element width;
// height is determined by projection
projection: "aitoff", // Map projection used: see below
projectionRatio: null, // Optional override for default projection ratio
transform: "equatorial", // Coordinate transformation: equatorial (default),
// ecliptic, galactic, supergalactic
center: null, // Initial center coordinates in set transform
// [longitude, latitude, orientation] all in degrees
// null = default center [0,0,0]
orientationfixed: true, // Keep orientation angle the same as center[2]
geopos: null, // optional initial geographic position [lat,lon] in degrees,
// overrides center
follow: "zenith", // on which coordinates to center the map, default: zenith, if location enabled,
// otherwise center
zoomlevel: null, // initial zoom level 0...zoomextend; 0|null = default, 1 = 100%, 0 < x <= zoomextend
zoomextend: 10, // maximum zoom level
adaptable: true, // Sizes are increased with higher zoom-levels
interactive: true, // Enable zooming and rotation with mousewheel and dragging
form: true, // Display form for interactive settings. Needs a div with
// id="celestial-form", created automatically if not present
location: false, // Display location settings. Deprecated, use formFields below
formFields: {"location": true, // Set visiblity for each group of fields with the respective id
"general": true,
"stars": true,
"dsos": true,
"constellations": true,
"lines": true,
"other": true,
"download": false},
advanced: true, // Display fewer form fields if false
daterange: [], // Calender date range; null: displaydate-+10; [n<100]: displaydate-+n; [yr]: yr-+10;
// [yr, n<100]: [yr-n, yr+n]; [yr0, yr1]
controls: true, // Display zoom controls
lang: "", // Global language override for names, any name setting that has the chosen language available
// Default: desig or empty string for designations, other languages as used anywhere else
culture: "", // Source of constellations and star names, default "iau", other: "cn" Traditional Chinese
container: "map", // ID of parent element, e.g. div, null = html-body
datapath: "data/", // Path/URL to data files, empty = subfolder 'data'
stars: {
show: true, // Show stars
limit: 6, // Show only stars brighter than limit magnitude
colors: true, // Show stars in spectral colors, if not use default color
style: { fill: "#ffffff", opacity: 1 }, // Default style for stars
designation: true, // Show star names (Bayer, Flamsteed, Variable star, Gliese or designation,
// i.e. whichever of the previous applies first); may vary with culture setting
designationType: "desig", // Which kind of name is displayed as designation (fieldname in starnames.json)
designationStyle: { fill: "#ddddbb", font: "11px 'Palatino Linotype', Georgia, Times, 'Times Roman', serif", align: "left", baseline: "top" },
designationLimit: 2.5, // Show only names for stars brighter than nameLimit
propername: false, // Show proper name (if present)
propernameType: "name", // Languge for proper name, default IAU name; may vary with culture setting
// (see list below of languages codes available for stars)
propernameStyle: { fill: "#ddddbb", font: "13px 'Palatino Linotype', Georgia, Times, 'Times Roman', serif", align: "right", baseline: "bottom" },
propernameLimit: 1.5, // Show proper names for stars brighter than propernameLimit
size: 7, // Maximum size (radius) of star circle in pixels
exponent: -0.28, // Scale exponent for star size, larger = more linear
data: 'stars.6.json' // Data source for stellar data,
// number indicates limit magnitude
},
dsos: {
show: true, // Show Deep Space Objects
limit: 6, // Show only DSOs brighter than limit magnitude
colors: true, // // Show DSOs in symbol colors if true, use style setting below if false
style: { fill: "#cccccc", stroke: "#cccccc", width: 2, opacity: 1 }, // Default style for dsos
names: true, // Show DSO names
namesType: "name", // Type of DSO ('desig' or language) name shown
// (see list below for languages codes available for dsos)
nameStyle: { fill: "#cccccc", font: "11px Helvetica, Arial, serif",
align: "left", baseline: "top" }, // Style for DSO names
nameLimit: 6, // Show only names for DSOs brighter than namelimit
size: null, // Optional seperate scale size for DSOs, null = stars.size
exponent: 1.4, // Scale exponent for DSO size, larger = more non-linear
data: 'dsos.bright.json', // Data source for DSOs,
// opt. number indicates limit magnitude
symbols: { //DSO symbol styles, 'stroke'-parameter present = outline
gg: {shape: "circle", fill: "#ff0000"}, // Galaxy cluster
g: {shape: "ellipse", fill: "#ff0000"}, // Generic galaxy
s: {shape: "ellipse", fill: "#ff0000"}, // Spiral galaxy
s0: {shape: "ellipse", fill: "#ff0000"}, // Lenticular galaxy
sd: {shape: "ellipse", fill: "#ff0000"}, // Dwarf galaxy
e: {shape: "ellipse", fill: "#ff0000"}, // Elliptical galaxy
i: {shape: "ellipse", fill: "#ff0000"}, // Irregular galaxy
oc: {shape: "circle", fill: "#ffcc00",
stroke: "#ffcc00", width: 1.5}, // Open cluster
gc: {shape: "circle", fill: "#ff9900"}, // Globular cluster
en: {shape: "square", fill: "#ff00cc"}, // Emission nebula
bn: {shape: "square", fill: "#ff00cc",
stroke: "#ff00cc", width: 2}, // Generic bright nebula
sfr:{shape: "square", fill: "#cc00ff",
stroke: "#cc00ff", width: 2}, // Star forming region
rn: {shape: "square", fill: "#00ooff"}, // Reflection nebula
pn: {shape: "diamond", fill: "#00cccc"}, // Planetary nebula
snr:{shape: "diamond", fill: "#ff00cc"}, // Supernova remnant
dn: {shape: "square", fill: "#999999",
stroke: "#999999", width: 2}, // Dark nebula grey
pos:{shape: "marker", fill: "#cccccc",
stroke: "#cccccc", width: 1.5} // Generic marker
}
},
planets: { //Show planet locations, if date-time is set
show: false,
// List of all objects to show
which: ["sol", "mer", "ven", "ter", "lun", "mar", "jup", "sat", "ura", "nep"],
// Font styles for planetary symbols
symbols: { // Character and color for each symbol in 'which' above (simple circle: \u25cf), optional size override for Sun & Moon
"sol": {symbol: "\u2609", letter:"Su", fill: "#ffff00", size:""},
"mer": {symbol: "\u263f", letter:"Me", fill: "#cccccc"},
"ven": {symbol: "\u2640", letter:"V", fill: "#eeeecc"},
"ter": {symbol: "\u2295", letter:"T", fill: "#00ccff"},
"lun": {symbol: "\u25cf", letter:"L", fill: "#ffffff", size:""}, // overridden by generated crecent, except letter & size
"mar": {symbol: "\u2642", letter:"Ma", fill: "#ff6600"},
"cer": {symbol: "\u26b3", letter:"C", fill: "#cccccc"},
"ves": {symbol: "\u26b6", letter:"Ma", fill: "#cccccc"},
"jup": {symbol: "\u2643", letter:"J", fill: "#ffaa33"},
"sat": {symbol: "\u2644", letter:"Sa", fill: "#ffdd66"},
"ura": {symbol: "\u2645", letter:"U", fill: "#66ccff"},
"nep": {symbol: "\u2646", letter:"N", fill: "#6666ff"},
"plu": {symbol: "\u2647", letter:"P", fill: "#aaaaaa"},
"eri": {symbol: "\u26aa", letter:"E", fill: "#eeeeee"}
},
symbolStyle: { fill: "#00ccff", font: "bold 17px 'Lucida Sans Unicode', Consolas, sans-serif",
align: "center", baseline: "middle" },
symbolType: "symbol", // Type of planet symbol: 'symbol' graphic planet sign, 'disk' filled circle scaled by magnitude
// 'letter': 1 or 2 letters S Me V L Ma J S U N
names: false, // Show name in nameType language next to symbol
nameStyle: { fill: "#00ccff", font: "14px 'Lucida Sans Unicode', Consolas, sans-serif", align: "right", baseline: "top" },
namesType: "desig" // Language of planet name (see list below of language codes available for planets),
// or desig = 3-letter designation
},
constellations: {
names: true, // Show constellation names
namesType: "iau", // Type of name Latin (iau, default), 3 letter designation (desig) or other language (see list below)
nameStyle: { fill:"#cccc99", align: "center", baseline: "middle",
font: ["14px Helvetica, Arial, sans-serif", // Style for constellations
"12px Helvetica, Arial, sans-serif", // Different fonts for diff.
"11px Helvetica, Arial, sans-serif"]},// ranked constellations
lines: true, // Show constellation lines, style below
lineStyle: { stroke: "#cccccc", width: 1, opacity: 0.6 },
bounds: false, // Show constellation boundaries, style below
boundStyle: { stroke: "#cccc00", width: 0.5, opacity: 0.8, dash: [2, 4] }
},
mw: {
show: true, // Show Milky Way as filled multi-polygon outlines
style: { fill: "#ffffff", opacity: 0.15 } // Style for MW layers
},
lines: { // Display & styles for graticule & some planes
graticule: { show: true, stroke: "#cccccc", width: 0.6, opacity: 0.8,
// grid values: "outline", "center", or [lat,...] specific position
lon: {pos: [""], fill: "#eee", font: "10px Helvetica, Arial, sans-serif"},
// grid values: "outline", "center", or [lon,...] specific position
lat: {pos: [""], fill: "#eee", font: "10px Helvetica, Arial, sans-serif"}},
equatorial: { show: true, stroke: "#aaaaaa", width: 1.3, opacity: 0.7 },
ecliptic: { show: true, stroke: "#66cc66", width: 1.3, opacity: 0.7 },
galactic: { show: false, stroke: "#cc6666", width: 1.3, opacity: 0.7 },
supergalactic: { show: false, stroke: "#cc66cc", width: 1.3, opacity: 0.7 }
},
background: { // Background style
fill: "#000000", // Area fill
opacity: 1,
stroke: "#000000", // Outline
width: 1.5
},
horizon: { //Show horizon marker, if location is set and map projection is all-sky
show: false,
stroke: "#cccccc", // Line
width: 1.0,
fill: "#000000", // Area below horizon
opacity: 0.5
},
daylight: { //Show day sky as a gradient, if location is set and map projection is hemispheric
show: false
}
};
// Display map with the configuration above or any subset thereof
Celestial.display(config);
```
__Supported projections:__ Airy, Aitoff, Armadillo, August, Azimuthal Equal Area, Azimuthal Equidistant, Baker, Berghaus, Boggs, Bonne, Bromley, Cassini, Collignon, Craig, Craster, Cylindrical Equal Area, Cylindrical Stereographic, Eckert 1, Eckert 2, Eckert 3, Eckert 4, Eckert 5, Eckert 6, Eisenlohr, Equirectangular, Fahey, Foucaut, Ginzburg 4, Ginzburg 5, Ginzburg 6, Ginzburg 8, Ginzburg 9, Hammer, Hatano, HEALPix, Hill, Homolosine, Kavrayskiy 7, Lagrange, l'Arrivee, Laskowski, Loximuthal, Mercator, Miller, Mollweide, Flat Polar Parabolic, Flat Polar Quartic, Flat Polar Sinusoidal, Natural Earth, Nell Hammer, Orthographic, Patterson, Polyconic, Rectangular Polyconic, Robinson, Sinusoidal, Stereographic, Times, 2 Point Equidistant, van der Grinten, van der Grinten 2, van der Grinten 3, van der Grinten 4, Wagner 4, Wagner 6, Wagner 7, Wiechel and Winkel Tripel. Most of these need the extension [d3.geo.projections](https://github.com/d3/d3-geo-projection/)
__Supported languages for constellation, star and planet name display:__ (name) Official IAU name, (desig) 3-Letter-Designation, (la) Latin, (en) English, (ar) Arabic, (zh) Chinese, (cz) Czech, (ee) Estonian, (fi) Finnish, (fr) French, (de) German, (el) Greek, (he) Hebrew, (it) Italian, (ja) Japanese, (ko) Korean, (hi) Hindi, (fa) Persian, (ru) Russian, (es) Spanish, (tr) Turkish
__Style settings__
`fill`: fill color [(css color value)](https://developer.mozilla.org/en-US/docs/Web/CSS/color)
`opacity`: opacity (number 0..1)
_Line styles_
`stroke`: outline color [(css color value)](https://developer.mozilla.org/en-US/docs/Web/CSS/color)
`width`: line width in pixels (number 0..)
`dash`: line dash ([line length, gap length])
_Text styles_
`font`: well, the font [(css font property)](https://developer.mozilla.org/en-US/docs/Web/CSS/font)
`align`: horizontal align (left|center|right|start|end)
`baseline`: vertical align (alphabetic|top|hanging|middle|ideographic|bottom)
_Symbol style_
`shape`: symbol shape (circle|square|diamond|ellipse|marker or whatever else is defined in canvas.js)
`symbol`: unicode charcter to represent solar system object.
### Getting Info
__Exposed functions & objects__
* `Celestial.metrics()`
Return object literal with current map dimensions in pixels
{width, height, margin, scale}
### Adding Data
__Exposed functions & objects__
* `Celestial.add({file:string, type:json|raw, callback:function, redraw:function, save: function)`
Add data in json-format (json) or directly (raw) to the display
The redraw function is added to the internal call stack of the main display routine
_file_: complete url/path to json data file (type:json)
_type_: type of data being added
_callback_: callback function to call when json is loaded (json)
or to directly add elements to the path (raw)
_redraw_: for interactive display, callback when view changes (optional)
_save_: for display svg-style, callback when saving as svg (optional)
* `Celestial.clear()`
Deletes all previously added functions from the display call stack
* `Celestial.getData(geojson, transform)`
Function to convert geojson coordinates to transformation
(equatorial, ecliptic, galactic, supergalactic)
Returns geojson-object with transformed coordinates
* `Celestial.getPoint(coordinates, transform)`
Function to convert a single coordinate to transformation
(equatorial, ecliptic, galactic, supergalactic)
Returns transformed coordinates
* `Celestial.getPlanet(id, date)`
Function to get solar system object specified with id
(available ids in config.planets.which array)
Returns planet object with coordinates at specified date
* `Celestial.container`
The object to add data to in the callback. See D3.js documentation
* `Celestial.context`
The HTML5-canvas context object to draw on in the callback. Also see D3.js documentation
* `Celestial.map`
The d3.geo.path object to apply projection to data. Also see D3.js documentation
* `Celestial.mapProjection`
The projection object for access to its properties and functions. Also D3.js documentation
* `Celestial.clip(coordinates)`
Function to check if the object is visible, and set its visiblility
_coordinates_: object coordinates in radians, normally supplied by D3 as geometry.coordinates array
* `Celestial.setStyle(<style object>)`
* `Celestial.setTextStyle(<style object>)`
Set the canvas styles as documented above under __style settings__. Seperate functions for graphic/text
_<style object>_: object literal listing all styles to set
* `Celestial.Canvas.symbol()`
Draw symbol shapes directly on canvas context: circle, square, diamond, triangle, ellipse, marker,
stroke-circle, cross-circle
### Adding Behaviour
* `Celestial.addCallback(func)`
Add a callback function that is executed every time the map is redrawn.
func: function that is execured in the client context
### Manipulating the Map
__Exposed functions__
* `Celestial.rotate({center:[long,lat,orient]})`
Turn the map to the given _center_ coordinates, without parameter returns the current center
* `Celestial.zoomBy(factor)`
Zoom the map by the given _factor_ - < 1 zooms out, > 1 zooms in, without parameter returns the
current zoom level
* `Celestial.apply(config)`
Apply configuration changes without reloading the complete map. Any parameter of the above
_config_-object can be set except width, projection, transform, and \*.data, which need a reload
and interactive, form, controls, container, which control page structure & behaviour and should
only be set on the initial load.
* `Celestial.resize({width:px|0|null}|number)`
Change the overall size of the map, canvas object needs a complete reload
Optional {_width_: number} or _number_: new size in pixels, or 0 = full parent width
* `Celestial.redraw()`
Just redraw the whole map.
* `Celestial.reload(config)`
Load all the data and redraw the whole map.
Optional _config_: change any configuration parameter before reloading
* `Celestial.reproject({projection:<see above>})`
Change the map projection.
_projection_: new projection to set
* `Celestial.date(<date object>, timezone)`
Change the set date, return current date w/o parameter.
_date_: javascript date-object
_timezone_: offset from UTC in minutes (optional)
* `Celestial.location([lat, lon])`
Change the current geolocation and set the time zone automatically,
called w/o parameter returns current location
_location_: [latitude, longitude] array in degrees
* `Celestial.skyview({date:<date object>, location:[lat, lon], timezone: offset})`
Show the current celestial view for one specific date and/or location,
independent of form fields, all parameters are optional
if location and no time zone is given, sets time zone automatically
called w/o parameter returns {date, location, timezone} in same format.
_date_: javascript date-object
_location_: [latitude, longitude] array in degrees
_timezone_: offset from UTC in minutes
* `Celestial.showConstellation(id)`
Zoom in and focus on the constellaion given by id.
id: string with valid IAU 3-letter constellation identifier, case-insensitive
### Animations
__Exposed functions__
* `Celestial.animate(anims, dorepeat)`
Set the anmation sequence and start it.
_anims_: sequence data (see below)
_dorepeat_: repeat sequence in endless loop
* `Celestial.stop(wipe)`
Stop the animation after the current step finishes.
_wipe_: if true, delete the list of animation steps as well
* `Celestial.go(index)`
Continue the animation, if animation steps set.
_index_: if given, continue at step #index in the anims arrray,
if not, continue where the animation was stopped
__Animation sequence format:__
[
{_param_: Animated parameter projection|center|zoom
_value_: Adequate value for each parameter
_duration_: in milliseconds, 0 = exact length of transition
_callback_: optional callback function called at the end of the transition
}, ...]
### HowTo
__1. Add your own data__
First of all, whatever you add needs to be valid geoJSON. The various types of objects are described in the readme of the [data folder](./data/). This can be a separate file or a JSON object filled at runtime or defined inline. Like so:
```js
var jsonLine = {
"type":"FeatureCollection",
// this is an array, add as many objects as you want
"features":[
{"type":"Feature",
"id":"SummerTriangle",
"properties": {
// Name
"n":"<NAME>",
// Location of name text on the map
"loc": [-67.5, 52]
}, "geometry":{
// the line object as an array of point coordinates,
// always as [ra -180..180 degrees, dec -90..90 degrees]
"type":"MultiLineString",
"coordinates":[[
[-80.7653, 38.7837],
[-62.3042, 8.8683],
[-49.642, 45.2803],
[-80.7653, 38.7837]
]]
}
}
]
};
```
As you can see, this defines the Summer Triangle asterism, consisting of the bright stars Vega (Alpha Lyr), Deneb (Alpha Cyg) and Altair (Alpha Aql).
*Note:* Since astronomical data is usually given in right ascension from 0 to 24 h and the geoJSON-format used in D3 expects positions in degrees from -180 to 180 deg, you may need this function to convert your data first:
```js
function hour2degree(ra) {
return ra > 12 ? (ra - 24) * 15 : ra * 15;
}
```
You also need to define how the triangle is going to look like with some styles (see definitions above). The parameters and values usually have the same formats as SVG- or CSS-data:
```js
var lineStyle = {
stroke: "#f00",
fill: "rgba(255, 204, 204, 0.4)",
width: 3
};
var textStyle = {
fill: "#f00",
font: "bold 15px Helvetica, Arial, sans-serif",
align: "center",
baseline: "bottom"
};
```
Now we can get to work, with the function
`Celestial.add({file:string, type:json|raw, callback:function, redraw:function)`
The file argument is optional for providing an external geoJSON file; since we already defined our data, we don't need it. Type is 'json' for JSON-Formatted data. That leaves two function definitions, the first one gets called on loading, this is where we add our data to the d3-celestial data container, and redraw is called on every redraw event for the map, this is where you define how to display the added object(s).
```js
callback: function(error, json) {
if (error) return console.warn(error);
// Load the geoJSON file and transform to correct coordinate system, if necessary
var asterism = Celestial.getData(jsonLine, config.transform);
// Add to celestial objects container in d3
Celestial.container.selectAll(".asterisms")
.data(asterism.features)
.enter().append("path")
.attr("class", "ast");
// Trigger redraw to display changes
Celestial.redraw();
}
```
The callback funtion is pretty straight forward: Load the data with Celestial.getData, add to Celestial.container in the usual d3 manner, and redraw. It also provides a json parameter that contains the parsed JSON if a file property is given, but we already have defined jsonLine above, so we use that.
```js
redraw: function() {
// Select the added objects by class name as given previously
Celestial.container.selectAll(".ast").each(function(d) {
// Set line styles
Celestial.setStyle(lineStyle);
// Project objects on map
Celestial.map(d);
// draw on canvas
Celestial.context.fill();
Celestial.context.stroke();
// If point is visible (this doesn't work automatically for points)
if (Celestial.clip(d.properties.loc)) {
// get point coordinates
pt = Celestial.mapProjection(d.properties.loc);
// Set text styles
Celestial.setTextStyle(textStyle);
// and draw text on canvas
Celestial.context.fillText(d.properties.n, pt[0], pt[1]);
}
})
}
```
And the redraw function with the actual display of the elements, contained in a d3.selectAll call on the previously set class property of the added objects. Celestial.setStyle applies the predefined canvas styles, Celestial.map projects each line on the map. However, that doesn't work for points, so that is done manually with Celestial.clip (true if point is currently visible) and Celestial.mapProjection. and the rest are standard canvas fill and stroke operations. The beginPath and closePath commands are done automatically.
```js
Celestial.display();
```
Finally, the whole map is displayed. The complete sample code is in the file [triangle.html](demo/triangle.html) in the demo folder
__2. Add point sources__
First we have to define the objects as valid geoJSON data again, as described in the readme of the [data folder](./data/). Since we're dealing with point sources, the definition is quite simple, the geometry only needs single points. If distinct point sizes are desired, a size criterion in the properties section is required, like the magnitude or extension of each object, and also a name if you want to label the objects on the map. This example uses supernova remnants filtered from the main deep space objects data file that comes with d3-celestial, but you can define your own data as below:
```js
var jsonSN = {
"type":"FeatureCollection",
// this is an array, add as many objects as you want
"features":[
{"type":"Feature",
"id":"SomeDesignator",
"properties": {
// Name
"name":"<NAME>",
// magnitude, dimension in arcseconds or any other size criterion
"mag": 10,
"dim": 30
}, "geometry":{
// the location of the object as a [ra, dec] array in degrees [-180..180, -90..90]
"type":"Point",
"coordinates": [-80.7653, 38.7837]
}
}
]};
```
Next we define the appearance of the objects and labels as they will appear on the map. The values are equivalent to CSS-formats. Fill and stroke colors are only necessary if the objects should appear solid (fill) or as an outline (stroke), or an outline with a semitransparent filling as below. Width gives the line width for outlines.
```js
var pointStyle = {
stroke: "#f0f",
width: 3,
fill: "rgba(255, 204, 255, 0.4)"
};
var textStyle = {
fill:"#f0f",
font: "bold 15px Helvetica, Arial, sans-serif",
align: "left",
baseline: "bottom"
};
```
Now we are ready to add the functions that do the real work of putting the data on the map.
```js
Celestial.add({file:string, type:json|raw, callback:function, redraw:function)
```
The file argument is optional for providing an external geoJSON file; since we already defined our data, we don't need it. Type is 'line', that leaves two function definitions: the first one is called at loading, this is where we add our data to the d3-celestial data container, while the second function 'redraw' is called at every redraw event for the map. So here you need to define how to display the added object(s). Here are two different possibilities to add data to the D3 data container. Either add the data defined as a JSON-Object in-page, as below with the jsonSN object we defined before.
```js
callback: function(error, json) {
if (error) return console.warn(error);
// Load the geoJSON file and transform to correct coordinate system, if necessary
var dsn = Celestial.getData(jsonSN, config.transform);
// Add to celestial objects container in d3
Celestial.container.selectAll(".snrs")
.data(asterism.features)
.enter().append("path")
.attr("class", "snr");
// Trigger redraw to display changes
Celestial.redraw();
}
```
Or add data from an external file with optional filtering, as shown below. In this case the file parameter of the Celsestial.add() function needs to give a valid url to the data file, while the filter function returns true for every object that meets the intended criteria.
```js
callback: function(error, json) {
if (error) return console.warn(error);
// Load the geoJSON file and transform to correct coordinate system, if necessary
var dsos = Celestial.getData(json, config.transform);
// Filter SNRs and add to celestial objects container in d3
Celestial.container.selectAll(".snrs")
.data(dsos.features.filter(function(d) {
return d.properties.type === 'snr'
}))
.enter().append("path")
.attr("class", "snr");
// Trigger redraw to display changes
Celestial.redraw();
}
```
However you add the data, as long as they receive the same class name - 'snr' in the examples above - the display method is the same, as shown below. With point data we can't rely on the map function to do all the work, we need to paint on the canvas step by step. First, check if the point is currently displayed (clip), then get the location (mapProjection), size (whatever scaling formula you like) and styling.
Now we are ready to throw pixels at the canvas: set the styles (fill color, stroke color & width), followed by whatever canvas commands are required to draw the object shape, here a filled circle outline. And then the same for the adjacent object name offset by the previously calculated radius.
```js
redraw: function() {
// Select the added objects by class name as given previously
Celestial.container.selectAll(".snr").each(function(d) {
// If point is visible (this doesn't work automatically for points)
if (Celestial.clip(d.geometry.coordinates)) {
// get point coordinates
var pt = Celestial.mapProjection(d.geometry.coordinates);
// object radius in pixel, could be varable depending on e.g. dimension or magnitude
var r = Math.pow(20 - prop.mag, 0.7); // replace 20 with dimmest magnitude in the data
// draw on canvas
// Set object styles fill color, line color & width etc.
Celestial.setStyle(pointStyle);
// Start the drawing path
Celestial.context.beginPath();
// Thats a circle in html5 canvas
Celestial.context.arc(pt[0], pt[1], r, 0, 2 * Math.PI);
// Finish the drawing path
Celestial.context.closePath();
// Draw a line along the path with the prevoiusly set stroke color and line width
Celestial.context.stroke();
// Fill the object path with the prevoiusly set fill color
Celestial.context.fill();
// Set text styles
Celestial.setTextStyle(textStyle);
// and draw text on canvas
Celestial.context.fillText(d.properties.name, pt[0] + r - 1, pt[1] - r + 1);
}
});
}});
```
Finally, the whole map can be displayed.
```js
Celestial.display();
```
__Bonus: Avoid overlapping labels__
You will note that there is a lot of overlap between distinct labels. Fortunately, d3 already has a solution for this: d3.geom.quadtree, which builds a hiearchical data structure ordered by proximity.
First we set the closest allowed distance between two labels in pixels, get the map dimensions from Celestial.metrics, and create a quadtree object with the extent of those dimensions.
```js
var PROXIMITY_LIMIT = 20,
m = Celestial.metrics(),
quadtree = d3.geom.quadtree().extent([[-1, -1], [m.width + 1, m. height + 1]])([]);
```
After proceeding as above - get the projected map position in pixelspace (pt) and draw the snr symbol - we use the quadtree.find() function to find the nearest neighbor relative to this position, and if it is more distant than our limit above, add it to quadtree and draw the label, otherwise don't.
```js
var nearest = quadtree.find(pt);
if (!nearest || distance(nearest, pt) > PROXIMITY_LIMIT) {
quadtree.add(pt)
// draw the label as above
}
```
This will only draw non-overlapping labels and scales with zoom-level, since it checks in pixel-space and not in coordinate-space.
Now we need just one more thing, the distance function used above, which is the standard Pythagorean square root of the sum of the differences squared function.
```js
// Simple point distance function
function distance(p1, p2) {
var d1 = p2[0] - p1[0],
d2 = p2[1] - p1[1];
return Math.sqrt(d1 * d1 + d2 * d2);
}
```
The complete sample code is in the file [snr.html](demo/snr.html) in the demo folder.
### Files
__GeoJSON data files__
(See format specification in the readme for the [data folder](./data/))
* `stars.6.json` Stars down to 6th magnitude \[1\]
* `stars.8.json` Stars down to 8.5th magnitude \[1\]
* `stars.14.json` Stars down to 14th magnitude (large) \[1\]
* `starnames.json` Star names and designations \[1b\]\[1c\]
* `dsos.6.json` Deep space objects down to 6th magnitude \[2\]
* `dsos.14.json` Deep space objects down to 14th magnitude \[2\]
* `dsos.20.json` Deep space objects down to 20th magnitude \[2\]
* `dsos.bright.json` Some of the brightest showpiece DSOs of my own choosing
* `messier.json` Messier objects \[8\]
* `lg.json` Local group and Milky Way halo galaxies/globiular clusters. My own compilation \[6\]
* `constellations.json` Constellation data \[3\]
* `constellations.bounds.json` Constellation boundaries \[4\]
* `constellations.lines.json` Constellation lines \[3\]
* `asterisms.json` Asterism data \[7\]
* `mw.json` Milky Way outlines in 5 brightness steps \[5\]
* `planets.json` Keplerian Elements for Approximate Positions of the Major Planets \[9\]
__Traditional Chinese Constellations & Stars__
* `constellations.cn.json` Constellation data \[10\]
* `constellations.bounds.cn.json` Constellation boundaries \[10\]
* `constellations.lines.cn.json` Constellation lines \[10\]
* `starnames.cn.json` Star names and designations \[10\]
__Sources__
* \[1\] XHIP: An Extended Hipparcos Compilation; <NAME>., <NAME>. (2012) [VizieR V/137D](http://cdsarc.u-strasbg.fr/viz-bin/Cat?V/137D)
* \[1b\] _Star names & designations:_
HD-DM-GC-HR-HIP-Bayer-Flamsteed Cross Index (Kostjuk, 2002) [VizieR IV/27A](http://cdsarc.u-strasbg.fr/viz-bin/Cat?IV/27A)
FK5-SAO-HD-Common Name Cross Index (Smith 1996) [VizieR IV/22](http://cdsarc.u-strasbg.fr/viz-bin/Cat?IV/22)
General Catalogue of Variable Stars (Samus et.al. 2007-2013) [VizieR B/gcvs](http://cdsarc.u-strasbg.fr/viz-bin/Cat?B/gcvs)
Preliminary Version of the Third Catalogue of Nearby Stars (Gliese+ 1991) [VizieR V/70A](http://cdsarc.u-strasbg.fr/viz-bin/Cat?V/70A)
* \[1c\] [Stellarium skycultures data](https://github.com/Stellarium/stellarium/tree/master/po/stellarium-skycultures) for star name translations
* \[2\] [Saguaro Astronomy Club Database version 8.1](http://www.saguaroastro.org/sac-downloads/)
* \[3\] [IAU Constellation page](http://www.iau.org/public/themes/constellations/), name positions and some line modifications by me, names in other languages from [Wikipedia](https://wiki2.org/en/88_modern_constellations_in_different_languages)
* \[4\] Catalogue of Constellation Boundary Data; <NAME>., <NAME>.K. (1989) [VizieR VI/49](http://vizier.cfa.harvard.edu/viz-bin/Cat?VI/49)
* \[5\] [Milky Way Outline Catalog](http://www.skymap.com/milkyway_cat.htm), <NAME>
* \[6\] Lots of sources, see [blog](http://armchairastronautics.blogspot.com/p/milky-way-halo.html) [pages](http://armchairastronautics.blogspot.com/p/local-group.html) for complete list
* \[7\] [Saguaro Astronomy Club Asterisms](http://saguaroastro.org/sac-downloads/) \(scroll down\)
* \[8\] [Messier Objects with Data](http://messier.seds.org/data.html), H.Frommert/seds.org
* \[9\] [Keplerian Elements for Approximate Positions of the Major Planets](https://ssd.jpl.nasa.gov/?planet_pos)
* \[10\] [Stellarium skycultures data](https://github.com/Stellarium/stellarium/tree/master/skycultures/chinese) for traditional Chinese constellations
All data converted to GeoJSON at J2000 epoch, positions converted from 0...24h right ascension to -180...180 degrees longitude as per GeoJSON requirements, so 0...12h becomes 0...180 degrees, and 12...24h becomes -180...0 degrees.
__Other files__
* `celestial.js` main javascript object
* `celestial.min.js` minified javascript
* `celestial.tar.gz` data, minified script and viewer, all you need for local display
* `LICENSE`
* `readme.md` this file
* `celestial.css` stylesheet
* `lib/d3.*.js` necessary d3 libraries
* `src/*.js` source code for all modules
Thanks to <NAME> and <NAME> for [D3.js](http://d3js.org/) and [d3.geo.projections](https://github.com/d3/d3-geo-projection).
And also thanks to <NAME> for [d3.geo.zoom](http://www.jasondavies.com/maps/rotate/), which saved me some major headaches in figuring out how to rotate/zoom the map.
Released under [BSD License](LICENSE)
<file_sep>/src/location.js
/* global Celestial, settings, horizontal, datetimepicker, config, formats, $, $form, pad, testNumber, isArray, isNumber, isValidDate, showAdvanced, enable, Round, has, hasParent, parentElement */
var geoInfo = null;
function geo(cfg) {
var dtFormat = d3.time.format("%Y-%m-%d %H:%M:%S"),
zenith = [0,0],
geopos = [0,0],
date = new Date(),
localZone = -date.getTimezoneOffset(),
timeZone = localZone,
config = settings.set(cfg),
frm = d3.select(parentElement + " ~ #celestial-form form").insert("div", "div#general").attr("id", "loc");
var dtpick = new datetimepicker(config, function(date, tz) {
$form("datetime").value = dateFormat(date, tz);
timeZone = tz;
go();
});
if (has(config, "geopos") && config.geopos !== null && config.geopos.length === 2) geopos = config.geopos;
var col = frm.append("div").attr("class", "col").attr("id", "location").style("display", "none");
//Latitude & longitude fields
col.append("label").attr("title", "Location coordinates long/lat").attr("for", "lat").html("Location");
col.append("input").attr("type", "number").attr("id", "lat").attr("title", "Latitude").attr("placeholder", "Latitude").attr("max", "90").attr("min", "-90").attr("step", "0.0001").attr("value", geopos[0]).on("change", function () {
if (testNumber(this) === true) go();
});
col.append("span").html("\u00b0");
col.append("input").attr("type", "number").attr("id", "lon").attr("title", "Longitude").attr("placeholder", "Longitude").attr("max", "180").attr("min", "-180").attr("step", "0.0001").attr("value", geopos[1]).on("change", function () {
if (testNumber(this) === true) go();
});
col.append("span").html("\u00b0");
//Here-button if supported
if ("geolocation" in navigator) {
col.append("input").attr("type", "button").attr("value", "Here").attr("id", "here").on("click", here);
}
//Datetime field with dtpicker-button
col.append("label").attr("title", "Local date/time").attr("for", "datetime").html(" Date/time");
col.append("input").attr("type", "button").attr("id", "day-left").attr("title", "One day back").on("click", function () {
date.setDate(date.getDate() - 1);
$form("datetime").value = dateFormat(date, timeZone);
go();
});
col.append("input").attr("type", "text").attr("id", "datetime").attr("title", "Date and time").attr("value", dateFormat(date, timeZone))
.on("click", showpick, true).on("input", function () {
this.value = dateFormat(date, timeZone);
if (!dtpick.isVisible()) showpick();
});
col.append("div").attr("id", "datepick").on("click", showpick);
col.append("input").attr("type", "button").attr("id", "day-right").attr("title", "One day forward").on("click", function () {
date.setDate(date.getDate() + 1);
$form("datetime").value = dateFormat(date, timeZone);
go();
});
//Now -button sets current time & date of device
col.append("input").attr("type", "button").attr("value", "Now").attr("id", "now").on("click", now);
//Horizon marker
col.append("br");
col.append("label").attr("title", "Show horizon marker").attr("for", "horizon-show").html(" Horizon marker");
col.append("input").attr("type", "checkbox").attr("id", "horizon-show").property("checked", config.horizon.show).on("change", apply);
//Daylight
col.append("label").attr("title", "Show daylight").attr("for", "daylight-show").html("Daylight sky");
col.append("input").attr("type", "checkbox").attr("id", "daylight-show").property("checked", config.daylight.show).on("change", apply);col.append("br");
//Show planets
col.append("label").attr("title", "Show solar system objects").attr("for", "planets-show").html(" Planets, Sun & Moon");
col.append("input").attr("type", "checkbox").attr("id", "planets-show").property("checked", config.planets.show).on("change", apply);
//Planet names
var names = formats.planets[config.culture] || formats.planets.iau;
for (var fld in names) {
if (!has(names, fld)) continue;
var keys = Object.keys(names[fld]);
if (keys.length > 1) {
//Select List
var txt = (fld === "symbol") ? "as" : "with";
col.append("label").attr("for", "planets-" + fld + "Type").html(txt);
var selected = 0;
col.append("label").attr("title", "Type of planet name").attr("for", "planets-" + fld + "Type").attr("class", "advanced").html("");
var sel = col.append("select").attr("id", "planets-" + fld + "Type").on("change", apply);
var list = keys.map(function (key, i) {
if (key === config.planets[fld + "Type"]) selected = i;
return {o:key, n:names[fld][key]};
});
sel.selectAll("option").data(list).enter().append('option')
.attr("value", function (d) { return d.o; })
.text(function (d) { return d.n; });
sel.property("selectedIndex", selected);
if (fld === "names") {
sel.attr("class", "advanced");
col.append("label").attr("for", "planets-" + fld).html("names");
col.append("input").attr("type", "checkbox").attr("id", "planets-" + fld).property("checked", config.planets[fld]).on("change", apply);
}
}
}
enable($form("planets-show"));
showAdvanced(config.advanced);
d3.select(document).on("mousedown", function () {
if (!hasParent(d3.event.target, "celestial-date") && dtpick.isVisible()) dtpick.hide();
});
function now() {
date.setTime(Date.now());
$form("datetime").value = dateFormat(date, timeZone);
go();
}
function here() {
navigator.geolocation.getCurrentPosition( function(pos) {
geopos = [Round(pos.coords.latitude, 4), Round(pos.coords.longitude, 4)];
$form("lat").value = geopos[0];
$form("lon").value = geopos[1];
go();
});
}
function showpick() {
dtpick.show(date, timeZone);
}
function dateFormat(dt, tz) {
var tzs;
if (!tz || tz === "0") tzs = " ยฑ0000";
else {
var h = Math.floor(Math.abs(tz) / 60),
m = Math.abs(tz) - (h * 60),
s = tz > 0 ? " +" : " โ";
tzs = s + pad(h) + pad(m);
}
return dtFormat(dt) + tzs;
}
function isValidLocation(loc) {
//[lat, lon] expected
if (!loc || !isArray(loc) || loc.length < 2) return false;
if (!isNumber(loc[0]) || loc[0] < -90 || loc[0] > 90) return false;
if (!isNumber(loc[1]) || loc[1] < -180 || loc[1] > 180) return false;
return true;
}
function isValidTimezone(tz) {
if (tz === undefined || tz === null) return false;
if (!isNumber(tz) && Math.abs(tz) > 840) return false;
return true;
}
function apply() {
Object.assign(config, settings.set());
config.horizon.show = !!$form("horizon-show").checked;
config.daylight.show = !!$form("daylight-show").checked;
config.planets.show = !!$form("planets-show").checked;
config.planets.names = !!$form("planets-names").checked;
config.planets.namesType = $form("planets-namesType").value;
config.planets.symbolType = $form("planets-symbolType").value;
enable($form("planets-show"));
Celestial.apply(config);
}
function go() {
var lon = parseFloat($form("lon").value),
lat = parseFloat($form("lat").value),
tz;
//Get current configuration
Object.assign(config, settings.set());
date = dtFormat.parse($form("datetime").value.slice(0,-6));
//Celestial.apply(config);
if (!isNaN(lon) && !isNaN(lat)) {
if (lat !== geopos[0] || lon !== geopos[1]) {
geopos = [lat, lon];
setPosition([lat, lon], true);
return;
}
//if (!tz) tz = date.getTimezoneOffset();
$form("datetime").value = dateFormat(date, timeZone);
var dtc = new Date(date.valueOf() - (timeZone - localZone) * 60000);
zenith = Celestial.getPoint(horizontal.inverse(dtc, [90, 0], geopos), config.transform);
zenith[2] = 0;
if (config.follow === "zenith") {
Celestial.rotate({center:zenith});
} else {
Celestial.redraw();
}
}
}
function setPosition(p, settime) {
if (!p || !has(config, "settimezone") || config.settimezone === false) return;
var timestamp = Math.floor(date.getTime() / 1000),
protocol = window && window.location.protocol === "https:" ? "https" : "http",
url = protocol + "://api.timezonedb.com/v2.1/get-time-zone?key=" + config.timezoneid + "&format=json&by=position" +
"&lat=" + p[0] + "&lng=" + p[1] + "&time=" + timestamp;
// oldZone = timeZone;
d3.json(url, function(error, json) {
if (error) return console.warn(error);
if (json.status === "FAILED") {
// Location at sea inferred from longitude
timeZone = Math.round(p[1] / 15) * 60;
geoInfo = {
gmtOffset: timeZone * 60,
message: "Sea locatation inferred",
timestamp: timestamp
};
} else {
timeZone = json.gmtOffset / 60;
geoInfo = json;
}
//if (settime) {
//date.setTime(timestamp * 1000); // - (timeZone - oldZone) * 60000);
//console.log(date.toUTCString());
//}
$form("datetime").value = dateFormat(date, timeZone);
go();
});
}
Celestial.dateFormat = dateFormat;
Celestial.date = function (dt, tz) {
if (!dt) return date;
if (isValidTimezone(tz)) timeZone = tz;
Object.assign(config, settings.set());
if (dtpick.isVisible()) dtpick.hide();
date.setTime(dt.valueOf());
$form("datetime").value = dateFormat(dt, timeZone);
go();
};
Celestial.timezone = function (tz) {
if (!tz) return timeZone;
if (isValidTimezone(tz)) timeZone = tz;
Object.assign(config, settings.set());
if (dtpick.isVisible()) dtpick.hide();
$form("datetime").value = dateFormat(date, timeZone);
go();
};
Celestial.position = function () { return geopos; };
Celestial.location = function (loc, tz) {
if (!loc || loc.length < 2) return geopos;
if (isValidLocation(loc)) {
geopos = loc.slice();
$form("lat").value = geopos[0];
$form("lon").value = geopos[1];
if (isValidTimezone(tz)) timeZone = tz;
else setPosition(geopos, true);
}
};
//{"date":dt, "location":loc, "timezone":tz}
Celestial.skyview = function (cfg) {
if (!cfg) return {"date": date, "location": geopos, "timezone": timeZone};
var valid = false;
if (dtpick.isVisible()) dtpick.hide();
if (has(cfg, "timezone") && isValidTimezone(cfg.timezone)) {
timeZone = cfg.timezone;
valid = true;
}
if (has(cfg, "date") && isValidDate(cfg.date)) {
date.setTime(cfg.date.valueOf());
$form("datetime").value = dateFormat(cfg.date, timeZone);
valid = true;
}
if (has(cfg, "location") && isValidLocation(cfg.location)) {
geopos = cfg.location.slice();
$form("lat").value = geopos[0];
$form("lon").value = geopos[1];
if (!has(cfg, "timezone")) {
setPosition(geopos, !has(cfg, "date"));
return;
}
}
//Celestial.updateForm();
if (valid === false) return {"date": date, "location": geopos, "timezone": timeZone};
if (config.follow === "zenith") go();
else Celestial.redraw();
};
Celestial.dtLoc = Celestial.skyview;
Celestial.zenith = function () { return zenith; };
Celestial.nadir = function () {
var b = -zenith[1],
l = zenith[0] + 180;
if (l > 180) l -= 360;
return [l, b-0.001];
};
if (has(config, "formFields") && (config.location === true || config.formFields.location === true)) {
d3.select(parentElement + " ~ #celestial-form").select("#location").style( {"display": "inline-block"} );
}
//only if appropriate
if (isValidLocation(geopos) && (config.location === true || config.formFields.location === true) && config.follow === "zenith")
setTimeout(go, 1000);
}
<file_sep>/src/transform.js
/* global Celestial, poles, eulerAngles */
var ฯ = Math.PI*2,
halfฯ = Math.PI/2,
deg2rad = Math.PI/180;
//Transform equatorial into any coordinates, degrees
function transformDeg(c, euler) {
var res = transform( c.map( function(d) { return d * deg2rad; } ), euler);
return res.map( function(d) { return d / deg2rad; } );
}
//Transform equatorial into any coordinates, radians
function transform(c, euler) {
var x, y, z, ฮฒ, ฮณ, ฮป, ฯ, dฯ, ฯ, ฮธ,
ฮต = 1.0e-5;
if (!euler) return c;
ฮป = c[0]; // celestial longitude 0..2pi
if (ฮป < 0) ฮป += ฯ;
ฯ = c[1]; // celestial latitude -pi/2..pi/2
ฮป -= euler[0]; // celestial longitude - celestial coordinates of the native pole
ฮฒ = euler[1]; // inclination between the poles (colatitude)
ฮณ = euler[2]; // native coordinates of the celestial pole
x = Math.sin(ฯ) * Math.sin(ฮฒ) - Math.cos(ฯ) * Math.cos(ฮฒ) * Math.cos(ฮป);
if (Math.abs(x) < ฮต) {
x = -Math.cos(ฯ + ฮฒ) + Math.cos(ฯ) * Math.cos(ฮฒ) * (1 - Math.cos(ฮป));
}
y = -Math.cos(ฯ) * Math.sin(ฮป);
if (x !== 0 || y !== 0) {
dฯ = Math.atan2(y, x);
} else {
dฯ = ฮป - Math.PI;
}
ฯ = (ฮณ + dฯ);
if (ฯ > Math.PI) ฯ -= ฯ;
if (ฮป % Math.PI === 0) {
ฮธ = ฯ + Math.cos(ฮป) * ฮฒ;
if (ฮธ > halfฯ) ฮธ = Math.PI - ฮธ;
if (ฮธ < -halfฯ) ฮธ = -Math.PI - ฮธ;
} else {
z = Math.sin(ฯ) * Math.cos(ฮฒ) + Math.cos(ฯ) * Math.sin(ฮฒ) * Math.cos(ฮป);
if (Math.abs(z) > 0.99) {
ฮธ = Math.abs(Math.acos(Math.sqrt(x*x+y*y)));
if (z < 0) ฮธ *= -1;
} else {
ฮธ = Math.asin(z);
}
}
return [ฯ, ฮธ];
}
function getAngles(coords) {
if (coords === null || coords.length <= 0) return [0,0,0];
var rot = eulerAngles.equatorial;
if (!coords[2]) coords[2] = 0;
return [rot[0] - coords[0], rot[1] - coords[1], rot[2] + coords[2]];
}
var euler = {
"ecliptic": [-90.0, 23.4393, 90.0],
"inverse ecliptic": [90.0, 23.4393, -90.0],
"galactic": [-167.1405, 62.8717, 122.9319],
"inverse galactic": [122.9319, 62.8717, -167.1405],
"supergalactic": [283.7542, 74.2911, 26.4504],
"inverse supergalactic": [26.4504, 74.2911, 283.7542],
"init": function () {
for (var key in this) {
if (this[key].constructor == Array) {
this[key] = this[key].map( function(val) { return val * deg2rad; } );
}
}
},
"add": function(name, ang) {
if (!ang || !name || ang.length !== 3 || this.hasOwnProperty(name)) return;
this[name] = ang.map( function(val) { return val * deg2rad; } );
return this[name];
}
};
euler.init();
Celestial.euler = function () { return euler; };
<file_sep>/src/get.js
/* global Celestial, Kepler, euler, transformDeg, isArray, isNumber, has, cfg */
//load data and transform coordinates
function getPoint(coords, trans) {
return transformDeg(coords, euler[trans]);
}
function getData(d, trans) {
if (trans === "equatorial") return d;
var leo = euler[trans],
f = d.features;
for (var i=0; i<f.length; i++)
f[i].geometry.coordinates = translate(f[i], leo);
return d;
}
function getPlanets(d) {
var res = [];
for (var key in d) {
if (!has(d, key)) continue;
if (cfg.planets.which.indexOf(key) === -1) continue;
var dat = Kepler().id(key);
if (has(d[key], "parent")) dat.parentBody(d[key].parent);
dat.elements(d[key].elements[0]).params(d[key]);
if (key === "ter")
Celestial.origin = dat;
else res.push(dat);
}
//res.push(Kepler().id("sol"));
//res.push(Kepler().id("lun"));
return res;
}
function getPlanet(id, dt) {
dt = dt || Celestial.date();
if (!Celestial.origin) return;
var o = Celestial.origin(dt).spherical(), res;
Celestial.container.selectAll(".planet").each(function(d) {
if (id === d.id()) {
res = d(dt).equatorial(o);
}
});
return res;
}
function getConstellationList(d) {
var res = {},
f = d.features;
for (var i=0; i<f.length; i++) {
res[f[i].id] = {
center: f[i].properties.display.slice(0,2),
scale: f[i].properties.display[2]
};
}
return res;
}
function getMwbackground(d) {
// geoJson object to darken the mw-outside, prevent greying of whole map in some orientations
var res = {'type': 'FeatureCollection', 'features': [ {'type': 'Feature',
'geometry': { 'type': 'MultiPolygon', 'coordinates' : [] }
}]};
// reverse the polygons, inside -> outside
var l1 = d.features[0].geometry.coordinates[0];
res.features[0].geometry.coordinates[0] = [];
for (var i=0; i<l1.length; i++) {
res.features[0].geometry.coordinates[0][i] = l1[i].slice().reverse();
}
return res;
}
function getTimezones() {
}
function translate(d, leo) {
var res = [];
switch (d.geometry.type) {
case "Point": res = transformDeg(d.geometry.coordinates, leo); break;
case "LineString": res.push(transLine(d.geometry.coordinates, leo)); break;
case "MultiLineString": res = transMultiLine(d.geometry.coordinates, leo); break;
case "Polygon": res.push(transLine(d.geometry.coordinates[0], leo)); break;
case "MultiPolygon": res.push(transMultiLine(d.geometry.coordinates[0], leo)); break;
}
return res;
}
function getGridValues(type, loc) {
var lines = [];
if (!loc) return [];
if (!isArray(loc)) loc = [loc];
//center, outline, values
for (var i=0; i < loc.length; i++) {
switch (loc[i]) {
case "center":
if (type === "lat")
lines = lines.concat(getLine(type, cfg.center[0], "N"));
else
lines = lines.concat(getLine(type, cfg.center[1], "S"));
break;
case "outline":
if (type === "lon") {
lines = lines.concat(getLine(type, cfg.center[1]-89.99, "S"));
lines = lines.concat(getLine(type, cfg.center[1]+89.99, "N"));
} else {
// TODO: hemi
lines = lines.concat(getLine(type, cfg.center[0]-179.99, "E"));
lines = lines.concat(getLine(type, cfg.center[0]+179.99, "W"));
}
break;
default: if (isNumber(loc[i])) {
if (type === "lat")
lines = lines.concat(getLine(type, loc[i], "N"));
else
lines = lines.concat(getLine(type, loc[i], "S"));
break;
}
}
}
//return [{coordinates, value, orientation}, ...]
return jsonGridValues(lines);
}
function jsonGridValues(lines) {
var res = [];
for (var i=0; i < lines.length; i++) {
var f = {type: "Feature", "id":i, properties: {}, geometry:{type:"Point"}};
f.properties.value = lines[i].value;
f.properties.orientation = lines[i].orientation;
f.geometry.coordinates = lines[i].coordinates;
res.push(f);
}
return res;
}
function getLine(type, loc, orient) {
var min, max, step, val, coord,
tp = type,
res = [],
lr = loc;
if (cfg.transform === "equatorial" && tp === "lon") tp = "ra";
if (tp === "ra") {
min = 0; max = 23; step = 1;
} else if (tp === "lon") {
min = 0; max = 350; step = 10;
} else {
min = -80; max = 80; step = 10;
}
for (var i=min; i<=max; i+=step) {
var o = orient;
if (tp === "lat") {
coord = [lr, i];
val = i.toString() + "\u00b0";
if (i < 0) o += "S"; else o += "N";
} else if (tp === "ra") {
coord = [i * 15, lr];
val = i.toString() + "\u02b0";
} else {
coord = [i, lr];
val = i.toString() + "\u00b0";
}
res.push({coordinates: coord, value: val, orientation: o});
}
return res;
}
function transLine(c, leo) {
var line = [];
for (var i=0; i<c.length; i++)
line.push(transformDeg(c[i], leo));
return line;
}
function transMultiLine(c, leo) {
var lines = [];
for (var i=0; i<c.length; i++)
lines.push(transLine(c[i], leo));
return lines;
}
Celestial.getData = getData;
Celestial.getPoint = getPoint;
Celestial.getPlanet = getPlanet;<file_sep>/data/readme.md
# Data Formats
For GeoJSON, all coordinates need to be given in degrees, longitude as [-180...180] deg, latitude as [-90...90] deg
## Stars
`stars.6.json`, `stars.8.json`, `stars.14.json`: the number indicates limit magnitude
```js
{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"id": "", // Hipparcos number
"properties": {
"mag": "", // Apparent magnitude
"bv": "" // b-v color index
},
"geometry": {
"type": "Point",
"coordinates": [lon, lat]
}
}, { } ]
}
```
## Starnames
`starnames.json`: Magnitude independent, all stars with a name/designation other than HIP/HD
```js
{"id": { // Hipparcos number
"name": "", // Proper name
... // and names in 17 further languages (see list in main readme)
"desig": "", // Standard designation, first from list below
"bayer": "", // Bayer
"flam": "", // Flamsteed
"var": "", // Variable star
"gliese": "", // Gliese
"hd": "", // <NAME>
"hip": "" // Hipparcos number again
}, "id": {...}
}
```
##Traditional Chinese star and DSO names
`starnames.cn.json`, `dsonames.cn.json`:
```js
{"id": { // Hipparcos number
"name": "", // Chinese name
"desig": "", // IAU designation
"en": "", // English translation
"pinyin": "" // Pinyin transcription
}, "id": {...}
}
```
## DSOs
`dsos.6.json`, `dsos.14.json`: the number indicates limit magnitude
`dsos.bright.json`: hand selected
`lf.json`: Local group
`messier.json` Messier objects
```js
{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"id": "", // Short designator
"properties": {
"desig": "", // Designator
"type": "", // Object type: gg, g, s, s0, sd, i, e, oc, gc, dn, bn, sfr, rn, en, pn, snr
"morph": "", // Morphology classification depending on type
"mag": "", // Apparent magnitude, 999 if n.a.
"dim": "", // Angular dimensions in arcminutes
"bv": "" // Blue minus visual magnitude color inder (b-v)
},
"geometry": {
"type": "Point",
"coordinates": [lon, lat]
}
}, { } ]
}
```
___Object type:___ _gg_: galaxy cluster, _g_: galaxy, _s_: spiral galaxy, _s0_: lenticular gal., _sd_: dwarf spheroidal gal., _i_: irregular gal., _e_: elliptical gal., _oc_: open cluster, _gc_: globular cluster, _dn_: dark nebula, _bn_: bright nebula, _sfr_: star forming region, _rn_: reflection nebula, _en_: emission nebula, _pn_: planetary nebula, _snr_: supernova remnant
___additional lg.json properties:___
_sub_: Sub group membership: \[MW|M31|N3109|LG\] (Milky Way, Andromeda, NGC 3109, gen. LG)
_pop_: MW populations \[OH|YH|BD\] (Old halo, young halo, bulge & disk), M31 populations \[M31|GP\] (gen. M31, great plane)
_str_: Tidal streams \[Mag|Sgr|CMa|FLS\] (Magellanic Stream, Sagittarius Stream, Canis Major/Monoceros Stream, Fornax-Leo-Sculptor Great Circle)
## DSOnames
`dsonames.json`: Magnitude/dimension independent, all DSOs with a proper name
```js
{"id": { // most common designation (NGC, IC, M, ...)
"name":"", // Proper name (in English)
... // and names in up to 17 further languages (see list in main readme)
}
```
## Constellations
`constellations.json`
```js
{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"id": "", // 3-letter designator
"properties": {
"name": "", // full IAU name
"desig": "", // 3-letter designator again
"gen": "", // genitive for naming stars, not yet used
"rank": "", // 1-3 for differential name display by size/brightness
"en": "", // english name
... // and names in 18 further languages (see list in main readme)
"display": [] // [ra,dec,scale], for single constellation display
},
"geometry": {
"type": "Point",
"coordinates": [lon, lat] // Position of const. name
}
}, { } ]
}
```
## Constellation lines
`constellations.lines.json`, `constellations.lines.cn.json`
```js
{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"id": "", // 3-letter designator of constellation
"geometry": {
"type": "MultiLineString",
"coordinates": [[[lon, lat],[lon, lat],..],[[]lon, lat,[lon, lat],..],..]
}
}, { } ]
}
```
## Constellation boundaries
`constellations.bounds.json`, `constellations.bounds.cn.json`
```js
{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"id": "", // 3-letter designator of constellation
"geometry": {
"type": "Polygon",
"coordinates": [[[lon, lat],[lon, lat],..]]
},
}, { } ]
}
```
##Traditional Chinese constellations
`constellations.cn.json`
```js
{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"id": "", // numerical id
"properties": {
"name": "", // chinese name
"en": "", // english translation
"pinyin": "", // pinyin transcription
"desig": "", // also chinese name, for compatibility
"rank": "", // so far only 1; differential name display by size/brightness
"display": [] // [ra,dec,scale], for single constellation display
},
"geometry": {
"type": "Point",
"coordinates": [lon, lat] // Position of const. name
}
}, { } ]
}
```
## Milky way
`mw.json`
```js
{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"id": "", // ol 1-5
"properties": {},
"geometry": {
"type": "MultiPolygon",
"coordinates":[[[[lon, lat],[lon, lat],..],[[lon, lat],[lon, lat],..],..]]
}
}, { } ]
}
```
## Special Planes
```js
{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"id": "",
"geometry": {
"type": "LineString",
"coordinates": [[lon, lat],[lon, lat]]
}
}, { } ]
}
```
## Asterisms
```js
{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"id": "", // Name without spaces
"properties": {
"n": "", // Proper name
"es": "", // Proper name in spanish
"loc": [lon,lat], // Center location of name string
"p": n // Priority 1..6 (~Average brighness)
// p=6: Guiding line
},
"geometry": {
"type": "MultiLineString",
"coordinates": [[[lon, lat],[lon, lat],..],[[]lon, lat,[lon, lat],..],..]
}
}, { } ]
}
```
## Planets
Not geojson, because positions need to be calculated by date from keplerian elements
All element values in degrees, except a (AU|km) and e (dimensionless)
```js
"id":{ // (usually) 3-letter id
"name": "", // full name
"trajectory": bool, // show trajectory (tbi)
"H": n, // absolute magnitude
"elements":[{
"a": "da": Semimajor axis / change per century (all 'dx' fields)
"e": "de": Eccentricity
"i": "di": Inclination
"L": "dL": or "M": "dM": mean longitude (M*Q) or mean anomaly
"W": "dW": or "w": "dw": longitude of periapsis (w*N) or argument of periapsis
"N": "dn": longitude of the ascending node
"ep":"2000-01-01" epoch, default date
}],
"desig": "", // 3-Letter designation
... // Names in 14 different languages, see list in main readme
}
```
| 39b16692244c20f73bf8a81771e01aad2db76548 | [
"JavaScript",
"Markdown"
] | 11 | JavaScript | ofrohn/d3-celestial | 7e720a3de062059d4c5400a379146a601d9010e0 | 0e3d38ac938baca6912466edf15052193e991273 |
refs/heads/master | <repo_name>serdalis/elec_portal<file_sep>/textbook_exchange/admin.py
from elec_portal.textbook_exchange.models import Book
from django.contrib import admin
class BookAdmin(admin.ModelAdmin):
list_display = ('title',)
admin.site.register(Book, BookAdmin)
<file_sep>/homepage/admin.py
from elec_portal.homepage.models import Users
from django.contrib import admin
class UsersAdmin(admin.ModelAdmin):
list_display = ('username', 'first_name', 'last_name')
admin.site.register(Users, UsersAdmin)
<file_sep>/user_site/models.py
from django.db import models
SITE_STATUS = (
(-2, 'Disabled'),
(-1, 'Rejected'),
(0, 'Pending Approval'),
(1, 'Active')
)
NAVIGATION_LINK_TYPE = (
(0, 'Internal Page'),
(1, 'External URL')
)
class User_site(models.Model):
site_id = models.IntegerField(primary_key=True)
url_name = models.CharField(max_length=64)
name = models.CharField(max_length=256)
description = models.CharField(max_length=256)
request_details = models.CharField(max_length=256)
user_id = models.ForeignKey('homepage.Users')
create_time = models.DateField(auto_now_add=True)
status = models.IntegerField(choices=SITE_STATUS)
class Site_pages(models.Model):
page_id = models.IntegerField(primary_key=True)
website_id = models.ForeignKey(User_site)
create_time = models.DateTimeField(auto_now_add=True)
mod_time = models.DateTimeField(auto_now=True)
data = models.CharField(max_length=1) ##*** What's a blob? data: blob -> blob of data - text
name = models.CharField(max_length=64)
description = models.CharField(max_length=256)
keywords = models.CharField(max_length=128)
class Site_navigation(models.Model):
link_id = models.IntegerField(primary_key=True)
website_id = models.ForeignKey(User_site)
create_time = models.DateTimeField(auto_now_add=True)
mod_time = models.DateTimeField(auto_now=True)
name = models.CharField(max_length=32)
disabled = models.BooleanField()
link_type = models.IntegerField(choices=NAVIGATION_LINK_TYPE)
page_id = models.ForeignKey(Site_pages)
url = models.URLField(verify_exists=True, max_length=128)<file_sep>/homepage/views.py
from models import *
from django.shortcuts import render_to_response
def index(request):
users = Users.objects.all()
return render_to_response('homepage/index.html', {'users': users})
<file_sep>/urls.py
from django.conf.urls.defaults import *
from elec_portal import textbook_exchange, homepage
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^/', include('elec_portal.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
#(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'^', include('homepage.urls')),
(r'^textbook_exchange/', 'elec_portal.textbook_exchange.views.index')
)
<file_sep>/textbook_exchange/views.py
from models import *
from django.shortcuts import render_to_response
def index(request):
books = Book.objects.all()
return render_to_response('textbook_exchange/index.html', {'books': books})
<file_sep>/textbook_exchange/urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns('textbook_exchange.views',
url(r'^$', 'index', name="main"),
url(r'^remove/$', 'remove', name='remove'),
)
<file_sep>/textbook_exchange/models.py
from django.db import models
BOOK_STATUS = (
(0, 'Unlisted'),
(1, 'For Sale'),
(2, 'Sold')
)
TRANSACTION_STATUS = (
(-2, 'Cancelled'),
(-1, 'Rejected'),
(0, 'Awaiting Approval'),
(1, 'Approved'),
(2, 'Delivered'),
(3, 'Completed')
)
FEEDBACK_SCORE = (
(1, 'Very Bad'),
(2, ''),
(3, ''),
(4, ''),
(5, 'Neutral'),
(6, ''),
(7, ''),
(8, ''),
(9, ''),
(10, 'Very Good')
)
class Book(models.Model):
book_id = models.IntegerField(primary_key=True)
isbn = models.IntegerField() # Data dictionary says that it should be a foeign key, but to what?
price = models.DecimalField(max_digits=4, decimal_places=2)
status = models.IntegerField(choices=BOOK_STATUS)
description = models.CharField(max_length=200)
title = models.CharField(max_length=80)
author = models.CharField(max_length=160)
edition = models.IntegerField()
class Transaction(models.Model):
transaction_id = models.IntegerField(primary_key=True)
seller_id = models.ForeignKey('homepage.Users', related_name = 'seller')
buyer_id = models.ForeignKey('homepage.Users', related_name = 'buyer')
book_id = models.ForeignKey(Book)
status = models.IntegerField(choices=TRANSACTION_STATUS)
date_initialised = models.DateField(auto_now=True)
class Feedback(models.Model):
feedback_id = models.IntegerField(primary_key=True)
transaction_id = models.ForeignKey(Transaction)
user_id = models.ForeignKey('homepage.Users')
score = models.IntegerField(choices=FEEDBACK_SCORE)
feedback = models.CharField(max_length=200)
<file_sep>/homepage/models.py
from django.db import models
USER_RANK = (
(0, 'General User'),
(1, 'Administrator')
)
class Users(models.Model):
user_id = models.IntegerField(primary_key=True)
username = models.CharField(max_length=80)
password = models.CharField(max_length=41)
email = models.EmailField(max_length=120)
first_name = models.CharField(max_length=80)
last_name = models.CharField(max_length=80)
rank = models.IntegerField(choices=USER_RANK)
reset = models.BooleanField()<file_sep>/user_site/admin.py
from elec_portal.user_site.models import User_site
from django.contrib import admin
class User_siteAdmin(admin.ModelAdmin):
list_display = ('url_name',)
admin.site.register(User_site, User_siteAdmin)
| 597fc574e0f191b6d018f34ab25794d78c2116d7 | [
"Python"
] | 10 | Python | serdalis/elec_portal | 7a25116f223607925fdf14e7b4b0ab4f4de23162 | edf2d44423b1237cfed939cea44fe76a65b21088 |
refs/heads/master | <repo_name>lang710/graphics2018<file_sep>/21860405ๆฑ ๆตช/project03/ObjLoader.h
//
// Created by mac on 2019-01-05.
//
#ifndef OBJLOADER_OBJLOADER_H
#define OBJLOADER_OBJLOADER_H
#include "glew.h"
#include "freeglut.h"
#include <vector>
#include <string>
using namespace std;
class ObjLoader{
public:
ObjLoader(string filename);//ๆ้ ๅฝๆฐ
void Draw();//็ปๅถๅฝๆฐ
private:
vector<vector<GLfloat>>vSets;//ๅญๆพ้กถ็น(x,y,z)ๅๆ
vector<vector<GLint>>fSets;//ๅญๆพ้ข็ไธไธช้กถ็น็ดขๅผ
};
#endif //OBJLOADER_OBJLOADER_H
<file_sep>/21860405ๆฑ ๆตช/project02/SunPlanetMoon/SunPlanetMoon/main.cpp
#include <GLUT/GLUT.h>
#include <math.h>
#define GL_PI 3.1415f
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;
GLfloat whiteLight[]={0.2f,0.2f,0.2f,1.0f};
GLfloat lightPos[]={0.0f,0.0f,0.0f,1.0f};
void RenderScene(void)
{
static float fMoonRot = 0.0f;
static float fEarthRot= 0.0f;
glClear(GL_COLOR_BUFFER_BIT |GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glTranslatef(0.0f,0.0f,-300.0f);
//็ปๅถๅคช้ณ
glColor3ub(255,0,0);
glRotatef(1,0.0f,1.0f,0.0f);
glDisable(GL_LIGHTING);
//glutWireSphere(20, 20, 20);
glutSolidSphere(60.0f,60.0f,60.0f);
glEnable(GL_LIGHTING);
glLightfv(GL_LIGHT0,GL_POSITION,lightPos);
//็ปๅถๅฐ็
glColor3ub(0,0,255);
glRotatef(fEarthRot,0.0f,1.0f,0.0f);
glTranslatef(105.0f,0.0f,0.0f);
glutSolidSphere(15.0f,15.0f,15.0f);
//็ปๅถๆ็
glColor3ub(200,200,200);
glRotatef(fMoonRot,0.0f,1.0f,0.0f);
glTranslatef(30.0f,0.0f,0.0f);
fMoonRot += 15.0f;
if(fMoonRot >= 365.0f)
fMoonRot = 0.0f;
glutSolidSphere(6.0f,15.0f,15.0f);
glPopMatrix();
fEarthRot += 5.0f;
if(fEarthRot>=365.0f)
fEarthRot=0.0f;
glutSwapBuffers();
}
void ChangeSize(GLsizei w,GLsizei h)
{
GLfloat fAspect;
if(h==0) h=1;
glViewport(0,0,w,h);
fAspect = (GLfloat)w/(GLfloat)h;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0f,fAspect ,1.0,4000);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void SetupRC(void)
{
glEnable(GL_DEPTH_TEST);
glEnable(GL_COLOR_MATERIAL);
glClearColor(0.0f,0.0f,0.0f,1.0f);
glEnable(GL_LIGHTING);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT,whiteLight);
glLightfv(GL_LIGHT0,GL_POSITION,lightPos);
glEnable(GL_LIGHT0);
}
void SpecialKeys(int key ,int x, int y)
{
if(key==GLUT_KEY_UP)
xRot -= 5.0f;
if(key==GLUT_KEY_DOWN)
xRot +=5.0f;
if(key == GLUT_KEY_LEFT)
yRot -=5.0f;
if(key == GLUT_KEY_RIGHT)
yRot +=5.0f;
xRot = (GLfloat)((const int)xRot %360);
yRot = (GLfloat)((const int)yRot %360);
glutPostRedisplay();
}
void TimerFunc(int value)
{
glutPostRedisplay();
glutTimerFunc(100,TimerFunc,1);
}
int main(int argc, char* argv[])
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB|GLUT_DEPTH);
glutInitWindowSize(800,600);
glutCreateWindow("Orthographic Projection");
glutDisplayFunc(RenderScene);
glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
SetupRC();
glutTimerFunc(250,TimerFunc,1);
glutMainLoop();
return 0;
}
| 61bf114a8763b9f4a31a4c456a08575ed76d4dc2 | [
"C++"
] | 2 | C++ | lang710/graphics2018 | 178f570c8f7cfc7223d4b1128647d463e9beba90 | 46f5d6ff437e49f42faf14443915028027a09b9e |
refs/heads/master | <file_sep>Administrative Scripting with Julia
===================================
Note that this tutorial is still in process. The intended
order, after the introduction is:
- files_
- CLI_
- filesystem_
- processes_
- regex_ (still being written)
However, each part should theoretically stand on its own to some extent.
Those parts which have been written should nonetheless be considered
drafts for the moment, but you may still find them useful.
.. _files: 1-files.ipynb
.. _CLI: 2-CLI.ipynb
.. _filesystem: 3-filesystem.ipynb
.. _processes: 4-processes.ipynb
.. _regex: 5-regex.ipynb
Introduction
------------
If you know anything about Julia_, you probably know it's an interpreted
language which is gaining popularity for numeric computing that competes
with the likes of R, Matlab, NumPy and others. You've probably also
heard that it compiles to LLVM bytecode at runtime and can often be
optimized to within a factor of two of C or Fortran.
Given these promises, it's not surprising that it's attracted some very
high-profile users_.
I don't do any of that kind of programming. I like Julia for other
reasons altogether. For me, the appeal is that it feels good to write.
It's like all the things I like from Python, Perl and Scheme all rolled
into one. The abstractions, both in the language and the standard
library, just feel like they are always hitting the right points.
Semantically and syntactically, it feels similar to Python and Ruby,
though it promotes some design patterns more common in functional
languages and doesn't support classical OO patterns in the same way.
Instead, it relies on structs, abstract types, and multiple dispatch for
its type system. Julia's metaprogramming story is simple yet deep. It
allows operator overloading and other kinds of magic methods for
applying built-in syntax features to your own types. If that isn't
enough, it has Lips-like AST macros.
Finally, reading the standard library (which is implemented mostly in
very readable Julia), you see just how pragmatic it is. It is happy to
call into libc for the things libc is good at. It's equally happy to
shell out if that's the most practical thing. Check out the code for
the download_ function for an instructive example. Julia is very happy
to rely on PCRE_ for regular expressions. On the other hand, Julia is
fast enough that many of the bundled data structures and primitives
are implemented directly in Julia.
While keeping the syntax fairly clean and straightforward, the Julia
ethos is ultimately about getting things done and empowering the
programmer. If that means performance, you can optimize to your heart's
content. If it means downloading files with ``curl``, it will do that,
too!
This ethos fits very well with system automation. The classic languages
in this domain are Perl and Bash. Perl has the reputation of being
"write only," and Bash is much worse than that! However, both are
languages that emphasize pragmatism over purity, and that seems to be a
win for short scripts. Julia is more readable than either of these, but
it is not less pragmatic. [#]_
This tutorial follows roughly the approach of my `Python tutorial`_ on
administrative scripting and may refer to it at various points. Note
that I've been using Linux exclusively for more than a decade and I'm
not very knowledgable about Windows or OS X. However, if people wish to
contribute content necessary to make this tutorial more compatible with
those platforms, I would be very happy to learn.
.. _Julia: https://julialang.org/
.. _users: https://juliacomputing.com/case-studies/
.. _download:
https://github.com/JuliaLang/julia/blob/e7d15d4a013a43442b75ba4e477382804fa4ac49/base/download.jl
.. _PCRE: https://pcre.org/
.. _Python tutorial:
https://github.com/ninjaaron/replacing-bash-scripting-with-python
.. [#] This is not to fault the creators of Perl or Bourne Shell. They
are much older langauges, and all interpreted languages,
including Julia, have followed in their footsteps. Later
languages learned from their problems, but they also learned from
what they did right, which was a lot!
.. contents::
Why You Shouldn't Use Julia for Administrative Scripts
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It's just a bad idea!
- Julia is not the most portable. It's a relatively new language and has
only had its 1.1 release (at the time of writing, 2019, while 1.4 was
out in 2020). Many Linux distros don't have a package available.
Ubuntu 18.04 (the latest one as I write this) doesn't have a package
in the repository, though it is available as a snap (but download at
julialang.org, is preferred; as of April 2020, the snap install is
32-bit, and it may give you trouble, while it could do in some cases).
- Julia has a fat runtime and it has a human-perceptible load time on a
slower system. For the kinds of intensive problems it's targeted at,
this is nothing. On a constrained server or an embedded system, it's
bad.
- Julia's highly optimizing JIT compiler also takes a little time to
warm up. There are ways to precompile some things, but who wants to
bother for little scripts? The speed of the compiler is impressive for
how good it actually is, but it's not instant.
The above are reasonable arguments against using Julia on a certain
class of servers. However, none of this stuff really matters on a
PC/workstation running an OS with current packages. If your system can
run a modern web browser, Julia's runtime is a pittance.
If you already want to learn Julia, which there are many good reasons to
do, writing small automation scripts is a gentle way to become
acquainted with the basic features of the language.
The other reason you might want to try administrative scripting in Julia
is because the abstractions it provides are surprisingly well suited to
the task. Translating a Bash script to Julia is very easy but will
automatically make your script safer and easier to debug.
One final reason to use Julia for administrative is that it means you're
not using Bash! I've made a `case against Bash`_ for anything but
running and connecting other processes in Bash in my Python tutorial. In
short, Bash is great for interactive use, but it's difficult to do
things in a safe and correct way in scripts, and dealing with data is an
exercise in suffering. Handle data and complexity in programs in other
languages.
.. _case against bash:
https://github.com/ninjaaron/replacing-bash-scripting-with-python#if-the-shell-is-so-great-what-s-the-problem
Learning Julia
~~~~~~~~~~~~~~
This tutorial isn't going to show you how to do control flow in Julia
itself, and it certainly isn't going to cover all the ways of dealing
with the rich data structures that Julia provides. To be honest, I'm
still in the process of learning Julia myself, and I'm relying heavily
on the `official docs`_ for that, especially the "Manual" section. As an
experienced Python programmer, the interfaces provided by Julia feel
very familiar, and I suspect the feeling will be similar for Ruby
programmers. For us, becoming productive in Julia should only take a few
hours, though there are rather major differences as one progresses in
the language.
For a quick introduction to the language, the `learning`_ page has some
good links. The `Intro to Julia`_ with <NAME> goes over
everything you'll need to know to understand this tutorial. If you
choose to follow this tutorial, you will be guided to log into
juliabox.com, but you don't need to unless you want to. You can
download and run the `Jupyter Notebooks`_ locally if you wish, and you
can also simply follow along in the Julia REPL in a terminal.
The `Fast Track to Julia`_ is a handy cheatsheet if you're learning
the language
.. _official docs: https://docs.julialang.org
.. _learning: https://julialang.org/learning/
.. _Intro to Julia: https://www.youtube.com/watch?v=8h8rQyEpiZA&t=
.. _Jupyter Notebooks: https://github.com/JuliaComputing/JuliaBoxTutorials
.. _Fast Track to Julia: https://juliadocs.github.io/Julia-Cheat-Sheet/
Anway, let's get straight on to files_.
<file_sep>#!/bin/sh
cp ./base.rst README.rst
# echo "" >> README.rst
# for file in *.ipynb; do
# jupyter nbconvert --stdout --to rst "$file" >> README.rst
# done
| 5e0de11d0d7de4852e4d540a0b15ac7f0b3139ef | [
"reStructuredText",
"Shell"
] | 2 | reStructuredText | matklad/administrative-scripting-with-julia | d00194b2f4f10c5274be274b1043413ee6318de3 | c8d36d5085c8a6d00b4ef300a73f36c1805fdcc4 |
refs/heads/master | <file_sep>import socket
import pickle
from player import Player
class Server:
def __init__(self):
# Socket object
self.s = socket.socket()
print ("Socket successfully created")
# Reserve port
self.port = 5000
# bind port
self.s.bind(('0.0.0.0', self.port))
print("socket binded to %s" %(self.port) )
# Set to listen
self.s.listen(5)
print ("socket is listening" )
def start(self):
# a forever loop until we interrupt it or
# an error occurs
while True:
# Establish connection with client.
c, addr = self.s.accept()
print('Got connection from', addr )
# Retrieved from client
retrieved = pickle.loads(c.recv(1024))
loaded = self.save_stats(retrieved)
# send back to client
loaded_byte = pickle.dumps(loaded)
c.send(loaded_byte)
# Close the connection with the client
c.close()
def save_stats(self, player):
loaded = self.upload_stats(player)
if loaded == None:
print('User does not exist, creating %s'%player.name)
pickle.dump(player, file = open('player_base/%s.pkl'%player.name, 'wb'))
else:
return loaded
def upload_stats(self, player):
try:
loaded = pickle.load(file = open('player_base/%s.pkl'%player.name, 'rb'))
if loaded.password != player.<PASSWORD>:
return 'Password is incorrect'
else:
return loaded
except:
return 'User %s created'%player.name
if __name__ == "__main__":
server = Server()
server.start()<file_sep>
class Player:
def __init__(self, name, password):
self.name = name
self.password = <PASSWORD>
self.health = 100
<file_sep>from client import Client
from player import Player
import time
from easygui import *
# player1 = Player('peder')
# player1.health = 10
class Game:
def __init__(self):
# Initiate client
self.client = Client()
# User registrer
msg = "Register new player/login"
title = "Demo of multpasswordbox"
fieldNames = ["User ID", "Password"]
fieldValues = [] # we start with blanks for the values
fieldValues = multpasswordbox(msg, title, fieldNames)
# make sure that none of the fields was left blank
while 1:
if fieldValues == None:
break
errmsg = ""
for i in range(len(fieldNames)):
if fieldValues[i].strip() == "":
errmsg = errmsg + ('"%s" is a required field.\n\n' %fieldNames[i])
if errmsg == "":
break # no problems found
fieldValues = multpasswordbox(errmsg, title, fieldNames, fieldValues)
player_name, password = fieldValues
new_player = Player(player_name, password)
loaded = self.client.retrieve(new_player)
if type(loaded) == str:
print(loaded)
else:
print('health: %s'%loaded.health)
if __name__ == "__main__":
game = Game()<file_sep># Import socket module
import socket
import pickle
class Client:
def __init__(self):
# Define the port on which you want to connect
self.port = 5000
def send(self, info):
# Create a socket object
self.s = socket.socket()
# connect to the server on local computer
self.s.connect(('foxxy.ddns.net', self.port))
info_byte = pickle.dumps(info)
self.s.send(info_byte)
self.s.close()
def retrieve(self, info):
# Create a socket object
self.s = socket.socket()
# connect to the server on local computer
self.s.connect(('foxxy.ddns.net', self.port))
info_byte = pickle.dumps(info)
self.s.send(info_byte)
retrieved_info = self.s.recv(1024)
info_retrieve = pickle.loads(retrieved_info)
# close the connection
self.s.close()
return info_retrieve
| dca38350140fb593ed604098d1f3e2f28dbbeb36 | [
"Python"
] | 4 | Python | MartinRovang/sockets-pickle | 15586baeb3453a6c47fb7512987e5731b315393a | d6eca58b4667be76d75c7ec4811bf0d8813ad7bb |
refs/heads/master | <repo_name>anilpai/apollo-client<file_sep>/ROADMAP.md
# ๐ฎ Apollo Client Roadmap
**Last updated: April 2022**
For up to date release notes, refer to the project's [Change Log](https://github.com/apollographql/apollo-client/blob/main/CHANGELOG.md).
> **Please note:** This is an approximation of **larger effort** work planned for the next 6 - 12 months. It does not cover all new functionality that will be added, and nothing here is set in stone. Also note that each of these releases, and several patch releases in-between, will include bug fixes (based on issue triaging) and community submitted PR's.
## โ Community feedback & prioritization
- Please report feature requests or bugs as a new [issue](https://github.com/apollographql/apollo-client/issues/new/choose).
- If you already see an issue that interests you please add a ๐ or a comment so we can measure community interest.
---
## 3.7
1. Web Cache and performance improvements through new hooks (useBackgroundQuery, useFragment)
- [#8694](https://github.com/apollographql/apollo-client/issues/8694)
- [#8236](https://github.com/apollographql/apollo-client/issues/8236)
2. RefetchQueries not working when using string array after mutation
- [#5419](https://github.com/apollographql/apollo-client/issues/5419)
3. Adding React suspense + data fetching support
- [#9627](https://github.com/apollographql/apollo-client/issues/9627)
## 3.8
- *TBD*
## 3.9
- *TBD*
## 4.0
- Full React layer rewrite ([#8245](https://github.com/apollographql/apollo-client/issues/8245))
- Removal of React from the default `@apollo/client` entry point ([#8190](https://github.com/apollographql/apollo-client/issues/8190))
- Core APIs to facilitate client/cache persistence (making life simpler for tools like [`apollo3-cache-persist`](https://github.com/apollographql/apollo-cache-persist), for example) ([#8591](https://github.com/apollographql/apollo-client/issues/8591))
<file_sep>/src/react/hoc/__tests__/queries/recomposeWithState.js
// Adapted from v0.30.0 of https://github.com/acdlite/recompose/blob/master/src/packages/recompose/withState.js
// to avoid incurring an indirect dependency on ua-parser-js via fbjs.
import { createFactory, Component } from 'react'
const setStatic = (key, value) => BaseComponent => {
/* eslint-disable no-param-reassign */
BaseComponent[key] = value
/* eslint-enable no-param-reassign */
return BaseComponent
}
const setDisplayName = displayName => setStatic('displayName', displayName)
const getDisplayName = Component => {
if (typeof Component === 'string') {
return Component
}
if (!Component) {
return undefined
}
return Component.displayName || Component.name || 'Component'
}
const wrapDisplayName = (BaseComponent, hocName) =>
`${hocName}(${getDisplayName(BaseComponent)})`
export const withState = (
stateName,
stateUpdaterName,
initialState
) => BaseComponent => {
const factory = createFactory(BaseComponent)
class WithState extends Component {
state = {
stateValue:
typeof initialState === 'function'
? initialState(this.props)
: initialState,
}
updateStateValue = (updateFn, callback) =>
this.setState(
({ stateValue }) => ({
stateValue:
typeof updateFn === 'function' ? updateFn(stateValue) : updateFn,
}),
callback
)
render() {
return factory({
...this.props,
[stateName]: this.state.stateValue,
[stateUpdaterName]: this.updateStateValue,
})
}
}
if (__DEV__) {
return setDisplayName(wrapDisplayName(BaseComponent, 'withState'))(
WithState
)
}
return WithState
}
// Jest complains if modules within __tests__ directories contain no tests.
describe("withState", () => {
it("is a function", () => {
expect(typeof withState).toBe("function");
});
});
<file_sep>/src/link/core/types.ts
import { DocumentNode, ExecutionResult } from 'graphql';
export { DocumentNode };
import { Observable } from '../../utilities';
export interface GraphQLRequest {
query: DocumentNode;
variables?: Record<string, any>;
operationName?: string;
context?: Record<string, any>;
extensions?: Record<string, any>;
}
export interface Operation {
query: DocumentNode;
variables: Record<string, any>;
operationName: string;
extensions: Record<string, any>;
setContext: (context: Record<string, any>) => Record<string, any>;
getContext: () => Record<string, any>;
}
export interface FetchResult<
TData = Record<string, any>,
TContext = Record<string, any>,
TExtensions = Record<string, any>
> extends ExecutionResult<TData, TExtensions> {
data?: TData | null | undefined;
extensions?: TExtensions;
context?: TContext;
};
export type NextLink = (operation: Operation) => Observable<FetchResult>;
export type RequestHandler = (
operation: Operation,
forward: NextLink,
) => Observable<FetchResult> | null;
| 1702f330d6daaf8e6fa39331af5a99df98cad9f0 | [
"Markdown",
"TypeScript",
"JavaScript"
] | 3 | Markdown | anilpai/apollo-client | efdbae05065bfc93e051203e0fbb396eb926830d | 5effdeed87970462b069a7090f6c9ee128e61ebd |
refs/heads/master | <repo_name>choliveira/people-profile<file_sep>/src/Trout/PersonProfileBundle/Controller/PersonProfileController.php
<?php
namespace Trout\PersonProfileBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Validator\Constraints\Date;
use Trout\PersonProfileBundle\Entity\PersonProfile;
use Trout\PersonProfileBundle\Form\PersonProfileType;
/**
* PersonProfile controller.
*
*/
class PersonProfileController extends Controller
{
/**
* Lists all PersonProfile entities.
*
*/
public function indexAction()
{
return $this->redirect($this->generateUrl('personprofile_list'));
}
/*
* List with pagination
*
*/
public function listAction($page)
{
$em = $this->getDoctrine()->getManager();
$dql = "SELECT a FROM PersonProfileBundle:PersonProfile a";
$query = $em->createQuery($dql);
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$query,
$this->get('request')->query->get('page', $page)/*page number*/, 5/*limit per page*/
);
$pagination->setUsedRoute('personprofile_list');
$deleteForm = array();
foreach ($pagination as $entity) {
$deleteForm[$entity->getId()] = $this->createDeleteForm($entity->getId())->createView();
}
return $this->render('PersonProfileBundle:PersonProfile:list.html.twig',
array(
'pagination' => $pagination,
'delete_form' => $deleteForm,
)
);
}
/**
* Creates a new PersonProfile entity.
*
*/
public function createAction(Request $request)
{
$entity = new PersonProfile();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect( $this->generateUrl('personprofile') );
}
return $this->render('PersonProfileBundle:PersonProfile:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
/**
* Creates a form to create a PersonProfile entity.
*
* @param PersonProfile $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(PersonProfile $entity)
{
$form = $this->createForm(new PersonProfileType(), $entity, array(
'action' => $this->generateUrl('personprofile_create'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new PersonProfile entity.
*
*/
public function newAction()
{
$entity = new PersonProfile();
$form = $this->createCreateForm($entity);
return $this->render('PersonProfileBundle:PersonProfile:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
/**
* Finds and displays a PersonProfile entity.
*
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('PersonProfileBundle:PersonProfile')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find PersonProfile entity.');
}
$deleteForm = $this->createDeleteForm($id);
return $this->render('PersonProfileBundle:PersonProfile:show.html.twig', array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
));
}
/**
* Displays a form to edit an existing PersonProfile entity.
*
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('PersonProfileBundle:PersonProfile')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find PersonProfile entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return $this->render('PersonProfileBundle:PersonProfile:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Creates a form to edit a PersonProfile entity.
*
* @param PersonProfile $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(PersonProfile $entity)
{
$form = $this->createForm(new PersonProfileType(), $entity, array(
'action' => $this->generateUrl('personprofile_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'Update'));
return $form;
}
/**
* Edits an existing PersonProfile entity.
*
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('PersonProfileBundle:PersonProfile')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find PersonProfile entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('personprofile_edit', array('id' => $id)));
} else {
$editForm->getErrorsAsString();
}
return $this->render('PersonProfileBundle:PersonProfile:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Deletes a PersonProfile entity.
*
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('PersonProfileBundle:PersonProfile')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find PersonProfile entity.');
}
$em->remove($entity);
$em->flush();
} else {
var_dump($form->getErrorsAsString());die;
}
return $this->redirect($this->generateUrl('personprofile'));
}
/**
* Creates a form to delete a PersonProfile entity by id.
*
* @param mixed $id The entity id
*
* @return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('personprofile_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Delete'))
->getForm()
;
}
}
<file_sep>/src/Trout/PersonProfileBundle/PersonProfileBundle.php
<?php
namespace Trout\PersonProfileBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class PersonProfileBundle extends Bundle
{
}
<file_sep>/src/Trout/PersonProfileBundle/Entity/Education.php
<?php
namespace Trout\PersonProfileBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Education
*
* @ORM\Table(name="education", indexes={@ORM\Index(name="fk_education_person_profile1_idx", columns={"fk_id_person_profile"})})
* @ORM\Entity
*/
class Education
{
/**
* @var string
*
* @ORM\Column(name="school", type="string", length=200, nullable=false)
*/
private $school;
/**
* @var string
*
* @ORM\Column(name="degree", type="string", length=200, nullable=false)
*/
private $degree;
/**
* @var string
*
* @ORM\Column(name="year_starts", type="string", length=4, nullable=false)
*/
private $yearStarts;
/**
* @var string
*
* @ORM\Column(name="year_ends", type="string", length=4, nullable=true)
*/
private $yearEnds;
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var \Trout\PersonProfileBundle\Entity\PersonProfile
*
* @ORM\ManyToOne(targetEntity="Trout\PersonProfileBundle\Entity\PersonProfile")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="fk_id_person_profile", referencedColumnName="id")
* })
*/
private $fkPersonProfile;
/**
* Set school
*
* @param string $school
* @return Education
*/
public function setSchool($school)
{
$this->school = $school;
return $this;
}
/**
* Get school
*
* @return string
*/
public function getSchool()
{
return $this->school;
}
/**
* Set degree
*
* @param string $degree
* @return Education
*/
public function setDegree($degree)
{
$this->degree = $degree;
return $this;
}
/**
* Get degree
*
* @return string
*/
public function getDegree()
{
return $this->degree;
}
/**
* Set yearStarts
*
* @param string $yearStarts
* @return Education
*/
public function setYearStarts($yearStarts)
{
$this->yearStarts = $yearStarts;
return $this;
}
/**
* Get yearStarts
*
* @return string
*/
public function getYearStarts()
{
return $this->yearStarts;
}
/**
* Set yearEnds
*
* @param string $yearEnds
* @return Education
*/
public function setYearEnds($yearEnds)
{
$this->yearEnds = $yearEnds;
return $this;
}
/**
* Get yearEnds
*
* @return string
*/
public function getYearEnds()
{
return $this->yearEnds;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set fkPersonProfile
*
* @param \Trout\PersonProfileBundle\Entity\PersonProfile $fkPersonProfile
* @return Education
*/
public function setFkPersonProfile(\Trout\PersonProfileBundle\Entity\PersonProfile $fkPersonProfile = null)
{
$this->fkPersonProfile = $fkPersonProfile;
return $this;
}
/**
* Get fkPersonProfile
*
* @return \Trout\PersonProfileBundle\Entity\PersonProfile
*/
public function getFkPersonProfile()
{
return $this->fkPersonProfile;
}
}
<file_sep>/src/Trout/PersonProfileBundle/Entity/PersonProfile.php
<?php
namespace Trout\PersonProfileBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* PersonProfile
*
* @ORM\Table(name="person_profile", indexes={@ORM\Index(name="fk_person_profile_organisation1_idx", columns={"fk_id_organisation"}), @ORM\Index(name="fk_person_profile_occupation1_idx", columns={"fk_id_occupation"}), @ORM\Index(name="fk_person_profile_position1_idx", columns={"fk_id_position"})})
* @ORM\Entity
*
*/
class PersonProfile
{
/**
*
*/
// public function __construct()
// {
// $this->setCreatedAt( new \DateTime(date('Y-m-d H:i:s')) );
//
// if($this->getModifiedAt() == null){
// $this->setModifiedAt( new \DateTime(date('Y-m-d H:i:s')) );
// }
// }
/**
* @var string
*
* @ORM\Column(name="first_name", type="string", length=200, nullable=false)
*/
private $firstName;
/**
* @var string
*
* @ORM\Column(name="last_name", type="string", length=200, nullable=false)
*/
private $lastName;
/**
* @var string
*
* @ORM\Column(name="photo_path", type="string", length=200, nullable=true)
*/
private $photoPath;
/**
* @var string
*
* @ORM\Column(name="experience", type="string", length=45, nullable=true)
*/
private $experience;
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var \Trout\PersonProfileBundle\Entity\Position
*
* @ORM\ManyToOne(targetEntity="Trout\PersonProfileBundle\Entity\Position")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="fk_id_position", referencedColumnName="id")
* })
*/
private $fkPosition;
/**
* @var \Trout\PersonProfileBundle\Entity\Organisation
*
* @ORM\ManyToOne(targetEntity="Trout\PersonProfileBundle\Entity\Organisation")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="fk_id_organisation", referencedColumnName="id")
* })
*/
private $fkOrganisation;
/**
* @var \Trout\PersonProfileBundle\Entity\Occupation
*
* @ORM\ManyToOne(targetEntity="Trout\PersonProfileBundle\Entity\Occupation")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="fk_id_occupation", referencedColumnName="id")
* })
*/
private $fkOccupation;
/**
* Set firstName
*
* @param string $firstName
* @return PersonProfile
*/
public function setFirstName($firstName)
{
$this->firstName = $firstName;
return $this;
}
/**
* Get firstName
*
* @return string
*/
public function getFirstName()
{
return $this->firstName;
}
/**
* Set lastName
*
* @param string $lastName
* @return PersonProfile
*/
public function setLastName($lastName)
{
$this->lastName = $lastName;
return $this;
}
/**
* Get lastName
*
* @return string
*/
public function getLastName()
{
return $this->lastName;
}
/**
* Set photoPath
*
* @param string $photoPath
* @return PersonProfile
*/
public function setPhotoPath($photoPath)
{
$this->photoPath = $photoPath;
return $this;
}
/**
* Get photoPath
*
* @return string
*/
public function getPhotoPath()
{
return $this->photoPath;
}
/**
* Set experience
*
* @param string $experience
* @return PersonProfile
*/
public function setExperience($experience)
{
$this->experience = $experience;
return $this;
}
/**
* Get experience
*
* @return string
*/
public function getExperience()
{
return $this->experience;
}
/**
* Set createdAt
*
* @param \DateTime $createdAt
* @return PersonProfile
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set modifiedAt
*
* @param \DateTime $modifiedAt
* @return PersonProfile
*/
public function setModifiedAt($modifiedAt)
{
$this->modifiedAt = $modifiedAt;
return $this;
}
/**
* Get modifiedAt
*
* @return \DateTime
*/
public function getModifiedAt()
{
return $this->modifiedAt;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set fkPosition
*
* @param \Trout\PersonProfileBundle\Entity\Position $fkPosition
* @return PersonProfile
*/
public function setFkPosition(\Trout\PersonProfileBundle\Entity\Position $fkPosition = null)
{
$this->fkPosition = $fkPosition;
return $this;
}
/**
* Get fkPosition
*
* @return \Trout\PersonProfileBundle\Entity\Position
*/
public function getFkPosition()
{
return $this->fkPosition;
}
/**
* Set fkOrganisation
*
* @param \Trout\PersonProfileBundle\Entity\Organisation $fkOrganisation
* @return PersonProfile
*/
public function setFkOrganisation(\Trout\PersonProfileBundle\Entity\Organisation $fkOrganisation = null)
{
$this->fkOrganisation = $fkOrganisation;
return $this;
}
/**
* Get fkOrganisation
*
* @return \Trout\PersonProfileBundle\Entity\Organisation
*/
public function getFkOrganisation()
{
return $this->fkOrganisation;
}
/**
* Set fkOccupation
*
* @param \Trout\PersonProfileBundle\Entity\Occupation $fkOccupation
* @return PersonProfile
*/
public function setFkOccupation(\Trout\PersonProfileBundle\Entity\Occupation $fkOccupation = null)
{
$this->fkOccupation = $fkOccupation;
return $this;
}
/**
* Get fkOccupation
*
* @return \Trout\PersonProfileBundle\Entity\Occupation
*/
public function getFkOccupation()
{
return $this->fkOccupation;
}
}
<file_sep>/Api/module/profile/Module.php
<?php
require __DIR__ . '/src/profile/Module.php';<file_sep>/README.md
people-profile
==============
A Symfony project created on March 28, 2015, 1:52 pm.
RESTfull links: localhost
Get
http://localhost/Sites/people-profile/Api/public/occupation
http://localhost/Sites/people-profile/Api/public/occupation?page=2
http://localhost/Sites/people-profile/Api/public/occupation/3
Post
http://localhost/Sites/people-profile/Api/public/occupation
{
"occupation" : "text"
}
Online:
Get
http://www.carlosholiveira.com/people-profile/Api/public/occupation
http://www.carlosholiveira.com/people-profile/Api/public/occupation?page=2
http://www.carlosholiveira.com/people-profile/Api/public/occupation/3
Post
http://www.carlosholiveira.com/people-profile/Api/public/occupation
{
"occupation" : "text"
}
Put | Patch
http://carlosholiveira.com/people-profile/Api/public/person_profile/8
{
"first_name": "<NAME>",
"last_name": "<NAME>"
}
http://www.carlosholiveira.com/people-profile/Api/public/occupation/8
{
"occupation" : "your text"
}
Delete
http://www.carlosholiveira.com/people-profile/Api/public/occupation/{id}
==============
Online DB
DBname: trout_test
DBhost: trout.carlosholiveira.com
DBuser: trout_test
DBpsswd: <PASSWORD>!
<file_sep>/Api/module/profile/src/profile/V1/Rest/Occupation/OccupationCollection.php
<?php
namespace profile\V1\Rest\Occupation;
use Zend\Paginator\Paginator;
class OccupationCollection extends Paginator
{
}
<file_sep>/src/Trout/PersonProfileBundle/Form/PersonProfileType.php
<?php
namespace Trout\PersonProfileBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class PersonProfileType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('firstName')
->add('lastName')
->add('photoPath')
->add('experience')
->add('fkPosition')
->add('fkOrganisation')
->add('fkOccupation')
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Trout\PersonProfileBundle\Entity\PersonProfile'
));
}
/**
* @return string
*/
public function getName()
{
return 'trout_personprofilebundle_personprofile';
}
}
<file_sep>/src/Trout/PersonProfileBundle/Entity/PersonHasExpertise.php
<?php
namespace Trout\PersonProfileBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* PersonHasExpertise
*
* @ORM\Table(name="person_has_expertise", indexes={@ORM\Index(name="fk_person_has_expertise_person_profile1_idx", columns={"fk_id_person_profile"}), @ORM\Index(name="fk_person_has_expertise_expertise1_idx", columns={"fk_id_expertise"})})
* @ORM\Entity
*/
class PersonHasExpertise
{
/**
* @var integer
*
* @ORM\Column(name="id_relationship", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idRelationship;
/**
* @var \Trout\PersonProfileBundle\Entity\PersonProfile
*
* @ORM\ManyToOne(targetEntity="Trout\PersonProfileBundle\Entity\PersonProfile")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="fk_id_person_profile", referencedColumnName="id")
* })
*/
private $fkPersonProfile;
/**
* @var \Trout\PersonProfileBundle\Entity\Expertise
*
* @ORM\ManyToOne(targetEntity="Trout\PersonProfileBundle\Entity\Expertise")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="fk_id_expertise", referencedColumnName="id")
* })
*/
private $fkExpertise;
/**
* Get idRelationship
*
* @return integer
*/
public function getIdRelationship()
{
return $this->idRelationship;
}
/**
* Set fkPersonProfile
*
* @param \Trout\PersonProfileBundle\Entity\PersonProfile $fkPersonProfile
* @return PersonHasExpertise
*/
public function setFkPersonProfile(\Trout\PersonProfileBundle\Entity\PersonProfile $fkPersonProfile = null)
{
$this->fkPersonProfile = $fkPersonProfile;
return $this;
}
/**
* Get fkPersonProfile
*
* @return \Trout\PersonProfileBundle\Entity\PersonProfile
*/
public function getFkPersonProfile()
{
return $this->fkPersonProfile;
}
/**
* Set fkExpertise
*
* @param \Trout\PersonProfileBundle\Entity\Expertise $fkExpertise
* @return PersonHasExpertise
*/
public function setFkExpertise(\Trout\PersonProfileBundle\Entity\Expertise $fkExpertise = null)
{
$this->fkExpertise = $fkExpertise;
return $this;
}
/**
* Get fkExpertise
*
* @return \Trout\PersonProfileBundle\Entity\Expertise
*/
public function getFkExpertise()
{
return $this->fkExpertise;
}
}
<file_sep>/src/Trout/PersonProfileBundle/Entity/Occupation.php
<?php
namespace Trout\PersonProfileBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Occupation
*
* @ORM\Table(name="occupation")
* @ORM\Entity
*/
class Occupation
{
/**
* @var string
*
* @ORM\Column(name="occupation", type="string", length=45, nullable=false)
*/
private $occupation;
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* Set occupation
*
* @param string $occupation
* @return Occupation
*/
public function setOccupation($occupation)
{
$this->occupation = $occupation;
return $this;
}
/**
* Get occupation
*
* @return string
*/
public function getOccupation()
{
return $this->occupation;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* @return string
*/
public function __toString()
{
return $this->occupation;
}
}
<file_sep>/Api/module/profile/src/profile/V1/Rest/Occupation/OccupationEntity.php
<?php
namespace profile\V1\Rest\Occupation;
use ArrayObject;
class OccupationEntity extends ArrayObject
{
}
<file_sep>/src/Trout/PersonProfileBundle/Entity/PersonHasEducataion.php
<?php
namespace Trout\PersonProfileBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* PersonHasEducataion
*
* @ORM\Table(name="person_has_educataion", indexes={@ORM\Index(name="fk_person_has_educataion_person_profile1_idx", columns={"fk_id_person_profile"}), @ORM\Index(name="fk_person_has_educataion_education1_idx", columns={"fk_id_education"})})
* @ORM\Entity
*/
class PersonHasEducataion
{
/**
* @var integer
*
* @ORM\Column(name="id_relationship", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idRelationship;
/**
* @var \Trout\PersonProfileBundle\Entity\PersonProfile
*
* @ORM\ManyToOne(targetEntity="Trout\PersonProfileBundle\Entity\PersonProfile")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="fk_id_person_profile", referencedColumnName="id")
* })
*/
private $fkPersonProfile;
/**
* @var \Trout\PersonProfileBundle\Entity\Education
*
* @ORM\ManyToOne(targetEntity="Trout\PersonProfileBundle\Entity\Education")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="fk_id_education", referencedColumnName="id")
* })
*/
private $fkEducation;
/**
* Get idRelationship
*
* @return integer
*/
public function getIdRelationship()
{
return $this->idRelationship;
}
/**
* Set fkPersonProfile
*
* @param \Trout\PersonProfileBundle\Entity\PersonProfile $fkPersonProfile
* @return PersonHasEducataion
*/
public function setFkPersonProfile(\Trout\PersonProfileBundle\Entity\PersonProfile $fkPersonProfile = null)
{
$this->fkPersonProfile = $fkPersonProfile;
return $this;
}
/**
* Get fkPersonProfile
*
* @return \Trout\PersonProfileBundle\Entity\PersonProfile
*/
public function getFkPersonProfile()
{
return $this->fkPersonProfile;
}
/**
* Set fkEducation
*
* @param \Trout\PersonProfileBundle\Entity\Education $fkEducation
* @return PersonHasEducataion
*/
public function setFkEducation(\Trout\PersonProfileBundle\Entity\Education $fkEducation = null)
{
$this->fkEducation = $fkEducation;
return $this;
}
/**
* Get fkEducation
*
* @return \Trout\PersonProfileBundle\Entity\Education
*/
public function getFkEducation()
{
return $this->fkEducation;
}
}
<file_sep>/src/Trout/PersonProfileBundle/Form/PersonHasExpertiseType.php
<?php
namespace Trout\PersonProfileBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class PersonHasExpertiseType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('fkPersonProfile')
->add('fkExpertise')
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Trout\PersonProfileBundle\Entity\PersonHasExpertise'
));
}
/**
* @return string
*/
public function getName()
{
return 'trout_personprofilebundle_personhasexpertise';
}
}
<file_sep>/src/Trout/PersonProfileBundle/Entity/Organisation.php
<?php
namespace Trout\PersonProfileBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Organisation
*
* @ORM\Table(name="organisation", indexes={@ORM\Index(name="fk_organisation_organisation_type_idx", columns={"fk_id_type_organisation"})})
* @ORM\Entity
*/
class Organisation
{
/**
* @var string
*
* @ORM\Column(name="organisation_name", type="string", length=200, nullable=false)
*/
private $organisationName;
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var \Trout\PersonProfileBundle\Entity\TypeOrganisation
*
* @ORM\ManyToOne(targetEntity="Trout\PersonProfileBundle\Entity\TypeOrganisation")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="fk_id_type_organisation", referencedColumnName="id")
* })
*/
private $fkTypeOrganisation;
/**
* Set organisationName
*
* @param string $organisationName
* @return Organisation
*/
public function setOrganisationName($organisationName)
{
$this->organisationName = $organisationName;
return $this;
}
/**
* Get organisationName
*
* @return string
*/
public function getOrganisationName()
{
return $this->organisationName;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set fkTypeOrganisation
*
* @param \Trout\PersonProfileBundle\Entity\TypeOrganisation $fkTypeOrganisation
* @return Organisation
*/
public function setFkTypeOrganisation(\Trout\PersonProfileBundle\Entity\TypeOrganisation $fkTypeOrganisation = null)
{
$this->fkTypeOrganisation = $fkTypeOrganisation;
return $this;
}
/**
* Get fkTypeOrganisation
*
* @return \Trout\PersonProfileBundle\Entity\TypeOrganisation
*/
public function getFkTypeOrganisation()
{
return $this->fkTypeOrganisation;
}
/**
* @return string
*/
public function __toString()
{
return $this->organisationName;
}
}
<file_sep>/src/Trout/PersonProfileBundle/Entity/PersonHasLanguageProficiency.php
<?php
namespace Trout\PersonProfileBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* PersonHasLanguageProficiency
*
* @ORM\Table(name="person_has_language_proficiency", indexes={@ORM\Index(name="fk_person_has_language_proficiency_language_proficiency1_idx", columns={"fk_id_language_proficiency"}), @ORM\Index(name="fk_person_has_language_proficiency_language1_idx", columns={"fk_id_language"}), @ORM\Index(name="fk_person_has_language_proficiency_person_profile1_idx", columns={"fk_id_person_profile"})})
* @ORM\Entity
*/
class PersonHasLanguageProficiency
{
/**
* @var integer
*
* @ORM\Column(name="id_relationship", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idRelationship;
/**
* @var \Trout\PersonProfileBundle\Entity\PersonProfile
*
* @ORM\ManyToOne(targetEntity="Trout\PersonProfileBundle\Entity\PersonProfile")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="fk_id_person_profile", referencedColumnName="id")
* })
*/
private $fkPersonProfile;
/**
* @var \Trout\PersonProfileBundle\Entity\LanguageProficiency
*
* @ORM\ManyToOne(targetEntity="Trout\PersonProfileBundle\Entity\LanguageProficiency")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="fk_id_language_proficiency", referencedColumnName="id")
* })
*/
private $fkLanguageProficiency;
/**
* @var \Trout\PersonProfileBundle\Entity\Language
*
* @ORM\ManyToOne(targetEntity="Trout\PersonProfileBundle\Entity\Language")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="fk_id_language", referencedColumnName="id")
* })
*/
private $fkLanguage;
/**
* Get idRelationship
*
* @return integer
*/
public function getIdRelationship()
{
return $this->idRelationship;
}
/**
* Set fkPersonProfile
*
* @param \Trout\PersonProfileBundle\Entity\PersonProfile $fkPersonProfile
* @return PersonHasLanguageProficiency
*/
public function setFkPersonProfile(\Trout\PersonProfileBundle\Entity\PersonProfile $fkPersonProfile = null)
{
$this->fkPersonProfile = $fkPersonProfile;
return $this;
}
/**
* Get fkPersonProfile
*
* @return \Trout\PersonProfileBundle\Entity\PersonProfile
*/
public function getFkPersonProfile()
{
return $this->fkPersonProfile;
}
/**
* Set fkLanguageProficiency
*
* @param \Trout\PersonProfileBundle\Entity\LanguageProficiency $fkLanguageProficiency
* @return PersonHasLanguageProficiency
*/
public function setFkLanguageProficiency(\Trout\PersonProfileBundle\Entity\LanguageProficiency $fkLanguageProficiency = null)
{
$this->fkLanguageProficiency = $fkLanguageProficiency;
return $this;
}
/**
* Get fkLanguageProficiency
*
* @return \Trout\PersonProfileBundle\Entity\LanguageProficiency
*/
public function getFkLanguageProficiency()
{
return $this->fkLanguageProficiency;
}
/**
* Set fkLanguage
*
* @param \Trout\PersonProfileBundle\Entity\Language $fkLanguage
* @return PersonHasLanguageProficiency
*/
public function setFkLanguage(\Trout\PersonProfileBundle\Entity\Language $fkLanguage = null)
{
$this->fkLanguage = $fkLanguage;
return $this;
}
/**
* Get fkLanguage
*
* @return \Trout\PersonProfileBundle\Entity\Language
*/
public function getFkLanguage()
{
return $this->fkLanguage;
}
}
<file_sep>/src/Trout/PersonProfileBundle/Controller/PersonHasExpertiseController.php
<?php
namespace Trout\PersonProfileBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Trout\PersonProfileBundle\Entity\PersonHasExpertise;
use Trout\PersonProfileBundle\Form\PersonHasExpertiseType;
/**
* PersonHasExpertise controller.
*
* @Route("/personhasexpertise")
*/
class PersonHasExpertiseController extends Controller
{
/**
* Lists all PersonHasExpertise entities.
*
* @Route("/", name="personhasexpertise")
* @Method("GET")
* @Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('PersonProfileBundle:PersonHasExpertise')->findAll();
return array(
'entities' => $entities,
);
}
/**
* Creates a new PersonHasExpertise entity.
*
* @Route("/", name="personhasexpertise_create")
* @Method("POST")
* @Template("PersonProfileBundle:PersonHasExpertise:new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new PersonHasExpertise();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('personhasexpertise_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Creates a form to create a PersonHasExpertise entity.
*
* @param PersonHasExpertise $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(PersonHasExpertise $entity)
{
$form = $this->createForm(new PersonHasExpertiseType(), $entity, array(
'action' => $this->generateUrl('personhasexpertise_create'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new PersonHasExpertise entity.
*
* @Route("/new", name="personhasexpertise_new")
* @Method("GET")
* @Template()
*/
public function newAction()
{
$entity = new PersonHasExpertise();
$form = $this->createCreateForm($entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Finds and displays a PersonHasExpertise entity.
*
* @Route("/{id}", name="personhasexpertise_show")
* @Method("GET")
* @Template()
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('PersonProfileBundle:PersonHasExpertise')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find PersonHasExpertise entity.');
}
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
);
}
/**
* Displays a form to edit an existing PersonHasExpertise entity.
*
* @Route("/{id}/edit", name="personhasexpertise_edit")
* @Method("GET")
* @Template()
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('PersonProfileBundle:PersonHasExpertise')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find PersonHasExpertise entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Creates a form to edit a PersonHasExpertise entity.
*
* @param PersonHasExpertise $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(PersonHasExpertise $entity)
{
$form = $this->createForm(new PersonHasExpertiseType(), $entity, array(
'action' => $this->generateUrl('personhasexpertise_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'Update'));
return $form;
}
/**
* Edits an existing PersonHasExpertise entity.
*
* @Route("/{id}", name="personhasexpertise_update")
* @Method("PUT")
* @Template("PersonProfileBundle:PersonHasExpertise:edit.html.twig")
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('PersonProfileBundle:PersonHasExpertise')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find PersonHasExpertise entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('personhasexpertise_edit', array('id' => $id)));
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes a PersonHasExpertise entity.
*
* @Route("/{id}", name="personhasexpertise_delete")
* @Method("DELETE")
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('PersonProfileBundle:PersonHasExpertise')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find PersonHasExpertise entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('personhasexpertise'));
}
/**
* Creates a form to delete a PersonHasExpertise entity by id.
*
* @param mixed $id The entity id
*
* @return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('personhasexpertise_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Delete'))
->getForm()
;
}
}
| ef0dabb4a3d441bca63bf66e81e6e56aca1fa434 | [
"Markdown",
"PHP"
] | 16 | PHP | choliveira/people-profile | 6dad8049730679b0a4bdbcf15293d085f16e423e | 4139a75876e1baaa38a56699623e33ba6acdc20b |
refs/heads/master | <file_sep># NLP-Autocomplete
<file_sep># #!/usr/bin/env python
# # -*- coding: utf-8 -*-
import codecs
import glob
import os
import re
import math
corpus = ""
for file in glob.glob(os.path.join('corpus', u'*')):
if os.path.isfile(file):
# print( file )
f=codecs.open(file,encoding='utf-8')
for line in f:
# print( line )
if len(line)> 3:
corpus+=line
f.close()
words=re.split('\s|,|ุ', corpus)
w=[]
for i in words:
if len(i)!=0:
w+=[i]
map1={}
map11={}
count1=[0]
id=1
for i in w:
if i in map1:
count1[map1[i]]+=1
else:
map1[i]=id
map11[id]=i
id += 1
count1+=[1]
# for i in range (1,100):
# print( count1[i]," , ",map11[i])
map2={}
map22={}
count2=[0]
id=1
for i in range (0,len(w)-1):
ss=(w[i],w[i+1])
if ss in map2:
count2[map2[ss]]+=1
else:
map2[ss]=id
map22[id]=ss
id += 1
count2+=[1]
#
# for i in range (1,100):
# print( count2[i]," , ",map22[i])
map3={}
map33={}
count3=[0]
id=1
for i in range (0,len(w)-2):
ss=(w[i],w[i+1],w[i+2])
if ss in map3:
count3[map3[ss]]+=1
else:
map3[ss]=id
map33[id]=ss
id += 1
count3+=[1]
# for i in range (1,100):
# print( count3[i]," , ",map33[i])
adj=[[]]
for i in range(0,len(map2)):
adj+=[[]]
for i in range(1,len(map3)):
if(map33[i][2]!='@'):
count_of_word=count1[map1[map33[i][2]]]
prob_with_prev_word=count2[map2[(map33[i][1],map33[i][2])]]/count1[map1[map33[i][1]]]
prob_with_prev_prev_word=count3[map3[(map33[i][0],map33[i][1],map33[i][2])]]/count2[map2[(map33[i][0],map33[i][1])]]
probability = math.log10(count_of_word)+math.log10(prob_with_prev_word)+math.log10(prob_with_prev_prev_word)
adj[map2[(map33[i][0], map33[i][1])]] += [(probability,map33[i][2])]
j=0
# for i in range (1,len(adj)):
# print(map33[i])
# print(adj[map2[(map33[i][0], map33[i][1])]])
output=codecs.open("res.txt","w",encoding="UTF-8")
nn=0
for i in map2:
if(len(adj[map2[i]])>0):
nn+=1
output.write(str(nn))
output.write( "\n" )
for i in map2:
if(len(adj[map2[i]])>0):
adj[map2[i]].sort( key=lambda x: x[0], reverse=True )
output.write(i[0])
output.write("\n")
output.write(i[1])
output.write("\n")
output.write(str(min(10,len(adj[map2[i]]))))
output.write("\n")
for j in range(min(10,len(adj[map2[i]]))):
# output.write(str(adj[map2[i]][j][0]))
# output.write("\n")
output.write(adj[map2[i]][j][1])
output.write("\n")
# print(i)
# print(adj[map2[i]])
<file_sep>import codecs
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/fill/<string:input>')
def fill(input):
input = input[0:len( input ) - 1]
temp=input
temp="@ @ "+input
s=temp.split(' ')
res=[]
# if (s[len( s ) - 2], s[len( s ) - 1]) in lookUpTable:
# for i in lookUpTable[(s[len( s ) - 2], s[len( s ) - 1])]:
# temp = i
# temp = input + " " + i
# res += [temp]
if(input[len(input)-1]==' '):
if (s[len(s)-3],s[len(s)-2]) in lookUpTable:
for i in lookUpTable[(s[len(s)-3],s[len(s)-2])]:
temp=i
temp=input+i
res+=[temp]
else:
if (s[len(s)-3],s[len(s)-2]) in lookUpTable:
input1 = input[0:len( input ) - len(s[len(s)-1])]
for i in lookUpTable[(s[len(s)-3],s[len(s)-2])]:
if (i.startswith(s[len(s)-1]) and i!=s[len(s)-1]):
temp=i
temp=input1+i
res+=[temp]
if(len(res)==0):
if (s[len( s ) - 2], s[len( s ) - 1]) in lookUpTable:
for i in lookUpTable[(s[len( s ) - 2], s[len( s ) - 1])]:
temp = i
temp = input+" "+ i
res += [temp]
res=str(res)
res=res.replace("'", '"')
return (res)
lookUpTable={}
def init():
f = codecs.open( "res.txt", encoding='utf-8' )
y=f.readline()
y = y[0:len( y ) - 1]
y=int(y)
for j in range(0,y):
s1=f.readline()
s2=f.readline()
s1=s1[0:len(s1)-1]
s2=s2[0:len(s2)-1]
lookUpTable[(s1,s2)]=[]
x=f.readline()
x = x[0:len( x ) - 1]
n=int(x)
for i in range(0,n):
# f.readline() #probability
ch=f.readline()
ch = ch[0:len( ch ) - 1]
lookUpTable[(s1, s2)] += [ch]
f.close()
if __name__ == '__main__':
init()
app.run(debug=True)<file_sep># #!/usr/bin/env python
# # -*- coding: utf-8 -*-
import codecs
import glob
import os
import re
import math
corpus = ""
for file in glob.glob(os.path.join('eco', u'*')):
if os.path.isfile(file):
# print( file )
f=codecs.open(file,encoding='utf-8')
for line in f:
# print( line )
if len(line)> 3:
corpus+=(line)
f.close()
corpus = re.sub("[a-zA-z]|\[\d+\]","",corpus)
corpus = re.sub("\+|ยป|\s.\s|-|โ|_|โข|โ|โ|'|\"|\(|\)|ุ|,|:|/|รณ|รญ|รง|ุ|!|\|"," ",corpus)
corpus = re.sub("\d.\d.\d"," ",corpus)
corpus = re.sub("\d.\d"," ",corpus)
corpus = re.sub("\."," @ @ ",corpus)
corpus = re.sub("\n","\n @ @ ",corpus)
output=codecs.open("monica.txt","w",encoding="UTF-8")
output.write(corpus) | 743badb43e0d0644aca32e2969763ca1242818a8 | [
"Markdown",
"Python"
] | 4 | Markdown | NadaAshrafAhmed/NLP-Autocomplete | 78d65c82a8b1e70b6a005e50107cda3775c33e15 | fbe6ec912ce20ceae577f1e4d09b6102bafe4fcc |
refs/heads/main | <file_sep>package com.dsm.flink;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import java.text.SimpleDateFormat;
import java.util.Date;
public class IotDemo {
public static void main(String[] args) throws Exception {
final StreamExecutionEnvironment env =
StreamExecutionEnvironment.getExecutionEnvironment();
final ParameterTool params = ParameterTool.fromArgs(args);
env.getConfig().setGlobalJobParameters(params);
DataStream<String> dataStream;
if(params.has("input") && params.has("agg")) {
System.out.println("Executing GreenHouse IoT example with file input");
dataStream = env.readTextFile(params.get("input"));
} else {
System.out.println("Use --input to specify file input and --agg for aggregation level");
System.exit(1);
return;
}
DataStream<String[]> iotDataStream = dataStream.filter(new IotDemo.FilterHeader())
.map(new IotDemo.Splitter());
DataStream<Tuple2<String, Double>> result = null;
String aggLevel = params.get("agg");
if ("day".equals(aggLevel)) {
result = iotDataStream.map(new DateTuple())
.keyBy(0)
.sum(1);
} else if ("hour".equals(aggLevel)) {
result = iotDataStream.map(new HourTuple())
.keyBy(0)
.sum(1);
} else if ("minute".equals(aggLevel)) {
result = iotDataStream.map(new MinuteTuple())
.keyBy(0)
.sum(1);
} else {
System.out.println();
}
env.execute("GreenHouse IoT");
result.print();
}
public static class FilterHeader implements FilterFunction<String> {
public boolean filter(String input) throws Exception {
try {
return !input.contains("Date Time");
} catch (Exception ex) {
}
return false;
}
}
public static class Splitter implements MapFunction<String, String[]> {
public String[] map(String sentence) throws Exception {
return sentence.split(",");
}
}
public static class DateTuple implements MapFunction<String[], Tuple2<String, Double>> {
public Tuple2<String, Double> map(String input[]) throws Exception {
double elecCons = Double.parseDouble(input[1].trim());
Date date = new Date( Long.parseLong(input[0]) * 1000 );
return new Tuple2<String, Double>(new SimpleDateFormat("yyyy-MM-dd").format(date), elecCons);
}
}
public static class HourTuple implements MapFunction<String[], Tuple2<String, Double>> {
public Tuple2<String, Double> map(String input[]) throws Exception {
double elecCons = Double.parseDouble(input[1].trim());
Date date = new Date( Long.parseLong(input[0]) * 1000 );
return new Tuple2<String, Double>(new SimpleDateFormat("yyyy-MM-dd HH").format(date), elecCons);
}
}
public static class MinuteTuple implements MapFunction<String[], Tuple2<String, Double>> {
public Tuple2<String, Double> map(String input[]) throws Exception {
double elecCons = Double.parseDouble(input[1].trim());
Date date = new Date( Long.parseLong(input[0]) * 1000 );
return new Tuple2<String, Double>(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(date), elecCons);
}
}
}
| 8ef89f60cf1b9d1555e68170c48e80858326dc34 | [
"Java"
] | 1 | Java | linux6200/test | be6725c6394dbd3c5b74acc0b0d9f944252cd081 | 75e8d0188bd513d795e324266aaafd5435c2968c |
refs/heads/master | <repo_name>cd-chicago-june-cohort/user-project-john<file_sep>/script.js
$(document).ready(function() {
var $form = $("form");
var $table = $("table");
$form.submit(function(event) {
event.preventDefault();
var $firstName = $("#firstName").val();
var $lastName = $("#lastName").val();
var $email = $("#email").val();
var $contact = $("#contact").val();
var newRow = "<tr><td>" + $firstName + "</td><td>" + $lastName + "</td><td>" + $email + "</td><td>" + $contact + "</td></tr>";
$table.append(newRow);
});
}); | 3077f3be5623e1ee4fe77e0ba04d88f51eed96f4 | [
"JavaScript"
] | 1 | JavaScript | cd-chicago-june-cohort/user-project-john | 99c1aea8cb75290d864c263445d4c4e6d077b296 | 5b1a5714f2a21c7b2d01c179a8b0d68b35ffbc5d |
refs/heads/master | <repo_name>candy-wei/dev<file_sep>/wx/src/main/java/com/ningyuan/wx/service/IWxRedPackResultService.java
package com.ningyuan.wx.service;
import com.ningyuan.wx.model.WxRedPackResultModel;
import com.ningyuan.base.IBaseService;
/**
* generated by Generate Service.groovy
* <p>Date: Thu Feb 14 11:29:54 CST 2019.</p>
*
* @author (zengrc)
*/
public interface IWxRedPackResultService extends IBaseService<WxRedPackResultModel> {
}
<file_sep>/wx/src/main/java/com/ningyuan/wx/dto/AccessTokenDto.java
package com.ningyuan.wx.dto;
import java.util.Date;
public class AccessTokenDto {
private String access_token;
private int expires_in;
private Date expire = new Date();
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public int getExpires_in() {
return expires_in;
}
public void setExpires_in(int expires_in) {
this.expire = new Date(expire.getTime() + expires_in*1000 - 100000);
this.expires_in = expires_in;
}
public Date getExpire() {
return expire;
}
public void setExpire(Date expire) {
this.expire = expire;
}
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/daomapper/mapper/ShopAttrKeyMapper.java
package com.ningyuan.mobile.daomapper.mapper;
import com.ningyuan.mobile.model.ShopAttrKey;
import com.ningyuan.mobile.model.ShopAttrVal;
import tk.mybatis.mapper.common.Mapper;
import java.util.List;
public interface ShopAttrKeyMapper extends Mapper<ShopAttrKey> {
List<ShopAttrVal> getAttrVals(Long keyId);
}
<file_sep>/admin/src/main/java/com/ningyuan/route/dto/SettingDto.java
package com.ningyuan.route.dto;
public class SettingDto {
private String performance_ratio;
private String dividend_ratio;
public String getPerformance_ratio() {
return performance_ratio;
}
public void setPerformance_ratio(String performance_ratio) {
this.performance_ratio = performance_ratio;
}
public String getDividend_ratio() {
return dividend_ratio;
}
public void setDividend_ratio(String dividend_ratio) {
this.dividend_ratio = dividend_ratio;
}
}
<file_sep>/wx/src/main/java/com/ningyuan/wx/daomapper/mapper/WxNotifyInfoMapper.java
package com.ningyuan.wx.daomapper.mapper;
import tk.mybatis.mapper.common.Mapper;
import com.ningyuan.wx.model.WxNotifyInfoModel;
/**
* generated by Generate Mapper.groovy
* <p>Date: Tue Nov 20 14:30:10 CST 2018.</p>
*
* @author (zengrc)
*/
public interface WxNotifyInfoMapper extends Mapper<WxNotifyInfoModel> {
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/dto/OrderGoodsDto.java
package com.ningyuan.mobile.dto;
public class OrderGoodsDto {
private Long id;
private String descript;
private String detail;
private String gallery;
private Long idCategory;
private Boolean isOnSale;
private String name;
private String pic;
/**
* ไปทๆ ผ
*/
private String price;
/**
* ๆฐ้
*/
private Integer count;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getDescript() { return descript; }
public void setDescript(String descript) { this.descript = descript; }
public String getDetail() { return detail; }
public void setDetail(String detail) { this.detail = detail; }
public String getGallery() { return gallery; }
public void setGallery(String gallery) { this.gallery = gallery; }
public Long getIdCategory() { return idCategory; }
public void setIdCategory(Long idCategory) { this.idCategory = idCategory; }
public Boolean getOnSale() {
return isOnSale;
}
public void setOnSale(Boolean onSale) {
isOnSale = onSale;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getPic() { return pic; }
public void setPic(String pic) { this.pic = pic; }
public String getPrice() { return price; }
public void setPrice(String price) { this.price = price; }
public Integer getCount() { return count; }
public void setCount(Integer count) { this.count = count; }
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/controller/FavoriteController.java
package com.ningyuan.mobile.controller;
import com.ningyuan.base.BaseController;
import com.ningyuan.bean.front.Rets;
import com.ningyuan.core.Context;
import com.ningyuan.mobile.model.ShopFavoriteModel;
import com.ningyuan.mobile.service.IShopFavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user/favorite")
public class FavoriteController extends BaseController {
@Autowired
private IShopFavoriteService favoriteService;
@RequestMapping(value = "/add/{idGoods}",method = RequestMethod.POST)
public Object add(@PathVariable("idGoods") Long idGoods){
String openId = Context.getOpenId();
ShopFavoriteModel model = new ShopFavoriteModel();
model.setOpenId(openId);
model.setIdGoods(idGoods);
ShopFavoriteModel old = favoriteService.selectLimitOne(model);
if(old!=null){
return Rets.success();
}
ShopFavoriteModel favorite = new ShopFavoriteModel();
favorite.setOpenId(openId);
favorite.setIdGoods(idGoods);
favoriteService.insertSelective(favorite);
return Rets.success();
}
@RequestMapping(value = "/ifLike/{idGoods}",method = RequestMethod.GET)
public Object ifLike(@PathVariable("idGoods") Long idGoods){
String openId = Context.getOpenId();
ShopFavoriteModel model = new ShopFavoriteModel();
model.setOpenId(openId);
model.setIdGoods(idGoods);
ShopFavoriteModel favorite = favoriteService.selectLimitOne(model);
return Rets.success(favorite!=null);
}
}
<file_sep>/wx/src/main/java/com/ningyuan/wx/service/impl/WxsaSubscribeServiceImpl.java
package com.ningyuan.wx.service.impl;
import com.ningyuan.base.BaseServiceImpl;
import com.ningyuan.wx.daomapper.mapper.WxsaSubscribeMapper;
import com.ningyuan.wx.model.wxsa.WxsaSubscribeModel;
import com.ningyuan.wx.service.IWxsaSubscribeService;
import org.springframework.stereotype.Service;
/**
* generated by Generate Service.groovy
* <p>Date: Mon Oct 07 17:14:41 CST 2019.</p>
*
* @author (zengrc)
*/
@Service
public class WxsaSubscribeServiceImpl extends BaseServiceImpl<WxsaSubscribeMapper, WxsaSubscribeModel> implements IWxsaSubscribeService {
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/service/impl/ShopReceiveRecordServiceImpl.java
package com.ningyuan.mobile.service.impl;
import com.ningyuan.base.BaseServiceImpl;
import com.ningyuan.mobile.daomapper.mapper.ShopReceiveRecordMapper;
import com.ningyuan.mobile.model.ShopReceiveRecordModel;
import com.ningyuan.mobile.service.IShopReceiveRecordService;
import org.springframework.stereotype.Service;
/**
* generated by Generate Service.groovy
* <p>Date: Fri Apr 03 15:21:29 CST 2020.</p>
*
* @author (zengrc)
*/
@Service
public class ShopReceiveRecordServiceImpl extends BaseServiceImpl<ShopReceiveRecordMapper, ShopReceiveRecordModel> implements IShopReceiveRecordService {
@Override
public void insertRecord(String optType, String amount, String openId) {
ShopReceiveRecordModel recordModel = new ShopReceiveRecordModel();
recordModel.setAmount(amount);
recordModel.setOpenId(openId);
recordModel.setOptType(optType);
this.mapper.insertSelective(recordModel);
}
}
<file_sep>/admin/src/main/webapp/app/customer/js/orderInfoService.js
(function () {
app.service('orderInfoService', orderInfoServiceFn);
function orderInfoServiceFn($req) {
this.getOrderList = function ($scope) {
$scope.initList('/customer/order/list', {});
}
this.saveOrder = function (data) {
return $req.post('/customer/order/update', data);
}
}
}());<file_sep>/admin/src/main/webapp/app/menu/js/menuCtrl.js
"use strict"
app.controller('menuCtrl', function ($scope, $location, menus) {
$scope.cssPath = appPath;
$scope.cssVersion = version;
$scope.path = path;
$scope.initMenu = function () {
$scope.wHeigth = document.documentElement.clientHeight - $("#nav-header").height() - 1;
menus.getMenus().then(function (response) {
$scope.menus = menus.sortMenu(response.data);
$scope.mainActive = 0;
$scope.subActive = 0;
$scope.menuShow($scope.mainActive);
}
)
menus.getUser().then(function (response) {
$scope.user = response.data;
}
)
}
$scope.menuShow = function (menuIndex) {
$scope.menus[$scope.mainActive].active = "main-menu";
$scope.menus[menuIndex].active = "main-active";
$scope.menuName = $scope.menus[menuIndex].name;
$scope.childrens = $scope.menus[menuIndex].childrens;
$scope.subMenuShow(menuIndex, 0);
};
$scope.subMenuShow = function (menuIndex, subIndex) {
if ($scope.menus[$scope.mainActive].childrens.length > 0) {
$scope.menus[$scope.mainActive].childrens[$scope.subActive].active = "sub-menu";
}
if ($scope.menus[menuIndex].childrens.length > 0) {
$scope.menus[menuIndex].childrens[subIndex].active = "sub-active";
}
$scope.mainActive = menuIndex;
$scope.subActive = subIndex;
$scope.subName = $scope.menus[$scope.mainActive].childrens[$scope.subActive].name;
if ($scope.menus[$scope.mainActive].childrens.length > 0) {
$location.path($scope.menus[$scope.mainActive].childrens[$scope.subActive].url);
} else{
$location.path("/");
}
}
$scope.logout = function(){
$("#logout").submit();
}
})
<file_sep>/wx/src/main/java/com/ningyuan/wx/dto/WxHeadDto.java
package com.ningyuan.wx.dto;
/**
* generated by Generate POJOs.groovy
* <p>Date: Wed Oct 24 09:50:21 CST 2018.</p>
*
* @author (zengrc)
*/
public class WxHeadDto {
private String openId;
private String nickname;
public String getNickname() { return nickname; }
public void setNickname(String nickname) { this.nickname = nickname; }
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
private String headimgurl;
public String getHeadimgurl() {
return headimgurl;
}
public void setHeadimgurl(String headimgurl) {
this.headimgurl = headimgurl;
}
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/dto/UserInfoDto.java
package com.ningyuan.mobile.dto;
public class UserInfoDto {
private String openId;
private String nickName;
private String headImgUrl;
private String vip;
private String vipName;
private Integer points;
private Integer redpacketAmount;
private Integer redpacketReceive;
private Integer redpacketDaily;
public String getOpenId() { return openId; }
public void setOpenId(String openId) { this.openId = openId; }
public String getNickName() { return nickName; }
public void setNickName(String nickName) { this.nickName = nickName; }
public String getVip() { return vip; }
public void setVip(String vip) { this.vip = vip; }
public Integer getPoints() { return points; }
public void setPoints(Integer points) { this.points = points; }
public Integer getRedpacketAmount() { return redpacketAmount; }
public void setRedpacketAmount(Integer redpacketAmount) { this.redpacketAmount = redpacketAmount; }
public Integer getRedpacketReceive() { return redpacketReceive; }
public void setRedpacketReceive(Integer redpacketReceive) { this.redpacketReceive = redpacketReceive; }
public String getHeadImgUrl() { return headImgUrl; }
public void setHeadImgUrl(String headImgUrl) { this.headImgUrl = headImgUrl; }
public Integer getRedpacketDaily() { return redpacketDaily; }
public void setRedpacketDaily(Integer redpacketDaily) { this.redpacketDaily = redpacketDaily; }
public String getVipName() { return vipName; }
public void setVipName(String vipName) { this.vipName = vipName; }
}
<file_sep>/admin/src/main/webapp/app/ningyuan/js/userService.js
(function () {
app.service('userService', userServiceFn);
function userServiceFn($req) {
}
}());<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/service/impl/GoodsServiceImpl.java
package com.ningyuan.mobile.service.impl;
import com.ningyuan.base.BaseServiceImpl;
import com.ningyuan.mobile.daomapper.mapper.GoodsMapper;
import com.ningyuan.mobile.dto.GoodsDto;
import com.ningyuan.mobile.model.ShopGoodsModel;
import com.ningyuan.mobile.service.IGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class GoodsServiceImpl extends BaseServiceImpl<GoodsMapper, ShopGoodsModel> implements IGoodsService {
@Autowired
private GoodsMapper goodsMapper;
@Override
public List<GoodsDto> getGoods(Long idCategory, Boolean isOnSale) {
return goodsMapper.getGoods(idCategory, isOnSale);
}
}
<file_sep>/wx/src/main/java/com/ningyuan/wx/model/wxsa/WxsaOutMsgModel.java
package com.ningyuan.wx.model.wxsa;
import com.ningyuan.base.BaseModel;
import com.ningyuan.base.annotation.FiledComment;
import javax.persistence.Column;
import javax.persistence.Table;
import java.util.Date;
/**
* generated by Generate POJOs.groovy
* <p>Date: Fri Aug 30 16:47:05 CST 2019.</p>
*
* @author (zengrc)
*/
@Table ( name ="wxsa_out_msg" )
public class WxsaOutMsgModel extends BaseModel {
/**
* ๆฅๆถๅฐ็ๆถๆฏไบไปถ
*/
@FiledComment(text = "ๆฅๆถๅฐ็ๆถๆฏไบไปถ" )
@Column(name = "in_event_type" )
private String inEventType;
/**
* ๆฅๆถๅฐ็ๆถๆฏ็ฑปๅ
*/
@FiledComment(text = "ๆฅๆถๅฐ็ๆถๆฏ็ฑปๅ" )
@Column(name = "in_msg_type" )
private String inMsgType;
/**
* ่ๅๅฏนๅบ็eventkey
*/
@FiledComment(text = "่ๅๅฏนๅบ็eventkey" )
@Column(name = "in_event_key" )
private String inEventKey;
/**
* ๅ
ณ้ฎ่ฏ
*/
@FiledComment(text = "ๅ
ณ้ฎ่ฏ" )
@Column(name = "key_word" )
private String keyWord;
/**
* ๅๅบๆถๆฏ็ฑปๅ
*/
@FiledComment(text = "ๅๅบๆถๆฏ็ฑปๅ" )
@Column(name = "out_msg_type" )
private String outMsgType;
/**
* ๅๅบ็ๆๆฌๆถๆฏๅ
ๅฎน
*/
@FiledComment(text = "ๅๅบ็ๆๆฌๆถๆฏๅ
ๅฎน" )
@Column(name = "content" )
private String content;
/**
* ็ด ๆmedia_id
*/
@FiledComment(text = "็ด ๆmedia_id" )
@Column(name = "media_id" )
private String mediaId;
/**
* ๅๅบ็ๅพๆๆถๆฏๅ
ๅฎน
*/
@FiledComment(text = "ๅๅบ็ๅพๆๆถๆฏๅ
ๅฎน" )
@Column(name = "articles" )
private String articles;
@Column(name = "create_time" )
private Date createTime;
@Column(name = "update_time" )
private Date updateTime;
public String getInEventType() {
return this.inEventType;
}
public void setInEventType(String inEventType) {
this.inEventType = inEventType;
}
public String getInMsgType() {
return this.inMsgType;
}
public void setInMsgType(String inMsgType) {
this.inMsgType = inMsgType;
}
public String getInEventKey() {
return this.inEventKey;
}
public void setInEventKey(String inEventKey) {
this.inEventKey = inEventKey;
}
public String getKeyWord() {
return this.keyWord;
}
public void setKeyWord(String keyWord) {
this.keyWord = keyWord;
}
public String getOutMsgType() {
return this.outMsgType;
}
public void setOutMsgType(String outMsgType) {
this.outMsgType = outMsgType;
}
public String getContent() {
return this.content;
}
public void setContent(String content) {
this.content = content;
}
public String getMediaId() {
return this.mediaId;
}
public void setMediaId(String mediaId) {
this.mediaId = mediaId;
}
public String getArticles() {
return this.articles;
}
public void setArticles(String articles) {
this.articles = articles;
}
public Date getCreateTime() {
return this.createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return this.updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
<file_sep>/wx/src/main/java/com/ningyuan/wx/model/WxRedPackResultModel.java
package com.ningyuan.wx.model;
import com.ningyuan.base.BaseModel;
import javax.persistence.Column;
import javax.persistence.Table;
import java.util.Date;
/**
* generated by Generate POJOs.groovy
* <p>Date: Thu Feb 14 12:00:07 CST 2019.</p>
*
* @author (zengrc)
*/
@Table ( name ="wx_red_pack_result" )
public class WxRedPackResultModel extends BaseModel {
@Column(name = "promote_type" )
private String promoteType;
@Column(name = "open_id" )
private String openId;
/**
* ๅๆท่ฎขๅๅท
*/
@Column(name = "mch_billno" )
private String mchBillno;
/**
* ไธๅก็ปๆ
*/
@Column(name = "result_code" )
private String resultCode;
/**
* ้่ฏฏไปฃ็
*/
@Column(name = "err_code" )
private String errCode;
/**
* total_amount
*/
@Column(name = "total_amount" )
private String totalAmount;
@Column(name = "success_time" )
private Date successTime;
@Column(name = "created_time" )
private Date createdTime;
@Column(name = "update_time" )
private Date updateTime;
public String getPromoteType() {
return this.promoteType;
}
public void setPromoteType(String promoteType) {
this.promoteType = promoteType;
}
public String getOpenId() {
return this.openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getMchBillno() {
return this.mchBillno;
}
public void setMchBillno(String mchBillno) {
this.mchBillno = mchBillno;
}
public String getResultCode() {
return this.resultCode;
}
public void setResultCode(String resultCode) {
this.resultCode = resultCode;
}
public String getErrCode() {
return this.errCode;
}
public void setErrCode(String errCode) {
this.errCode = errCode;
}
public String getTotalAmount() {
return this.totalAmount;
}
public void setTotalAmount(String totalAmount) {
this.totalAmount = totalAmount;
}
public Date getSuccessTime() {
return this.successTime;
}
public void setSuccessTime(Date successTime) {
this.successTime = successTime;
}
public Date getCreatedTime() {
return this.createdTime;
}
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
public Date getUpdateTime() {
return this.updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/service/IShopWalletService.java
package com.ningyuan.mobile.service;
import com.ningyuan.base.IBaseService;
import com.ningyuan.mobile.dto.RedPacketDto;
import com.ningyuan.mobile.model.ShopWalletModel;
import java.util.List;
/**
* generated by Generate Service.groovy
* <p>Date: Fri Apr 03 14:41:01 CST 2020.</p>
*
* @author (zengrc)
*/
public interface IShopWalletService extends IBaseService<ShopWalletModel> {
List<RedPacketDto> getCashList(String openId);
String getCashSum();
void updateWallet(String openId);
}
<file_sep>/mobile-core/src/main/java/com/ningyuan/base/annotation/ExampleQuery.java
package com.ningyuan.base.annotation;
import java.lang.annotation.*;
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExampleQuery {
String method() default "andEqualTo";
Class valueClass() default Object.class;
boolean hasValue() default true;
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/daomapper/mapper/ShopReceiveRecordMapper.java
package com.ningyuan.mobile.daomapper.mapper;
import tk.mybatis.mapper.common.Mapper;
import com.ningyuan.mobile.model.ShopReceiveRecordModel;
/**
* generated by Generate Mapper.groovy
* <p>Date: Fri Apr 03 15:21:29 CST 2020.</p>
*
* @author (zengrc)
*/
public interface ShopReceiveRecordMapper extends Mapper<ShopReceiveRecordModel> {
}
<file_sep>/mobile-core/src/main/java/com/ningyuan/base/datasource/DataSourceSwitchAspect.java
package com.ningyuan.base.datasource;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Aspect
@Order(1)
@Component
public class DataSourceSwitchAspect {
@Before("execution(* com.ningyuan.*.daomapper.mapper.*.*(..))")
public void mapper() {
DataSourceSwitcher.setDataSourceKey(DataSourceType.SOURCE_MAPPER);
}
@Before("execution(* com.ningyuan.*.daomapper.dao.*.*(..))")
public void dao(){
DataSourceSwitcher.setDataSourceKey(DataSourceType.SOURCE_DAO);
}
@Before("execution(* com.ningyuan.*.daomapper.orm.*.*(..))")
public void orm(){
DataSourceSwitcher.setDataSourceKey(DataSourceType.SOURCE);
}
}
<file_sep>/admin/src/main/webapp/app/ningyuan/js/userCtrl.js
(function () {
app.controller('userCtrl', userCtrlFn);
function userCtrlFn($scope, userService) {
}
}());<file_sep>/mobile-core/src/main/java/com/ningyuan/utils/StringUtil.java
package com.ningyuan.utils;
import org.apache.commons.lang.StringUtils;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* ๅญ็ฌฆไธฒ่ฝฌๆข็ฑป
* <p>
* ้กน็ฎๅ็งฐ๏ผWeiChatService
* ็ฑปๅ็งฐ๏ผStringUtil
* ็ฑปๆ่ฟฐ๏ผ
* ๅๅปบไบบ๏ผzhouling
* ๅๅปบๆถ้ด๏ผNov 12, 2013 5:16:48 PM
* ไฟฎๆนๅคๆณจ๏ผ
*/
public class StringUtil {
/**
* ๅฐๅญ่ๆฐ็ป่ฝฌๆขไธบๅๅ
ญ่ฟๅถๅญ็ฌฆไธฒ
*
* @param byteArray
* @return
*/
public static String byteToStr(byte[] byteArray) {
String strDigest = "";
for (int i = 0; i < byteArray.length; i++) {
strDigest += byteToHexStr(byteArray[i]);
}
return strDigest;
}
/**
* ๅฐๅญ่่ฝฌๆขไธบๅๅ
ญ่ฟๅถๅญ็ฌฆไธฒ
*
* @param mByte
* @return
*/
public static String byteToHexStr(byte mByte) {
char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
char[] tempArr = new char[2];
tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
tempArr[1] = Digit[mByte & 0X0F];
String s = new String(tempArr);
return s;
}
/**
* ่ฎก็ฎ้็จutf-8็ผ็ ๆนๅผๆถๅญ็ฌฆไธฒๆๅ ๅญ่ๆฐ
*
* @param content
* @return
*/
public static int getByteSize(String content) {
int size = 0;
if (null != content) {
try {
// ๆฑๅญ้็จutf-8็ผ็ ๆถๅ 3ไธชๅญ่
size = content.getBytes("utf-8").length;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return size;
}
public static String replaceAll(String template, Map<String, String> params) {
Pattern pattern = Pattern.compile("\\$\\{(.*?)}");
Matcher matcher = pattern.matcher(template);
while (matcher.find()) {
if (params.containsKey(matcher.group(1))) {
template = template.replace(matcher.group(), params.get(matcher.group(1)));
}
}
return template;
}
public static String replaceAll(String template, Map<String, String> params, String... others) {
template = replaceAll(template, params);
template = replaceAll(template, others);
return template;
}
public static String replaceAll(String template, Object dto) {
if (dto == null) {
return template;
}
if (dto instanceof String) {
return replaceAll(template, (String) dto, "");
}
Pattern pattern = Pattern.compile("\\$\\{(.*?)}");
Matcher matcher = pattern.matcher(template);
Class<?> clazz = dto.getClass();
while (matcher.find()) {
try {
Field field = clazz.getDeclaredField(matcher.group(1));
field.setAccessible(true);
if (null == field.get(dto)) {
continue;
}
template = template.replace(matcher.group(), (String) field.get(dto));
} catch (Exception e) {
}
}
return template;
}
public static String replaceAll(String template, String... params) {
List<String> paramList = Arrays.asList(params);
Pattern pattern = Pattern.compile("\\$\\{(.*?)}");
Matcher matcher = pattern.matcher(template);
int i = 0;
while (matcher.find()) {
template = template.replace(matcher.group(), paramList.get(i));
i++;
}
return template;
}
public static String inputStreamToString(InputStream is) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = in.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
}
public static String codeParseURLDecoderDecode(String URI) throws UnsupportedEncodingException {
if (StringUtils.isNotEmpty(URI)) {
return URI;
}
return URLDecoder.decode(URI, "UTF-8");
}
public static Map<String, String> requestParams2Map(Map requerstParams) {
Map<String, String> params = new HashMap<String, String>();
if (null != requerstParams) {
for (Object o : requerstParams.entrySet()) {
Map.Entry<String, String[]> entry = (Map.Entry) o;
String value = "";
for (String s : entry.getValue()) {
value += s;
}
params.put(entry.getKey(), value);
}
}
return params;
}
/**
* ๆฏๅฆไธบ้็ฉบๅญ็ฌฆ
*/
public static boolean isNotEmpty(String str) {
return (!isEmpty(str));
}
/**
* ๆฏๅฆไธบ็ฉบๅญ็ฌฆ
*/
public static boolean isEmpty(String str) {
if (str == null || str.trim().length() == 0) {
return true;
}
if ("null".equalsIgnoreCase(str) || "undefined".equalsIgnoreCase(str)) {
return true;
}
return false;
}
}
<file_sep>/admin/src/main/webapp/app/customer/js/orderInfoCtrl.js
(function () {
app.controller('orderInfoCtrl', orderInfoCtrlFn);
function orderInfoCtrlFn($scope, orderInfoService) {
$scope.orderModel = {};
$scope.statusOpt = [{'value': '1', 'text': 'ๅพ
ไปๆฌพ'},{'value': '2', 'text': 'ๅพ
ๅ่ดง'},{'value': '3', 'text': 'ๅทฒๅ่ดง'},
{'value': '4', 'text': 'ๅทฒๅฎๆ'},{'value': '5', 'text': 'ๅๆถ'}]
$scope.booleanOptions = [{'value': '1', 'text': 'ๆฏ'},{'value': '0', 'text': 'ๅฆ'}]
orderInfoService.getOrderList($scope);
this.save = function () {
orderInfoService.saveOrder($scope.orderModel).then(function (response) {
if (response.data.errorCode === 'SUCCESS') {
alert('ไฟฎๆนๆๅ')
$scope.pageInfo.list[$scope.currentIndex].status = $scope.orderModel.status;
}
$('#updateModal').modal('hide');
});
}
this.update = function (index) {
$scope.currentIndex = index;
$('.modal-body .form-control').each(function () {
$scope.orderModel[$(this).attr('name')] = $scope.pageInfo.list[index][$(this).attr('name')];
})
$('#updateModal').modal();
}
}
}());<file_sep>/wx/src/main/java/com/ningyuan/wx/model/WxPay2userResultModel.java
package com.ningyuan.wx.model;
import com.ningyuan.base.BaseModel;
import com.ningyuan.base.annotation.FiledComment;
import javax.persistence.Column;
import javax.persistence.Table;
import java.util.Date;
/**
* generated by Generate POJOs.groovy
* <p>Date: Wed May 15 08:51:08 CST 2019.</p>
*
* @author (zengrc)
*/
@Table ( name ="wx_pay2user_result" )
public class WxPay2userResultModel extends BaseModel {
@Column(name = "promote_type" )
private String promoteType;
@Column(name = "open_id" )
private String openId;
/**
* ๅๅ ,้ๅธธไธบ็ธๅ
ณ็จๆทopen_id
*/
@FiledComment(text = "ๅๅ ,้ๅธธไธบ็ธๅ
ณ็จๆทopen_id" )
@Column(name = "reason" )
private String reason;
@Column(name = "mch_appid" )
private String mchAppid;
/**
* ๅๆท่ฎขๅๅท
*/
@FiledComment(text = "ๅๆท่ฎขๅๅท" )
@Column(name = "partner_trade_no" )
private String partnerTradeNo;
@Column(name = "amount" )
private String amount;
/**
* ไผไธไปๆฌพๅคๆณจ
*/
@FiledComment(text = "ไผไธไปๆฌพๅคๆณจ" )
@Column(name = "res_desc" )
private String resDesc;
@Column(name = "result_code" )
private String resultCode;
@Column(name = "err_code" )
private String errCode;
/**
* ๆฅๅฃ่ฐ็จ็ปๆjson
*/
@FiledComment(text = "ๆฅๅฃ่ฐ็จ็ปๆjson" )
@Column(name = "result_text" )
private String resultText;
@Column(name = "success_time" )
private Date successTime;
@Column(name = "create_time" )
private Date createTime;
@Column(name = "update_time" )
private Date updateTime;
public String getPromoteType() {
return this.promoteType;
}
public void setPromoteType(String promoteType) {
this.promoteType = promoteType;
}
public String getOpenId() {
return this.openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getReason() {
return this.reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public String getMchAppid() {
return this.mchAppid;
}
public void setMchAppid(String mchAppid) {
this.mchAppid = mchAppid;
}
public String getPartnerTradeNo() {
return this.partnerTradeNo;
}
public void setPartnerTradeNo(String partnerTradeNo) {
this.partnerTradeNo = partnerTradeNo;
}
public String getAmount() {
return this.amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getResDesc() {
return this.resDesc;
}
public void setResDesc(String resDesc) {
this.resDesc = resDesc;
}
public String getResultCode() {
return this.resultCode;
}
public void setResultCode(String resultCode) {
this.resultCode = resultCode;
}
public String getErrCode() {
return this.errCode;
}
public void setErrCode(String errCode) {
this.errCode = errCode;
}
public String getResultText() {
return this.resultText;
}
public void setResultText(String resultText) {
this.resultText = resultText;
}
public Date getSuccessTime() {
return this.successTime;
}
public void setSuccessTime(Date successTime) {
this.successTime = successTime;
}
public Date getCreateTime() {
return this.createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return this.updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/service/impl/ShopWalletServiceImpl.java
package com.ningyuan.mobile.service.impl;
import com.ningyuan.base.BaseServiceImpl;
import com.ningyuan.core.Context;
import com.ningyuan.mobile.daomapper.mapper.ShopWalletMapper;
import com.ningyuan.mobile.dto.RedPacketDto;
import com.ningyuan.mobile.model.ShopWalletModel;
import com.ningyuan.mobile.service.IShopWalletService;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import java.util.List;
/**
* generated by Generate Service.groovy
* <p>Date: Fri Apr 03 14:41:01 CST 2020.</p>
*
* @author (zengrc)
*/
@Service
public class ShopWalletServiceImpl extends BaseServiceImpl<ShopWalletMapper, ShopWalletModel> implements IShopWalletService {
@Override
public List<RedPacketDto> getCashList(String openId) {
return this.mapper.getCashList(openId);
}
@Override
public String getCashSum() {
return this.mapper.getCashSum(Context.getOpenId());
}
@Override
public void updateWallet(String openId) {
Example example = new Example(ShopWalletModel.class);
Example.Criteria criteria = example.createCriteria();
criteria.andEqualTo("openId", openId);
ShopWalletModel walletModel = new ShopWalletModel();
walletModel.setFinance("0");
this.mapper.updateByExampleSelective(walletModel, example);
}
}
<file_sep>/admin/src/main/java/com/ningyuan/route/dto/ShopMarketRatio.java
package com.ningyuan.route.dto;
import java.util.List;
public class ShopMarketRatio {
private List<ShopMarketRatioDto> marketRatio;
public List<ShopMarketRatioDto> getMarketRatio() {
return marketRatio;
}
public void setMarketRatio(List<ShopMarketRatioDto> marketRatio) {
this.marketRatio = marketRatio;
}
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/daomapper/mapper/FileMapper.java
package com.ningyuan.mobile.daomapper.mapper;
import com.ningyuan.mobile.model.SysFileInfoModel;
import tk.mybatis.mapper.common.Mapper;
public interface FileMapper extends Mapper<SysFileInfoModel> {
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/service/impl/CategoryServiceImpl.java
package com.ningyuan.mobile.service.impl;
import com.ningyuan.base.BaseServiceImpl;
import com.ningyuan.mobile.daomapper.mapper.CategoryMapper;
import com.ningyuan.mobile.model.CmsBannerModel;
import com.ningyuan.mobile.model.ShopCategoryModel;
import com.ningyuan.mobile.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CategoryServiceImpl extends BaseServiceImpl<CategoryMapper, ShopCategoryModel> implements ICategoryService {
@Autowired
private CategoryMapper categoryMapper;
@Override
public List<ShopCategoryModel> listCategory() {
return this.mapper.selectAll();
}
@Override
public List<CmsBannerModel> listBannerRel(Long id) {
return categoryMapper.listBannerRel(id);
}
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/controller/ShopCustomerController.java
package com.ningyuan.mobile.controller;
import com.ningyuan.base.BaseController;
import com.ningyuan.bean.front.Ret;
import com.ningyuan.bean.front.Rets;
import com.ningyuan.core.Conf;
import com.ningyuan.core.Context;
import com.ningyuan.mobile.model.ShopCustomerModel;
import com.ningyuan.mobile.service.IShopCustomerService;
import com.ningyuan.utils.ParamsUtils;
import com.ningyuan.utils.TemplateUtils;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
/**
* generated by Generate Controller.groovy
* <p>Date: Fri Apr 03 11:10:05 CST 2020.</p>
*
* @author (zengrc)
*/
@Controller
@RequestMapping("shop/user")
public class ShopCustomerController extends BaseController {
@Autowired
private IShopCustomerService shopCustomerService;
@RequestMapping(value = "index/{openId}",method = RequestMethod.GET)
@ResponseBody
public ModelAndView callbackHandle(@PathVariable("openId") String openId){
// ไฟๅญ็จๆทไฟกๆฏ
ShopCustomerModel customerModel = new ShopCustomerModel();
customerModel.setOpenId(openId);
ShopCustomerModel queryCustomer = shopCustomerService.selectOne(customerModel);
if (queryCustomer == null) {
shopCustomerService.insertSelective(customerModel);
}
return new ModelAndView("redirect:".concat(ParamsUtils.getRomote())
.concat(TemplateUtils.replaceAll("/dist/index.html?openId=${openId}", openId)));
}
@RequestMapping(value = "getInfo",method = RequestMethod.POST)
@ResponseBody
public Ret getUserInfo(){
String openId = Context.getOpenId();
return Rets.success(shopCustomerService.queryUserInfo(openId));
}
@RequestMapping(value = "list/task",method = RequestMethod.POST)
@ResponseBody
public Ret getTaskStatus(){
String openId = Context.getOpenId();
return Rets.success(shopCustomerService.getTaskStatus(openId));
}
@RequestMapping(value = "tasks",method = RequestMethod.POST)
@ResponseBody
public Ret listTask(){
String openId = Context.getOpenId();
return Rets.success(shopCustomerService.listTask(openId));
}
@RequestMapping(value = "recommend",method = RequestMethod.POST)
@ResponseBody
public Ret getRecommend(){
String openId = Context.getOpenId();
return Rets.success(shopCustomerService.getRecommend(openId));
}
@RequestMapping(value = "team",method = RequestMethod.POST)
@ResponseBody
public Ret getTeam(){
String openId = Context.getOpenId();
return Rets.success(shopCustomerService.getTeam(openId));
}
@RequestMapping("getShareParam")
@ResponseBody
public Object getShareParam() {
String openId = Context.getOpenId();
return TemplateUtils.replaceAll(Conf.get("shop.share.url"), openId);
}
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/model/ShopCategoryModel.java
package com.ningyuan.mobile.model;
import javax.persistence.Column;
import com.ningyuan.base.annotation.FiledComment;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.ningyuan.base.BaseModel;
import java.util.Date;
import java.util.List;
/**
* generated by Generate POJOs.groovy
* <p>Date: Wed Mar 18 11:33:46 CST 2020.</p>
*
* @author (zengrc)
*/
@Table ( name ="shop_category" )
public class ShopCategoryModel extends BaseModel {
/**
* ๅพๆ
*/
@FiledComment(text = "ๅพๆ " )
@Column(name = "icon" )
private String icon;
/**
* ๅ็งฐ
*/
@FiledComment(text = "ๅ็งฐ" )
@Column(name = "name" )
private String name;
/**
* ้พๆฅๅฐๅ
*/
@FiledComment(text = "้พๆฅๅฐๅ" )
@Column(name = "url" )
private String url;
@Transient
private List<CmsBannerModel> bannerList;
public String getIcon() {
return this.icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
public List<CmsBannerModel> getBannerList() { return bannerList; }
public void setBannerList(List<CmsBannerModel> bannerList) { this.bannerList = bannerList; }
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/daomapper/mapper/ShopGoodsSkuMapper.java
package com.ningyuan.mobile.daomapper.mapper;
import tk.mybatis.mapper.common.Mapper;
import com.ningyuan.mobile.model.ShopGoodsSkuModel;
/**
* generated by Generate Mapper.groovy
* <p>Date: Sat Mar 21 14:55:34 CST 2020.</p>
*
* @author (zengrc)
*/
public interface ShopGoodsSkuMapper extends Mapper<ShopGoodsSkuModel> {
}
<file_sep>/wx/src/main/java/com/ningyuan/wx/utils/WxUtils.java
package com.ningyuan.wx.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.ningyuan.base.exception.ErrorMessage;
import com.ningyuan.base.exception.StatelessException;
import com.ningyuan.core.Conf;
import com.ningyuan.core.Context;
import com.ningyuan.utils.*;
import com.ningyuan.wx.dto.*;
import com.ningyuan.wx.model.WxRedPackResultModel;
import com.ningyuan.wx.model.WxUserModel;
import com.ningyuan.wx.service.IWxRedPackResultService;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.mp.api.WxMpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.servlet.ModelAndView;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class WxUtils {
protected static Logger log = LoggerFactory.getLogger(WxUtils.class);
private static AccessTokenDto accessTokenDto = null;
private static JsApiTicketDto jsApiTicketDto = null;
public static <T> T post(String url, Object params, Class<T> tClass) {
HttpEntity httpEntity = new HttpEntity(params, RESTUtils.header());
ResponseEntity<String> responseEntity = RESTUtils.rest().postForEntity(url, httpEntity, String.class);
return JSON.parseObject(responseEntity.getBody()).toJavaObject(tClass);
}
public static <T> T get(String url, Class<T> tClass) {
ResponseEntity<String> responseEntity = RESTUtils.rest().getForEntity(url, String.class);
return JSON.parseObject(responseEntity.getBody()).toJavaObject(tClass);
}
private static AccessTokenDto getAccessToken() {
accessTokenDto = new AccessTokenDto();
try {
accessTokenDto.setAccess_token(Context.getBean(WxMpService.class).getAccessToken());
accessTokenDto.setExpire(new Date());
accessTokenDto.setExpires_in(0);
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new RuntimeException(e);
}
return accessTokenDto;
}
public static <T> T postWithToken(String url, Object params, Class<T> tClass) {
AccessTokenDto accessTokenDto = getAccessToken();
url = TemplateUtils.replaceAll(url, accessTokenDto.getAccess_token());
JSONObject object = post(url, params, JSONObject.class);
if (!object.get("errmsg").equals("OK")) {
WxUtils.accessTokenDto = null;
accessTokenDto = getAccessToken();
url = TemplateUtils.replaceAll(url, accessTokenDto.getAccess_token());
return post(url, params, tClass);
}
return object.toJavaObject(tClass);
}
public static GetBrandWCPayRequestDto getPayRequestDto(String attach, String openId, String price) throws Exception {
return getPayRequestDto(attach, openId, price, null);
}
/**
* @param attach
* @param openId
* @param price
* @param payType ็ฑปๅซ:"applet"ไธบๅฐ็จๅบ,ๅฆๅไธบๅ
ฌไผๅท
* @return
* @throws Exception
*/
public static GetBrandWCPayRequestDto getPayRequestDto(String attach, String openId, String price, String payType) throws Exception {
UnifiedorderDto dto = new UnifiedorderDto();
GetBrandWCPayRequestDto payRequestDto = new GetBrandWCPayRequestDto();
dto.setAppid(Conf.get("wxsa.appId"));
dto.setMch_id(Conf.get("wx.partner"));
dto.setNonce_str(getNonceStr());
dto.setBody(Conf.get("wx.pay.body"));
dto.setFee_type("CNY");
dto.setAttach(attach);
dto.setOut_trade_no(CreateGUID.createGuId());
dto.setTotal_fee((int) (Double.parseDouble(price) + Double.parseDouble(Conf.get("shop.goods.fare"))) + "");
dto.setTrade_type("JSAPI");
dto.setNotify_url(TemplateUtils.replaceAll(Conf.get("wx.notify.uri")));
dto.setOpenid(openId);
dto.setSpbill_create_ip("127.0.0.1");
Map<String, String> result = getPrepareId(dto);
payRequestDto.setAppId(dto.getAppid());
payRequestDto.setTimeStamp(new Date().getTime() + "");
payRequestDto.setNonceStr(getNonceStr());
payRequestDto.setSignType(WXPayConstants.MD5);
Map params = CommonUtil.objectToMap(payRequestDto);
params.put("package", "prepay_id=".concat(result.get("prepay_id")));
payRequestDto.setPaySign(WXPayUtil.generateSignature(params, Conf.get("wx.api.key")));
payRequestDto.setPrepayId(result.get("prepay_id"));
return payRequestDto;
}
public static String getNonceStr() {
String strTime = new Date().toString();
strTime = strTime.substring(8, strTime.length());
String strRandom = buildRandom(4) + "";
return strTime + strRandom;
}
public static String getMchBillNo() {
StringBuilder sb = new StringBuilder();
String strTime = String.valueOf(System.currentTimeMillis());
return sb.append(strTime).append(buildRandom(4)).toString();
}
/**
* ๅๅบไธไธชๆๅฎ้ฟๅบฆๅคงๅฐ็้ๆบๆญฃๆดๆฐ.
*
* @param length int ่ฎพๅฎๆๅๅบ้ๆบๆฐ็้ฟๅบฆใlengthๅฐไบ11
* @return int ่ฟๅ็ๆ็้ๆบๆฐใ
*/
public static int buildRandom(int length) {
int num = 1;
double random = Math.random();
if (random < 0.1) {
random = random + 0.1;
}
for (int i = 0; i < length; i++) {
num = num * 10;
}
return (int) ((random * num));
}
public static Map<String, String> getPrepareId(UnifiedorderDto unifiedorderDto) throws Exception {
Map params = CommonUtil.objectToMap(unifiedorderDto);
String dataXml = WXPayUtil.generateSignedXml(params, Conf.get("wx.api.key"));
log.info("params :{}", params);
String resXml = HttpUtil.postData(WXPayConstants.UNIFIEDORDER_URL, dataXml);
Map<String, String> result = WXPayUtil.xmlToMap(resXml);
return result;
}
public static Map<String, String> getRequestXml() throws Exception {
return WXPayUtil.xmlToMap(getRequestParams());
}
public static String getRequestParams() throws Exception {
StringBuffer sb = new StringBuffer();
String s = "";
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(Context.getHttpServletRequest().getInputStream(), "UTF-8"));
while ((s = in.readLine()) != null) {
sb.append(s);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
}
}
log.info(sb.toString());
return sb.toString();
}
//้็ฅๅพฎไฟก.ๅผๆญฅ็กฎ่ฎคๆๅ.ๅฟ
ๅ.ไธ็ถไผไธ็ด้็ฅๅๅฐ.ๅ
ซๆฌกไนๅๅฐฑ่ฎคไธบไบคๆๅคฑ่ดฅไบ.
public static void resNotifySuccess() {
String resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
try {
BufferedOutputStream outBuffer = new BufferedOutputStream(Context.getHttpServletResponse().getOutputStream());
outBuffer.write(resXml.getBytes());
outBuffer.flush();
outBuffer.close();
} catch (Exception e) {
log.error("ๆฏไปๅ่ฐๆๅ่ฟๅๅคฑ่ดฅ");
}
}
public static ModelAndView auth2(String state) {
String authUrl = TemplateUtils.replaceAll(Conf.get("wx.oauth2.url"), Conf.get("wxsa.appId"),
URLEncoder.encode(Conf.get("wx.auth.callback.url")),
Conf.get("wx.request.auth.type:snsapi_userinfo"), state);
return new ModelAndView("redirect:" + authUrl);
}
public static GetTokenByCodeResultDto getAccessTokenByCode(String code) {
String url = TemplateUtils.replaceAll(Conf.get("wx.access.token.code.url"), Conf.get("wxsa.appId"), Conf.get("wxsa.secret"), code);
return get(url, GetTokenByCodeResultDto.class);
}
public static WxUserModel getServerUserInfo(String urlKey, String openId, String token) {
String url = TemplateUtils.replaceAll(Conf.get(urlKey), token, openId);
WxUserDto wxUserDto = post(url, new HashMap(), WxUserDto.class);
WxUserModel wxUserModel = new WxUserModel();
BeanUtils.copyProperties(wxUserDto, wxUserModel);
wxUserModel.setOpenId(wxUserDto.getOpenid());
try {
if (wxUserDto.getNickname() != null) {
// ๅฐๅพฎไฟกๆต็งฐ่ฝฌไธบ UTF-8
wxUserModel.setHeadImgUrl(wxUserDto.getHeadimgurl());
wxUserModel.setNickname(new ByteArrayInputStream(wxUserDto.getNickname().getBytes("UTF-8")));
}
} catch (UnsupportedEncodingException e) {
}
return wxUserModel;
}
public static synchronized JsApiTicketDto getJsapiTicket() {
if (jsApiTicketDto == null || jsApiTicketDto.getExpire().before(new Date())) {
String url = TemplateUtils.replaceAll(Conf.get("wx.jsapi.ticket"), getAccessToken().getAccess_token());
jsApiTicketDto = get(url, JsApiTicketDto.class);
}
return jsApiTicketDto;
}
public static JsApiDto genJsApiDto(String url) throws Exception {
WxMpService wxMpService = Context.getBean(WxMpService.class);
JsApiDto jsApiDto = new JsApiDto(wxMpService.getWxMpConfigStorage().getAppId());
if (Conf.enable("wx.jsApi.enable")) {
WxJsapiSignature jsapiSignature = wxMpService.createJsapiSignature(url);
jsApiDto.setNoncestr(jsapiSignature.getNonceStr());
jsApiDto.setSignature(jsapiSignature.getSignature());
jsApiDto.setTimestamp(String.valueOf(jsapiSignature.getTimestamp()));
}
return jsApiDto;
}
public static JsApiDto genJsApiDto() throws Exception {
return genJsApiDto(ParamsUtils.getLocalUrl());
}
public static synchronized RedPackReturnDto redpack(RedpackDto redpackDto) throws Exception {
IWxRedPackResultService resultService = Context.getBean(IWxRedPackResultService.class);
WxRedPackResultModel resultModel = new WxRedPackResultModel();
resultModel.setOpenId(redpackDto.getRe_openid());
resultModel.setPromoteType(Context.getPromoteType());
resultModel = resultService.selectOne(resultModel);
if (resultModel != null && "SUCCESS".equals(resultModel.getResultCode())) {
throw new StatelessException(ErrorMessage.getFailure("redPack again", "ๆจๅทฒ้ขๅ็บขๅ
"));
}
if (resultModel == null) {
resultModel = new WxRedPackResultModel();
redpackDto.setNonce_str(WxUtils.getMchBillNo());
redpackDto.setMch_billno(WxUtils.getMchBillNo());
resultModel.setOpenId(redpackDto.getRe_openid());
resultModel.setPromoteType(Context.getPromoteType());
resultModel.setMchBillno(redpackDto.getMch_billno());
resultService.insertSelective(resultModel);
} else {
//ๅ้ๅคฑ่ดฅ็็จๅๆฅ็ๅๆท่ฎขๅ้ๆฐๅ้
redpackDto.setNonce_str(WxUtils.getMchBillNo());
redpackDto.setMch_billno(resultModel.getMchBillno());
}
RedPackReturnDto redPackReturnDto = WxCertUtils.postWithCert(Conf.get("wx.redpack.url"), Conf.get("wx.redpack.cert"), redpackDto, RedPackReturnDto.class);
resultModel.setResultCode(redPackReturnDto.getResult_code());
resultModel.setErrCode(redPackReturnDto.getErr_code());
resultModel.setTotalAmount(redPackReturnDto.getTotal_amount());
if ("SUCCESS".equals(resultModel.getResultCode())) {
resultModel.setSuccessTime(new Date());
}
resultService.updateByPrimaryKey(resultModel);
return redPackReturnDto;
}
public static ResponseEntity<byte[]> downloadMedia(String mediaId) {
String token = getAccessToken().getAccess_token();
String url = Conf.get("wx.media.get.url");
url = TemplateUtils.replaceAll(url, token, mediaId);
HttpHeaders headers = new HttpHeaders();
ResponseEntity<byte[]> response = RESTUtils.rest().exchange(url,
HttpMethod.GET, new HttpEntity<byte[]>(headers), byte[].class);
return response;
}
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/model/ShopReceiveRecordModel.java
package com.ningyuan.mobile.model;
import com.ningyuan.base.BaseModel;
import com.ningyuan.base.annotation.FiledComment;
import javax.persistence.Column;
import javax.persistence.Table;
import java.util.Date;
/**
* generated by Generate POJOs.groovy
* <p>Date: Fri Apr 03 15:21:29 CST 2020.</p>
*
* @author (zengrc)
*/
@Table ( name ="shop_receive_record" )
public class ShopReceiveRecordModel extends BaseModel {
@Column(name = "open_id" )
private String openId;
/**
* ่ฎฐๅฝ็ฑปๅ๏ผ1๏ผ้ขๅ็บขๅ
๏ผ2๏ผ็บขๅ
ๆ็ฐ
*/
@FiledComment(text = "่ฎฐๅฝ็ฑปๅ๏ผ1๏ผ้ขๅ็บขๅ
๏ผ2๏ผ็บขๅ
ๆ็ฐ" )
@Column(name = "opt_type" )
private String optType;
/**
* ้้ขๆ่
็บขๅ
ไธชๆฐ
*/
@FiledComment(text = "้้ขๆ่
็บขๅ
ไธชๆฐ" )
@Column(name = "amount" )
private String amount;
@Column(name = "create_time" )
private Date createTime;
@Column(name = "update_time" )
private Date updateTime;
public String getOpenId() {
return this.openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getOptType() { return optType; }
public void setOptType(String optType) { this.optType = optType; }
public String getAmount() {
return this.amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public Date getCreateTime() {
return this.createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return this.updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
<file_sep>/wx/src/main/java/com/ningyuan/wx/model/WxNotifyInfoModel.java
package com.ningyuan.wx.model;
import com.ningyuan.base.BaseModel;
import javax.persistence.Column;
import javax.persistence.Table;
/**
* generated by Generate POJOs.groovy
* <p>Date: Thu Nov 22 11:14:32 CST 2018.</p>
*
* @author (zengrc)
*/
@Table ( name ="wx_notify_info" )
public class WxNotifyInfoModel extends BaseModel {
@Column(name = "appoint_id" )
private String appointId;
@Column(name = "open_id" )
private String openId;
@Column(name = "time_end" )
private String timeEnd;
@Column(name = "transaction_id" )
private String transactionId;
public String getAppointId() {
return this.appointId;
}
public void setAppointId(String appointId) {
this.appointId = appointId;
}
public String getOpenId() {
return this.openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getTimeEnd() {
return this.timeEnd;
}
public void setTimeEnd(String timeEnd) {
this.timeEnd = timeEnd;
}
public String getTransactionId() {
return this.transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/model/ShopAttrKey.java
package com.ningyuan.mobile.model;
import com.ningyuan.base.BaseModel;
import javax.persistence.Column;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Date;
/**
* generated by Generate POJOs.groovy
* <p>Date: Wed Mar 18 11:33:46 CST 2020.</p>
*
* @author (zengrc)
*/
@Table ( name ="shop_attr_key" )
public class ShopAttrKey extends BaseModel {
@Column(name = "attr_name" )
private String attrName;
@Column(name = "id_category" )
private Long idCategory;
public String getAttrName() {
return attrName;
}
public void setAttrName(String attrName) {
this.attrName = attrName;
}
public Long getIdCategory() {
return idCategory;
}
public void setIdCategory(Long idCategory) {
this.idCategory = idCategory;
}
}
<file_sep>/mobile-core/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>ningyuan_pos</artifactId>
<groupId>com.ningyuan</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>mobile-core</artifactId>
<dependencies>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>${ehcache.core.version}</version>
</dependency>
</dependencies>
<build>
<resources>
<!-- Include other files as resources files. -->
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
<excludes>
<exclude>config/dev.properties</exclude>
</excludes>
</resource>
</resources>
</build>
</project><file_sep>/admin/src/main/webapp/app/lib/route.config.js
๏ปฟ"use strict"
app.config(["$stateProvider", "$urlRouterProvider", "$routesDataProvider", routeFn]);
function routeFn($stateProvider, $urlRouterProvider, $routesDataProvider) {
let routes = $routesDataProvider.getRoutes();
$urlRouterProvider.otherwise(routes[0].url);
routes.forEach(item => {
if (typeof (item.resolve) == 'string') {
item.resolve = JSON.parse(item.resolve);
}
for (let i = 0; i < item.resolve.length; i++) {
item.resolve[i] = appPath + item.resolve[i] + "?" + version;
}
$stateProvider
.state(item.state, {
url: item.url,
templateUrl: appPath + item.view + ".html",
controller: item.ctrl + "Ctrl",
controllerAs: item.ctrl,
resolve: {
deps: ["$ocLazyLoad", function ($ocLazyLoad) {
return $ocLazyLoad.load(item.resolve);
}]
}
})
})
};<file_sep>/admin/src/main/java/com/ningyuan/route/dto/ShopUserQueryDto.java
package com.ningyuan.route.dto;
public class ShopUserQueryDto {
private Long id;
private String receiver;
private String mobile;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getReceiver() { return receiver; }
public void setReceiver(String receiver) { this.receiver = receiver; }
public String getMobile() { return mobile; }
public void setMobile(String mobile) { this.mobile = mobile; }
}
<file_sep>/wx/src/main/java/com/ningyuan/wx/service/IWxCommonRelateView.java
package com.ningyuan.wx.service;
import com.ningyuan.wx.model.WxRelateModel;
import org.springframework.web.servlet.ModelAndView;
public interface IWxCommonRelateView {
ModelAndView viewByType(WxRelateModel wxRelateModel);
}
<file_sep>/wx/src/main/java/com/ningyuan/wx/dto/WxGetPhoneDto.java
package com.ningyuan.wx.dto;
/***
* Author: YeJian
* Create on: 2019/5/20
* Email: <EMAIL>
* Explanation: ่ฏฅ็ฑป็ๅ
ทไฝๆ่ฟฐ
*/
public class WxGetPhoneDto {
/**
* phoneNumber : 13580006666
* purePhoneNumber : 13580006666
* countryCode : 86
* watermark : {"appid":"APPID","timestamp":"TIMESTAMP"}
*/
private String phoneNumber;
private String purePhoneNumber;
private String countryCode;
private WatermarkBean watermark;
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getPurePhoneNumber() {
return purePhoneNumber;
}
public void setPurePhoneNumber(String purePhoneNumber) {
this.purePhoneNumber = purePhoneNumber;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public WatermarkBean getWatermark() {
return watermark;
}
public void setWatermark(WatermarkBean watermark) {
this.watermark = watermark;
}
public static class WatermarkBean {
/**
* appid : APPID
* timestamp : TIMESTAMP
*/
private String appid;
private String timestamp;
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
}
}
<file_sep>/admin/src/main/java/com/ningyuan/route/service/impl/BgRouteServiceImpl.java
package com.ningyuan.route.service.impl;
import com.ningyuan.base.BaseServiceImpl;
import com.ningyuan.route.daomapper.mapper.BgRouteMapper;
import com.ningyuan.route.model.BgRouteModel;
import com.ningyuan.route.service.IBgRouteService;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* generated by Generate Service.groovy
* <p>Date: Wed Mar 20 14:42:20 CST 2019.</p>
*
* @author (zengrc)
*/
@Service
public class BgRouteServiceImpl extends BaseServiceImpl<BgRouteMapper, BgRouteModel> implements IBgRouteService {
@Override
public List<BgRouteModel> getRouteByRole(Long roleId) {
return this.mapper.getRouteByRole(roleId);
}
// @Override
// public List<BgRouteRoleDto> getRouteByRoleId(Long roleId) {
// return this.mapper.getRouteByRoleId(roleId);
// }
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/dto/RedPacketDto.java
package com.ningyuan.mobile.dto;
public class RedPacketDto {
private String optionType;
private String finance;
private String openId;
private Integer optType;
private String createTime;
public String getFinance() { return finance; }
public void setFinance(String finance) { this.finance = finance; }
public String getOptionType() { return optionType; }
public void setOptionType(String optionType) { this.optionType = optionType; }
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public Integer getOptType() {
return optType;
}
public void setOptType(Integer optType) {
this.optType = optType;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/service/IGoodsService.java
package com.ningyuan.mobile.service;
import com.ningyuan.base.IBaseService;
import com.ningyuan.mobile.dto.GoodsDto;
import com.ningyuan.mobile.model.ShopGoodsModel;
import java.util.List;
public interface IGoodsService extends IBaseService<ShopGoodsModel> {
List<GoodsDto> getGoods(Long idCategory, Boolean isOnSale);
}
<file_sep>/wx/src/main/java/com/ningyuan/wx/service/IWxsaCustomerService.java
package com.ningyuan.wx.service;
import com.ningyuan.base.IBaseService;
import com.ningyuan.wx.model.wxsa.WxsaCustomerModel;
/**
* generated by Generate Service.groovy
* <p>Date: Tue Aug 20 09:48:12 CST 2019.</p>
*
* @author (zengrc)
*/
public interface IWxsaCustomerService extends IBaseService<WxsaCustomerModel>, IWxGetByOpenId<WxsaCustomerModel> {
void saveCustomer(String openId, WxsaCustomerModel customerModel);
}
<file_sep>/admin/src/main/webapp/app/menu/js/menuService.js
"use strict"
app.service('menus', function($req) {
let menuService = this;
this.sortBySeq = function (a, b){
return b.seq - a.seq;
}
this.sortMenu = function(menus){
for(let i = 0; i < menus.length; i++){
menus[i].childrens = menus[i].childrens.sort(menuService.sortBySeq);
}
return menus.sort(menuService.sortBySeq);
}
this.getMenus = function () {
return $req.post("/menu/menus");
}
this.getUser = function () {
return $req.post("/menu/login/user");
}
});<file_sep>/admin/src/main/webapp/app/lib/reqService.js
"use strict"
app.service('$req', function ($http) {
this.post = function (uri, data) {
let params = {};
//ๅป้ค็ฉบๅญ็ฌฆไธฒ
for (let key in data) {
if(data[key] != null && data[key] != 'null'&& (data[key] !== '' || typeof (data[key]) == 'boolean') ){
params[key] = data[key];
}
}
return $http.post(path + uri, params);
}
this.get = function (uri, data) {
return $http.get(path + uri, data);
}
});<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/model/ShopGoodsSkuModel.java
package com.ningyuan.mobile.model;
import com.ningyuan.base.BaseModel;
import com.ningyuan.base.annotation.FiledComment;
import javax.persistence.Column;
import javax.persistence.Table;
import java.math.BigDecimal;
import java.util.Date;
/**
* generated by Generate POJOs.groovy
* <p>Date: Sat Mar 21 14:55:34 CST 2020.</p>
*
* @author (zengrc)
*/
@Table ( name ="shop_goods_sku" )
public class ShopGoodsSkuModel extends BaseModel {
/**
* sku็ผ็ ,ๆ ผๅผ:้ๅทๅๅฒ็ๅฑๆงๅผid
*/
@FiledComment(text = "sku็ผ็ ,ๆ ผๅผ:้ๅทๅๅฒ็ๅฑๆงๅผid" )
@Column(name = "code" )
private String code;
/**
* skuๅ็งฐ,ๆ ผๅผ:้ๅทๅๅฒ็ๅฑๆงๅผ
*/
@FiledComment(text = "skuๅ็งฐ,ๆ ผๅผ:้ๅทๅๅฒ็ๅฑๆงๅผ" )
@Column(name = "code_name" )
private String codeName;
/**
* ๅๅid
*/
@FiledComment(text = "ๅๅid" )
@Column(name = "id_goods" )
private Long idGoods;
/**
* ๅธๅบไปท,ๅไปท
*/
@FiledComment(text = "ๅธๅบไปท,ๅไปท" )
@Column(name = "marketing_price" )
private BigDecimal marketingPrice;
/**
* ไปทๆ ผ
*/
@FiledComment(text = "ไปทๆ ผ" )
@Column(name = "price" )
private BigDecimal price;
@FiledComment(text = "ๅบๅญ" )
@Column(name = "stock" )
private Integer stock;
public String getCode() {
return this.code;
}
public void setCode(String code) {
this.code = code;
}
public String getCodeName() {
return this.codeName;
}
public void setCodeName(String codeName) {
this.codeName = codeName;
}
public Long getIdGoods() {
return this.idGoods;
}
public void setIdGoods(Long idGoods) {
this.idGoods = idGoods;
}
public BigDecimal getMarketingPrice() { return marketingPrice; }
public void setMarketingPrice(BigDecimal marketingPrice) { this.marketingPrice = marketingPrice; }
public BigDecimal getPrice() { return price; }
public void setPrice(BigDecimal price) { this.price = price; }
public Integer getStock() { return stock; }
public void setStock(Integer stock) { this.stock = stock; }
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/service/IShopReceiveRecordService.java
package com.ningyuan.mobile.service;
import com.ningyuan.base.IBaseService;
import com.ningyuan.mobile.model.ShopReceiveRecordModel;
/**
* generated by Generate Service.groovy
* <p>Date: Fri Apr 03 15:21:29 CST 2020.</p>
*
* @author (zengrc)
*/
public interface IShopReceiveRecordService extends IBaseService<ShopReceiveRecordModel> {
void insertRecord(String optType, String amount, String openId);
}
<file_sep>/admin/src/main/java/com/ningyuan/route/service/impl/BgUserServiceImpl.java
package com.ningyuan.route.service.impl;
import com.ningyuan.base.BaseServiceImpl;
import com.ningyuan.route.daomapper.mapper.BgUserMapper;
import com.ningyuan.route.model.BgUserModel;
import com.ningyuan.route.service.IBgUserService;
import org.springframework.stereotype.Service;
/**
* generated by Generate Service.groovy
* <p>Date: Wed Mar 20 14:42:20 CST 2019.</p>
*
* @author (zengrc)
*/
@Service
public class BgUserServiceImpl extends BaseServiceImpl<BgUserMapper, BgUserModel> implements IBgUserService {
@Override
public BgUserModel getUserByUsername(String userName) {
BgUserModel bgUserModel = new BgUserModel();
bgUserModel.setUsername(userName);
bgUserModel = this.selectOne(bgUserModel);
return bgUserModel;
}
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/model/ShopFavoriteModel.java
package com.ningyuan.mobile.model;
import javax.persistence.Column;
import javax.persistence.Table;
import com.ningyuan.base.BaseModel;
import com.ningyuan.base.annotation.FiledComment;
import java.util.Date;
/**
* generated by Generate POJOs.groovy
* <p>Date: Tue Mar 24 16:55:30 CST 2020.</p>
*
* @author (zengrc)
*/
@Table ( name ="shop_favorite" )
public class ShopFavoriteModel extends BaseModel {
@Column(name = "open_id" )
private String openId;
/**
* ๅๅid
*/
@FiledComment(text = "ๅๅid" )
@Column(name = "id_goods" )
private Long idGoods;
@Column(name = "create_time" )
private Date createTime;
@Column(name = "update_time" )
private Date updateTime;
public String getOpenId() {
return this.openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public Long getIdGoods() {
return this.idGoods;
}
public void setIdGoods(Long idGoods) {
this.idGoods = idGoods;
}
public Date getCreateTime() {
return this.createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return this.updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
<file_sep>/wx/src/main/java/com/ningyuan/wx/daomapper/mapper/WxsaSubscribeMapper.java
package com.ningyuan.wx.daomapper.mapper;
import com.ningyuan.wx.model.wxsa.WxsaSubscribeModel;
import tk.mybatis.mapper.common.Mapper;
/**
* generated by Generate Mapper.groovy
* <p>Date: Mon Oct 07 17:14:16 CST 2019.</p>
*
* @author (zengrc)
*/
public interface WxsaSubscribeMapper extends Mapper<WxsaSubscribeModel> {
}
<file_sep>/admin/src/main/webapp/app/lib/init.config.js
if ('undefined' == typeof (appConf)) {
appConf = {};
}
(function () {
$.ajax({
url: path + "/rest/sys/params/config/app",
async: false,
data: {},
success: function (response) {
if (typeof (response) == 'string' && response.indexOf("็ปๅฝ") != -1) {
//่ฟๆฒกๆ็ปๅฝ
location.href = path + "/login.jsp";
return;
}
for(var key in response){
if(!appConf[key]){
appConf[key] = response[key];
}
}
}
});
})();<file_sep>/wx/src/main/java/com/ningyuan/wx/config/WxMpConfiguration.java
package com.ningyuan.wx.config;
import com.ningyuan.core.Conf;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* ๅพฎไฟกๅ
ฌไผๅทไธป้
็ฝฎ
* <p>
*/
@Configuration
public class WxMpConfiguration {
@Autowired
private WxMpHttpClientBuilder httpClientBuilder;
public WxMpConfigStorage wxMpConfigStorage() {
WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();
configStorage.setAppId(Conf.get("wxsa.appId"));
configStorage.setSecret(Conf.get("wxsa.secret"));
configStorage.setToken(Conf.get("wxsa.token"));
configStorage.setAesKey(Conf.get("wxsa.aesKey"));
configStorage.setApacheHttpClientBuilder(httpClientBuilder);
return configStorage;
}
@Bean
public WxMpService wxMpService() {
WxMpService wxMpService = new WxMpServiceImpl();
wxMpService.setWxMpConfigStorage(wxMpConfigStorage()); //default
return wxMpService;
}
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/dto/OrderDto.java
package com.ningyuan.mobile.dto;
import com.ningyuan.mobile.model.ShopAddressModel;
import java.util.List;
public class OrderDto {
private Long id;
private Long idAddress;
private String openId;
private String orderSn;
private String realPrice;
private String status;
private String statusName;
private String totalPrice;
private String createTime;
private ShopAddressModel address;
private List<OrderGoodsDto> goods;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public Long getIdAddress() { return idAddress; }
public void setIdAddress(Long idAddress) { this.idAddress = idAddress; }
public String getOpenId() { return openId; }
public void setOpenId(String openId) { this.openId = openId; }
public String getOrderSn() { return orderSn; }
public void setOrderSn(String orderSn) { this.orderSn = orderSn; }
public String getRealPrice() { return realPrice; }
public void setRealPrice(String realPrice) { this.realPrice = realPrice; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public String getStatusName() { return statusName; }
public void setStatusName(String statusName) { this.statusName = statusName; }
public String getTotalPrice() { return totalPrice; }
public void setTotalPrice(String totalPrice) { this.totalPrice = totalPrice; }
public String getCreateTime() { return createTime; }
public void setCreateTime(String createTime) { this.createTime = createTime; }
public ShopAddressModel getAddress() { return address; }
public void setAddress(ShopAddressModel address) { this.address = address; }
public List<OrderGoodsDto> getGoods() { return goods; }
public void setGoods(List<OrderGoodsDto> goods) { this.goods = goods; }
}
<file_sep>/admin/src/main/webapp/app/customer/js/inviteInfoCtrl.js
(function () {
app.controller('inviteInfoCtrl', inviteInfoCtrlFn);
function inviteInfoCtrlFn($scope, inviteInfoService) {
$scope.customerModel = {};
inviteInfoService.getInviteList($scope);
}
}());<file_sep>/mobile-core/src/main/java/com/ningyuan/system/interceptor/SysInterceptor.java
package com.ningyuan.system.interceptor;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SysInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
/*if(Conf.enable("sys.event.interceptor.enable")) {
threadPool.execute(() -> {
String uri = request.getRequestURI().replaceAll("/(.*?)/(.*?)/(.*?)/(.*?)/.*", "$1/$2/$3/$4");
sysEventStatsService.countUrl(uri);
});
}*/
return true;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
}
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/service/IShopCartService.java
package com.ningyuan.mobile.service;
import com.ningyuan.base.IBaseService;
import com.ningyuan.mobile.dto.CartAddDto;
import com.ningyuan.mobile.dto.ShopCartDto;
import com.ningyuan.mobile.model.ShopCartModel;
import java.util.List;
/**
* generated by Generate Service.groovy
* <p>Date: Sat Mar 21 14:55:34 CST 2020.</p>
*
* @author (zengrc)
*/
public interface IShopCartService extends IBaseService<ShopCartModel> {
List<ShopCartDto> queryCart(String openId);
Integer addCartItem(CartAddDto cartDto, String openId);
void deleteCartList(List<ShopCartDto> cartList);
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/service/IShopCustomerService.java
package com.ningyuan.mobile.service;
import com.ningyuan.base.IBaseService;
import com.ningyuan.mobile.dto.*;
import com.ningyuan.mobile.model.ShopCustomerModel;
import com.ningyuan.mobile.model.ShopOrderModel;
import java.util.List;
/**
* generated by Generate Service.groovy
* <p>Date: Fri Apr 03 11:08:59 CST 2020.</p>
*
* @author (zengrc)
*/
public interface IShopCustomerService extends IBaseService<ShopCustomerModel> {
void updateCustomer(ShopOrderModel orderModel);
UserInfoDto queryUserInfo(String openId);
ShopCustomerModel checkuser(String openId);
// ๆๅผ็บขๅ
String openRedpacket(String openId);
TaskStatusDto getTaskStatus(String openId);
ParentUserDto getParentOpenId(String openId);
List<UserDto> getRecommend(String openId);
List<UserDto> getTeam(String openId);
List<TaskDto> listTask(String openId);
void saveMobile(String openId, String mobile);
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/controller/AddressController.java
package com.ningyuan.mobile.controller;
import com.ningyuan.base.BaseController;
import com.ningyuan.bean.front.Rets;
import com.ningyuan.core.Context;
import com.ningyuan.mobile.model.ShopAddressModel;
import com.ningyuan.mobile.service.IShopAddressService;
import com.ningyuan.mobile.service.IShopCustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;
import javax.validation.Valid;
import java.util.List;
@Controller
@RequestMapping("user/address")
public class AddressController extends BaseController {
@Autowired
private IShopAddressService addressService;
@Autowired
private IShopCustomerService shopCustomerService;
@RequestMapping(value = "{id}",method = RequestMethod.GET)
@ResponseBody
public Object get(@PathVariable("id") Long id){
ShopAddressModel shopAddressMode = new ShopAddressModel();
if (id != null) {
String openId = Context.getOpenId();
shopAddressMode.setOpenId(openId);
shopAddressMode.setId(id);
}
return Rets.success(addressService.selectByPrimaryKey(shopAddressMode));
}
@RequestMapping(value = "{id}",method = RequestMethod.DELETE)
@ResponseBody
public Object remove(@PathVariable("id") Long id){
ShopAddressModel shopAddressMode = new ShopAddressModel();
if (id != null) {
String openId = Context.getOpenId();
shopAddressMode.setOpenId(openId);
shopAddressMode.setId(id);
addressService.deleteByPrimaryKey(shopAddressMode);
}
return Rets.success();
}
@RequestMapping(value = "{id}/{isDefault}",method = RequestMethod.POST)
@ResponseBody
public Object changeDefault(@PathVariable("id") Long id,@PathVariable("isDefault") Boolean isDefault){
String openId = Context.getOpenId();
ShopAddressModel queryModel = new ShopAddressModel();
queryModel.setOpenId(openId);
queryModel.setIsDefault(Boolean.TRUE);
ShopAddressModel defaultAddr = addressService.selectOne(queryModel);
if(defaultAddr != null){
if(defaultAddr.getId().equals(id)){
defaultAddr.setIsDefault(isDefault);
addressService.updateByPrimaryKeySelective(defaultAddr);
return Rets.success();
}else{
if(isDefault) {
defaultAddr.setIsDefault(false);
addressService.updateByPrimaryKeySelective(defaultAddr);
}
}
}
ShopAddressModel queryModel2 = new ShopAddressModel();
queryModel2.setOpenId(openId);
queryModel2.setId(id);
ShopAddressModel address = addressService.selectLimitOne(queryModel2);
address.setIsDefault(isDefault);
addressService.updateByPrimaryKeySelective(address);
return Rets.success(address);
}
@RequestMapping(value = "/queryByUser",method = RequestMethod.GET)
@ResponseBody
public Object getByUser(){
String openId = Context.getOpenId();
Example example = new Example(ShopAddressModel.class);
example.createCriteria().andEqualTo("openId", openId).andEqualTo("isDelete", Boolean.FALSE);
List<ShopAddressModel> list = addressService.selectByExample(example);
return Rets.success(list);
}
@RequestMapping(value = "/save",method = RequestMethod.POST)
@ResponseBody
public Object save(@RequestBody @Valid ShopAddressModel addressInfo){
String openId = Context.getOpenId();
addressInfo.setOpenId(openId);
if(addressInfo.getId()!=null){
addressService.updateByPrimaryKeySelective(addressInfo);
}else{
addressService.insertSelective(addressInfo);
}
shopCustomerService.saveMobile(openId, addressInfo.getMobile());
return Rets.success();
}
}
<file_sep>/admin/src/main/webapp/app/customer/js/confirmUserInfoCtrl.js
(function () {
app.controller('confirmUserInfoCtrl', confirmUserInfoCtrlFn);
function confirmUserInfoCtrlFn($scope, confirmUserInfoService) {
$scope.confirmUserInfoModel = {};
$scope.settingModel = [];
confirmUserInfoService.getCustomerList($scope);
$scope.booleanOptions = [{'value': true, 'text': 'ๆฏ'},{'value': false, 'text': 'ๅฆ'}]
$scope.vipGrade = [{'value': '1', 'text': 'ๆฎ้ไผๅ'},{'value': '2', 'text': '้ถ็ไผๅ'},{'value': '3', 'text': '้็ไผๅ'},
{'value': '4', 'text': '้้ไผๅ'},{'value': '5', 'text': '้ป็ณไผๅ'},{'value': '6', 'text': '็็ไผๅ'}]
this.save = function () {
confirmUserInfoService.saveUser($scope.confirmUserInfoModel).then(function (response) {
if ($scope.currentIndex === '') {
$scope.pageInfo.list.push(response.data);
} else {
$scope.pageInfo.list[$scope.currentIndex] = response.data;
}
$('#updateModal').modal('hide');
});
}
this.saveSetting = function () {
confirmUserInfoService.saveSetting($scope.settingModel).then(function (response) {
$('#updateSetting').modal('hide');
});
}
this.update = function (index) {
$scope.currentIndex = index;
$('.modal-body .form-control').each(function () {
$scope.confirmUserInfoModel[$(this).attr('name')] = $scope.pageInfo.list[index][$(this).attr('name')];
})
$('#modalLabel').text('ไผๅไฟกๆฏไฟฎๆน');
$('#updateModal').modal();
}
this.updateSetting = function () {
confirmUserInfoService.getSetting().then(function (response) {
console.log(response)
$scope.settingModel = response.data
})
$('#updateSetting').modal();
}
this.addRedpacket = function (index) {
$scope.currentIndex = index;
$('.modal-body .form-control').each(function () {
$scope.confirmUserInfoModel[$(this).attr('name')] = $scope.pageInfo.list[index][$(this).attr('name')];
})
$('#addRedpacketModal').modal();
}
this.saveRedpacketSum = function (id, addAmount, minusAmount, openId) {
confirmUserInfoService.saveRedpacketSum(id, addAmount, minusAmount, openId).then(function (response) {
if (response.data.errorCode === 'SUCCESS') {
alert('ไฟๅญๆๅ')
$scope.confirmUserInfoModel = {};
confirmUserInfoService.getCustomerList($scope);
} else {
alert('ไฟๅญๅคฑ่ดฅ')
}
$('#addRedpacketModal').modal('hide');
});
}
}
}());<file_sep>/admin/src/main/java/com/ningyuan/route/dto/ShopMarketRatioDto.java
package com.ningyuan.route.dto;
public class ShopMarketRatioDto {
private Long id;
private String vipKey;
private String vipName;
private String dividendRatio;
private String performanceRatio;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getVipKey() {
return vipKey;
}
public void setVipKey(String vipKey) {
this.vipKey = vipKey;
}
public String getVipName() {
return vipName;
}
public void setVipName(String vipName) {
this.vipName = vipName;
}
public String getDividendRatio() {
return dividendRatio;
}
public void setDividendRatio(String dividendRatio) {
this.dividendRatio = dividendRatio;
}
public String getPerformanceRatio() {
return performanceRatio;
}
public void setPerformanceRatio(String performanceRatio) {
this.performanceRatio = performanceRatio;
}
}
<file_sep>/wx/src/main/java/com/ningyuan/wx/utils/WxsaUtils.java
package com.ningyuan.wx.utils;
import com.ningyuan.base.exception.ErrorMessage;
import com.ningyuan.base.exception.StatelessException;
import com.ningyuan.core.Conf;
import com.ningyuan.wx.constant.WxsaConstant;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class WxsaUtils {
protected static Logger log = LoggerFactory.getLogger(WxsaUtils.class);
private WxsaUtils() {
}
/**
* ่ทๅwx_relate ไธparamsไธญ ๆไธชๅๆฐ็ๅผ
*
* @param commonParams
* @param key paramsไธญ็ๅๆฐๅ
* @return
*/
public static String getFromCommonParams(String commonParams, String key) {
if (StringUtils.isEmpty(commonParams) || StringUtils.isEmpty(key)) {
return null;
}
String val = null;
String[] arr = StringUtils.split(commonParams, WxsaConstant.commonRelate.SIGN_BETWEEN_PARAM);
for (String s : arr) {
String value = StringUtils.substringAfter(s, key + WxsaConstant.commonRelate.SIGN_BETWEEN_KV);
if (StringUtils.isNotBlank(value)) {
val = value;
break;
}
}
return val;
}
public static void checkToken(String token) throws Exception {
if (!org.apache.commons.lang3.StringUtils.equals(token, Conf.get("promote.notify.common.token"))) {
throw new StatelessException(ErrorMessage.getFailure("invalid token", "ๆ ๆtoken"));
}
}
}
<file_sep>/admin/src/main/webapp/app/lib/init.load.js
function loadCss(cssList){
let head = document.getElementsByTagName("head").item(0);
// ๅจๆๅ ่ฝฝ css
cssList.forEach(item => {
let css = document.createElement('link');
css.href = appPath + item + "?" + version;
css.rel = "stylesheet";
head.appendChild(css);
})
}
function asyncLoadJs(asyncScriptList){
let head = document.getElementsByTagName("head").item(0);
asyncScriptList.forEach(item => {
let script = document.createElement('script');
script.src = appPath + item + "?" + version;
head.appendChild(script);
})
}
function loadJs(scriptList, success){
let head = document.getElementsByTagName("head").item(0);
// ๅจๆๅ ่ฝฝ js
let scripts = [];
let next = 0;
for (let i = 0; i < scriptList.length; i++) {
let script = document.createElement('script');
script.src = appPath + scriptList[i] + "?" + version;;
script.onload = function () {
next += 1;
if (next < scripts.length) {
head.appendChild(scripts[next]);
}
if(next == scripts.length){
if(success){
success();
}
}
};
scripts.push(script)
}
head.appendChild(scripts[0]);
}
(function () {
let cssList = [
"/lib/css/bootstrap.min.css",
"/lib/css/bootstrap-datetimepicker.min.css",
"/menu/css/menu.css",
"/css/table.css",
];
let scriptList = [
"/lib/js/jquery-3.3.1.min.js",
"/lib/js/angular.min.js",
"/lib/js/angular-ui-router.min.js",
"/lib/js/angular-sanitize.min.js",
"/lib/js/ocLazyLoad.min.js",
"/lib/js/bootstrap.min.js",
"/lib/js/bootstrap-datetimepicker.min.js",
"/lib/js/bootstrap-datetimepicker.zh-CN.js",
"/lib/app.config.js",
"/lib/route.config.js",
"/lib/routesProvider.js",
];
let asyncScriptList = [
"/lib/reqService.js",
"/lib/init.config.js",
"/menu/js/menuService.js",
"/menu/js/menuCtrl.js",
"/directive/page/pageDirective.js",
"/directive/page/pageCtrl.js",
"/directive/popup/popupDirective.js",
"/directive/popup/popupCtrl.js",]
loadCss(cssList);
loadJs(scriptList, function () {
asyncLoadJs(asyncScriptList);
});
})();
<file_sep>/mobile-core/src/main/java/com/ningyuan/base/annotation/CacheEnbale.java
package com.ningyuan.base.annotation;
import java.lang.annotation.*;
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CacheEnbale {
}
<file_sep>/wx/src/main/java/com/ningyuan/wx/dto/WxUserDto.java
package com.ningyuan.wx.dto;
import com.ningyuan.base.BaseModel;
/**
* generated by Generate POJOs.groovy
* <p>Date: Thu Nov 22 11:14:32 CST 2018.</p>
*
* @author (zengrc)
*/
public class WxUserDto extends BaseModel {
private String subscribe;
private String openid;
private String unionid;
private String nickname;
private Integer sex;
private String language;
private String city;
private String province;
private String country;
private String headimgurl;
private String subscribeTime;
private String remark;
private String groupid;
public String getSubscribe() {
return this.subscribe;
}
public void setSubscribe(String subscribe) {
this.subscribe = subscribe;
}
public String getOpenid() {
return this.openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public String getUnionid() {
return this.unionid;
}
public void setUnionid(String unionid) {
this.unionid = unionid;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public Integer getSex() {
return this.sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public String getLanguage() {
return this.language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getProvince() {
return this.province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCountry() {
return this.country;
}
public void setCountry(String country) {
this.country = country;
}
public String getHeadimgurl() {
return this.headimgurl;
}
public void setHeadimgurl(String headimgurl) {
this.headimgurl = headimgurl;
}
public String getSubscribeTime() {
return this.subscribeTime;
}
public void setSubscribeTime(String subscribeTime) {
this.subscribeTime = subscribeTime;
}
public String getRemark() {
return this.remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getGroupid() {
return this.groupid;
}
public void setGroupid(String groupid) {
this.groupid = groupid;
}
}
<file_sep>/wx/src/main/java/com/ningyuan/wx/model/wxsa/WxsaSubscribeModel.java
package com.ningyuan.wx.model.wxsa;
import com.ningyuan.base.BaseModel;
import com.ningyuan.base.annotation.FiledComment;
import javax.persistence.Column;
import javax.persistence.Table;
import java.util.Date;
/**
* generated by Generate POJOs.groovy
* <p>Date: Wed Oct 09 11:22:22 CST 2019.</p>
*
* @author (zengrc)
*/
@Table ( name ="wxsa_subscribe" )
public class WxsaSubscribeModel extends BaseModel {
@Column(name = "open_id" )
private String openId;
@Column(name = "scene_id" )
private String sceneId;
/**
* ๆฅๆบid, t_media่กจ็id
*/
@FiledComment(text = "ๆฅๆบid, t_media่กจ็id" )
@Column(name = "source_id" )
private String sourceId;
/**
* ๆฏๅฆๅทฒ็ปๅๆถๅ
ณๆณจ
*/
@FiledComment(text = "ๆฏๅฆๅทฒ็ปๅๆถๅ
ณๆณจ" )
@Column(name = "has_unsubscribe" )
private Boolean hasUnsubscribe;
@Column(name = "create_time" )
private Date createTime;
@Column(name = "update_time" )
private Date updateTime;
public String getOpenId() {
return this.openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getSceneId() {
return this.sceneId;
}
public void setSceneId(String sceneId) {
this.sceneId = sceneId;
}
public String getSourceId() {
return this.sourceId;
}
public void setSourceId(String sourceId) {
this.sourceId = sourceId;
}
public Boolean getHasUnsubscribe() {
return this.hasUnsubscribe;
}
public void setHasUnsubscribe(Boolean hasUnsubscribe) {
this.hasUnsubscribe = hasUnsubscribe;
}
public Date getCreateTime() {
return this.createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return this.updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/service/impl/ShopGoodsSkuServiceImpl.java
package com.ningyuan.mobile.service.impl;
import com.ningyuan.base.BaseServiceImpl;
import com.ningyuan.mobile.daomapper.mapper.ShopGoodsSkuMapper;
import com.ningyuan.mobile.model.ShopGoodsSkuModel;
import com.ningyuan.mobile.service.IShopGoodsSkuService;
import org.springframework.stereotype.Service;
/**
* generated by Generate Service.groovy
* <p>Date: Sat Mar 21 14:55:34 CST 2020.</p>
*
* @author (zengrc)
*/
@Service
public class ShopGoodsSkuServiceImpl extends BaseServiceImpl<ShopGoodsSkuMapper, ShopGoodsSkuModel> implements IShopGoodsSkuService {
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/daomapper/mapper/ShopFavoriteMapper.java
package com.ningyuan.mobile.daomapper.mapper;
import tk.mybatis.mapper.common.Mapper;
import com.ningyuan.mobile.model.ShopFavoriteModel;
/**
* generated by Generate Mapper.groovy
* <p>Date: Tue Mar 24 16:55:30 CST 2020.</p>
*
* @author (zengrc)
*/
public interface ShopFavoriteMapper extends Mapper<ShopFavoriteModel> {
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/dto/CartAddDto.java
package com.ningyuan.mobile.dto;
import com.ningyuan.utils.CreateGUID;
public class CartAddDto {
private Long idGoods;
private Integer count;
private Long idSku;
private String openId;
public static void main(String[] args) {
System.out.println(CreateGUID.createGuId());
}
public Long getIdGoods() { return idGoods; }
public void setIdGoods(Long idGoods) { this.idGoods = idGoods; }
public Integer getCount() { return count; }
public void setCount(Integer count) { this.count = count; }
public Long getIdSku() { return idSku; }
public void setIdSku(Long idSku) { this.idSku = idSku; }
public String getOpenId() { return openId; }
public void setOpenId(String openId) { this.openId = openId; }
}
<file_sep>/admin/src/main/webapp/app/directive/popup/popupCtrl.js
"use strict";
app.controller("popopCtrl", function ($scope, $req) {
$scope.popupInfo = {
title: "ๆ็คบ",
content: "ๆ็คบๅ
ๅฎน",
btnCloseText: "ๅๆถ",
btnRightStyle: "btn-primary",
btnRightText: "็กฎๅฎ"
};
$scope.popupClick = function () {
alert("็นๅป็กฎๅฎ");
}
});<file_sep>/admin/src/main/webapp/app/customer/js/unConfirmUserInfoService.js
(function () {
app.service('unConfirmUserInfoService', unConfirmUserInfoServiceFn);
function unConfirmUserInfoServiceFn($req) {
this.getUnconfirmList = function ($scope) {
$scope.initList('/user/list/unConfirm', {});
};
this.updateConfirm = function (id) {
let param = {"id": id}
return $req.post('/user/confirm/update', param);
}
}
}());<file_sep>/admin/src/main/webapp/app/customer/js/addressInfoCtrl.js
(function () {
app.controller('addressInfoCtrl', addressInfoCtrlFn);
function addressInfoCtrlFn($scope, addressInfoService) {
$scope.addressModel = {};
addressInfoService.getAddressList($scope);
}
}());<file_sep>/wx/src/main/java/com/ningyuan/wx/service/impl/WxsaCustomerServiceImpl.java
package com.ningyuan.wx.service.impl;
import com.ningyuan.base.BaseServiceImpl;
import com.ningyuan.wx.daomapper.mapper.WxsaCustomerMapper;
import com.ningyuan.wx.model.wxsa.WxsaCustomerModel;
import com.ningyuan.wx.service.IWxsaCustomerService;
import org.springframework.stereotype.Service;
/**
* generated by Generate Service.groovy
* <p>Date: Tue Aug 20 09:48:12 CST 2019.</p>
*
* @author (zengrc)
*/
@Service
public class WxsaCustomerServiceImpl extends BaseServiceImpl<WxsaCustomerMapper, WxsaCustomerModel> implements IWxsaCustomerService {
@Override
public void saveCustomer(String openId, WxsaCustomerModel customerModel) {
WxsaCustomerModel exist = this.getByOpenId(openId);
if (null == exist) {
customerModel.setOpenId(openId);
this.insertSelective(customerModel);
} else {
customerModel.setId(exist.getId());
this.updateByPrimaryKeySelective(customerModel);
}
}
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/daomapper/mapper/ShopCartMapper.java
package com.ningyuan.mobile.daomapper.mapper;
import com.ningyuan.mobile.dto.ShopCartDto;
import tk.mybatis.mapper.common.Mapper;
import com.ningyuan.mobile.model.ShopCartModel;
import java.util.List;
/**
* generated by Generate Mapper.groovy
* <p>Date: Sat Mar 21 14:55:34 CST 2020.</p>
*
* @author (zengrc)
*/
public interface ShopCartMapper extends Mapper<ShopCartModel> {
List<ShopCartDto> queryCart(String openId);
}
<file_sep>/wx/src/main/java/com/ningyuan/wx/daomapper/mapper/WxRelateMapper.java
package com.ningyuan.wx.daomapper.mapper;
import tk.mybatis.mapper.common.Mapper;
import com.ningyuan.wx.model.WxRelateModel;
/**
* generated by Generate Mapper.groovy
* <p>Date: Mon Mar 25 15:39:26 CST 2019.</p>
*
* @author (zengrc)
*/
public interface WxRelateMapper extends Mapper<WxRelateModel> {
}
<file_sep>/admin/src/main/java/com/ningyuan/route/service/IBgRoleService.java
package com.ningyuan.route.service;
import com.ningyuan.base.IBaseService;
import com.ningyuan.route.model.BgRoleModel;
import java.util.List;
/**
* generated by Generate Service.groovy
* <p>Date: Wed Mar 20 14:42:20 CST 2019.</p>
*
* @author (zengrc)
*/
public interface IBgRoleService extends IBaseService<BgRoleModel> {
List<BgRoleModel> getRolesByUser(Long id);
}
<file_sep>/wx/src/main/java/com/ningyuan/wx/model/wxsa/WxsaCustomerModel.java
package com.ningyuan.wx.model.wxsa;
import com.ningyuan.base.BaseModel;
import com.ningyuan.base.annotation.FiledComment;
import javax.persistence.Column;
import javax.persistence.Table;
import java.util.Date;
/**
* generated by Generate POJOs.groovy
* <p>Date: Mon Sep 02 10:15:06 CST 2019.</p>
*
* @author (zengrc)
*/
@Table ( name ="wxsa_customer" )
public class WxsaCustomerModel extends BaseModel {
@Column(name = "open_id" )
private String openId;
/**
* ้ข็บฆid
*/
@FiledComment(text = "้ข็บฆid" )
@Column(name = "appoint_id" )
private String appointId;
/**
* ๅญฆๅid
*/
@FiledComment(text = "ๅญฆๅid" )
@Column(name = "student_id" )
private String studentId;
/**
* ไธๅกๅid
*/
@FiledComment(text = "ไธๅกๅid" )
@Column(name = "counterman_id" )
private String countermanId;
/**
* ๅ
ณๆณจๆฅๆบ
*/
@FiledComment(text = "ๅ
ณๆณจๆฅๆบ" )
@Column(name = "parent_open_id" )
private String parentOpenId;
/**
* ๅ
ณๆณจๆฅๆบๆ็ซ
*/
@FiledComment(text = "ๅ
ณๆณจๆฅๆบๆ็ซ " )
@Column(name = "article_id" )
private String articleId;
@Column(name = "create_time" )
private Date createTime;
@Column(name = "update_time" )
private Date updateTime;
public String getOpenId() {
return this.openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getAppointId() {
return this.appointId;
}
public void setAppointId(String appointId) {
this.appointId = appointId;
}
public String getStudentId() {
return this.studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public String getCountermanId() {
return this.countermanId;
}
public void setCountermanId(String countermanId) {
this.countermanId = countermanId;
}
public String getParentOpenId() {
return this.parentOpenId;
}
public void setParentOpenId(String parentOpenId) {
this.parentOpenId = parentOpenId;
}
public String getArticleId() {
return this.articleId;
}
public void setArticleId(String articleId) {
this.articleId = articleId;
}
public Date getCreateTime() {
return this.createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return this.updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/model/ShopOrderItemModel.java
package com.ningyuan.mobile.model;
import com.ningyuan.base.BaseModel;
import com.ningyuan.base.annotation.FiledComment;
import javax.persistence.Column;
import javax.persistence.Table;
import java.math.BigDecimal;
import java.util.Date;
/**
* generated by Generate POJOs.groovy
* <p>Date: Tue Mar 24 19:29:46 CST 2020.</p>
*
* @author (zengrc)
*/
@Table ( name ="shop_order_item" )
public class ShopOrderItemModel extends BaseModel {
/**
* ๆฐ้
*/
@FiledComment(text = "ๆฐ้" )
@Column(name = "count" )
private BigDecimal count;
/**
* ๅๅid
*/
@FiledComment(text = "ๅๅid" )
@Column(name = "id_goods" )
private Long idGoods;
/**
* ๆๅฑ่ฎขๅid
*/
@FiledComment(text = "ๆๅฑ่ฎขๅid" )
@Column(name = "id_order" )
private Long idOrder;
/**
* skuId
*/
@FiledComment(text = "skuId" )
@Column(name = "id_sku" )
private Long idSku;
/**
* ๅไปท
*/
@FiledComment(text = "ๅไปท" )
@Column(name = "price" )
private BigDecimal price;
/**
* ๅ่ฎก
*/
@FiledComment(text = "ๅ่ฎก" )
@Column(name = "total_price" )
private BigDecimal totalPrice;
@Column(name = "create_time" )
private Date createTime;
@Column(name = "update_time" )
private Date updateTime;
public BigDecimal getCount() { return count; }
public void setCount(BigDecimal count) { this.count = count; }
public Long getIdGoods() {
return this.idGoods;
}
public void setIdGoods(Long idGoods) {
this.idGoods = idGoods;
}
public Long getIdOrder() {
return this.idOrder;
}
public void setIdOrder(Long idOrder) {
this.idOrder = idOrder;
}
public Long getIdSku() {
return this.idSku;
}
public void setIdSku(Long idSku) {
this.idSku = idSku;
}
public BigDecimal getPrice() { return price; }
public void setPrice(BigDecimal price) { this.price = price; }
public BigDecimal getTotalPrice() { return totalPrice; }
public void setTotalPrice(BigDecimal totalPrice) { this.totalPrice = totalPrice; }
public Date getCreateTime() {
return this.createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return this.updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
<file_sep>/swagger/src/main/java/com/ningyuan/swagger/SwaggerConfig.java
package com.ningyuan.swagger;
import com.ningyuan.core.Conf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
@Configuration //ๅฟ
้กปๅญๅจ
@EnableSwagger2 //ๅฟ
้กปๅญๅจ
@EnableWebMvc //ๅฟ
้กปๅญๅจ
@ComponentScan(basePackages = {"com.ningyuan.*.controller"})
public class SwaggerConfig {
@Bean
public Docket customDocket() {
if (Boolean.parseBoolean(Conf.get("swagger.show"))) {
//ๆทปๅ headๅๆฐstart
ParameterBuilder tokenPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<Parameter>();
tokenPar.name("openId")
.description("openId")
.modelRef(new ModelRef("string"))
.parameterType("header").required(false).build();
pars.add(tokenPar.build());
return new Docket(DocumentationType.SWAGGER_2).host(Conf.get("swagger.host")).apiInfo(apiInfo()).select()
.paths(PathSelectors.regex(Conf.get("swagger.paths.regex")))
.build()
.globalOperationParameters(pars)
;
} else {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
.paths(PathSelectors.none()) //ๅฆๆๆฏ็บฟไธ็ฏๅข๏ผๆทปๅ ่ทฏๅพ่ฟๆปค๏ผ่ฎพ็ฝฎไธบๅ
จ้จ้ฝไธ็ฌฆๅ
.build();
}
}
private ApiInfo apiInfo() {
Contact contact = new Contact("xxx", "http://www.ningyuanxinxi.com/", "<EMAIL>");
return new ApiInfoBuilder().title("APIๆฅๅฃ").description("APIๆฅๅฃ").contact(contact).version("1.1.0").build();
}
}
<file_sep>/admin/src/main/java/com/ningyuan/route/service/impl/BgResourceServiceImpl.java
package com.ningyuan.route.service.impl;
import com.ningyuan.base.BaseServiceImpl;
import com.ningyuan.route.daomapper.mapper.BgResourceMapper;
import com.ningyuan.route.model.BgResourceModel;
import com.ningyuan.route.service.IBgResourceService;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* generated by Generate Service.groovy
* <p>Date: Wed Mar 20 14:42:20 CST 2019.</p>
*
* @author (zengrc)
*/
@Service
public class BgResourceServiceImpl extends BaseServiceImpl<BgResourceMapper, BgResourceModel> implements IBgResourceService {
@Override
public List<BgResourceModel> getResourcesByRole(long id) {
return this.mapper.getResourcesByRole(id);
}
/*@Override
public List<BgResourceRouteDto> getResourcesByRoute(long id) {
return this.mapper.getResourcesByRoute(id);
}*/
}
<file_sep>/wx/src/main/java/com/ningyuan/wx/utils/Sha1Util.java
package com.ningyuan.wx.utils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.util.*;
/*
'============================================================================
'api่ฏดๆ๏ผ
'createSHA1Signๅๅปบ็ญพๅSHA1
'getSha1()Sha1็ญพๅ
'============================================================================
'*/
public class Sha1Util {
public static String getTimeStamp() {
return String.valueOf(System.currentTimeMillis() / 1000);
}
//ๅๅปบ็ญพๅSHA1
public static String createSHA1Sign(SortedMap<String, String> signParams) throws Exception {
StringBuffer sb = new StringBuffer();
Set es = signParams.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
sb.append(k + "=" + v + "&");
//่ฆ้็จURLENCODER็ๅๅงๅผ๏ผ
}
String params = sb.substring(0, sb.lastIndexOf("&"));
return getSha1(params);
}
//Sha1็ญพๅ
public static String getSha1(String str) {
if (str == null || str.length() == 0) {
return null;
}
char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f'};
try {
MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
mdTemp.update(str.getBytes("GBK"));
byte[] md = mdTemp.digest();
int j = md.length;
char buf[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
buf[k++] = hexDigits[byte0 & 0xf];
}
return new String(buf);
} catch (Exception e) {
return null;
}
}
public static String getSign(SortedMap<String, String> signParams, String key) {
StringBuffer sb = new StringBuffer();
Set es = signParams.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
sb.append(k + "=" + v + "&");
//่ฆ้็จURLENCODER็ๅๅงๅผ๏ผ
}
String params = sb.append("key=" + key).toString();
String md5Params = getSha1(params).toUpperCase();
System.out.println("md5Params:" + md5Params);
return md5Params;
}
public static String map2Sting(SortedMap<String, String> signParams) {
StringBuffer sb = new StringBuffer();
Set es = signParams.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
sb.append(k + "=" + v + "&");
//่ฆ้็จURLENCODER็ๅๅงๅผ๏ผ
}
String params = sb.substring(0, sb.lastIndexOf("&"));
System.out.println("sha1 sb:" + params);
return params;
}
public static String MapToXML(Map map) {
StringBuffer sb = new StringBuffer();
sb.append("<xml>");
mapToXMLTest2(map, sb);
sb.append("</xml>");
try {
return new String(sb.toString().getBytes("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static void mapToXMLTest2(Map map, StringBuffer sb) {
Set set = map.keySet();
for (Iterator it = set.iterator(); it.hasNext(); ) {
String key = (String) it.next();
Object value = map.get(key);
if (null == value)
value = "";
if (value.getClass().getName().equals("java.util.ArrayList")) {
ArrayList list = (ArrayList) map.get(key);
sb.append("<" + key + ">");
for (int i = 0; i < list.size(); i++) {
HashMap hm = (HashMap) list.get(i);
mapToXMLTest2(hm, sb);
}
sb.append("</" + key + ">");
} else {
if (value instanceof HashMap) {
sb.append("<" + key + ">");
mapToXMLTest2((HashMap) value, sb);
sb.append("</" + key + ">");
} else {
sb.append("<" + key + ">" + value + "</" + key + ">");
}
}
}
}
public static String postData(String urlStr, String data) {
return postData(urlStr, data, null);
}
public static String postData(String urlStr, String data, String contentType) {
BufferedReader reader = null;
try {
URL url = new URL(urlStr);
URLConnection conn = url.openConnection();
System.out.println("conn:" + conn.getURL());
conn.setDoOutput(true);
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
/*if(StringUtils.isNotBlank(contentType))
conn.setRequestProperty("content-type", contentType);*/
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
if (data == null) {
data = "";
}
writer.write(data);
writer.flush();
writer.close();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append("\r\n");
}
System.out.println("Stringbuilder" + sb);
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
//logger_.error("Error connecting to " + urlStr + ": " + e.getMessage());
} finally {
try {
if (reader != null)
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
public static void main(String[] args) {
// Auto-generated method stub
String ss = "jsapi_ticket=bxLdikRXVbTPdHSM05e5u_TYBj0a_bMC8nK1aARl0B0FNu8_m0D7q5CC8UquMyiH3TIT_B2HSl2Bpo6YJ5Flvw&noncestr=test×tamp=1527753326447&url=http://dasitest.com.ngrok.xiaomiqiu.cn/dasi/jsp/bg/referral/share.jsp";
if(getSha1(ss).equals("55712a354c7699785e9abec62e8a73c20bf6c3cc")){
System.out.println("========");
} else {
System.out.println(getSha1(ss));
}
}
}
<file_sep>/admin/src/main/webapp/app/directive/popup/popupDirective.js
"use strict";
app.directive("popup", function () {
return {
restrict:"EACM",
transclude:true,
scope: false,
templateUrl: appPath + '/directive/popup/popup.html',
}
});<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/daomapper/mapper/ShopAddressMapper.java
package com.ningyuan.mobile.daomapper.mapper;
import tk.mybatis.mapper.common.Mapper;
import com.ningyuan.mobile.model.ShopAddressModel;
/**
* generated by Generate Mapper.groovy
* <p>Date: Sat Mar 21 14:55:34 CST 2020.</p>
*
* @author (zengrc)
*/
public interface ShopAddressMapper extends Mapper<ShopAddressModel> {
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/dto/ShopCartDto.java
package com.ningyuan.mobile.dto;
import com.ningyuan.mobile.model.ShopGoodsModel;
import com.ningyuan.mobile.model.ShopGoodsSkuModel;
import java.math.BigDecimal;
public class ShopCartDto {
private Long id;
private ShopGoodsModel goods;
private ShopGoodsSkuModel skuModel;
private Long idGoods;
private Long idSku;
private BigDecimal amount;
private BigDecimal price;
private BigDecimal fare;
public BigDecimal getPrice() {
if (idSku != null) {
return skuModel.getPrice();
}
return goods.getPrice();
}
public BigDecimal getFare() {
return goods.getFare();
}
public String getTitle() {
return idSku != null ? getGoods().getName() + " " + getSkuModel().getCodeName() : getGoods().getName();
}
public Long getIdGoods() {
return idGoods;
}
public void setIdGoods(Long idGoods) {
this.idGoods = idGoods;
}
public ShopGoodsModel getGoods() {
return goods;
}
public void setGoods(ShopGoodsModel goods) {
this.goods = goods;
}
public Long getIdSku() {
return idSku;
}
public void setIdSku(Long idSku) {
this.idSku = idSku;
}
public ShopGoodsSkuModel getSkuModel() {
return skuModel;
}
public void setSkuModel(ShopGoodsSkuModel skuModel) {
this.skuModel = skuModel;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
<file_sep>/mobile-core/src/main/java/com/ningyuan/base/BaseController.java
package com.ningyuan.base;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BaseController {
protected transient Logger log = LoggerFactory.getLogger(getClass());
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/model/ShopOrderModel.java
package com.ningyuan.mobile.model;
import com.ningyuan.base.BaseModel;
import com.ningyuan.base.annotation.FiledComment;
import javax.persistence.Column;
import javax.persistence.Table;
import java.math.BigDecimal;
import java.util.Date;
/**
* generated by Generate POJOs.groovy
* <p>Date: Sat Mar 21 14:55:34 CST 2020.</p>
*
* @author (zengrc)
*/
@Table ( name ="shop_order" )
public class ShopOrderModel extends BaseModel {
/**
* ๆถ่ดงไฟกๆฏ
*/
@FiledComment(text = "ๆถ่ดงไฟกๆฏ" )
@Column(name = "id_address" )
private Long idAddress;
@Column(name = "open_id" )
private String openId;
/**
* ่ฎขๅๅคๆณจ
*/
@FiledComment(text = "่ฎขๅๅคๆณจ" )
@Column(name = "message" )
private String message;
/**
* ่ฎขๅๅท
*/
@FiledComment(text = "่ฎขๅๅท" )
@Column(name = "order_sn" )
private String orderSn;
/**
* ๅฎไป้้ข
*/
@FiledComment(text = "ๅฎไป้้ข" )
@Column(name = "real_price" )
private BigDecimal realPrice;
/**
* ็ถๆ
*/
@FiledComment(text = "็ถๆ" )
@Column(name = "status" )
private Integer status;
/**
* ๆป้้ข
*/
@FiledComment(text = "ๆป้้ข" )
@Column(name = "total_price" )
private BigDecimal totalPrice;
@FiledComment(text = "ๆฏๅฆๆฏไป" )
@Column(name = "has_pay" )
private Boolean hasPay;
public Long getIdAddress() {
return this.idAddress;
}
public void setIdAddress(Long idAddress) {
this.idAddress = idAddress;
}
public String getOpenId() { return openId; }
public void setOpenId(String openId) { this.openId = openId; }
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
public String getOrderSn() {
return this.orderSn;
}
public void setOrderSn(String orderSn) {
this.orderSn = orderSn;
}
public BigDecimal getRealPrice() { return realPrice; }
public void setRealPrice(BigDecimal realPrice) { this.realPrice = realPrice; }
public Integer getStatus() { return status; }
public void setStatus(Integer status) { this.status = status; }
public BigDecimal getTotalPrice() { return totalPrice; }
public void setTotalPrice(BigDecimal totalPrice) { this.totalPrice = totalPrice; }
public Boolean getHasPay() { return hasPay; }
public void setHasPay(Boolean hasPay) { this.hasPay = hasPay; }
}
<file_sep>/wx/src/main/java/com/ningyuan/wx/config/WxMpHttpClientBuilder.java
package com.ningyuan.wx.config;
import me.chanjar.weixin.common.util.http.apache.ApacheHttpClientBuilder;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class WxMpHttpClientBuilder implements ApacheHttpClientBuilder {
@Autowired
private CloseableHttpClient httpClient;
@Override
public CloseableHttpClient build() {
return httpClient;
}
@Override
public ApacheHttpClientBuilder httpProxyHost(String httpProxyHost) {
return this;
}
@Override
public ApacheHttpClientBuilder httpProxyPort(int httpProxyPort) {
return this;
}
@Override
public ApacheHttpClientBuilder httpProxyUsername(String httpProxyUsername) {
return this;
}
@Override
public ApacheHttpClientBuilder httpProxyPassword(String httpProxyPassword) {
return this;
}
@Override
public ApacheHttpClientBuilder sslConnectionSocketFactory(SSLConnectionSocketFactory sslConnectionSocketFactory) {
return this;
}
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/controller/ShopRedPackController.java
package com.ningyuan.mobile.controller;
import com.ningyuan.base.BaseController;
import com.ningyuan.base.exception.ErrorMessage;
import com.ningyuan.base.exception.StatelessException;
import com.ningyuan.core.Conf;
import com.ningyuan.core.Context;
import com.ningyuan.mobile.dto.RedPacketDto;
import com.ningyuan.mobile.model.ShopCustomerModel;
import com.ningyuan.mobile.model.ShopWalletModel;
import com.ningyuan.mobile.service.IShopCustomerService;
import com.ningyuan.mobile.service.IShopReceiveRecordService;
import com.ningyuan.mobile.service.IShopWalletService;
import com.ningyuan.utils.CommonUtil;
import com.ningyuan.wx.model.WxPay2userResultModel;
import com.ningyuan.wx.utils.AppletUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.*;
@Controller
@RequestMapping("shop/redPack")
public class ShopRedPackController extends BaseController {
@Autowired
private IShopWalletService walletService;
@Autowired
private IShopReceiveRecordService recordService;
@Autowired
private IShopCustomerService customerService;
@ApiOperation(value = "ๅฏๆ็ฐๆป้้ข")
@PostMapping("canCashSum")
@ResponseBody
public String canCashSum() {
ShopWalletModel walletModel =new ShopWalletModel();
walletModel.setOpenId(Context.getOpenId());
walletModel = walletService.selectLimitOne(walletModel);
return walletModel != null ? walletModel.getFinance() : "0";
}
@ApiOperation(value = "ๆปๆถ็")
@PostMapping("cashSum")
@ResponseBody
public String cashSum() {
String cashSum = walletService.getCashSum();
return cashSum != null ? cashSum : "0";
}
@ApiOperation(value = "้ขๅ่ฎฐๅฝ")
@PostMapping("getList")
@ResponseBody
public Map<String, List<RedPacketDto>> getCashList(Integer pageNum, Integer pageSize) {
CommonUtil.initPageInfo(pageNum, pageSize, Integer.valueOf(Conf.get("theme.getCashList.pageSize:10")));
Map<String, List<RedPacketDto>> map = new HashMap<>();
List<RedPacketDto> list = walletService.getCashList(Context.getOpenId());
List<RedPacketDto> cashList = new ArrayList<>();
List<RedPacketDto> receiveList = new ArrayList<>();
List<RedPacketDto> recordList = new ArrayList<>();
Integer cashtype = Integer.parseInt(Conf.get("wallet.cash.type:2"));
Integer openType = Integer.parseInt(Conf.get("wallet.open.type:3"));
Integer receiveType = Integer.parseInt(Conf.get("wallet.receive.type:6"));
list.forEach(redRacket -> {
if (redRacket.getOptType().equals(cashtype)) {
cashList.add(redRacket);
} else if (redRacket.getOptType().equals(openType) || redRacket.getOptType().equals(receiveType)) {
receiveList.add(redRacket);
} else {
recordList.add(redRacket);
}
});
map.put("cashList", cashList);
map.put("receiveList", receiveList);
map.put("recordList", recordList);
return map;
}
@ApiOperation(value = "ๆ็ฐ")
@PostMapping("cash")
@ResponseBody
public Object cash() throws Exception{
ShopWalletModel walletModel =new ShopWalletModel();
String openId = Context.getOpenId();
walletModel.setOpenId(openId);
walletModel = walletService.selectLimitOne(walletModel);
if (walletModel != null && Double.parseDouble(walletModel.getFinance()) > 0.0) {
WxPay2userResultModel resultModel = AppletUtils.pay2User(Conf.get("wxsa.appId"), openId
, (int)(Double.parseDouble(walletModel.getFinance()) * 100) + "", Conf.get("wx.pay2user.desc")
, Conf.get("shop.cash.reason"));
if (StringUtils.equals("SUCCESS", resultModel.getResultCode())) {
recordService.insertRecord(Conf.get("shop.cash.type:2"), walletModel.getFinance(), openId);
walletService.updateWallet(openId);
return ErrorMessage.getSuccess();
}
}
return ErrorMessage.getFailure();
}
@ApiOperation(value = "้ขๅ็บขๅ
")
@PostMapping("open/redpacket")
@ResponseBody
public String openRedpacket() throws StatelessException {
String openId = Context.getOpenId();
ShopCustomerModel customerModel = customerService.checkuser(openId);
if (customerModel == null) {
throw new StatelessException(ErrorMessage.getFailure());
}
String money = customerService.openRedpacket(openId);
return money;
}
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/service/impl/IAttrKeyServiceImpl.java
package com.ningyuan.mobile.service.impl;
import com.ningyuan.base.BaseServiceImpl;
import com.ningyuan.mobile.daomapper.mapper.ShopAttrKeyMapper;
import com.ningyuan.mobile.model.ShopAttrKey;
import com.ningyuan.mobile.model.ShopAttrVal;
import com.ningyuan.mobile.service.IAttrKeyService;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* generated by Generate Service.groovy
* <p>Date: Sat Mar 21 14:55:34 CST 2020.</p>
*
* @author (zengrc)
*/
@Service
public class IAttrKeyServiceImpl extends BaseServiceImpl<ShopAttrKeyMapper, ShopAttrKey> implements IAttrKeyService {
@Override
public List<ShopAttrVal> getAttrVals(Long keyId) {
return this.mapper.getAttrVals(keyId);
}
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/controller/CategoryController.java
package com.ningyuan.mobile.controller;
import com.ningyuan.base.BaseController;
import com.ningyuan.bean.front.Rets;
import com.ningyuan.mobile.model.ShopCategoryModel;
import com.ningyuan.mobile.service.ICategoryService;
import io.swagger.annotations.ApiOperation;
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 java.util.List;
@Controller
@RequestMapping("category")
public class CategoryController extends BaseController {
@Autowired
private ICategoryService categoryService;
@ApiOperation(value = "้ฆ้กตๅพ็่ตๆบๅ ่ฝฝ")
@RequestMapping(value = "/list",method = RequestMethod.GET)
@ResponseBody
public Object list() {
List<ShopCategoryModel> list = categoryService.listCategory();
list.forEach(item->{
item.setBannerList(categoryService.listBannerRel(item.getId()));
});
return Rets.success(list);
}
}
<file_sep>/admin/src/main/java/com/ningyuan/route/service/impl/ShopUserServiceImpl.java
package com.ningyuan.route.service.impl;
import com.ningyuan.core.Conf;
import com.ningyuan.route.daomapper.mapper.ShopUserMapper;
import com.ningyuan.route.dto.SettingDto;
import com.ningyuan.route.dto.ShopMarketRatioDto;
import com.ningyuan.route.dto.ShopUserDto;
import com.ningyuan.route.dto.ShopUserQueryDto;
import com.ningyuan.route.service.IShopUserService;
import com.ningyuan.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* generated by Generate Service.groovy
* <p>Date: Wed Mar 20 14:42:20 CST 2019.</p>
*
* @author (zengrc)
*/
@Service
public class ShopUserServiceImpl implements IShopUserService {
@Autowired
private ShopUserMapper shopUserMapper;
@Override
public List<ShopUserDto> listConfirmUser(ShopUserQueryDto queryDto) {
return shopUserMapper.listConfirmUser(queryDto);
}
@Override
public List<ShopUserDto> listUnConfirmUser(ShopUserQueryDto queryDto) {
return shopUserMapper.listUnConfirmUser(queryDto);
}
@Override
public void updateConfirm(Long id) {
shopUserMapper.updateConfirm(id);
}
@Override
public void updateUserByid(ShopUserDto shopUserDto) {
shopUserMapper.updateUserByid(shopUserDto);
}
@Override
public List<ShopMarketRatioDto> getMarketRatio() {
List<ShopMarketRatioDto> marketRatio = shopUserMapper.getMarketRatio();
return marketRatio;
}
@Override
public void updateSetting(List<ShopMarketRatioDto> marketRatio) {
shopUserMapper.updateMarketRatio(marketRatio);
}
@Override
public void addRedpacketAmount(Long id, String openId, Integer addAmount, Integer amount) {
shopUserMapper.updateRedpacketAmount(id, amount);
if (StringUtil.isNotEmpty(openId)) {
shopUserMapper.insertRecord(openId, addAmount, Conf.get("wallet.receive.type:6"));
}
}
@Override
public void minusRedpacketAmount(Long id, Integer amount) {
shopUserMapper.updateRedpacketAmount(id, amount);
}
@Override
public Integer getShopCustomer(Long id) {
return shopUserMapper.getCustomer(id);
}
}
<file_sep>/mobile-core/src/main/java/com/ningyuan/utils/HttpUtil.java
package com.ningyuan.utils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
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.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
public class HttpUtil {
//private static final Log logger = Logs.get();
private final static int CONNECT_TIMEOUT = 5000; // in milliseconds
private final static String DEFAULT_ENCODING = "UTF-8";
public static String postData(String urlStr, String data){
return postData(urlStr, data, null);
}
public static String postData(String urlStr, String data, String contentType){
BufferedReader reader = null;
try {
URL url = new URL(urlStr);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setConnectTimeout(CONNECT_TIMEOUT);
conn.setReadTimeout(CONNECT_TIMEOUT);
if(contentType != null)
conn.setRequestProperty("content-type", contentType);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);
if(data == null)
data = "";
writer.write(data);
writer.flush();
writer.close();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_ENCODING));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append("\r\n");
}
return sb.toString();
} catch (IOException e) {
//logger.error("Error connecting to " + urlStr + ": " + e.getMessage());
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException e) {
}
}
return null;
}
/**
* ่ทๅ ๅ
่ฃ
้ฒXss Sqlๆณจๅ
ฅ็ HttpServletRequest
* @return request
*/
public static HttpServletRequest getRequest() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
return new WafRequestWrapper(request);
}
/**
* ่ทๅ HttpServletRequest
*/
public static HttpServletResponse getResponse() {
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
return response;
}
}
<file_sep>/mobile-api/src/main/java/com/ningyuan/mobile/service/impl/ShopAddressServiceImpl.java
package com.ningyuan.mobile.service.impl;
import com.ningyuan.base.BaseServiceImpl;
import com.ningyuan.mobile.daomapper.mapper.ShopAddressMapper;
import com.ningyuan.mobile.model.ShopAddressModel;
import com.ningyuan.mobile.service.IShopAddressService;
import org.springframework.stereotype.Service;
/**
* generated by Generate Service.groovy
* <p>Date: Sat Mar 21 14:55:34 CST 2020.</p>
*
* @author (zengrc)
*/
@Service
public class ShopAddressServiceImpl extends BaseServiceImpl<ShopAddressMapper, ShopAddressModel> implements IShopAddressService {
@Override
public ShopAddressModel getDefaultAddr(String openId) {
ShopAddressModel addressModel = new ShopAddressModel();
addressModel.setOpenId(openId);
addressModel.setIsDefault(Boolean.TRUE);
return this.selectLimitOne(addressModel);
}
}
<file_sep>/admin/src/main/java/com/ningyuan/route/service/IShopCustomerService.java
package com.ningyuan.route.service;
import com.ningyuan.route.dto.InviteQueryDto;
import com.ningyuan.route.dto.ShopAddressDto;
import com.ningyuan.route.dto.ShopInviterDto;
import com.ningyuan.route.dto.ShopOrderDto;
import java.util.List;
/**
* generated by Generate Service.groovy
* <p>Date: Wed Mar 20 14:42:20 CST 2019.</p>
*
* @author (zengrc)
*/
public interface IShopCustomerService {
List<ShopInviterDto> getInviteList(InviteQueryDto inviteQueryDto);
List<ShopAddressDto> getAddressList(String mobile, String defaultAddress);
List<ShopOrderDto> getOrderList(String orderSn);
void updateOrder(ShopOrderDto orderDto);
}
<file_sep>/admin/src/main/webapp/app/lib/routesProvider.js
"use strict"
app.provider('$routesData', function () {
this.getRoutes = function () {
let routes = [];
let data = {};
$.ajax({ url: path + "/menu/states",
type:"POST",
async:false,
data: data,
success: function(response){
routes = response;
}});
return routes;
}
this.$get = function () {
}
});<file_sep>/mobile-core/src/main/java/com/ningyuan/base/exception/StatelessException.java
package com.ningyuan.base.exception;
public class StatelessException extends BaseException {
public StatelessException() {
super.errorMessage = ErrorMessage.getFailure();
}
public StatelessException(ErrorMessage errorMessage) {
super(errorMessage.getErrorCode(), errorMessage);
}
public StatelessException(String message, ErrorMessage errorMessage) {
super(message, errorMessage);
}
public StatelessException(String message, Throwable cause, ErrorMessage errorMessage) {
super(message, cause, errorMessage);
}
public StatelessException(Throwable cause, ErrorMessage errorMessage) {
super(cause, errorMessage);
}
public StatelessException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, ErrorMessage errorMessage) {
super(message, cause, enableSuppression, writableStackTrace, errorMessage);
}
}
| 37e17c5903da96a7ee60d0e192000677f4749a8f | [
"JavaScript",
"Java",
"Maven POM"
] | 97 | Java | candy-wei/dev | 923ae16c99208c12f8f5e57e213911b3f2e5bb2d | 0ca212d64afd601182a745d682ac700cf19aa941 |
refs/heads/master | <repo_name>fruttasecca/unitn_cv_2018_project<file_sep>/util.py
#!/usr/bin/python3
import numpy as np
import cv2
def parse_truth(truth):
"""
Parse the ground truth file, mapping each frame to the
number of people in it.
:param truth: Path to the truth file.
:return: A dict mapping keys to the true number of people contained in it.
"""
frame_to_count = dict()
with open(truth, "r") as file:
for line in file:
frame, id, posx, posy = line.split(',')
frame = int(frame)
frame_to_count[frame] = frame_to_count.get(frame, 0) + 1
return frame_to_count
def box_contains_point(bx, by, bw, bh, px, py):
"""
Check if a box contains a point.
:param bx:
:param by:
:param bw:
:param bh:
:param px:
:param py:
:return:
"""
return bx <= px <= (bx + bw) and by <= py <= (by + bh)
def draw_people_counter(frame, count):
"""
Draw the counter of people in the middle of the screen.
:param frame: Frame on which to write.
:param count: Value to be written, an integer.
:return:
"""
height, width, _ = frame.shape
# set parameters
corner_point = (int(0.35 * width), int(height * 0.15)) # bottom left corner
scale = 4
color = (0, 0, 255)
width = 10
# draw
cv2.putText(frame, 'People: %s' % count, corner_point, cv2.FONT_HERSHEY_PLAIN, scale, color, width)
def generate_center_feature(features, boxes, n, thres=40):
"""
Add features to empty boxes (no feature points inside them) that have an area greater than
a certain threshold, features are added by considering
the center of the box as a feature.
This is done with the idea that big boxes are probably correct foreground detections, and if they
are empty its because the feature detector is failing.
:param features: Existing feature points.
:param boxes: List of boxes.
:param n: Number of features to have for each empty box, this is done to get enough features
to trigger the entity matcher (feature swarm) to consider this box.
:param thres: Area threshold, boxes below this area are not candidates for new features.
:return:
"""
new_features = []
for i, box in enumerate(boxes):
x, y, w, h = box
if (w * h) > thres:
hasfeatures = False
index = 0
while index < len(features) and not hasfeatures:
feat = features[index, 0]
fx = feat[0]
fy = feat[1]
hasfeatures = box_contains_point(x, y, w, h, fx, fy)
index += 1
if not hasfeatures:
for i in range(n):
new_features.append((x + w / 2, y + h / 2))
new_features = np.array(new_features, dtype=np.float32)
new_features.resize(len(new_features), 1, 2)
return new_features
def filter_contours(contours, thres):
"""
Filter out contours based on area and position.
:param contours: List of contours (x,y,w,h).
:param thres: Contours with an area lower than this are filtered out.
:return: List of (filtered) contours.
"""
filtered = []
for c in contours:
rect = cv2.boundingRect(c)
x, y, w, h = rect
area = w * h
if area > thres and 50 < y < 650:
filtered.append(c)
return filtered
def find_selected_id_in_history(history, selected_frame, posx, posy):
"""
Find which one of our ids matches with the selected pedestrian to be tracked,
which was in posx and posy at the selected_frame.
:param history:
:param selected_frame:
:param posx:
:param posy:
:return:
"""
mindist = 1e10
minid = -1
# go through the history of each id and find which was the nearest
# when the pedestrian to follow appeared in the scene
for id, h in history.items():
if h[0][2] <= selected_frame:
for (x, y, frame) in h:
if frame == selected_frame:
dist = (posx - x) ** 2 + (posy - y) ** 2
if dist < mindist:
mindist = dist
minid = id
return minid
def process_id_history(id, history, framebeg, frameend):
"""
Give the history of an identity, save the history
from a certain frame to another, writing it to a file
named "estimated_id_<identity number>.txt".
:param id: Id of the entity we are dealing with, used for the file name.
:param history: History of such identity.
:param framebeg: Beginning frame.
:param frameend: Ending frame.
"""
i = framebeg
with open("estimated_id_%i.txt" % id, "w") as file:
for (x, y, frame) in history:
if framebeg <= frame <= frameend:
file.write("%s,%s,%s\n" % (i, x, y))
i += 1
def resolve_candidates(boxes, point):
"""
Get the best box for a point, among the candidates, based
un distance.
This is something written hastly given that it's only
run once for the whole script.
Box to point matching is done with a rtree during the actual loop.
:param boxes:
:param point:
:return:
"""
if len(boxes) > 1:
# look for box with the minimum centre
mindist = 1e10
minbox = None
for i, box in enumerate(boxes):
x, y, w, h, _ = box
dist = ((x + w / 2) - point[0]) ** 2 + ((x + y / 2) - point[1]) ** 2
if dist < mindist:
mindist = dist
minbox = box
return minbox
# return the only box
return boxes[0]
<file_sep>/README.md
# unitn_cv_2018_project
Hasty implementation of a top view people tracker for the computer vision course in unitn.
#### Stuff in this reporistory:
- input video, video.mp4
- ouput video, result.mp4
- ground truth files
- estimated trajectories of selected pedestrians
- code (main.py, feature_swarm.py, util.py)
- report on this project
#### Requirements:
- numpy
- opencv
- the Rtree python package
In main.py you will obviousy find the main loop, feature_swarm
contains the tracking algorithm and util is where I have stuffed all the utility
stuff to avoid overly cluttering the code.
__To run the project just run main.py with python3, no arguments needed__;
it will output a file named output.mp4.
This is not a long term project or anything, do not expect tests or whatever.
Note that the names of some parameters or functions might not always be the same
in both the pseudocode (report) and the code.
<file_sep>/main.py
#!/usr/bin/python3
from feature_swarm import FeatureSwarm
from util import *
np.random.seed(1337)
# PARAMETERS
##########################
# KERNELS FOR DIFFERENT OPERATIONS
# not all of them are currently being used
kernel_opening = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2, 2))
kernel_closing = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (4, 4))
kernel_dilation = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
kernel_erosion = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
# MOG2 PARAMETERS
history = 20
varThreshold = 40
lr = 0.01
MOG2 = cv2.createBackgroundSubtractorMOG2(history, varThreshold, detectShadows=False)
# TRACKING
old_hue = None
feature_points = None # collected feature points that we are tracking
feature_swarm = None # class used to track all people
last_update = 0 # last time there was a detection using a feature detector (good features to track in our case)
frames_between_detection = 10 # do feature detection every n frames
# identified boxes, a list of boxes in the form of (x,y,w,h, id)
boxes_ided = []
lukas_kanade_params = dict(winSize=(10, 10),
maxLevel=2,
criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.80))
good_features_to_track_params = dict(maxCorners=1000, qualityLevel=0.01, minDistance=1, blockSize=5,
useHarrisDetector=True)
# stuff used to check on the error on the count of people of each frame
frame_counts = parse_truth("A1_groundtruthC.txt")
error_per_frame = 0
predicted_avg = 0
truth_avg = 0
# INPUT VIDEO
cap = cv2.VideoCapture('video.mp4')
width = int(cap.get(3))
height = int(cap.get(4))
has_new_frame, frame = cap.read()
print("Running video with witdh: %s, height: %s" % (width, height))
# OUTPUT VIDEO
fourcc = cv2.VideoWriter_fourcc(*'DIVX')
out = cv2.VideoWriter('output.mp4', fourcc, 20.0, (width, height))
# stuff needed to draw trajectories
color = np.random.randint(0, 255, (1000, 3))
trajectories_mask = np.zeros_like(frame)
subtract_traj_mask = np.ones_like(frame)
index = 0
while has_new_frame:
original = frame.copy()
# DETECTION PHASE
############################
# get hue plane, avoid shadows
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
hue, s, v = cv2.split(hsv)
hue = cv2.blur(hue, (4, 4)) # seems to help
# get foreground figures
foreground = MOG2.apply(hue, learningRate=lr)
# apply morphological transformations to clear away noise and conglomerate blobs
morph_transformed = cv2.morphologyEx(foreground, cv2.MORPH_OPEN, kernel_opening, iterations=1)
morph_transformed = cv2.morphologyEx(morph_transformed, cv2.MORPH_CLOSE, kernel_closing, iterations=5)
# get contours
contours, _ = cv2.findContours(morph_transformed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_KCOS)
contours = filter_contours(contours, 100)
boxes = [cv2.boundingRect(contour) for contour in contours]
# TRACKING PHASE
############################
# mask used to exclude feature points found by the feature detector
ret, mask = cv2.threshold(morph_transformed, 127, 255, cv2.THRESH_BINARY)
if old_hue is not None:
if feature_points is None:
"""
Get features, create labelings based on
boxes and features
"""
feature_points = cv2.goodFeaturesToTrack(old_hue, mask=foreground, **good_features_to_track_params)
# add features to empty boxes
a = generate_center_feature(feature_points, boxes, 1)
if feature_points is not None and len(feature_points) > 0:
feature_points = np.concatenate((feature_points, a), axis=0)
else:
feature_points = a
feature_swarm = FeatureSwarm(feature_points, boxes, max_points_per_box=40,
infer_thres=10, max_lost_dist=120, max_lost_id_age=50)
else:
# find the features points in the next frame
predicted_points, flags, err = cv2.calcOpticalFlowPyrLK(old_hue, hue, feature_points[:, :, :2], None,
**lukas_kanade_params)
# filter out lost points and update positions of the ones that we are keeping
feature_swarm.update_current_points(predicted_points, flags)
# find new features
if (index - last_update) > frames_between_detection:
last_update = index
feature_points = cv2.goodFeaturesToTrack(old_hue, mask=foreground, **good_features_to_track_params)
# add features to empty boxes
a = generate_center_feature(feature_points, boxes, 1)
if feature_points is not None and len(feature_points) > 0:
feature_points = np.concatenate((feature_points, a), axis=0)
else:
feature_points = a
else:
feature_points = None
# boxes identified by the feature swarm and their id
boxes_ided = feature_swarm.update(feature_points, boxes)
# features we will want to keep track at the next step
feature_points = feature_swarm.points
old_hue = hue
# DRAWING PHASE
############################
# draw frame number
cv2.putText(original, str(index), (1180, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0, 0, 255), 3)
# counter of number of people
draw_people_counter(original, len(contours))
# counters for number of people exiting/entering
if feature_swarm:
cv2.putText(original, "en:" + str(len(feature_swarm.entering_left)), (0, 640), cv2.FONT_HERSHEY_SIMPLEX, 1.5,
(0, 0, 255), 3)
cv2.putText(original, "ex:" + str(len(feature_swarm.exiting_left)), (0, 700), cv2.FONT_HERSHEY_SIMPLEX, 1.5,
(0, 0, 255), 3)
cv2.putText(original, "en:" + str(len(feature_swarm.entering_right)), (1170, 640), cv2.FONT_HERSHEY_SIMPLEX,
1.5, (0, 0, 255), 3)
cv2.putText(original, "ex:" + str(len(feature_swarm.exiting_right)), (1170, 700), cv2.FONT_HERSHEY_SIMPLEX, 1.5,
(0, 0, 255), 3)
# draw the tracks
for box in boxes_ided:
x, y, w, h, id = box
a = int(x + w / 2)
b = int(y + h / 2)
id = int(id)
trajectories_mask = cv2.line(trajectories_mask, (a, b), (a, b), color[id].tolist(), 15)
original = cv2.circle(original, (a, b), 5, color[id].tolist(), -1)
trajectories_mask = cv2.addWeighted(trajectories_mask, 0.95, 0, 0, 0)
original = cv2.add(original, cv2.bitwise_and(trajectories_mask, trajectories_mask, mask=(255 - mask)))
# draw lines for left and right gates
cv2.line(original, (120, 0), (120, 720), (255, 255, 125), 6)
cv2.line(original, (1160, 0), (1160, 720), (255, 255, 125), 6)
# draw ids
for box in boxes_ided:
x, y, w, h, id = box
id = int(id)
# cv2.rectangle(original, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(original, str(id), (int(x + w / 4), int(y + h / 2)), cv2.FONT_HERSHEY_SIMPLEX, 1.0,
(255, 0, 0), 3)
out.write(original)
cv2.imshow('frame', original)
# USER INPUT PHASE
############################
# press "s" to pause/unpause
# press "q" to qui
key = cv2.waitKey(1) & 0xFF
if key == ord("s"):
while True:
key2 = cv2.waitKey(1) or 0xff
if key2 == ord("s"):
break
elif key == ord("q"):
break
# get next frame and update counter
has_new_frame, frame = cap.read()
index += 1
# STATISTICS COLLECTION PHASE
############################
# check if the ground truth has any data on this frame
if index in frame_counts:
predicted_avg += len(contours)
truth_avg += frame_counts[index]
error_per_frame += abs(frame_counts[index] - len(contours))
# print statistics
# statistics relative to counting the number of people
error_per_frame /= len(frame_counts)
predicted_avg /= len(frame_counts)
truth_avg /= len(frame_counts)
print("Avg error per frame: %s" % error_per_frame)
print("Avg predicted per frame: %s" % predicted_avg)
print("Avg truth per frame: %s" % truth_avg)
"""
Save selected pedestrian trajectories to file. First we need
to find a matching between the id in the ground truth (selected pedestrian) and
an id in our history, once we have found that we write down its history
from a certain frame to another (based on the ground truth).
"""
# original = cv2.circle(original, (730, 350), 5, (255, 0, 255), -1) # 10 frame 1
# original = cv2.circle(original, (1280, 280), 5, (255, 0, 255), -1) # 36 frame 264
# original = cv2.circle(original, (4, 581), 5, (255, 0, 255), -1) # 42 253
id_of_selected10 = find_selected_id_in_history(feature_swarm.history, 1, 730, 350)
id_of_selected36 = find_selected_id_in_history(feature_swarm.history, 264, 1280, 280)
id_of_selected42 = find_selected_id_in_history(feature_swarm.history, 253, 4, 581)
process_id_history(10, feature_swarm.history[id_of_selected10], 1, 96)
process_id_history(36, feature_swarm.history[id_of_selected36], 264, 451)
process_id_history(42, feature_swarm.history[id_of_selected42], 253, 476)
# release resources and exit
cap.release()
out.release()
cv2.destroyAllWindows()
<file_sep>/feature_swarm.py
import math
import operator
from collections import Counter
import cv2
import numpy as np
import rtree.index # used to speed up/make scalable the implementation
from util import box_contains_point, resolve_candidates
class FeatureSwarm():
def __init__(self, points, boxes, max_points_per_box=20, infer_thres=5, max_lost_dist=10,
max_lost_id_age=40, max_point_age=80):
# number of processed frames
self.max_lost_id_age = max_lost_id_age
# number of identities seen, used to create an id for a new identity
self.identities_counter = 0
# max number of feature points that should be in a single bounding box
self.max_points_per_box = max_points_per_box
# max age of a feature point, points older that this are discarded
self.max_point_age = max_point_age
"""
A box will be assigned an identity i if the majority of points in that box
have decided have identity i and are >= self.infer_thres.
A new box will be created if there is a cluster of points with the same identity but
that do not have a box containing them.
"""
self.infer_thres = infer_thres
"""
Maximum distance threshold to associate a lost identity (which was lost in a certain position
x,y) to a box without identity.
"""
self.max_lost_dist = max_lost_dist
"""
Maximum age than a lost identity can have, identities that have been lost for too long are
considered definitively lost and not reusable.
"""
self.seen_frames = 0
# a list of boxes and their id, of the form (x,y,w,h,id)
self.boxes = None
# numpy array of points (x,y,id,to_be_removed)
self.points = None
# Stuff used to keep track of the history of identities, who is exiting or entering, etc
#####
# identities considered to have correctly left the scene
self.exited = set()
# identities that are moving out or entering
self.entering_right = set()
self.exiting_right = set()
self.entering_left = set()
self.exiting_left = set()
# identities that are currently considered lost
self.lost_identities = dict()
# history, for each identity a list of (x, y, frame index)
self.history = dict()
# wasted ids, which are ids that have been used for such a short amount of time
# that they are going to be reused
self.wasted = []
"""
We are going to "attach" to the matrix of x,y points
3 columns:
-an identity column, to what identity this point belong to, can also be
consider what identity a point is "voting" for for the box it is into
-age of the point
the np.float32 is needed to make opencv kanade not angry
"""
extra = np.ones((points.shape[0], 1, 2), dtype=np.float32)
points = np.concatenate((points, extra), axis=2)
points[:, :, 2] = -1 # no identity
# assign ids to each box
tmp = []
for box in boxes:
x, y, w, h = box
tmp.append((x, y, w, h, self.identities_counter))
self.identities_counter += 1
boxes = tmp
for point in points:
# map point to a box
candidate_boxes = []
for box in boxes:
x, y, w, h, _ = box
if box_contains_point(x, y, w, h, point[0][0], point[0][1]):
candidate_boxes.append(box)
if len(candidate_boxes) > 0:
assigned_box = resolve_candidates(candidate_boxes, point[0])
boxid = assigned_box[-1]
# set box to which the point belongs to
point[0, 2] = boxid
# this can be retrieved to have a list of boxes of the form (x,y,w,hue,id)
self.boxes = boxes
# this can be retrieved to have an array of the form (x,y,id,boxid,last time since assigned to a box)
self.points = points
def update_current_points(self, updated_points, flags):
"""
Remove points based on flags (1 to be kept, 0 to be removed),
update the x and y coordinates of remaining points.
If flags is none the function does not do anything.
:param updated_points: Numpy array of the same length of the current points of the instance of this class,
containing updated x and y coordinates for each point.
:param flags: Numpy array of the same length of the current points of the instance of this class,
containing either 1 of 0 for each point, 1 means that the point should be kept, 0 that the point
will be dropped.
"""
if flags is not None:
# keep only stuff that was not lost
updated_points = updated_points[flags == 1]
old_points = self.points[flags == 1]
# update positions (x,y) of points
old_points[:, 0:2] = updated_points[:, :]
# reshape needed because of how the opencv kanade implementation wants its inputs
self.points = old_points.reshape(-1, 1, 4)
def update(self, new_points, starting_boxes):
"""
Update the current status of the feature swarm, adding new points,
matching the input boxes and identities, and returning a list
of boxes (and inferred boxes) with their id.
:param new_points: np.array of shape (number of points, 1, 2) which is (number of points, 1, x and y).
:param starting_boxes: List of boxes of the form [x,y,w,h].
:return: List of boxes of the form (x,y,w,h,id).
"""
self.seen_frames += 1
self.points[:, 0, 3] += 1
"""
Add new feature points to our current points.
"""
if new_points is not None:
# format new points in the way we like
extra = np.ones((new_points.shape[0], 1, 2), dtype=np.float32)
new_points = np.concatenate((new_points, extra), axis=2)
new_points[:, :, 2] = -1 # no identity
# get as points the old ones + the new ones
self.points = np.concatenate((self.points, new_points), axis=0)
# points with identity mapped to boxes, boxes now have an identity
assigned_boxes = self.assign_decided_points_to_boxes(starting_boxes)
# grow more boxes based on clusters of points with the same identity (when there is no box with such identity)
self.infer_boxes(assigned_boxes)
# points with no identiy now have the same identity of the box they are contained into
self.assign_undecided_points_to_boxes(assigned_boxes)
# For each box keep only up to a maximum number of points
self.trim_boxes(assigned_boxes)
"""
Identities that are contended by multiple boxes are resolved,
boxes without identities have an identity assigned to them.
"""
boxes_ided = self.decide_contended_identities(assigned_boxes)
# keep track of history
for box in boxes_ided:
x, y, w, h, id = box
if id not in self.history:
self.history[id] = []
self.history[id].append((x + w / 2, y + h / 2, self.seen_frames))
# keep updating the position of lost identities based
# on previous movements, when they were not lost
self.advance_lost_identities()
# process history to decide who is entering, exiting, etc.
self.process_history()
"""
Remove points that are too old or are to be discarded.
"""
self.points = self.points[self.points[:, 0, 3] < self.max_point_age]
return boxes_ided
def decide_contended_identities(self, boxes):
"""
Identities that are contended by multiple boxes are resolved,
boxes without identities have an identity assigned to them.
:param boxes: List of boxes in the form of (x,y,w,h, list of points, id).
:return: List of boxes in the form of (x,y,w,h,id).
"""
# boxes with id to return
result = []
"""
For each identity make a list of boxes
contenting that identity, for each box
with no identity append it to a list of
boxes with no identity.
"""
# boxes that have no id
boxes_noid = []
# for each id get a list of contending boxes
id_to_boxes = dict()
for box in boxes:
id = box[5]
if id == -1:
boxes_noid.append(box)
else:
if id not in id_to_boxes:
id_to_boxes[id] = []
id_to_boxes[id].append(box)
"""
Decide on what identities are considered to be lost.
"""
self.lost_identities.clear()
for identity, history in self.history.items():
last_time_seen = history[-1][2] # frame number of last update
diff = self.seen_frames - last_time_seen
# not seen this frame & not considered exited & not too old
if identity not in id_to_boxes and identity not in self.exited and diff < self.max_lost_id_age:
self.lost_identities[identity] = (history[-1])
"""
Given an identity contended by multiple boxes
give identity to the box that has the most points
voting for it.
"""
for id, boxes in id_to_boxes.items():
maxvotes = 0
maxid = -1
for boxindex, box in enumerate(boxes):
x, y, w, h, voters, id = box
if len(voters) > maxvotes:
maxvotes = len(voters)
maxid = boxindex
# assign identity to winning box
winning = boxes.pop(maxid)
x, y, w, h, voters, id = winning
result.append((x, y, w, h, id))
boxes_noid.extend(boxes)
"""
For each box with no identity assign it an identity
by first looking for lost identities that may fit this
box, or just creating a new id if there are no such identities.
"""
for box in boxes_noid:
x, y, w, h, points, id = box
# if it contains at least a point
if len(points) >= 1:
id = self.find_lost_identity((x, y, w, h))
result.append((x, y, w, h, id))
# set the identity of all points in this box
for i in points:
self.points[i, 0, 2] = id
return result
def find_lost_identity(self, box):
"""
Search for a lost identity that can be matched to the box, based
on distance and for how long the identity has been lost, if there
is no lost identity respecting the threshold minimum distance, either
try to reuse a wasted identity or create a new one by updating
the identity counter.
:param box: Box of the form (x,y,w,h).
:return: An id for the box.
"""
# get lost identity nearest to our box
x, y, w, h = box
bcx = x + w / 2
bcy = y + h / 2
# to do that look for the nearest lost identity within the threshold
mindist = self.max_lost_dist
minid = None
for id, stats in self.lost_identities.items():
cx, cy, last_seen = stats
if (self.seen_frames - last_seen) < self.max_lost_id_age:
dist = math.sqrt((bcx - cx) ** 2 + (bcy - cy) ** 2)
# if near enough and not too old
if dist < mindist and (self.seen_frames - self.history[id][-1][-1]) < self.max_lost_id_age:
mindist = dist
minid = id
# delete the matched identity from the list of lost identities
if minid and minid not in self.exited:
del self.lost_identities[minid]
else:
if len(self.wasted) > 0:
minid = self.wasted.pop()
else:
minid = self.identities_counter
self.identities_counter += 1
return minid
def process_history(self):
"""
Process history, for each
identity decide which one is exiting or entering
the scene, and which one is definitively exited, check
if some ids have been wasted, etc.
"""
# reset who is entering/exiting
self.entering_right.clear()
self.exiting_right.clear()
self.entering_left.clear()
self.exiting_left.clear()
for id, history in list(self.history.items()): # transform to a list so that we can remove stuff while running
begx, _, _ = history[0]
endx, _, lastseen = history[-1]
goingright = endx > begx
# also consider that that we have lost track of, but very recently
if ((self.seen_frames - lastseen) < 5) and (len(history) >= 5):
# something related to the right gate
if endx > 1160:
if goingright and len(history) > 15:
self.exiting_right.add(id)
self.exited.add(id)
else:
self.entering_right.add(id)
# something related to the left gate
elif endx < 120:
if goingright:
self.entering_left.add(id)
elif len(history) > 15:
self.exiting_left.add(id)
self.exited.add(id)
# if an id has been used for too few frames then it got lost recycle it
if (self.seen_frames - lastseen) > 1 and len(history) <= 5:
self.wasted.append(id)
# make sure it is as if the wasted id did not exist
self.lost_identities.pop(id, None)
self.history.pop(id, None)
self.exited.discard(id)
self.entering_right.discard(id)
self.exiting_right.discard(id)
self.entering_left.discard(id)
self.exiting_left.discard(id)
def advance_lost_identities(self):
"""
Update the x and y coordinate of lost identities based
on their previous history, if their history is long enough.
Currently only updating the x coordinate, because pedestrians
might change their vertical direction after bumping into each other,
so past info might not be so useful.
Only histories of lost identities that are longer than 10 are updated.
"""
for identity in self.lost_identities:
recent_hist = self.history[identity][-30:]
if len(recent_hist) > 10:
oldx, oldy, _ = recent_hist[0]
lastx, lasty, lastframeseen = recent_hist[-1]
gradx = (lastx - oldx) / len(recent_hist) if len(recent_hist) > 5 else 0
"""
Currently not updating on y given the fact that identities usually keep going on their
horizontal direction, but not always keep the same vertical one.
"""
# grady = (lasty - oldy) / len(recent_hist)
self.history[identity].append((lastx + gradx, lasty, lastframeseen))
self.lost_identities[identity] = (lastx + gradx, lasty, lastframeseen)
def assign_undecided_points_to_boxes(self, boxes):
"""
Go through undecided points and try to assign an identity
to them based on the box they are contained into. If they
are contained in a box with an identity that identity will
become the one of the points, otherwise if they are in box
that only contains undecided points just append the box to the
list of boxes, the box will have in its list of points
those undecided points.
:param boxes: List of boxes of the form (x,y,w,h, points belonging to them and voting for their identity, id)
"""
# use a tree index to make everything more scalable
tree_index = rtree.index.Rtree()
boxdict = dict()
for box in boxes:
x, y, w, h, _, _ = box
tree_index.add(len(boxdict), (x + w / 2, y + h / 2, x + w / 2, y + h / 2))
boxdict[len(boxdict)] = box
# look for the nearest box for each point that has no decided identity
indexes = np.where(self.points[:, 0, 2] == -1)[0]
for point_index in indexes:
px, py, = self.points[point_index, 0, :2]
nearbox = list(tree_index.nearest((px, py, px, py), 1))
if len(nearbox) > 0:
nearbox = nearbox[0]
x, y, w, h, decided, box_id = boxdict[nearbox]
if box_contains_point(x, y, w, h, px, py):
self.points[point_index, 0, 2] = box_id
decided.append(point_index)
def assign_decided_points_to_boxes(self, boxes):
"""
For each box find points that are inside it and that have an identity,
use those identities to democratically decide the identity of the box.
Return boxes with their points voting for their identity, and their identity.
:param boxes: List of boxes of the form (x,y,w,h)
:return: List of boxes of the form (x,y,w,h, list of points that have voted for this identiy for this box, id)
"""
# put boxes in a rtree
tree_index = rtree.index.Rtree()
boxdict = dict()
for box in boxes:
x, y, w, h, = box
tree_index.add(len(boxdict), (x + w / 2, y + h / 2, x + w / 2, y + h / 2))
boxdict[len(boxdict)] = (x, y, w, h, [], [])
# look for the nearest box for each point that has a decided identity
# append such point and its vote to the box's lists
indexes = np.where(self.points[:, 0, 2] != -1)[0]
for point_index in indexes:
px, py, vote = self.points[point_index, 0, :3]
nearbox = list(tree_index.nearest((px, py, px, py), 1))
if len(nearbox) > 0:
nearbox = nearbox[0]
x, y, w, h, points, votes = boxdict[nearbox]
if box_contains_point(x, y, w, h, px, py):
points.append(point_index)
votes.append(vote)
assigned_boxes = []
# for each box decide identity based on majority voting
for box in boxdict.values():
x, y, w, h, points, votes = box
# group votes by id, decide on id
summed_votes = Counter(votes)
sorted_votes = sorted(summed_votes.items(), key=operator.itemgetter(1), reverse=True)
# id for this box is undecided if there are no points with an identity within this box
id = -1 if (len(summed_votes) == 0) else sorted_votes[0][0]
tmp = []
if id != -1:
# points assigned to this box should be only the points that have voted for that particular identity
for p, v in zip(points, votes):
if v == id:
tmp.append(p)
assigned_boxes.append([x, y, w, h, tmp, int(id)])
return assigned_boxes
def infer_boxes(self, boxes):
"""
If there is a cluster of points with the same identity
and there is no box already having that identity, "grow"
a new box around those points.
:param boxes: List of boxes of the form (x,y,w,h,points voting for its identity, id)
"""
# ids that have already been assigned to boxes
assigned_ids = set(box[-1] for box in boxes if box[1] != -1)
# get all unique identities in our feature points
ids = np.unique(self.points[:, 0, 2])
for id in ids:
# see if we can grow a box only for identities that have not
# a box of their own but have enough points with that identity
# and clustered near each other
if id not in assigned_ids and id != -1:
points_indices = np.where(self.points[:, 0, 2] == id)
points = self.points[points_indices, 0, :2][0]
decided = list(points_indices[0])
if len(points) >= self.infer_thres:
x, y, w, h = cv2.boundingRect(points)
# accept only boxes of certain size
if w < 120 and h < 120:
boxes.append([x, y, max(50, w), max(50, h), decided, id])
def trim_boxes(self, boxes):
"""
Keep only a maximum amount of points for each box.
:param boxes: List of boxes of form (x,y,w,h,points,id).
"""
# for each box keep only up to max_crowndess
for box in boxes:
points = box[4]
points = list(reversed(points))
self.points[points[self.max_points_per_box:], 0, 3] = self.max_point_age
del points[self.max_points_per_box:]
box[4] = points
| a49e31fb56e989c9ffa118bd38bd51426169990e | [
"Markdown",
"Python"
] | 4 | Python | fruttasecca/unitn_cv_2018_project | 8ea0fecee5d403a9e41dde282e6a3c8f9c9b6afd | dc72bad059fd21814a31043efed6e672424b769c |
refs/heads/master | <file_sep>from flask import request as r
from flask_restful import Resource
import requests as req
from requests.auth import HTTPBasicAuth
user = 'SK20841af8008834611f84e7590630f467'
pwd = '<PASSWORD>'
def cfr(b):
d = b
a = {}
a["id"] = d["sid"]
a["roomUniqueName"] = d["unique_name"]
a["rooomstatus"] = d["status"]
a["maxparticipants"] = d["max_participants"]
a["type"] = d["type"]
a["startAt"] = None
a["endDt"] = None
a["duration"] = 0
a["createdDt"] = d["date_created"]
a["modifiedDt"] = d["date_updated"]
a["participants"] = []
return a
class CompleteRoom(Resource):
def get(self, uniqueName):
head = {"Content-Type": "application/x-www-form-urlencoded"}
payload = {
"Status": "completed"
}
call = req.post("https://video.twilio.com/v1/Rooms/" + uniqueName,
data=payload, headers=head, auth=HTTPBasicAuth(user, pwd))
# print(call.json())
if call.status_code == 404:
return {"message": "Room not Found"}, 404
x = cfr(call.json())
return x, 202
<file_sep>from flask import request as r
from flask_restful import Resource
import requests as req
from requests.auth import HTTPBasicAuth
from util import get_random_string
user = 'SK<PASSWORD>'
pwd = '<PASSWORD>'
def create_transform(b):
d = b
a = {}
a["id"] = d["sid"]
a["roomUniqueName"] = d["unique_name"]
a["roomSID"] = None
a["rooomstatus"] = d["status"]
a["maxparticipants"] = d["max_participants"]
a["type"] = d["type"]
a["startAt"] = None
a["endDt"] = None
a["duration"] = 0
a["createdDt"] = d["date_created"]
a["modifiedDt"] = d["date_updated"]
a["participants"] = []
return a
class CreateRoom(Resource):
def post(self):
request = r.get_json()
head = {"Content-Type": "application/x-www-form-urlencoded"}
payload = {
"MaxParticipants": 4,
"Type": "group-small"
}
if request is not None: # dict type
if (request['roomUniqueName'] is not None):
payload["UniqueName"] = str(request['roomUniqueName']) + \
get_random_string(4)
if (request['maxParticipants']):
if (request['maxParticipants'] > 4):
payload["Type"] = "group"
payload['MaxParticipants'] = request['maxParticipants']
if (request['RecordParticipantConnect'] is not None):
payload["RecordParticipantsOnConnect"] = request["RecordParticipantConnect"]
else:
return {"message": "Bad request please retry"}, 400
call = req.post('https://video.twilio.com/v1/Rooms/', auth=HTTPBasicAuth(
user, pwd), headers=head, data=payload)
return call.json(), 201
if call.status_code == 400:
if call.json()['code'] == 53113:
return {'message': "Room already exists"}, 400
return {'message': "Room name is invalid"}, 400
<file_sep>from flask import request as r
from flask_restful import Resource
import requests as req
from requests.auth import HTTPBasicAuth
user = 'SK20841af8008834611f84e7590630f467'
pwd = '<PASSWORD>'
class DeleteRoom(Resource):
def delete(self, uniqueName):
head = {"Content-Type": "application/x-www-form-urlencoded"}
payload = {
"Status": "completed"
}
call = req.post("https://video.twilio.com/v1/Rooms/" + uniqueName,
data=payload, headers=head, auth=HTTPBasicAuth(user, pwd))
# print(call.json())
if call.status_code == 404:
return {"message": "Room not Found"}, 404
return None, 200
<file_sep>from app import app
# from flask_compress import Compress
from gevent.pywsgi import WSGIServer
from gevent import monkey
# COMPRESS_MIMETYPES = ['application/json']
# COMPRESS_LEVEL = 7
# Compress(app)
# monkey.patch_all()
if __name__ == "__main__":
# app.run(debug=True, threaded=True)
http = WSGIServer(('', 5000), app.wsgi_app) # for production
http.serve_forever()
# http.serve() # for production
<file_sep>from flask import Flask, request
from flask_restful import Api
from CreateRoom import CreateRoom
from CompleteRoom import CompleteRoom
from DeleteRoom import DeleteRoom
app = Flask(__name__)
api = Api(app)
api.add_resource(CreateRoom, '/api/rooms/createRoom')
api.add_resource(CompleteRoom, '/api/rooms/completeRoom/<string:uniqueName>')
api.add_resource(DeleteRoom, '/api/rooms/deleteRoom/<string:uniqueName>')
<file_sep>import random
import string
import time
def get_random_string(length):
letters = string.ascii_uppercase
result_str = ''.join(random.choice(letters)
for i in range(length)) + str(time.time())[-5:-2]
return result_str
| 7729392845d8be7d718d44cb889e77704cf4fd6f | [
"Python"
] | 6 | Python | VCA-External/Twiliov2 | 3b918d88d990ed7592b08bdf4ebfdbbfe8d6d33b | abe6d0a328b24689886759e517a0eb4bd1d2015d |
refs/heads/master | <repo_name>yangjehpark/iOS-Swift-Flicker-Feed<file_sep>/FlickerFeed/ImageManager.swift
//
// ImageManager.swift
// FlickerFeed
//
// Created by yangjehpark on 2017. 1. 21..
// Copyright ยฉ 2017๋
yangjehpark. All rights reserved.
//
import UIKit
import SDWebImage
class ImageParser {
/*
MARK: Get Image
*/
class func getImage(imageIndex: Int, completionHandler: (image: UIImage?) -> Void) {
if let imageUrl = NSURL(string: FeedManager.sharedInstance.items[imageIndex].media!.m!) {
SDWebImageManager.sharedManager().downloadImageWithURL(imageUrl, options: SDWebImageOptions.HighPriority, progress: nil, completed: {
(image:UIImage!, error:NSError!, type:SDImageCacheType, complete:Bool, url:NSURL!) in
if (image != nil) {
completionHandler(image: image!)
} else {
completionHandler(image: nil)
}
})
}
}
/*
MARK: Preload
*/
class func preloadImages(criteriaIndex:Int) {
let firstIndex = 0
let lastIndex = FeedManager.sharedInstance.items.count-1
// preload forward one
let forwardTargetIndex = (criteriaIndex == lastIndex ? firstIndex : criteriaIndex+1)
self.getImage(forwardTargetIndex, completionHandler: { (image) in
if (image != nil) {
}
})
}
}<file_sep>/FlickerFeed/FlickerItem.swift
//
// FlickerItem.swift
// FlickerFeed
//
// Created by yangjehpark on 2017. 1. 21..
// Copyright ยฉ 2017๋
yangjehpark. All rights reserved.
//
import Foundation
import ObjectMapper
class FlickerItem: Mappable {
required init?(_ map: Map){
}
init() {
}
func mapping(map: Map) {
self.title <- map["title"]
self.link <- map["link"]
self.media <- map["media"]
self.date_taken <- map["date_taken"]
self.description <- map["description"]
self.published <- map["published"]
self.author <- map["author"]
self.author_id <- map["author_id"]
self.tags <- map["tags"]
}
var title: String?
var link: String?
var media: FlickerMedia?
var date_taken: String?
var description: String?
var published: String?
var author: String?
var author_id: String?
var tags: String?
}<file_sep>/README.md
A sample iOS application for querying public images by using Flickr Public API, Alamofire, ObjectMapper, and SDWebimage.

## Features
- [x] Provide Flickr public open API images
## Requirements
- iOS 8.0+
- Xcode 7.0+
- Swift 2.3
## Communication
- If you **found a bug** or **have a feature request**, please open an issue.
- If you **want to contribute**, submit a pull request.
## Installation
Of course, [CocoaPods](http://cocoapods.org) is necessary. This is a dependency manager for Cocoa projects.
At the directory where 'podfile' is, please run the following command in the folder:
```bash
$ pod install
```
This is a nessacery course. If you don't, some build error would be occured.
## Usage
After installation, open 'FlickerFeed.xcworkspace' and start build & run.
## License
My codes are under the Beerware license. <file_sep>/FlickerFeed/FlickerMedia.swift
//
// FlickerMedia.swift
// FlickerFeed
//
// Created by yangjehpark on 2017. 1. 21..
// Copyright ยฉ 2017๋
yangjehpark. All rights reserved.
//
import Foundation
import ObjectMapper
class FlickerMedia: Mappable {
required init?(_ map: Map){
}
init() {
}
func mapping(map: Map) {
self.m <- map["m"]
}
var m: String?
}<file_sep>/FlickerFeed/FeedManager.swift
//
// FeedManager.swift
// FlickerFeed
//
// Created by yangjehpark on 2017. 1. 21..
// Copyright ยฉ 2017๋
yangjehpark. All rights reserved.
//
import UIKit
import Alamofire
class FeedManager {
static let sharedInstance = FeedManager()
var items = [FlickerItem]()
func getFeed(completionHandler: (complete: Bool, error: NSError?) -> Void) {
let urlString = "http://api.flickr.com/services/feeds/photos_public.gne?lang=en-us&format=json&nojsoncallback=1"
let responseObjectType = FlickerJSON()
Parser.requestAndResponseObject(Method.GET, urlString: urlString, parameters: nil, encoding: ParameterEncoding.URL, headers: nil, responseObjectType: responseObjectType) { (responseObject, error) in
if (responseObject != nil) {
if (responseObject!.items != nil && responseObject!.items?.count != 0) {
for item in responseObject!.items! {
self.items.append(item)
}
completionHandler(complete: true, error: nil)
} else {
// no more feed item to get
completionHandler(complete: false, error: nil)
}
} else {
// get fail
completionHandler(complete: false, error: error)
}
}
}
}<file_sep>/FlickerFeed/ModalViewController.swift
//
// ModalViewController.swift
// FlickerFeed
//
// Created by yangjehpark on 2017. 1. 21..
// Copyright ยฉ 2017๋
yangjehpark. All rights reserved.
//
import UIKit
protocol ModalViewControllerDelegate {
func start(interval: NSTimeInterval)
}
class ModalViewController: FlickerFeedViewController {
static let identifier = "ModalViewController"
var delegate = ModalViewControllerDelegate?()
@IBOutlet weak var startButton:UIButton!
@IBOutlet weak var intervalSilder:UISlider!
@IBOutlet weak var intervalLabel:UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.intervalSilder.value = 7
self.intervalSilder.minimumValue = 5
self.intervalSilder.maximumValue = 10
self.valueChanged(self.intervalSilder)
}
@IBAction func valueChanged(silder: UISlider) {
self.intervalLabel.text = String(Float(Int(silder.value*10))/10)+" sec"
}
@IBAction func startButtonPressed(sender: UIButton) {
let interval = NSTimeInterval(self.intervalSilder.value)
self.dismissViewControllerAnimated(true) {
self.delegate?.start(interval)
}
}
}<file_sep>/FlickerFeed/FlickerJSON.swift
//
// FlickerJSON.swift
// FlickerFeed
//
// Created by yangjehpark on 2017. 1. 21..
// Copyright ยฉ 2017๋
yangjehpark. All rights reserved.
//
import Foundation
import ObjectMapper
class FlickerJSON: Mappable {
required init?(_ map: Map){
}
init() {
}
func mapping(map: Map) {
self.title <- map["title"]
self.link <- map["link"]
self.description <- map["description"]
self.modified <- map["modified"]
self.generator <- map["generator"]
self.items <- map["items"]
}
var title: String?
var link: String?
var description: String?
var modified: String?
var generator: String?
var items: [FlickerItem]?
}<file_sep>/FlickerFeed/PagingImageViewCell.swift
//
// PagingImageViewCell.swift
// FlickerFeed
//
// Created by yangjehpark on 2017. 1. 21..
// Copyright ยฉ 2017๋
yangjehpark. All rights reserved.
//
import UIKit
import PagingView
class PagingImageViewCell: PagingViewCell, DTZoomableViewDelegate {
static let reuseIdentifier = "PagingImageViewCellReuseIdentifire"
@IBOutlet weak var zoomableView: DTZoomableView!
@IBOutlet weak var numberLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
var image:UIImage?
override func awakeFromNib() {
super.awakeFromNib()
self.zoomableView!.zoomableDelegate = self
}
}
<file_sep>/Podfile
platform :ios, '8.0'
use_frameworks!
def shared_pods
pod 'PagingView'
pod 'Alamofire'
pod 'AlamofireObjectMapper', '~> 2.1'
pod 'SDWebImage'
end
target 'FlickerFeed' do
shared_pods
end
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['SWIFT_VERSION'] = '2.3'
end
end
end<file_sep>/FlickerFeed/FlickerFeedViewController.swift
//
// FlickerFeedViewController.swift
// FlickerFeed
//
// Created by yangjehpark on 2017. 1. 21..
// Copyright ยฉ 2017๋
yangjehpark. All rights reserved.
//
import UIKit
class FlickerFeedViewController: UIViewController {
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
var loadingView: UIView?
override func viewDidLoad() {
super.viewDidLoad()
self.initLoadingView()
}
func initLoadingView() {
let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
activityIndicatorView.startAnimating()
activityIndicatorView.center = CGPointMake(UIScreen.mainScreen().bounds.width/2, UIScreen.mainScreen().bounds.height/2)
self.loadingView = UIView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
self.loadingView!.backgroundColor = UIColor.grayColor()
self.loadingView!.alpha = 0.5
self.loadingView!.addSubview(activityIndicatorView)
self.loadingView!.userInteractionEnabled = false
}
func showLoadingView() {
if (self.loadingView != nil) {
self.view.addSubview(self.loadingView!)
}
}
func hideLoadingView() {
if (self.loadingView != nil) {
self.loadingView!.removeFromSuperview()
}
}
func showPopup(title title: String, message: String, completionHandler: (complete: Bool) -> Void) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let cancel = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel) { (alertAction:UIAlertAction) -> Void in
completionHandler(complete: true)
}
alertController.addAction(cancel)
self.presentViewController(alertController, animated: true, completion: nil)
}
func showRetryPopup(title title: String, message: String, completionHandler: (retry: Bool) -> Void) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { (alertAction:UIAlertAction) -> Void in
completionHandler(retry: false)
}
let retry = UIAlertAction(title: "Retry", style: UIAlertActionStyle.Default) { (alertAction:UIAlertAction) -> Void in
completionHandler(retry: true)
}
alertController.addAction(cancel)
alertController.addAction(retry)
self.presentViewController(alertController, animated: true, completion: nil)
}
}<file_sep>/FlickerFeed/Parser.swift
//
// Parser.swift
// FlickerFeed
//
// Created by yangjehpark on 2017. 1. 21..
// Copyright ยฉ 2017๋
yangjehpark. All rights reserved.
//
import Foundation
import Alamofire
import AlamofireObjectMapper
import ObjectMapper
class Parser {
class func checkNetwork() -> Bool {
do {
let reachability: Reachability = try Reachability.reachabilityForInternetConnection()
return reachability.isReachable()
} catch {
return false
}
}
class func requestAndResponseObject<T:Mappable>(method: Alamofire.Method, urlString: String, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil, responseObjectType: T, completionHandler: (responseObject: T?, error:NSError?) -> Void) {
if (Parser.checkNetwork()) {
request(method, urlString, parameters: parameters, encoding: encoding, headers: headers).responseObject(completionHandler: { (response:Response<T, NSError>?) -> Void in
if (response!.response?.statusCode != 200 && (response!.result.value == nil || response!.result.value?.toJSON().count == 0)) {
completionHandler(responseObject: nil, error: response!.result.error)
return
}
if (response != nil && response!.result.value != nil) {
completionHandler(responseObject: response!.result.value!, error: nil)
} else {
completionHandler(responseObject: nil, error: response!.result.error)
}
})
} else {
completionHandler(responseObject: nil, error: nil)
}
}
class func requestAndResponseArray<T:Mappable>(method: Alamofire.Method, urlString: String, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil, responseArrayType: [T], completionHandler: (responseArray: [T]?, error:NSError?) -> Void) {
if (Parser.checkNetwork()) {
request(method, urlString, parameters: parameters, encoding: encoding, headers: headers).responseArray {(response:Response<[T], NSError>) -> Void in
if (response.response?.statusCode != 200 && (response.result.value == nil || response.result.value?.toJSON().count == 0)) {
completionHandler(responseArray: nil, error: response.result.error)
return
}
if (response.result.value != nil) {
completionHandler(responseArray: response.result.value!, error: nil)
} else {
completionHandler(responseArray: nil, error: response.result.error)
}
}
} else {
completionHandler(responseArray: nil, error: nil)
}
}
}<file_sep>/FlickerFeed/MainViewController.swift
//
// ViewController.swift
// FlickerFeed
//
// Created by yangjehpark on 2017. 1. 21..
// Copyright ยฉ 2017๋
yangjehpark. All rights reserved.
//
import UIKit
import PagingView
class MainViewController: FlickerFeedViewController, PagingViewDataSource, PagingViewDelegate, UIScrollViewDelegate, ModalViewControllerDelegate {
/*
MARK: UIViewController
*/
override func viewDidLoad() {
super.viewDidLoad()
self.initPagingView()
self.performSelector(#selector(MainViewController.showModalViewController), withObject: nil, afterDelay: 0.0)
}
/*
MARK: ModalViewController
*/
func showModalViewController() {
let modalViewController: ModalViewController = self.mainStoryboard.instantiateViewControllerWithIdentifier(ModalViewController.identifier) as! ModalViewController
modalViewController.delegate = self
self.presentViewController(modalViewController, animated: true, completion: nil)
}
/*
MARK: ModalViewControllerDelegate
*/
func start(interval: NSTimeInterval) {
self.animatingInterval = interval
self.getFeed()
}
/*
MARK: UI
*/
private func initPagingView() {
self.pagingView.infinite = true
self.pagingView.dataSource = self
self.pagingView.delegate = self
self.pagingView.showsHorizontalScrollIndicator = false
self.pagingView.pagingMargin = UInt(pagingViewMargin)
self.pagingViewMarginLeft?.constant = -pagingViewMargin
self.pagingViewMarginRight?.constant = -pagingViewMargin
self.pagingView.registerNib(UINib(nibName: "PagingImageViewCell", bundle: nil), forCellWithReuseIdentifier: PagingImageViewCell.reuseIdentifier)
}
private func getFeed() {
FeedManager.sharedInstance.getFeed { (complete, error) in
if (error == nil) {
if (complete) {
self.showFeed()
} else {
self.showPopup(title: "Sorry", message: "No more feed now", completionHandler: { (complete) in
})
}
} else {
self.showRetryPopup(title: (error != nil ? String(error!.code) : "Sorry"), message: "Fail to get more feed", completionHandler: { (retry) in
if (retry) {
self.getFeed()
} else {
self.showModalViewController()
}
})
}
}
}
private func showFeed() {
self.pagingView.reloadData()
self.startAnimating(self.animatingInterval)
}
/*
MARK: PagingViewDelegate, PagingViewDataSource
*/
@IBOutlet private weak var pagingView: PagingView!
private let pagingViewMargin: CGFloat = 10
@IBOutlet private weak var pagingViewMarginLeft: NSLayoutConstraint?
@IBOutlet private weak var pagingViewMarginRight: NSLayoutConstraint?
private var currentIndex:Int = 0
func numberOfSectionsInPagingView(pagingView: PagingView) -> Int {
return 1
}
func pagingView(pagingView: PagingView, numberOfItemsInSection section: Int) -> Int {
return FeedManager.sharedInstance.items.count
}
func pagingView(pagingView: PagingView, cellForItemAtIndexPath indexPath: NSIndexPath) -> PagingViewCell {
let cell = pagingView.dequeueReusableCellWithReuseIdentifier(PagingImageViewCell.reuseIdentifier) as! PagingImageViewCell
cell.numberLabel.text = String(indexPath.item+1)+"/"+String(FeedManager.sharedInstance.items.count)
cell.titleLabel.text = FeedManager.sharedInstance.items[indexPath.item].title
cell.zoomableView.image = nil
ImageParser.getImage(indexPath.row, completionHandler: { (image) in
cell.zoomableView.image = image
ImageParser.preloadImages(indexPath.row)
})
return cell
}
func pagingView(pagingView: PagingView, willDisplayCell cell: PagingViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
let beforeLastItemIndex = FeedManager.sharedInstance.items.count-3
if (self.currentIndex == beforeLastItemIndex) {
self.getFeed()
}
}
func pagingView(pagingView: PagingView, didEndDisplayingCell cell: PagingViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
if let zoomableView = (cell as? PagingImageViewCell)?.zoomableView {
if let zoomScale: CGFloat = zoomableView.zoomScale where zoomScale > 1.0 {
zoomableView.setZoomScale(1.0, animated: false)
}
}
self.startAnimating(self.animatingInterval)
}
func indexPathOfStartingInPagingView(pagingView: PagingView) -> NSIndexPath? {
if (FeedManager.sharedInstance.items.count > 0) {
return NSIndexPath(forItem: self.currentIndex, inSection: 0)
} else {
return nil
}
}
/*
MARK: UIScrollViewDelegate
*/
func scrollViewDidScroll(scrollView: UIScrollView) {
if (scrollView == self.pagingView) {
if let centerCell = self.pagingView!.visibleCenterCell() as? PagingImageViewCell {
self.currentIndex = centerCell.indexPath.item
}
}
}
/*
MARK: Auto Scroll
*/
var animatingTimer: NSTimer?
var animatingInterval: NSTimeInterval = 5
func startAnimating(interval: NSTimeInterval) {
self.stopAnimating()
if (self.animatingTimer == nil) {
self.animatingTimer = NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: #selector(MainViewController.doAnimate), userInfo: nil, repeats: false)
self.animatingTimer?.valid
}
}
func doAnimate() {
if (FeedManager.sharedInstance.items.count > 1) {
self.pagingView?.scrollToPosition(Position.Right, indexPath: nil, animated: true)
} else {
self.stopAnimating()
}
}
func stopAnimating() {
if (self.animatingTimer != nil) {
self.animatingTimer!.invalidate()
self.animatingTimer = nil
}
}
} | 07f703dac84b1f3d146212da7c57efded28bf4f4 | [
"Swift",
"Ruby",
"Markdown"
] | 12 | Swift | yangjehpark/iOS-Swift-Flicker-Feed | b71547c6906218b435ad5d86810bcbea3ee56751 | 00b45848f51356891cbcdcd32520c87c2ea2774b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.